Q:

Is data binding a bad idea?

Another discussion (we've been having a lot of them these days!) in our work is whether data binding is a bad idea or not.
Personally, I think it is a Bad Thing™.
My reasons are thrice:

It circumvents my well architectured MVP framework - with databinding, the view communicates bi-directionally with a model.  Ewww.
It promotes hooking up view controls to datafields at design time.  In my experience, this leads to vital code (binding column A to Field X) being obscure and hidden away in some designer file.  IMO this code should be explicit and in-your-face, so that it is easy to modify and see what is going on, without having to use a clunky designer interface.
Relating to Point #1 this direct binding makes it harder to isolate each component (view, model, controller/presenter) and unit-test.

The pros are that it is easy to set up, and you can take advantage of some nice features (validation etc) which come with the plumbing already done for you.
But for me, databinding becomes much more of a hindrance when dealing with a large data-centric application.
Any thoughts?

A:

As we say in the UK, "It's Horses for courses"
First off all, I agree with you! But...
For enterprise level applications, then spending the extra time on the system architecture, modelling and standards will give you a robust and sustainable system.
But it will take longer to develop (or at least longer to get to an initial release) and this may not be appropriate for every system or every part of the system.
Sometimes you just need to "get it done and done quick".  For internal applications, back office systems and maintenance applications that are rarely used or very dynamic (the spec's change often) then there is little justification in building the Rolls Royce solution for this.  It's better to get the developer spending time on the CRITICAL part of the system.
What you have to avoid / prevent is using these "one click framework" solutions on the MISSION CRITICAL area's of the system where the big transaction rate area's and where data quality and integrity is critical.  Spend quality time shaving the milliseconds off on the most heavily used area's on the system!!

A:

Another discussion (we've been having a lot of them these days!) in our work
  is whether data binding is a bad idea or not.
Personally, I think it is a Bad Thing™.

Strong opinion, but imho, you bring out all the wrong reasons.

It circumvents my well architectured MVP framework - with databinding, the view communicates bi-directionally with a model. Ewww.

I guess it depends on the implementation of the data binding.
In the early years of my programming career, I used to do a lots of VBA for MS Access programming and Access forms had indeed this direct binding to tables/fields in database.
Most of the general purpose languages/frameworks have databinding as a separate component, do not use such a direct binding and are usually considered as a easy generic dropin for a controller in MVC pattern sense.

It promotes hooking up view controls to datafields at design time. In my experience, this leads to vital code (binding column A to Field X) being obscure and hidden away in some designer file. IMO this code should be explicit and in-your-face, so that it is easy to modify and see what is going on, without having to use a clunky designer interface.

I guess you are talking about the binding in WinForms?
My experience with win forms comes from a long ago, so I might be pretty out of date here.
It sure is a convenience feature, and I would strongly argue against it, unless you are writing really simple modal context CRUD style interfaces.

Relating to Point #1 this direct binding makes it harder to isolate each component (view, model, controller/presenter) and unit-test.

Again - assuming the view (a widget in WinFoms?) is tied together with databinding awareness, you are right.

But for me, databinding becomes much more of a hindrance when dealing with a large data-centric application.

Quite contrary - if data binding is implemented as an independent component (eg. bindings in Cocoa or JFace DataBinding, or JGoodies Binding), that acts as a controller between View and a Model, taking care of all the nitty-gritty of event handling and conversion and validation, then it is just so much more easier to use, change and replace than your custom controller code doing just the same thing.
The only downside of a general purpose data binding framework is that if the binding is off and/or misconfigured, the interactions between bound pieces are just notoriously difficult to debug due to the level of abstraction inside the data binding code... So You better not make any mistakes! ;)

A:

I've used databinding in some pretty large systems and find that it works pretty well.
Seems that I do things a bit differently from you though ...
... I don't databind to the model, instead to a dedicated view class that works as an adapter between the model's structure and what I need on screen. This includes things like providing choices for comboboxes & listviews, and so on.
... I never set up the binding using the UI. Instead, I have a single method (usually called Bind() or BindXYZ() that hooks everything up in one place.
My Model remains agnostic, knowing nothing about databinding; my Presenter sticks to the workflow coordinate it's designed for; my Views are now also simple classes (easy to test) that encapsulate my UI behavior (is button X enabled, etc) and the actual UI is relegated to a simple helper on the side.


Q:

ディスプレイプロファイルのパスの取得方法

Mac OS X で「システム環境設定」→「ディスプレイ」→「カラー」を開くと現在使用しているディスプレイプロファイル名が分かり、マウスオーバーでパスも見られます。それと同じパスをJavaまたはObjective-Cのプログラム内で取得したいのですが、どうすればよいでしょうか。
パスが分かりさえすればよく、別のプロファイルに設定したりできる必要はありません。

A:

自己解決しました。https://github.com/mpv-player/mpv/issues/594 等が参考になりました。
char* getSystemDisplayProfilePath()
{
  CGDirectDisplayID displayID = CGMainDisplayID();
  CFUUIDRef displayUUID = CGDisplayCreateUUIDFromDisplayID(displayID);
  if (!displayUUID) return NULL;

  CFDictionaryRef displayInfo =
    ColorSyncDeviceCopyDeviceInfo(kColorSyncDisplayDeviceClass, displayUUID);
  CFRelease(displayUUID);
  if (!displayInfo) return NULL;

  CFDictionaryRef factoryInfo =
    (CFDictionaryRef)CFDictionaryGetValue(displayInfo, kColorSyncFactoryProfiles);
  if (!factoryInfo) return NULL;

  CFStringRef defaultProfileID =
    (CFStringRef)CFDictionaryGetValue(factoryInfo, kColorSyncDeviceDefaultProfileID);
  if (!defaultProfileID) return NULL;

  CFURLRef profileURL;
  CFDictionaryRef customProfileInfo =
    (CFDictionaryRef)CFDictionaryGetValue(displayInfo, kColorSyncCustomProfiles);
  if (customProfileInfo) {
    profileURL =
      (CFURLRef)CFDictionaryGetValue(customProfileInfo, defaultProfileID);
    if (!profileURL) return NULL;
  } else {
    CFDictionaryRef factoryProfileInfo =
      (CFDictionaryRef)CFDictionaryGetValue(factoryInfo, defaultProfileID);
    if (!factoryProfileInfo) return NULL;

    profileURL =
      (CFURLRef)CFDictionaryGetValue(factoryProfileInfo, kColorSyncDeviceProfileURL);
    if (!profileURL) return NULL;
  }

  char path[PATH_MAX];
  bool const result =
    CFURLGetFileSystemRepresentation(profileURL, true, (UInt8*)path, PATH_MAX);
  CFRelease(profileURL);
  CFRelease(displayInfo);
  if (!result) return NULL;

  return new_strdup( path );
}


Q:

How do I get the character index at a given coordinate in a Text-node?

In JavaFX, how can I get the index of the character (in a javafx.scene.text.Text object) under the mouse pointer from a mouse clicked event? Or more generally, how do I get the index of the character located at a (x, y) coordinate in a javafx.scene.text.Text node?
I have managed to find the index using Node.queryAccessibleAttribute(), but this feels somewhat like a hack and not the proper use of the JavaFX APIs:
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import static javafx.scene.AccessibleAttribute.OFFSET_AT_POINT;

public class TextClicked extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        final Text textNode = new Text("Hello, world!");
        textNode.setOnMouseClicked(event -> {
            final int idx = (int) textNode.queryAccessibleAttribute(OFFSET_AT_POINT, new Point2D(event.getScreenX(), event.getScreenY()));
            System.out.println("Character clicked: " + textNode.getText().charAt(idx));
        });

        primaryStage.setScene(new Scene(new HBox(textNode)));
        primaryStage.show();
    }
}

A:

JavaFX doesn't really encourage a functionality where you register an event handler with a control, and then inspect low-level details of the event (such as the mouse coordinates) in order to deduce semantic information about the event. The preferred approach is to register listeners with individual contained nodes in the scene graph. For example, whereas in Swing you might register a listener with a JList and then locationToIndex(...) method to get the index of the item in the JList, in JavaFX you are encouraged to register listeners with the individual ListCells instead of the ListView itself.
So the "idiomatic" way to do this is probably to create a TextFlow and add individual Texts to it. To determine which Text is clicked, you would register listeners with each of the individual texts.
You could create a reusable class to encapsulate this functionality, of course, exposing as much API of the enclosed TextFlow as you need.
Here's a fairly basic example:
import java.util.ArrayList;
import java.util.List;

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.event.Event;
import javafx.event.EventType;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.InputEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;

public class ClickableTextExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        ClickableText text = new ClickableText("The quick brown fox jumped over the lazy dog.");
        text.asNode().addEventHandler(TextClickEvent.CLICKED, e -> {
            System.out.println("Click on "+e.getCharacter()+" at "+e.getIndex());
        });

        StackPane root = new StackPane(text.asNode());
        Scene scene = new Scene(root, 350, 120);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static class ClickableText {
        private final StringProperty text = new SimpleStringProperty();
        public StringProperty textProperty() {
            return text ;
        }
        public String getText() {
            return textProperty().get();
        }
        public void setText(String text) {
            textProperty().set(text);
        }

        private final TextFlow textFlow ;

        public ClickableText(String text) {

            textFlow = new TextFlow();

            textProperty().addListener((obs, oldText, newText) ->
                rebuildText(newText));

            setText(text);
        }

        public Node asNode() {
            return textFlow ;
        }

        private void rebuildText(String text) {
            List<Text> textNodes = new ArrayList<>();
            for (int i = 0; i < text.toCharArray().length; i++) {
                char c = text.charAt(i);
                Text textNode = new Text(Character.toString(c));
                textNodes.add(textNode);
                registerListener(textNode, i);
            }
            textFlow.getChildren().setAll(textNodes);
        }

        private void registerListener(Text text, int index) {
            text.addEventHandler(MouseEvent.MOUSE_CLICKED, e -> {
                TextClickEvent event = new TextClickEvent(text.getText().charAt(0), index, textFlow, textFlow);
                Event.fireEvent(textFlow, event);
            });
        }

    }

    public static class TextClickEvent extends InputEvent {

        private final char c ;
        private final int index ;

        public static final EventType<TextClickEvent> CLICKED = new EventType<TextClickEvent>(InputEvent.ANY);

        public TextClickEvent(char c, int index, Node source, Node target) {

            super(source, target, CLICKED);

            this.c = c ;
            this.index = index ;
        }

        public char getCharacter() {
            return c ;
        }

        public int getIndex() {
            return index ;
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Another solution, which you may or may not regard as a hack, would be to use a non-editable text field and style it to look like a Text (or Label). Then you can check the caretPosition after the user clicks.
This code is based on Copiable Label/TextField/LabeledText in JavaFX
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class TextClicked extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        final TextField textNode = new TextField("Hello, world!");
        textNode.setEditable(false);
        textNode.getStyleClass().add("clickable-text");
        textNode.setOnMouseClicked(event -> {
            final int idx = Math.max(0, textNode.getCaretPosition() - 1);
            System.out.println("Character clicked: " + textNode.getText().charAt(idx));
        });

        Scene scene = new Scene(new HBox(textNode));
        scene.getStylesheets().add("clickable-text.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

and then
clickable-text.css:
.clickable-text, .clickable-text:focused {
    -fx-background-color: transparent ;
    -fx-background-insets: 0px ;
}


Q:

How to get node content of XML with Dom4j in java

I have a XML file like:
<description>
  <text>blahblah</text>
  code
  <text>blah</text>
</description>

I've navigated to the node description, and I want to read the full content including the <text> and so on.
I've used the getText(), but it returned empty string.
I've used the getStringValue(), but it filtered all <text>.
I've used the asXML(), the result is close, but the result contains <description> which I don't want.
Is there a method to get the XML content of a element?

A:

Something like this:
public static void main(String[] args) throws DocumentException {
  String xml = "<description><text>blahblah</text>code<text>blah</text></description>";
  SAXReader reader = new SAXReader();
  Document doc = reader.read(new StringReader(xml));
  Element description = doc.getRootElement();
  String content = getContent(description);
  System.out.println(content);
}

private static String getContent(Element element) {
  StringBuilder builder = new StringBuilder();
  for (Iterator<Element> i = element.elementIterator(); i.hasNext();) {
    Element e = i.next();
    builder.append(e.asXML());
  }
  return builder.toString();
}

Note that if the element has text content itself, this won't return the text content, only the child nodes.

A:

Assume that document is and instance of org.dom4j.Document, then
String xPath = "description";
List<Node> nodes = document.selectNodes( xPath );
for (Node node : nodes) {
 node.asXML()
}


Q:

iOS9: Custom UIWindow makes status bar disappear

When I create a custom UIWindow in iOS9, the window becomes visible on the screen, but the status bar suddenly disappears.
When the window becomes hidden, the status bar appears again.
Below, 2 screenshots of what I get on iOS9 with Xcode7 beta5.
Status bar while the custom window is hidden:

Status bar while the custom window is visible:

(The whole screen moves to the top.)
This is the code I'm using (which worked well on iOS8):
#define DEBUG_SHOWENV_HEIGHT 20.0f

@interface AppDelegate ()
@property (nonatomic) UIWindow*     envWindow;
@end

-(UIWindow*)envWindow
{
    if (_envWindow == nil)
    {
        // Create the window
        _envWindow = [[UIWindow alloc] initWithFrame:CGRectMake(0.0f, self.window.frame.size.height, self.window.frame.size.width, DEBUG_SHOWENV_HEIGHT)];
        _envWindow.rootViewController = [[UIViewController alloc] init]; // added since iOS9 to avoid the assertion
        _envWindow.userInteractionEnabled = NO;
        _envWindow.windowLevel = UIWindowLevelStatusBar;
        _envWindow.backgroundColor = [UIColor colorWithRed:0.243 green:0.471 blue:0.992 alpha:0.8];

        // Make a label
        UILabel* labelEnv = [[UILabel alloc] initWithFrame:CGRectMake(8.0f, 0.0f, _envWindow.bounds.size.width - 16.0f, DEBUG_SHOWENV_HEIGHT)];
        labelEnv.font = [UIFont boldSystemFontOfSize:12.0f];
        labelEnv.textColor = [UIColor whiteColor];
        labelEnv.text = @"DEVELOP ENVIRONMENT";
        [_envWindow addSubview:labelEnv];
    }
    return _envWindow;
}

// ==== in applicationDidBecomeActive

// Show the window 2 seconds then hide it.
[self.envWindow.layer removeAllAnimations];
self.envWindow.frame = CGRectMake(0.0f, self.window.frame.size.height, self.window.frame.size.width, DEBUG_SHOWENV_HEIGHT);
self.envWindow.hidden = NO;
[UIView animateWithDuration:0.25f
                      delay:0.0f
                    options:UIViewAnimationOptionCurveEaseOut
                 animations:^{
                     self.envWindow.frame = CGRectMake(0.0f, self.window.frame.size.height - DEBUG_SHOWENV_HEIGHT, self.window.frame.size.width, DEBUG_SHOWENV_HEIGHT);
                 }
                 completion:^(BOOL finished) {

                     if (finished)
                     {
                         [UIView animateWithDuration:0.25f
                                               delay:2.0f
                                             options:UIViewAnimationOptionCurveEaseOut
                                          animations:^{
                                              self.envWindow.frame = CGRectMake(0.0f, self.window.frame.size.height, self.window.frame.size.width, DEBUG_SHOWENV_HEIGHT);
                                          }
                                          completion:^(BOOL finished) {

                                              if (finished)
                                              {
                                                  self.envWindow.hidden = YES;
                                              }
                                          }];
                     }
                 }];

I'd appreciate any help.

A:

Solved.
I needed to implement this method in the root view controller:
- (BOOL)prefersStatusBarHidden
{
    return NO;
}

For some reasons, the root view controller in this UIWindow hid the status bar.
(though it should return NO by default, normally)
So instead of doing:
_envWindow.rootViewController = [[UIViewController alloc] init]; // added since iOS9 to avoid the assertion

I created my own view controller with prefersStatusBarHidden overridden.


Q:

what will happen if Http response is not consumed and connection not closed?

I am using below java classes for remote call.

org.apache.http.HttpResponse
  org.apache.http.client.HttpClient

My code snippet goes as follows.
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(URL);
HttpResponse response = client.execute(request);

Now what will happen if I don't consume the response and do not close the connection??

A:

If you don't consume the response will happen just nothing. All the message data is already in the client. If you don't close the connection also nothing because it is usually the server the one that closes the connection after sending the response unless the client sets the header:
Connection: Keep-Alive

Even when you set this header, after some timeout configured in the server, it will close the connection.


Q:

MainPanel not listening to KeyBinding inside nested JPanel

I have a JFrame and on it a MainPanel that extends a JPanel.
The MainPanel contains 2 other JPanels using the BorderLayout to arrange the view.
One of the Panel contains a button where the click event is triggered.
But for the other Panel, the keybinding does not get triggered at all.
Here's the code for the MainClass that hold the 2 Panels
public class MainClass implements ... {

    public JFrame frame;
    JPanel highscore;
    Board board;
    Board.MoveAction moveAction;

    @Override
    public void init(Platform platform, int id) {
        this.platform = platform;
        this.selfId = id;

        platform.setAbout("Hello ");
        //platform.setSleepAfterSync(sleepPeriod);

        frame = platform.createWindow(false);

        // Create mainPanel to add all nested panels and buttons inside
        JPanel mainPanel = new MainPanel();
        mainPanel.add(board, BorderLayout.CENTER);
        mainPanel.add(highscore, BorderLayout.PAGE_END);
        frame.add(mainPanel);

        frame.setTitle("Test");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(380, 440);
        //frame.setBackground(Color.YELLOW);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

public class MainPanel extends JPanel {

    public MainPanel() {
        setLayout(new BorderLayout());
        //setBackground(Color.RED);

        <-- the board here is the issue in the mainpanel-->
        board = new Board(platform);
        //board.setBackground(Color.BLUE);

        highscore = new JPanel();
        JButton button = new JButton("highscore");
        button.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.print("highscore button");
            }
        });
        highscore.add(button);
        //highscore.setBackground(Color.GREEN);
    }
}

And here is the code for the Board class that extends JPanel
public class Board extends JPanel implements ActionListener {

    public Platform platform;
    private int req_dx, req_dy, view_dx, view_dy;
    private int IFW = JComponent.WHEN_IN_FOCUSED_WINDOW;
    private final String MOVE_UP = "UP";
    private final String MOVE_DOWN = "DOWN";
    private final String MOVE_RIGHT = "RIGHT";
    private final String MOVE_LEFT = "LEFT";
    private final String START_GAME = "START";

    public Board(Platform platform) {

        this.platform = platform;
        loadImages();
        initVariables();
        initBoard();
        initKeyBinding();
    }

    private void initBoard() {
        setBackground(Color.black);
        setDoubleBuffered(true);
    }

    private void initVariables() {
    ...
    ...

    }

    ..
    ..
    ..
    ..

     public void initKeyBinding() {

        System.out.println("HERE?  init key binding -> yep ");

        addKeyBinding(MOVE_UP, KeyEvent.VK_UP, new MoveAction(MOVE_UP, 0,-1));
        addKeyBinding(MOVE_DOWN, KeyEvent.VK_DOWN, new MoveAction(MOVE_DOWN, 0,1));
        addKeyBinding(MOVE_LEFT, KeyEvent.VK_LEFT, new MoveAction(MOVE_LEFT, -1 ,0));
        addKeyBinding(MOVE_RIGHT, KeyEvent.VK_RIGHT, new MoveAction(MOVE_RIGHT, 1,0));

        //this 's' to start is definitely wrong
        //figure out how to change from if (key == 's' || key == 'S') to keybinding
        //addKeyBinding(START_GAME, KeyEvent.VK_S, new MoveAction(START_GAME, KeyEvent.VK_S, KeyEvent.VK_S));
}

    private void addKeyBinding(String name, int keyCode, AbstractAction action) {
        //on keyRelease - true if the KeyStroke should represent a key release; false otherwise
        // keyCode - an int specifying the numeric code for a keyboard key
        // ie getInputMap(IFW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true/false), MOVE_UP);

        getInputMap(IFW).put(KeyStroke.getKeyStroke(keyCode, 0), name);
        getActionMap().put(keyCode, action);
}

    public class MoveAction extends AbstractAction {

        private int deltaX;
        private int deltaY;
        private String direction;

        public MoveAction(String direction, int deltaX, int deltaY) {
            this.direction = direction;
            this.deltaX = deltaX;
            this.deltaY = deltaY;
        }

        @Override
        public void actionPerformed(ActionEvent e) {

            System.out.print(direction);

            switch (direction) {
                case MOVE_UP:
                    System.out.println("up? ");
                    req_dx = 0;
                    req_dy = -1;
                    // do stuff that will move up
                case MOVE_DOWN:
                    System.out.println("down? ");
                    req_dx = 0;
                    req_dy = 1;
                    // do stuff that will move down
               // case START_GAME:
               //     System.out.println("sss");
               //     inGame = true;
               //     initGame();

            }
        }
    }
}

I understand there are 4 components to note for KeyBinding
an Action ie actionPerformed {.. }
a KeyStroke ie (KeyStroke.getKeyStroke..)
an InputMap ie getInputMap(...)
an ActionMap ie getActionMap(...)
What am I missing for my keyboard event to be triggered in the MainPanel? thanks!

A:

using this as reference KeyEvent keyPressed key combination is blocked
managed to change keylisteners to keybinding instead
  public void initKeyBinding() {

    mapKeys = new HashMap<>();
    mapKeys.put(MOVE_UP, false);
    mapKeys.put(MOVE_DOWN, false);
    mapKeys.put(MOVE_LEFT, false);
    mapKeys.put(MOVE_RIGHT, false);
    mapKeys.put(START_GAME, false);
    mapKeys.put(PAUSE_GAME, false);
    mapKeys.put(ESCAPE, false);

    addKeyBinding(KeyEvent.VK_UP, MOVE_UP);
    addKeyBinding(KeyEvent.VK_DOWN, MOVE_DOWN);
    addKeyBinding(KeyEvent.VK_LEFT, MOVE_LEFT);
    addKeyBinding(KeyEvent.VK_RIGHT, MOVE_RIGHT);
    addKeyBinding(KeyEvent.VK_S, START_GAME);
    addKeyBinding(KeyEvent.VK_ESCAPE, ESCAPE);

}

private void addKeyBinding(int keyCode, String name) {
    // keyRelease - true if the KeyStroke should represent a key release; false otherwise
    // keyCode - an int specifying the numeric code for a keyboard key

    InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
    ActionMap actionMap = getActionMap();

    inputMap.put(KeyStroke.getKeyStroke(keyCode, 0, true), "pressed" + name);
    inputMap.put(KeyStroke.getKeyStroke(keyCode, 0, false), "released" + name);

    actionMap.put("pressed" + name, new KeyAction(name, true));
    actionMap.put("released" + name, new KeyAction(name, false));
}

public class KeyAction extends AbstractAction {
    private String name;
    private boolean state;

    public KeyAction(String name, boolean state) {
        this.name = name;
        this.state = state;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(name);
        System.out.println(state);
        mapKeys.put(name, state);

        if (inGame) {
            switch (name) {
                case MOVE_UP:
                    req_dx = 0;
                    req_dy = -1;
                    break;
                case MOVE_DOWN:
                    req_dx = 0;
                    req_dy = 1;
                    break;
                case MOVE_RIGHT:
                    req_dx = 1;
                    req_dy = 0;
                    break;
                case MOVE_LEFT:
                    req_dx = -1;
                    req_dy = 0;
                    break;
                case ESCAPE:
                    if (timer.isRunning()) {
                        inGame = false;
                    }
                    break;
            }
        } else {
            if (mapKeys.put(START_GAME, false)) {
                inGame = true;
                initGame();
            }
        }
    }
}

@Override
public void actionPerformed(ActionEvent e) {

    repaint();
}


Q:

Get the previous page name in PHP (not the entire URL)

I have a URL like this;
http://www.mydomain.co.uk/blist.php?prodCodes=NC023-NC022-NC024-NCB33&customerID=NHFGR
Which i grab using HTTP Referrer.  The trouble is i only need the page name i.e. blist.php from the link, not the entire URL as is default using:
$_SERVER['HTTP_REFERER']

Can anyone give me an idea on how to grab that part of the URL?

A:

try with
parse_url($_SERVER['HTTP_REFERER'],PHP_URL_PATH);

Note: this variable doesn't exist in mobile devices.

A:

Try this one:
basename($_SERVER['HTTP_REFERER']);

REF: http://www.php.net/manual/en/function.basename.php

A:

This seems to work, but there might be other elegant url functions.
$url = 'http://www.mydomain.co.uk/blist.php?prodCodes=NC023-NC022-NC024-NCB33&customerID=NHFGR';

preg_match('/\/[a-z0-9]+.php/', $url, $match);

$page = array_shift($match);

echo $page;


Q:

Trentrichardson datetimepicker doesn't work

I'm trying to use the Following timepicker. However, I'm not able to run it. I'm using jsDelivr CDN as suggested by the author.
I include all files listed by the author in the correct order:

jQuery
jQuery UI
datetimepicker
datetimepicker CSS
<!doctype html>
<meta charset="utf-8">
<title>Example</title>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/jquery.ui.timepicker.addon/1.4.5/jquery-ui-sliderAccess.js"></script>
        <script src="https://cdn.jsdelivr.net/jquery.ui.timepicker.addon/1.4.5/jquery-ui-timepicker-addon.js"></script>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/jquery.ui.timepicker.addon/1.4.5/jquery-ui-timepicker-addon.css">

        <script>
            $function () {
            $('#input').datetimepicker();
            });
        </script>

        <title>Example</title>
    </head>
    <body>
        <input type="text" id="input" name="input" value=""/>
    </body>
</html>

Nothing displays when clicking on the form.

A:

Working fiddle.
The problem is in the includs the following example will work :
<!doctype html>
<meta charset="utf-8">
<title>Example</title>
<html>
    <head>
        <title>Example</title>

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-timepicker-addon/1.4.5/jquery-ui-timepicker-addon.min.css" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-timepicker-addon/1.4.5/jquery-ui-timepicker-addon.min.js"></script>
    </head>
    <body>
        <input type="text" id="input" name="input" value=""/>

        <script>
            $(function () {
                $('#input').datetimepicker();
            });
        </script>
    </body>
</html>

Hope this helps.


Q:

SSRS Iif Evaluates True and False

MSDN states that SSRS will evaluate both the true and false part of an Iif statement regardless of which one is returned. This seems to make Iif completely useless in regard to error avoidance. In other words, you cannot use Iif to skirt around an error, so essentially any operation you choose to include must always be valid regardless of the conditions. Honestly, what good is this?
So my question is... Does SSRS have other ways of evaluating conditions besides Iif?
Here is my example.  I just want to be able to return Left without grabbing the first character of the match.
=Iif
(
    InStr(Fields!SearchField.Value, Fields!Criteria.Value) <= 1,
    "",
    Left(Fields!SearchField.Value, InStr(Fields!SearchField.Value, Fields!Criteria.Value)-1)
)

However, what is happening here is that InStr(Fields!Criteria.Value, Fields!Criteria.Value)-1 is evaluating to 0 in some cases, which is perfectly fine until the FALSE part of the statement tries to deduct 1 from it and pass it into the InStr function. InStr cannot accept -1 as the number of characters to return.
An oversimplification of this is as follows.  Assume you have a situation where Value can never fall below 0 without throwing an error.
Iif (Value > 0, Value = Value -1, 0)

Trying to use Iif to force the value not to fall below 0 does not work because all of these statements get evaluated even if they do not meet the conditions.
Trying to use InStr to get an index on a match, and Left to build a substring based on that index fails because of this.  I have no idea how to completely avoid the condition.

A:

Here is the final result from C Black's suggestion to use custom code.  I had eventually hoped to use the segment of the string to format the match in a different color in the opposite column.  I had to add some html tags.  It works perfectly.  Thank you all for your assistance.
Code block:
Public Function ParseMatch (ByVal FullString As String, ByVal Criteria As String) As String

    Dim Segment(2) As String
    Dim Result As String

    If FullString.ToUpper.Contains(Criteria.ToUpper)

        Segment(0) = Left(FullString, InStr(Ucase(FullString), Ucase(Criteria) )-1 )
        Segment(1) = Criteria
        Segment(2) = Right(FullString, Len(FullString) - Len(Segment(0)) - Len(Criteria))

        Result = Segment(0) & "" & Segment(1) & "" & Segment(2)

    Else
        Result = FullString
    End If

    Return Result

End Function

Report cell:
=Code.ParseMatch(Fields!Defendants.Value, Fields!Firm_Client_Name.Value)

If the name is found in the list of defendants, it colors the text blue in that field and bolds it.


Q:

Confused about Having COUNT() = 0

I want to select rows with using inner join to another table.
SELECT COUNT(t3.ID), t3.act, t3.dj_id, t1.ID,
  t1.name, t1.label_id, t1.date, t1.genre,
  t1.plink, t1.featana, t1.promo_aktif
FROM `release` t1
INNER JOIN `acts` t3 ON t3.release_id = t1.ID
WHERE t1.ID IN ($lst) AND t1.promo_aktif = 'Active'
 AND t3.act = 'hide' AND t3.dj_id = '$id'
HAVING COUNT(t3.ID) = 0
ORDER BY t1.ID DESC
LIMIT 0,15

In this query, result is empty. it selects 0 rows. but i am sure there are rows with this conditions.
query needs to select rows in t1 when there is no record found in t3
where am i wrong in this query ?
thanks
EDIT
correct code is
SELECT t3.act, t3.dj_id, t1.ID,
  t1.name, t1.label_id, t1.date, t1.genre,
  t1.plink, t1.featana, t1.promo_aktif
FROM `release` t1
LEFT JOIN `acts` t3 ON t3.release_id = t1.ID AND t3.act = 'hide' AND t3.dj_id = '$id'
WHERE t1.ID IN ($lst) AND t1.promo_aktif = 'Active'
AND t3.release_id is null
ORDER BY t1.ID DESC
LIMIT 0,15

A:

correct code is
SELECT t3.act, t3.dj_id, t1.ID,
  t1.name, t1.label_id, t1.date, t1.genre,
  t1.plink, t1.featana, t1.promo_aktif
FROM `release` t1
LEFT JOIN `acts` t3 ON t3.release_id = t1.ID AND t3.act = 'hide' AND t3.dj_id = '$id'
WHERE t1.ID IN ($lst) AND t1.promo_aktif = 'Active'
AND t3.release_id is null
ORDER BY t1.ID DESC
LIMIT 0,15


Q:

Why are Action and Predicate used or defined as delegates?

Can somebody explain what is the exact reason behind using Action<T> and Predicate<T> as delegates in C#

A:

Are you asking why they exist, or why they're defined as delegates?
As to why they exist, perhaps the best reason is convenience.  If you want a delegate that returns no value and takes a single parameter of some type, they you could define it yourself:
public delegate void MyDelegate(int size);

And then later create one:
MyDelegate proc = new MyDelegate((s) => { // do stuff here });

And, of course, you'd have to do that for every different type you want to have such a method.
Or, you can just use Action<T>:
Action<int> proc = new Action<int>((s) => { /* do stuff here */ });

Of course, you can shorten that to:
Action<int> proc = (s) => { /* do stuff here */ });

As to "why are they delegates?"  Because that's how function references are manipulated in .NET:  we use delegates.  Note the similarities in the examples above.  That is, MyDelegate is conceptually the same thing as an Action<int>.  They're not exactly the same thing, since they have different types, but you could easily replace every instance of that MyDelegate in a program with Action<int>, and the program would work.

A:

What else would they be? Delegates are the most flexible and closest match to what Action<T>, Predicate<T> and Func<T> are modlling - an invocation list with specified parameter types (aka delegates).

A:

The best way to explain why the idiom for performing action and predicate operations using the Action<T> and Predicate<T> delegates was chosen is to first consider the alternative. How could you accomplish the same thing without delegates? The next best thing would be to have interfaces IAction and IPredicate and force developers to declare a class and implement the appropriate interface for each different type of operation needed. But, the problem with that approach is that it requires more effort, more class proliferation, and less maintainable code. The delegate approach is a lot more convenient because you can write the logic inline with where it will be used using anonymous methods or lambda expressions.


Q:

lual_dofile(); wont load script with C++ and Lua

Hello i'm trying to get this code to work
extern "C"
{
#include <lua.h>
#include "lualib.h"
#include "lauxlib.h"
}

#include "glew.h"
#define GLEW_STATIC
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include <stdlib.h>
#include <iostream>
#include <fstream>

////////////////////////
////////////////////////
test.h
void Test(void)

{
    int status;

**//The Lua Interpreter**
lua_State  *L = lua_open();

**//Open Lua Libarys**
luaL_openlibs(L);

**//Run Lua Script**
status = luaL_loadfile(L,"Test.lua");

printf( "actually getting to this point!");
getchar();
//Close Lua
lua_close(L);

}

this is named test.lua
    this is my lua file
print"Whats your name?"

function sleep(n)
end

this doesn't work :(
lual_dofile(L,"Test.lua");
the hole program compiles but then doesn't execute the script or show any visual feedback of the lua script running
has anyone encountered this problem before? and has any knowledge of why ?**

A:

You seem to not understand a few things.
luaL_loadfile loads the script from a file, compiles it, but it does not run it. It just pushes it onto the Lua stack, so that you can run it with whatever parameters you see fit.
luaL_dofile loads the script from a file, compiles it, and runs it, thus popping the script off the stack.
In the case of errors, luaL_loadfile will return an error code explaining what kind of error it is. It also pushes an error message onto the Lua stack if there is an error. If no errors happen, it returns 0.
Similarly, luaL_dofile will return 1 if an error happens, and the error message will be on the Lua stack.
You should always be checking the return value of these functions to see if an error has happened, and acting accordingly.


Q:

casting variable as the function's returned class instance

I have a function that returns one of classes instances.
What I want to do is to 're-cast' the variable as the returned value's actual type.
typescript playground
// classes
class Cake{
    myName: string;
    base: string = "vanilla"
    frosting: string = "empty"
    constructor(myName: string) {
        this.myName = myName
    }
}

class Chocolate extends Cake{
    frosting: string = "chocolate"
    cut() {
        console.log("cut to 8 pieces!")
    }
}

class Strawberry extends Cake {
    frosting:string="strawberry"
    topping:string="coconut"
}

// functions
function getCake(frosting:string, myName:string):Chocolate|Strawberry {
    const chocolateClass = new Chocolate(myName)
    const strawberryClass = new Strawberry(myName)
    const classes:any = { chocolateClass, strawberryClass }
    let returnedObj: Chocolate|Strawberry;
    Object.keys(classes).forEach((key) => {
        if (classes[key].frosting == frosting) {
            returnedObj = classes[key]
        }
    })
    return returnedObj
}

// logic
const myCake: Strawberry | Chocolate = getCake("chocolate", "John")
console.log(myCake.frosting)  // can access it
console.log(myCake.myName)  // can access it
myCake.cut() // can access it, but has linting error + can't see it through intellisense

I can access specific properties from the strawberry class,
console result
but my issue is that the linting says it doesn't exist even though it does. This also prevents intellisense from seeing cut().
So I came to the conclusion that, in some way, I need to recast myCake variable based on what is returned in getCake() function. How can I do that?
I do not want specific functions for each cake type (getStrawberryCake()), because I could have 50 cakes.

A:

If you'd like the compiler to help infer the proper types for you, as opposed to having to "cast" (actually type assert) in multiple places, then it can be done by changing a few things in your code.
The first thing is that the compiler does not understand that Chocolate's frosting property is always the exact string "chocolate", because you've annotated it as string.  To give it a better idea of the relationship between frosting and the type of cake, you can mark the properties as readonly and don't annotate at all.  This prompts the compiler to infer that "chocolate" is a string literal type which can be used later to key off of a mapping from cake frosting names to class types:
class Chocolate extends Cake {
  readonly frosting = "chocolate"
  cut() {
    console.log("cut to 8 pieces!")
  }
}

And the same goes for Strawberry:
class Strawberry extends Cake {
  readonly frosting = "strawberry"
  topping: string = "coconut"
}

Then we'll do a little type juggling to give names to the mapping from frosting to class type:
type PossibleCakes = Chocolate | Strawberry;
type CakeMap = { [K in PossibleCakes["frosting"]]: Extract<PossibleCakes, { frosting: K }> };
// type CakeMap = { chocolate: Chocolate; strawberry: Strawberry; }

The PossibleCakes type is just the union you were using, and you can always add members to this union as desired.  The CakeMap uses a mapped type whose properties use the Extract utility type to pull the proper member out of the PossibleCakes union. This ends up becoming the equivalent of {chocolate: Chocolate; strawberry: Strawberry;}.
Now we can finally write the getCake() function.  It should be a generic function so that by calling it with a particular frosting value, the output will be a particular class, not the PossibleCakes union.
Here it is:
function getCake<K extends keyof CakeMap>(frosting: K, myName: string): CakeMap[K] {
  return { chocolate: new Chocolate(myName), strawberry: new Strawberry(myName) }[frosting];
}

First let's look at the signature... the frosting parameter is of type K, a generic type variable constrained to keyof CakeMap which in this example is "chocolate" | "strawberry".  If you call getCake("chocolate", "xxx") the value of K should be inferred as "chocolate".  Then the return type is CakeMap[K], which is what you get when you look up the K-keyed property of CakeMap.  If K is "chocolate", then CakeMap[K] is Chocolate.
Notice that I've changed the implementation significantly into a straightforward object lookup. That is partially just stylistic choice, but mostly it's because the compiler can actually verify that the output of that will be a CakeMap[K], because the object is a CakeMap and the index is a K.  The iterative version with Object.keys() and forEach() is not as conducive to compiler inference.  If you stick with that version, you'll likely need a type assertion somewhere.
Anyway, let's see if it works:
const myCake = getCake("chocolate", "John")
console.log(myCake.frosting)
console.log(myCake.myName)
myCake.cut()

No errors anymore.  myCake is known by the compiler to be Chocolate and therefore the cut() method is known to be available.  Okay, hope that helps; good luck!
Playground link to code


Q:

Looking for an alterantive to List>>

Ended up with this awful data structure:
List<KeyValuePair<string, KeyValuePair<string, string>>>

It's not likely to get huge (<1K I estimate) and I am gonna iterate this list over and over.
Anyone can think of some better alternative with built-in types?

A:

struct MrStruct
{
   public string Key1,
   public string Key2,
   public string Value1
}

List<MrStruct>;

This is assuming that you are accessing the list sequentially as you did say iterate over.  Potentially, other data structures could be faster for searching.

A:

The best option would be to wrap your own Tuple class, sort of like the one shipping in .NET 4.0.
Then you could have a single:
List<Tuple<string,string,string>>

This is easy enough to write in .NET 2.0 - it's basically just a triplet of values, instead of having 2 in a KeyValuePair.  There is no built-in equivelent for a triplet of values in .NET 2.0, though.

Edit:
After reading your comment about querying in another post, I thought I'd mention this as well -
Even if you don't have unique values in key1, you could dramatically speed up any type of query/search by using:
Dictionary<string, List<KeyValuePair<string,string>>>

Then, instead of storing a single KeyValuePair, you could look up the list of them via the key in the first element.  This would be much, much faster if you needed to find all of the elements with a given first key...


Q:

Jade iteration to HTML table

How can I add the price array to the second 'td' tag in Jade? I would like it to be iteration. Is it possible?
- var item = ['Item1', 'Item2', 'Item3']
- var price = ['40', '90', '140']

table.pricetable
    thead
        tr
            th item
            th price
    tbody
        each a in item
            tr
                td #{a}
                td ???

Thanks,
Simon

A:

Assuming they are directly related:
- var item = ['Item1', 'Item2', 'Item3']
- var price = ['40', '90', '140']

table.pricetable
    thead
        tr
            th item
            th price
    tbody
        each a, index in item
            tr
                td #{a}
                td #{price[index]}

However, a much better approach would be to use an array of objects, instead of two separate arrays:
- var items = [{item: 'Item1', price: 40}, {item: 'Item2', price: 90}, {item: 'Item3', price: 140}]

table.pricetable
    thead
        tr
            th item
            th price
    tbody
        each a in item
            tr
                td #{a.item}
                td #{a.price}


Q:

Using ZXingScannerPage with XF, my content page has weird behavior

I am making an app in xamarin forms of which I will have a login similar to that of whatapp web, an on-screen qr that will be scanned by the phone, in the emulator with visual studio 2017 I have no problems, but when I export the app to an apk and the I install on a mobile device, the app reads the qr and returns to the previous login screen, not showing any reaction, which should be to go to the next screen where I have a dashboard.
What can be? I enclose my code used.
 btnScanQRCode.IsEnabled = false;
        var scan = new ZXingScannerPage();

        scan.OnScanResult += (result) =>
        {
            scan.IsScanning = false;
            Device.BeginInvokeOnMainThread(async () =>
            {
                await Application.Current.MainPage.Navigation.PopAsync();
                var resultado = JsonConvert.DeserializeObject<QrCode>(result.Text);

                JObject qrObject = JObject.Parse(JsonConvert.SerializeObject(resultado));
                JsonSchema schema = JsonSchema.Parse(SettingHelper.SchemaJson);

                bool valid = qrObject.IsValid(schema);

                if (valid == true)
                {
                    App.Database.InsertQrCode(resultado);
                    QrCode qr = App.Database.GetQrCode();
                    await _viewModel.Login();
                    await Navigation.PushAsync(new Organization());
                }
                else
                {
                    await DisplayAlert("False", JsonConvert.SerializeObject(resultado), "ok");
                }
            });
        };
        await Application.Current.MainPage.Navigation.PushAsync(scan);
        btnScanQRCode.IsEnabled = true;

A:

This was originally a comment, but through the writing i realized this is the answer.
You need to debug your code. Attach a device and deploy the app in Debug config. Step through your code and see where it fails.
It sounds like it's crashing silently and probably on the line where you Deserialize result.Text in a QrCode. result.Text is just a string and will never deserialize into an object. You probably need a constructor that takes a string like QrCode(result.Text).


Q:

Line over MapControl dissappears when out of right side or lower side of the control

I have different XAML Line Controls defined inside a MapControl. They change the rotation, color, ... so I thought it was better to do with lines that with MapPolyline which are supposed to stay static.
When panning around the map I found that when the origin of the lines are out of the MapControl, sometimes the lines dissappear, sometimes not. They dissappear only when outside the MapControl BUT on the right side or the lower side. THat doesn't happen when they pan out left side or upper side.
Obviously, I want them in the screen everytime, I don't want to dissappear them.
Any idea why it happens? And how can I get them visible all the time?

Lines visible when origin (orange point) inside the MapControl

 Lines hidden when Lines origin outside right side. Orange point is partially visible.

Lines visible when origin outside left side. Even the orange point is outside the control, but lines are still visible.

A:

I have found a solution for the dissapearing lines problem.
All the lines and XAML shapes that were just on the MapControl should be grouped inside a canvas, width the correct width and height (in my case the max length of the lines in both dimensions and also negative and positive directions, center/anchor the canvas in the MapControl.Center and play with margins tofit all the controls correctly).
For all the tests I have done, lines stays in th screen even both starting point and the ending point are not in the screen.


Q:

How can I fix iTunes to sync apps and musics?

I have used my own apple ID to sync music and apps for long times. About 5 months ago my friend installed a new app by his own apple ID on my phone and now unfortunately I can't sync any app or music.
iPhone 5s
iTunes version:   12.0.1.26
iOS version:     7.0.4
How can I fix this problem ?

A:

As @patrix said, check the Apple ID under Settings > iTunes and App Store on your phone. Also, make sure you DELETED the app your friend bought with their Apple ID before you try syncing to your iTunes on your computer.
Goes without saying, make sure your same Apple ID is used on your iTunes on your computer.


Q:

Installing DIMM modules in HP ProLiant DL180G6 not in recommended order

I have two DL180G6 servers, I used them with 2x2 GB RAM modules, now I'd like to upgrade the memory to 16 GB for each. I have spare 6x2 GB RAM modules per machine (parameters match for the existing ones), but when I populate the remaining slots (these slots were empty from the beginning), one of the RAMs seems to be missing - 2 GB is missing in total memory.
I have made some trial-and-error checking on the slots, it seems both machines have one slot where the memory could not be identified, the memory modules are working fine.
The warranties have just expired on both machines.
I've been following the recommended population order for the memories.
My question is: what happens if I don't follow the population order, will be the machine and memories still be usable or will it damage the RAM/CPU/MB?
Also, I've seen in the specs that it is not required to have both RAM blocks filled with same amount of DIMM module. Would it be feasible to fill one bank with only one module (the second one is the faulty(?)) and fill the rest of the memory in the other?
Thanks for the answers in advance!
Edit #1
I have two CPUs installed in both servers (P/N: 482601-002, 586641-001), also the P/N for the RAMs are all 500202-061.
Edit #2
On one machine the first slot on the second channel for the second CPU (the one farther from the front panel) seems to be faulty while on the other machine the first slot on the third channel for the second CPU.
That is in the first case:
(ch3/2 none) (ch3/1 none) (ch2/2 none) (ch2/1 FAIL) (ch1/2 none) (ch1/1 OK) [CPU]
[CPU] (ch1/1 OK) (ch1/2 none) (ch2/1 OK) (ch2/2 none) (ch3/1 none) (ch3/2 none)
That is in the second case:
(ch3/2 none) (ch3/1 FAIL) (ch2/2 none) (ch2/1 OK) (ch1/2 none) (ch1/1 OK) [CPU]
[CPU] (ch1/1 OK) (ch1/2 none) (ch2/1 OK) (ch2/2 none) (ch3/1 OK) (ch3/2 none)
OK means RAM is working perfectly, FAIL means no RAM in any combinations are detected in that slot. none is an empty slot (as it should be according to the population recommendation).

A:

Servers on this platform have specific DIMM population guidelines. But most of those won't matter except that you're probably using 2GB UDIMMs and that you may only have one processor installed.
If these are UDIMMs, you are allowed to fill two slots per DIMM channel. You mentioned that half of the DIMM slots were initially empty. If you only have one CPU, you can't use half of the slots on the system.
Populate the white slots first, then fill in each channel with the second DIMM.


Q:

the django template and combine {{ }}

I start with django, and I have a little problem.
Well, I have a tuple (top)  and I wanted to display an element of it  according to another template value (date, which is a datetime type).
So, I did that :
{{top.date.day}}

Well it doesn't work, so I tried it :
{{ top.{{date.day}} }}

And it didn't work neither.
So what is the good way to do ?
Thanks.

A:

Use the {% with %} tag to assign the intermediate value to another context variable first.


Q:

Android - MediaPlayer not playing SHOUTcast stream URL on Android 9 device

Strange issue, I have got an Android 6.0 Huawei and a 9.0 Samsung device, I'm testing the following code on both of them:
String streamURL = radioObj.getString(RADIOSTATIONS_STREAM_URL) + "/stream";
        Log.i(TAG, "STREAM URL: " + streamURL);
        // prints: http://109.123.70.138:8136/stream

        // Play selected station
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            playPauseButton.setBackgroundResource(R.drawable.play_icon);
        }

        mediaPlayer = new MediaPlayer();

        try {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(streamURL);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
            }});

        } catch (IOException e) { e.printStackTrace();
            simpleAlert("Thers's something wrong with this stream's URL:" + e.getMessage(), ctx);
        }

I know that the URL is valid because I'm calling another function that checks for Artist and Current Song, and it works fine by printing that info in the Logcat, but no music at all from my Android 9 device, Samsung A40. Volume is all up.
Instead, on my 6.0 device, the music plays!
I'm also trying to get some Logcat message like this:
public void onPrepared(MediaPlayer mp) {
    Log.i(TAG, "MEDIA PLAYER: " + mp.getDuration());
    mediaPlayer.start();
}});

But nothing gets printed, it's like if my code ignores the onPreparedListener call.
I've also tried to assign my mediaPlayer to mp, like this:
@Override
public void onPrepared(MediaPlayer mp) {
    Log.i(TAG, "MEDIA PLAYER: " + mp.getDuration());
    mediaPlayer = mp;
    mp.start();

}});
Again, no success at all.
What am I doing wrong?

A:

Solution
I've created a network_security_config.xml file in the res/xml folder, and placed this code in it:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
            <certificates src="user" />
        </trust-anchors>
    </base-config>
</network-security-config>

Then I've updated my Manifest.xml:
<application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        android:usesCleartextTraffic="true"
        tools:targetApi="n">

Lastly, I've updated my Java code:
// Initialize mediaPlayer
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes( new AudioAttributes.Builder()
              .setUsage(AudioAttributes.USAGE_MEDIA)
              .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
              .build());

try {
            mediaPlayer.setDataSource(ctx, Uri.parse(streamURL));
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
            }});
        } catch (IllegalArgumentException e) { e.printStackTrace();
            simpleAlert(e.getMessage(), ctx);
        } catch (IllegalStateException e) { e.printStackTrace();
            simpleAlert(e.getMessage(), ctx);
        } catch (IOException e) { e.printStackTrace();
            simpleAlert(e.getMessage(), ctx);
        }


Q:

Restarting OpenVPN server causes connected clients to stall

I have a small OpenVPN based network tying together a bunch of VPS's and I noticed that when I add a new client and restart the OpenVPN server to expose the IP address of the new client, the already connected clients will stall for 1 to 2 mins after which they will be able to see the OpenVPN server again.
The way I tested this is by having my already connected VPN clients to ping the VPN server (ping 10.8.0.1). When I add a new client I create a file containing the IP address of the new client in the ccd/newclient file. E.g:
ifconfig-push 10.8.0.5 10.8.0.6

After doing this I restart my OpenVPN server with service openvpn restart. At this point the new client is pretty much able to see the server immediately, but the already connected clients will stall for 1 to 2 minutes after which they will start pinging again.
I tried using service openvpn reload on the VPN server instead but the behaviour seems to be the same.
What is the best way to add a new client to an existing OpenVPN network without impacting the already existing clients in the network?

A:

In my experience, it is not necessary to restart OpenVPN for a new client file in the client config dir.  Indeed, from the man page:

One  of  the  useful properties of this option is that it allows
  client configuration files to be conveniently  created,  edited,  or
  removed while the server is live, without needing to restart  the
  server


Q:

2 white and 2 black rooks on chessboard

I realize this is a fairly basic combinatorial problem, but I'm still confused.
In how many was can 2 black and 2 white rooks be placed on a standard chessboard such that white and black don't attack each other.
The way I saw it first, there are 2 cases:
Case 1. Both white are on the same row/column. In this case there are $
\frac{64 \times 15}{2} \times \binom{49}{2}$ ways of allocating these pieces.
Case 2. Both white are on different rows and columns. In this case there are $\frac{64 \times 49}{2} \times \binom{34}{2}$
Hence the solution is the sum of Case 1 and Case 2. After some deliberation, I realized that this is probably wrong because the order in which the pieces are placed on the board matter, e.g. WBWB is different to WWBB.
So I came up with a different idea, to use inclusion-exclusion theorem.
First, we find 4 squares: $\binom{64}{4}$ for all pieces, then we have 4 cases: 1w/1b attack each other, 2w/1b attack each other, 1b/2w attack each other and 2w/2b attack each other, but as I started analyzing them, I got stuck (e.g. case 1 depends on the distance between rooks), and not sure this is the correct approach either.
Any suggestions?

A:

I'm copying your own solution:
There are 2 cases:
Case 1. Both white rooks are on the same row/column. In this case there are $
\frac{64 \cdot 14}{2} \cdot \binom{42}{2}$ ways of allocating the four pieces.
Proof. The first white rook may be placed on $64$ squares. Then there are $14$ squares for the second white rook. Since the two white rooks are indistinguishable we have to divide $64\cdot14$ by $2$. Now $2$ rows and $1$ column (or vice versa) are forbidden for the black rooks. There remain $6\cdot7$ allowed squares, and we can freely choose $2$ of them.
Case 2. Both white rooks are on different rows and columns. In this case there are $\frac{64 \cdot 49}{2} \cdot \binom{36}{2}$ ways of allocating the four pieces.
Proof. Essentially the same as in case 1.


Q:

Propel with Schema.xml

Is it possible to generate model in Propel using Schema.xml, instead of Schema.yml?
There was once upon a time when xml was used for database generation in Propel, but it had been dropped in favor of yml. I should go for yml if I were handcoding my database schema, but now since I directly export my database schema from MySQL workbench using a plugin, and the result is in xml format, I have no choice but to work with xml.

A:

I have found the answer: Just put your schema.xml in the folder where schema.yml is located and run the command line
php symfony propel:build-model

and you will be fine.


Q:

How can I  get all constants of a type by reflection?

How can I get all constants of any type using reflection?

A:

Though it's an old code:
private FieldInfo[] GetConstants(System.Type type)
{
    ArrayList constants = new ArrayList();

    FieldInfo[] fieldInfos = type.GetFields(
        // Gets all public and static fields

        BindingFlags.Public | BindingFlags.Static |
        // This tells it to get the fields from all base types as well

        BindingFlags.FlattenHierarchy);

    // Go through the list and only pick out the constants
    foreach(FieldInfo fi in fieldInfos)
        // IsLiteral determines if its value is written at
        //   compile time and not changeable
        // IsInitOnly determines if the field can be set
        //   in the body of the constructor
        // for C# a field which is readonly keyword would have both true
        //   but a const field would have only IsLiteral equal to true
        if(fi.IsLiteral && !fi.IsInitOnly)
            constants.Add(fi);

    // Return an array of FieldInfos
    return (FieldInfo[])constants.ToArray(typeof(FieldInfo));
}

Source
You can easily convert it to cleaner code using generics and LINQ:
private List<FieldInfo> GetConstants(Type type)
{
    FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public |
         BindingFlags.Static | BindingFlags.FlattenHierarchy);

    return fieldInfos.Where(fi => fi.IsLiteral && !fi.IsInitOnly).ToList();
}

Or with one line:
type.GetFields(BindingFlags.Public | BindingFlags.Static |
               BindingFlags.FlattenHierarchy)
    .Where(fi => fi.IsLiteral && !fi.IsInitOnly).ToList();

A:

If you would like to get the values of all constants of a specific type, from the target type, here is an extension method (extending some of the answers on this page):
public static class TypeUtilities
{
    public static List<T> GetAllPublicConstantValues<T>(this Type type)
    {
        return type
            .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
            .Where(fi => fi.IsLiteral && !fi.IsInitOnly && fi.FieldType == typeof(T))
            .Select(x => (T)x.GetRawConstantValue())
            .ToList();
    }
}

Then for a class like this
static class MyFruitKeys
{
    public const string Apple = "apple";
    public const string Plum = "plum";
    public const string Peach = "peach";
    public const int WillNotBeIncluded = -1;
}

You can obtain the string constant values like this:
List<string> result = typeof(MyFruitKeys).GetAllPublicConstantValues<string>();
//result[0] == "apple"
//result[1] == "plum"
//result[2] == "peach"

A:

As Type extensions:
public static class TypeExtensions
{
    public static IEnumerable<FieldInfo> GetConstants(this Type type)
    {
        var fieldInfos = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);

        return fieldInfos.Where(fi => fi.IsLiteral && !fi.IsInitOnly);
    }

    public static IEnumerable<T> GetConstantsValues<T>(this Type type) where T : class
    {
        var fieldInfos = GetConstants(type);

        return fieldInfos.Select(fi => fi.GetRawConstantValue() as T);
    }
}


Q:

I need help creating this macro in Assembly x86

I need to create a macro "ADD128 N,M" that will add two unsigned numbers of 128bits each in memory and will put the sum in the memory by N  (N=N+M)
I've been trying to get this to work for a few hours, and I can't get it to work at all. No matter what I try the answer will only be 0s.
Here is the code I need to add this macro in.
 PAGE    80,132
;===================================================================
;                   PROGRAM LISTING 5.1
;
;
;
;===================================================================
        .MODEL  SMALL,BASIC,FARSTACK
        .386
;===================================================================
                                   ;PROCEDURES TO
       EXTRN   NEWLINE:FAR         ;DISPLAY NEWLINE CHARACTER
       EXTRN   PUTDEC:FAR          ;DISPLAY DECIMAL INTEGER
;===================================================================
; S T A C K   D E F I N I T I O N
;
       .STACK  386

SHL64 MACRO REG1, REG2
    SHL     REG2, 1
    RCL     REG1, 1
    ENDM

SHR64   MACRO   REG1, REG2
    SHR     REG1, 1
    RCR     REG2, 1
    ENDM

;===================================================================
; C O D E   S E G M E N T   D E F I N I T I O N
;
       .CODE
;
EX_5_1:
       MOV     BL,1                ;SET CODE FOR WORD DISPLAY
       MOV     EDI,0001H            ;LOAD AX WITH 0000000000000001
       MOV     ESI,0010H
       MOV     EBX,0001H
       MOV     EDX,0001H
       MOV     ECX,0001H
       MOV     DL,1

       MOV      EAX, EDI
       CALL     PUT_BIN         ;DISPLAY CONTENTS OF AX
       MOV      EAX, ESI
       CALL     PUT_BIN         ;DISPLAY CONTENTS OF AX
       CALL     NEWLINE         ;SKIP TO NEXT LINE ON DISPLAY
       CALL     NEWLINE
       CALL     NEWLINE

       SHL64  EDI,ESI

       MOV      EAX,EDI
       CALL     PUT_BIN
       MOV      EAX,ESI
       CALL     PUT_BIN
       CALL     NEWLINE
       CALL     NEWLINE
       CALL     NEWLINE

        SHR64   EDI,ESI

       MOV      EAX,EDI
       CALL     PUT_BIN
       MOV      EAX,ESI
       CALL     PUT_BIN
       CALL     NEWLINE
       CALL     NEWLINE
       CALL     NEWLINE

        MOV     EAX, EBX
       CALL     PUT_BIN
       MOV      EAX,EDX
       CALL     PUT_BIN
       MOV      EAX, EDI
       CALL     PUT_BIN         ;DISPLAY CONTENTS OF AX
       MOV      EAX, ESI
       CALL     PUT_BIN         ;DISPLAY CONTENTS OF AX
       CALL     NEWLINE         ;SKIP TO NEXT LINE ON DISPLAY
       CALL     NEWLINE
       CALL     NEWLINE

This is the last part I need to do, and the only part I can't get to work. Whoever would help me would be a life saver!

A:

Correct macro for adding two 128 bit memory address locations is:
ADD128   MACRO n, m
         mov   eax, dword ptr[m]
         add   dword ptr[n], eax
         mov   eax, dword ptr[m + 4]
         adc   dword ptr[n + 4], eax
         mov   eax, dword ptr[m + 8]
         adc   dword ptr[n + 8], eax
         mov   eax, dword ptr[m + 12]
         adc   dword ptr[n + 12], eax
         ENDM


Q:

Usar SQL LIKE para encontrar um número seguido por espaço

Tenho um campo reunindo valores que são sequências de números separados por espaço e vírgula, como: "1 , 2 , 3 , 23 , 41 , 54"
Estava usando SQL dentro do PHP pra encontrar um número dentro desse campo com LIKE, mas da forma que eu fiz, se eu quisesse encontrar só 5, por exemplo, ele encontraria o 54 no campo que escrevi ali em cima, e isso estaria errado.
$sql = mysql_query("select nm_linha from linhas where cidades_origem like '%$cod_cidades%' and ida like '%$cod_bairros%' and cidades_destino like '%$cod_cidades2%' and ida like '%$cod_bairros2%'");

cidades_origem, ida e cidades_destino são colunas do banco; $cod_cidades, $cod_cidades2, $cod_bairros e $cod_bairros2 são variáveis PHP com os números que quero encontrar.
Como posso fazer pra que a consulta busque o número em questão antecedido e seguido por um espaço, sendo que antes e depois desses espaços possa existir qualquer conteúdo (%)?

A:

usa a virgula do separador para encontrar ex:> LIKE '%, 5,%'... neste caso o primeiro registro deveria vir antecedido por ", " também ex:>, 1, 2, 3,
 Este creio que seja o método mais simples para sua forma de consulta...


Q:

$u_{n+2}=\frac{1}{2^{u_n}}+\frac{1}{2}$. find $\lim u_n$

Let ${u_n}$ be a real sequence defined by
$$
u_1=2, ~ u_2=0, ~ u_{n+2 } =\frac{1}{2^{u_n}} + \frac{1}{2}
$$
Prove that ${u_n}$ has finite limit and find $\lim u_n$.

A:

HINT: Note first that the subsequences $\langle x_{2k}:k\in\Bbb Z^+\rangle$ and $\langle x_{2k-1}:k\in\Bbb Z^+\rangle$ are completely independent, so you’re really dealing with the recurrence $$y_{n+1}=\frac1{2^{y_n}}+\frac12\tag{1}$$ with two different initial values, $2$ and $0$. You need to show that the resulting sequence converges for each of these initial values, and to the same limit for both.
Let $$f(x)=\frac1{2^x}+\frac12\;,$$ and let $g(x)=f(x)-x$. Show that the limit of a convergent sequence satisfying $(1)$ must be a fixed point of $f$ and therefore a zero of $g$. Then show that $g'(x)<0$ for all $x$ and conclude that $g$ has only one zero. By inspection the unique fixed point of $f$ is $x=1$.
Finally, show that if $x<1$, then $x<f\big(f(x)\big)<1$, and if $x>1$, then $x>f\big(f(x)\big)>1$, and put the pieces together to get the desired result.


Q:

query regarding white space in fscanf()

CODE :-
while ( fscanf ( fp,"%s %d %f", e.name, &e.age, &e.bs ) !=EOF )
{
    printf ( "%s     %d     %f\n", e.name, e.age, e.bs ) ;
}

Say I am having following sentences in a file:-

fname lname 20 200000
fname1 lname1 30 50000

The desired output is :-
fname lname     20     200000.0000

fname1 lname1     30     50000.0000

But the output I am getting is :-
fname     (garbage value)     (garbage value)

lname      20     200000.0000

fname1     20     200000.0000

lname1     30     50000.0000

The above problem is due to the fact that %s do not read white spaces, hence it is splitting my fname lname into two parts.
Is there any solution to get the desired output?

A:

You need to use %s %s in your fscanf and read the first name and last name into separate variables, then concatenate them manually. (Use snprintf with %s %s as your format string.)
char first[200], last[200];
while (fscanf(fp, "%200s %200s %d %f", first, last, &e.age, &e.bs) == 4)
{
    snprintf(e.name, sizeof(e.name), "%s %s", first, last);
    printf ( "%s     %d     %f\n", e.name, e.age, e.bs ) ;
}

If names can sometimes have more than two parts, you will need to use something more advanced to parse the string (a regular expression would be one approach), or to continue using fscanf, you'd need to insert an explicit separator character between the name and the numbers.


Q:

Translation of mild, medium, and hot (food spiciness)

In English, salsa, hot sauce, or other spicy foods are often classified as either mild (not very spicy), medium (moderately spicy), or hot (very spicy). Does Spanish have similar adjectives to describe the range of spiciness of food?

A:

This is a common way of speaking about spiciness

poco/ligeramente picante- mild
picante - medium
muy picante - hot

If something is not spicy or slightly spicy we would say it is "suave".


Q:

De-reference error when printing the item pointed to by head in a linked list

I am trying to print the item of the node pointed to by head, but I end up with a 'dereferencing pointer to incomplete type ‘struct nodeStruct’ error.
Code that is not shown includes the list.h file and other functions of the class.
Relevant Code:
List.c:
struct nodeStruct {
    int item;
    struct nodeStruct *next;
};
/*
 * Allocate memory for a node of type struct nodeStruct and initialize
 * it with the value item. Return a pointer to the new node.
 */
struct nodeStruct* List_createNode(int item) {
    struct nodeStruct *newNode = malloc(sizeof(struct nodeStruct));
    newNode->item = item;
    newNode->next = NULL;
    printf("New node created with item %d\n", newNode->item);
    return newNode;
}

/*
 * Insert node at the head of the list.
 */
void List_insertHead (struct nodeStruct **headRef, struct nodeStruct *node) {
    if(*headRef == NULL) {
        printf("List is empty, creating new head\n");
        *headRef = node;
        printf("Empty list new head: %d\n", (*headRef)->item);
    }
    // Head already exists, shift pointer of head to new node
    // and change new head pointer to old head
    else {
        struct nodeStruct* oldHead = *headRef;
        printf("Old head item: %d\n", oldHead->item);
        node->next = *headRef;
        *headRef = node;
        printf("New Head: %d // Old head: %d\n", (*headRef)->item, node->next->item);
    }
}

test_list.c:
int main(int argc, char** argv)
{
printf("Starting tests...\n");
struct nodeStruct* head = NULL;

// Create 1 node:
struct nodeStruct* firstNode = List_createNode(0);
List_insertHead(&head, firstNode);
printf("%d\n", head->item); // error

Makefile:
CC=cc
CXX=CC
CCFLAGS= -g -w -std=c99 -Wall -Werror

all: test_list test

# Compile all .c files into .o files
# % matches all (like * in a command)
# $< is the source file (.c file)
%.o : %.c
    $(CC) -c $(CCFLAGS) $<

test_list: list.o test_list.o
    $(CC) -o test_list list.o test_list.o

test: test_list
    ./test_list

clean:
    rm -f core *.o test_list

The purpose for printing head->item is to see whether or not the head is functioning correctly.

A:

You're missing a header file.
C compiles each source file into object files separately. Then it links them together. Each .c file must know the signature of all types and functions it uses. That means test_list.c must know the signatures of the structs and functions in list.c. Currently it does not.
You could directly include list.c in test_list.c with #include list.c which basically pastes list.c into test_list.c. This will work, but then list.c cannot be used by any other file without causing all sorts of problems.
Better is to make a header file which declares all your types and forward declares all your functions. A forward declaration let's the compiler know what functions are available and what their signature is, with a promise that something else will define the function later.
// list.h

struct nodeStruct {
    int item;
    struct nodeStruct *next;
};

struct nodeStruct* List_createNode(int);
void List_insertHead (struct nodeStruct **, struct nodeStruct *);

Now both test_list.c and list.c can #include "list.h" to give the compiler enough information to compile each source file into an object file. Then the objects will be linked together and tell test_list.o where to find the functions in list.o.
# Compile list.c into list.o using the declarations in list.h
cc -c -g -w -std=c99 -Wall -Werror list.c

# Compile test_list.c into test_list.o using the declarations in list.h
cc -c -g -w -std=c99 -Wall -Werror test_list.c

# Link both object files into an executable so test_list.o can
# use the functions compiled into list.o
cc -o test_list list.o test_list.o


Q:

Print class stack in python

I have the following three classes:
class foo(object):
    pass
class bar(foo):
    pass
class baz(bar):
    pass

I want a method that does something like this:
>>> class_stack(baz)
baz > bar > foo

A:

Perhaps you are looking for the MRO (method resolution order):
In [32]: baz.mro()
Out[32]: [__main__.baz, __main__.bar, __main__.foo, object]

In [33]: [cls.__name__ for cls in baz.mro()]
Out[33]: ['baz', 'bar', 'foo', 'object']

In [34]: ' > '.join([cls.__name__ for cls in baz.mro()])
Out[34]: 'baz > bar > foo > object'


Q:

Which is faster asp.net mvc json or json.net?

I was wondering if anyone has run any benchmark tests on the JSON() function in Asp.net MVC and how it compares to JSON.NET? Also which one outputs the best json strings?

A:

There is a performance comparison here. ASP.NET MVC uses the JavaScriptSerializer.
Json.NET gives you more control over outputting JSON (especially around dates) and also has the option for printing indented JSON.


Q:

Как сделать каст строки в int SQL

 @Query("select b from Book b join b.authors a" +
        " where b.title" +
        " like %:key%" +
        " or b.year like %:key%" +
        " or a.name like %:key%" +
        " or a.lastName like %:key% " +
        " or a.size = :key (ЧТО ТУТ СДЕЛАТЬ?)" +
        " group by b")
Page<Book> findAllBooksByAnyKeyword(@Param("key") String key, Pageable pageable);

У меня есть вот такой метод
Мне нужно скастить строку @Param("key") String key в значение int дабы получить значение размера коллекции a.size
Как это сделать в моем случае?

A:

or a.size = CAST(:key as bigint)

Для postgres это работает.
Есть еще такой вариант, но он зачастую не работает в подобных запросах -
or a.size = :key::bigint


Q:

Can you Mule-click on a mechanical to repair it?

When you do a mule drop in order to repair a mech, can you click on the mechanical unit itself while doing the drop, or do you have to wait for the mule to appear, and then order it to repair?

A:

I tested this in a custom game vs an AI opponent.
You cannot click on the mech unit with the MULE target. You must click on the ground beside the unit to drop the MULE, select the MULE, then right click on the target to start repairing it.
You must turn on auto-repair for it to automatically start repairing other nearby mech units.


Q:

Kivy - Touch not answer everytime on android

I have an App which is working fine, but sometimes I don't have touch answer, no matter where (Button, Tabbed Panel...). This happens in other android I tested, different versions and different cell phones. Sometimes I touch once and answer is ok, sometimes I need touch two or three times. Is not just me, other people using same app in others cell phones had the same problem.
I built with buildozer and have no idea why I have this behavior.
I built and install touch tracer (that demo app) and all the touchs were recognized, so I suppose the problem is not with buildozer, but just is case, this is my buildozer.spec (for my app, not for touch tracer):
    [app]

# (str) Title of your application
title = DAP

# (str) Package name
package.name = DAP

# (str) Package domain (needed for android/ios packaging)
package.domain = com.doatlanticoaopacifico

# (str) Source code where the main.py live
source.dir = .

# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,jpg,kv,atlas,ttf,db

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin

# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version = 0.1

# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = sqlite3,kivy,datetime,plyer,ecdsa,paramiko

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (list) Garden requirements
#garden_requirements =

# (str) Presplash of the application
presplash.filename = %(source.dir)s/data/figura.png

# (str) Icon of the application
icon.filename = %(source.dir)s/data/logo.png

# (str) Supported orientation (one of landscape, portrait or all)
orientation = portrait

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY

#
# OSX Specific
#

#
# author = © Copyright Info

#
# Android specific
#

# (bool) Indicate if the application should be fullscreen or not
fullscreen = 0

# (list) Permissions
android.permissions = INTERNET,ACCESS_NETWORK_STATE,CAMERA

# (int) Android API to use
#android.api = 19

# (int) Minimum API required
#android.minapi = 9

# (int) Android SDK version to use
#android.sdk = 20

# (str) Android NDK version to use
#android.ndk = 9c

# (bool) Use --private data storage (True) or --dir public storage (False)
android.private_storage = False

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
#android.ndk_path =

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
#android.sdk_path =

# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
#android.p4a_dir =

# (list) python-for-android whitelist
#android.p4a_whitelist =

# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
# android.skip_update = False

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (str) python-for-android branch to use, if not master, useful to try
# not yet merged features.
#android.branch = master

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (list) Android additionnal libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

# (str) Android logcat filters to use
#android.logcat_filters = *:S python:D

# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1

#
# iOS specific
#

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s

[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2

# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1

#    -----------------------------------------------------------------------------
#    List as sections
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#

#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

I can provide all the code and apk for test if necessary. I found similiar problems in other forums (stackoverflow too) but in all of them the touch just doesn't work - in my case doesn't work many times, but not with a pattern, apparently.
EDIT
This is a short example of a code which have the same problem:
import kivy
kivy.require('1.0.5')

from kivy.uix.floatlayout import FloatLayout
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.tabbedpanel import TabbedPanel

from kivy.core.window import Window
Window.clearcolor = (1, 1, 1, 1)
import kivy.metrics as conv

class Dap(FloatLayout):
    telal,telaa  = Window.size

class DapApp(App):

    def build(self):

        return Dap()

if __name__ == '__main__':
    DapApp().run()

kv file:
#:kivy 1.0
#:import conv kivy.metrics

<Dap>:

    TabbedPanel:
        do_default_tab: False
        background_color: (1, 1, 1, 0)
        background_normal: ''
        background_disabled_normal:''
        background_down: ''
        background_disabled_down: ''
        tab_width:root.telal/4
        tab_height:conv.cm(1.25)

        TabbedPanelItem:
            background_color: (0, 0, 1, 0.7)
            background_normal: ''
            background_disabled_normal:''
            background_down: ''
            background_disabled_down: ''
            font_size: 18
            color: (1,1,1,1)
            text: 'Login'
            Label:
                text: 'Login tab content area'
                background_color: (1, 1, 1, 1)
                background_normal: ''
                size:(root.telal,conv.cm(3))
                color:(0, 0, 1, 1)

        TabbedPanelItem:
            background_color: (0, 0, 1, 0.7)
            background_normal: ''
            background_disabled_normal:''
            background_down: ''
            background_disabled_down: ''
            font_size: 18
            color: (1,1,1,1)
            text: 'Home'
            Label:
                text: 'Home tab content area'
        TabbedPanelItem:
            background_color: (0, 0, 1, 0.7)
            background_normal: ''
            background_disabled_normal:''
            background_down: ''
            background_disabled_down: ''
            font_size: 18
            color: (1,1,1,1)
            text: 'Pass'
            Label:
                text: 'Pass tab content area'
        TabbedPanelItem:
            background_color: (0, 0, 1, 0.7)
            background_normal: ''
            background_disabled_normal:''
            background_down: ''
            background_disabled_down: ''
            font_size: 18
            color: (1,1,1,1)
            text: 'Fotos'
            Label:
                text: 'Fotos tab content area'

A:

Me and some other people I know had the same problem, and we got it fixed by upgrading to kivy 1.9.2_dev.
Try changing requirements to requirements: kivy==master, ...


Q:

Find smallest number formed by two digits divisible by given number

I was asked the following question in an interview and I had no clue how to do it

Write a program to find the smallest number that can be formed by 0
  and 9 which is divisible by a given number.
  For example, if given
  number is 3 output should be 9,  if given number is 2 output is 90,
  if given number is 10 output is 90

I found this solution online but I haven't understood this one bit :-
public class Smallest0And9DivisibleNumber {
    public static int find(int divisible) {
        int bin = 1;
        while (true) {
            int res = translate(bin);
            if (res % divisible == 0) {
                return res;
            }
            bin += 1;
        }
    }

    private static int translate(int bin) {
        int result = 0;
        for (int i = Integer.toBinaryString(bin).length(); i > 0; i--) {
            result *= result != 0 ? 10 : 0;
            int mask = 1 <<  (i - 1);
            result += (bin & mask) == mask ? 9 : 0;
        }
        return result;
    }

    public static void main(String[] args) {
        assert find(10) == 90;
        assert find(99) == 99;
        assert find(33) == 99;
        assert find(3) == 9;
        assert find(333) == 999;
        assert find(300) == 900;
        assert find(303) == 909;
        assert find(3033) == 9099;
        assert find(3303) == 9909;
    }
}

Can anyone please help with a good understanding or an alternative solution ?

A:

This is a similar approach.
How do we do it manually for 33:
Let's go from the least number which will be? - 0. Is it divisible? No.

Let's go up a number. 9. Is it divisible? No.

Again by a number 90. Is is divisible? No.

Again by a number 99. Is it divisible? Yes.

Let's look at the pattern.
0 9 90 99

How does it look like? binary! Yes, instead of a 1 we have 9.
Now i'll go from 0 till I get a number which divides it, in the form of a binary(by replacing 1 with 9).
we get
Number Binary    0 And 9
0        0         0
1        1         9
2        10        90
3        11        99
4        100       900
5        101       909
6        110       990
7        111       999

We get all the numbers which can be formed using 0 and 9 in an ascending order.


Q:

Image on top of another one in Beamer

I am trying to place an image on top of another in beamer.
I am using
\documentclass[slidestop,compress,mathserif,12pt,xcolor=dvipsnames]{beamer}
\graphicspath{{images/}}
\definecolor{LHCblue}{RGB}{4, 114, 255}
\usecolortheme[named=LHCblue]{structure}
\usepackage[bars]{beamerthemetree} % Beamer theme v 2.2
\usepackage{kerkis}
\usepackage{multimedia}
\usepackage{subfigure}
\mode<presentation>
%frame
\newcommand*\oldmacro{}%
\let\oldmacro\insertshorttitle%
\renewcommand*\insertshorttitle{%
     \oldmacro\hfill%
  \insertframenumber\,}%/\,\inserttotalframenumber
\setbeamertemplate{footline}[frame number]
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\setbeamercovered{higly dynamic}
\usetheme[watermark=ntua-logo.jpg]{Ilmenau} % Beamer theme v 3.0
\useoutertheme[subsection=true]{smoothbars}%Beamer Outer Theme-circles on top

\useinnertheme{circles} %rectangle bullet points instead of circle ones
\usepackage{beamerthemebars}
\setbeamercolor{navigation symbols dimmed}{fg=red!80!black}
\setbeamercolor{navigation symbols}{fg=red!80!black}
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\title[July 2012 H4 Test Beam\hspace{3cm} Stony Brook, NYC]{July 2012 H4 Test Beam}
\author[Stamatopoulos N. Athanasios\hspace{2.5cm}{athanasios.stamatopoulos@cern.ch}]            {Stamatopoulos N. Athanasios}
\institute{NTUA/CERN}
\logo{%
  \makebox[0.99\paperwidth]{%
    \includegraphics[width=1cm,keepaspectratio]{cern_logo_white.jpg}%
    \hfill%
    \includegraphics[width=1cm,keepaspectratio]{ntua-logo.jpg}%
  }%
}

\usepackage{textpos}
\usepackage{tikz}
\usetikzlibrary{%
calc,%
fadings,%
shadings%
}

\usetikzlibrary{arrows,snakes,shapes}
%\usepackage{enumitem}
%\usepackage{paralist}

 \begin{document}

\begin{frame}
%\uncover<1->{\begin{figure}
%  \begin{center}
%    \includegraphics[width=10cm]{layers1}
%  \end{center}
%\end{figure}}
%\hspace{-15cm}
%\uncover<2->{
%\begin{figure}
%  \begin{center}
%    \includegraphics[width=10cm]{layers}
%  \end{center}
%\end{figure}}
\hspace{-15cm}
\begin{figure}
    \centering
    \uncover<1->{\includegraphics[width=10cm]{layers1}}%
    \llap{\raisebox{0cm}{%  move next graphics to top right corner
     \uncover<2->{ \includegraphics[width=10cm]{layers}}%
    }}
%    \caption{My overlay figure.}
  \end{figure}
\end{frame}

\end{document}

I also tried using just the figure enviroment with \hspace{} between two images but it didn't work.{Code in comment}

A:

Do not use the figure environment, it makes no real sense in beamer
\PassOptionsToPackage{demo}{graphics}%% Delete it later
\documentclass{beamer}
\usepackage{caption}
\begin{document}
\begin{frame}{Titel}{Subtitle}
\centering
\includegraphics[height=0.35\textheight]{foo}
\captionof{figure}{first image}
\includegraphics[height=0.35\textheight]{bar}
\captionof{figure}{second image}
\end{frame}

\end{document}

and here the same as an overlay (on top of each other)
\PassOptionsToPackage{demo}{graphics}
\documentclass{beamer}
\usepackage{caption}
\begin{document}
\begin{frame}{Titel}{Subtitle}
\centering
\only<1>{\includegraphics[height=0.7\textheight]{foo}
\captionof{figure}{first image}}
\only<2>{\includegraphics[height=0.7\textheight]{bar}
\captionof{figure}{second image}}
\end{frame}

\end{document}


Q:

extend jquery plugin object with functions

I'm trying to write a new jQuery plugin.
base (this is not my plugin, just for better understanding):
(function($) {
    $.fn.mySuperCoolPlugin = function(options) {

        // Build main options before element iteration
        var opts = $.extend({}, $.fn.mySuperCoolPlugin.defaults, options);

        var editText= 'pre ' + opts.text + ' post';

        return this.each(function() {
            $(this).html(editText);
        });

    }

    // Default settings
    $.fn.mySuperCoolPlugin.defaults = {
        text: 'hi'
    }

})(jQuery);

Now after running my plugin I want to do some additional functions on it.
var plug = $('.text').mySuperCoolPlugin({text: 'running it'});
plug.runAnotherFunction('blabla');
// this for example should set the html to "pre running it post blabla"

plug.runAnotherFunction for example now should extend my previous text and add the text I entered.
Do you know what I mean? How to add extra functions to my plugin? I only see plugins you run once with some options.

A:

you need to create wrapper method. And there is one important rule: It must return the wrapped set. So you must return 'this' (refers to the wrapped set) to allow chaining (what you also needs). You can do this using following pattern:
(function($){
  $.fn.runAnotherFunction = function() {
    // put your code here
    // but you have to return 'this' to allow the chaining
  }
})(jQuery);

Or, better to say (in order to iterate over all wrapped sets inside):
(function($){
  $.fn.runAnotherFunction = function() {
    return this.each(function(){
      // put your code here
    });
  }
})(jQuery);


Q:

Letting :hover transition complete even when not hovering on element

I've been building a photography website here but i'm having an issue with the :hover transitions in the gallery pages. It loads two links that lay over the thumbnails, one opens the image in fancybox and the other sets the image as the background.
Everything works fine, but if you hover off of the thumbnail before the transition is finished, it animates back to its original state.
Is there a way to let the transition play out before reverting to its idle state?

A:

Assuming JavaScript isn't out of the question, jQuery will certainly let you have this behaviour using the .hover() method's ability to accept two callbacks, one for the hover, one for when the hover stops.
$("div.thumb").hover(function(){
    // show the magnifying glasses
    $(this).animate({ top: "0", opacity: 1 });
}, function() {
    // hide the magnifying glasses
    $(this).animate({ top: "-100px", opacity: 0 });
});


Q:

Can hadoop be used as a distributed queue server?

I'm thinking of learning hadoop but not sure if it'll solve my problem.  Basically I have a job with a queue and a bunch of workers.  Each worker does a small amount of work and then either saves the results(if successful) or sends it back to the queue for further processing.  My problem is scalable, is limited by the bandwidth on the network(ec2) which will never keep up with multiple cpu's crunching the data.  I thought maybe I could run my jobs in Java in a hadoop cluster and have hadoop distribute the work via a queue.  Would this be a better approach? I am correct in assuming hadoop can a queue and try to run jobs as locally as possible to minimize bandwidth usage and maximize cpu usage? My program is very cpu bound but most of my recent problems with its performence are related to passing work over a network(I want to keep the work as local as possible), but the difference between the hadoop tutorials I see and my problem is that in the tutorials all the work is known in advance while my program is generating new work for its self constantly(until its finally done).  Would this work and would it help me reduce the impact of passing messages over a network?
Sorry I'm new to hadoop and wanted to know if it could solve my problem.

A:

Hadoop is all about running jobs in a batch-like mode over a large data set. It's hard to get it to have some sort of queue-like behavior, but not impossible. There is Apache ZooKeeper, which will give you synchronization to build a queue if you need it.
There are plenty of tools to solve the problem it looks like you are trying to solve. I suggest taking a look at RabbitMQ. If you use python, Celery is quite fantastic.


Q:

Uncaught Type Error in javascript: object has no method

Uncaught TypeError: Object 0 has no method 'addEventListener'

var A={};
A.addEventsToClassName=function(event,className,func)
{
    var a=document.getElementsByClassName(className);
    for(var b in a)
        {
            b.addEventListener(event,func,false);
        }
};

Object b is meant to be an element object once the function is called later in the code.  How can I prevent this error?

A:

A for (var b in a) will give the property names within a, not the actual values; so you need to dererefence a when you want to use them.
a[b].addEventListener(event, func, false);

Also, it's an Array like data structure, so you should iterate it as such:
for (var i = 0; i < a.length; ++i) {
    a[i].addEventListener(event, func, false);
}