Q:

Javafx Timeline stops playing upon passing through multiple listeners

I'm a beginner who recently picked up JavaFX, I've been trying to make a program that executes an animation on a node upon clicking on it. I've tried to see if anyone else has tried something similar but I have not been able to find a similar case to what I've tried to do.
The Timeline animates Panes, which contain a Rectangle and Text, horizontally across the screen, upon finishing the execution the stage will change scenes. When the user clicks a button to go back to the original scene the buttons should perform another animation.
I've verified that it isn't the scene transition that is causing it to stop and I have also verified that the program is indeed executing .play() on the timeline. The timelines are executed within the custom listeners so the listeners are not an issue as far as I know.
Here is the code sample to recreate the issue I have, run the script and just press on. Here you can see that done is being printed to the console which is right underneath Main_Button_Animation.play(); however, nothing is being animated.
import java.util.ArrayList;
import java.util.List;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;

public class main extends Application{
    Scene scene1;

    @Override
    public void start(Stage primaryStage) {

        primaryStage.setTitle("test");
        Main_Screen MainScreen = new Main_Screen(800, 480);

        scene1 = MainScreen.MainScreen(primaryStage);
        MainScreen.getInitiater().Calibration_Listener(() -> {
            MainScreen.getInitiater().Back_Button_Pressed();
        });

        primaryStage.setScene(scene1);
        primaryStage.show();
    }
    public static void main(String[] args) {
        Application.launch(args);
    }
}
//custom listeners
interface Calibration {
    void menu();
}
interface Back {
    void back();
}
class Initiater {
    private List<Calibration> calilist = new ArrayList<Calibration>();;
    private List<Back> Go_Back = new ArrayList<Back>();

    public void Calibration_Listener(Calibration toAdd) {
        calilist.add(toAdd);
    }
    public void Back_Listener(Back toAdd) {
        Go_Back.add(toAdd);
    }

    public void Calibration_Pressed() {
        System.out.println("Calibration Pressed");
        for (Calibration hl : calilist)
            hl.menu();
    }
    public void Back_Button_Pressed() {
        System.out.println("Back Pressed");
        for (Back hl : Go_Back)
            hl.back();
    }
}

//animations and setup
class Main_Screen {
    Initiater initiater;
    private int X;
    private int Y;

    public Main_Screen(int X, int Y) {
        this.initiater = new Initiater();
        this.X = X;
        this.Y = Y;
    }

    private Pane UI_Button(String name, int[] pos, int[] size, Color color) {
        final Text text = new Text(0, 0, name);
        text.setFont(new Font(20));

        final Rectangle outline = new Rectangle(0, 0, size[0], size[1]);
        outline.setFill(color);

        final StackPane stack = new StackPane();
        stack.getChildren().addAll(outline, text);
        stack.setLayoutX(pos[0]);
        stack.setLayoutY(pos[1]);

        return stack;
    }

    public int getX() {
        return this.X;
    }

    public int getY() {
        return this.Y;
    }

    public Initiater getInitiater() {
        return this.initiater;
    }

    public Scene MainScreen(Stage stage) {
        Scene scene = new Scene(new Group(), getX(), getY());
        scene.setFill(Color.WHITE);

        Pane Start = UI_Button("Start", new int[] { getX() - getX() / 4, 0 }, new int[] { getX() / 4, getY() / 4 }, Color.rgb(255, 0, 0));
        Pane Calibration = UI_Button("Callibration", new int[] { 0, ((getY() + (getY() / 8)) / 4) * 0 }, new int[] { getX() / 2, getY() / 4 }, Color.rgb(60, 208, 230));

        System.out.println(Calibration.boundsInLocalProperty());
        ((Group) scene.getRoot()).getChildren().addAll(Calibration, Start);

        final Timeline Main_Button_Animation = new Timeline();
        final KeyFrame Cali_kf = new KeyFrame(Duration.millis(500), new KeyValue(Calibration.translateXProperty(), getX() / 2));
        final KeyFrame Start_kf = new KeyFrame(Duration.millis(500), new KeyValue(Start.translateXProperty(), -getX() / 4));
        Main_Button_Animation.getKeyFrames().addAll(Cali_kf, Start_kf);
        Main_Button_Animation.setRate(-1);
        Main_Button_Animation.jumpTo(Main_Button_Animation.getTotalDuration());
        Main_Button_Animation.play();

        Calibration.setOnMouseClicked(MouseEvent -> {
            Calibration.setDisable(true);
            Start.setDisable(true);
            System.out.println(Calibration.boundsInLocalProperty());
            Main_Button_Animation.setRate(1);
            Main_Button_Animation.jumpTo(Duration.millis(0));
            Main_Button_Animation.play();
            Main_Button_Animation.setOnFinished(event -> {
                Main_Button_Animation.play();
                System.out.println("done");
            });
        });
        return scene;
    }

}

Edit1 : For clarity, The example above doesn't use any scene transition. Here is a example with a scene transition.
import java.util.ArrayList;
import java.util.List;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;

public class main extends Application{
    Scene scene1, scene2;

    @Override
    public void start(Stage primaryStage) {

        primaryStage.setTitle("test");
        Main_Screen MainScreen = new Main_Screen(800, 480);

        scene1 = MainScreen.MainScreen(primaryStage);
        MainScreen.getInitiater().Calibration_Listener(() -> {
            primaryStage.setScene(scene2);
            primaryStage.show();
        });

        Label label2 = new Label("This is the second scene");
        Button button2 = new Button("Go to scene 1");
        button2.setOnAction(e -> {
            MainScreen.getInitiater().Back_Button_Pressed();
            primaryStage.setScene(scene1);
            primaryStage.show();
        });
        VBox layout2 = new VBox(20);
        layout2.getChildren().addAll(label2, button2);
        scene2 = new Scene(layout2, 800, 480);

        primaryStage.setScene(scene1);
        primaryStage.show();
    }
    public static void main(String[] args) {
        Application.launch(args);
    }
}
//custom listeners
interface Calibration {
    void menu();
}
interface Back {
    void back();
}
class Initiater {
    private List<Calibration> calilist = new ArrayList<Calibration>();;
    private List<Back> Go_Back = new ArrayList<Back>();

    public void Calibration_Listener(Calibration toAdd) {
        calilist.add(toAdd);
    }
    public void Back_Listener(Back toAdd) {
        Go_Back.add(toAdd);
    }

    public void Calibration_Pressed() {
        System.out.println("Calibration Pressed");
        for (Calibration hl : calilist)
            hl.menu();
    }
    public void Back_Button_Pressed() {
        System.out.println("Back Pressed");
        for (Back hl : Go_Back)
            hl.back();
    }
}

//animations and setup
class Main_Screen {
    Initiater initiater;
    private int X;
    private int Y;

    public Main_Screen(int X, int Y) {
        this.initiater = new Initiater();
        this.X = X;
        this.Y = Y;
    }

    private Pane UI_Button(String name, int[] pos, int[] size, Color color) {
        final Text text = new Text(0, 0, name);
        text.setFont(new Font(20));

        final Rectangle outline = new Rectangle(0, 0, size[0], size[1]);
        outline.setFill(color);

        final StackPane stack = new StackPane();
        stack.getChildren().addAll(outline, text);
        stack.setLayoutX(pos[0]);
        stack.setLayoutY(pos[1]);

        return stack;
    }

    public int getX() {
        return this.X;
    }

    public int getY() {
        return this.Y;
    }

    public Initiater getInitiater() {
        return this.initiater;
    }

    public Scene MainScreen(Stage stage) {
        Scene scene = new Scene(new Group(), getX(), getY());
        scene.setFill(Color.WHITE);

        Pane Start = UI_Button("Start", new int[] { getX() - getX() / 4, 0 }, new int[] { getX() / 4, getY() / 4 }, Color.rgb(255, 0, 0));
        Pane Calibration = UI_Button("Callibration", new int[] { 0, ((getY() + (getY() / 8)) / 4) * 0 }, new int[] { getX() / 2, getY() / 4 }, Color.rgb(60, 208, 230));

        System.out.println(Calibration.boundsInLocalProperty());
        ((Group) scene.getRoot()).getChildren().addAll(Calibration, Start);

        final Timeline Main_Button_Animation = new Timeline();
        final KeyFrame Cali_kf = new KeyFrame(Duration.millis(500), new KeyValue(Calibration.translateXProperty(), getX() / 2));
        final KeyFrame Start_kf = new KeyFrame(Duration.millis(500), new KeyValue(Start.translateXProperty(), -getX() / 4));
        Main_Button_Animation.getKeyFrames().addAll(Cali_kf, Start_kf);
        Main_Button_Animation.setRate(-1);
        Main_Button_Animation.jumpTo(Main_Button_Animation.getTotalDuration());
        Main_Button_Animation.play();

        Calibration.setOnMouseClicked(MouseEvent -> {
            Calibration.setDisable(true);
            Start.setDisable(true);
            System.out.println(Calibration.boundsInLocalProperty());
            Main_Button_Animation.setRate(1);
            Main_Button_Animation.jumpTo(Duration.millis(0));
            Main_Button_Animation.play();
            Main_Button_Animation.setOnFinished(event -> {
                this.initiater.Calibration_Pressed();
                System.out.println("done");
            });
        });
        this.initiater.Back_Listener(() -> {
            Main_Button_Animation.setRate(-1);
            Main_Button_Animation.jumpTo(Main_Button_Animation.getTotalDuration());
            Main_Button_Animation.play();
            Main_Button_Animation.setOnFinished(e -> {
                Calibration.setDisable(false);
                Start.setDisable(false);
            });
        });
        return scene;
    }

}

A:

You only define KeyValues for the frame at the end of the Timeline animation. This only allows the Timeline to interpolate between the value at the start of the animation and the target value. Inserting another KeyFrame at the beginning of the animation should fix this issue:
public Scene MainScreen(Stage stage) {
    final Group root = new Group();

    Scene scene = new Scene(root, getX(), getY());
    scene.setFill(Color.WHITE);

    Pane Start = UI_Button("Start", new int[] { getX() * 3 / 4, 0 }, new int[] { getX() / 4, getY() / 4 }, Color.RED);
    Pane Calibration = UI_Button("Callibration", new int[] { 0, 0 }, new int[] { getX() / 2, getY() / 4 }, Color.rgb(60, 208, 230));

    System.out.println(Calibration.boundsInLocalProperty());
    root.getChildren().addAll(Calibration, Start);

    final Timeline Main_Button_Animation = new Timeline(
            new KeyFrame(Duration.ZERO,
                    new KeyValue(Calibration.translateXProperty(), 0),
                    new KeyValue(Start.translateXProperty(), 0)),
            new KeyFrame(Duration.millis(500),
                    new KeyValue(Calibration.translateXProperty(), getX() / 2),
                    new KeyValue(Start.translateXProperty(), -getX() / 4)));

    Main_Button_Animation.setRate(-1);
    Main_Button_Animation.playFrom(Main_Button_Animation.getTotalDuration());

    Calibration.setOnMouseClicked(MouseEvent -> {
        Calibration.setDisable(true);
        Start.setDisable(true);
        System.out.println(Calibration.boundsInLocalProperty());
        Main_Button_Animation.playFromStart();
        Main_Button_Animation.setOnFinished(event -> {
            this.initiater.Calibration_Pressed();
            System.out.println("done");
        });
    });
    this.initiater.Back_Listener(() -> {
        Main_Button_Animation.setRate(-1);
        Main_Button_Animation.playFrom(Main_Button_Animation.getTotalDuration());
        Main_Button_Animation.setOnFinished(e -> {
            Calibration.setDisable(false);
            Start.setDisable(false);
        });
    });
    return scene;
}

Note that there have been a few additional changes here:

Combining  KeyFrames at the same time to a single one with multiple KeyValues
Keep a reference to the scene root to avoid the use of the getter/cast
Using playFrom and playFromStart instead of jumpTo/play
Simplifications of some of the parameters passed to the UI_Button method (rounding could make the result differ by 1 though)
...


Q:

problem with generics delegate

I am new to c#. I am trying to declare a delegate function which takes 2 generics inputs.
I am having problems compile it. can anyone tell me what is the problem here.
delegate int ippcFuncPtr<in T1, in T2>(T1 param, T2 returnval);

static int ippcServerRegisterProcedure(int handle,
    string procedureName, ippcFuncPtr<in T1, in T2> procedure)
    {
        return 0;
    }

Thanks,
Eyal

A:

You don't need to redeclare the contravariance in the parameter, but you do need to give the method type parameters, unless it's in a generic type:
static int ippcServerRegisterProcedure<T1, T2>(int handle, string procedureName,
                                               ippcFuncPtr<T1, T2> procedure)

I'd also strongly recommend that you follow .NET naming conventions - and use the standard delegates where possible... so in this case:
static int RegisterIpccServerProcedure<T1, T2>(int handle, string procedureName,
                                               Func<T1, T2, int> procedure)


Q:

Why is requestAnimFrame being called 2 times?

I'm following along this book to learn about html5 canvas animations, and I was wondering, in this code:
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          window.oRequestAnimationFrame      ||
          window.msRequestAnimationFrame     ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

var x = 0;
function drawIt() {
    window.requestAnimFrame(drawIt);
    var canvas = document.getElementById('canvas');
    var c = canvas.getContext('2d');
    c.fillStyle = "red";
    c.fillRect(x,100,200,100);
    x+=5;
}
window.requestAnimFrame(drawIt);

Why is window.requestAnimFrame(drawIt) being called both outside and inside drawIt function?

A:

To elaborate on what most have already stated in comments (with some additional tips) -
requestAnimationFrame does a single asynchronous call to the function passed in as an argument. This means the method needs to be called continuously to create an animation loop.
The logic place to invoke the call to update the next frame is from within the loop itself. However, the loop is merely a function and needs to be invoked as well, so an initial call is required to "start" the loop. (For this reason it is also wise to consider a mechanism to break the loop).
Another technique could be to use a self-invoking call. The code would in that case look like this instead, without the initial call:
(function drawIt() {
    window.requestAnimFrame(drawIt);
    var canvas = document.getElementById('canvas');
    var c = canvas.getContext('2d');
    c.fillStyle = "red";
    c.fillRect(x,100,200,100);
    x+=5;
})();

The function inside first pair of parenthesis is evaluated while the second pair will invoke a call for whatever is evaluated, ie. the function. If you chose this or the original is more or less a matter of personal taste (the first frame is not updated until the first next available monitor refresh anyways so you won't have any glitches doing a manual update the first time).
Another thing worth noticing while at it: obtaining references to canvas and context is usually never done inside a loop as they are relative costly operations. Try to always obtain those outside the loop, and only once:
var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');

(function drawIt() {
    window.requestAnimFrame(drawIt);
    c.fillStyle = "red";       // also a potential candidate for optimizing
    c.fillRect(x,100,200,100);
    x+=5;
})();

If you set color only once, this too could be moved outside the loop (ie. fillStyle, strokeStyle etc.). These are also costly in terms of animation.


Q:

Howto convert a Comparable into Ordering[A] in Scala

Even if it's really straightforward, e.g. for LocalDate :
  implicit val ord : Ordering[java.time.LocalDate] = new Ordering[java.time.LocalDate] {
    override def compare(x: LocalDate, y: LocalDate): Int = x.compareTo(y)
  }

Is there a way to convert a Comparable<A> into Ordering[A].
I've tried to import import scala.math.Ordering._ but I get this error
diverging implicit expansion for type Ordering[java.time.LocalDate]
[error] starting with method comparatorToOrdering in trait LowPriorityOrderingImplicits

A:

Normally you should be able to get an implicit ordering from a type that implements Comparable. Unfortunately Java does not have type variance, though, and LocalDate implements Comparable[ChronoLocalDate] instead of Comparable[LocalDate], so that doesn't work:
implicitly[Ordering[java.time.chrono.ChronoLocalDate]] // ok
implicitly[Ordering[java.time.LocalDate]] // no implicit found

However, you can use other constructors, for example
Ordering.by[java.time.LocalDate, java.time.chrono.ChronoLocalDate](identity)

or
Ordering.fromLessThan[java.time.LocalDate] { (a, b) => a.compareTo(b) < 0 }


Q:

How do you dynamially invoke a property, but only if its argument is a certain type?

I am trying to use reflection to get all the (settable) properties in my POCO (which take a string argument, for now, but I plan to expand to other types), and set them to something arbitrary. (I need to make sure the .Equals method is implemented properly.)
I have some code in my unit tests that looks something like this (where t is the object under test, and u is a default version of that object):
foreach(var property in t.GetType().GetProperties())
{
    var setMethod = property.GetSetMethod();
    var type = setMethod.GetParameters()[0].GetType();
    if(typeof(string).IsAssignableFrom(type))
    {
        setMethod.Invoke(t, new object[] {"a"});
        Assert.IsFalse(t.Equals(u));
        Assert.IsFalse(t.GetHashCode() == u.GetHashCode());
    }
}

The place where this fails is where I say typeof(string).IsAssignableFrom(type). The code inside the if { ... } block never runs. How would I properly code up this part of the test?

A:

You have confused ParameterInfo.GetType() with ParameterInfo.ParameterType. You should have:
var type = setMethod.GetParameters()[0].ParameterType;

.GetType() returns the Type of the current object, in this case ParameterInfo, which is obviously not what you want.


Q:

Filter Pandas Dataframe that is an array

I have a data frame that I'd like to filter by a column that is of type array. What is the most effective way to do this?
df = pd.DataFrame({'a': [1,2,3,4,5], 'b': [['true','false'],['false'],['false','false','false'],['false','false','true'],[]]})
df

    a   b
0   1   [true, false]
1   2   [false]
2   3   [false, false, false]
3   4   [false, false, true]
4   5   []

I'd ideally like to only return rows that contain a true value.

A:

Without loop :-)
df[pd.DataFrame(df.b.tolist()).eq('true').any(1)]
Out[98]:
   a                     b
0  1         [true, false]
3  4  [false, false, true]


Q:

Unable to create strongly typed view in VS2010 with Fluent Nhibinate and MVC2

HI,
I was wondering if any one else had had a problem with VS2010 MVC 2 projects not being able to automaticly create a strongly typed view after doing a fluent mapping?
When trying to do the mapping VS2010 doesnt show the Entities in the drop down and even if i manually put the class in it doent auto build the view .
Cheers
Dan

A:

It looks like Vs2010 doent like something to do with Nhibinate 3. linking to v2 seems to get it to work as required even when relinking back to v3.
Very odd


Q:

Time conversion in java of format 20170526T043000Z

I have a time string in the following format 20170526T043000Z how can I convert it to milliseconds.

A:

You can use SimpleDateFormat in java since you know the date format.
Eg:
String testDate = "20170526T043000Z";

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmdd'T'HHmmss");
Date parsedDate = simpleDateFormat.parse(testDate);
System.out.println("Time in millis " + parsedDate.getTime());


Q:

Bibtex: How to input accentuation on url?

I am trying to use bibtex to output the url from a reference, but it's not working because the  url has accentuation, just like below:
url = {http://www.epe.gov.br/mercado/Documents/Série\%20Estudos\%20de\%20Energia/20130117_1.pdf},

The output is:
http://www.epe.gov.br/mercado/Documents/S\unhbox\voidb@x\ bgroup\let\unhbox\voidb@x\setbox\@tempboxa\hbox{e\global\ mathchardef\accent@spacefactor\spacefactor}\accent19e\ egroup\spacefactor\accent@spacefactorrie%20Estudos%20de% 20Energia/20130117_1.pdf

Is there a way to protect the accentuation when it enters on url environment?

A:

An URL should not contain accented characters (cf. Uniform resource locator or RFC 3986).
In your URL, replace accented characters by encoded characters:

http://www.epe.gov.br/mercado/Documents/S%C3%A9rie%20Estudos%20de%20Energia/20130117_1.pdf

Edit: Fast reference for encoded characters.


Q:

Recursive division using only subtraction and addition

I have to write a function that returns the quotient and remainder of a division after taking two arguments, the first a dividend, the second a divisor by recursively subtracting the divisor from the dividend.
def recursive_division (a, b, c = 0):
    if b == 0:
        return ("(Cannot divide by zero)","(Cannot divide by zero)")
    elif a < b:
        return (c,a)
    else:
        return recursive_division (a - b, b, 1 + c)

Is there any way to find the quotient without having the default variable c defined as zero in the function... With the function only having two arguments when defined and only returning something based on a or b? (example below)
def recursive division (a, b)
    ...
    return (x, y)

A:

Yes, you can avoid using c by increasing the divisor returned by the recursive_division recursion.
Something like that (not tested):
def recursive_division (a, b):
    if b == 0:
        return ("(Cannot divide by zero)","(Cannot divide by zero)")
    elif a < b:
        return (0, a)
    else:
        (x, y) = recursive_division (a - b, b)
        return (x+1, y)


Q:

wp8 Handle raw push notification in more than one pages

I am developing a wp8 application and the need is the above:
My server sends some raw push notifications that i can handle in my mainpage successful. But i have more pages so i need my app continue to get and handle notifications when the user is on the other pages.
As far i have tried to add the same code as i have put in the main page to handle notifications
  string channelName = "test";
            pushChannel = HttpNotificationChannel.Find(channelName);
            if (pushChannel == null)
            {
                pushChannel = new HttpNotificationChannel(channelName);

                // Register for all the events before attempting to open the channel.
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
                // Register for this notification only if you need to receive the notifications while your application is running.
                pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);

                //pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
                pushChannel.Open();
                // Bind this new channel for toast events.
                //pushChannel.BindToShellToast();
                System.Threading.Thread.Sleep(3000);
                channel = pushChannel.ChannelUri.ToString();
                cSettings.device_notify_id = channel;
            }
            else
            {
                // The channel was already open, so just register for all the events.
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
                // Register for this notification only if you need to receive the notifications while your application is running.
                // pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
                pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
                System.Threading.Thread.Sleep(3000);
                channel = pushChannel.ChannelUri.ToString();
                cSettings.device_notify_id = channel;
                // Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
            }

and the handlers methods
void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
    Dispatcher.BeginInvoke(() =>
    {
        cSettings.device_notify_id = e.ChannelUri.ToString();
        // Display the new URI for testing purposes.   Normally, the URI would be passed back to your web service at this point.
    });
}

void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
    cSettings set = new cSettings();
    set.LogEx(new Exception((String.Format("A push notification {0} error occurred.  {1} ({2}) {3}",
            e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))));

    // Error handling logic for your particular application would be here.
    Dispatcher.BeginInvoke(() =>
        MessageBox.Show(String.Format("A push notification {0} error occurred.  {1} ({2}) {3}",
            e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
            );
}

void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
    string message;
    VibrationDevice vibr = VibrationDevice.GetDefault();
    vibr.Vibrate(TimeSpan.FromSeconds(3));

    using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
    {
        message = reader.ReadToEnd();
    }
    cSettings set = new cSettings();
    string n_type = "";
    string n_header = "";
    //var obj = set.parse_stringfromnotify(message, ref n_type, ref n_header);
    Dispatcher.BeginInvoke(() => nofication_received_action(message, n_type, ""));
}

   private void nofication_received_action(string n_header, string n_type, object data)
        {
            MessageBoxResult result;
            CallSrvData cdata = new CallSrvData();
            Exception ex = null;
            WP_MemberData m;
            WP_MemberRules wpmr;
            cSettings set;
            MemberRules mr;
            Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast();
            Rules c_rules;

                    Notify.data = data;
                    Notify.msg_box_text = String.Format("{0}", n_header);
                    //dose k data sth forma
                    toast = new Microsoft.Phone.Shell.ShellToast();
                    toast.Content = "Invitation received";
                    toast.Title = "Title : ";
                    //SetProperty(toast, "Sound", new Uri("/data/alert.mp3", UriKind.Relative));
                    toast.NavigationUri = new Uri("/forms/Notify.xaml?type=0", UriKind.Relative);
                    toast.Show();
}

When the app is in background and i successfully get the notification and navigate to  Notify.xaml the mechanism works fine, but when i go back or i press start button to leave from Notify.xaml and i resend a notification nothing happens. I have tried to add the same code and in Notify.xaml but again nothing happen when i send notification. In comparison with android where you just register listeners once in your app and then you can receive notification in in any page even the app is "closed" who can i succeed something like that or can i succeed something like that?
Thx a lot for your contribution.

A:

I have found that i can create all the notification functionality in a class which will initialize on app.cs or any time is needed.


Q:

You don’t have permission to use internal app sharing for your app

I am trying to upload an APK for internal app sharing from play store, but while uploading it, its giving me following error:
You don’t have permission to use internal app sharing for com.example
Do we need to add privacy policy prior to it? My app is not using any permission except Internet and ACCESS_NETWORK_STATE. Please tell me why I might be getting this error?

A:

You don't need to add a privacy policy prior to it. I would suggest checking a couple of things:

That you are an authorized uploader for internal app sharing. You can check this under development tools > internal app sharing > manage uploaders in the google play console.
That you are using one of your published application IDs in the Google Play Console. For instance, if you're trying to upload somebody else's sample app to internal app sharing in your console, you should go and change the applicationID in your build.gradle to your published application ID.

Seems like (2) is most likely your issue considering your application id is most likely not com.example.
Hope this helps!


Q:

1980s or late 70s comic featuring a space ark with humanity frozen on board and a romance?

I may be remembering this incorrectly, but was a large hardbound SF anthology with several comics.  May have been black and white, don't remember color.
In one particular story, there is a space ark carrying several shining examples of humanity, who are frozen in suspended animation for the long journey.  Most of them are beautiful females, but there are a few males too to help rebuild the population.
A female is unfrozen too soon, and wakes up to find an older male who has also been unfrozen.  They are alone on this spacecraft and cannot return to suspended animation because, conveniently, to go through the process again would kill them.
So, since they're bored and going to die anyway, they start a romance that goes through all the typical phases including jealousy, betrayal, etc.  The male passenger turns on the female and attempts to kill her by re-freezing her in the cryogenic process.  Turns out her unfroze himself early on purpose and has been thawing out, then killing new girlfriends for years.  At the expense of humanity!  I believe the woman won the battle and then began unfreezing the men?
I was like 11 or 12 when I read this (so 1981 or 1982).  Any ideas?

A:

I believe this was Weird Science, a comic written in the early 1950's. The 22 issues were published in four hardbound volumes in 1980 as part of 'The Complete EC Library'. I remember the story you describe occurring within it, called '50 Girls 50' by Al Williamson - this link includes a color picture of one of pages of the story mentioned (the compendium was published in black and white).


Q:

elasticsearch - planning data mining and metrics

I'm planning a database for a project that stores millions of documents about users and his machine logs.
The question is: how to store and shard this data? User-based or time-based?
Indexing by user I can fastly query million docs of ONE user and generate many time-based reports about him.
Indexing by time I can fastly query all users of ONE day and generate reports about them.
--
What is the best way to mine this data in both directions (user and time)?
I'm reading some about sharding, indexing and routing.

A:

There's no simple rule of thumb to follow, as I emphasize in an article I wrote on Sizing Elasticsearch. It discusses various approaches to sharding and partitioning and other things to keep in mind. Pros and cons with user-based routing and time range partitioning are both covered.
As you indicate in the comment, your ingestion rate isn't very big, so e.g. an index per day can work well. But whether that's a good idea depends a lot on your searches. Are you typically just searching for the last few days, or will a user typically search his entire history? If so, then time-based partitioning might actually work against you, since you'll be searching over so many Lucene indexes.
The linked article references Shay's excellent talk on this topic as well: https://vimeo.com/44716955


Q:

shared value between 2 js file

I declared a variable with inline method in let say index.php, like this
<script type="text/javascript">
var a = 1;
</script>

and how can I use it in the external js file?

A:

In your index.php file, you could have:
<!-- index.php -->
<script type="text/javascript" src="/main.js"></script>
<script type="text/javascript">
var a = 1;
</script>

And the JS file:
// main.js
function stuff() {
    var theValue = a || 1;
}

Instead of the js file being dependent on the variable, perhaps you want the variable dependent on the js file:
<!-- index.php -->
<script type="text/javascript" src="/main.js"></script>
<script type="text/javascript">
var a = 1;
someFunctionInMain(a);
</script>

And then in the js file:
// main.js
function someFunctionInMain(theVariable) {
    console.log(theVariable);
}

This is all very dependent on scope, but if you're working in global/window scope, this should all work just fine. If not you need to reference the variables/functions appropriately.


Q:

An sql query that lists values that are not the same in one column

I'm trying to find an sql that list the majors that are not offered by armstrong state.
The table is called major
majorNumber --    MajorName      --    -   universityName
1  ---------------         --        art   ------------- --       Austin
2  ---------------    --         automotive    --- -       Fort Smith
3   ---------------    --        Chemistry    ---   --      Armstrong
4     ---------------  --        Chemistry     ---  --      Austin

A:

select * from majors where majorName not in (select distinct majorName from
majors where universityName = 'Armstrong')


Q:

Multiple toggle on mobile version

Hello i have a footer navigation (for desktop) with 3 Ul, i want transform each ul in a toggle on mobile version, how can do it?
thx in advance

Title

prod1

prod2

prod3

prod2

prod3

Title 3

prod1

prod2

prod3

prod2

prod3

Title 3

prod1

prod2

prod3

prod2

prod3

A:

This is an extremely basic answer to your issue.
You need to restructure your html so that you have a sub ul in the previous ones like so:

Title

prod1

prod2

prod3

prod2

prod3

Then if you wrap the following in a media query so that they only kick in at your mobile width, they will hide your sub nav:
.subnav {display: none;}
.show-nav {display:block;}

Finally, the following jquery will allow you to toggle a class that changes the display properties of the sub-nav:
$(document).ready(function() {
    var button = $('.clickme');
    var subnav = $('.sub-nav');

    button.on('click',function(){
       subnav.toggleClass('show-nav');
    });
});

This is all here in a fiddle for you: http://jsfiddle.net/uuL2wyLk/

EDIT:
fiddle: http://jsfiddle.net/uuL2wyLk/2/
This fiddle shows the display:none; property only being applied when the window width is less than 500px. When the page is loaded, the script will check to see if the .sub-nav has display:none;, and if it does, will allow the accordion script to run.
This means that when the page is loaded on mobile, the display property will be present due to the media query, which in turn allows the script, but on desktop, the property will not be present and the accordion script will not run.
If you see the new fiddle and shrink the result section down small, and then hit run, you will see that the accordion works. If you make the result section larger and hit run again, the accordion will not fire.
Here is the fiddle again: http://jsfiddle.net/uuL2wyLk/2/

EDIT 2:
Fiddle: http://jsfiddle.net/uuL2wyLk/3/
I have updated the fiddle to allow multiple menus. I have changed the html so that the
 contains the sub nav as well as the click button, like so:

Title

prod1

prod2

prod3

prod2

prod3

With the jquery, you can then make it so that on click of the title, it will find the sibling .sub-nav and apply the .shownav to it. Below is a snippet from the code:
button.on('click',function(){
    $(this).siblings(subnav).toggleClass('show-nav');
});

For all of the code to make this work, see the fiddle: http://jsfiddle.net/uuL2wyLk/3/


Q:

Is it possible to implement 'FileInputStream::BackUp()'-like functionality with Varint32 size-prefixed Protocol Buffer messages?

I am trying to parse delimited protobuf messages (from a file) in C++ using the following implementation of readDelimitedFrom() - also copied below:
bool readDelimitedFrom(
    google::protobuf::io::ZeroCopyInputStream* rawInput,
    google::protobuf::MessageLite* message) {
  // We create a new coded stream for each message.  Don't worry, this is fast,
  // and it makes sure the 64MB total size limit is imposed per-message rather
  // than on the whole stream.  (See the CodedInputStream interface for more
  // info on this limit.)
  google::protobuf::io::CodedInputStream input(rawInput);

  // Read the size.
  uint32_t size;
  if (!input.ReadVarint32(&size)) return false;

  // Tell the stream not to read beyond that size.
  google::protobuf::io::CodedInputStream::Limit limit =
      input.PushLimit(size);

  // Parse the message.
  if (!message->MergeFromCodedStream(&input)) return false;
  if (!input.ConsumedEntireMessage()) return false;

  // Release the limit.
  input.PopLimit(limit);

  return true;
}

My issue is that I need to group messages and process them in batches based on a uint32_t field contained within the message - let's call it id.
Currently, I have the following code in my main loop:
...
int infd = -1;
_sopen_s(&infd, argv[1], _O_RDONLY | _O_BINARY, _SH_DENYWR, _S_IREAD);

google::protobuf::io::ZeroCopyInputStream *input =
    new google::protobuf::io::FileInputStream(infd);

std::vector<ProtoMessage> msgList;
bool readMore = true;

do {
    ProtoMessage msg;
    readMore = readNextMessage(input, msg, msgList);

    if (!msgList.empty()) {
        std::cout << "Processing Message Batch - ID: " << msgList[0].id();
        /* some processing done here */
    }
} while (readMore);

The implementation of readNextMessage() is as follows:
bool readNextMessage(
    google::protobuf::io::ZeroCopyInputStream* rawInput,
    ProtoMessage& nextMsg,
    std::vector<ProtoMessage>& batchList) {

    bool sameBatch = false;
    uint32_t msgID = 0;
    do {
        if (readDelimitedFrom(rawInput, &scan) == -1)
            return false;
        if (nextMsg.id() == 0)
            msgID = nextMsg.id();    // guaranteed to be non-zero
        if (sameBatch = (msgID == nextMsg.id()))
            batchList.push_back(nextMsg);
    } while (sameBatch);

    // need a way to roll-back here as nextMsg is now the first new
    // ProtoMessage belonging to a new batch.

    return true;
}

The logic of this function is fairly simple: take a ZeroCopyInputStream and parse it using readDelimitedFrom() to group ProtoMessage messages into a vector based on their id field. If it encounters a message with a new id, stop and return control back to main for processing on the message batch.
This leads to the undesired requirement of having to consume/read the first message (including its Varint32-encoded size) that does not belong to the previous batch without having a way to 'backup' the stream. I would like to be able to point the ZeroCopyInputStream to the location before the last readDelimitedFrom().
Is there any way for me to modify readDelimitedFrom() to also return the number of bytes consumed during its call, and then use pointer arithmetic on the ZeroCopyInputStream to achieve the desired functionality?
The provided function ZeroCopyInputStream::Backup() has a precondition that ZeroCopyInputStream::Next() be the last method call. Obviously, this is not the case when using the CodedInputStream wrapper to parse delimited messages.

A:

ZeroCopyInputStream::Backup() can only back up over the last buffer received. A single message may span multiple buffers, therefore there's no general way to do what you want given the ZeroCopyInputStream interface.
Some options:

Call rawInput->ByteCount() before parsing each message, in order to determine exactly the byte position where the message started. If you need to roll back, seek the underlying file backwards and recreate the ZeroCopyInputStream on top of it. This only works if you are reading from a file, of course.
When you encounter a message in a new batch, store it off to the side, and then bring it back out when the caller asks to start reading the next batch.


Q:

Using color as string in mixin parameter (lesscss)

Basically I want to use a string that may contain keywords like 'red','green' or 'blue'. However LESS converts it to hex values like #ff0000 instead of red.

Example
.foo(@className) {
    .bar_@{className} { color: white; }
}

Using the mixin
.foo(red);

should output
.bar_red { color: white; }

but instead it shows
.bar_#ff0000 { color: white; }

How do I escape or cast the parameter as a string? Thanks.

A:

Try .foo(~"red"); might work...


Q:

O(n) runtime algorithm

The algorithm below has runtime O(n) according to our professor, however I am confused as to why it is not
O(n log(n)), because the outer loop can run up to log(n) times and the inner loop can run up to n times.
Algoritme Loop5(n)
i = 1
while i ≤ n
    j = 1
    while j ≤ i
       j = j + 1
    i = i∗2

A:

Your professor was right, the running time is O(n).
In the i-th iteration of the outer while-loop, when we have i=2^k for k=0,1,...,log n, the inner while-loop makes O(i) iterations. (When I say log n I mean the base-2 logarithm log_2 n.)
The running time is O(1+2+2^2+2^3+...+2^k) for k=floor(log n). This sums to O(2^{k+1}) which is O(2^{log n}). (This follows from the formula for the partial sum of geometric series.)
Because 2^{log n} = n, the total running time is O(n).
For the interested, here's a proof that the powers of two really sum to what I claim they sum to. (This is a very special case of a more general result.)
Claim. For any natural k, we have 1+2+2^2+...+2^k = 2^{k+1}-1.
Proof. Note that (2-1)*(1+2+2^2+...+2^k) = (2 - 1) + (2^2 - 2) + ... + (2^{k+1} - 2^k) where all 2^i for 0<i<k+1 cancel out, except for i=0 and i=k+1, and we are left with 2^{k+1}-1. QED.


Q:

Apex Trigger to update Account field when Case field is updated

I am struggling to come up with a trigger to update an Account field (Last Survey Sent) when the same field gets inserted or updated on the Case (Last Survey Sent). I am unable to do this via workflow. Any help?
Survey gets sent -> Last Survey Sent field on Case is updated to TODAY() -> Last Survey Sent field on its Account gets set to the same date as the Last Survey Sent field on the Case.
Thanks,
Brian

A:

You could use the following trigger code to keep the two in sync. Rename the Last Survey Sent to match your API name.
Trigger CaseAfterInsertUpdate on Case (after insert, after update) {
    List<Account> accList = new List<Account>();
    for (Case c : Trigger.new) {
        Account acc = new Account(
            Id = c.Account.Id,
            Last_Survey_Sent__c = c.Last_Survey_Sent__c
        );
        accList.add(acc);
    }
    try {
        update accList;
    } catch (Exception ex) {
        System.debug('Could not update Last Survey Sent field on Account with cause: ' + ex.getCause())
    }
}

And the test class. This assumes that the Last Survey Sent field is writable on the Case object.
@isTest
private class CaseTriggerTests() {
    @isTest static void testLastSurveySent() {
        // Insert Account and Case for tests
        // These may need additional fields, depending on your organization
        Account acc = new Account(
           Name = 'Test Account',
           Website = 'www.test.com',
           Phone = '8888888888'
        );
        insert acc;
        Case c = new Case(
            Account = acc.Id,
            Last_Survey_Sent__c = Date.Today();
        );
        insert c;
        // Test that the Last Survey Sent field on the account was updated on Insert
        Account accTest = [SELECT Id, Last_Survey_Sent__c FROM Account WHERE Id = :acc.id];
        System.assertEquals(accTest.Last_Survey_Sent__c, Date.Today());
        // Test that the Last Survey Sent field on the account changes on Update
        c.Last_Survey_Sent__c = Date.Today()+1;
        update c;
        accTest = [SELECT Id, Last_Survey_Sent__c FROM Account WHERE Id = :acc.id];
        System.assertEquals(accTest.Last_Survey_Sent__c, Date.Today()+1);
    }
}

While it may seem more intuitive to query for the account, the use of new and then setting the ID protects you during bulk updates. If you had 1000 cases to update at once, it would require 1000 SOQL queries. Also note that I am adding the accounts to a list and updating the entire list after the trigger runs its for loop. That's another technique for 'bulkifying' and protects against exceeding DML  limits.
Let me know if you have any other questions. I would be happy to walk you through writing unit tests for this trigger.


Q:

Balalaika Fingering Standards

I have noticed that many players construct chords on the balalaika using the thumb, however the neck is quite narrow and even a small hand can manage to extend fingers across the fret board.
As a new player, should I aim to construct chords with the thumb to 'future-proof' my playing for some really radical stuff I cannot yet imagine, or can I get away with a fingers only approach as I have learned for uke/guitar? ... or is it simply impractical and rude to violate the traditional stylings of any instrument?

A:

You were absolutely correct in noticing that the thumb is used in fingering for playing the balalaika. Once you get over the initial hesitation in using your thumb, you will realize that it is a huge advantage for playing chords and solo passages. The thumb is typically used for the 2nd and 3rd (E) strings and the other fingers are used to play on the 1st (A) string. In printed music, you will often see a "T" or Russian "б" (big finger) above the note indicating that you should press down on the fret with your thumb. If you see it below the note, it means you should pluck the string with the thumb of your other hand.
I don't think anyone will be offended if you don't use your thumb but they will certainly think you don't know what you are doing. Your attitude should not be that you are playing with your thumb in order to fit into some dogmatic tradition but that you are using your thumb to a great advantage over other instruments. On a virtuoso level, players absolutely shred the instrument in a very impressive manner while using thumb pizzicato. You will never develop very far as a balalaika player unless you can get used to playing with your thumb.


Q:

Is there a way to make it so that my Xamarin Forms application only works in Portrait mode?

I have an application that looks good in portrait mode but doesn't look good in landscape mode.
Is there any way within forms or through custom renderers that I can set the application so that it always sets itself into portrait mode?
Not sure if this helps, but I am using Xamarin Essentials, just in case there's a way to do it with the functionality that Essentials offers.

A:

Look for this one in android
Activity(ScreenOrientation = ScreenOrientation.Portrait

In android MainActivity:
  namespace Namespace.Droid
{
    [Activity(ScreenOrientation = ScreenOrientation.Portrait , ...]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
     ...

In Ios Info.pList:
<key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>

make sure that only the portrait orientation remains


Q:

Rails: Getting column value from query

Seems like it should be able to look at a simple tutorial or find an aswer with a quick google, but I can't...
codes = PartnerCode.find_by_sql "SELECT * from partner_codes where product = 'SPANMEX' and isused = 'false' limit 1"

I want the column named code, I want just the value.  Tried everything what that seems logical.  Driving me nuts because everything I find shows an example without referencing the actual values returned
So what is the object returned?  Array, hash, ActiveRecord?  Thanks in advance.

A:

You need this one
Partner.where( conditions ).map(&:code)

is shorthand for
Partner.where( conditions ).map{|p| p.code}

PS
if you are often run into such case you will like this gem valium by ernie
it gives you pretty way to get values without instantiating activerecord object like
Partner.where( conditions ).value_of :code

UPDATED:
if you need access some attribute and after that update record
save instance first in some variable:
instance=Partner.where( conditions ).first

then you may access attributes like instance.code and update some attribute
instance.update_attribute || instance.update_attributes
check documentation at api.rubyonrails.org for details


Q:

Что такое constructor в JavaScript и для чего он полезен?

Ни как не могу уложить у себя в голове что такое конструктор в JavaScript ?
Для чего мы его изменяем и используем ?
К примеру:
var Duck = function(name){
  this.name = name;
};

Duck.prototype.quack = function(){
    return this.name + " Duck: Quack-quack!";
};

var TalkingDuck = function(name){
    Duck.call(this, name);
}

TalkingDuck.prototype = Object.create(Duck.prototype);
TalkingDuck.prototype.constructor = TalkingDuck;

Как эффективно мы можем его использовать на практике ?
Обьясните это коротко и понятно, или на оборот :)

A:

На практике constructor обычно не используется.

Что это такое:

У любой функции f() есть свойство f.prototype, являющееся объектом со свойством constructor, равным самой функции. То есть:
f.prototype.constructor === f

Это означает, что у любого объекта o, сконструированого функцией f, у которой не заменяли prototype, будет выполнено
o.constructor /* === (new f()).constructor */ === f

Кроме того, constructor определен у встроенных объектов (Number, Boolean, String, RegExp, ...) и, вследствие "boxing", даже у примитивных значений (1, "asdf", /reg[eE]xp/). У последних его не имеет смысла менять, т.к. изменение касается временно созданного объекта-оболочки над примитивом, и фактически не имеет эффекта.

Некоторые пытаются использовать это свойство, чтобы в методе объекта использовать this.constructor чтобы определить функцию, с помощью которой можно построить такой же объект (пример).

Однако, если заменять prototype, как в вашем примере:
TalkingDuck.prototype = Object.create(Duck.prototype);

..то TalkingDuck.prototype.constructor уже равен Duck, что означает, что new TalkingDuck() уже будет не будет иметь ожидаемый constructor (=== Duck, а не TalkingDuck). Это лечится дополнительным финтом:
TalkingDuck.prototype.constructor = TalkingDuck;

...но чтобы опираться на то что constructor "правильно" установлен для всех объектов, нужно чтобы для каждого из них был проделан этот финт.
Ну а дальше решайте сами - нужен вам такой constructor или нет.


Q:

Open excel sheet from JButton - Java Swing

I'm designing a form using swing.If report button was clicked in my form it have to open the predefined format excel sheet from my D drive.What code have to write in button action listener ??
Thanks ..

A:

I'd recommend looking at the Desktop class in awt.  There's a method here that should help you.
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

public class OpenFile {

    public static void main(String[] args) {
        File file = new File("c:\\appNominalJournalFix.txt");
        try {
            Desktop.getDesktop().open(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Q:

Connect 6 accelerometers to Raspberry Pi

I need to connect 6 LIS3DH Accelerometers to a Raspberry Pi. Is this possible, and how would I do this? Do I need to use I2C or SPI? Or do I need something like an I2C multiplexer?
(If another type of accelerometer would be better, that would be OK as well.)

A:

If you are not short on GPIOs, use SPI.
The main difference between SPI and I²C is that I²C uses device addresses to talk to a given device. Of course, those addresses need to be unique on the I²C bus, and that's the problem. The address is pre-set by the manufacturer, and of course, same devices get the same address.
Some devices allow to change the address freely, often via I²C, but this requires that no other device with same address is connected at that time. Some devices do not allow to change the address. And some, like the LIS3DH allow to change it a little.
The LIS3DH has a single pin, which, connected either to GND or Vsupply, sets the lowest bit of the address to 1 or 0.
So, you can connect two LIS3DH to a single I²C bus. For six, you either need three buses, or a I²C Multiplexer. A multiplexer is like a relay, allowing to connect one of many I²C buses to the master, and is often controlled via I²C itself.
SPI does not use addresses. Here, each device has a ChipSelect pin (CS). The CS pins of all devices are connected to Vsupply, except that of the device the master wants to communicate with.
For your project you can connect all six LIS3DH in parallel to the SPI pins of the Pi, and each CS pin to one GPIO of the Pi. To talk to one device, set its GPIO to 0, and the other five to 1.
While the SPI costs six GPIO pins, it is much easier to setup.


Q:

Line break on javascript not working

I have tried a lot to add line break but it dose not work... replace \n with line brack
I'm going to save html form in txt format in Notepad see all input text with one line which is i don't want that...
need your help please.

<form method="post" action="" id="formToSave">

Date:

    <input type="text" id="nameField" value="00002014" />
    <input type="text" id="title" value="Credit Card Payment" />

Card No:

<input type="text" id="lastNameField" value="Last Name" />

Gender:

<input type="radio" checked="checked" name="gender" value="M" id="genderMale" />
        Male
        <input type="radio" checked="checked" name="gender" value="F" />
        Female

Save as TXT

<button type="submit"> Save as TXT</button>

thank in advance...

A:

I think your problem is not in Javascript, but in the way it is shown afterwards. Try alert(buildData()), does it work properly? If you're appending the text to the DOM, you have to use HTML line feeds, like
.


Q:

How to make an HTTP request without waiting for the response in Ruby

I just want to hit a server from inside of my Rails controller, but not wait for the response. Is this possible? (without launching other threads I can't do that for performance reasons)

A:

It's possible by opening a socket and closing it. This will establish a connection and close the connection without transferring any data within the connection's context...
...you will need to wait for the connection to open - although there might be a way to avoid that.
require 'socket'
# opens a connection, will wait for connection but not for data.
s = TCPSocket.new 'host.url.com', 80
# closes the connection
s.close

It's probably the equivalent of a ping and will not open a new thread... although, it's not totally asynchronous.
With an HTTP request, the code might look something like this:
require 'socket'
host = 'www.google.com'
# opens a connection, will wait for connection but not for data.
s = TCPSocket.new host, 80
# send a GET request for '/' .
s.puts "GET / HTTP/1.1\r\nHost: #{host}\r\n\r\n"
# closes the connection
s.close

You can search for more info about HTTP requests on stack exchange and get some ideas, like here.
Just to clarify (due to comments):
This WILL introduce the latency related to establishing the connection (and sending the request), but you WILL NOT have to wait for the reply to be processed and received.
Dropping the connection (closing your half of the socket) could have any of the following effects - all of which are assuming a decent web server:

if s.close is completed BEFORE the response is fully sent by the web server, the web server will first process the request and then an exception will be raised on the web-server's socket when it tries to send the data. The web server should then close the socket and release any resources.
if s.close is completed AFTER the response is fully sent by the web server, then the server might either: 1. close the socket immediately (normal HTTP 1 behavior) OR 2. keep the connection alive until a timeout occurs (optional HTTP 1.1 behavior) - Timeout is usually about 10 seconds.

Hitting the web server repeatedly in very small intervals might cause a DOS security flag to be raised and future connections to be blocked (this is true regardless of how you hit the web server).
I would probably opt to use a worker thread, like so:
I do believe that running a separate thread might not be as expensive as you believe. It's possible to have one thread cycle for all the asynchronous web requests.
here's a thought:
require 'socket'

REQUESTS_MUTEX = Mutex.new
REQUESTS_QUE = []
REQUESTS_THREAD = Thread.new do
   begin
      loop do
         sleep 0.5 while REQUESTS_QUE.empty?
         host, path = REQUESTS_MUTEX.synchronize {REQUESTS_QUE.shift}
         # the following will open a connection and start a request,
         # but it's easier to use the built in HTTP API...
         # although it will wait for a response.
         s = TCPSocket.new host, 80
         s.puts "GET #{path} HTTP/1.1\r\nHost: #{host}\r\n\r\n"
         s.close
         # log here:
         puts "requested #{path} from #{host}."
      end
   rescue Exception => e
      retry
   end
end
def asynch_request host, path = '/'
   REQUESTS_MUTEX.synchronize {REQUESTS_QUE << [host, path]}
   REQUESTS_THREAD.alive?
end

Now, for every request, you can simply call asynch_request and the cycling thread should hit the web server as soon as it wakes up and notices the que.
You can test it from the terminal by pasting a few requests in a bunch:
asynch_request 'www.google.com'
asynch_request 'www.yahoo.com'
asynch_request 'I.Dont.exist.com'
asynch_request 'very bad host address...'
asynch_request 'www.github.com'

Notice the silent fails (you can tweak the code).

A:

From your controller, add the request-url job to a queue.
Then run a background processes that reads from the queue and performs the requests.
This will remove the request performance delay from your controller action.
Rails 4.2 includes a way of doing this that is abstracted from the particular back-end implementation. It's called ActiveJob:
https://github.com/rails/rails/tree/master/activejob
Here's an example of using it with the Sidekiq service:
https://github.com/mperham/sidekiq/wiki/Active-Job
If you're using an older version of Rails, you could use one of the queue services directly as well.


Q:

Promises in test cases in mocha and chai failing

I am writing a test case in mocha and chai to check if the file is not present it will create the file. Following is the test case :
context('if the valid message is supplied and file is not present in the app\'s logs folder', () => {
  beforeEach((done) => {
    setTimeout(() => {
      fs.exists(filePath, (exists) => {
        if (exists) {
          fileFound = true;
        } else {
          fileFound = false;
        }
      });
      done();
    }, 100);
  });

  it('should indicate the file is not present in the app\'s log folder', () => {
    expect(fileFound).to.be.false;
  });
  it('should create a new file in the app\'s log folder', () => {
    expect(fileFound).to.be.true;
  });
});

Let's day file is present in the folder, in that case first test case should fail. But the problem is, it is saying expected undefined to be false, rather than expected true to be false.

A:

There's very little point in using promises here. Your API is callback-based, so you should use a callback test.
Like this:
it('should exist', (done) => {
  fs.exists(filePath, (exists) => {
    expect(exists).to.be.true;

    done();
  });
});

One thing to bear in mind, mostly unrelated to your issue, is that fs.exists is deprecated and you should use a different method like fs.access or fs.stat:
it('should exist', (done) => {
  fs.access(filePath, (err) => {
    expect(err).to.be.null;

    done();
  });
});

To address your post edit question, the problem here is that you are using setTimeout for no reason and calling done before fs.exists has a chance to finish.
The solution: get rid of the setTimeout and call done inside the fs.exists callback. You should also scope your fileFound variable at a place where it makes sense:
context('if the valid message is supplied and file is not present in the app\'s logs folder', () => {
  let fileFound;

  beforeEach((done) => {
    fs.exists(filePath, (exists) => {
      fileFound = exists;

      done();
    });
  });

  it('should indicate the file is not present in the app\'s log folder', () => {
    expect(fileFound).to.be.false;
  });
  it('should create a new file in the app\'s log folder', () => {
    expect(fileFound).to.be.true;
  });
});


Q:

How to create a PDF file from a dict() data in Python

I have got a Dict from a .txt data, and I want to create a PDF file with this data.
How can I create it?

A:

pip install pdfkit

Also install wkhtmltopdf:
Debian/Ubuntu:
$ sudo apt-get install wkhtmltopdf

Then in your code:
import pdfkit
import json
pdfkit.from_string(json.dumps(yourdict))

You could also do:
import pdfkit
pdfkit.from_file('your.txt', 'out.pdf')


Q:

Find volume by shell method

I am trying to find the volume for the below question using the shell method but I can't get the right answer. can someone give me step by step answer?
$y = x^3, y = 8, x = 0$ about x-axis
what I tried:
$2\pi\int_0^2y(8-y^(3/2))dy$
The answer is $768\pi/7$ but mine isn't even close.

A:

You have some conventions for disk / washers confused with conventions for shells.
First your limits; y goes from 0 to 8.  If you were doing disks you would say x from 0 to 2.  Next, how high is each shell?  $y=x^{1/3}$
$2\pi\int_0^8y(y^{1/3})dy$
via washers:
$\pi\int_0^2 8^2 - x^6 dx$


Q:

Can Teleport and Fly be used interchangeably in the Long Range Trainer Glitch?

I'm currently playing Pokémon Red on the 3DS virtual console and was excited to find that the old glitches were still in tact.
Long Range Trainer Glitch Guide
When I made use of the Long Range Trainer glitch on my original Red cartridge, I used Abra's teleport in Cerulean, but I never tried it anywhere else. I know there is another potential Mew using a north-facing Gambler on route 8, but when I tried this using teleport, when I return to the area, no other trainers will start a battle with me, and I have to reset.
The guide says to use fly, but also says teleport can be used to acquire Mew at the earliest point in the game, which I can verify. I don't know why it wouldn't be a valid way to initiate the glitch in any other area.

A:

Yes, you can use any move that will take you away from the currently planned fight. Dig or an escape rope would also work as well. From the article you linked.

Any method of 'escape' from the Long-Range Trainer may be used, including Teleport and both Dig and the Escape Rope if the Trainer is in a cave area.

This is because the key to the glitch is actually triggering the Long Range Trainer with the ! above their head to initiate a battle, but not letting it start. Any method from the menu by which you can do that should work.
Of note, it may be difficult to use teleport or dig over fly mostly because of the nature of these moves. You don't get to control where you end up quite as easily as you do with fly so it would require a more planning and setup to get it to work than it would otherwise.


Q:

Rails, Silverlight, and cross-domain calls

I have a Rails API hosted in Heroku. I also have a .NET console client that issues HTTPRequests (POST) to it just fine. However, I have a Silverlight that needs to do the same, but I keep getting this error:
Code 4004
ManagedRuntimeError
Which apparently is related to crossdomain issues.
Does anybody know what I need to do to get this Silverlight app to work against my Rails API?

A:

Sounds like you need to add a crossdomain.xml and/or clientaccesspolicy.xml file to the root of your rails site.  Add the domain from which you are requesting from with the silverlight app.
Here is an MSDN article:
http://msdn.microsoft.com/en-us/library/cc197955(v=vs.95).aspx
See also this answer: Cross Domain security error in Silverlight?


Q:

setFrame of UILabel property of .xib doesn´t work

i make the next method in a viewController
-(void)setupDocsLabel:(NSMutableArray *)documents{
    self.lDocumentos.frame = CGRectMake(self.lDocumentos.frame.origin.x, kFirstLabelYPosition+actualLabelYPos,self.lDocumentos.frame.size.width,lDocumentos.frame.size.height);
    self.Documentos.frame = CGRectMake(self.Documentos.frame.origin.x, kFirstLabelYPosition+actualLabelYPos,self.Documentos.frame.size.width,self.Documentos.frame.size.height);

    actualLabelYPos +=20.0;

    for (DocInformation *doc in documents) {
        NSString *textLabel = [doc.documentDescription stringByAppendingString:@" :"];
        UIFont *lblFont = lDocumentos.font;
        CGSize sizeFont = [textLabel sizeWithFont:lblFont forWidth:120.0 lineBreakMode:NSLineBreakByTruncatingTail];

        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(lDocumentos.frame.origin.x+20, kFirstLabelYPosition+actualLabelYPos,sizeFont.width,sizeFont.height)] retain];
        label.text = textLabel;
        [label setFont:lblFont];
        [label setTextColor:lDocumentos.textColor];
        [label setBackgroundColor:[UIColor clearColor]];
        //[label setLineBreakMode:NSLineBreakByTruncatingTail];

        NSString *textDoc = doc.cdgoDocum;
        UIFont *lblFontDoc = Documentos.font;
        CGSize sizeFontDoc = [textDoc sizeWithFont:lblFontDoc];

        UILabel *labelDoc = [[[UILabel alloc] initWithFrame:CGRectMake(label.frame.origin.x+label.frame.size.width+20, kFirstLabelYPosition+actualLabelYPos,sizeFontDoc.width,lDocumentos.frame.size.height)] retain];
        labelDoc.text = textDoc;
        [labelDoc setFont:lblFontDoc];
        [labelDoc setTextColor:lDocumentos.textColor];
        [labelDoc setBackgroundColor:[UIColor clearColor]];

        [self.scrollView addSubview:label];
        [self.scrollView addSubview:labelDoc];

        [label release];
        [labelDoc release];

        actualLabelYPos+=20.0;
    }
    //[self.view setNeedsDisplay];
    //[self.view setNeedsLayout];
}

New Labels add to the scrollView well, but self.lDocumentos (a IBOutlet of the .xib) don´t change his position.
Thanks for the help!!

A:

I've solved it, the problem was that the .xib had enabled Use AutoLayout in the File Inspector.


Q:

Firebase orderByChild query not returning ordered results

I am trying to use the Firebase orderByChild() function per the documentation example but the queries are not coming back filtered or sorted.
Here is the sample data structure:
"notifications": {
  "001": {
    "member_id":      "abc123",
    "created_at":     1424357680681,
    "new":            true,
    "first_name":     "Jon",
    "last_name":      "Snow",
    "message":        "likes your photo"
  },
  "002": {
    "member_id":      "abc456",
    "created_at":     1424357680681,
    "new":            true,
    "first_name":     "Clark",
    "last_name":      "Kent",
    "message":        "likes your comment"
  }
}

When a user logs in, I want to query the notifications hash for only the notifications with a member_id that matches the current user's id.
I have tried both versions with and without the "child_added".
Option A:
  ref.orderByChild("member_id").equalTo(memberId);

Option B:
  ref.orderByChild("member_id").equalTo(memberId)
    .on("child_added", function(data) {
       console.log("new child id = " + data.key());
    });

When I query the notifications hash, the query returns an array of all of the notifications. They are neither limited to the member_id of the current user, nor sorted by member_id. (I can delete the member_id key entirely and the notification will still be returned).
I can always filter the returned array by member_id in-app, but I would really like to get the query working per the documentation.
Any help is appreciated!

A:

I found the problem!
I was under the impression that you could add the query modifiers in place.
I was doing:
  ref.orderByChild("member_id").equalTo(memberId);
  var sync = $firebase(ref);

It should actually be:
  var sync = $firebase(ref.orderByChild("member_id").equalTo(memberId));


Q:

Uniq Descending Sort in a column

In the given data is it possible to uniq sort and print only the top hits against each region?
Given Data
aza1 18
bcn1 16
sat2 12
lcy2 12
fra1 12
aza1 12
bcn1 10
sat2 8
lcy2 9
fra1 13
aza1 21
bcn1 2
sat2 10
lcy2 0
fra1 1

Required Output
aza1 21
bcn1 16
sat2 12
lcy2 12
fra1 13

A:

Solution if order matters, using only sort and uniq
<INPUT_FILE sort -k 1,1 -k 2nr,2 | uniq -w4

OUTPUT:
aza1 21
bcn1 16
fra1 13
lcy2 12
sat2 12

Sort parameters:
-k: sort by key (in this case column, pairs with -t)
-n: sort as a number
-r: reverse order
(optional) -t: in case you want to change the key separator (default: space)
Uniq parameter:
-w: choose the first N characters
Explanation:
In your problem, we need to first sort the first column and then the second one. So there is a -k 1,1 followed by -k 2,2.
But, the second key (ONLY) must be sorted as a number and in the reverse order.
Thus, it should be -k 2nr,2.
Note that if the -n or -r sort parameters are outside -k parameter, they are applied to the whole input instead of specific keys.
Lastly, me must find the unique lines, but matching only the first 4 chars. Thus, uniq -w 4


Q:

How to deploy a mobile 6 application on a phone?

I have made my application and I want to check it out. I made a Cab file through the smartphone cab setup wizard.
Now I have no clue what to do.

A:

Just transfer this .cab to the phone by any means (ActiveSync, Flash card, Bluetooth....) and run it there via file manager.
As an alternative, if you're developing with MS Visual Studio, you can configure deployment options in your project (though defaults are OK in most cases) and hit Debug. MSVC will copy the app to the device and run it under debugger. Cab-file is not involved in this scenario. You need an ActiveSync connection.
All these methods (except Bluetooth, I think) can work with emulator as well as real device.


Q:

Obtaining distance function of path traced by sum of multiple rotating vectors

These shapes are generated by tracing the sum of 2 vectors with different lengths rotating in opposite directions at different frequencies. I am trying to obtain these images using only fragment shaders, so I am unable to record each location of the sum as the vectors rotate.

Rotating vector function of $\theta$ (angle) and $\ell$ (length)
$$\theta = [0, 2\pi]$$
$$
\vec{R}\left(\theta, \ell\right)=
\begin{bmatrix}
\ell \cos{\theta} \\ \ell \sin{\theta}
\end{bmatrix}
$$
Two vectors rotating at different frequencies, $f$
$$ \vec{a} = \vec{R}\left(f\theta, 1\right) \quad f=1 $$
$$ \vec{b} = \vec{R}\left(f\theta, \frac{1}{2}\right) \quad f=-3 $$
The line is traced at $\vec{c}$
$$ \vec{c} = \vec{a} + \vec{b} $$
This process resembles figures produced by a Spirograph, which requires $\vec{c}$ to be recorded for every value of $\theta$.
One way to obtain these shapes with fragment shaders is to recycle the output of the buffer, tracing the shape over time. My goal is to be able to generate these shapes in parallel, without having to reuse any frame-buffers. I have been trying to find a method to compose a distance field that would produce a similar pattern, when intersected with a plane.
The function $f(x,y)=\sqrt{x^2 + y^2}$ plots the distance from $(x,y)$ to the origin. How may I find a function $f(x,y)$ which is the distance between $(x,y)$, and the nearest point that $\vec{c}$ may pass through?
If there is a better method to achieve this please let me know!

A:

The sum of the two vectors is
$$
\begin{bmatrix}
\cos{\theta} \\ \sin{\theta}
\end{bmatrix}
+
\begin{bmatrix}
\frac{1}{2}\cos{-3\theta} \\ \frac{1}{2}\sin{-3\theta}
\end{bmatrix}
=
\begin{bmatrix}
\cos{\theta}+\frac{1}{2}\cos{-3\theta} \\ \cos{\theta}+\frac{1}{2} \sin{-3\theta}
\end{bmatrix}
$$
I used wolfram alpha to convert these two parametric equations to a Cartesian equation (I think thats what it is called).
$$
y = \pm\sqrt{-x^2 \pm\sqrt{x^2 (8 x + 9)} - 3 x}
$$
Using some algebra and some help from wolfram (again)
$$
x^4 - 2 x^3 + 2 x^2 y^2 + 6 x y^2 + y^4 = 0
$$
Then to create my distance field, I exchange $z$ for $0$
$$
x^4 - 2 x^3 + 2 x^2 y^2 + 6 x y^2 + y^4 = z
$$
therefore my distance field is
$$
f(x,y)=x^4 - 2 x^3 + 2 x^2 y^2 + 6 x y^2 + y^4
$$
Before this, I had no idea what parametric functions were, and I am still very unclear on how this works. Though I am really happy because I learned something, and I solved my problem!
Here is a more generalized method: Converting parametric equation to Cartesian


Q:

Best Way To Display Music Play Controls On Lock Screen iOS7

I have a music app. What is the best way to have the song info and music controls show up in the lock screen like SoundCloud - see (http://cl.ly/image/1a1H041A1Z34)
Thank you very much!

A:

Pretty useful guide - Lock screen “Now Playing” with MPNowPlayingInfoCenter;
This only works with iOS 5+ and is done something like this.
- (void)setupNowPlayingInfoCenter:(MPMediaItem *)currentSong
{
    NSString *ver = [[UIDevice currentDevice] systemVersion];
    CGFloat version = 4.0;
    if ([ver length] >= 3)
    {
        version = [[ver substringToIndex:3] floatValue];
    }

    if (version >= 5.0)
    {
        MPMediaItemArtwork *artwork = [currentSong valueForProperty:MPMediaItemPropertyArtwork];

        MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];

        if (currentSong == nil)
        {
            infoCenter.nowPlayingInfo = nil;
            return;
        }

        infoCenter.nowPlayingInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                [currentSong valueForKey:MPMediaItemPropertyTitle], MPMediaItemPropertyTitle,
                [currentSong valueForKey:MPMediaItemPropertyArtist], MPMediaItemPropertyArtist,
                [currentSong valueForKey:MPMediaItemPropertyAlbumTitle], MPMediaItemPropertyAlbumTitle,
                [currentSong valueForKey:MPMediaItemPropertyAlbumTrackCount], MPMediaItemPropertyAlbumTrackCount,
                [currentSong valueForKey:MPMediaItemPropertyAlbumTrackNumber], MPMediaItemPropertyAlbumTrackNumber,
                artwork, MPMediaItemPropertyArtwork,
                [currentSong valueForKey:MPMediaItemPropertyComposer], MPMediaItemPropertyComposer,
                [currentSong valueForKey:MPMediaItemPropertyDiscCount], MPMediaItemPropertyDiscCount,
                [currentSong valueForKey:MPMediaItemPropertyDiscNumber], MPMediaItemPropertyDiscNumber,
                [currentSong valueForKey:MPMediaItemPropertyGenre], MPMediaItemPropertyGenre,
                [currentSong valueForKey:MPMediaItemPropertyPersistentID], MPMediaItemPropertyPersistentID,
                [currentSong valueForKey:MPMediaItemPropertyPlaybackDuration], MPMediaItemPropertyPlaybackDuration,
                [NSNumber numberWithInt:self.mediaCollection.nowPlayingIndex + 1], MPNowPlayingInfoPropertyPlaybackQueueIndex,
                [NSNumber numberWithInt:[self.mediaCollection count]], MPNowPlayingInfoPropertyPlaybackQueueCount, nil];
    }
}

next time, try to use search:

Changing iphone lock screen programmatically when app is running in background


Q:

Deprecation warning from Capybara

I am upgrading from rails 3.2.19 to rails 4.1.5, using rspec-rails 2.14.0.rc1 and capybara 2.4.1. All tests pass, and I only have one deprecation warning left:
[DEPRECATION] Capybara::Webkit::Driver#accept_js_confirms! is deprecated. Please use Capybara::Session#accept_confirm instead.

The line of code that is causing this is
page.driver.accept_js_confirms!

How do I change this line in order to eliminate the deprecation warning?

A:

Given that the exception says:

Please use Capybara::Session#accept_confirm instead.

You probably want:
page.accept_confirm

Note that accept_confirm is being run against the Capybara::Session instead of the driver.
This method expects a block that triggers the confirm alert to appear. For example:
page.accept_confirm do
  click_link('that_opens_confirm')
end

A:

Justin Ko's answer is correct as to the usage of #accept_confirm - it's
page.accept_confirm do
  #code that will trigger the modal
end

or you can do
page.accept_confirm 'Are you sure?' do
  #code that will trigger the modal
end

which will verify that "Are you sure?" is the prompt displayed in the confirm box.
In your failing test do you happen to be dealing with another modal first?  capybara-webkit had a bug with multiple modals that was fixed a few days ago - https://github.com/thoughtbot/capybara-webkit/commit/86e422f94422d39e537329d64d7bfe8f6360bd8b .  It's not in a relased version yet though.

A:

I had 50/50 success with Justin Ko's answer.  The one that worked had code like this:
link_to "Reset", reset_pre_shot_description_mental_game_path(@mental_game), data: {confirm: 'Are you sure?'}, class: "small_button round", id: "reset_pre-shot"

and this test:
page.accept_confirm do
  click_link "Reset"
end

The test that fails (but has code that works in the browser) has code
link_to 'Delete', micropost, data: {confirm: 'Are you sure?'}, method: :delete

and test
page.accept_confirm do
  click_link "Delete"
end

The failure message was
Failure/Error: page.accept_confirm do
Capybara::ModalNotFound:
  Timed out waiting for modal dialog

I tried moving the method: :delete into the :data hash, but this did not help.
It turns out that the deprecation warning actually found two bugs in the code, as I was using the rails 3 syntax for confirm i.e. not using the :data hash, so my code was broken but the page.driver.accept_js_confirms! test was not picking it up. So this has been worthwhile tracking down.


Q:

What is the AI assistant for the Rescue armor of Pepper?

In Avengers: Endgame Pepper Potts dons the Rescue armor. Does it have an AI assistant? If yes, what is its name? We have seen Iron Man use J.A.R.V.I.S. and F.R.I.D.A.Y, and Spider-Man has Karen and E.D.I.T.H.

A:

It would appear so, in Avengers: Endgame when Pepper goes to see Tony after his Snap she asks F.R.I.D.A.Y. to examine him. It isn't exactly clear where F.R.I.D.A.Y. is talking from as they both have their helmets off but it is presumably from the Rescue suit as Tony's was damaged from the Snap. You can watch that scene here.

Pepper: F.R.I.D.A.Y.?
F.R.I.D.A.Y.: Life functions critical.
Avengers: Endgame

The Rescue Armor also has the same HUD and advanced functionality of Tony's suits and even lets her know about the incoming flood so that she can alert Doctor Strange about it. It seems unlikely that Tony would add all of this functionality in but not an AI, in fact, some of it probably doesn't work without an AI.


Q:

What is the alternative to "scroll-linked positioning effect" to prevent performance issues?

I get the following warning in firefox

This site appears to use a scroll-linked positioning effect. This may not work well with asynchronous panning; see https://developer.mozilla.org/docs/Mozilla/Performance/ScrollLinkedEffects for further details and to join the discussion on related tools and features!

The snippet I use is
$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
    $('#share-bar').hide('slow');
  }
  else {
    $('#share-bar').show('slow');
  }
});

How can I solve this?

A:

I have the same problem here to javascript/jquery] .onscroll() then show the back to top button.
I solved this problem with a "switch boolean" and a timer:
(I had several solutions but it seems that this one is best)
With an ftm license (Free To Mankind license: show this script to anyone still programming):
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="Generator" content="Constantin">
  <title>on scroll 2019</title>

GO TO TOP

bla bla bla
not a lorem ipsum
only bla bla bla
bla bla bla
not a lorem ipsum
only bla bla bla
bla bla bla
not a lorem ipsum
only bla bla bla
bla bla bla
not a lorem ipsum
only bla bla bla
bla bla bla
not a lorem ipsum
only bla bla bla
bla bla bla
not a lorem ipsum
only bla bla bla
bla bla bla
not a lorem ipsum
only bla bla bla
bla bla bla
not a lorem ipsum
only bla bla bla
bla bla bla
not a lorem ipsum
only bla bla bla
bla bla bla
not a lorem ipsum
only bla bla bla
bla bla bla
not a lorem ipsum
only bla bla bla
bla bla bla
not a lorem ipsum
only bla bla bla
bla bla bla
not a lorem ipsum
only bla bla bla


Q:

Macro Signature Not Honored by Velocity Engine

How can I enable Velocity engine to honor  #macro signatures so that if I try calling a macro in templates Example:
#myTestMacro($arg1 $arg2)

that has a different signature when defined Example:
#macro(myTestMacro $arg)

Velocity will be smart enough to throw an error, so I can catch invalid number of arguments in the example above?

A:

In the configuration, set velocimacro.arguments.strict=true.


Q:

Run a function/script in PHP and without affect the script flow

I need to make a php script that execute another function (or another script) in background: When i call it, the flow of the script must continue even if the second script is not finished.
I found http://php.net/manual/en/function.sleep.php (sleep function), but is not exactly what i need.
Some help?
Edit:
What i want to acomplish?
I need to make a change in my database. Then run a php script, but i need to make another change in my database 1 second (or whatever lapse) after i ran the php script.

A:

Since you apparently don't care about a response from the script you are calling.
And if your server allow...
You could call your script as if it was from a shell and say that it should discard output  with "> /dev/null 2>/dev/null &"...
shell_exec('php yourotherscript.php > /dev/null 2>/dev/null &');


Q:

C# Getting a component's values at runtime?

I'm attempting to create a NotifyIcon that can be inherited so that I can add my own properties/etc. Through looking at a component class someone else wrote, I've made some progress as can be seen below, and the component can be dragged into the form. To be honest, I have little idea on what I'm doing, and there appears to be no tutorials anywhere on the internet that are of any use at all.
In the PrepareIcon method you see, the message box that pops up appears blank, even though I have tried changing the value from the designer default of notifyIconInheritable1. I have seen the NotifyIcon appear while in the designer, so I have been utterly confused on how this works.
The question is; what's wrong with this or what am I doing wrong, and am I wasting my time and shouldn't be attempting this at all?
namespace AwesomeNotifyIcon
{
    [DefaultProperty("Text"), DefaultEvent("Click"), Description("Displays an icon in the notification area, on the right side of the Windows taskbar, during run time")]
    public partial class NotifyIconInheritable : Component
    {
        private NotifyIcon notifyIcon;

        public NotifyIconInheritable()
        {
            //PrepareIcon();
            InitializeComponent();
        }

        public NotifyIconInheritable(IContainer container)
        {
            if (container != null)
            {
                container.Add(this);
            }
            PrepareIcon();
            InitializeComponent();
        }

        [Category("Appearance"), Description("The icon to associate with the balloon ToolTip."), DefaultValue(ToolTipIcon.None)]
        public ToolTipIcon BalloonTipIcon { get; set; }

        [Category("Appearance"), Description("The text to associate with the balloon ToolTip.")]
        public string BalloonTipText { get; set; }

        [Category("Appearance"), Description("The title of the balloon ToolTip.")]
        public string BalloonTipTitle { get; set; }

        [Category("Appearance"), Description("The icon to display in the system tray.")]
        public Icon Icon { get; set; }

        [Category("Appearance"), Description("The text that will be displayed when the mouse hovers over the icon.")]
        public string Text { get; set; }

        [Category("Behaviour"), Description("The shortcut menu to show when the user right-clicks the icon.")]
        public ContextMenuStrip ContextMenuStrip { get; set; }

        [Category("Behaviour"), Description("Determines whether the control is visible or hidden."), DefaultValue(false)]
        public bool Visible { get; set; }

        [Category("Data"), Description("User-defined data associated with the object.")]
        public object Tag { get; set; }

        [Category("Action"), Description("Occurs when the component is clicked.")]
        public event EventHandler Click;

        private void PrepareIcon()
        {
            notifyIcon = new NotifyIcon();
            notifyIcon.Dispose();
            MessageBox.Show(this.Text);

            if (Click != null)
                notifyIcon.Click += Click;
        }
    }
}

Here's the properties as seen in the designer:
http://cl.ly/1vIF/content http://cl.ly/1vIF/content

A:

When you add a control using the designer, it generates code that looks something like this:
NotifyIconInheritable icon = new NotifyIconInheritable();
icon.Text = "Some text";
parent.Controls.Add(icon);

You can see that your property isn't set until after the constructor has run.  So, at the point when you call PrepareIcon, the Text really is null.
Other advice: as Henk says, you really shouldn't be calling Dispose() at this point in your code.  You also shouldn't be showing a message box from a constructor, though hopefully that's just there for your testing purposes.  Finally, because you're calling PrepareIcon from the constructor, .Click will always be null.


Q:

How to define a function in Rust?

I decided to do 2D vector cross product in Rust. In JavaScript, this is simple to do:
float CrossProduct( const Vec2& a, const Vec2& b ) {
    return a.x * b.y - a.y * b.x;
}

I tried to convert it to the Rust system:
// Just created two separate variables for the two different vectors

let vec1 = vec![1.15, 7.0];
let vec2 = vec![7.0, 2.0];
let cross_product(&vec1, &vec2) = vec1[0] * vec2[1] - vec1[1] * vec2[0];
println!("{}", cross_product);

// I also tried return.
let vec1 = vec![1.15, 7.0];
let vec2 = vec![7.0, 2.0];
let cross_product(&vec1, &vec2) {
    return (vec1[0] * vec2[1] - vec1[1] * vec2[0]);
}
println!("{}", cross_product);

I thought that one of these would work, however this was more of a reality check to me how different Rust can be from any language I have used previously.
I found a very inefficient way to work around this, however I would rather learn to do this correctly. I am new to Rust, so please take my attempts with a grain of salt.

A:

There are two possible ways to do this.
First Way
You can declare a function and pass it into println!() which is similar to many programming languages like Java,C# etc.
//Declare the function
fn cross_product(slice1: &[i32], slice2: &[i32]) -> i32 {
    slice1[0] * slice2[1] - slice1[1] * slice2[2]
}

//Use it Like following
fn main() {
    let vec1 = vec![1, 2, 3];
    let vec2 = vec![4, 5, 6];

    println!("{}", cross_product(&vec1[..], &vec2[..]));
}

Second Way
You can declare a closure and pass it into println!(), a common methodology in functional programming:
// You can declare a closure and use it as function in the same code block
fn main() {
    let vec1 = vec![1, 2, 3];
    let vec2 = vec![4, 5, 6];

    let cross_product = |slice1: &[i32], slice2: &[i32]| -> i32 {
        let result = slice1[0] * slice2[1] - slice1[1] * slice2[2];
        result
    };

    println!("{}", cross_product(&vec1[..], &vec2[..]));
}

Please note that I have created the vectors and closures using the i32 data type, which corresponds to an integer. You can change the type with f32 or if you want wider float range f64.


Q:

Need initial N characters of column in Postgres where N is unknown

I have one column in my table in Postgres let's say employeeId. We do some modification based on the employee type and store it in DB. Basically, we append strings from these 4 strings ('ACR','AC','DCR','DC'). Now we can have any combination of these 4 strings appended after employeeId. For example, EMPIDACRDC, EMPIDDCDCRAC etc. These are valid combinations. I need to retrieve EMPID from this. EMPID length is not fixed. The column is of varying length type. How can this be done in Postgres?
Thanks in advanced. :)

A:

I am not entirely sure I understand the question, but regexp_replace() seems to do the trick:
with sample (employeeid) as (
  values
  ('1ACR'),
  ('2ACRDCR'),
  ('100DCRAC')
)
select employeeid,
       regexp_replace(employeeid, 'ACR|AC|DCR|DC.*$', '', 'gi') as clean_id
from sample

returns:
employeeid | clean_id
-----------+---------
1ACR       | 1
2ACRDCR    | 2
100DCRAC   | 100

The regular expression says "any character after any of those string up to the end of the string" - and that is then replace with nothing. This however won't work if the actual empid contains any of those codes that are appended.

It would be much cleaner to store this information in two columns. One for the empid and one for those "codes"


Q:

Customize word definition in Vim?

How can I customize word definition in Vim? The default is a series of character like _,[a-zA-Z] are considered as word. I'd like to add some other chars to this definition.

A:

You can redefine the iskeyword setting.
Read the VIM docs for it or see this woss article for an example.


Q:

Is there any way that I can alter this SQL query so that it doesn't return any results containing whitespace?

I have a SQL query that I use for a search function (shown below)
SELECT t.op_id, t.op_desc FROM operator
WHERE UPPER(t.op_id) LIKE UPPER(?);

when my web page first loads, it simply returns every operator in the table.
There a few entries in the database for which the operator id (t.op_id) contains some white space "Operator A". Is there any way that I can alter this query so that results that contain white space in the operator name are excluded?

A:

To ignore white spaces, you can try
WHERE NOT LIKE '% %'

This will perform the same as INSTR.


Q:

Landships in an Ice World

Imagine a landship that can travel on a mostly frozen icy world.
How big can it be while being capable of traveling and being self sustaining?
It should be able to;

travel great distances
be self sufficient
fairly armed so it can be protected
accommodate a large population

Any ideas on such a landship that is feasible?

A:

The size of your land-ship is based on one thing: the thickness and strength of the ice. That's the consideration made in situations where the weather gets cold and people want to take vehicles on the ice, either for recreation or for business. For an introduction to that topic (which is a side discussion of your basic question), see http://lakeice.squarespace.com/bearing-strength/.
Now, as for the vehicles, you DO NOT want your people living in the vehicles. Commuting is fine, but a traveling community cannot be as economically productive as a stationary community. We've seen this with every culture that has gone from a migratory lifestyle to a sedentary lifestyle, such as the Mongols, any number of First Nations in the Americas, and (to a lesser extent) the Roma in Europe and the Americas. Yes, I know it CAN be done, in theory, but that doesn't mean that it SHOULD be done. Having a sedentary population will make it much easier for the populace to support itself economically, and that's going to be VERY important on an ice world.
Additionally, if you did have a migratory populace, they need smaller, single-family vehicles, rather than massive population vehicles that house the entire populace. Frankly, people fight, have social conflicts, get kicked out of the community, start feuds ... any number of social problems that are usually solved by people separating from one group and joining a different one. So instead of massive traveling cities, you would have a convoy of ice-vardos. (see https://en.wikipedia.org/wiki/Vardo_(Romani_wagon))
OK, with all that being said, there are several questions that will shape your vehicle design.

Do your vehicles travel on fixed routes? If so, you need some form of track or road-bed. Tracks are better for low-frequency, high-weight traffic (like trains), roads are better for high-frequency, low-weight traffic (like cars and trucks). In this case, the vehicles will be designed to travel on the fix route.
Do your vehicles travel over smooth ice? For the most part, unless you are positing a very cold world with little or no atmosphere (like an Earth-sized Pluto), you might look at sleds or skids for your non-motive support, and wheels or tracks for motive support.
Do your vehicles have to deal with inclement weather, over and above the cold? In this case, higher-traction and more powerful motors will be needed.
Does your planet have a survivable atmosphere? If not, you're going to have to look at the precautions and safety equipment the vehicles will need. Antarctica and Pluto may look similar on the surface, but the need for pressurized cabins will make for significant engineering challenges.

With those questions answered, I might be able to whip up my concept of a terrific ice vehicle--but my concept will not be your concept. So think about the questions I've asked. Think about questions I've not asked--because I haven't even begun to cover the possibilities. See what you can come up with--or if anything above is not clear, leave a comment and I'll do my best to clarify.


Q:

Double Free Under ARC

I am using ARC in my application and getting a new crash with this reason :
malloc: *** error for object 0x17e9a5d0: double free
*** set a breakpoint in malloc_error_break to debug

To figure it out , I enabled Zombie Objects , and the reason :
*** -[CFString release]: message sent to deallocated instance 0x15d183e0

My code :
Class myClass = NSClassFromString(classString);
SEL mySelector =  NSSelectorFromString(selectorString);
NSString *arg = @"arg";

NSMethodSignature *sig = [myClass methodSignatureForSelector:mySelector];
NSInvocation * myInvocation = [NSInvocation invocationWithMethodSignature:sig];

[myInvocation setTarget: myClass];
[myInvocation setSelector: mySelector];
[myInvocation setArgument:&arg atIndex:2];

NSString *result = nil;
[myInvocation retainArguments];
[myInvocation invoke];
[myInvocation getReturnValue: &result];

NSLog(@" Result String : %@ ",result);

What's gone wrong ? Which CFString ??
Thank you for any replies.
EDIT:
The object NSString *result caused . How to correct this error in the next step?

A:

result is not being retained when passed back by the invocation.
Try
CFStringRef result;
[myInvocation retainArguments];
[myInvocation invoke];
[myInvocation getReturnValue:&result];
if (result)
    CFRetain(result);

NSLog(@" Result String : %@ ", (__bridge NSString *)result);


Q:

How can I pass an empty string into triple quoted f-string in Python?

Here is a function using a triple quoted f-string with lots of sub-elements:
def pass_empty_string(param):
    from lxml import etree
    xml = etree.XML(f'''
    <root>
        <child>text</child>
        <child>{param}</child>
        ...
    </root>''')
    return xml

Is it possible to get an empty </child> element when param is getting None or '' value?

A:

You can accomplish this with or:
f"<child>{param or ''}</child>"

Anything in the braces is evaluated as an expression, so...
>>> param = None
>>> f"<child>{param or ''}</child>"
'<child></child>'
>>> param = ''
>>> f"<child>{param or ''}</child>"
'<child></child>'
>>> param = "some valid child"
>>> f"<child>{param or ''}</child>"
'<child>some valid child</child>'

Both '' and None are falsy values, so it will fall back to the RHS of the or, which will be just an empty string.