text:
Q: TexMaker: Greek acute next to letter instead of above I'm writing a document in Greek language.
My problem is that the editor sometimes displays the greek acute next to the letter instead of above. This occurs when I change the language to English in my keyboard and then back to Greek but not always.
Example given for the right acute position
Οι προτάσεις που ικανοποιούνται από την $I$ είναι οι
$\phi_1,\phi_2,\phi_3$.

Now if I change the language to English and write something and then try to rewrite the same sentence as above
Οι προτ´ασεις που ικανοποιο´υνται απ´ο την $I$ ε´ιναι οι
$\phi_1,\phi_2,\phi_3$.

If I compile the two sentences the result is the same but it is really annoying having this kind of code. The problem is solved if I restart TexMaker but usually reoccurs within minutes.
I'm using TexMaker in Debian 8.
Edit: MWE after request
\documentclass[12pt]{article}
\usepackage[english,greek]{babel}
\usepackage[utf8x]{inputenc}
\usepackage{enumitem}
\usepackage{ulem}
\usepackage{graphicx}
\graphicspath{ {images/} }

\title{Τεχνητή Νοημοσύνη}
\author{Εργασία 4\\ }
\date{}
\begin{document}
\maketitle
\begin{enumerate}[label={\arabic*.}]

\item
Χρησιμοποιώ τον όρο \textlatin{grufallo} για να
περιγράψω τον  \textlatin{grufallo} της
εικόνας και την λέξη \textlatin{littlemouse}
για να περιγράψω τον ποντίκι της εικόνας.
\begin{enumerate}[label={\roman*.}]
\item
Θα ορίσω μια ερμηνεία $I$ με βάση την οποία το λεξιλόγιο
των παρακάτω προτάσεων περιγράφει
με ακρίβεια τον κόσμο της εικόνας.\\
\item Οι προτάσεις που ικανοποιούνται από την $I$ είναι οι
$\phi_1,\phi_2,\phi_3$.
\end{enumerate}
\end{enumerate}
\end{document}

A: I can only reproduce the issue if I input the accented letter into two different ways:
\documentclass[12pt]{article}
\usepackage[english,greek]{babel}
\usepackage[utf8x]{inputenc}

\begin{document}

\textlatin{precomposed}: ώ

\textlatin{combining}: ώ

\end{document}

In the first case I typed directly ώ (U+03CE), in the second case I typed ω (U+03C9) followed by U+0301 (COMBINING ACUTE ACCENT). This site apparently does input normalization, so if you copy the second instance of ώ you get U+03CE).
However, utf8x and ucs raise an error message:
! Package ucs Error: Please activate option 'combine'.

See the ucs package documentation for explanation.
Type  H <return>  for immediate help.
 ...

l.9 \textlatin{combining}: ώ

Unfortunately, adding \usepackage[combine]{ucs} produces wrong output nonetheless (even worse).
Ensure you only use precomposed glyphs, never combining accents.
Also, it's better not using utf8x. With \usepackage[utf8]{inputenc} I get
! Package inputenc Error: Unicode char ́ (U+301)
(inputenc)                not set up for use with LaTeX.

See the inputenc package documentation for explanation.
Type  H <return>  for immediate help.
 ...

l.9 \textlatin{combining}: ώ

which informs you where finding the combining character, so to be able to fix it.


text:
Q: C# SerialPort DataReceived Event not updating main UI I'm presently working on a burglar alarm solution having coded it entirely in c#. The program talks to a USB serial port based based IO board which has the alarm sensors hardwired into it. I'm having an issue whereby the DataReceived event is not able to update the main UI unless I call a sub called TextLog (see end) from within the DataReceived event. Oddly enough, the DataReceived event from querying Zone 1 is able to update the main UI but not Zone 2 or 3. Additionally, if I insert a break point at the line where the Serial Port write is performed, it works as expected.
Worth mentioning these global variables:
string ioCardRxString = "";

bool[] arrGlobalZoneStatus = new bool[4];

Open the serial port by reading settings from the Settings file (all works well).
private void OpenIOComPort()
    {
        bool error = false;

        else
        {
            // Set the port's settings
            spIOCard.PortName = Settings1.Default.ioComPort;
            spIOCard.BaudRate = int.Parse(Settings1.Default.ioBaudRate);
            spIOCard.DataBits = int.Parse(Settings1.Default.ioDataBits);
            spIOCard.StopBits = (System.IO.Ports.StopBits)Enum.Parse(typeof(System.IO.Ports.StopBits), Settings1.Default.ioStopBits);
            spIOCard.Parity = (System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity), Settings1.Default.ioParity);
            spIOCard.Handshake = (System.IO.Ports.Handshake)Enum.Parse(typeof(System.IO.Ports.Handshake), Settings1.Default.ioHandshake);

            try
            {
                // Open the port
                spIOCard.Open();
            }
            catch (UnauthorizedAccessException) { error = true; }
            catch (System.IO.IOException) { error = true; }
            catch (ArgumentException) { error = true; }

            //On error, advise the user
            if (error)
            {
                MessageBox.Show("Could not open the I/O Board COM port.");
                globalIOCardError = true;
            }

            if (!error)
            {
                globalIOCardError = false;
                // Do Nothing
            }

        }
    }

A timer runs every 500ms, it writes 3 commands to the serial port, each separated by 25ms (hardware limitation). These commands query the IO board in order to determine the status of each alarm sensor.
private void tmrAuditSensors_Tick(object sender, EventArgs e)
    {
        try
        {
            if (globalIOCardError == false && Settings1.Default.disableSensorAudit == false)
            {
                if (Settings1.Default.zone1Armed == true)
                {
                    spIOCard.Write("~in01~");
                    System.Threading.Thread.Sleep(25);;
                }

                if (Settings1.Default.zone2Armed == true)
                {
                    spIOCard.Write("~in02~");
                    System.Threading.Thread.Sleep(25);;
                }

                if (Settings1.Default.zone3Armed == true)
                {
                    spIOCard.Write("~in03~");
                    System.Threading.Thread.Sleep(25);;
                }

                //Applicable results will appear on serial data received event
            }
        }
        catch
        {
            textLog("There was a problem writing to the serial port, check and restart app");
            emergencyHalt();
        }
    }

The Serial Port DataReceived event reads the returned string and writes to a global array of booleans. True if that zone is open (=1), and False if it is closed (=0). NOTE: the starred line.
private void spIO_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        ioCardRxString = spIOCard.ReadExisting();
        textLog(ioCardRxString); //*Cannot make it work without this

        if (ioCardRxString.Contains("in05=1") == true)
        {
            arrGlobalZoneStatus[1] = true;
        }

        if (ioCardRxString.Contains("in05=0") == true)
        {
            arrGlobalZoneStatus[1] = false;
        }

        if (ioCardRxString.Contains("in01=1") == true)
        {
            arrGlobalZoneStatus[2] = true;
        }

        if (ioCardRxString.Contains("in01=0") == true)
        {
            arrGlobalZoneStatus[2] = false;
        }

        if (ioCardRxString.Contains("in17=1") == true)
        {
            arrGlobalZoneStatus[3] = true;
        }

        if (ioCardRxString.Contains("in17=0") == true)
        {
            arrGlobalZoneStatus[3] = false;
        }

    }

Separately, another timer periodically (every 250ms) checks the contents of each array member and then accordingly updates the main UI with some colour changing and text updates.
 private void tmrCheckZoneStatus_Tick(object sender, EventArgs e)
    {
        if (arrGlobalZoneStatus[1] == true)
        {
            button10.BackColor = System.Drawing.Color.Red;
            textLog(button10.Text + " was activated");

            if (globalFullAlarmSet || globalNightAlarmSet || globalDoorsAlarmSet)
            {
                this.BeginInvoke(new EventHandler(delegate { checkAndActivateRelays(1); }));
            }
        }

        if (arrGlobalZoneStatus[1] == false)
        {
            button10.BackColor = System.Drawing.Color.Gray;
        }

        if (arrGlobalZoneStatus[2] == true)
        {
            button11.BackColor = System.Drawing.Color.Red;
            textLog(button11.Text + " was activated"); ;

            if (globalFullAlarmSet || globalNightAlarmSet || globalDoorsAlarmSet)
            {
                this.BeginInvoke(new EventHandler(delegate { checkAndActivateRelays(2); }));
            }
        }

        if (arrGlobalZoneStatus[2] == false)
        {
            button11.BackColor = System.Drawing.Color.Gray;
        }

        if (arrGlobalZoneStatus[3] == true)
        {
            button12.BackColor = System.Drawing.Color.Red;
            textLog(button12.Text + " was activated");

            if (globalFullAlarmSet || globalNightAlarmSet || globalDoorsAlarmSet)
            {
                this.BeginInvoke(new EventHandler(delegate { checkAndActivateRelays(3); }));
            }
        }

        if (arrGlobalZoneStatus[3] == false)
        {
            button12.BackColor = System.Drawing.Color.Gray;
        }

    }

textLog sub:
public void textLog(string logEntry)
    {
        textLines++;
        try
        {
            if (this.txtLog.InvokeRequired)
            {
                ChangeTextCallback MethodCallback = new ChangeTextCallback(textLog);
                this.Invoke(MethodCallback, new object[] { logEntry });
            }
            else
            {
                if (!logEntry.Contains("?"))
                {
                    txtLog.Text = txtLog.Text + DateTime.Now + " >: " + logEntry + "\r\n";
                    txtLog.SelectionStart = txtLog.Text.Length;
                    txtLog.ScrollToCaret();

                    if (textLines > 3000)
                    {
                        txtLog.Clear();
                        textLines = 0;
                        textLog("Text log cleared");
                    }

                    System.IO.StreamWriter sw = new System.IO.StreamWriter(logFile, true);
                    try
                    {
                        sw.WriteLine(DateTime.Now + " >: " + logEntry);
                    }
                    catch (Exception ex)
                    {
                        //
                    }

                    sw.Close();
                }
            }
        }
        catch
        {
            //
        }

    }

I guess I need to incorporate invoke/delegate somewhere but as a noob I'm kind of scratching my head. Your help would be appreciated.
Thanks

A: I didn't read throuh everything, but this should get you going on the right path:
The SerialPort.DataReceived event is raised on a separate thread.  If you need to asynchronously handle the receipt of data, and do something with the GUI on it, you would do something like this:
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) {
    var port = (SerialPort)sender;
    string data = port.ReadExisting();

    UpdateGui(data);
}

private void UpdateGui(string data) {
    if (this.InvokeRequired) {
        this.Invoke(new Action( d => UpdateGui(d) ));
        return;
    }

    this.txtBox1.Text = data;
}

Now, that said.... Do you really want to be using DataReceived?  It sounds like you (the host computer) is initiating all communication with the external board.  If that is the case, then I recommend you use Synchronous (blocking) reads instead:
1. Write the request out the port
2. Call read() with the expected number of bytes
3. Process the reply.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does my SQL script select too many outputs (CS50 pset7 sql.13)? I am currently working on pset7 in cs50, and I thought I had selected the correct number of values specified, but my script is outputting 349 rows instead of the 176 the answer key has.
"In 13.sql, write a SQL query to list the names of all people who starred in a movie in which Kevin Bacon also starred.
Your query should output a table with a single column for the name of each person.
There may be multiple people named Kevin Bacon in the database. Be sure to only select the Kevin Bacon born in 1958.
Kevin Bacon himself should not be included in the resulting list."
CS50 pset7 sql.13
sqlite> .schema
CREATE TABLE movies (
                    id INTEGER,
                    title TEXT NOT NULL,
                    year NUMERIC,
                    PRIMARY KEY(id)
                );
CREATE TABLE stars (
                movie_id INTEGER NOT NULL,
                person_id INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id),
                FOREIGN KEY(person_id) REFERENCES people(id)
            );
CREATE TABLE directors (
                movie_id INTEGER NOT NULL,
                person_id INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id),
                FOREIGN KEY(person_id) REFERENCES people(id)
            );
CREATE TABLE ratings (
                movie_id INTEGER NOT NULL,
                rating REAL NOT NULL,
                votes INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id)
            );
CREATE TABLE people (
                id INTEGER,
                name TEXT NOT NULL,
                birth NUMERIC,
                PRIMARY KEY(id)
            );

MY SCRIPT
SELECT DISTINCT name

FROM
    people
    INNER JOIN  stars ON people.id = stars.person_id
    INNER JOIN movies ON movies.id = stars.movie_id

WHERE movies.title IN (

SELECT
    title

From
    movies
    INNER JOIN stars ON movies.id = stars.movie_id
    INNER JOIN people ON stars.person_id= people.id

WHERE
    people.name = "Kevin Bacon"
    AND
    people.birth = "1958"
    )

EXCEPT SELECT name FROM people WHERE people.name = "Kevin Bacon"

Are there some logical errors in this script? My logic was:

*

*Select all movies Kevin Bacon stars in (nested SELECT)

*Select names of stars (main SELECT) who appear in any of these Kevin Bacon movies, except Kevin Bacon himself.

A: Something like this would work in postgres. May need to adapt to your database.
    select name
    from (
        with kb_movies as
            (select distinct movies.id as kb_movie_id
            from movies
            join stars
                on stars.movie_id = movies.id
            join people
                on people.id = stars.people_id
            where people.name = 'Kevin Bacon'
            and people.birth = '1958' --or 1958
            )
            select distinct people.name
            from people
            join stars
                on stars.people_id = people.id
            join movies
                on movies.id = stars.movie_id
            join kb_movies
                on kb_movie_id = movies.id
        )z
    where name <> 'Kevin Bacon'


text:
Q: Replace text after nth comma with null I have a file with hundreds of SQL insert statements like
INSERT INTO dbname.dbo.tbl1(col1, col2, col3,...., coln,...) VALUES (val1, val2, val3,....,valn,....)

I need to replace the "valn" with "null" in all the insert statements.
Note: "valn" occurs after the (n-1)th comma.
How can i achieve this in perl?

A: perl -i.bak -pe's/,[^,]+,([^)]+)\)/,NULL,$1)/g' your.sql

A: If you have data that may contain quoted commas, a simple regex will not be enough. You may try and come up with another solution, but the best way may be to use a CSV module such as Text::CSV_XS for that part of your string.
There are a lot of options and functionality to the Text::CSV_XS module, and it can be a little invasive, but it can probably be tweaked to work with your data. Try something along these lines. Be sure to keep backups.
Usage: script.pl input.txt > output.txt
Code:
use strict;
use warnings;
use Text::CSV_XS;

while (<>) {
    my $csv = Text::CSV_XS->new ({
        binary => 1,
        keep_meta_info => 1,
        allow_whitespace => 1,
    });
    my ($pre, $str, $post) = /^(.* VALUES *\()([^)]+)(\).*)$/;
    $csv->parse($str);
    my @cols = $csv->fields();
    my $n = 4;   # The N-th field
    splice @cols, $n, 1, "null";
    $csv->combine(@cols);
    print $pre, $csv->string(), $post;
}


text:
Q: Understanding getStyleClass().add() and a few lines of code A few days ago I managed to create a custom button with JavaFX by creating a simple button and modifying it's style using the setStyle() method with String objects (whose values vary depending on if the button was clicked or not) as parameters.
I didn't know how to convert that customized button into a class that I can import each time that I want to use it, so I've been researching and I found this project, which includes several JavaFX controllers customized with Material Design. The controller in which I'm interested right now is MaterialButton, whose source code is the following:
import com.sun.javafx.scene.control.skin.ButtonSkin;

import javafx.animation.Animation;
import javafx.animation.FadeTransition;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.ParallelTransition;
import javafx.animation.SequentialTransition;
import javafx.animation.Timeline;
import javafx.animation.Transition;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.scene.control.Button;
import javafx.scene.control.Skin;
import javafx.scene.control.SkinBase;
import javafx.scene.effect.BlurType;
import javafx.scene.effect.DropShadow;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.util.Duration;

@SuppressWarnings("restriction")
public class CustomButton extends Button {

    private static final Duration RIPPLE_DURATION = Duration.millis(250); // Duration of the ripple effect
    private static final Duration SHADOW_DURATION = Duration.millis(350); // Duration of the shadow effect
    private static final Color RIPPLE_COLOR = Color.web("#FFF", 0.3); // Ripple color

    public CustomButton() { // Except from the setPrefHeifht() method, everything between this braces seems useless.
                            // Probably I'm wrong, but why would you want to do this?
        textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
            if (!oldValue.endsWith(newValue.toUpperCase())) {
                textProperty().set(newValue.toUpperCase());
            }
        });
        setPrefHeight(36); // Height of the button
    }

    @Override
    public Skin<?> createDefaultSkin() { // Overrides the default skin of the button.
        ButtonSkin buttonSkin = (ButtonSkin) getSkin();
        if (buttonSkin == null) {
            buttonSkin = new ButtonSkin(this);
            Circle circleRipple = new Circle(0.1, RIPPLE_COLOR); // Creates the circle that must appear when the
                                                                 // ripple effect animation is displayed.
            buttonSkin.getChildren().add(0, circleRipple); // Adds the nodes to the screen.
            setSkin(buttonSkin);

            createRippleEffect(circleRipple); // Creates the ripple effect animation.
            getStyleClass().add("ripple-button"); // I don't know what this line does, but if it is
                                                   // removed, the button is narrowed.
        }
        return buttonSkin;
    }

    public ButtonSkin getButtonSkin() { // Returns the skin casted to a ButtonSkin.
        return (ButtonSkin) getSkin();
    }

    public void setFlated(boolean flated) { // The button is "flated" when it's pressed, so I guess that this is the same that saying "clicked".
        if (flated) {
            getStyleClass().add("flat"); // I don't know what this does.
        } else {
            getStyleClass().remove("flat"); // I don't know what does this do, either.
        }
    }

    public boolean getFlated() {
        return getStyleClass().indexOf("flat") != -1; // If the style class doesn't contain "flat", it returns false.
    }

    public void toggled(boolean toggled) { // For as far as I know, a toggle is the switch from one effect to another.
        if (toggled) {
            getStyleClass().add("toggle"); // I know as much about this line as I know about the other "getStyleClass()" lines.
        } else {
            getStyleClass().remove("toggle"); // I know as much about this line as I know about the other "getStyleClass()" lines.
        }
    }

    public boolean getToggled() {
        return getStyleClass().indexOf("toggle") != -1; // If the style class doesn't contain "toggle". it returns false.
    }

    private void createRippleEffect(Circle circleRipple) { // Defines the ripple effect animation.
        Rectangle rippleClip = new Rectangle(); // Creates a new Rectangle
        rippleClip.widthProperty().bind(widthProperty()); // For as far as I understand, it binds the width property of the
                                                          // rippleClip to itself. Why would you do that?

        rippleClip.heightProperty().bind(heightProperty()); // For as far as I understand, it binds the width property of the
                                                            // rippleClip to itself. Why would you do that?

        circleRipple.setClip(rippleClip); // For as far as I know, clipping is the process that consists
                                          // in hiding everything that is outside of a specified area.
                                          // What this does is specifying that area so that the parts of the circle
                                          // that are outside of the rectangle, can be hided.
        circleRipple.setOpacity(0.0); // Sets the circle's opacity to 0.

        /*Fade Transition*/
        FadeTransition fadeTransition = new FadeTransition(RIPPLE_DURATION, circleRipple); // Creates the fadeTransition.
        fadeTransition.setInterpolator(Interpolator.EASE_OUT);
        fadeTransition.setFromValue(1.0);
        fadeTransition.setToValue(0.0);

        /*ScaleTransition*/
        final Timeline scaleRippleTimeline = new Timeline(); // Creates the scaleRippleTimeLine Timeline.
        DoubleBinding circleRippleRadius = new DoubleBinding() { // Binds the radius of the circle to a double value.
            {
                bind(heightProperty(), widthProperty());
            }

            @Override
            protected double computeValue() {
                return Math.max(heightProperty().get(), widthProperty().get() * 0.45); // Returns the greater of both.
            }
        };

        // The below line adds a listener to circleRippleRadius.
        circleRippleRadius.addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
            KeyValue scaleValue = new KeyValue(circleRipple.radiusProperty(), newValue, Interpolator.EASE_OUT);
            KeyFrame scaleFrame = new KeyFrame(RIPPLE_DURATION, scaleValue);
            scaleRippleTimeline.getKeyFrames().add(scaleFrame);
        });
        /*ShadowTransition*/
        Animation animation = new Transition() { // Creates and defines the animation Transition.
            {
                setCycleDuration(SHADOW_DURATION); // Sets the duration of "animation".
                setInterpolator(Interpolator.EASE_OUT); // It sets the EASE_OUT interpolator,
                                                        // so that the shadow isn't displayed forever and its an animation.
            }

            @Override
            protected void interpolate(double frac) {
                setEffect(new DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, 0.30), 5 + (10 * frac), 0.10 + ((3 * frac) / 10), 0, 2 + (4 * frac)));
                // Creates a a DropShadow effect and then sets it to "animation".
            }
        };
        animation.setCycleCount(2);
        animation.setAutoReverse(true);

        final SequentialTransition rippleTransition = new SequentialTransition(); // Creates a SequentialTransition. The circle's scaling is the
                                                                                // first transition to occur, and then the color of the button
                                                                                // changes to the original one with fadeTransition
        rippleTransition.getChildren().addAll(
                scaleRippleTimeline,
                fadeTransition
        );

        final ParallelTransition parallelTransition = new ParallelTransition();

        getStyleClass().addListener((ListChangeListener.Change<? extends String> c) -> { // For as far as I understand, each time that the
                                                                                // Style class changes, the lines of code between the
                                                                                // braces are executed, but I still don't understand how
                                                                                // does the Style class work.
            if (c.getList().indexOf("flat") == -1 && c.getList().indexOf("toggle") == -1) {
                setMinWidth(88);
                setEffect(new DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, 0.30), 5, 0.10, 0, 2));
                parallelTransition.getChildren().addAll(rippleTransition, animation);
            } else {

                parallelTransition.getChildren().addAll(rippleTransition);
                setMinWidth(USE_COMPUTED_SIZE);
                setEffect(null);
            }
        });

        this.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> { // When the button is clicked, each object's value is assigned to the first
                                                                  // that it must have at the beginning of the animation. Then, the animation
                                                                  // starts.
            parallelTransition.stop();
            circleRipple.setOpacity(0.0);
            circleRipple.setRadius(0.1);
            circleRipple.setCenterX(event.getX());
            circleRipple.setCenterY(event.getY());
            parallelTransition.playFromStart();

        });
    }

    public void setRippleColor(Color color) {
        ((Shape) ((SkinBase) getSkin()).getChildren().get(0)).setFill(color); // I don't understand this line of code.
    }

}

As I'm pretty new to JavaFX, I see the whole GitHub project as a gold mine, since not only I have access to examples that show how to create a custom controller as a class that can be imported from another, but also it shows how to customize several other controllers too.
The problem is that there are some lines of code that I don't understand (as you'll se if you read the comments I made on the source code).
As an example, there are several times in which getStyleClass().add("something") is used.
I know how getStylesheets().add() works, but this is different; I would say that the "Style" class is different from a CSS file.
If that's the case, how does it work? For as far as I understand, the Strings used as a parameter for the getStyleClass().add() method are used for being able to determine if it is inside of the "Style" class with an if() statement later; but what exactly is this class? I haven't seend any documentation about it on the internet.
I have problems understanding the setRippleColor() method at the end of the source code, too. If somebody has an idea of how it works or what should I look up for for understanding it, I'd appreciate it.
Thanks in advance.
UPDATE: Somebody pointed out that ripple-button is part of a CSS file that can be found on the GitHub project.
I copied the MaterialButton class and pasted it in a new project, so it can't access to ripple-button by just mentioning it. Nevertheless, it turns out that if I delete this line of code, the button is narrowed. I can change "ripple-button" by anything and the result is going to be the same, but the line has to be there. Why does this happen?
UPDATE 2: I already understood what the setRippleColor(Color color) method does: basically it gets the skin of the circle and gets its children so then it can change the rectangle's color once it's casted into a Shape. It's casted into a shape because Rectangle extends Shape. It's pretty simple actually.

A: There are some issues that might shed some light on your confusion.
First the things are not called 'controllers' but 'controls', this just for clarity as it might be easily confused.
The method getStyleSheets() returns an ObservableList of type String. This list contains the various path to the .css files defining the style of the application. Styles are added either on a Scene or a Control of type Parent. For more details check the linked JavaDoc or these articles:

*

*http://docs.oracle.com/javafx/2/css_tutorial/jfxpub-css_tutorial.htm

*https://blog.idrsolutions.com/2014/04/use-external-css-files-javafx/
The style sheets define the style of the controls. They also provide some additional style classes that can be set on any Node through getStyleClass(), which also returns an ObservableList of type String, this time defining the style class names. When rendering the name is looked up in the set of style sheets defined for that Node and then applied. If no such style class is found it is just ignored. A Node is the base class for any control.
The method createDefaultSkin() does not override the default skin, as you mentioned in your comment, but it defines the default skin (Well you are partially correct as CustomButton extends Button which's Skin is overriden). Generally a control is made up of a 'control' class and a 'skin' class, at least this was the case with JavaFX up till version 8, when it changed. See the article on the control architecture for full detail.


text:
Q: SQL Server unique set of columns without using a constraint - getting bit by the 900 byte limit I have a table which contains 3 nvarchar(255) columns and a combination of these 3 columns must be unique.  Normally I would create a Unique constraint, but in this case, I am hitting the 900 byte limit.  Since I have to support SQL Server 2000, I can not use Include columns to get around this situation.

A: If I understand you correctly, you could use a trigger and on the Insert or Update check to see if the combination of the values is unique prior to making the change.  You could also do the same via a stored procedure.

A: 255 seems pretty arbitrary.  With that in mind, any chance that nvarchar(150)'s would be adequate?  Or some combination that results in <= 900 bytes?

A: Was working on this in parallel, but looks like it's an extension of some other ideas already proposed... You should be able to create an indexed view using CHECKSUM to handle this.
As an example:
CREATE TABLE dbo.Test_Unique_Limit (
    string_1    NVARCHAR(255)   NOT NULL,
    string_2    NVARCHAR(255)   NOT NULL,
    string_3    NVARCHAR(255)   NOT NULL )
GO
CREATE VIEW dbo.Test_Unique_Limit_View
WITH SCHEMABINDING
AS
    SELECT string_1, string_2, string_3, CHECKSUM(string_1, string_2, string_3) AS CHKSUM
    FROM dbo.Test_Unique_Limit
GO
CREATE UNIQUE CLUSTERED INDEX Test_Unique_Limit_IDX ON dbo.Test_Unique_Limit_View (CHKSUM)
GO

I haven't used this method in production, so I can't vouch for either its performance or complete accuracy. You'll need to do your own testing there.
One thing that I will point out though... the fact that you're running into this issue should make you take a step back and consider whether or not the model itself is really as good as it should be. A unique index on the columns as you've described seems a bit odd.
Good luck!

A: I don't have access to SQL 2000 Server so I couldn't test this there, but assuming that it supports scalar functions it ought to work.  You could make it faster by adding non-unique indices on each column so that it doesn't have to do a table scan.
CREATE FUNCTION [dbo].[fn_count_rows_for_ids]
(
    @id1 nvarchar(255),
    @id2 nvarchar(255),
    @id3 nvarchar(255)
)
RETURNS int
AS
BEGIN
    DECLARE @count int

    SELECT @count = count(*) FROM tbl_test WHERE (string_1 = @id1 AND string_2 = @id2 AND string_3 = @id3)

    RETURN @count

END

CREATE TABLE [dbo].[tbl_test](
    [string_1] [nvarchar](255) NOT NULL,
    [string_2] [nvarchar](255) NOT NULL,
    [string_3] [nvarchar](255) NOT NULL
) ON [PRIMARY]

ALTER TABLE [dbo].[tbl_test]  WITH CHECK ADD  CONSTRAINT [CK_tbl_test] CHECK  (([dbo].[fn_count_rows_for_ids]([string_1],[string_2],[string_3])<=(1)))

ALTER TABLE [dbo].[tbl_test] CHECK CONSTRAINT [CK_tbl_test]

A: You could hash the 3 columns, using MD5 or SHA1, and create a unqiue constraint on the hashed value.
How easy it is to implement depends on where you INSERTs/UPDATEs come from.
If they only come from your application, then it should be relatively easy to implement.
If they come from multiple sources you can look into implementing the hash in T-SQL.  A quick Google search turned up the following implementation of MD5 in T-SQL: http://binaryworld.net/Main/CodeDetail.aspx?CodeId=3600.  On SQL2005, you can use the built-in hash function: http://msdn.microsoft.com/en-us/library/ms174415.aspx.
Note that MD5 is no longer considered "secure", though it should be sufficient for this scenario.  It runs quicker and is easier to implement than SHA1.

A: Another idea:  could you add a column that stores a hash of those values cat'd together?  SQL 2000 supports an extended stored procedure for md5 sums that you could call from a trigger to create the hash.


text:
Q: How can I build Google App Enging Java SDK? I have downloaded the source code of Google App Engine and I would like to change the behavior of some methods (for example, DatastoreService.put(Entity e)) used in this example:
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import static com.google.appengine.api.datastore.FetchOptions.Builder.withLimit;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

public class LocalDatastoreTest {

    private final LocalServiceTestHelper helper =
        new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());

    @Before
    public void setUp() {
        helper.setUp();
    }

    @After
    public void tearDown() {
        helper.tearDown();
    }

    // run this test twice to prove we're not leaking any state across tests
    private void doTest() {
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        assertEquals(0, ds.prepare(new Query("yam")).countEntities(withLimit(10)));
        ds.put(new Entity("yam"));
        ds.put(new Entity("yam"));
        assertEquals(2, ds.prepare(new Query("yam")).countEntities(withLimit(10)));
    }

    @Test
    public void testInsert1() {
        doTest();
    }

    @Test
    public void testInsert2() {
        doTest();
    }
}

The problem is that I do not see that the build.xml file provided with the source code makes any compilation of the source .java files. For example, when I add some garbage to one of the source files and try to build the SDK using ant dist it returns BUILD SUCCESSFUL rather than a compile time error.
Any ideas where can I find the source file of the put(Entity e) method? and how can I compile the source code?

A: You cannot make any changes to App Engine SDK. SDK exposes methods that are directly related to and dependent upon the internal operations of the App Engine and its Datastore. You are not supposed to compile the SDK separately from your source code.


text:
Q: ModuleWithProviders / forRoot - use generics as type parameter for a provider I am wondering why I can't do this:
export class TopBannerModule {
  static forRoot<T>(): ModuleWithProviders {
    return {
      ngModule: TopBannerModule,
      providers: [
        { provide: AppNavigationServiceToken, useClass: T]
    };
  }
}

'T' only refers to a type, but is being used as a value here

However useClass is expecting a type.
Is this possible to utilise generics over a factory here?

A: As @edric states, we need a type parameter instead
export class TopBannerModule {
  static forRoot(typeOfAppNavigationService: typeof AppNavigationService): ModuleWithProviders {
    return {
      ngModule: TopBannerModule,
      providers: [
        { provide: AppNavigationServiceToken, useClass: typeOfAppNavigationService]
    };
  }
}


text:
Q: Batch Script to run for months with various options I want to run a batch script that runs for month. The code is below. It processes loads of videos and sends their various outputs to various folders.
The problem is if its running for a month unattended, the disk might be full. I want it to check if the disk is full and ontinue writing to another disk. It would be nice to have a log as well
`@echo off
    setlocal enabledelayedexpansion
    set EXE_FILE=E:\opencv\build\bin\Release\blobtrack_sample.exe
    set INPUT_PATH=E:\Glasgow\Test\
    set TRACKS_PATH=E:\Glasgow\Tracks\
    set OUTPUT_PATH=E:\Glasgow\Result\
    set COUNT=0
    pushd %INPUT_PATH%
    for %%f in (*) do if %%f neq %~nx0 (
        set /a COUNT+=1
        echo Processing %%f, track=%%~nf.txt, btavi=test!COUNT!%%~xf
        %EXE_FILE% fg=FG_0S bd=BD_CC bt=CCMSPF btpp=None bta=Kalman btgen=RawTracks track=%TRACKS_PATH%\%%~nf.txt FGTrainFrames=125 btavi=%OUTPUT_PATH%\%%~nf.avi %%f
    )
    popd`

A: Consider the following:
`@echo off
    set drive="E"
    set /A size=99
    FOR /F "tokens=1-5" %G IN ('dir ^| find "Dir(s)"') do set size=%I
    echo %size% > currentsize.txt
    echo %size% >> sizelog.log
    FOR /F "tokens=1-5" %G IN ('dir ^| find "currentsize.txt"') do set /A size=%J

REM SIZE LESS THAN 4 INDICATES LESS THAN 1024 Bytes left on the disk.
    IF %size% LSS 4 set drive="F"

    setlocal enabledelayedexpansion
    set EXE_FILE=%drive%:\opencv\build\bin\Release\blobtrack_sample.exe
    set INPUT_PATH=%drive%:\Glasgow\Test\
    set TRACKS_PATH=%drive%:\Glasgow\Tracks\
    set OUTPUT_PATH=%drive%:\Glasgow\Result\
    set COUNT=0
    pushd %INPUT_PATH%
    for %%f in (*) do if %%f neq %~nx0 (
        set /a COUNT+=1
        echo Processing %%f, track=%%~nf.txt, btavi=test!COUNT!%%~xf
        %EXE_FILE% fg=FG_0S bd=BD_CC bt=CCMSPF btpp=None bta=Kalman btgen=RawTracks track=%TRACKS_PATH%\%%~nf.txt FGTrainFrames=125 btavi=%OUTPUT_PATH%\%%~nf.avi %%f
    )
    popd`

A: I found this code from this answer. I advise you to read all the answers there and you will find something to work with
save the folling in a batch file and run it. It will display the free bytes of C: drive. Use the variable in an IF condition to change the target save-to drive
@setlocal enableextensions enabledelayedexpansion
@echo off
for /f "tokens=3" %%a in ('dir c:\') do (
    set bytesfree=%%a
)
set bytesfree=%bytesfree:,=%
echo %bytesfree%
endlocal && set bytesfree=%bytesfree%


text:
Q: A harmonic function Consider the vertical strip of angle $\alpha=\frac{\pi}{2}$
In this case, the harmonic function which is $0$ on the left line and $1$ on the right line is given by $$f(a+ib)=\frac{a}{T}.$$
Now, when the angle $0<\alpha <\frac{\pi}{2}$ the strip becomes bent.
My question is: can we determine explicitly the harmonic function that is $0$ on left half lines and $1$ on the right ones. My attempt gave the following function
$$f(a+ib)=\frac{a}{T}- \frac{\cos(\alpha)}{\sin(\alpha)}\frac{|b|}{T},$$
but this is not a harmonic function. Thank you for any hint.

A: Yes, it can be found explicitly, though not in elementary functions but in terms of a combination of elementary and hypergeometric functions.
The problem is (almost) equivalent to finding a conformal map
from your straight strip onto the broken strip. For this it is sufficient to find
a conformal map from the upper half-plane onto the UPPER half of the broken strip (and then apply the Schwarz Symmetry principle). This map of the upper half-plane on the upper half
of the broken strip is given by the Christoffel-Schwarz formula
$$C\int_0^z\zeta^{\beta-1}(\zeta-T)^{-\beta} d\zeta,$$
where $\alpha=\pi\beta$. This integral can be explicitly expressed in terms of
hypergeometric function. I hope these hints are enough to make an explicit computation.
In a comment you ask about dependence on $T$. Dependence on $T$ is trivial:
If $F$ is the conformal mapping corresponding to $T=1$, normalized such that
$F(0)=0,F(1)=1,F(\infty_j)=\infty_j, j=1,2$ then $TF(z/T)$ is the
map corresponding to $T$.
Remark. According to a theorem of Chebyshev, this integral is not an elementary function when $\beta$ is irrational. Therefore I suppose that the solution of
your problem is also not an elementary function.
Here are some more detail. Let $T=1$. Let $F(z)$ be the integral I wrote above. Then $C$
is determined from the boundary correspondence: $C=1/F(1)$. Now
$$G(z)=(-\cos(\pi z)+1)/2$$
maps the rectangular half-strip onto the upper half-plane, $(0,1,\infty)\mapsto (0,1,\infty)$. Therefore
$$H(z)=F(G(z))/F(1)$$
maps the upper half of the rectilinear strip on the upper half of the slanted strip (both with $T=1$). So the solution of the Dirichlet problem (with $T=1$) is
$$\Re(H^{-1}(z)).$$
Not very explicit, of course, since one has to invert the integral $F$. But OK for numerical computation.
Remark 2. The integral
$$B_x(\beta,1-\beta):=\int_0^x\zeta^{\beta-1}(1-\zeta)^{-\beta}d\zeta$$
is called the incomplete Beta-function, and there is even the standard notation
$$I_x(\beta,1-\beta):=\frac{B_x(\beta,-\beta)}{B(\beta,1-\beta)}=F(x)/F(1).$$
To obtain simple estimates, expand it to the power series:
$$B_x(\beta,1-\beta)=\beta^{-1}x^\beta+\sum_{n=1}^\infty\frac{\beta(\beta+1)\ldots(\beta+n-1)}{n!(n+\beta)}x^{n+\beta}.$$
This is sufficient to determine your function on $(0,c)$ with any desired accuracy, unless $c$ is close to $1$. Near $1$ use a similar expansion
into powers of $x-1$.
For example, near $0$, $G(x)\sim x^2/4,$ so $$H(x)\sim\frac{1}{\beta 4^{\beta}B(\beta,1-\beta)}x^{2\beta},$$
$H^{-1}(x)\sim Cx^{1/(2\beta)}.$ Also notice that the series for $B_x$ has
positive coefficients which simplifies the estimates.
To obtain a lower estimate, you need the upper estimate to $B_x(\beta,1-\beta)$. We can write it as
$$B(x):=B_x(\beta,1-\beta)=\beta^{-1}x^\beta+f(x),$$
where $f$ is increasing (because it is a power series with positive coefficients), and we also know that $B(1)=B(\beta,1-\beta),$ therefore
$f(x)<f(1)=B(\beta,1-\beta)-1/\beta$. This will give an explicit constant $C$
in the lower estimate $Cx^{(1/2\beta)}$.

A: There is also a probability formulation: For $z\in \mathbb{C}$ inside the strip let $B_t^{(z)}$ the brownian motion starting at $z$. Then we have
$$ f(z)=\mathbb{P}\big(B_t^{(z)}\text{ touch the right half lines before the left half lines} \big)$$
This kind of formula is useful to get quantitative properties of $f$. For example
$$f(a+ib)=\frac{a}{T}-\frac{\cos(\alpha)}{\sin(\alpha)}\frac{|b|}{T} + \mathcal{O}(e^{-\gamma|b|})$$
for some $\gamma>0$ because the probability that $B^{(z)}_t$ cross the axis ($b=0$) before touching the right or the left lines decays exponentially.
RELATED QUESTION : I just want to react to the remark of Alexandre Eremenko because I didn't know the theorem of Chebyschev he mention.
Do you think that one can find an explicite formula for the eigenvetors and eigenvalues of the Laplacian $\Delta$ on a parallelogram (with Dirichlet b.c.) if its angular are rational?


text:
Q: JSON Select option question? I wrote somethinh like this,
`$sql = "SELECT * FROM dbase";
    $strOptions = "";

    if (!$q=mysql_query($sql)) {
        $strOptions = "<option>There was an error connecting to database</option>";
    }
    if (mysql_num_rows($q)==0) {
        $strOptions = "<option>There are no news in database</option>";
    }else {
        $a=0;
        while ($redak=mysql_fetch_assoc($q)) {
            $a=$a+1;
            $vvvv[$a]["id"]=$redak["id"];
            $vvvv[$a]["ssss"]=$redak["ssss"];
        }
    }
    for ($i=1; $i<=$a; $i++) {
        $strOptions = $strOptions. '<option value="'. $vvvv[$i]["id"] .'">'.$i.'.) - '.strip_tags($vvvv[$i]["ssss"]).'</option>';
    }

    echo '[{ "message": "3" },{ "message": "' . count($wpdb->get_results("SELECT * FROM dbase")) . '" },{ "message": "'.$strOptions .'"}]';`

I just cannot later parse json file,later I parse it on this way to fill select-option
$jq("#select-my").children().remove();
        $jq("#select-my").append(data[2].message);

I use jquery form pluing,everything work fine,except this,I cant parse data for select-option element.I try and with json_encode in php.Can someone help please?

A: If I'm reading your PHP right, your JSON ends up looking like this:
[{ "message": "3" },{ "message": "(count_goes_here)" },{ "message": "(options_go_here)"}]

The top level of a JSON string must be an anonymous object, not array (details). So this is valid:
{"test": ["one", "two", "three"]}

but the array on its own is not:
["one", "two", "three"]

To fix it, just wrap your array in an object:
{"values": [{ "message": "3" },{ "message": "(count_goes_here)" },{ "message": "(options_go_here)"}]}

...and then when you've deserialized the JSON string, use the values property of the resulting object to access the array.


text:
Q: What does 'the Harry Potterization of pop-culture' [in Star Wars] refer to? The following commentator writes:

Suffice it to say, it's also the rebuke of the Harry Potterization of pop culture I've been looking for.

Now there is a book called Harry Potterization - which appears to be talking about creating worlds in which you can sell merchandise and spin-offs.
There is a discussion about the Harry Potterization of modern life, in which they appear to assume that Harry Potter invented the fans losing a sense of balance and proportion with a fun myth, and dressing up and going nuts about it.
There is a discussion stating the Harry Potterization of Star Wars is about how midi-chlorians involve 'being born with it' and eliminate the idea of democratic spiritual progress opportunity open to all.
The original discussion referred to it as a kind of 'small world of relationships' in which you first crush is your spouse and everyone is related. (But arguably that was always there in Star Wars).
My question is: What does 'the Harry Potterization of pop-culture' [in Star Wars] refer to?

A: His next tweet answers this. He's referring to "small universe syndrome", where every character and plot element ultimately turn out to be related to every other character and plot element in some fashion (e.g. Harry's best friend's parents turn out to be part of the same organisation that his own parents were part of, he marries his best friend's sister, his best friend's rat turns out to be a spy for his nemesis, his future wife gets taken over by his nemesis, etc etc)

The Potter stories suggest everyone's related, the person you crush on
in middle school will be your spouse – "mythic" storytelling has
rarely been so small, so juvenile, so petty. Johnson's film shuns all
of that – and Hollywood's current "plot is everything" approach.
Per Twitter

Marvel VP Justin Lambros suggested that the best way to prevent this was to "silo" different properties, giving showrunners and directors broad info about canon, but letting them generate their own characters and plotlines and their own "cool ideas" without constantly "calling back" to earlier shows and films in order to provide connection.


text:
Q: dropdown list with autocomplete/ suggestion in excel vba In a merged cell (named as SelName) I have a dropdown list with more then 100 items. Searching through the list is not efficient, as this list is constantly growing. Therefore, I would like to have a dropdown list with autocomplete/ suggestion function. One of the codes that I have is the following which I have found on extendoffice.com:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Update by Extendoffice: 2017/8/15
Dim xCombox As OLEObject
Dim xStr As String
Dim xWs As Worksheet
Dim Cancel As Boolean
Set xWs = Application.ActiveSheet

'On Error Resume Next
Set xCombox = xWs.OLEObjects("TempCombo")
With xCombox
    .ListFillRange = ""
    .LinkedCell = ""
    .Visible = False
End With
If Target.Validation.Type = 3 Then
    Target.Validation.InCellDropdown = False
    Cancel = True
    xStr = Target.Validation.Formula1
    xStr = Right(xStr, Len(xStr) - 1)
    If xStr = "" Then Exit Sub
    With xCombox
        .Visible = True
        .Left = Target.Left
        .Top = Target.Top
        .Width = Target.Width + 5
        .Height = Target.Height + 5
        .ListFillRange = xStr
        .LinkedCell = Target.Address
    End With
    xCombox.Activate
    Me.TempCombo.DropDown
End If
End Sub

 Private Sub TempCombo_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
    Case 9
        Application.ActiveCell.Offset(0, 1).Activate
    Case 13
        Application.ActiveCell.Offset(1, 0).Activate
End Select
End Sub

First, I tried to test it in an empty sheet (with just the dropdown list) and it worked well. But as soon as I try to insert this code into the other worksheet, it doesn't. Does anyone has an idea what the problem could be?
FYI: I have several drop down lists in this worksheet and all of them are in merged cells. Additionally, I have some other Private subs...

A: Why do you have to do that instead of just creating a ComboBox control and setting ListFillRange and LinkedCell without any code?
The error happens because the Range you are editing (Target) does not have any Validation. You should add the check for validation:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim vType As XlDVType
    On Error GoTo EndLine
    vType = Target.Validation.Type

    Dim xCombox As OLEObject
    Dim xStr As String
    Dim xWs As Worksheet
    Dim Cancel As Boolean
    Set xWs = Application.ActiveSheet

    'On Error Resume Next
    Set xCombox = xWs.OLEObjects("TempCombo")
    With xCombox
        .ListFillRange = ""
        .LinkedCell = ""
        .Visible = False
    End With
    If vType = 3 Then
        Target.Validation.InCellDropdown = False
        Cancel = True
        xStr = Target.Validation.Formula1
        xStr = Right(xStr, Len(xStr) - 1)
        If xStr = "" Then Exit Sub
        With xCombox
            .Visible = True
            .Left = Target.Left
            .Top = Target.Top
            .Width = Target.Width + 5
            .Height = Target.Height + 5
            .ListFillRange = xStr
            .LinkedCell = Target.Address
        End With
        xCombox.Activate
        Me.TempCombo.DropDown
    End If
EndLine:
End Sub

EDIT
If i understand the problem correctly, you want a ComboBox that auto-fills from a column and auto-updates if you type more entries in the column. There is no need for such complicated code. You can simply add a ComboBox (say ComboBox1), set its ListFillRange (e.g. to A1:A20) and do this:
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        With ComboBox1
            Dim OrigRange As Range: OrigRange = .ListFillRange
            If Not Application.Intersect(OrigRange, Target) Is Nothing Then
                .ListFillRange = .OrigRange.Resize(OrigRange.Cells(1).End(xlDown).Row - OrigRange.Row + 1)
            End If
        End With
    End Sub

A: Autocomplete Dropdowns are now native with excel O365
https://www.excel-university.com/autocomplete-for-data-validation-dropdown-lists/


text:
Q: Solve the SDE by applying Ito formula Solve the SDE
$d\delta_{t}=\mu\delta_{t}dt+\sigma\delta_{t}dW_{t}$
by applying the Ito formula and the final solution should be in the form of
$\delta_{t}=\delta_{0}\exp\left((\mu-\frac{1}{2}\sigma^{2})t+\sigma W_{t}\right)$

A: The useful form of Ito's lemma is that:
$$f(W_b,b)-f(W_a,a)=\int_a^b\partial_wf(W_t,t)dW_t+\int_a^b\left(\frac{1}{2}\partial^2_wf(W_t,t)+\partial_tf(W_t,t)\right)dt$$
which is equivalent to:
$$df=\partial_tfdt+\partial_wfdW_t+\frac{1}{2}\sigma\partial^2_wfdt$$
for a brownian motion $W_t$. You have then that $\sigma\delta_t=\partial_w\delta(W_t,t)$ and that $\mu\delta_t=\partial_t\delta(W_t,t)+\frac{1}{2}\partial^2_w\delta_t(W_t,t)$. The first equation gives $\delta(W_t,t)=C(t)\exp(\sigma W_t)$, so plugging this into the second equation and dividing by $\exp(W_t)$ gives: $\mu C(t)=C'(t)+\frac{\sigma^2}{2}C(t)$. This is again easy to solve and gives $C(t)=D\exp\left[\left(\mu-\frac{\sigma^2}{2}\right)t\right]$. Combining, we have $\delta(W_t,t)=D\exp\left((\mu-\frac{\sigma^2}{2})t+\sigma W_t\right)$. At $t=0$, $\delta(W_0,0)=\delta_0=D$, so we finally end up with:
$$\delta(W_t,t)=\delta_0\exp\left(\left(\mu-\frac{\sigma^2}{2}\right)t+\sigma W_t\right)$$


text:
Q: Can I make Sublime to display `\` as lambda? A friend who uses vim gets a very nice representation of Haskell source code. One thing I find very nice is that he gets \ displayed as λ.
Is it possible to display \ in Sublime Text 3 as λ for Haskell?
It seems as if this is possible for Sublime Text 2: https://sublime.wbond.net/packages/Lambda%20Substitution


text:
Q: SQL Query retrieving info from 3 tables which are in relationship I even don't know how to title my problem or what to search to solve it so please don't mind me if I don't describe it properly.
I have 3 tables:
Patient(id, name, ....)
Examination(id, date, patient_id*, notes)
Diagnoses(id, diagnose)
ExaminationDijagnose(id, diagnose_id*, examination_id*)
So I want to make a query where is only one input parameter and that is ExaminationID (Primary Key). The result will be one row with columns
(examination_id, date, name, diagnoses(array), notes).
The diagnoses column will be an array based on a examination_id foreign key.
So like this if examination id is 10
Diagnose:
1 - Flu
2 - High temperature
ExaminationDijagnose will be
1 , 1 , 10
1 , 2 , 10
I need output to look like this
1(ExaminationID), date, patient_name(patient_id*), Array(Flu, High Temperature), notes)
That array is concatination, so diagnose period diagnose. "Flu, High Temperature, Fracture etc...
Sorry again if I described it badly.
Thanks

A: The query would look something like the following (updated to include the array of diagnoses):
SELECT examination_id, date, name, GROUP_CONCAT(diagnose), notes
FROM Patient
INNER JOIN Examination ON Examination.patient_id = Patient.id
INNER JOIN ExaminationDiagnose ON ExaminationDiagnose.examination_id = Examination.id
INNER JOIN Diagnoses ON Diagnoses.id = ExaminationDiagnose.diagnose_id
WHERE Examination.id = ?

A: You can use JOIN with GROUP_CONCAT function to get the array of diagnoses, e.g.:
SELECT e.id, e.date, p.id, p.name, notes, GROUP_CONCAT(d.diagnose)
FROM examination e JOIN ExaminationDiagnose ed ON e.id = ed.examination_id
JOIN patient p ON e.patient_id = p.id
JOIN diagnose d ON ed.diagnose_id = d.id
WHERE e.id = ?
GROUP BY e.id, e.date, p.id, p.name, notes;

A: https://dev.mysql.com/doc/refman/5.7/en/data-types.html MySQL doesn't support Array but you can use JSON Array if required.
If you want the list of Diagnose to be part of your select query regardless of type, the following query will get you the comma (,) separated list of diagnoses. Which you can later tansform to any format you want by spliting the string by comma (,).
SELECT examination.id, examination.date, patient.name, group_concat(diagnoses.diagnose) as diagonses, examination.notes
FROM ExaminationDijagnose ed
JOIN Examination examination on examination.id = ed.examination_id
JOIN Patient patient on patient.id = examination.patient_id
JOIN Diagnoses diagnoses on diagnoses.id = ed.diagnoses_id
GROUP BY examination.id, examination.date, patient.name, examination.notes


text:
Q: Blank forms displays in MS Access I just converted my MS Access database from 2000 to 2003 format and then created an executable (.mde) file. The executable works fine, but on one form the screen is blank in form view, even though all of the contols show up in design view. What am I doing wrong?

A: Check to see if the query populating the form is returning any rows back.

A: I figured it out. I adventently turned on the filter. When I turned it off, the form displays data again.


text:
Q: correct form of struct for strings (or byte array) when importing Labview DLL into python (using ctypes) I'm trying to import a DLL (created in Labview) into python.
I've reduced it to a very simple Labview VI, a string goes into a cluster, the cluster is a function in the DLL i.e. the function is: void TestCluster(Cluster *outputCluster)
I can get everything but strings and arrays to read in from a cluster. I think I just don't have the correct Struct (?).
Has anyone done this? There's a partial guide:
http://www.ni.com/white-paper/8911/en/
It might also be due to my little knowledge of ctypes in Python too.
Sample Python code for the import:
#!/usr/bin/env python
import sys, os, string
from ctypes import *

class byteArrayStructure(Structure):
    _fields_ = [("dimSize", c_int),("bytes", c_uint8 )]

class clusterStructure(Structure):
    _fields_ = [("stringField", c_char*4 ),
                ("byteArray", byteArrayStructure )]

dll = cdll.LoadLibrary("test.dll")
libc = cdll.msvcrt

def testMain():
    retValue = 0
    try:
        clusterIn = clusterStructure()
        dll.TestCluster( byref(clusterIn) )

        print clusterIn.byteArray.bytes
        print cast(clusterIn.byteArray.bytes,c_char_p)

    except ValueError, Argument:
        retValue = "Error: " + str(ValueError) + "  " + str(Argument)
    return retValue

testMain()

edit:
structs from test.h,
typedef struct {
    int32_t dimSize;
    uint8_t elt[1];
} Uint8ArrayBase;
typedef Uint8ArrayBase **Uint8Array;
typedef struct {
    LStrHandle elt1;
    Uint8Array unsignedByteArray;
} Cluster;

void __cdecl TestCluster(Cluster *outputCluster);

MgErr __cdecl LVDLLStatus(char *errStr, int errStrLen, void *module);

/*
* Memory Allocation/Resize/Deallocation APIs for type 'Uint8Array'
*/
Uint8Array __cdecl AllocateUint8Array (int32 elmtCount);
MgErr __cdecl ResizeUint8Array (Uint8Array *hdlPtr, int32 elmtCount);
MgErr __cdecl DeAllocateUint8Array (Uint8Array *hdlPtr);

Thanks :)

A: You need to allocate and deallocate strings, arrays, and clusters because LabVIEW expects a full and complete object owned by its memory manager instead of Python's in case it needs to modify them (add/remove array elements or string characters). For example, VIKit has a LabVIEW-built library that uses strings and clusters in its entry points.

*

*Allocating a string in C

*Allocating an array of clusters
For more information, while this link is the reverse (a C DLL called from LabVIEW), the examples here include clusters, strings, and arrays: Calling C/C++ DLLs Containing Simple and Complex Datatypes from LabVIEW.


text:
Q: Spring REST Multimodule with Maven/Gradle I'm making bigger project in Spring with maven.
Currently there is one core-app and several additional services. Basically core-app can work without any of the additional apps and the additional apps can work on different hosts and port. To manage this i've created additional app in python which is able to clone, pull, start and stop those modules, or change configuration which is held in xml file. But I've heard that this is not a good idea to create whole new app just to manage those projects (like big init file on steroids) and I should do this with multimodules.
The problem is I want to be able to run this in many configuration and to add/remove module without big changes in configuration file and be able to run modules in any combination. I want to run only module 1 or only 1 and 3 and so on, i don't want to create maven build for every combination (image to add 2 modules to 5 and make all combination from scratch). I'm trying to do this with gradle too but i don't see way to run 2 spring boot apps in row with one command (because when the first one starts to run the building is stopped because spring don't want to end, because it should be running all the time an i just want to log it to file in background).
I hope I've described that problem quite good and please suggest me anything I can do or tell me whether creating additional app to do that is good or not.


text:
Q: Options for executing SQL commands in parallel Scenario
Note: I am using SQL Server 2017 Enterprise
I am looping through a list of databases and copying data to them out of one database. This database will only be accessed by the script (no other transactions will be made against it from something else). The copy includes copying straight table to table, or will have more complex, longer-running queries or stored procedures. All of this is done with SQL Server jobs calling procedures; I'm not using anything like SSIS.

Question
Instead of looping through all the databases and running the statements one at a time, I want to be able to run them in parallel. Is there an easy way to do this?
Options I've thought of:

*

*Run each data transfer as a job and then run all the jobs at once. From my understanding, they would be executed asynchronously, but I'm not 100% sure.

*Generate the SQL statements and write a script outside of SQL Server (e.g. Powershell or Python) and run all the commands in parallel

*Leverage SSIS
I prefer not to do this, since this would take too much work and I'm not very familiar with it. This may be used down the road though.

A: Use powershell...
Create a table on the central database to house instance / connection string details. (Remember to obfuscate for security)
Create another table to house the queries.
Create a third table to map Instance to Query.
In powershell create a collection / list based object. Deserialized from your data entries. The object will be made up of three properties {Source / Destination / Query}
Write a method / function to carry out the ETL based work. CONNECT TO DB, READ FROM SOURCE, WRITE TO DEST.
Iterate over the collection using Foreach-Parallel construct with your function nested within. This will initiate a new SPID based on the number of elements in the collection and pass those values into your function where the work will be carried out.


text:
Q: What is the purpose of calling the constructor of the object class in Java? Take this simple class...
public class Gen
{
    public static void main (String[] Args)
    {
        Gen genny = new Gen();
    }
}

Section 8.8.9 of the JLS states that "If a class contains no constructor declarations, then a default constructor is implicitly declared." It also says that as long as we're not in the java.lang.object class, then the "default constructor simply invokes the superclass constructor with no arguments."
So because the class Gen extends java.lang.object, we are forced to call java.lang.object's constructor through super() as part of the implicitly-created default constructor.
Likewise...
public class Gen extends Object
{
    public static void main (String[] Args)
    {
        Gen genny = new Gen();
    }

    public Gen()
    {

    }
}

Even if we explicitly declare a constructor for Gen, Section 8.8.7 of the JLS mandates that "if a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments."
So once again, Java is going above and beyond to get us to call java.lang.object's constructor through super(). But java.lang.object's constructor literally has an empty body. It doesn't do anything. A constructor has actual purpose only 1) if you write it such that it initializes a class' instance variables or 2) if it directly/indirectly calls its superclass(es)'s constructors to initialize their instance variables. java.lang.object's constructor does neither of these things because it 1) has no instance variables and 2) is the root of the inheritance hierarchy. So it's a pointless constructor. And now, in our class Gen, we are being pointlessly forced to call a pointless constructor.
Why do this? Why can't the Java people just say "right, if the class is a direct subclass of java.lang.object then we won't implicitly define a constructor and neither will we implicitly call super() if a constructor explicitly exists." Honestly, why even have a constructor for java.lang.object in the first place if it's gonna be empty?

A: First of all, it is NOT necessary to write this:
 public class Gen extends Object {

If a class doesn't explicitly have some other class as its direct superclass, then it implicitly extends Object.  There is not need to tell the compiler that.

Yes ... all classes (apart from Object) constructors will call a constructor of their superclass.  Even if the superclass is Object.
But it doesn't matter to the programmer.  As the spec says, if the constructor to be called is a no-args constructor, then you don't need an explicit super call.  The compiler injects a missing super() call for you if you don't include one.
Yes ... the Object constructor has an empty body in all Java implementations I have come across.
But I don't think that the JLS mandates that.
The JLS section on how objects are created states that the constructor will be called.
But it doesn't say that the compilers can't optimize away the call to the Object() constructor.  And that is what they do.  (The bytecode compiler is required to emit instructions for the call by JVM spec, but the JIT compiler can and will optimize it away.)
Why do they specify it in these terms?

*

*Primarily because the spec is easier to understand and the language is easier to use if there are fewer special cases in the Java syntax and semantics.
"You can't have a super() class if the superclass is Object" would be a special case.  But this complexity is not needed to make the language work, and it certainly doesn't help programmers if you force them to leave out a super() call in this context.

*In addition, the current way permits a Java implementation to have a non-empty Object() constructor, if there was a good reason for doing that.  (But I doubt that that was serious consideration when they designed Java.)

Either way, this is the way that Java has been since before Java 1.0, and they won't change it now.  The current way doesn't actually cause any problems, or add any appreciable overheads.


text:
Q: Java scanner object skipping lines? So its been awhile since I've really written anything console based for java,
I have this method, below, which should be asking me for each line, right? Instead, I get one prompt, then three.. What did I do wrong herer?
        try {

        System.out.println("Please enter the product's LONG details: ");
        product.setLongDetails(sc.next()); //set products long details

        System.out.println("Please enter the product's SHORT details: ");
        product.setShortDetails(sc.next()); //set short details

        System.out.println("Please enter the product's UPC data: ");
        product.setUpc(sc.next()); //set upc

        System.out.println("Please enter the product's stock: ");
        product.setStock(sc.nextInt());

        System.out.println("Please enter the products price. ");
        System.out.println("This MUST be entered with no dollar sign.");
        product.setPrice(sc.nextBigDecimal());

        InventoryManager.addProduct(product); //add product to database

    }

My console is outputting like this:
Please enter the product's LONG details:
Fireplace Cleaning Package
Please enter the product's SHORT details:
Please enter the product's UPC data:
Please enter the product's stock:
BUILD STOPPED (total time: 3 minutes 5 seconds)

The scanner is initialized just inside the class declaration as:
public static Scanner sc = new Scanner(System.in); //class level scanner object for reuse.

If I call sc.nextLine() between each objects set method, it prompts correctly but gets the wrong information:
Please enter the product's SHORT details:
Fire Poker

Displays the object as:
Please enter your selection:
    Fire

A: The documentation states:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

That means that when you are entering a text with spaces (Like the "Fireplace Cleaning Package" in your example) it gets split into 3 different inputs, each returned by one call of sc.next().
The solution is to adjust your delimeter pattern to newline:
sc.useDelimeter("\\r?\\n");

A: Scanner.next() takes the next complete token followed by a delimiter as described in the doumentation. Since you type in three words (the delimiter here is a space), the first three
sc.next()
will read each of those words. I think what you are looking for instead is
sc.nextLine()


text:
Q: Masked 2D array replace value operation not working in numpy I would like to replace the values of a 2D numpy array based on a mask from another array. The idea is that values in arr_b should be set to 0.8 in the locations where arr_a value equals 0.4. Both arr_a and arr_b are always going to have the same size. And for the purpose of this toy example, you can assume that arr_a has sevreral values that are 0.4. But the code is not working:
import numpy
arr_a = numpy.random.rand(20,40)
arr_b = numpy.random.rand(20,40)
arr_a[0,1] = 0.4

mask_cntr = numpy.ma.masked_not_equal(arr_a[:], 0.4)
ma_arr = numpy.ma.masked_where(mask_cntr, arr_b)
ma_arr.filled(fill_value = 0.8)

Can someone tell me how to fix this?

A: Your array definitions are wrong, as you can read in your error message.
arr_a = numpy.random.random((20,40))


text:
Q: нужно написать скрипт для замены флага и сокращенного названия языка при его выборе Всем привет!
Есть вот такой дропдаун https://prnt.sc/gbzgx3
И код:

.dropdown_lang .bdd_lang {
  background: inherit;
  border: none;
  box-shadow: none;
  padding: 4px 12px; }
  .dropdown_lang .bdd_lang:hover, .dropdown_lang .bdd_lang:focus {
    background: inherit; }
  .dropdown_lang .bdd_lang span {
    font-family: PFSquareSansPro-Regular;
    font-size: 18px;
    color: #a6aaae;
    margin-left: 9px; }
  .dropdown_lang .bdd_lang img {
    -webkit-transform: scale(1.2);
    transform: scale(1.2); }

.dropdown_lang .dropdown-menu {
  background-color: #434a54;
  text-align: center;
  border-radius: 7px;
  padding: 0;
  left: -58px;
  top: 45px;
  box-shadow: none; }
  .dropdown_lang .dropdown-menu:before {
    content: '';
    position: absolute;
    right: 20px;
    top: -20px;
    border: 10px solid transparent;
    border-bottom: 10px solid #434a54; }
  .dropdown_lang .dropdown-menu li {
    height: auto; }
    .dropdown_lang .dropdown-menu li a {
      font-family: PFSquareSansPro-Regular;
      font-size: 18px;
      color: #ffffff;
      line-height: 40px; }
      .dropdown_lang .dropdown-menu li a:hover {
        background-color: #393f48;
        background-image: none; }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

                            <button class="btn btn-default dropdown-toggle bdd_lang" type="button" id="dropdown_lang" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">

                                RU

                            </button>

Українська

Руский

English

нужно написать скрипт для замены флага и сокращенного названия языка при его выборе. Буду благодарен за помощь!


text:
Q: Как в классе инициализировать public переменную? Вопрос неоднозначный но поясню:
Имеется класс:
class Config {

    public function __construct($config = '') {
        ...
    }

}

Мне нужно в конструкторе этого класса инициализировать public переменную этого класса (которая, в свою очередь тоже будет экземпляром этого класса) т.е. в результате такого действа:
$config = new Config('custom');

Получился объект $config класса Config с такой структурой (прошу прощения за псевдоязык):
$config = Object(Config) {

    public $custom = Object(Config) {

        public function __construct($config = '') {
            ...
        }

    }

    public function __construct($config = '') {
            ...
    }

}

Хочу сделать такую вот рекурсию в конструкторе образования класса.
Пытаюсь реализовать паттерн MVC. Фреймверки не использую т.к. уже работал с таковыми и считаю полезным (в плане опыта, осмысления ООП) написать что-то на чистом PHP. В ходе написания понадобилось грузить конфиг, который разбит на несколько файлов в виде такой структуры:
application
|_config
| |_database.php
| |_session.php
|_system
| |_core.php
|_и т.д.

Файлы конфигурации представляют из себя ассоциативные массивы, т.е. так:
session.php:
$session['prefix'] = 'PP_';

Хотелось бы в любом месте программы иметь простой доступ к конфигу, т.е. так:
echo $config->session->prefix;

или так:
echo $config->session->get('prefix');

A:
Пытаюсь реализовать паттерн MVC. Фреймверки не использую т.к. уже
работал с таковыми и считаю полезным
(в плане опыта, осмысления ООП)
написать что-то на чистом PHP. В ходе
написания понадобилось грузить конфиг,
разбитый на несколько файлов в виде
такой структуры:
    application |_config | |_database.php | |_session.php
|_system |_core.php
    Файлы конфигурации представляют из себя массивы, т.е. так:
    session.php: $session['prefix'] = 'PP_';
    Хотелось бы в любом месте программы иметь простой доступ к
конфигу, т.е. так:
    $config->session->prefix или так: $config->session->get('prefix')

Для решения вашей задачи, я бы посоветовал реализовать паттерн Registry, он прекрасно впишется в вашу архитектуру.
P.S.: по ссылке, в конце обзора паттерна даже есть такая вещь:

На основе этого класса можно создать
класс Config, для хранения различных
параметров проекта.
<?php
class Config extends Regisrty
{
  // Дополнительные методы
}
?>


text:
Q: Allow Firebase collaborators access to specific nodes I have an app that uses Firebase and I have a few people that need to be able to update data in the Firebase Dashboard. Luckily, Firebase added the feature to add collaborators. But the problem is, I don't want these collaborators to have access to every node of the JSON. Is there a way that I can assign collaborators specific access to certain nodes of the data structure or no?
Any feedback would be great. Thanks!

A: Collaborators on the Firebase project/app have access to all data. There is no way to limit that.
It sounds like you are looking to add application administrator. For this you'll have to develop your own application dashboard, where you add such functionality. These application administrators are then just regular users of your app and you can use Firebase security rules to determine what data they have access to.
Very similar: Stopping accidental deletion of a firebase DB via Firebase Dashboard


text:
Q: C++: how to read **argv value and copy into a string I'm making a new app for my lab and  I must take form terminal some arguments, and I want to copy the **args value into a string, and after that I must match the args for execute some foreplay operation.
I try to build this code to copy the **argv value into string var but this is the error:
No source available for "std::string::operator=() at 0x44c1dc"

The code is this:
 int main(int argc, char **argv)
 {
     string args[argc-1];
 int j=0;
 for(int i=2; i<argc-1;i++)
 {
    j=0;
    while(argv[i][j]!='\0')
    {
        args[i]=args[i]+argv[i][j];
        j++;
    }
}
return 0;
}

A: I would propose this solution:
std::vector<std::string> args;
std::copy(argv + 1, argv + argc, std::back_inserter(args));

References:

*

*std::copy

*std::back_inserter

To explain it a little, this copies from argv[1] (I don't care about argv[0] as it's the "command" and usually irrelevant for argument handling) into the vector. We stop copying at argv[argc] which is one beyond the end of the actual arguments (which is how "end" iterators work).
std::back_inserter creates a special iterator that is used to insert ad the end of containers.

A: Fastest and shortest solution with range constructor:
std::vector<std::string> args(argv + 1,argv + argc);

A: Make things as clear as you can. (Will help those 3am debugging sessions in your laboratory).
 int main(int argc, char **argv)
 {
     std::vector<std::string> args(argc);
     for (int i = 0; i < argc; ++i){
         args[i] = argv[i];
     }

    // rest of code here.
}

Yes I know I waste args[0], but do you really care about that? The indexing is so much clearer if you do it this way, args has the same indexing conventions as argv (which all us old cats are used to), and you don't get a whole lot of edge cases when you only pass the program name.

A: There are a few mistakes in your code, which also causes the odd problems. Also you're overcomplicating things quite a bit.
Here's what I'd do, this will require one additional header, <vector>, for the STL container, but it will make things a lot easier (since you shouldn't rely on being able to create arrays with dynamic lengths (also note that your array length might be 0, if there are no arguments given!))
int main(int argc, char **argv) {
    std::vector<const std::string>> params; // This is the container that will take all arguments.

    // Iterate over all arguments provided
    //  (skipping the very first, since that's the executable itself)
    for (int i = 1; i < argc; i++)
        // Add the argument to the vector
        //  (this will construct a new std::string and add it to the end).
        params.push_back(argv[i]);

    // You're now able to access the arguments passed:
    // params.size() will return the number of arguments.
    // params[i] will return the i-th argument, starting at 0.

    return 0;
}

A:  int main(int argc, char **argv)
 {
     string args[argc];
     int j=0;
     for(int i=2; i<argc;i++)
     {
         args[i-2].assign(argv[i]);

     }
     return 0;
}

A: first, you can't use a dynamic argument in a static expression.
you must use either new to create a string array, or, better yet, use a vector (or any other container you like).
second, there is no point in copying the values one character by another. copy the entire string.
here is a sample code that will work:
#include <iostream>
#include <vector>
#include <string>
using namespace std;

typedef vector<string> svec;

int main(int argc,char **argv)
{
    svec strings;
    if(argc>1)
    {
        cout <<"arguments:"<<endl;

        for(int i=1;i<argc;i++)
        {
            strings.push_back(argv[i]);
        }
    }

    for(auto i:strings)
    {
        cout << i;
    }

    return 0;
}

D.


text:
Q: Cannot get position from Network I'm trying to get the location based on network. I've declared in the manifest

I've registered the listener and requested location updates :
 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,  listener);

The problem is that I don't receive any location updates in listener's  onLocationChanged()
 This only happens for devices with API level 8 and above Samsung Galaxy S , Google Nexus One
for pre 2.2 devices (e.g Htc Desire) works fine.
after  requesting updates from network provider I've checked if  NETWORK_PROVIDER is enabled:
 Criteria criteria =new Criteria();

 criteria.setAccuracy(Criteria.ACCURACY_FINE);

 Log.d(TAG,"best app provider:"+locationManager.getBestProvider(criteria, true));

 Log.d(TAG,"is network enabled:"+locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER));

and returned: best app provider:network
              is network enabled:true
so everything seems to be fine except no position is received by the listener.
can anyone give me hint if something changed in the api? do I have to set up something else?


text:
Q: Inner hits on doubly nested field in bool query I am using a bool query to find a query string in several fields in my document. I would like to use highlighting to show which field(s) matched to cause the return of the document. I have the below query working to tell me whether the non-nested field (the first in the should array) matched, but I can't figure out how to get the highlight for the doubly nested part.
 "query": {
    "bool": {
      "should": [
        {
          "match": {
            "name": {
              "boost": 100.0,
              "query": "queryString"
            }
          }
        },
        {
          "nested": {
            "query": {
              "nested": {
                "boost": 1.0,
                "query": {
                  "match": {
                    "nested1.nested2.name": {
                      "query": "queryString"
                    }
                  }
                },
                "path": "nested1.nested2"
              }
            },
            "path": "nested1"
          }
        }
      ]
    }
 },
 "highlight": {
    "fields": {
      "m_szTopicName": {}
    }
  }

I have tried adding an inner hits highlight at the same level as the "path": "nested1.nested2" but that doesn't seem to return anything (and I have results which aren't getting highlights on the working part, so I assume they must be matching the doubly nested query).
"inner_hits": {
    "highlight": {
        "fields": {
            "nested1.nested2.name": {}
        }
    }
}


text:
Q: Reconciling RGeo spheroid calculations with PostGIS I have a Rails/Postgresql app that uses a combination of RGeo and PostGIS, and I'd like to move more calculations in to RGeo and reduce some of the load on the database. One of the problems I'm having is doing length calculations on the spheroid instead of the sphere. From the RGeo::Geographic docs (https://www.rubydoc.info/github/rgeo/rgeo/RGeo/Geographic):

Some geographic implementations include a secondary factory  that
  represents a projection. For these implementations,  you can quickly
  transform data between lat/long coordinates  and the projected
  coordinate system, and most calculations  are done in the projected
  coordinate system. For  implementations that do not include this
  secondary projection  factory, calculations are done on the sphereoid.

There are three ways to make factories in RGeo::Geographic:

*

*RGeo::Geographic.projected_factory, which lets me include a factory for an arbitrary Proj4 projection

*RGeo::Geographic.simple_mercator_factory, which includes a factory for the SRID: 3857 projection

*RGeo::Geographic.spherical_factory, which does not include a projection factory but explicitly does calculations on a spherical Earth.

The first two of those include a projection, so according to the docs calculations are done in that projection. The last one doesn't include a projection, but is specifically done on a spherical Earth. So it's unclear how to do calculations on the spheroid.
Ultimately, the thing I'm really trying to reconcile is the results of calculating the length of a linestring in RGeo with the results from calculating the length of a geography type linestring PostGIS.
If I have the following linestring:
LINESTRING(2.3565473 48.8518338,2.3566331 48.851804,2.3580518 48.8512945,2.3580839 48.851283,2.3581316 48.8512659,2.3589446 48.8509735,2.35903847509631 48.8509397089643)

Calculating its length in PostGIS:

*

*On the sphere: select st_length(way,false) = 207.625186169259 m

*On the spheroid: select st_length(way,true) = 208.114332509536 m

Calculating it in RGeo:

*

*On the sphere: RGeo::Geographic.spherical_factory.parse_wkt(way).length = 207.85748843579324 m

*On the spheroid: ?

I understand that these differences are small, but I'd like to be consistent, at the very least for writing tests, and because I am going to be using both RGeo and PostGIS and don't want "errors" accumulating between them. The length of these linestrings is important.
Is it possible to get these values to be the same (/ do calculations on the spheroid in RGeo) or just an inevitable result of implementation differences?


text:
Q: ¿Cómo puedo saber la cantidad de ventanas minimizadas y ancladas en la barra de tarea de windows? Buenas, estoy inmerso en un proyecto donde muestro determinada información en un Panel que inserto en la parte inferior derecha de la barra de tareas de Windows. El problema es que solo deseo que se agregue a esa zona si no se ha llenado mucho la barra, para no superponerlo sobre algo que ya exista.
Esto es lo que he logrado hacer.

Lo que está marcado es el panel que cree en la barra de tareas.
He investigado un poco y me he informado que recorriendo todas las ventanas con EnumWindows y comprobando su estado puedo saber las minimizadas pero aún faltarían las que están ancladas. Agregar que lo estoy haciendo en Windows 10. Bienvenida cualquier información adicional que pueda ayudarme a terminar el proyecto. Thanks

A: Tengo entendido que las ventanas, aunque estén ancladas, siguen "enumerándose" como ventanas por EnumWindows, igual estoy equivocado pero es lo mismo si están o no ancladas, el anclaje es solo un acceso directo para abrir la ventana.
Otra cosa que debes tener en cuenta, EnumWindows solo te dará información acerca de las aplicaciones Win32 (las que funcionan también en Windows anteriores a Windows 8), las aplicaciones de la tienda no las enumera, igual te sirve mas la función 'FindWindowEx' https://msdn.microsoft.com/en-us/library/windows/desktop/ms633500(v=vs.85).aspx


text:
Q: Hibernate ManyToOne/N+1 Issue I have a persistent class that contains ManyToOne relationships with my user table for auditing purposes. In fact, all of my classes have these fields, even the User class.
public class MyClass implements Serializable {

@Fetch(value=FetchMode.SELECT)
@ManyToOne(optional=false, fetch=FetchType.LAZY)
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "CREATE_USER_ID")
public User getCreatedBy() {
    return createdBy;
}

@Fetch(value=FetchMode.SELECT)
@ManyToOne(optional=false)
@NotFound(action=NotFoundAction.IGNORE)
@JoinColumn(name="USER_ID")
public User getLastUpdatedBy() {
    return lastUpdatedBy;
}
}

Just to make this even better, some maroon made the auditing fields in most of the tables a CHAR(8), but the field in T_USER a VARCHAR2(8), meaning that a foreign key can't be created on them.
Anyhoo, a query for MyClass will kick off queries to populate the audit fields, which then in turn kicks off a query to populate the User's audit field.
I rarely need the audit fields, so I want to make them lazy. Unfortunately, I think I have alot working against me here, not least of which is a poorly designed schema.
Can anyone help me out here?
Jason

A: It seems like the @Fetch(value=FetchMode.SELECT) annotation and the @ManyToOne(optional=false, fetch=FetchType.LAZY) would be fighting against one another, have you tried removing the @Fetch(value=FetchMode.SELECT) for each entity and adding fetch=FetchType.LAZY to both of the associations?
Another reason may be that the @NotFound annotation is fighting against the optional=false annotation parameter.  One says that there can be a NULL where the other says there can't.  I believe that in a case where you can have a null value in a *toOne association, you cannot have lazy loading unless the association cannot be NULL.


text:
Q: Преобразование Map с помощью Stream API Имеется структура типа Map<String, List<MyClass>>.
Как с помощью Stream API преобразовать ее к типу Map<String, List<MyClass.getField()>>, где MyClass.getField() - некоторое поле класса MyClass?

A: Получаем лист строк из листа объектов
Преобразовываем Map<String, List<MyClass>> в Map<String, List<String>>:
class MyClass {
    String field;

    public MyClass(String field) {
        this.field = field;
    }

    public String getField() {
        return field;
    }
}

public static void main(String[] args) {
    Map<String, List<MyClass>> map = new HashMap<>();

    map.put("one", Arrays.asList(new MyClass("one1"), new MyClass("one2")));
    map.put("two", Arrays.asList(new MyClass("two1"), new MyClass("two2")));

    Map<String, List<String>> map2 = map.entrySet().stream()
        // собираем из исходной
        // карты новую карту
        .collect(Collectors.toMap(
            // ключ такой же
            k -> k.getKey(),
            // значение - из листа объектов
            // получаем лист строк
            v -> v.getValue().stream()
                // получаем значение
                // поля объекта
                .map(MyClass::getField)
                // собираем обратно в лист
                .collect(Collectors.toList())));

    System.out.println(map2); // {one=[one1, one2], two=[two1, two2]}
}

Если у нас List<Object>, то не обязательно собирать новую карту, можно преобразовать существующую, т. е. заменить значения в листе:
public static void main(String[] args) {
    Map<String, List<Object>> map = new HashMap<>();

    map.put("one", Arrays.asList(new MyClass("one1"), new MyClass("one2")));
    map.put("two", Arrays.asList(new MyClass("two1"), new MyClass("two2")));

    map.forEach((key, list) ->
        IntStream.range(0, list.size()).forEach(i ->
            // получаем значение поля объекта
            // и заменяем им сам объект
            list.set(i, ((MyClass) list.get(i)).getField())));

    System.out.println(map); // {one=[one1, one2], two=[two1, two2]}
}

A: Вот более прямолинейный и грубый вариант при помощи forEach:
public class MapToMap {
    public static void main(String[] args) {
        Map<String, List<String>> mySrc = new HashMap<>();

        List<String> list1 = new ArrayList<>();
        list1.addAll(Arrays.asList("asdf", "qwerty", "zxcvb"));
        mySrc.put("list1", list1);

        List<String> list2 = new ArrayList<>();
        list2.addAll(Arrays.asList("asdf1234", "qwer12345", "zxcv12456"));
        mySrc.put("list2", list2);

        // Создаем переменную назначения
        Map<String, List<Integer>> myDst = new HashMap<>();

        // И здесь полностью проводим разбор и сохранение
        mySrc.entrySet().stream().forEach(elem -> {
            var myKeySrc = elem.getKey();
            var myValSrc = elem.getValue();
            List<Integer> myValDst = new ArrayList();
            myValSrc.stream().forEach(i -> myValDst.add(i.length()));
            myDst.put(myKeySrc, myValDst);
        });

        for (Map.Entry<String, List<Integer>> elem : myDst.entrySet()) {
            System.out.println(elem.getKey());
            for (Integer i : elem.getValue()) {
                System.out.printf("\t%d\n", i);
            }
        }
    }
}

Вывод:
list1
    4
    6
    5
list2
    8
    9
    9


text:
Q: How do I restore the default Windows 7 "Desktop" folder? I am trying move the location of my laptop's Desktop folder from one location to another.
I had forgotten how to do this, so instead of changing the location via the Location tab in Properties I moved the files to a new location, then deleted the Desktop directory and created a new one. Then I realized I had done it wrong.
There's no option to change my new "Desktop" folder into a proper special Desktop folder so that the files show up on the desktop and treated like the desktop folder is supposed to. I think what I need to do is find a way to restore the canonical Desktop folder in explorer?

*

*Restore deleted default folders - This question recommends this post on another site, but the section on restoring the desktop links to some .zip files that I am not comfortable trying blindly.

A: Try these options:

*

*Go to C:\Users\<username> and see if a Desktop folder exists. If it does, then move it to the new location via the right-click -> Properties -> Location method.

*If you can't find your Desktop folder there, try going to shell:Desktop (from Explorer address bar or Start menu search field). If it works, move it as above.

*Check the Recycle Bin to see if the Desktop folder you deleted is still there. If it is, then restore it.

*If all above options fail, try the following:

*

*open regedit

*navigate to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

*in the right-hand pane find the entry called Desktop

*go to the folder it points to and move that to your new location

*(alternatively, edit the entry directly to point to your new location, then log out and back in for the setting to take effect)


text:
Q: possibly dangerous text input handling I've read up on SQL Injection, XSS and other security issues and am trying to figure out what to use to safeguard the company's site.
We are about to deploy a simple 'User feedback' form with a textarea so users can tell us how to improve the site to enhance their user experience.
When the user pushes 'submit' on the form, we read the textarea comments from the user, and then programmatically create a filename in that user's subfolder and save their comments to a file.  Then we add the filename and path to that user's database record.
The team is not worried about security issues here but I am.  Their thinking is "we create the filename, it is 0% based on any user input, and since we write this 'UserX comments' filename and path to the database with no direct user influence -- there is no risk."
My concern is NOT the database activity -- because they're right, the user has no role in WHAT we write to their database record since we're just creating our own filename and storing it in their db record.
My concern is the text file!
So I'm petitioning our small team to rewrite the code to use security to read then write the user's comments in the textarea to the text file.
My concern is -- since we plan to actually READ our user's feedback and open these text files to read them later on -- there might be bad stuff in the textarea that (unless we clean it) could hurt us somehow.
I'm insisting we use strip_tags() but I need to sound informed about the manner in which we sanitize the textarea input -- I'm thinking strip_tags() is the way to go here but I'm 100% new to sanitizing user input.  I looked at htmlspecialchars() but that just converts certain characters like '&' to &
and so forth.
Are there other ways to santize/make safe any text the user types into a textarea before we write it out to a file on our web server?

A: Looks like strip_tags is a good way to go. I'd also suggest writing the file outside of the webroot so that it can't be accessed by a browser.
See also: This Other Thread

A: If you're not worried about SQL injection, and it seems you're not (either because you know the SQL is sanitized or because you're saving to a text file), then the other problem is the possible XSS attack.
It's easy to ignore those, they don't affect you directly. An XSS attack is an attack that allows one to inject client-side scripts into a webpage. Your database works fine, your server files are not modified, your session files aren't modified either.
This vulnerability is completely client-side. Like I said, it doesn't affect your server. But then someone (i.e.: me) goes on your website, and all of a sudden is redirected to a Warez site while viewing a totally SFW, trusted website. You lose trust from your users. The search engines that crawl your site also mark you as possibly harmful. You lose traffic. You lose revenues. Then again, your server is perfectly fine.
You definitely need to sanitize the user input that is outputted back to the user because of this. Yes, strip_tags is a solution and so is htmlspecialchars or htmlentities.
strip_tags is a little less restrictive however, because it allows you to define some tags you'd like your users to be able to insert in their posts, like bold, links, or italic.
In conclusion, you are absolutely right on insisting on this practice. It doesn't affect you (i.e.: your company's server) directly, but it will affect you at some point if you want a trusted presence on the world wide web.
I know this may be a longer answer than others who should suggest to just strip_tags. They are absolutely right, which is why I upvoted them. Just trying to give you some "corporate" arguments there. :)

A: It depends on how you are creating a file, and what are you doing with the text after reading it.
If you are using PHP's native functions to write the file, then you should have no problem with remote code execution.
If all you do after reading it is display to a user via HTML, htmlentities(), which effectively makes HTML tags inside the text powerless while still displaying correctly to the user, should be enough.
If you are using it as a part of some query to a database, you should use that database cleaning routine before concatenating it to your SQL. (ie. mysql_real_escape_string() for MySQL, or pg_escape_string() for PostgreSQL).
You may also want to take a look at some info on the OWASP page.
Edit: I forgot to mention, you should also use ENT_QUOTES with htmlentities to prevent single quote injections.

A: simply use mysql_real_escape_string() to get rid of quotes. htmlentities() if you are worried about js files. That should be about as good as it gets there.

A: Sanitizing input only protects you from sql injection by removing certain characters. These characters, however, cannot act in a malicious manner from within a text file.  I happen to know quite a bit about malware, and trust me, you are not at risk here.
Edit:
If I somehow missed the point of this post through my rambling, do let me know so I can update my answer.

A: I have a solution that follows mainstream of your development team ideology:
Do not use any user authorization on your site, including admins. Thus, no XSS will harm you either.


text:
Q: Isometries of non-singular bilinear space over field of characteristic $\neq 2$ In the book of Geometric Algebra, Artin says (p. 108)

If $V$ is a non-singular bilinear space then any isometry $T:V\rightarrow V$ has determinant $1$ or $-1$. The map
  $$\mbox{Isom}(V)\rightarrow \{1,-1\}, \,\,\,\,\,\,T\mapsto \det(T)$$ is a homorphism. The image of this homomorphism is $\{1,-1\}$ or just  $\{1\}$ (in case there are no reflections or if the characteristic of k is 2).

Question 1. Can there be a case of non-survectivity of above map where field is of characteristic $\neq 2$ for some non-singular space?
I mean, I want to know example (if exists) of a non-singular space with all isometries of determinant $1$ but characteristic of field is not $2$.
On the page 108, perhaps, he do not considers whether bilinear form is symmetric/skew-symmetric etc; he just consider's non-singular.
Question 2. If a bilinear space $V$ is symmetric or skew symmetric over a field of characteristic $\neq 2$, then is there always an isometry with determinant $-1$?


text:
Q: Configure Fiddler2 for flash Fiddler2 does not log requests made through flash applications. It is picked up in wireshark, but wireshark does not offer the simple interface and the formatted content.
How can I configure Fiddler2 to log requests made by flash applications?