text:
Q: Do all forms of energy have the ability to do work? According to this definition of energy: it is the ability to do work. That is $F×s$.
But except for K.E. and M.E, no other energy form can do work. So why is this definition in Physics?
Lets take an object to space, it has P.E. - but without any external force, it can't be converted into other forms. But according to the definition of energy, it has its own force.

A: I think it was James Watt who famously noticed that if you boiled water in a kettle, it would lift the lid, and that this meant that heat could do work.

A: The First Law of Thermodynamics can be written:
$dE = \delta Q - \delta W$,
i.e. the change in energy is equal to the heat gained minus the work done. Work done is a function of force (and distance) only, so if your energy type cannot provide a force (e.g. chemical energy) then all transfer must be in the form of heat.
In your example, for an object to have potential energy, it must exist in some potential field in the first place: it is that field that does work on the object. There can be no potential energy without the same field also imparting a force, the latter is just the vector gradient of the former.

A: We associate energy with the ability to do work. Having heated water, say 1 litre with 90°C (with the specific for water heat capacity) we have some energy to heat a room.
How much do we have energy? This depends from the room temperature, than lower, than more energy we have. So energy is the difference between some state(s) of a subsystem to another subsystem. Take we hot water from the first floor to the second and in relation to a room in the first floor you have two states with higher energIe in relation to the subsystem room. If a fire burn up the room (it's an example only, sorry), the energy flow takes place from the room to the water. This happens because it seems to be a natural law, that all somehow connected subsystems come to thermodynamic equilibration.
So if we label something with energy we know that the could use it. And on the other side, than we declare that something contains energy we try to extract it. Best example is the nuclear fusion and fission.
After the edit of the question:
Kinetic and potential energy are not we only energies which able to do work. Heat, torsion, pressure, nuclear energy we claim to be energies. Work, done by wind, water, animals and humans (called physical work) is the expression of energy contain. Light is energy (solar cells) and so on.
If you dig deeper you cam to the point, that all energies (perhaps without nuclear energy) are bases on electromagnetic processes. The exchange of photons is the real process. Someone does not agree? Take any process and grab deep enough.

A: Every form of energy can be converted to kinetic energy as work, or already are kinetic energy themselves.

*

*Kinetic energy of another body can be transferred to do work

*Elastic potential energy can be stored in elastic objects and the objects have a tendency to regain their original shape - elastic force. That's the $F$ in your equation.

*Gravitational potential energy is in fact negative, by the equation $U_g=G\frac{Mm}{r^2}$. The equation $mgh$ is merely an approximation that is practically correct within a distance interval (mostly used near the surface of Earth). This form of energy can be used to do work and make an object fall. In your example, even when taken to space there is a minute gravitational force that will slowly accelerate your object, hence doing work.

*Chemical energy is potential energy stored in molecules or atoms. Chemical reactions can release a lot of gasses moving at high speeds, this is the kinetic energy of gas molecules. When these kinetic energy promote random, Brownian motion, it becomes thermal energy. When the kinetic energy causes all the molecules to rush at a certain direction this creates a pressure wave and hence airflow, or even shockwave. Now that is macroscopic kinetic energy no doubt.

*Electric potential energy is, like gravitational potential energy, is the an object has when it is in a field, in this case an electric field instead of a gravitational field. Electric potential energy converts into the kinetic energy of charge carriers, or electric energy. That's what happens when objects with like charges repel each other, and electric current is the flow of charge carriers, so again kinetic energy.

*Nuclear energy is like the nuclear version of chemical energy, again a form of potential energy. Nuclear reactions give rise to new matter, $\gamma$-ray and a lot of kinetic energy (often in the form of thermal energy).

*Thermal energy is the kinetic and potential energy of molecules moving, rotating or vibrating in a random manner.

*Wave energy is the energy stored in and transferred by waves. In mechanical waves it fluctuates between kinetic and potential energy, and is the superset of sound energy. In case of electromagnetic waves, it is the superset of light energy.

All these "types" of energy can be directly converted to, or already are kinetic energy, so no problem with the definition of work. The thing is, everything boils down to the kinetic and potential energy of something: molecules for thermal, atoms for chemical, nucleons for nuclear, charge carriers for electric, etc. These distinguishments are just a way for us to better communicate and know what is at hand, and the very same amount of energy can be referred to with a different name even when discussing the same object, only a different aspect or property of it.
However I don't think the ability to do work is a good definition of energy. It is indeed true that something can only do work if it has energy, but this definition does not address what exactly energy is, and its primary notion. You said you read it from Wikipedia, so I suppose you also read in the same sentence that "it is difficult to give one single comprehensive definition of energy"[sic].


text:
Q: Change background img IF class="active" I'm trying to change the background image of a div when I click on a thumbnail.
The background needs to change based on what thumbnail is "active"
My code I tried;
$('#sliderThumbs li a').click( function() {
    if($('#sliderThumbs li.entalk.active') === true) {
        $('#slider').css('background','url(i/slider-bg.jpg) no-repeat 0 -550px');
    }
});

The HTML:

        Intelliblast™ unit

        Dolfin™ sensor

        EnTalk™

So when I click on say.. Intellibalast, that li will then turn to class="intellibalast active"
The background of  Will need to change based on what li is active (I have 3 different images, each corresponding to the li class.

A: Update: Used .is instead of hasClass and removed ; from the css value.
Try this:
$('#sliderThumbs li a').click( function() {
    if($(this).closest("li").is(".entalk, .active")) {
        $('#slider').css('background','url(../i/slider-bg.jpg) no-repeat 0 -550px');
    }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML dom parser get inner h5 data

familya yapı Gayrimenkul Gyo ltd şti

I want to get h5 data.
I can access div.username-info-area.
$items = $new_data->find('div.username-info-area', 0)->outertext;
        echo $items . '
';

A: Run an if clause inside of your foreach loop, check this example out for instance:
The script below will make sure that if there's an h5 value it will print $div and its outertext.
<?php
foreach ($new_data->find('div[class=username-info-area]') as $div)
{
    if($div->find('h5') !== '')
    {
        print_r($div->outertext);
    }
}
?>

Or you can run another foreach loop inside of the next foreach loop, for example.
    <?php
foreach ($new_data->find('div[class=username-info-area]') as $div)
{
    foreach($div->find('h5') as $h5)
    {
        print_r($h5->outertext);
    }
}
?>

I hope this help.


text:
Q: Php echo date,month,day,hour,minute,second in numbers only I was wondering if there is a PHP command to echo current timestamp in numbers.
Example: 25/02/2015 and time 10:40:31 should be output like: 25022015104031

A: echo date("d").date("m").date("Y").date("H").date("i").date("s");

or the short version
echo date('dmYHis');

A: If you look at the php date documentation here, you see that there are sufficient ways to display a date (and time) in a human-readable format.
In your example the following code will do fine:
echo date('dmYHis');

format: description:                                            example:

d:      Day of the month, 2 digits with leading zeros           01 to 31
m:      Numeric representation of a month, with leading zeros   01 through 12
Y:      A full numeric representation of a year, 4 digits       1999 or 2003
H:      24-hour format of an hour with leading zeros            00 through 23
i:      Minutes with leading zeros                              00 to 59
s:      Seconds, with leading zeros                             00 through 59

Check the documentation for more ways of displaying date formats.

A: This will do the trick:
echo date('dmYHis');

Human readable way:
echo date('d/m/Y H:i:s');


text:
Q: Strange javafx app look on android I've got a problem with my javafx ported app on android.
After first launch it looks like that:

But when i go to home screen and then rejoin to application it looks as it should be.

build.gradle:
buildscript {
    repositories {
         mavenCentral()
        maven {
      url "https://plugins.gradle.org/m2/"
      url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:1.1.1'

    }
}

apply plugin: 'org.javafxports.jfxmobile'

repositories {
    mavenCentral()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
    }
}

mainClassName = 'pl.siemaeniu500.wszywka.main.Main'
ext.CHARM_DOWN_VERSION = "2.0.1"

dependencies {
    compile "com.gluonhq:charm-down-common:2.0.1"
    //compile 'com.gluonhq:charm-glisten:3.0.0'
    compile 'com.gluonhq:charm:2.1.1'
    compile files('D:/Android/Sdk/platforms/android-21/android.jar', 'C:/Users/Kamil/Documents/NetBeansProjects/WszywkaSounds/jfxdvk-8.60.8.jar')
    androidRuntime 'com.gluonhq:charm-android:2.1.1'
    iosRuntime 'com.gluonhq:charm-ios:2.1.1'
    desktopRuntime 'com.gluonhq:charm-desktop:2.1.1'
    desktopCompile 'com.github.sarxos:webcam-capture:0.3.10'
}

jfxmobile {

    downConfig {
        version = '3.0.0'
        plugins 'display', 'lifecycle', 'statusbar', 'storage'
    }

    android {
        manifest = 'src/android/AndroidManifest.xml'
        //compileSdkVersion 24
        //buildToolsVersion "24.0.3"
        androidSdk = 'D:/Android/Sdk'
    }
    ios {
        infoPList = file('src/ios/Default-Info.plist')
        forceLinkClasses = [
                'com.gluonhq.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]
    }
}

main application class:
package pl.siemaeniu500.wszywka.main;

import javafx.application.Application;
import static javafx.application.Application.launch;

import javafx.fxml.FXMLLoader;
import javafx.geometry.Rectangle2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Screen;
import javafx.stage.Stage;

/**
 *
 * @author Kamil
 */

public class Main extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Rectangle2D visualBounds = Screen.getPrimary().getVisualBounds();
        Parent root = FXMLLoader.load(getClass().getResource("FXML.fxml"));
        Scene scene = new Scene(root, visualBounds.getWidth(), visualBounds.getHeight());
        stage.setScene(scene);
        stage.setMaximized(true);
        //new FXMLController().initialize();
        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

What can cause that?

A: When you set the scene size:
Scene scene = new Scene(root, visualBounds.getWidth(), visualBounds.getHeight());

you are already taking the whole screen on your device, so you don't need to set this:
stage.setMaximized(true);

Removing that line should fix the issue.
As for the build script, you can simplify the dependencies.
In a first step, remove charm-down-common. If you are not using charm glisten you can remove all charm-* dependencies. If you use it, you will use the new version 4+ (uncomment the line below).
dependencies {
    // compile 'com.gluonhq:charm:4.0.1'
    compile files('D:/Android/Sdk/platforms/android-21/android.jar', 'C:/Users/Kamil/Documents/NetBeansProjects/WszywkaSounds/jfxdvk-8.60.8.jar')
    desktopCompile 'com.github.sarxos:webcam-capture:0.3.10'
}

As for the android and jfxdvk jars, those shouldn't be there. The plugin will manage that for you.
dependencies {
    // compile 'com.gluonhq:charm:4.0.1'
    desktopCompile 'com.github.sarxos:webcam-capture:0.3.10'
}

Reload the project (Project root, right click, Reload Project):

and you will see them under Dependencies -> Compile for Android:


text:
Q: ¿Como funciona un return a || b de una funcion en recursion en JavaScript? Esta es una función recursiva para mostrar en pantalla la forma de obtener X numero a traves de un calculo matematico donde solo se puede sumar 5 (+5) o multiplicar por 3 (*3), teniendo como base el numero 1:
Ejemplo:
Si quiero llegar a 13 desde 1, primero multiplico por 3, luego sumo 5 y luego de nuevo sumo 5.
findSolution(13) === (((1 * 3) + 5) + 5)

Codigo Javascript:
function findSolution(target) {
  function find(current, history) {
    if (current == target)
      return history;
    else if (current > target)
      return null;
    else
      return find(current + 5, "(" + history + " + 5)") ||
             find(current * 3, "(" + history + " * 3)");
  }
  return find(1, "1");
}

console.log(findSolution(13));
(((1 * 3) + 5) + 5)

Iterando únicamente usando +5:
6,1
11,1
16,1
null

Iterando multiplicando por 3:
3,1
9,1
27,1
null

Por lo tanto quisiera saber: ¿Como funciona el return find() || find()?, ya que no se como hace la función para decidir entre +5 o *3, o ¿si genera automáticamente dos llamados a FIND cada vez que haga un return, y a su vez dos llamados por opcion?, algo parecido al siguiente árbol:

A: El operador || en JavaScript evalua la expresión de la izquierda y si esta no es un valor falsy (null en este caso) la devuelve, de lo contrario devuelve la expresión de la derecha.
En este caso esta línea:
return find(current + 5, "(" + history + " + 5)") ||
         find(current * 3, "(" + history + " * 3)");

Sería equivalente a:
var left = find(current + 5, "(" + history + " + 5)");
return left ? left : find(current * 3, "(" + history + " * 3)");

O a esto:
var left = find(current + 5, "(" + history + " + 5)");
if (left) {
    return left;
} else {
    return find(current * 3, "(" + history + " * 3)");
}

Pero sin crear ninguna variable intermedia ni ejecutar la expresión de la izquierda dos veces

A: Para complentar la respuesta de @Carlos Muñoz:
Estos serian los llamados de recursion:
find(1, "1")
  find(6, "(1 + 5)")
    find(11, "((1 + 5) + 5)")
      find(16, "(((1 + 5) + 5) + 5)")
        muy grande
      find(33, "(((1 + 5) + 5) * 3)")
        muy grande
    find(18, "((1 + 5) * 3)")
      muy grande
  find(3, "(1 * 3)")
    find(8, "((1 * 3) + 5)")
      find(13, "(((1 * 3) + 5) + 5)")
        Encontrado!


text:
Q: How to prompt user for a number until they choose an Odd number? C++ int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << "you entered ";
    cout << num;
    cout << endl;
    return 0;
}

How will a program know when an odd number is input by the user?
For an "If statement"... I can't say If (num == odd) { cout << "all done"

A: By using the Modulus Operator, you can detect whether a number is even or odd. You can think of the modulus operator (%) as giving you the 'remainder' after a division. For example, 12 % 2 would give you 0. 13 % 2 would give you 1. In this way, just do
if (variable % 2 == 1)

to check if your variable is odd.


text:
Q: SELECT is not working as expected If I remove LIMIT "&PageStart&" , "&PageEnd&" the query below works fine. I get all the data from the database. But it don't work with LIMIT and these two parameters. What am I doing wrong?
Dim Conn,strSQL,objRec
Set Conn = Server.Createobject("ADODB.Connection")
Conn.Open "Driver={SQL Server}; Server=Localhost; Database=book-it-fifa;"
strSQL = "select distinct buchung_id, von, bis, abteilung, veranstalter, THEMA, THEMA_ENABLED " & _
    "  from RESERVIERUNGRAUM r  " & _
    "      ,BUCHUNG b  " & _
    " where r.BUCHUNG_ID = b.ID " & _
    "   and von >= convert(date, getdate(), 4) " & _
    "   and von < convert(date, dateadd(day,1, GETDATE()), 4) " & _
    "   and BIS >= getdate() " & _
    "   and STORNO is null  "
Set objRec = Server.CreateObject("ADODB.Recordset")
objRec.Open strSQL, Conn, 1,3

If objRec.EOF Then
    Response.write (" Not found record.")
Else

'**** Paging/Pagination Calculator ***'
Dim PageLen,PageNo,TotalRecord,TotalPage,intID
Dim PageStart,PageEnd
PageLen = 2
PageNo = Request.QueryString("Page")
if PageNo = "" Then PageNo = 1
TotalRecord = UBound(objRec.GetRows,2)+1
PageStart = ((PageLen*PageNo)-PageLen)
PageEnd = PageLen
If TotalRecord <= PageLen Then
    TotalPage =1
ElseIf (TotalRecord Mod PageLen = 0) Then
    TotalPage =(TotalRecord/PageLen)
Else
    TotalPage =(TotalRecord/PageLen)+1
    TotalPage = Cint(TotalPage)
End If

'*** Close Object and Open New RecordSet ***'
objRec.Close()
strSQL = strSQL & "ORDER BY von, bis ASC LIMIT "&PageStart&" , "&PageEnd&" "
objRec.Open strSQL, Conn, 1,3

A: SQL Server doesn't support LIMIT.  You can read more about it here:
http://channel9.msdn.com/Forums/Coffeehouse/102407-SQL-Server-and-LIMIT-clauses-on-SELECT-statements


text:
Q: Sequence name as a task input I have a SPB register sequence which sets up the hardware register values in a particular configuration.  The values of this configuration are used by a subsequent DAI sequence, by assigning the register values to the DAI sequence values.  I have managed this correctly using the following code to assign the register values to temporary ints to be used to constraint the DAI Sequence:
 task assign_reg_value();

    `uvm_info ("VIRT_SEQ_MODEL_PRINT", $sformatf ("Initial Register Setup : %s", ljf_reg_wr_seq.model.sprint()), UVM_LOW)

    //------------------------------------------------------------------------------------------------------
    //Get the register field value and assign it to the temporary variable. These are used for the serial
    //sequence
    //------------------------------------------------------------------------------------------------------
    //DAI_CTRL
    seq_ser_format      = ljf_reg_wr_seq.model.DAI_CTRL.format.get();

    //MORE LINES SIMILAR TO ABOVE HERE

endtask

However, in the event of running more than one register sequence to have different configurations in a single simulation, I require a method of generalising the above task such that it takes the sequence name argument.  Without this, I would need to replicate the ~50 lines of code and change the sequence name.  The pseudo code below shows the functionality that I require:
seq_ser_format = <seq_name>.model.DAI_CTRL.format.get();

I guess that there is a way to do this by setting the register sequence name in the configuration database before it is run, then retrieving it inside the task after it has finished running.  Does anybody have any suggestions for this implementation? Can it be done using the config database?

A: In your test/virtual sequence, you can implement your task as follows:
task assign_reg_value(my_base_sequence seq);
  // ...
  seq_ser_format = seq.get_format_reg();
endtask

I assume your sequences are extended from base class my_base_sequence. Then you need to implement the above function get_format_reg() in your my_base_sequence as virtual method and override it in your subclasses.
class my_base_sequence extends uvm_sequence;
  // ...
  virtual function int get_format_reg();
     // leave it empty
     $display("Not implemented in base class");
  endfunction
endclass

class ljf_reg_wr_sequence extends my_base_sequence;
// ...
  virtual function int get_format_reg();
    return this.mode1.DAI_CTRL.format.get();
  endfunction
endclass

Then in your test/virtual sequence:
// ...
ljf_reg_wr_sequence ljf_reg_wr_seq;
other_reg_sequence other_seq;
// ... create sequence

assign_reg_value(ljf_reg_wr_seq);
// do something
assign_reg_value(other_seq);
// ...


text:
Q: Uninstall Visual Studio Code 32bit I'm trying to install the 64bit version of Visual Studio Code but I can't figure out how to remove the 32 bit version first. I'm running Ubuntu 17.04. I tried:
sudo apt-get purge code

but that removes the newly installed 64 bit version.  Other things I've tried with no luck:
sudo dpkg --remove code
sudo dpkg --remove visual-studio-code
sudo apt-get --auto-remove visual-studio-code
sudo umake --remove ide visual-studio-code

I have no idea what else to try.  Any help would be appreciated!


text:
Q: Why are functions returning references with prefix inc/dec operators are lvalue expressions but not with postfix inc/dec operators Why functions that return lvalue references, along with prefix increment/decrement operators are lvalue expressions whereas, functions that return lvalue references along with postfix increment/decrement operators are not lvalue expressions ?
C++ Primer, Lippman et al. 5/e mentions :

Functions that return lvalue references, along with the assignment, subscript, dereference, and prefix increment/decrement operators, are all examples of expressions that return lvalues. We can bind an lvalue reference to the result of any of these expressions.
Functions that return a nonreference type, along with the arithmetic, relational, bitwise, and postfix increment/decrement operators, all yield rvalues. We cannot bind an lvalue reference to these expressions, but we can bind either an lvalue reference to const or an rvalue reference to such expressions.*

A: I will try to answer this myself with some hint that I got from  @YSC.
Not sure about the correctness. Community please help to review this answer.
In the case of prefix:
The return value (which is a reference) can be incremented (by using overloaded prefix ++ operator), which itself returns the reference to the same object, which can be assigned, in a sense the object maintains the identity throughout this prefix inc/dec operations and so it yields a lvalue expression.
In the case of postfix:
return value is a reference as before, but now the copy of the object (returned by reference) has to be made because there is a post inc/dec operator.
Situation is similar to the case :
int i;
i+1 = j

i+1 is not a lvalue expression. i+1 has no identity (memory allocation) so it can't be used as lvalue expression.

A: Question

Why functions that return lvalue references, along with prefix increment/decrement operators are lvalue expressions whereas, functions that return lvalue references along with postfix increment/decrement operators are not lvalue expressions ?

Answer
Because the standard says so.
From value catogeries's documentation:

The following expressions are lvalue expressions:

*

*a function call or an overloaded operator expression, whose return type is lvalue reference

*++a and --a, the built-in pre-increment and pre-decrement expressions;

Similarly,

The following expressions are prvalue expressions:

*

*a function call or an overloaded operator expression, whose return type is non-reference

*a++ and a--, the built-in post-increment and post-decrement expressions

*a + b, a % b, a & b, a << b, and all other built-in arithmetic expressions


text:
Q: Samsung's MultiWindow drag and drop with latest SDK for Android I was trying to implement Samsung's MultiWindow support in an Android app, and I haven't been able to find the drag and drop feature between MultiWindows that was available in Samsung's S Pen SDK 2.3.
Latest SDK for Pen is 4.0.7 and for MultiWindow is 1.2.6: in both cases drag and drop support seems to have vanished - and previous SDK versions cannot be found anywhere.
So, is there any way to support drag and drop between MultiWindows or it is not possible now?

A: Samsung has not included the feature in the latest SDKs mostly due to performance issues that they may have noticed. I found a similar thread on the Developers Site:
http://developer.samsung.com/forum/thread/how-to-implement-multiwindow-drag-and-drop-in-the-new-sdk-103/201/253829?boardName=SDK&startId=zzzzz~&searchSubId=0000000016
I would suggest you to use Android's Drag&Drop listeners to implement the same which is pretty similar to how it was done in the older SDK's.
Hope this helps!


text:
Q: Java Thread.sleep() does not work properly I have some trouble with the delay command.
I want to show my logo for 2 seconds and then go to the MainMenu screen. But what it does is it shows a black screen for a couple of seconds, and goes to the MainMenu (I can see my logo for about 1ms):
public void render(float delta) {
    Gdx.gl.glClearColor(0, 0, 0.2f, 0);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    game.batch.setProjectionMatrix(camera.combined);

    game.batch.begin();
    game.batch.draw(PGSImage, 0, 0);
    game.batch.end();

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
        Thread.currentThread().interrupt();
    }

    game.setScreen(new MainMenuScreen(game));
    dispose();
}

What am I doing wrong?

A: You should not use such long methods as sleep() inside render() method because normally it is called 30 times per second (or even more frequently).
You can add timer to the show() method of your current Screen:
@Override
public void show() {
    super.show();

    float delay = 2; // seconds

    Timer.schedule(new Task(){
        @Override
        public void run() {
            game.setScreen(new MainMenuScreen(game));
        }
    }, delay);
}

It will be called once your first Screen is displayed and then it will change your Screen to MainMenuScreen after 2 seconds.
Here Timer is com.badlogic.gdx.utils.Timer.
You can also count time using delta parameter of the render() method. Take a look at this question for more details.

A: I am assuming you are calling render() from the UI Thread. This means that Thread.sleep() will pause the execution of the UI Thread for 2 seconds.
If you want to delay execution one option is to use the Handler class. Make sure you read about Handlers and memory leaks.


text:
Q: Only show certain nested fields in aggregate query I have the aggregate query:
db.laureates.aggregate([
{ $match : { "nobelPrizes.affiliations.name.en" : "CERN" }},
{ $project : { _id: 0, "nobelPrizes.affiliations.country.en" : 1 }},
{ $limit : 1}]).pretty()

which results in this:
{
        "nobelPrizes" : [
                {
                        "affiliations" : [
                                {
                                        "country" : {
                                                "en" : "Switzerland"
                                        }
                                }
                        ]
                }
        ]
}

The resulting value of the query is correct (Switzerland), but I am trying to only print certain fields in the result, namely country. It should look like this:
{ "country" : "Switzerland" }

How do I exclude the fields beside the "country" field? I'm aware that the projection part of the aggregate pipeline can exclude fields parallel to the one being targeted, but how can this be done for nested fields?

A: You can use $unwind to flat the array
db.collection.aggregate([
  { "$unwind": "$nobelPrizes"},
  { "$unwind": "$nobelPrizes.affiliations"},
  { $match: { "nobelPrizes.affiliations.country.en": "Switzerland"}},
  {
    $project: {
      _id: 0,
      "country": "$nobelPrizes.affiliations.country.en"
    }
  },
  { $limit: 1 }
])

Working Mongo playground


text:
Q: Java: Overhead in executing StringBuilder.indexOf() that concatenates a variable and literal Is there a performance overhead in executing sb.indexOf(c + "")
where c is of type Character or char and sb is StringBuilder object?

A: You can use String.valueOf
builder.indexOf(String.valueOf(c));

There are good things about this approch.

*

*Clean code

*String.valueOf creates String object using char[] from passed char likechar data[] = {c}; so no additional operation is required.

2 is really a micro optimization and I would always go for option 1 i.e. "clean code".
For what it's worth, here's the bytecode generated by the concatenation version:
new #2; //class java/lang/StringBuilder
dup
invokespecial #6; //Method java/lang/StringBuilder."<init>":()V
aload_1
invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/Object;)Ljava/lang/StringBuilder;
ldc #8; //String
invokevirtual #9; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
invokevirtual #10; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
invokevirtual #11; //Method java/lang/StringBuilder.indexOf:(Ljava/lang/String;)I

As you can see, it creates a second StringBuilder, does two append calls, and then a toString. In contrast, here's the String.valueOf version:
aload_0
aload_1
invokestatic #12; //Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String;
invokevirtual #11; //Method java/lang/StringBuilder.indexOf:(Ljava/lang/String;)I

That just hands the Character (which has already been automatically unboxed into a char) off to String.valueOf. So what does that do? Let's look at the JDK source code:
public static String valueOf(char c) {
    char data[] = {c};
    return new String(0, 1, data);
}

So it creates a new one-character array and hands off directly to the String constructor. Very likely to be more efficient.
But again, it's probably a micro-optimization. The String.valueOf call makes the code clearer, which is the main thing.

A: The String and StringBuilder/StringBuffer classes in Java uses brute force method of pattern first exact string matching algorithm. This algorithm involves checking for an occurrence of the pattern at all positions of the text starting at some position and moving by one position, so I feel String.indexOf and StringBuilder.indexOf will be identical in terms of performance.
However, the String class has a indexOf(char c) method while StringBuilder/StringBuffer have indexOf(String s) methods, so if you searching for a character in StringBuilder you will have to first cast the char to String. In your example, that would probably be the only overhead.
Note: The brute force algorithm employed by String and StringBuilder classes are enough when you are dealing with small or medium sized texts but when dealing with large documents, it is preferable to use more sophisticated search string search algorithms.


text:
Q: Rails relation overload Let's say I have the following models:
Class Wishlist
    belongs_to :user # User class is irrelevant here
    has_many :inclusions
    has_many :products, :through => :inclusions
  end

  Class Product
    has_many :inclusions
    has_many :wishlists, :through => :inclusions
  end

  Class Inclusion
    belongs_to :product
    belongs_to :wishlist
  end

inclusions/index.html.erb
  <%= render @inclusions %>

inclusions/_inclusion.html.erb
  <%= "#{ inclusion.quantity } #{ inclusion.product.name } #{ inclusion.wishlist.user.name }"%>

This example is trivial, but the point is: the amount of database queries is overwhelming. For every instance of _inclusion.html.erb, at least three new queries seem to be created.
Is there a way to prefetch this information beforehand, maybe through a JOIN command?

A: Maybe this can help:
 @inclusions = Inclusions.includes(:product, { :wishlist => :user })

Read about eager loading.

A: have you thinking about creating sql view, called for example ProductsWishlist and (if the performance will be bad) materializing it?
http://ss64.com/ora/syntax-views.html


text:
Q: In android, how to listen to gestures on an ImageView? I would like to define an ImageView in Xml, and then listen to gestures which occur only on that ImageView.  But, it appears that the constructor for GestureDector requires an Activity as a parameter, and then responds to gesture events on all components in that Activity.  Is there any way to limit this such that events are only generated for gestures upon the pre-defined ImageView?
Thank you

A: extend ImageView and make it implement OnGestureListener
`


text:
Q: Скрипт не выполняет код в main() Проблема в том что скрипт не выводит текст который размещен в инструкции main().
import os
from os.path import splitext
import fnmatch

print ('Производиться поиск ключевого \nслова во всех файлах заданой директории \nкроме расширений *.exe, *.zip, *.xls(x), \n*.dot(x), *.apk, *.dll, *.doc(x), *.ppt(x).')
print ('\n----------------------------------\n')

def main():
    path = input('Директория: ')
    while not os.path.isdir(path): #проверка пути
        print('Такого каталога нет')
        path = input('Директория: ')
        return

    pattern = input('Искаемое слово: ')

    keyword = get_keyword(pattern)

    EXCL_EXTS = ('.exe', '.zip', '.xls(x)', '.dot(x)', '.apk', '.dll', '.doc(x)', '.ppt(x')

    for dirpath, dirs, files in os.walk(path):
        for file_name in files:
            fn, fext = splitext(file_name)
            if fext not in EXCL_EXTS:
                continue
            inp = open(os.path.join(path, file_name), 'r')
            for line in inp:
                if pattern in line:
                    print(os.path.join(path, file_name))

Почему скрипт не выводит 'Директория: '?

A: main() не является специальной функцией в Питоне. Её следует вызвать явно как любую другую функцию:
#!/usr/bin/env python
#file: your_program.py
import sys
print('display during import')

def main():
    print('hello{} world'.format(' verbose' * ('--verbose' in sys.argv)))

if __name__ == "__main__":
    main()

if __name__ == "__main__" используется, чтобы main() вызывалась только при исполнении скрипта и чтобы main() не вызывалась во время импортирования как модуль в какой-то другой Питон программе. Например, вот скрипт, который всегда добавляет --verbose параметр перед тем как вызывать main():
#!/usr/bin/env python
#file: your-program-verbose.py
import sys
import your_program # 'display during import' is printed here

sys.argv.append('--verbose') # make it verbose
your_program.main()          # 'hello verbose world' is printed here

python your-program-verbose.py печатает display during import и hello verbose world. Тот же результат должен быть, если запустить python your_program.py --verbose.
Если запустить python -c 'import your_program', то только display during import должно напечататься.
Чтобы пошагово посмотреть что происходит, можно запустить отладчик, например:
$ python -mpdb your_program.py


text:
Q: Distribute DIV children evenly over entire height and width of container I have an empty div and I create other divs in it with javascript. I've set up my CSS so it will create a grid. My question is: how can I dynamically resize the divs so they evenly fill their container?
I tried to illustrate it better with a drawing but my drawing skills aren't that good. Hopefully you will understand what I want.

The black square is the parent div and the red squares are the children. When I create one div it should fill the parent div (with a little margin).
With two divs it will split the parent in half.
With 3 it will behave like you see in the upper right corner of the image, and so on for the others.
How could I accomplish this with CSS?
Some more info:
This is a game I have to make for school. This is a previous version but you get the idea of having squares in a div. Now the next task is to let the user chose how many squares they want to play with. But that has to be dynamic and they have to be able to choose numbers like 5 or 8. Not just 4, 9, 16, 25 etc. that's too easy.
https://luukwuijster.io/school/csp/kleurenspel/

A: This type of layout can be achieved using CSS Flexbox.
First turn your wrapping element into a flexbox by adding display:flex. Next add flex:1 1 auto to your boxes to allow them to grow and shrink as needed to fill the space.
To keep your boxes from being squished into one line by flexbox, set a min-width value on them. I've used min-width:30% but this number can be changed to suit your needs. 30% will mean that the maximum number of boxes in a row at any time is 3 (as it is just below 1/3 or 33% of the container's width).
Try adding or removing boxes from the example code below.

#wrapper {
  display:flex;
  flex-wrap:wrap;
  width:400px;
  height:400px;
}

.box {
  background-color:white;
  border:1px solid black;
  min-width:30%;
  flex:1 1 auto;
  }


text:
Q: Django - Remove Unique Constraint from a field I have a model like
class LoginAttempts(models.Model):
    user = models.OneToOneField(User, unique=False)
    counter = models.IntegerField(null=True)
    login_timestamp = models.DateTimeField(auto_now=True)

The table created in db is like

However If I create another entry with user_id = 362 it fails with IntegrityError: duplicate key value violates unique constraint. Id is already my primary key, I want to have same user having different counters instead of creating a new table referencing them since this is simple table.
How to achieve the same or what what could be the best way. I want to restrict user to some specified number of failed logins.

A: If you want a relationship that permits more than one LoginAttempt for a User, you should not use OneToOneField. by definition, that implies only one item on each side. Instead, use ForeignKey.

A: The very nature of a OneToOneField is that it's a ForeignKey with a unique constraint.
However, if you don't want separate entries, then update the counter and login_timestamp fields:
from django.utils import timezone

def update_attempts_for_user(user):
    attempts, created = LoginAttempts.objects.get_or_create(user=user, defaults={'counter': 1, 'login_timestamp': timezone.now())
    if not created:
        attempts.counter += 1
        attempts.login_timestamp = timezone.now()
        attempts.save(update_fields=['counter', 'login_timestamp'])


text:
Q: How to use template in  I've got a very basic question which I can't answer myself because most links to http://www.primefaces.org/primeng don't work anymore.
I also tried registering to their forum but their activation mail never arrives.
I use Angular2 and have a datatable with two columns: filename and status.
The status column I want to change. It holds now a number from 1 to 4 and I want to show a glyphicon based on the status.
I now have this, which is working:
<p-dataTable [hidden]="loading" [value]="files" selectionMode="single"  sortField="Status" [sortOrder]="-1">
  <p-column field="FileName" header="Naam" sortable="true"></p-column>
  <p-column field="Status" header="Status" sortable="true"></p-column>
</p-dataTable>

I tried this, just to test the templating but nothing changes:
<p-dataTable [hidden]="loading" [value]="files" selectionMode="single"  sortField="Status" [sortOrder]="-1">
  <p-column field="FileName" header="Naam" sortable="true"></p-column>
  <p-column field="Status" header="Status" sortable="true">
    <template let-file="rowData">
        {{file.Status == 1 ? "Yes" : "No"}}
    </template>
  </p-column>
</p-dataTable>

So save to conclude I'm not using it properly.
We're using PrimeNG 1.0.0-beta.16

A: Each p-column can have two templates - body and header, you should specify which one it is. It's not mandatory because body is default I think and this is what you need in this case, but it's good practice. You also need to add pTemplate to template in order for p-column to use it, this is the reason p-column won't display template you provided. So, your code should look like this:
<p-dataTable [hidden]="loading" [value]="files" selectionMode="single" sortField="Status" [sortOrder]="-1">
  <p-column field="FileName" header="Naam" sortable="true"></p-column>
  <p-column field="Status" header="Status" sortable="true">
    <ng-template let-file="rowData" pTemplate type="body">
        {{file.Status == 1 ? "Yes" : "No"}}
    </ng-template>
  </p-column>
</p-dataTable>


text:
Q: Optional ManyToOne relationship in Doctrine 2 I'm building an application for SNMP Trap logging. It has two MySQL tables: one with the traps, and one with the hosts that I want to log.
The traps table is filled externally. The hosts can be entered through the website. A host CAN have one or many traps. A trap CAN have one host.
So this is a many to one relationship, but optional on both sides. How do I implement this, since Doctrine requires for one of the members to be a primary key, and therefore not nullable?
Code for both classes:
class Trap
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="eventname", type="string", length=50)
     */
    private $eventname;

    /**
     * @var string
     *
     * @ORM\Column(name="eventid", type="string", length=50)
     */
    private $eventid;

    /**
     * @var string
     *
     * @ORM\Column(name="trapoid", type="string", length=100)
     */
    private $trapoid;

    /**
     * @var string
     *
     * @ORM\Column(name="enterprise", type="string", length=100)
     */
    private $enterprise;

    /**
     * @var string
     *
     * @ORM\Column(name="community", type="string", length=20)
     */
    private $community;

    /**
     * @var string
     *
     * @ORM\Column(name="hostname", type="string", length=255)
     */
    private $hostname;

    /**
     * @var string
     *
     * @ORM\Column(name="agentip", type="string", length=16)
     */
    private $agentip;

    /**
     * @var string
     *
     * @ORM\Column(name="category", type="string", length=20)
     */
    private $category;

    /**
     * @var string
     *
     * @ORM\Column(name="severity", type="string", length=255)
     */
    private $severity;

    /**
     * @var string
     *
     * @ORM\Column(name="uptime", type="string", length=20)
     */
    private $uptime;

    /**
     * @var datetime
     *
     * @ORM\Column(name="traptime", type="datetime")
     */
    private $traptime;

    /**
     * @var string
     *
     * @ORM\Column(name="formatline", type="string", length=255)
     */
    private $formatline;

    /**
     * @ORM\ManyToOne(targetEntity="Host", inversedBy="traps")
     * @ORM\JoinColumn(name="agentip", referencedColumnName="ip", nullable=true)
     */
    protected $host;
}

class Host
{
    /**
     * @var string
     * @ORM\Id
     * @ORM\Column(name="ip", type="string", length=16)
     */
    private $ip;

    /**
     * @ORM\Column(name="hostname", type="string", length=100)
     */
    private $hostname;

    /**
     * @ORM\Column(name="type", type="string", length=100)
     */
    private $type;

    /**
     * @ORM\Column(name="importance", type="integer", length=1)
     */
    private $importance;

    /**
     * @ORM\OneToMany(targetEntity="Trap", mappedBy="host")
     */
    protected $traps;
}

Edited with error
The error is that I'm not allowed to delete or truncate my hosts table, which should be possible in my application, because traps must be able to exist without a host.
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`snmptt`.`snmptt`, CONSTRAINT `FK_9BF059B998B5BE9E` FOREIGN KEY (`agentip`) REFERENCES `hosts` (`ip`))

A: Posted as answer from comment as believe to be appropriate answer;
"If you are trying to remove this as straight sequel then yes the error is correct you cannot remove the parent before unlink the child, if there is no parent then this is fine if so unlink first then remove"


text:
Q: Bash If Else for login -p the command logins -p is to show which users do not have a password while wc -l is to count the number of newlines. Thus, logins -p | wc -l shows the number of users that do not have a password. In my case, logins -p | wc  -l returns me a value of 4 but when I compare it to be equal to 0, it prints "equal to 0" which is wrong. I would like to ask if there are any mistakes in my script and does wc -l returns an INT? Thanks.
if [ "$(logins -p | wc -l)" -eq 0 ]; then
  echo "equal to 0"
else
  echo "not equal to 0"
fi


text:
Q: canvas is flickering constantly I've looked at a few different posts on StackOverflow, but didn't really find the one that solved my issue. The code below works, but it's flickering constantly.
Essentially, I'm just creating a starry background where random stars will fade in and out
var canvas = document.querySelector("canvas");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var c = canvas.getContext("2d");

function Star(x, y, a, z, size, b) {
  this.x = x;
  this.y = y;
  this.z = z;
  this.a = a;
  this.size = size;
  this.b = b;

  this.draw = function () {
    c.fillStyle = "rgba(155, 241, 052, 1)";
    c.beginPath();
    c.arc(this.x, this.y, this.z, 0, Math.PI * 2, false);
    c.fill();
  };

  this.update = function () {
    if (this.z > this.size) {
      this.a = 0;
    }
    if (this.z < 0) {
      this.a = 1;
    }

    if (this.a == 1) {
      this.z += this.b;
    } else {
      this.z -= this.b;
    }
    this.draw();
  };
}

var starArray = [];

for (var i = 0; i < 100; i++) {
    var size = Math.random() * 3 + 2; //size range
    var x = Math.random() * innerWidth; //x coordinate
    var y = Math.random() * innerHeight; //y coordinate
    var z = Math.random() * size; //star size
    var a = 1; //on-off switch for the star to fade in or fade out
    var b = Math.random() / 20; //fade-in/fade-out rate (random for each star)
    starArray.push(new Star(x, y, a, z, size, b));
}

function animate() {
  requestAnimationFrame(animate);
  c.clearRect(0, 0, innerWidth, innerHeight);
  for (var i = 0; i < starArray.length; i++) {
      starArray[i].update();
  }
}

animate();

A: You are getting negative radius on the arc call, just do:
c.arc(this.x, this.y, Math.max(this.z, 0), 0, Math.PI * 2, false);

A: You are providing a negative radius to CanvasRenderingContext2D.arc(). You may need to rethink your logic or use Math.abs to make sure the radius provided is always non-negative.
c.arc(this.x, this.y, Math.abs(this.z), 0, Math.PI * 2, false);

var canvas = document.querySelector("canvas");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var c = canvas.getContext("2d");

function Star(x, y, a, z, size, b) {
  this.x = x;
  this.y = y;
  this.z = z;
  this.a = a;
  this.size = size;
  this.b = b;

  this.draw = function () {
    c.fillStyle = "rgba(155, 241, 052, 1)";
    c.beginPath();
    c.arc(this.x, this.y, Math.abs(this.z), 0, Math.PI * 2, false);
    c.fill();
  };

  this.update = function () {
    if (this.z > this.size) {
      this.a = 0;
    }
    if (this.z < 0) {
      this.a = 1;
    }

    if (this.a == 1) {
      this.z += this.b;
    } else {
      this.z -= this.b;
    }
    this.draw();
  };
}

var starArray = [];

for (var i = 0; i < 100; i++) {
    var size = Math.random() * 3 + 2; //size range
    var x = Math.random() * innerWidth; //x coordinate
    var y = Math.random() * innerHeight; //y coordinate
    var z = Math.random() * size; //star size
    var a = 1; //on-off switch for the star to fade in or fade out
    var b = Math.random() / 20; //fade-in/fade-out rate (random for each star)
    starArray.push(new Star(x, y, a, z, size, b));
}

function animate() {
  requestAnimationFrame(animate);
  c.clearRect(0, 0, innerWidth, innerHeight);
  for (var i = 0; i < starArray.length; i++) {
      starArray[i].update();
  }
}

animate();
<canvas></canvas>


text:
Q: Confusion Matrix not Giving Predicted Values for Species I have a set of 1385 spectra across 23 species. I am doing models made of species X against the other 22 species to get a 2x2 confusion matrix. However, none of my models or predictions are working, as they give out a confusion matrix [

`ClassDT1 <- as.factor(ClassDT1 <- c(rep(1,60), rep(0,1325)))

DT1DataFrame <- data.frame(x = VRData, Class = ClassDT1)

set.seed(floor(runif(1, min=0, max=1001)))

Smp_size <- floor(0.65 * nrow(DT1DataFrame))
Train_ind <- sample(seq_len(nrow(DT1DataFrame)), size = Smp_size)
Train1 <- DT1DataFrame[Train_ind,]
Test1 <- DT1DataFrame[-Train_ind,]

DT1 <- rfsrc(Class ~ ., data = Train1, ntree = 1000, mtry = 15, ytry = 10)
DT1

Pred1 <- predict(DT1, Test1, type = 'raw')
Pred1`


text:
Q: Silverlight Runtime Error 1001 So I have a deployed Silverlight app that works fine on most client machines.  However, I have 1 client machine (Windows Vista / IE8) that throws the following javascript error:

Webpage error details
User Agent: Mozilla/4.0 (compatible;
  MSIE 8.0; Windows NT 6.0; Trident/4.0;
  SLCC1; .NET CLR 2.0.50727; .NET CLR
  3.5.30729; .NET CLR 3.0.30618; OfficeLiveConnector.1.3;
  OfficeLivePatch.0.0) Timestamp: Tue,
  21 Jul 2009 14:38:15 UTC
Message:
  Sys.InvalidOperationException: Runtime
  error 1001 in control 'Xaml1', method
  : 1001 An error has occurred. Line:
  453 Char: 17 Code: 0
  URI: www.DOMAINNAME.com/ScriptResource.axd?d=DYlfEE5ljRCaoM7uReLHHn6ek5uYaOA1UhTw1oJkABzHek2FGpt_ylvF5NNjuH26VVA5njj6q3r4MlWsNnz7ag2&t=1f1ca10

This is working fine on other Vista / IE8 machines and I cannot reproduce on my dev machine.
I am assuming this is a generic error message and the real details are not being displayed.  Based on the following link there is probably a way to access what is really going on, but I have no idea how.
https://silverlight.net/forums/p/99022/226122.aspx#226122

A: You can try to check if browser set in 'Compatible' mode. If yes, then you can try set the java script line into HEADER of your HTML/ASP page:
<head runat="server">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
</head>


text:
Q: Can't get Perl web service running using WSDL::Generator I have been trying for two weeks to create a web service in Perl (with WSDL::Generator) and call it with a client written in Perl.
Now I try the examples provided with the library specializes in WSDL: Soap::Lite
but I get an error that keeps appearing
404 file not found at c.PL at line 7.

Can you help me solve it?
Here is my code:
WorldFunctions.pm (C:\Perl\SOAP-Lite\WorldFunctions.pm) : the class
package WorldFunctions;
    sub new { bless {}, shift; }
    sub Hello { my ($s, $name) = @_;
            return 'Hello, ' . $name . "\n";
    }
    sub GoodBye { my ($s, $name) = @_;
            return 'Goodbye, ' . $name . "\n";
    }

a.pl (C:\Perl\SOAP-Lite\a.pl): to create the WSDL file of the class WorldFunctions.pm
#!/usr/bin/perl
use WSDL::Generator;
my $init = {
        'schema_namesp' => 'http://localhost/world/WorldFunctions.xsd',
        'services'      => 'WorldFunctions',
        'service_name'  => 'WorldFunctions',
        'target_namesp' => 'http://localhost/world',
        'documentation' => 'Simple Hello World SOAP Service.',
        'location'      => 'http://localhost/world'
};
my $w = WSDL::Generator->new($init);
WorldFunctions->Hello('Joe');
WorldFunctions->GoodBye('Joe');
print $w->get(WorldFunctions); # Returns the WSDL code for a specific class
open(TOTO,"<a.wsdl");
close(TOTO);
open(TOTO,">a.wsdl");
print TOTO $w->get(WorldFunctions);
close(TOTO);

c.pl (C:\Perl\SOAP-Lite\c.pl): perl client WSDL file
#!/usr/bin/perl
use DBI();
use CGI;
use SOAP::Lite;
my $service = SOAP::Lite-> service('file:a.wsdl');
print "test retour : |".$service-> Hello('Joe')."|";

Knowing that I use a local server (with WAMP server) and I copied into my directory WorldFunctions.pm localhost / world.
Here is the WSDL file:
<?xml version="1.0"?>
<definitions name="WorldFunctions" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" targetNamespace="http://localhost/world" xmlns:tns="http://localhost/world" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:xsdl="http://localhost/world/WorldFunctions.xsd">
    <types>
        <xsd:schema targetNamespace="http://localhost/world/WorldFunctions.xsd">
            <xsd:element name="GoodByeRequest" type="xsd:string" />
            <xsd:element name="GoodByeResponse" type="xsd:string" />
            <xsd:element name="HelloRequest" type="xsd:string" />
            <xsd:element name="HelloResponse" type="xsd:string" />
        </xsd:schema>
    </types>
    <message name="GoodByeRequest">
        <part name="GoodByeRequestSoapMsg" element="xsdl:GoodByeRequest"/>
    </message>
    <message name="GoodByeResponse">
        <part name="GoodByeResponseSoapMsg" element="xsdl:GoodByeResponse"/>
    </message>
    <message name="HelloRequest">
        <part name="HelloRequestSoapMsg" element="xsdl:HelloRequest"/>
    </message>
    <message name="HelloResponse">
        <part name="HelloResponseSoapMsg" element="xsdl:HelloResponse"/>
    </message>
    <portType name="WorldFunctionsWorldFunctionsPortType">
        <operation name="GoodBye">
            <input message="tns:GoodByeRequest" />
            <output message="tns:GoodByeResponse" />
        </operation>
        <operation name="Hello">
            <input message="tns:HelloRequest" />
            <output message="tns:HelloResponse" />
        </operation>
    </portType>
    <binding name="WorldFunctionsWorldFunctionsBinding" type="tns:WorldFunctionsWorldFunctionsPortType">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
            <operation name="GoodBye">
                <soap:operation style="document" soapAction=""/>
                <input>
                    <soap:body use="literal"/>
                </input>
                <output>
                    <soap:body use="literal"/>
                </output>
            </operation>
            <operation name="Hello">
                <soap:operation style="document" soapAction=""/>
                <input>
                    <soap:body use="literal"/>
                </input>
                <output>
                    <soap:body use="literal"/>
                </output>
            </operation>
    </binding>
    <service name="WorldFunctions">
        <documentation>
            Simple Hello World SOAP Service.
        </documentation>
        <port name="WorldFunctionsWorldFunctionsPort" binding="tns:WorldFunctionsWorldFunctionsBinding">
            <soap:address location="http://localhost/world"/>
        </port>
    </service>
</definitions>

A: It looks like you are not mapping http://localhost/world to the SOAP handler that can handle the request, hence you are getting a 404 for that URL.
You need to configure apache so there is something at that URL.
http://metacpan.org/pod/SOAP::WSDL::Server::Mod_Perl2


text:
Q: Postsharp: How to set the return value after an exception Using Postsharp, how do you set the return value after an exception has been thrown?
I thought this would work:
namespace MvcApplication3.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values/5
        [MyExceptionHandler]
        public string Get(int id)
        {
            string value = GetValue(id);
            return value;
        }

        private string GetValue(int id)
        {
            throw new DivideByZeroException();
        }
    }

    [Serializable]
    public class MyExceptionHandler : OnExceptionAspect
    {
        public override void OnException(MethodExecutionArgs args)
        {
            args.FlowBehavior = FlowBehavior.Continue;
            args.ReturnValue = "Error Getting Value";
        }
    }
}

A: I figured it out.
You need to Return from the function, not continue.
    public override void OnException(MethodExecutionArgs args)
    {
        args.FlowBehavior = FlowBehavior.Return;
        args.ReturnValue = "Error Getting Value";
    }


text:
Q: How to use d3.scaleLinear to find the radius of a map in d3 I have a chart as shown below

where the radius of the pie chart on the chart is am trying to do it as shown below
 <PieChartMarkers
              totalSites={totalSites}
              key={i}
              keymarket={name}
              pieData={pieData}
              x={projection(coordinates)[0]}
              y={projection(coordinates)[1]}
              **radius={this.getMarketRadius(totalCase)}**
              mouseOverHandler={this.showTooltip}
              mouseOutHandler={this.hideTooltip}
            />

  getMarketRadius = (totalCase) => {
    let radius = null;
    // let data=d3.scaleLinear([10,130]).range([0,960]);
    let callback= d3.scaleLinear()
    .range([0, totalCase])
    .domain([10, 130])
    radius = totalCase / 650 + 10;
    console.log(radius)
    return radius;
  };

currently i am getting the radius  radius = totalCase / 650 + 10; which is working fine  but suggestion is to use d3.scaleLinear to get the radius of the on chart when trying to use i am getting the value as 1313316 using the below code snippet
//totalCase is the variable value coming from API
let callback= d3.scaleLinear()
    .range([0, totalCase])
    .domain([10, 130]

please help me understand how to get the radius using d3.scaleLinear to draw the pie chart on the map

A: First of all, you should not use a linear scale to get these radii: we encode the data as the area of the circles, not as their radii. That said, you should use d3.scaleSqrt. Also, set the 0 range for the 0 domain, because there should be no circle if there are no cases.
So, your function would be something like this:
getMarketRadius = totalCase => {
    return d3.scaleLinear().range([0, totalCase]).domain([0, 130])(totalCase);
};

A better option is just setting the scale outside the function, and using it directly for setting the radius.
myScale = d3.scaleLinear()
    .range([0, totalCase])
    .domain([0, 130]);

radius={this.myScale(totalCase)}


text:
Q: How to read "A = (πr)²" so as not to mistake it for "A = πr²" None of the 26 answers given here, or the 5 answers given here mentions any similarity between the pronunciation of  E = mc² and  A = πr², yet I still remain confusioned as to what distinguishes the reading of E = (mc)² and A = (πr)² with the reading of the first two.

A: Most of the mathematicians I know would pronounce these as:
A = πr²
A equals pi r squared
A = (πr)²
A equals pi r all squared
There is no fixed rule, so this really comes under the category of primarily opinion based.

A: To read A=(πr)2 to a class, items in parentheses tend be categorized as the quantity with contents terminated by a pause in speech.
Per the Oregon State math read-aloud accommodation

Parentheses - read as "the
quantity"
3(x + 2) is read as "three times the quantity 'x' plus two"
(y – 5) ÷ 6 is read as " the quantity 'y' minus five (pause) divided by six"

Which is to be interpreted for the question as:

A equals the quantity pi 'r' (pause) squared

Edit to add: "Is it pi 'r' or is it pi times r?"

Expressions containing variables (any letter may be used as a variable):
"'V' equals four thirds pi 'r' cubed"

I think it should be noted that vocalization of a math(s) expression is likely to be accompanied by a written version of what's being said: either on the board and/or for students to transcribe. In the case of the AmE the quantity, this signals the beginning of a parenthetical expression (i.e., write or read an opening parenthesis) where the pause signals the end (close parenthesis). It may be trivial to retroactively assign parentheses as the expression is complete (all squared), so this distinction is not as problematic as it may seem, especially since it can be argued that "all" is an unambiguous demarcation point between the parenthetical expression and the accompanying exponent, versus a pause in speech.
Reviewing the body of the question:

.. the pronunciation of E = mc² and A = πr², yet I still remain confusioned as to what distinguishes the reading of E = (mc)² and A = (πr)²

Taking the latter first:

E equals the quantity of mc (pause) squared

is read the same as

A equals the quantity of pi r (pause) squared.

Contrast this with:

E equals m c squared,

or

A equals pi r squared

(no pause, and without the quantity) one understands that the exponent only applies to the preceding variable/operand. If one asks how the written version distinguishes the coverage of exponent to its applicable operand (e.g., why the exponent applies to the entire expression in parentheses), that is indeed a math(s) question.
Further edit:
There appears to be some confusion that the quantity is dependent on the content within parentheses being a sum or difference rather than being agnostic to the contents. It can be argued that a quantity can contain any expression but while it has been generally associated with add/subtract, it's the parentheses that determines whether the quantity is being used or not.
Additional usage examples of the quantity:
mathforum post
http://www.mastermathmentor.com/mmm/ReadingMath.ashx (How to read to the blind and dislexic). Replaces the pause with "end quantity".
Yes, while the expressions tend to be sum/difference, every discussion talks about the parentheses being addressed, not the content, and at no time is there any distinction being made about the expression within parentheses changing the attribute describing parentheses.
Further, quantity itself does not distinguish the expression configuration as does sum, difference, or product. The free dictionary does not indicate anything about how an expression is defined for the definition of quantity.

A: A = (πr)² can be read as "πr all squared", and is another way of writing π²r² which is also the same as π² x r² (pi squared times r squared).  In other words, the original formula [A = (πr)²] is just a different, and sometimes shorter way of writing the equivalent formulas.  It doesn't save much time in this particular example, but it would if you wrote A = (a + b)² instead of the equivalent A = a² + 2ab + b²

A: It is common that A equals PI R squared is understood to be A = πr². If someone wanted to say something more like B = π(r²) then they might say B equals PI, times R squared.
The typical way it is pronounced will be by using timing and inflection to attempt to let the listener know what you mean. Some teachers, in order to alleviate any confusion, might sometimes actually say paren(s) or parenthesis. I have only witnessed this a small number of times and it was done in a classroom environment when the instructor could see that many students were taking notes without looking up very much. Mostly, the actual speaking of any parenthesis is done with more complicated formulas then the ones noted here.

A: A = πr² (A equals pi r squared)
A = (πr)²(A equals whole square of pi multiplied by r)
That's another way to define parentheses in mathematics.


text:
Q: PHP array with Ajax and Jquery - How to create dropdown from the data? This is the first time i've used AJAX and PHP.  I've written a simple login page (below). As you can see, Ajax will send the username to getLocations.php on blur, which i coded with the help of this site and youtube (i'm leaving out the db connect bit, but it's there):
<!doctype html>

  <title>Fetch JSON array Data</title>

    <form method="post" action="#" onsubmit="return false;">
        <input type="username" id="username" name="username" placeholder="username" value="" />

        <input type="password" id="password" name="password" />

        <select name="foo" id="foo">
          <option></option>
        </select>

        <input type="submit" id="button" value="Login"  />
    </form>

getLocations.php:
$name     = $_REQUEST['username']; //from ajax request

$query  = "select LOCATION ";
$query .= "FROM dc_MASTER.DC_CNSLR_ACCESS dca ";
$query .= "JOIN dc.MEMBERS m ON dca.id = m.id ";
$query .= "AND m.EMAIL = '$name' ";

$Sresult = mysqli_query($mysqli, $query);
    if( ! $Sresult) {
        die("Database query failed: $Sresult");
    }
    $result = array();

    while( $row = mysqli_fetch_array($Sresult) )

      $list = array_push($result, array('name' => $row[0]));

      $c = json_encode(array("result" => $result));
      echo $c;

?>

At this point, my array is "loaded" and i'm able to see the response in firebug:
{"result":[{"name":"Chenal"},{"name":"Heights"}]}

However, i can't seem to get my select options populated. I feel like i'm making this harder than it should be (and i've been staring at it for quite a while).  Thanks for the help guys.

A: 1) You haven't told jquery that you're expecting a json response back, so it'll just treat it as plain text.
$.post(
    dataType: 'json'   // <<--you need this

With that, jquery will automatically parse/decode the JSON into a native JS data structure
2) Then it's a simple matter of looping:
 success: function(data) {
        $.each(data, function(i, opt) {
            $('select').blahblah + opt.name + blahblah
        })

On the efficiency side of things, while it's sometimes a good idea to pass around data AS data, but if all you're going to be doing with the data is stuffing it into a form field, you might be better off just building the HTML on the server and passing that around directly.

A: You have to loop through the JSON returned by the PHP:
Demo: http://jsfiddle.net/L7a68y26/
var response = {"result":[{"name":"Chenal"},{"name":"Heights"}]}
var r = response.result;

for (var i in r)
{
    $('select').append("<option value=\""+r[i].name+"\">"+r[i].name+"</option>");
}

In context:
$.ajax({
    type: "POST",
    url: "getLocations.php",
    data: "username="+sendu,
    // Added this so jQuery knows what kind of data is being returned
    dataType: 'json',
    success: function(response){
        var r = response.result;
        for (var i in r)
        {
            $('select').append("<option value=\""+r[i].name+"\">"+r[i].name+"</option>");
        }
    }
});


text:
Q: jQuery - A different background color for each item when active in a sticky menu I'm having some difficulty wrapping my head around how to make my sticky-menu items each have their own background color when their respective anchor is scrolled to in the viewport.
JSfiddle here: https://jsfiddle.net/ym88etuk/6/ -- this works how I want it to now, but I could still use help making this DRY friendly.
HTML:

part1

part2

part3

part4

CSS:
.sticky{
  position: fixed;
  top:0px;
  width:100%;
  z-index:999;
  background: white;
  margin:0;
}
.content{
  position:relative;
  top: 28px;
  width:100%;
}
ul{
  list-style-type:none;
}
li{
  float: left;
  width 20%;
  padding:2.5%;
}
.section{
  height:300px;
}
.gray{
  background-color:gray;
}
.green{
  background-color:green;
}
.clearfix:after {
    content: " ";
    display: table;
    clear: both;
}
.extraspace{
  height: 400px;
}

jQuery/Javascript:
jQuery(document).ready(function($) {
    $(".scroll").click(function(event){
        event.preventDefault();
        $('html, body').animate({
      scrollTop:($(this.hash).offset().top) - 32}, 500);
    });
});

$(window).scroll(function(){
// I've removed my work here, because it was very broken... and not pertinent to solving the issue.
}

A: What you need is jQuery.scrollfire
And working demo here.
1. import jQuery.scroll script

2. update your html

part1

part2

part3

part4

3. update your script
jQuery(document).ready(function($) {
    $(".scroll").click(function(event){
        event.preventDefault();
        $('html, body').animate({
      scrollTop:($(this.hash).offset().top) - 32}, 500);
    });

  //bind section scrollfire event
  $(".section").scrollfire({
    topOffset: 64,
    onTopOut:function(elm, distance){
      var className = $(elm).hasClass('gray') ? 'gray' : 'green';
        $('.scroll > li' ).removeClass('gray green');
      $('#'+$(elm).data('anchor')+' > li').addClass(className);
      console.info($(elm).attr('id') + 'top out');
    },
    onTopIn:function(elm, distance){
        var className = $(elm).hasClass('gray') ? 'gray' : 'green';
        $('.scroll > li ').removeClass('gray green');
      $('#'+$(elm).data('anchor')+' > li').addClass(className);
      console.info($(elm).attr('id') + 'top in');
    }
  });
});

A: you can do it by getting the div background and setting it as li background... kindly check https://jsfiddle.net/RRR0308/ym88etuk/10/
HTML

      part1

      part2

      part3

      part4

CSS
.sticky{
  position: fixed;
  top:0px;
  width:100%;
  z-index:999;
  background: white;
  margin:0;
}
.content{
  position:relative;
  top: 28px;
  width:100%;
}
ul{
  list-style-type:none;
}
li{
  float: left;
  width 20%;
  padding:2.5%;
}
.section{
  height:300px;
}
.gray{
  background-color:gray;
}
.green{
  background-color:green;
}
.red{
  background-color:red;
}
.yellow{
  background-color:yellow;
}
.clearfix:after {
    content: " ";
    display: table;
    clear: both;
}
.extraspace{
  height: 400px;
}

li{
  cursor:pointer;
}

jQuery
    //smooth scroll
jQuery(document).ready(function($) {
    $("li").click(function(event){

        event.preventDefault();
    event.stopPropagation();
    t= $(this).find('a').attr('href');
    var bg=$(document).find(''+t).css('background-color');

    $('li').removeClass('highlight').css('background-color', '#fff');

    $(this).css('background-color',bg);
        $('html, body').animate({

      scrollTop:($(t).offset().top) - 32}, 500);

   console.log(bg);
    });

});

A: I have an answer, though I am still struggling to make this fit DRY programming techniques:
I've updated the JSfiddle to reflect these changes https://jsfiddle.net/ym88etuk/36/
HTML:

part1

part2

part3

part4

CSS:
.sticky{
  position: fixed;
  top:0px;
  width:100%;
  z-index:999;
  background: white;
  margin:0;
}
.content{
  position:relative;
  top: 28px;
  width:100%;
}
ul{
  list-style-type:none;
}
li{
  float: left;
  width 20%;
  padding:2.5%;
}
.section{
  height:300px;
}
.gray{
  background-color:gray;
}
.green{
  background-color:green;
}
.blue{
  background-color:blue;
  color: #fff;
}
.orange{
  background-color:orange;
  color: #fff;
}
.pink{
  background-color:pink;
  color: #fff;
}
.purple{
  background-color:purple;
  color: #fff;
}
.clearfix:after {
    content: " ";
    display: table;
    clear: both;
}
.extraspace{
  height: 400px;
}

jQuery:
//smooth scroll
jQuery(document).ready(function($) {
var greenback =
    $(".scroll").click(function(event){
        event.preventDefault();
        $('html, body').animate({
      scrollTop:($(this.hash).offset().top) - 32}, 500);
    });
});

//Navbar Functions
$(document).ready(function() {
  var pos1 = $("#part1").position();
  var pos2 = $("#part2").position();
  var pos3 = $("#part3").position();
  var pos4 = $("#part4").position();
  $(window).scroll(function(){
    var windowpos = $(window).scrollTop();
    part1li = $("li", 'a[href="#part1"]');
    part2li = $("li", 'a[href="#part2"]');
    part3li = $("li", 'a[href="#part3"]');
    part4li = $("li", 'a[href="#part4"]');
    if (windowpos >= pos1.top && windowpos < pos2.top) {
            part1li.addClass('blue');
        } else {
            part1li.removeClass('blue');
        }
            if (windowpos >= pos2.top && windowpos < pos3.top) {
            part2li.addClass('orange');
        } else {
            part2li.removeClass('orange');
        }
            if (windowpos >= pos3.top && windowpos < pos4.top) {
            part3li.addClass('pink');
        } else {
            part3li.removeClass('pink');
        }
            if (windowpos >= pos4.top) {
            part4li.addClass('purple');
        } else {
            part4li.removeClass('purple');
        }
      });
    });


text:
Q: Following calls to static methods with indexing when importing classes I have a class file myClass.m in a package folder +myPack that's on the path. A simple example of the class file is:
classdef myClass
    properties
        prop
    end

    methods
        function obj = myClass(x)
            obj.prop = x;
        end
    end
end

Now if I directly call the method and access the property using the full package name, i.e.:
x = myPack.myClass(2).prop;

returns x = 2 correctly. Now, if I try the same by importing this class (and not use the package name):
import myPack.myClass
y = myClass(2).prop

it gives me the following error:

Static method or constructor invocations cannot be indexed.
  Do not follow the call to the static method or constructor with
  any additional indexing or dot references.

Why does this work in the first case and not the second? As far as I understood, importing a class mainly allowed one to use the class name without the long package name (among other considerations). What is the difference in these two that causes this error and how can I work around it?

A: Here is some more weird for you: the behavior is different if you are running in the command window, from a script, or from a function!
1) command prompt (1st: ok, 2nd: error)
This is what you've already shown
>> x = myPack.myClass(2).prop
x =
     2

>> import myPack.myClass; y = myClass(2).prop
Static method or constructor invocations cannot be indexed.
Do not follow the call to the static method or constructor with
any additional indexing or dot references.

2) Script (1st: error, 2nd: error)
testMyClassScript.m
x = myPack.myClass(2).prop
import myPack.myClass; y = myClass(2).prop

and
>> testMyClassScript
Static method or constructor invocations cannot be indexed.
Do not follow the call to the static method or constructor with
any additional indexing or dot references.
Error in testMyClassScript (line 1)
x = myPack.myClass(2).prop

(the second line would also throw the same error)
3) Function (1st: ok, 2nd: ok)
testMyClassFunction.m
function testMyClassFunction()
    x = myPack.myClass(2).prop
    import myPack.myClass; y = myClass(2).prop
end

and
>> testMyClassFunction
x =
     2
y =
     2

I would definitely call that a bug :) The expected behavior is to give an error in all cases.


text:
Q: Linq- Get main that has property of list where list contain string I have a List that has a property of List. How can I get the any List when the string items in its property List contain a string?
Here is my code but it return nothing.
class Program
{
    static void Main(string[] args)
    {
        List<Plist> a = new List<Plist>()
        {
            new Plist()
            {
                Name="a",
                StringList=new List<string>()
                {
                    "a1","b1","c1"
                }
            },
            new Plist()
            {
                Name="b",
                StringList=new List<string>()
                {
                    "a2","b2","c2"
                }
            },new Plist()
            {
                Name="c",
                StringList=new List<string>()
                {
                    "a3","b3","c3"
                }
            },new Plist()
            {
                Name="d",
                StringList=new List<string>()
                {
                    "a4","b4","c4"
                }
            }
        };
        var list = a.Where(n=>n.StringList.All(s=>s.Contains("a"))).Take(3);

        foreach(Plist items in list)
        {
            Console.WriteLine($"{items.Name}");
            foreach(string item in items.StringList)
            {
                Console.WriteLine($"    {item}");
            }
        }

        Console.ReadLine();
    }

}

public class Plist
{
    public string Name { get; set; }
    public List<string> StringList { get; set; }
}

I am new to Linq so hope all of you help me out of this.

A: Currently your LINQ states that every (All()) item in inner list has to contain "a". What you want to check whether Any() of the items contains "a".
To do so you should use Any() instead of All():
var list = a.Where(n => n.StringList.Any(s => s.Contains("a")));


text:
Q: Converting a double to a time that makes sense Basically I  am setting a limit of hours a user can use. Now every time a button is press, whatever time that person accrued gets taken away from  this total value.
However because a limit would be represented as say 156 hours, and  the datetime representation of 5 minutes would be 00.05 the result would be 155.95, rather than 155.55 .
I work this out like so
 string date2 = TotalMonthlyHours.ToString("HH.mm");
                    double date = double.Parse(date2);
                    RunningTotal = date + RunningTotal;
                    Total = limit - RunningTotal;

Any ideas?

A: I think you are trying to represent 5 minutes as 0.05. The way to do that is to first of all obtain the minutes as an integer. And then simply convert to double.
double floatmins = minutes/100.0;

And you convert in the other direction like this:
int minutes = (int) (floatmins*100.0);

However, I urge you not to go any further with this. You cannot expect to perform arithmetic on a quantity like that. What is the result of 2.20-1.50? You and I know it's 30 minutes, but the computer says 0.70 which is no use at all.
Store the hours using a true fractional representation. So 5 minutes is 5/60.0. Or store the total minutes in an integer. Or total seconds in an integer. Or a TimeSpan.
The key is that you can write your own helper routines to convert from a sane storage format to a value that is human readable. But you must store the raw data in a representation that will admit arithmetic operations.

A: I think I worked it out by doing something like this
                   string[] times = date.ToString().Split('.');

                    if (date != 0.0)
                    {
                        string minutesString = times[1];
                        string hoursString = times[0];
                        double minutes = Convert.ToDouble(minutesString);
                        double hours = Convert.ToDouble(hoursString);

                        // end of splitting
                        TimeSpan Limit = TimeSpan.FromHours(limit);

                        TimeSpan Hours = TimeSpan.FromHours((int)hours);
                        TimeSpan Minutes = TimeSpan.FromMinutes((int)minutes);

                        TimeSpan SubTotal = Hours + Minutes;

                        Time = Limit - SubTotal;
                    }

Edit: Glad you came up with the same as me,Just read your reply David, let's hope it works

A: I would convert it to minutes first than add as minutes to the date
var min = Convert.ToDouble(Convert.ToDecimal(textbox.Text) * 60);
DateTimePickerEnd.DbSelectedDate = e.NewDate.Value.AddMinutes(min);


text:
Q: How do you pipe to an object in another require module I have a scrollview in a module which loads views which are returned from other modules.
Module containing scrollview:
define(function(require, exports, module) {
    var View = require('famous/core/View');
    var Utility = require('famous/utilities/Utility');
    var Scrollview = require('famous/views/Scrollview');
    var HomeView = require('views/HomeView');
    var DescriptionView = require('views/DescriptionView');

    var paginationView = new Scrollview({
        direction: Utility.Direction.X
    });

    var AppViews = [
        HomeView,
        DescriptionView
    ];

    paginationView.sequenceFrom(AppViews);

    module.exports = paginationView;
});

Here's the module code
define(function(require, exports, module) {
    var View = require('famous/core/View');
    var Surface = require('famous/core/Surface');
    var FlexScrollView = require('famous-flex/FlexScrollView');
    var MainView = require('views/MainView');
    var EventHandler = require('famous/core/EventHandler');

    function HomeView() {
        View.apply(this, arguments);
    }

    HomeView.prototype = Object.create(View.prototype);
    HomeView.prototype.constructor = HomeView;

    HomeView.DEFAULT_OPTIONS = {};

    var homeView = new HomeView();
    var scrollView = new FlexScrollView();

    homeView.add(scrollView);

    for (var i = 0, temp; i < 40; i++) {
        var surface = new Surface({
            content: "Surface: " + (i + 1),
            size: [undefined, 200],
            properties: {
                backgroundColor: "hsl(" + (i * 360 / 40) + ", 100%, 50%)",
                lineHeight: "200px",
                textAlign: "center"
            }
        });

        surface.pipe(scrollView);
        // ... I want to pipe to the parent scrollview here ...

How could I pipe the surfaces from the second module to the scrollview in the first module? I'm still learning the whole event piping and am not sure how I would implement it here. I know that since I'm inheriting from the famous View module I should be able to access some advanced event management, but am  in the dark as to how I'd do it in my case.

A: The module HomeView extends the Famo.us View, so you can pipe the surfaces to the event handlers in HomeView
// ... I want to pipe to the parent scrollview here ...
Surface.pipe(this._eventOutput);


text: Q: problems with gnuplot in 14.10 some of the useful terminal types (wxt or qt) do not exist.  With previous versions of gnuplot and ubuntu, wxt worked well.  However, Debian apparently dropped support for wxWidgets 2.8, so gnuplot no longer has an option for the wxt terminal type.  Can this be fixed, or qt be supported?


text:
Q: Impossible to select items DragonBar of Dragon NaturallySpeaking When I open Dragon NaturallySpeaking 11, I can't select the items in the DragonBar. For example I click on Tools and the items like Transcribe Recording do not work. Could you help me?

A: Your status message says that the profile is not ready for dictation. This means that the profile is opened but you have not performed an Audio Setup yet for the microphone that is attached to your computer. You have to do that before you can start dictating.


text:
Q: How to make useEffect hook call the provided effect only if all the elements in inputs change? I'm trying to convert UNSAFE_componentWillReceiveProps into a hook. Below is the logic for using CWRP.
UNSAFE_componentWillReceiveProps(nextProps){
  if (this.props.val1 !== nextProps.val1 && this.props.val2 !== nextProps.val2) {
    // do something
  }
}

Is there any way I can tell hook to call effect only when val1 & val2 changes.
useEffect(() => {
  // do something only when both inputs change
}, [val1, val2])

A: `I guess you could use a custom hook as mentioned in react documents:
function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

function MyComponent({val1, val2}) {
    let val1Prev = usePrevious(val1);
    let val2Prev = usePrevious(val2);
    useEffect(() => {
        if(val1Prev !== val1 || val2Prev !== val2) {
            // do whatever you want
        }
    })
}

Also, make attention to this sentence from react documents:

It's possible that in the future React will provide a usePrevious Hook
  out of the box since it's a relatively common use case.

A: You could use the useRef hook to store the props of the last time the effect was run and compare against that.
Example

const { useEffect, useRef } = React;

function MyComponent({ val1, val2 }) {
  const lastProps = useRef({ val1, val2 });
  useEffect(
    () => {
      if (lastProps.current.val1 !== val1 && lastProps.current.val2 !== val2) {
        console.log("Both changed!");
      }

      lastProps.current = { val1, val2 };
    },
    [val1, val2]
  );

  return
 {val1} {val2}
;
}

class App extends React.Component {
  state = { val1: 1, val2: 1 };

  componentDidMount() {
    setTimeout(() => this.setState({ val1: 2 }), 1000);
    setTimeout(() => this.setState({ val2: 2 }), 2000);
    setTimeout(() => this.setState({ val1: 3, val2: 3 }), 3000);
  }

  render() {
    const { val1, val2 } = this.state;
    return <MyComponent val1={val1} val2={val2} />;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));


text:
Q: What areas of research question the existence of the Planck length? As a follow up to What are the structures that exist at roughly the scale of the Planck length?, what areas of research question the idea of a Planck length (or Planck scale)? Or if there are no areas of research, what specific qualities make it questionable?

A: The Planck Length is equal to $1.616199 \times 10^{-35}$m which is roughly $100$ billion billionth of the diameter of a proton. It is a base unit defined in terms of the five physical constants $G, \hbar, c, (4 \pi \varepsilon_{0})^{-1}$ and $\kappa_{B}$.
No areas of current research (that I know of) question the idea of the Planck length or indeed any of the underlying physical constants listed above;


text:
Q: Remove shipping address from paypal I am using paypal-rest-sdk (the version for python) and I have some issue with the shipping address. Simple it shouldn't be there as we sell service, not items. Is there any way to keep using the PayPal sdk and remove the shipping address?

A: Actually this is a feature request and it should be fixed in the next few months.
Here is the link with more information about it:

*

*https://github.com/paypal/rest-api-sdk-python/wiki/Existing-Issues-and-Unavailable%5CUpcoming-features

*https://github.com/paypal/rest-api-sdk-php/issues/57


text:
Q: Проверка выполнения метода Есть метод
    public void Send(int one, int two)
    {
        try
        {
            using (MySqlConnection myCon = new MySqlConnection("подключ."))
            {
                MySqlCommand upd = new MySqlCommand("INSERT INTO Numbers VALUES ('one', 'two')", myCon);
                myCon.Open();
                upd.ExecuteNonQuery();
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

Скажите пожалуйста, как проверить, что он выполнился (т.е.  данные добавились и соединение не оборвалось)?

A: Убрать
catch(Exception ex)

и обработать нужное исключение там, где требуется проверить, выполнилось ли добавление.

A: Любое исключение произошедшее в try (к примеру недопустимое значение или отсутствие подключение)повлечет за собой иcисполнение кода из catch. В вашем случае это вывод ошибки...
Там где вы запускаете этот метод надо просто прописать тот же самый try-catch. При ошибке в использовании метода заработает код из catch
try{
send(int one, int two);
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}

A:
Скажите пожалуйста, как проверить, что он выполнился (т.е. данные
  добавились и соединение не оборвалось)?

По значению, которое возвращает метод ExecuteNonQuery().
В конструкции try-catch неплохо было бы первым делом ловить исключения вроде MySqlException, т.к. если это будут проблемы с подключением (Open()), то сгенерирован будет именно этот тип исключения.
После того, как подключение установлено - оперируйте значениями connection.State, вроде удобно.
Соответственно код будет выглядеть следующим образом:
try
{
    send( .. , .. );
}
catch( MySqlException ex )
{
    // ...
}
catch( Exception ex )
{
    // ...
}

A: Посмотрите на задачу с другой стороны. Вы пытаетесь в C# решить задачу, которую должна решать БД. Заверните INSERT в явную транзакцию (в принципе это не обязательно, но и вреда не будет, всегда можно откатить изменения если что-то пошло не так. MySQL это умеет с 4.какой-то версии) и все это заверните в хранимую процедуру. От C# требуется только установить соединение, передать вызов процедуры и ее параметры. Для диагностики, что все прошло удачно, верните из хранимки число в качестве кода возврата и по нему узнавайте - правильно все прошло, или случилась какая-то ошибка. Не спорю, .NET вообще и C# в частности имеют хорошую поддержку операций в БД, но все таки задачи БД должна решать БД.


text:
Q: Nicer arithmetics on primitive types in Rust Is there a nicer way of doing arithmetics on different primitive types (with auto-promotion up) than explicit casting and unwrapping?
For example in case like:
let a: u8 = 1;
let b: u16 = 2;
let c: u32 = 3;

can I somehow get rid of all the casts in:
let total: u64 = a.to_u64().unwrap() + b.to_u64().unwrap() + c.to_u64().unwrap();

A: Yes, you can use as:
let total: u64 = a as u64 + b as u64 + c as u64;

More info on type casting: http://doc.rust-lang.org/reference.html#type-cast-expressions


text:
Q: Rails 4 Nested Resources/Routes... almost there...? I have three models - users, manufacturers, and lines. I need users to have multiple manufacturers, and each manufacturer to have multiple lines. I'm to the point where lines is finally pulling the manufacturer_id on the _form, but now it's not saving the 'name' of the 'line', only the id. It'll save the 'name' as nil, like it's not passing in the name from the form. I've read the standard docs on this and I can't for the life of me get it working. It keeps hanging up on the final create stage in the controller, and I have a feeling that I've got a lot of things wrong in the paths of the form and the controller. Hoping someone will take it easy on me and help me get the whole shebang working.
user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :manufacturers
end

manufacturer.rb
class Manufacturer < ActiveRecord::Base
  belongs_to :user
  has_many :lines
end

line.rb
class Line < ActiveRecord::Base
  belongs_to :manufacturer
end

lines_controller.rb

class LinesController < ApplicationController
  before_action :set_line, only: [:show, :edit, :update, :destroy]
  before_filter :load_manufacturer

  # GET /lines
  # GET /lines.json
  def index
    @lines = Line.all
  end

  # GET /lines/1
  # GET /lines/1.json
  def show
  end

  # GET /lines/new
  def new
    @manufacturer = Manufacturer.find(params[:manufacturer_id])
    @line = @manufacturer.lines.build
  end

  # GET /lines/1/edit
  def edit
  end

  # POST /lines
  # POST /lines.json
  def create
    @line = @manufacturer.lines.build

    respond_to do |format|
      if @line.save
        format.html { redirect_to @line, notice: 'Line was successfully created.' }
        format.json { render action: 'show', status: :created, location: @line }
      else
        format.html { render action: 'new' }
        format.json { render json: @line.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /lines/1
  # PATCH/PUT /lines/1.json
  def update
    respond_to do |format|
      if @line.update(line_params)
        format.html { redirect_to @line, notice: 'Line was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @line.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /lines/1
  # DELETE /lines/1.json
  def destroy
    @line.destroy
    respond_to do |format|
      format.html { redirect_to lines_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_line
      @line = Line.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def line_params
      params.require(:line).permit(:name, :manufacturer_id)
    end

    def load_manufacturer
      @manufacturer = Manufacturer.find(params[:manufacturer_id])
    end
end

lines/_form.html.erb
<%= form_for [@manufacturer,@line] do |f| %>
  <% if @line.errors.any? %>

<%= pluralize(@line.errors.count, "error") %> prohibited this line from being saved:

      <% @line.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label :name %>

    <%= f.text_field :name %>

    <%= f.label :manufacturer_id %>

    <%= f.text_field :manufacturer_id %>

    <%= f.submit %>

<% end %>

routes.rb
Linecarder::Application.routes.draw do
  resources :manufacturers do
    resources :lines
  end

  devise_for :users
  root "pages#home"

  get "about" => "pages#about"

  match 'users/:id' => 'users#show', :via => "get"
  match '/users', :to => 'users#index', :as => "all_users", :via => "get"
  match '/users/:name' => 'users#show', via: :get, as: :public_profile
end

rake routes
                  Prefix Verb   URI Pattern                                              Controller#Action
      manufacturer_lines GET    /manufacturers/:manufacturer_id/lines(.:format)          lines#index
                         POST   /manufacturers/:manufacturer_id/lines(.:format)          lines#create
   new_manufacturer_line GET    /manufacturers/:manufacturer_id/lines/new(.:format)      lines#new
  edit_manufacturer_line GET    /manufacturers/:manufacturer_id/lines/:id/edit(.:format) lines#edit
       manufacturer_line GET    /manufacturers/:manufacturer_id/lines/:id(.:format)      lines#show
                         PATCH  /manufacturers/:manufacturer_id/lines/:id(.:format)      lines#update
                         PUT    /manufacturers/:manufacturer_id/lines/:id(.:format)      lines#update
                         DELETE /manufacturers/:manufacturer_id/lines/:id(.:format)      lines#destroy
           manufacturers GET    /manufacturers(.:format)                                 manufacturers#index
                         POST   /manufacturers(.:format)                                 manufacturers#create
        new_manufacturer GET    /manufacturers/new(.:format)                             manufacturers#new
       edit_manufacturer GET    /manufacturers/:id/edit(.:format)                        manufacturers#edit
            manufacturer GET    /manufacturers/:id(.:format)                             manufacturers#show
                         PATCH  /manufacturers/:id(.:format)                             manufacturers#update
                         PUT    /manufacturers/:id(.:format)                             manufacturers#update
                         DELETE /manufacturers/:id(.:format)                             manufacturers#destroy
        new_user_session GET    /users/sign_in(.:format)                                 devise/sessions#new
            user_session POST   /users/sign_in(.:format)                                 devise/sessions#create
    destroy_user_session DELETE /users/sign_out(.:format)                                devise/sessions#destroy
           user_password POST   /users/password(.:format)                                devise/passwords#create
       new_user_password GET    /users/password/new(.:format)                            devise/passwords#new
      edit_user_password GET    /users/password/edit(.:format)                           devise/passwords#edit
                         PATCH  /users/password(.:format)                                devise/passwords#update
                         PUT    /users/password(.:format)                                devise/passwords#update
cancel_user_registration GET    /users/cancel(.:format)                                  devise/registrations#cancel
       user_registration POST   /users(.:format)                                         devise/registrations#create
   new_user_registration GET    /users/sign_up(.:format)                                 devise/registrations#new
  edit_user_registration GET    /users/edit(.:format)                                    devise/registrations#edit
                         PATCH  /users(.:format)                                         devise/registrations#update
                         PUT    /users(.:format)                                         devise/registrations#update
                         DELETE /users(.:format)                                         devise/registrations#destroy
                    root GET    /                                                        pages#home
                   about GET    /about(.:format)                                         pages#about
                         GET    /users/:id(.:format)                                     users#show
               all_users GET    /users(.:format)                                         users#index
          public_profile GET    /users/:name(.:format)                                   users#show

A: Update the create action as below:
 def create
    @line = @manufacturer.lines.build(line_params) ## Pass the params via line_params

    respond_to do |format|
      if @line.save
        format.html { redirect_to @line, notice: 'Line was successfully created.' }
        format.json { render action: 'show', status: :created, location: @line }
      else
        format.html { render action: 'new' }
        format.json { render json: @line.errors, status: :unprocessable_entity }
      end
    end
  end

You are not passing the params that you received from the form. Hence, name of line is not getting saved in database.
Also, in order to permit the attributes for mass-assignment(strong parameters) pass them via line_params method.
UPDATE for OP's question in the comment to resolve
undefined method 'line_url'... for 'format.html { redirect_to @line, notice: 'Line was successfully created.' }'
Use this
format.html { redirect_to manufacturer_line_path(@manufacturer, @line), notice: 'Line was successfully created.' }

instead of
format.html { redirect_to @line, notice: 'Line was successfully created.' }


text:
Q: Is it possible to plant trees in minecraft earth? I've just started playing Minecraft Earth and have been experimenting with the first 8x8 tile that you get.
I cut down the tree and the leaves, but didn't get an saplings.
My question is - do you plant trees in the normal way like in standard Minecraft, or do you have to construct them entirely from blocks in your inventory?

A: You can now get saplings in tree tappables or in adventure mode when you break leaves. You can plant the saplings in the ground and wait a bit to make them grow !
Thanks PausePause for the heads up

A: You have to place down the leaves and break them with a tool (pickaxe, axe, etc.) to have a chance of getting a sapling. You don't get something every time but you can get them that way.