text:
Q: JavaBeans: Can not read Variables from JavaBeans class i got a simple programm that begins on an input form where the user fills in 3 numbers. The form action refers to a controller servlet where i store the data in the Bean class with the setter methods I have defined.
number.setNumber1(Double.parseDouble(request.getParameter("number1")));

Till now I stored the Number object in the request with
request.setAttribute("numbers", number);

and forwarded it to the output page where i could get it with ${numbers.biggestNumber ( getter-Method that simply determines the biggest Number) }. A tutorial i am using says I could also get the data directly from the Bean by using this piece of code:
<jsp:useBean id="num" scope="session" class="model.Numbers"/>
<c:out value="${num.biggestNumber}/>

but somehow the Bean uses another object of the Numbers-class. I see the advantage of this technique, because I dont have to put the Numbers object into the request. Can someone tell me how I can use the same Numbers object I stored the data before?
I already read that I shouldnt use "jsp:setProperty..." to store the data on the input page, but if i cant get the information i wrote manually to the Bean, I have to ask myself why I should use the JSP JavaBeans annotation at all.
I used the search function but could not find an answer suitable to my question, or maybe I am just not experienced enough to get them in a more advanced context... Any help would be welcome

A: if you are using this one,
request.setAttribute("numbers", number);

And using requestDispacher redirecting then at target page you can do likewise,
into JSP file :
<jsp:useBean id="numbers" scope="request" class="model.Numbers"/>
<c:out value="${numbers.biggestNumber}/>

Here,

*

*you did with wrong scope=session, means you are putting value into 'request' scope and try to pull it from session is wrong.

*also maintain name of attribute 'same' while putting/getting from scope. here, name="numbers" maintain while putting/getting

A: Okay my mistake was that I thought JavaBeans-Jsp-Tags would save time and code. Indeed I had to create a HttpSession-Object that stores the ID of the used JavaBean
HttpSession sess = request.getSession(true);
sess.setAttribute("number", number);

Now the JavaBean-Tag in my Output.jsp knows which object to use (the one created in the Input.jsp). As far as I do understand now, the only advantage of the JavaBean-Jsp-Tag above normal Parameters added to the Request is that I can use the Bean-Class in the whole Session and am not dependend on the Request-Object.


text:
Q: What is the best way to pass a List from a class and use it in other scripts? This class contain the Dialogues List:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Conversation
{
    public string conversationName;
    public List<Dialogue> Dialogues = new List<Dialogue>();
}

And I want to be able to call and use the Dialogues in another scripts without making it static.
I need to use it in this script in 3 places:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;

public class DialogueTrigger : MonoBehaviour
{
    public List<Conversation> conversations = new List<Conversation>();

    [HideInInspector]
    public int dialogueNum = 0;

    private bool triggered = false;
    private List<Dialogue> oldDialogue;

    public void TriggerDialogue()
    {
        if (triggered == false)
        {
            if (FindObjectOfType<DialogueManager>() != null)
            {
                FindObjectOfType<DialogueManager>().StartDialogue(Dialogues[dialogueNum]);
                dialogueNum += 1;
            }
            triggered = true;
        }
    }

    private void Update()
    {
        if (DialogueManager.dialogueEnded == true)
        {
            if (dialogueNum == Dialogues.Count)
            {
                return;
            }
            else
            {
                FindObjectOfType<DialogueManager>().StartDialogue(Dialogues[dialogueNum]);
                DialogueManager.dialogueEnded = false;
                dialogueNum += 1;
            }
        }
    }
}

And in this part of script:
private void EndDialogue()
    {
        dialogueEnded = true;
        if (trigger.dialogueNum == Dialogues.Count)
            canvas.SetActive(false);
        Debug.Log("End of conversation.");
    }

In all places I called it Dialogues but now it's not public static since I'm using it in a third script editor type script and it can't be static:
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

[CustomEditor(typeof(DialogueTrigger))]
public class DialogueTriggerEditor : Editor
{
    private SerializedProperty _conversations;

    private void OnEnable()
    {
        _conversations = serializedObject.FindProperty("conversations");
    }

    public override void OnInspectorGUI()
    {
        //base.OnInspectorGUI();

        serializedObject.Update();

        if (_conversations.arraySize == 0)
            _conversations.ClearArray();

        _conversations.arraySize = EditorGUILayout.IntField("Conversations Size", _conversations.arraySize);

        for (int x = 0; x < _conversations.arraySize; x++)
        {
            var conversation = _conversations.GetArrayElementAtIndex(x);

            var conversationName = conversation.FindPropertyRelative("conversationName");

            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(conversationName);

            EditorGUI.indentLevel++;
            var _dialogues = conversation.FindPropertyRelative("Dialogues");

            _dialogues.arraySize = EditorGUILayout.IntField("Dialogues size", _dialogues.arraySize);

            for (int i = 0; i < _dialogues.arraySize; i++)
            {
                var dialogue = _dialogues.GetArrayElementAtIndex(i);
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(dialogue, new GUIContent("Dialogue " + i), true);

                EditorGUI.indentLevel--;
            }

            if (_dialogues.arraySize > 0)
            {
                if (GUILayout.Button("Save Conversation"))
                {

                }
            }

            EditorGUI.indentLevel--;
            EditorGUI.indentLevel--;
        }

        serializedObject.ApplyModifiedProperties();
    }
}

And since _conversations is a SerializedProperty type It will not get the Dialogues if Dialogues will be static.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Melhor método para localizar valores em um DataTable Em uma tela de cadastro de unidade de medida, tenho que verificar se a unidade que o usuario esta querendo cadastrar, se ja existe, entao como tenho um DataGrid populado por um DataTable, pensei em percorrer o DataTable e verificar se esse ja existe.
Então fiz o codigo assim:
 //botão salvar
 private void simpleButton2_Click(object sender, EventArgs e)
    {
        //Verifico se os dois textbox estao preenchidos
        if (textBox1.Text != string.Empty && textBox2.Text != string.Empty)
        {
            // defino minha string de filtro
            string exp = "SIGLA = " + "'" + textBox2.Text + "'";
            // Executo a busca com base no meu filtro
            DataRow[] find_sigla = dat.Select(exp);

            // se o retorno da busca for 0 faz a ação
            if (find_sigla.Count() == 0)
            {
                //Insiro o valor no banco
                Classes.Cadastro.Cadastro_estqUn cad_estqun = new Classes.Cadastro.Cadastro_estqUn();
                if (cad_estqun.cadastro_unidade(textBox1.Text, textBox2.Text) > 0)
                {
                    textBox1.Text = "";
                    textBox2.Text = "";
                }
            }
            else
            {
                MessageBox.Show("Unidade de medida já cadastrada.", "Salvar", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
    }

Então ouvi dizer, que esse método tenho perca de performance, procede? alguém tem alguma solução melhor?
Obrigado.

A: Eu não confiaria no que está na DataGrid, mas sim no que está no banco de dados.
Um exemplo hipotético mas se aplica a outras situações reais:
"Seu sistema tem um servidor de banco de dados e 3 estações de trabalho. Seu usuário abriu essa tela e tinha 5 unidades de medidas, mas foi almoçar. Enquanto ele almoçava alguém cadastrou a unidade de medida que ele ia cadastrar. Vai duplicar no banco de dados se ele cadastrar depois do almoço, pois a DataGrid está desatualizada."
Nessa sua classe Cadastro_estqUn faça uma implementação que verifique no banco de dados se já existe o registro com a descrição. Seria algo assim:
public bool UnidadeMedidaUnica(string nome)
{
  string sql = "SELECT COUNT(*) FROM tbUnidadeMedida WHERE unidade_nome = @nome";
  SqlCommand cmd = new SqlComman(sql, connectionString);
  cmd.Parameters.AddWithValue("@nome", nome);
  SqlDataReader mySqlDataReader = cmd.ExecuteReader();
  int qtde = (int)cmd.ExecuteScalar();
  return qtde == 0;

}
Para melhorar ainda pode adicionar um "unique index", que vai garantir que até instruções SQL disparadas diretamente no banco de dados dupliquem registros.
CREATE UNIQUE INDEX idx_unidade_nome ON tbUnidadesMedida(unidade_nome)


text:
Q: Can you upload files to github pages via browser? I'm trying to design a music website that involves users uploading mp3 files and sharing them. Is it possible to do this with Github Pages or would I need a different hosting service? Like if I created a submit button with javascript, could the files be stored in the github repo?
Thanks.

A: GitHub Pages is designed to handle only static sites. While it is possible to use JavaScript, in order to make your concept work securely, you'd need some sort of server-side code to upload the files, which isn't possible on GitHub Pages.
In addition, GitHub and Git aren't a good fit for storing things like user uploads which don't generally need versioning. Some sort of file or object storage would be a better fit and perform much better.


text:
Q: Gr. 11 Functions - Limiting domain and range on a graphing calculator I'm trying to do a homework assignment on my graphing calculator app for my ipad (Quick graph+).
(Edit by Willie: The images are originally posted here http://imgur.com/a/XRj4g I've included them below.)

The first image at the top right is what I am trying to make on my graphing calculator. Basically I have to limit the domain when graphing. Halfway down in the red box I highlighted is the ears that we have to graph by limiting f(x)=-2abs(2x-5)+6 to a domain of 1<=x<=4
At the bottom right of the first image you can see how they insert it into the graphing calculator they use. They put f(x)=(-2abs(2x-5)+6)((x<=1)(x<=4)) however looking at the second image in the album my graphing calculator disallows that. I emailed the app creators and they said to use the "if" button. (image 3)
However when I used "if" it didn't turn out properly like I expected (image 4). I was wondering how I could go about properly graphing this function so it will limit the domain properly.
If there is any confusion in what I'm trying to do leave a comment and I'll try to explain my self further.

A: You used the if operator incorrectly. The format is
if( condition, what to do if True, what to do if False)

But you put another condition in the place of "what to do if false".
Here's an example: I want a function which is equal to $3x$ between $x=1$ and $x=4$, is equal to $x+8$ between $x=4$ and $x=5$, and is undefined otherwise. The code could be
if(x>5, ln(0), if(x>4, x+8, if(x>1, 3*x, ln(0) ) ) )

Here I'm using $\ln(0)$ with the hope that it will simply produce no output for the corresponding range, rather than halt the entire computation. Don't have the app (or iPad for that matter), so can't tell for sure.

A: You need to set the function to "undefined" when it is not in your region. Do you see any way to do that?

A: *

*Just use desmos which is more efficient and functional

https://support.desmos.com/hc/en-us/articles/203192385-Piecewise

*wtf are you doing the graphing calculator questions lol

*is a cat really worth this much time and investment


text:
Q: Calculating two columns at once in QGIS Is it possible to calculate two columns at once?
So what I mean is that we have different covers and lengths and I want a total length of "Cover A" after that a total length of cover tb and so on.
See that attached photo for the columns that I mean.

A: QGIS has an algorithm for that :

*

*Statistics by categories (official documentation)

You have to select your layer, your category field (here "Cover") and the field to calculate statistics (here "Length"). It will create a new non-geographic layer with your categories and some new statistic fields as minimum, maximum, mean, sum, etc.

You can also do a "Virtual Layer" through Layer > Add Layer > Add/Edit Virtual Layer... with a SQL query :
SELECT
    "Cover",
    SUM("Length") AS total_length
FROM
    your_table_name
GROUP BY
    "Cover"


text:
Q: I dont understad nmcli connection modify --temporary 802-11-wireless.cloned-mac-address 00:60:1B:EB:F8:73 This is from How can I set mac address using the command line in Ubuntu 16.04? , where I cannot contact the_velour_fog
I have this same problem but im stuck with the solution adonis proposed:
nmcli connection modify --temporary 802-11-wireless.cloned-mac-address 00:60:1B:EB:F8:73

Is this a command? What do I write instead of connection_name? I don't know where to find it.
nmcli connection up

If this is a whole command, do I && between them?

A: Yes, "nmcli" is a command.  It's a shortened version of NetworkManager command-line interface.  You can find it by using the "which" command, like this (but it should already be in your PATH)
[jcall@laptop ~]$ which nmcli
/usr/bin/nmcli

The 'connection name' will be something you created previously.  Your connections could be created from the command-line, but I usually just use the GUI to create them (especially wireless connections.)  You can list your connections with the command "nmcli connection show" or the abbreviated way "nmcli c s"  Here is an example of my connections...
[jcall@laptop ~]$ nmcli connection show
NAME              UUID                                  TYPE             DEVICE
Home_WiFi         c1c95bd9-78f3-4764-9922-971339702735  802-11-wireless  --
Hotel_WiFi        921ad0bf-e18e-4d90-87d9-0f1c852c3dc7  802-11-wireless  --
Google Starbucks  d5242485-ebd6-4152-a839-eaedacc49b4a  802-11-wireless  --
enp0s25           6c6036d5-4739-3540-ac21-bf7a04669ed6  802-3-ethernet   --

Finally, you need to execute the commands in order, one after the other.  You could use && to do that, if you want to create a long single-line command.  I usually just create a small script file to make things easier.  Here is my example.
[jcall@laptop ~]$ cat ~/bin/mac-changer.sh
#!/bin/bash

DEV=wlp3s0
NEWMAC=9c:d9:17:2e:ae:5f

if [ $# -lt 1 ]
then
  echo "You forgot to tell me which network to connect to..."
  echo "Please run \`nmcli con show\` for ideas..."
  exit 1
fi

if $(nmcli -t -f NAME con show | grep -q $1)
then
  nmcli connection modify --temporary $1 802-11-wireless.cloned-mac-address $NEWMAC
  nmcli connection up $1
else
  echo "Error: $1 is not a known network.  Please run \`nmcli con show\` for ideas..."
fi

A: You can either do a one whole command with && or in order. < Connection name > is the name of the wifi you are currently connected too. You dont have to input <> just the string name ex. MyWifi


text:
Q: onClick Event Listener inside a while enter code here

classesFilterWerke = [
        'skulptur',
        'malerei',
        'druck',
        'neueMedien',
        'sozialkritischs',
        'performance',
        'installation',
        'kunstImÖffentlichenRaum'
    ];

    for( var i = 0; i < classesFilterWerke.length; i++ ) {
        iNthChild = i+2
        $('.werke-filter button:nth-child('+ iNthChild +')').click(function(){
            $('.'+ classesFilterWerke[i] +'').toggle();
        })
    }

Filter:

    <button class="active btn btn-primary-outline">Skulptur</button>
    <button class="active btn btn-primary-outline">Malerei</button>
    <button class="btn btn-primary-outline">Druck</button>
    <button class="btn btn-primary-outline">Neue Medien</button>
    <button class="btn btn-primary-outline">Sozialkritisches</button>
    <button class="btn btn-primary-outline">Performance</button>
    <button class="btn btn-primary-outline">Installation</button>
    <button class="btn btn-primary-outline">Kunst im öffentlichen Raum</button>

Longboard

Skulptur

Keramikton Arbeiten

Skulptur

Stehleuchte

Skulptur

I want to make a filter which toggles elements with a certain class. My problem now is that if I use the jQuery .click Event Listener inside a while loop it doesn't work. If I get the jQuery statement outside of the while loop it works.
NOTE: I haven't used the i variable and the classesFilterWerke (Array) inside the loop because it doesn't work even without.

A: Relying on index is not the best thing. Your code already had things out of order so it would have a bug. So if you add an attribute we can simplify this code to just select that element.
I am not sure the end goal so I am just toggling a class to show it working.

$('.werke-filter').on("click", "button", function () {
  var button = $(this)
  var toggles = button.data("toggles")
  button.toggleClass("selected")
  $(toggles).toggleClass("selected")
})
.selected {
  background-color: yellow;
}

.karte {
  display: block;
}

Filter:

  <button class="active btn btn-primary-outline" data-toggles=".karte.skulptur">Skulptur</button>
  <button class="active btn btn-primary-outline" data-toggles=".karte.malerei">Malerei</button>
  <button class="btn btn-primary-outline" data-toggles=".karte.druck">Druck</button>

Longboard

Skulptur

Keramikton Arbeiten

Skulptur

Stehleuchte

Skulptur


text:
Q: Turn Bluetooth On and Off in Android 1.5 (SDK level 3)? There are tons of pay and free bluetooth toggles on the market that work with Android 1.5 (SDK level 3).  The problem is there is no visible API for this!
Does anyone have any working code snippits on how to enable and disable bluetooth that works on Android 1.5?  I assume you must have to use some kind of reflection for it.  There are some examples over on anddev.org, but they only work with Android 1.1 or lower.
This is for Android 1.5 (SDK level 3) and not Android 2.0 or greater.  In Android 2.0 or later Google added easy to use APIs.

A: This may/may not be useful to you as a better example: http://code.google.com/p/android-wifi-tether/source/browse/#svn/trunk/src/android/tether/system
It selects the right classed based on the SDK level and then uses it to enable/disable bluetooth.


text:
Q: Grep element from variable? I need to extract an element using a regular expression.
First I'm reading a file from a function, then from a second function I'm reading another file and extract a value.
When processing the read of the second function, I grep the value from the first file:
#function read file
def get_file_as_string(filename)
  data = ''
  f = File.open(filename, "r")
  f.each_line do |line|
    data += line
  end
  return data
end

Main:
file.each do |filename|
  lunsrvfile = 'server_lun.csv'
  ldev = get_file_as_string lunsrvfile
  f=File.read(filename)
  lunid = f.scan(/^"No.","time","(\h+:\h+:\h+).*/).flatten  #it's ok:  ex: 00:02:00
       if (ldev =~ /#{lunid}/) then
           server = ldev.lines.grep(lunid) #--> don't work
           #server = %x[grep lunid 'server_lun.csv' |awk -F ";" '{print $1}'] #--> don't work
           puts filename
           puts lunid
           puts server
    end
end

server_lun.csv:
server1;00:02:00
server2;00:03:25
server3;00:03:26

Thx for your answer:
yes, i aldready test it, but when i put
server = ldev.lines.grep(/#{lunid}/)

all the file(lunsrvfile) is listed.
If match i need the first value: server1 for exemple
Thx for your answer2:
but with:
server = ldev.grep(/#{lunid}/).first.split(';').first

Only the first server1 is print.
output:
filename1
lunid1
server1

filename2
lunid2
server1
(...)

A: grep requires a RegExp, you are passing it a string.   The same way you did for =~  you can do for the grep command.  Also you don't need to implement the get_file_as_string. The one liner at the top will do it for you.
I think this will do what you want:
lunsrvfile = 'server_lun.csv'
ldev = File.open(lunsrvfile, "rb").read

file.each do |filename|
  f = File.read(filename)
  lunid = f.scan(/^"No.","time","(\h+:\h+:\h+).*/).flatten  #it's ok:  ex: 00:02:00
  if (ldev =~ /#{lunid}/) then
    server = ldev.lines.grep(/#{lunid}/)
    puts filename
    puts lunid
    puts server
  end
end

A: You can read file into array this way
ldev = IO.readlines lunsrvfile

Then
ldev.grep /#{lunid}/

will return only string with that server
To get just server name you can try for example:
ldev.grep(/#{lunid}/).first.split(';').first


text:
Q: Sentence-final "at which time" replacing "at this time" – Latino variety, or idiolect? I just landed at LAX and the flight attendant (who had a slight Latino accent, but was a native or near-native English speaker) gave the last announcement:

"As we prepare to land please have cups and other items ready to throw away, as we're going to make one last pass through the cabin at which time." Full stop.

There were several such utterances during the flight which ended with "at which time," each of which was clearly meant to signify "at this time." Is this a common usage in a variety of English I'm unfamiliar with, or is it more likely to be this one speaker's quirk?

A: But in your example, "at which time" doesn't mean "at this time."  This refers to the proximate; that refers to the distant; which refers to its antecedent.  In the context of contemporaneous direct speech, the proximate refers to the time of speaking.  The standard "one last pass through the cabin" will occur shortly, presumably after the attendant stops talking.  We know this because the attendant says "we're going to."  Presently, the attendant will say

The captain has just turned off the seatbelt sign, and at this time
  you may leave your seats and retrieve your luggage from the overhead
  bins.

This isn't an invitation to travel back in time a few moments to get up; it means you can get up as the attendant speaks.
So the attendant can talk about that time just mentioned:

... as we're going to make one last pass through the cabin, and at that time [you may dispose of your trash].

of save the conjunction:

... as we're going to make one last pass through the cabin, at which time [you may dispose of your trash].

A: This article at Englishpage.net says of at which time

It functions as a conjunction.

This is, I'd say, its only normal role with the 'at the time specified' sense†, so it requires a sensible main clause to follow it.

The hotel closed for two weeks last February, at which time essential
  repairs were carried out.
*The hotel closed for two weeks last February, essential repairs being carried out at which time.

Compare:

The hotel closed for two weeks last February, and/when essential
  repairs were carried out.
*The hotel closed for two weeks last February, essential repairs being carried out and/when.

†As Jesse Sielaff wisely points out, usages like

"I need to keep track of which event happens at which time"
'At which time is it best to phone you?'

where the sense is 'when[?]', complicate the picture. These are adverbial usages.


text:
Q: How an interface knows whick class' implementation to use? First of all, let me clarify my understanding of an interface.
Real World Scenario
In a real-world scenario, any vehicle having an engine must implement the functionality of the start engine. A CAR cannot be a CAR without an engine and the same goes for a motorbike. In programming terms, both Car and Bike classes must have a startEngine() method to be a Car & a Bike. But How? Here interfaces come into play. Interfaces enforce some classes or objects to implement specific methods to make the class more in sync with concrete reality.
The Problem
Let's assume I have a VehicleController class and I want to call startEngine() methods of Car and Bike classes by implementing
VehicalInterface on both Car and Bike classes.
interface VehicalInterface {
    public function startEngine();
}

class Car implements VehicalInterface {
    public function startEngine() {
        // Start the engine of CAR
    }
}

class Bike implements VehicalInterface {
    public function startEngine() {
        // Start the engine of BIKE
    }
}

class VehicleController extends Controller
{
    public function start(VehicalInterface $vehical)
    {
        $vehical->startEngine();
    }
}

My question is if a user wants to start the engine of a bike, let's say in a game, how VehicalInterface will decide that bike's class' implementation be used?

A: Let's start with a simple definition of what an interface is:

An interface is basically a contract in which you can define what methods a class has
to obey/implement.

Now let's have a look at the question you are asking:

How/where is decided which class definition to call when an implemented method is called?

The answer I'm gonna give could be hard to comprehend:
The actual type of the object does not matter
The type could be a Motorcycle, Car, Bus,... As long as the object implements the interface VehicalInterface we can be certain the method startEngine actually exist.
How the Vehicle actually starts the engine, or start driving, does not matter for the program, it can be done by turning the key, pulling a rope, pushing it downhill. It does not matter in any way, as long as the vehicle just starts to drive/roll.
This concept is basically called abstraction.
By implementing an interface to a class, you are also appointing an (extra) type to your class. This can actually be seen in your own code as well
public function start(VehicalInterface $vehical)

The code above will tell the interpreter that the argument passed to the method start should have the type VehicalInterface, by doing so the interpreter will also know the method startEngine exists and can be called.

Here is another example that is maybe easier to understand.

Imagine you go shopping. You put everything you need inside the basket and you want to check-out and you go the cashier.
In order to know the price the customer has to pay, every items needs to be scanned and every items has to report it's price to the cashier in order to know the total amount the customer has to pay.
<?php
    class Checkout {
        protected $total_price = 0.00;

        public function scanItems(array $items) {
            for($items as $item) {
                $this->total_price += $item->getPrice();
            }
            return $this;
        }

        public function getTotalPrice() {
            return $this->total_price;
        }
    }

    interface ICartItem {
        public function getPrice();
    }

    class Apple implements ICartItem {
        ...
        public function getPrice() {
            return $this->getUnitPrice() * $this->getWeight();
        }
        ...
    }

    class Cereal implements ICartItem {
        ...
        public function getPrice() {
            return $this->getUnitPrice();
        }
        ...
    }

    class Curtain implements ICartItem {
        ...
        public function getPrice() {
            return $this->getPricePerSquareFoot() * $this->getArea();
        }
        ...
    }

As you can see above, the "crucial" part for the class Checkout is that it needs to know the price of an item. It does not care how the price is calculated, it only has to be certain it receives back a certain price so it can calculate what the total price is that the customer has to pay.

By using the interface ICartItem in the example above, we can be sure that if the shop suddenly starting selling new items, .e.g. UnknownItem, the class Checkout doesn't needs to be modified, as long as UnkownItem implements the interface ICartItem


text:
Q: Counting the restaurants with a specific rating mysql I have a table of tripadvisor data. There are columns (restaurant, rank, score, user_name,review_stars,review_date,user_reviews....) and other columns that are not useful for my question...
I am trying to return each restaurant with how many 3-star reviews they have and list them using the rank column from high to low.
I know i can use count, i was thinking of count if ( review_stars=3) and then order by rank to return it... i am stuck and any help would be appreciated. Thank you.

A: What you are wanting to accomplish is counting how many 3 star reviews each restaurant has ..
You really are almost there --  Your original question really does contains all the answers, just written out in long-hand.  Think about what you are asking:
"I need to SELECT the restaurants that have 3 star reviews and count how many there are per restaurant"  --  The basic syntax you are missing is GROUP BY --  Which groups all of your results per restaurant to a single row.
SELECT restaurant, count(*) as 3_star_count from table where review_stars = '3' GROUP BY restaurant

This is a basic example.  But from what you are asking .. This syntax should get you the number of 3 star reviews for each restaurant.
I would recommend that you look into SQL clauses and what they mean as @Alexis stated in an earlier comment.  The WHERE clause and the GROUP BY clause (especially this one) are what you want to understand here.


text:
Q: VBA Excel - Executing a command in a Range - Interacting w/ other workbooks I have been trying how to figure this out for awhile now. I locked my vba project, because I don't want most people to be able to altered the code. The problem is, I have code that modifies other modules based on user input, this obviously would cause a problem as, you cannot modify a module if it is locked. Being how I just don't do 'sendkeys' (lol c'mon), there is no practical way to unlock it so I can modify the code.
So I created an .xlam add-in. The module writes the new code to file, saves it as a .bas type, then the add-in imports and runs it.
But...
I am having trouble interacting with the workbook (the one that generated the module for the .xlam add-in). Below are the portions of the code that I am finding tricky. It is primarily related to performing autofill and updating a form with said workbook.
public sub wbUpdate()
    Dim wb as workbook
    Set wb = workbooks("WB.xlsm")
    Dim lastRow as long

    '======example #1====== not sure my autofill syntax is right:
    Worksheets("Sheet1").Select
    lastRow = wb.worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).row
    k = lastRow
    wb.worksheets("Sheet1").Range("B2").Select
    wb.worksheets("Sheet1").Range("B2").value = ""

    'below is where I get a runtime error, not sure why
    wb.worksheets("sheet1").Range("B2").AutoFill _
        Destination:=wb.worksheets("Sheet1").Range("B2:B" & lastRow)

    '======Example #2====== Try to show a userForm and center
    'but can't seem to get the syntax right

    With wb.progressBar '<== runtime error on @ this line
        .StartUpPosition = 0
        .Left = Application.Left + (0.5 * Application.Width) - (0.5 * .Width)
        .Top = Application.Top + (0.5 * Application.Height) - (0.5 * .Height)
        .Show
    End With
End Sub

These are the primary issues. Personally, I would rather just run code directly from the worksheet (in other words think of a module executing what something in say Range("A1") - like "msgbox someString") but I am not sure if this is even possible. Been wondering this one for quite awhile
Any pointers on what the syntax should be for example #1 and #2 -- And/Or ideas on how to execute code directly from a sheet, thereby bypassing the headache all together?


text:
Q: Unity Project Convert in iOS I want to convert my iOS project to Unity. Kudan Framework is used in Unity project. It is displaying two errors in XCode:

*

*Error verifying license key for bundleID: com.bundleid.app error: (null)

*API key not valid

A: Are you using either your licensed key (or the provided sample API keys and the correct bundle identifier for each key)
https://wiki.kudan.eu/Development_License_Keys


text:
Q: IDIV: Checking Boundaries The IDIV documentation (found here) has this weird line that says:
if(Temporary > 0x7FFFFFFF || Temporary < 0x80000000) Exception(DE); //f a positive result is greater than 7FFFFFFFH or a negative result is less than 80000000H

What exactly is the point of this error checking? It fails if we do something like 0x80000000/-1, but it doesn't seem intuitive as to why this would do anything of use.
Note in particular that this isn't at all the case with IMUL found here.

A: idiv's dividend input (the concatenation of rdx:rax) is twice as wide as the output and divisor operands.  So the result can easily fail to fit if the divisor isn't big enough.
This rarely happens in practice, though.  It's common to simply sign-extend rax into rdx with a cltq (AT&T mnemonic), aka cdq / cqo (Intel/NASM mnemonic), so this usually never comes up.  128b dividend inputs would only come up in extended-precision situations.  (Compilers of course prefer to use 128 by 64 -> 64 bit division for 64bit operands, to easily support cases where the divisor doesn't fit in 32 bits.  Similarly for 32 and 16bit operands.  This could come up for int64_t / int32_t in 32bit-mode, though.  The compiler would know that the promoted 32bit variable would be all-zero in the upper 32, and could directly do a single idiv.  Except if the result didn't fit into 32b...)
Intel's insn ref manual (see links in the x86 tag wiki) comments that "Overflow is indicated with the #DE (divide error) exception rather than with the CF flag."  IDK why they made that choice, instead of only erroring on division by zero or something.


text:
Q: How to find the variance of a random sample with exponential distribution? This will seem like a very simple question to many of you; but I cannot understand part of the solution, so to give context I have had to unfortunately resort to typing the whole thing out, apologies.
Start of Question:

$100$ independent measurements (i.e. samples) are made of a random variable, which
  has an exponential distribution $\lambda e^{−\lambda x}$, and their average is found. Consider the probability distribution of this average. The expectation value of this distribution will be $\lambda^{-1}$.
What is the standard deviation of the distribution?

End of Question.

Start of Solution:

The sum of the $100$ values of $x$ is $$X=\sum_{i=0}^{i=N}x_i$$ and has an expectation value $$E(x)=\sum_{i=0}^{i=N}E(x_i)=N\cdot E(x)$$
Since $E(x) \propto x$, the expectation value of the average $\overline{x}=\dfrac{X}{N}$ is
  $$E\Big(\overline{x}\Big)=\dfrac{N\cdot E(x)}{N}=E(x)=\color{blue}{\dfrac{1}{\lambda}}$$ $\color{blue}{\fbox{$\text{as stated in the question}$}}$. Similarly, for the Variance
  $$Var(x)=\sum_{i=1}^{i=N}Var(x_i)=N\cdot Var(x)$$ Since $Var(x)\propto x^2$, the variance of the average $\overline{x}=\dfrac{X}{N}$ is
  $$Var\Big(\overline{x}\Big)=\dfrac{N\cdot Var(x)}{N^2}=\dfrac{1}{N}\cdot \color{red}{Var(x)}=\dfrac{1}{100}\cdot \color{red}{\dfrac{1}{\lambda^2}}\tag{?}\label{}$$ The Standard Deviation is therefore
  $$\sqrt{Var\Big(\overline{x}\Big)}=\dfrac{1}{10\lambda}$$

End of Solution.

I understand why $E(x)=\color{blue}{\dfrac{1}{\lambda}}$ as it was stated in the question as shown by the $\color{blue}{\mathrm{blue}}$ box. But what I don't understand is why $\color{red}{Var(x)}\stackrel{\eqref{*}}=\color{red}{\dfrac{1}{\lambda^2}}$. Could someone please explain to me how this was worked out?

A: We have
$$E(X^2)=\int_0^\infty x^2 \lambda e^{-\lambda x}dx=\frac{2}{\lambda^2}$$
So,
$$Var(X)=E(X^2)-E(X)^2=\frac{2}{\lambda^2}-\frac{1}{\lambda^2}=\frac{1}{\lambda^2}$$


text:
Q: javascript: Access object properties through variable I want to access a Javascript Object dynamicly.
Example:
example: {
    name: "dev.pus",
    year: 2012,
    os: "linux"
}

This isn't anything new. Now you normaly can access properties of the "example" with:
console.log(example.name);
// or
console.log(example.year);

But what is if I want to take the attribute dynamicly?
For example, another var (lets assume the user sets it) should decide which property we want:
var = "name";
console.log(example.var); // error
console.log(example[var]); // error

What is the way to go?

A: Your example should work if you'll change your variable name (var is reserved).
var key = 'name';
console.log(example[key]);

You can also iterate over your object to get all keys:
for (var item in example){
    if (example.hasOwnProperty(item)){
      console.log(example[item]);
    }
}

http://jsfiddle.net/bC9XJ/


text:
Q: Dynamics CRM: How do I make a javascript function trigger every time a field/control on the form gains focus? I'm on version 2016, if that matters.
I have a javascript function that I need called every time a field on the form gains focus.
My end goal is to make it so if a lookup field gains focus, the text is auto-highlighted so there's no need to click it again before editing.
I just need to know how to get a function called each time a field gains focus on the form and can take it from there. Thanks.


text:
Q: PyDev Setting breakpoints in doctests Is it possible to set breakpoints in doctests, using PyDev (i.e. eclipse)? I found that while I am seemingly able to do so, the breakpoints do not work at all.
To have some code in the question, and to clarify, say I have
def funct():
  """
  >>> funct()
  Whatever
  """
  print "Whatever"

and that I set a breakpoint at the funct() call in the doctest. Can I do that?
PS: I know I can do
>>> import pdb; pdb.set_trace()

to have a prompt in a doctest, but I would prefer not inserting such lines.

A: I don't think you can set breakpoints in strings.
doctest is a module for automated testing. If you need to debug your doctest code, why not run it normally and verify the output, then once you know it works, throw it into a docstring?


text:
Q: complex sql tree rows table structure
id    |    message    |    reply_id
1     |    help me!   |    0
434   |    love to    |    1
852   |    didn't work |    434
0110  |    try this   |    852
2200  |    this wont  |    0
5465  |    done. :)   |    0110

i have a id "852" which is middle of tree menu, but i want to get all the previous related and next related rows, so i want to get following results like this:

help me! >  love to > didn't work > try this > done. :) (this result shows like that after php loop, but starts looping from starter id 1 with reply id 0.

NOTE: 2200 id didn't show in the result, because its not part of the group.

A: There are several alternatives for making hierarchical information easier to work with in SQL:

*

*Common Table Expressions (per the SQL-2003 standard) support recursive SQL queries against the parent-id type of data you're using.  So far, MySQL does not support this feature.  PostgreSQL 8.4, Microsoft SQL Server, and IBM DB2 are examples of RDBMS brands that support CTE syntax.  Oracle also has a proprietary extension to SQL syntax that supports recursive queries.

*Nested Sets (the left/right solution that @phantombrain mentions) is a solution detailed in Joe Celko's book "Trees and Hierarchies in SQL for Smarties" and also in numerous articles and blog postings on the internet.

*Path Enumeration (aka Materialized Path) stores a string in each row in the hierarchy to note the path of ancestors of that row.  Combine this with LIKE queries to compare the path string to its ancestors' paths and descendants' paths.

*Closure Table (aka Transitive Closure Relation) uses a second table to store all ancestor-descendant relationships, not just the immediate parent as in the design you're using.  Many types of queries become easier once you have all the paths stored.

*Hybrid solutions also exist.  For example, store the immediate parent id as you're doing, but also the root of the tree.  Now you can get all other rows in the same hierarchy, fetch them into application code, and sort out the tree with conventional data structures.

A: Assuming these are menu items and not something very dynamic, such as a forum, I would recommend a schema change to add left and right values for each item.  The IDs between the left and right values are all children of the node you are querying.  Thus, it's easy to do one query to get the left/right values, and a second query to get the sub items.
See http://www.sitepoint.com/print/hierarchical-data-database/ for more information

A: Recursion is the most elegant way to do this, but I don't think mySql supports it in custom functions or storedprocedures. I would suggest a loop into a temp table or table variable to get your IDs, then join the table and query the results back.  I don't know mySql very well so this is untested, but something to this effect.
CREATE TEMPORARY TABLE tbl (myid int, ViewOrder int);
Set @ifoundID=IdYourLookingFor;
Set @iStartID=@ifoundID;
Set @iOrder=0;
INSERT INTO tbl(myid,ViewOrder)VALUES(@ifoundID,@iOrder);

BEGIN --get the ones going up
 WHILE (@ifoundID Is Not Null) DO
  SELECT @ifoundID=reply_id FROM YourTable WHERE id=@ifoundID; --find the next id
  SET @iOrder1=@iOrder-1; --increment the order
  INSERT INTO tbl(myid,ViewOrder)VALUES(@ifoundID,@iOrder);--save the nextid
 END WHILE;
END

Set @ifoundID=@iStartID;
BEGIN --get the ones going down
 WHILE (@ifoundID Is Not Null) DO
  SELECT @ifoundID=id FROM YourTable WHERE reply_id=@ifoundID; --find the next id
  SET @iOrder1=@iOrder+1; --increment the order
  INSERT INTO tbl(myid,ViewOrder)VALUES(@ifoundID,@iOrder);--save the nextid
 END WHILE;
END

SELECT * FROM tbl INNER JOIN YourTable ON tbl.myid=YourTable.id ORDER BY ViewOrder

Hope that helps


text:
Q: Zoom in/out on a point of a function: I have taken a code on this site (Edit/Guess by Manuel Kuehner: Plotting several functions with TikZ/pgf)
\documentclass{article}

\usepackage[latin1]{inputenc}
\usepackage{tikz}

\begin{document}
\pagestyle{empty}

\begin{tikzpicture}[domain=0:4]
  \draw[very thin,color=gray] (-0.1,-1.1) grid (3.9,3.9);
  \draw[->] (-0.2,0) -- (4.2,0) node[right] {$x$};
  \draw[->] (0,-1.2) -- (0,4.2) node[above] {$f(x)$};
  \draw[color=red] plot (\x, \x) node[right] {$f(x) =x$};
  \draw[color=blue] plot (\x, { sin(\x r) }) node[right] {$f(x) = \sin x$};
  \draw[color=orange] plot (\x, { 0.05*exp(\x) })
    node[right] {$f(x) = \frac{1}{20} \mathrm e^{x}$};
\end{tikzpicture}

\begin{tikzpicture}[domain=0:4]
  \draw[very thin,color=gray] (-0.1,-1.1) grid (3.9,3.9);
  \draw[->] (-0.2,0) -- (4.2,0) node[right] {$x$};
  \draw[->] (0,-1.2) -- (0,4.2) node[above] {$f(x)$};
  \draw[color=red] plot (\x, {-\x / 3 + 1/5}) node[right] {$f(x)$};
  \draw[color=blue] plot
    (\x, { 1/2 * \x + 1/2 - 1/2 * sqrt(5 * \x^2 + 2*\x + 1)})
    node[right] {$g(x)$};
\end{tikzpicture}

\end{document}

and I would like to have a zoom with a magnifying glass on a generic point of the graph using only the coordinates. That is, fixing generic coordinates I wondered if there was a general command to view a particular of the graph. This is the result I would like to get.

Thank you.

A: I guess that you are looking for the so-called spy feature of tikz (not pgfplots, but you can use it within pgfplots). In the pgfplots manual you find an example:

Here's a screenshot of the corresponding chapter for pgf/tikz:

% https://tex.stackexchange.com/questions/200354
\documentclass{article}

\usepackage[latin1]{inputenc}
\usepackage{tikz}
\usetikzlibrary{spy} % <-- added

\begin{document}
\pagestyle{empty}

\begin{tikzpicture}[
    domain=0:4,
    spy using outlines={circle, magnification=4, size=2cm, connect spies}, % <-- added (pgf manual example)
    ]
  \draw[very thin,color=gray] (-0.1,-1.1) grid (3.9,3.9);
  \draw[->] (-0.2,0) -- (4.2,0) node[right] {$x$};
  \draw[->] (0,-1.2) -- (0,4.2) node[above] {$f(x)$};
  \draw[color=red] plot (\x, \x) node[right] {$f(x) =x$};
  \draw[color=blue] plot (\x, { sin(\x r) }) node[right] {$f(x) = \sin x$};
  \draw[color=orange] plot (\x, { 0.05*exp(\x) })
    node[right] {$f(x) = \frac{1}{20} \mathrm e^{x}$};

    \spy [red] on (1.6,0.3) in node [left] at (3.5,-1.25); % <-- added (pgf manual example)
\end{tikzpicture}

\begin{tikzpicture}[domain=0:4]
  \draw[very thin,color=gray] (-0.1,-1.1) grid (3.9,3.9);
  \draw[->] (-0.2,0) -- (4.2,0) node[right] {$x$};
  \draw[->] (0,-1.2) -- (0,4.2) node[above] {$f(x)$};
  \draw[color=red] plot (\x, {-\x / 3 + 1/5}) node[right] {$f(x)$};
  \draw[color=blue] plot
    (\x, { 1/2 * \x + 1/2 - 1/2 * sqrt(5 * \x^2 + 2*\x + 1)})
    node[right] {$g(x)$};
\end{tikzpicture}

\end{document}


text:
Q: How to transport data from a server to an Android device, by using data compression? I am writing an application which downloads data from a server and displays it. The data consists of text, video, audio and picture files. The data is downloaded in so called data-bundles.  A data-bundle can consist of a collenction of all data types, ranging from a few kilobytes to many hundreds of megabytes. The reason for too large data-bundles are video files.
Server is written in Go and the application is written Java (Android).
Question: Which compression algorithm would be the best way to go, if I want to transmit data-bundles (small and large)? Is Deflate enough, or should I consider a more sophisticated approach?

A: First of all, I assume that your video, audio and image files are already compressed with a lossy algorithm. In that case, you usually won't be able to compress the data (much) using an additional, different compression algorithm. If the text data is usually just a small part of the entire data-bundle, I don't think I would bother applying any further compression at all, since adding complexity to your software for a very small overall gain is not justified. For example, if you combine a 10MB audio file with a 5kB text file and could be able to compress the text to 1kB (which is probably much better than what you'd achieve in reality), the complete size of the data bundle would only be reduced from 10.005MB to 10.001MB, or by 0.04%.
If the amount of text is generally so high, that you can justify the compression, Android supports inflate/deflate and gzip using the standard Android API. There are also 3rd party Java libraries for bzip2 and lzma(2), which I suppose would compile without modifications for Android (I haven't tried though). A quick Google search finds gzip, bzip2 and lzma implementations for Go as well.
These algorithms generally compress the data better at the cost of higher computing costs and memory requirements in this order: deflate, gzip, bzip2, lzma. Especially the lzma encoder/decoder may require more memory than actually available to an Android application. Especially the compressor requires relatively much memory, the decoder not so much if you keep to smaller dictionaries.


text:
Q: How to do subsequent calls on same url via Nock having different status code Problem:
I want to mock a situation in which on the same http call I get different results. Specifically, the first time it fails.
To some extent this is similar to Sinon capability of stub.onFirstCall(), stub.onSecondCall()
Expectation:
I expected that if I use once on the first call and twice on the second call I would be able to accomplish the above.
nock( some_url )
    .post( '/aaaa', bodyFn )
    .once()
    .reply( 500, resp );
nock( some_url )
    .post( '/aaaa', bodyFn )
    .twice()
    .reply( 200, resp );

A: The correct way is to simply
call Nock twice.
nock( some_url )
    .post( '/aaaa', bodyFn )
    .reply( 500, resp );
nock( some_url )
    .post( '/aaaa', bodyFn )
    .reply( 200, resp );

The way Nock works is that each call registers an interceptor for some_url.
In fact the first time you call some_url will clear the first interceptor and so on.
as stated in docs:

When you setup an interceptor for a URL and that interceptor is used,
  it is removed from the interceptor list. This means that you can
  intercept 2 or more calls to the same URL and return different things
  on each of them. It also means that you must setup one interceptor for
  each request you are going to have, otherwise nock will throw an error
  because that URL was not present in the interceptor list. If you don't
  want interceptors to be removed as they are used, you can use the
  .persist() method.


text:
Q: How to I make the text to change if i click on the screen I'm trying to figure out how to make a dialogue system that shows the text and after you click it removes all the text in the box and new text appears in its place. (I want to be able to do this multiple times)

var container = document.querySelector(".text");

var speeds = {
  pause: 400,
  slow: 120,
  normal: 50,
  fast: 20,
  superFast: 10
};

var textLines = [{
    speed: speeds.slow,
    string: "this is a test"
  },
  {
    speed: speeds.pause,
    string: "",
    pause: true
  },
  {
    speed: speeds.normal,
    string: "pls help me"
  },
  {
    speed: speeds.fast,
    string: "idk what im doing",
    classes: ["red"]
  },
  {
    speed: speeds.normal,
    string: ":("
  }
];

var characters = [];
textLines.forEach((line, index) => {
  if (index < textLines.length - 1) {
    line.string += " ";
  }

  line.string.split("").forEach((character) => {
    var span = document.createElement("span");
    span.textContent = character;
    container.appendChild(span);
    characters.push({
      span: span,
      isSpace: character === " " && !line.pause,
      delayAfter: line.speed,
      classes: line.classes || []
    });
  });
});

function revealOneCharacter(list) {
  var next = list.splice(0, 1)[0];
  next.span.classList.add("revealed");
  next.classes.forEach((c) => {
    next.span.classList.add(c);
  });
  var delay = next.isSpace && !next.pause ? 0 : next.delayAfter;

  if (list.length > 0) {
    setTimeout(function() {
      revealOneCharacter(list);
    }, delay);
  }
}

setTimeout(() => {
  revealOneCharacter(characters);
}, 600)

const btn = document.getElementById('btn');
html,
body {
  height: 100%;
  width: 100%;
}

.text span {
  opacity: 0;
}

.text span.revealed {
  opacity: 1;
}

.text span.green {
  color: #27ae60;
}

.text span.red {
  color: #ff0000;
}

body {
  background: #3498db;
  padding: 3em;
  font-family: 'Sora', monospace;
}

.text {
  font-size: 6vw;
  word-spacing: 0.2em;
  margin: 0 auto;
  background: #fff;
  padding: 1em;
  border-bottom: 1vw solid #0e6dad;
  position: relative;
  line-height: 1.2em;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />

  <button id="textchanger"> continue </button>

so far all I'm able to make from this is a single phrase appear on the screen and that's about it. to change it, I have to go in manually.

A: I make (almost) all the js from scratch because it would have been really hard to refactor your code in order to achieve what you want, what I've done seems to work, it is pretty straightforward :

const container = document.querySelector(".text");
const btn = document.querySelector("#textchanger");

// rename speeds in delays which is more coherant
const delays = {
  slow: 120,
  normal: 50,
  fast: 20,
  superFast: 10
};

const textLines = [
  {
    delay: delays.slow,
    string: "this is a test"
  },
  {
    delay: delays.normal,
    string: "pls help me"
  },
  {
    delay: delays.fast,
    string: "idk what im doing",
    classes: ["red"]
  },
  {
    delay: delays.normal,
    string: ":("
  }
];

const revealLine = (lineIndex = 0) => {
  const line = textLines[lineIndex]
  let charIndex = 0

  const nextChar = () => {
    const char = line.string[charIndex]
    const span = document.createElement('span')

    span.textContent = char
    span.classList.add(...(line.classes ?? []))

    container.appendChild(span)

    charIndex++

    if (charIndex < line.string.length)
      setTimeout(nextChar, line.delay);
    else if (lineIndex + 1 < textLines.length) {
      const cb = () => {
        // remove this listener to display the next one
        btn.removeEventListener('click', cb)

        // clear the container
        Array.from(container.children).forEach(el => el.remove())

        // reveal the next line
        revealLine(lineIndex + 1)
      }

      btn.addEventListener('click', cb)
    }
  }

  nextChar()
}

revealLine()
html,
body {
  height: 100%;
  width: 100%;
}

.text span.green {
  color: #27ae60;
}

.text span.red {
  color: #ff0000;
}

body {
  background: #3498db;
  padding: 3em;
  font-family: 'Sora', monospace;
}

.text {
  font-size: 6vw;
  word-spacing: 0.2em;
  margin: 0 auto;
  background: #fff;
  padding: 1em;
  border-bottom: 1vw solid #0e6dad;
  position: relative;
  line-height: 1.2em;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

  <button id="textchanger"> continue </button>


text:
Q: How can I generate data with a prespecified correlation matrix? I'm trying to generate correlated random sequence with mean = $0$, variance = $1$, correlation coefficient = $0.8$. In the code below, I use s1 & s2 as the standard deviations, and m1 & m2 as the means.
p = 0.8
u = randn(1, n)
v = randn(1, n)
x = s1 * u + m1
y = s2 * (p * u + sqrt(1 - p^2) * v) + m2

This gives me the correct corrcoef() of 0.8 between x and y. My question is how can I generate a series means if I want z that is also correlated with y (with the same correlation $r=0.8$), but not with x. Is there a particular formula I need to know? I found one but couldn't understand it.

A: If you're using R, you can also use the mvrnorm function from the MASS package, assuming you want normally distributed variables. The implementation is similar to Macro's description above, but uses the eigenvectors of the correlation matrix instead of the cholesky decomposition and scaling with a singular value decomposition (if the empirical option is set to true).
If $X$ is a matrix with entries drawn from a normal distribution, $\Sigma$ is a positive definite correlation matrix with eigenvectors $\gamma$, and $\lambda$ is a square matrix with the square root eigen values from $\Sigma$ along the diagonal then:
$X' = \gamma\lambda X^{T} $
Where X' is a normally distributed matrix with correlation matrix of $\Sigma$ and column means are the same as $X$.
Note that the correlation matrix have to be positive definite, but converting it with the nearPD function from the Matrix package in R will be useful.

A: It appears that you're asking how to generate data with a particular correlation matrix.
A useful fact is that if you have a random vector ${\bf x}$ with covariance matrix $\Sigma$, then the random vector ${\bf Ax}$ has mean ${\bf A} E({\bf x})$ and covariance matrix $ \Omega = {\bf A} \Sigma {\bf A}^{T} $. So, if you start with data that has mean zero, multiplying by ${\bf A}$ will not change that, so your first requirement is easily satisfied.
Let's say you start with (mean zero) uncorrelated data (i.e. the covariance matrix is diagonal) - since we're talking about the correlation matrix, let's just take $\Sigma = I$. You can transform this to data with a given covariance matrix by choosing ${\bf A}$ to be the cholesky square root of $\Omega$ - then ${\bf Ax}$ would have the desired covariance matrix $\Omega$.
In your example, you appear to want something like this:
$$ \Omega = \left( \begin{array}{ccc}
1 & .8 & 0 \\
.8 & 1 & .8 \\
0 & .8 & 1 \\ \end{array} \right) $$
Unfortunately that matrix is not positive definite, so it cannot be a covariance matrix - you can check this by seeing that the determinant is negative. Perhaps, instead
$$ \Omega = \left( \begin{array}{ccc}
1 & .8 & .3 \\
.8 & 1 & .8 \\
.3 & .8 & 1 \\ \end{array} \right) \ \ \ \ {\rm or} \ \ \ \Omega = \left( \begin{array}{ccc}
1 & 2/3 & 0 \\
2/3 & 1 & 2/3 \\
0 & 2/3 & 1 \\ \end{array} \right)$$
would suffice. I'm not sure how to calculate the cholesky square root in matlab (which appears to be what you're using) but in R you can use the chol() function.
In this example, for the two $\Omega$s listed above the proper matrix multiples(respectively) would be
$$ {\bf A} = \left( \begin{array}{ccc}
1 & 0 & 0 \\
.8 & .6 & 0 \\
.3 & .933 & .1972 \\ \end{array} \right) \ \ \ \ {\rm or} \ \ \ {\bf A} = \left( \begin{array}{ccc}
1 & 0 & 0 \\
2/3 & .7453 & 0 \\
0 & .8944 & .4472 \\ \end{array} \right)$$
The R code used to arrive at this was:
x = matrix(0,3,3)
x[1,]=c(1,.8,.3)
x[2,]=c(.8,1,.8)
x[3,]=c(.3,.8,1)
t(chol(x))

     [,1]      [,2]      [,3]
[1,]  1.0 0.0000000 0.0000000
[2,]  0.8 0.6000000 0.0000000
[3,]  0.3 0.9333333 0.1972027

x[1,]=c(1,2/3,0)
x[2,]=c(2/3,1,2/3)
x[3,]=c(0,2/3,1)
t(chol(x))

      [,1]      [,2]      [,3]
[1,] 1.0000000 0.0000000 0.0000000
[2,] 0.6666667 0.7453560 0.0000000
[3,] 0.0000000 0.8944272 0.4472136

A: An alternative solution without cholesky factorization is the following.
Let $\Sigma_y$ the desired covariance matrix and suppose you have data $x$ with $\Sigma_x = I$. Suppose $\Sigma_y$ is positive definite with $\Lambda$ the diagonal matrix of the eigenvalues and $V$ the matrix of column eigenvectors .
You can write $\Sigma_y = V \Lambda V^T = ( V \sqrt{\Lambda} ) (\sqrt{\Lambda}^T V^T ) = A A^T$.
$y=Ax$ generate the desired data.


text:
Q: google datastore query with embedded collection of items We have a Kind containing objects like the following example stored in google datastore. (firestore in datastore mode now)
{
"id": "xxx"
"date": "xxx"
"array": [
        {
            "itemid": "xxx"
            "param1": "xxx"
            "subarray": [
                {
                    "subparam1": "xxx",
                    "subparam2": "xxx",
                },
                {
                    "subparam1": "xxx",
                    "subparam2": "xxx",
                }
            ]
        },
        {
            "itemid": "xxx",
            "param1": "xxx",
            "subarray": [
                {
                    "subparam1": "xxx",
                    "subparam2": "xxx",
                },
                {
                    "subparam1": "xxx",
                    "subparam2": "xxx",
                }
            ]
        },
    ]
}

what is the best way to:

*

*retrieve a list of subarray for a given id and where date>datetime("2021-10-19T20:00:00.00000+02:00") in the form

id / date / subarray_content

*

*retrieve a list of subparam1 for a given id and where date>datetime("2021-10-19T20:00:00.00000+02:00") in the form

id / data / itemid / subparam1

can they be expressed in GQL?
what indexes should be created for them?
(yes it is easy to retrieve objects matching id and criteria on date and filter the results programmatically but it is not very efficient)
thanks


text:
Q: Will Cobalt provide reference cdm (content decryption module) for widevine/playerady drm porting? As far as I know, cobalt will support widevine/playready drm playback, and we are trying to port on our platform with TEE support.
We have already done the starboard/player.h porting and I want to say the reference code for player did a great help! But when I try to start starboard/drm.h porting (at Cobalt 6.14197), I only find a little code related to drm. (e.g Starboard_decryptor, some stub implementation for drm.h API).
Do we need to implement our own content decryption module to handle license parsing, policy, etc., or will cobalt provide the reference cdm (which will be great) and we can use our OEMCrypto module to finish the rest part?

A: Cobalt is able to support any DRM system compatible with the Encrypted Media Extensions, but this has only been fully proven out with both PlayReady and Widevine on deployed products.
Licensing makes it difficult to provide an open-source reference integration with Widevine or PlayReady, so it is currently up to the platform implementer to integrate the code to generate license challenges, install keys, and decrypt samples before decoding. Note that you should not need to change any code in src/media to do this, you should be able to accomplish this by only implementing Starboard player/drm/media APIs.
You may be able to directly contact the business entities involved to get access to a non-open-source reference implementation.


text:
Q: Does Oracle 11gR2 is supported on RHEL 8 or Oracle Linux 8? Oracle (afaik) did not updated their compatibility matrix yet. Can I run Oracle 11gR2 (which still is in extended suporte) in the new OS?

A: Most likely you can run it without any issues but it is not supported by Oracle. As Phil suggests in his comment this combination will never be supported as you are mixing an almost out of support database (extended is over on December 2020) with a just added Linux release.
Best solution is use Oracle 12.2 which, in my experience, is a minimal problem migration target for most applications using Oracle 11.  The 12.2 release allows an easy upgrade to Oracle 18 or 19 when the time comes.


text:
Q: Flink Stateful Functions 2.0 Multiple Calls During Asynchronous Wait Flink Stateful Functions 2.0 has the ability to make asychronous calls, for example to an external API:
[https://ci.apache.org/projects/flink/flink-statefun-docs-release-2.0/sdk/java.html#completing-async-requests][1].
Function execution is then paused until the call completed with Success, Failure, or Unknown.  Unknown is:

The stateful function was restarted, possibly on a different machine,
  before the CompletableFuture was completed, therefore it is unknown
  what is the status of the asynchronous operation.

What happens when there is a second call with the same ID to the paused/waiting function?

*

*Does the callee then wait on the called function's processing of
its async result so that this second call executes with a clean,
non-shared post-async state?

*Or does the second call execute on a
normal schedule, and thus on top of the state that was current as of
the async call, and then when the async call completes it continues
processing using the state that was updated while the async call was
pending?

*Or maybe the call counts as a "restart" of the called
function - in which case what is the order of execution: the
"restart" runs and then the async returns with "restart" to execute
from the now updated state, or this order is reversed?

*Or something else?

A: Function execution does not pause while an async request is completing. The instance for that id will continue to process messages until the request completes. This means the state can change while the future is running.
Think of your future as an ad-hoc function that you message and that then messages you back when it has a result. Functions can spawn multiple asynchronous requests without issue. Whichever future completes first will be processed first by the function instance, not necessarily the order in which they were spawned.


text:
Q: JQuery Modal won't tie-in with dotnet ClientID Simple problem which is causing enormous headaches.
I'm using the JQuery modal plugin (jqm) which is normally initiallised with a function that looks like this:
 $().ready(function () {
    $('#popup').jqm({ trigger: $('.trigger') });
 });

Where #popup is the ID of the element you want to show when the modal is displayed and 'trigger is the css class of elements which cause the modal to be displayed.
This works find with static ID's, but as soon as you replace the #popup ID with a dynamic clientID the whole thing falls over:
 $().ready(function () {
    $('#<%= popup.clientID %>').jqm({ trigger: $('.trigger') });
 });

I'm not sure why this is happening - I assume there's some sort of timing issue with the javascript initialising before the element in question has had it's dynamic ID assigned. Certainly once the page is loaded, looking at the ID's in the element and in the JavaScript function they match as expected. I've tried placing the javascript directly in the page and also injecting it dynamically with REgisterStartUpScript but neither work.
Any suggestions gratefully received.
Cheers,
Matt

A: You could use a class selector:
$(function() {
    $('.popup').jqm({ trigger: $('.trigger') });
});

and assign the popup class to the DOM element you would like to attach the modal to.
Also maybe I am wrong but wasn't $().ready(function () a deprecated syntax (I remember having read about it somewhere but don't recall exactly at the moment)?


text:
Q: Knative on GKE is not working with some images, shows RevisionMissing error I am running Knative on a GKE cluster. The sample images provided on the Knative website work but when I switch to some other images, it stops working. Only 2 containers work out of 3 and route's ready state remains 'unknown' and Reason shows as 'RevisionMissing'.
I tried with multiple images, k8s.gcr.io/hpa-example is one of them.
Edit: The cluster has a two-node of configuration of type n1-standard-4 (4 vCPUs, 15 GB memory). I created this cluster using the GCP console with the latest version of kubernetes, and checking the Enable Istio checkbox. I used following commands to install the Knative:
kubectl apply --selector knative.dev/crd-install=true \
-f https://github.com/knative/serving/releases/download/v0.8.0/serving.yaml \
-f https://github.com/knative/eventing/releases/download/v0.8.0/release.yaml \
-f https://github.com/knative/serving/releases/download/v0.8.0/monitoring.yaml

kubectl apply \
-f https://github.com/knative/serving/releases/download/v0.8.0/serving.yaml \
-f https://github.com/knative/eventing/releases/download/v0.8.0/release.yaml \
-f https://github.com/knative/serving/releases/download/v0.8.0/monitoring.yaml

Thanks

A: Ok, I found the problem. I tried posting custom images. All worked until I change the port (inside image) to 80. This image not only work as Knative service, but also, It did not work on Cloud run service as well.
Bottom line is, either pull port number from environment variable, or hard code it to any other port than 80.

A: Thanks for the precisions.
When you installed Knative you should see this kind of errors
# Without CRD
unable to recognize "https://github.com/knative/serving/releases/download/v0.8.0/serving.yaml": no matches for kind "Gateway" in version "networking.istio.io/v1alpha3"
unable to recognize "https://github.com/knative/serving/releases/download/v0.8.0/serving.yaml": no matches for kind "Gateway" in version "networking.istio.io/v1alpha3"
unable to recognize "https://github.com/knative/serving/releases/download/v0.8.0/serving.yaml": no matches for kind "Image" in version "caching.internal.knative.dev/v1alpha1"
unable to recognize "https://github.com/knative/eventing/releases/download/v0.8.0/release.yaml": no matches for kind "ClusterChannelProvisioner" in version "eventing.knative.dev/v1alpha1"

# Without CRD
Error from server (NotFound): error when creating "https://github.com/knative/serving/releases/download/v0.8.0/monitoring.yaml": namespaces "istio-system" not found
Error from server (NotFound): error when creating "https://github.com/knative/serving/releases/download/v0.8.0/monitoring.yaml": namespaces "istio-system" not found
Error from server (NotFound): error when creating "https://github.com/knative/serving/releases/download/v0.8.0/monitoring.yaml": namespaces "istio-system" not found
Error from server (NotFound): error when creating "https://github.com/knative/serving/releases/download/v0.8.0/monitoring.yaml": namespaces "istio-system" not found

You didn't have installed Istio. Do it, relaunch the knative installation (with and without CRD) to solve previous errors and enjoy!!!


text:
Q: In Xcode 5, is there a shortcut to move up one option in the autocomplete list? For example, I'm currently on viewDidUnload. Pressing Ctrl+n will let me go to the next option(viewWillAppear). Is there a shortcut to make the cursor go up one option(viewDidLoad)?

.
I know this is tedious, but it's been very annoying to me because I don't want to move my hand to the up and down key every time I type a variable.
Thanks!

A: I don't know about XCode in particular but in similar situations in other apps I find Ctrl-P is the usual counterpart to Ctrl-N ("previous" vs. "next" perhaps?).  These are the standard bindings in the Emacs editor, along with Ctrl-B and Ctrl-F for left and right ("backward" and "forward" respectively).


text:
Q: NServiceBus Outbox pattern with SQL question Im trying to figure out how exactly outbox is suppose to work with NServicebus but I'm not quite sure I get it. Here is the current scenario that we have:
Service1
Service2
Service3
ServiceN
Each of the services has its own database where it holds business data and servicebus shared database used for queue/message broker.
This means that each of these services is using the same connection string for servicebus and has different connection string for business database.
The problem we are facing is that saving into business database and publishing is technically saving into 2 databases, so this will create distributed transaction if wrapped into transaction.
Now, Im considering implementing outbox pattern to solve this problem, but NServiceBus documentation doesnt really give us an idea regarding this question:

*

*Where should Outbox table be stored? Is it suppose to be stored in a same database as bussiness data? Where will the subsciption data be stored in this case for given service? Is it possible to configure NServicebus to create outbox table into bussiness database while the rest of the tables are created in service bus database?

By enabling outbox NServiceBus indeed creates new table for holding messages servicename_Outbox table, but should it be stored into Servicebus database or business data database? If its stored in servicebus database then, technically to save data into it it still needs distributed transaction?

*

*How does servicebus know which table to pool for Outbox pattern and to dispatch messages? Can this be explicitly configured?

A:
Where should Outbox table be stored? Is it suppose to be stored in a same database as bussiness data?

Yes

Where will the subsciption data be stored in this case for given service?

If you use message driven pubsub instead of native pubsub then yes.

Is it possible to configure NServicebus to create outbox table into bussiness database while the rest of the tables are created in service bus database?

Yes, that is expected.

but should it be stored into Servicebus database or business data database? If its stored in servicebus database then, technically to save data into it it still needs distributed transaction?

Outbox data is stored in the business database and share the same storage connection/transaction so does not require a distributed transaction.

How does servicebus know which table to pool for Outbox pattern and to dispatch messages?

Each endpoint has its own entity.

Can this be explicitly configured?

Please check the outbox configuration for the persister that you are using to see if the table name van be configured:
https://docs.particular.net/persistence/


text:
Q: show by induction if there exists a $n_0 \in \mathbb N $such that $n\geq n_0 , n! \gt 2n^3$ I tried and I got there doesn't exist such a $n_0$
However, I dun think I have a formal proof for this.
My approach is, First assume there is such a $n_o$ exist
and start my calculation with induction
$(n+1)!\\
  =(n+1)n!\\
   \gt(n+1)2n^3 (Induction Premise)\\
= 2n^4 + 2n^3\\
\gt 2n^3+6n^2+6n+1 , n \geq 3 \\
= 2(n+1)^3
$
So I get $n_0$ = 3, But when I subsitute back to the original equation, it doesn't work,
so, what can i conclude?
It doesn't exist such a $n_0$?

A: You need a base case.  You're right that $n_0=3$ doesn't work, but that does not mean that there is no $n_0$ that works.  What you've shown is that for your inductive step to work, you will need $n$ to be at least $3$, but there is still the requirement that you get the inequality to hold once in the first place.
So, one way to proceed is to find an $n_0>3$ for which the inequality holds, then prove by induction that the inequality holds for all $n\geq n_0$.
In fact, you can make your induction step a little easier by taking $n_0$ (very) slightly larger than necessary.  If $n\geq 7$, then $2(n+1)^3<2(2n)^3=8(2n^3)\leq(n+1)2n^3$.


text:
Q: RSelenium I am scraping yahoo finance and on financial tables there are "quarterly" and "expand all" clicks. When I inspect on buttons gives me <button class= expandPF Fz(s)....................." and I don't how to do it in CSS. the link and my code is;
webElem <- remDr$findElement(using = "class", ".expandPf")

But it gives error. I also tried using = "CSS" but same error.

Please Help!! :)) Thanks in advance

I also tried;
> webElem <-remDr$findElement("xpath", "//*[@id='Col1-1-Financials-Proxy']/section/div[2]/button/div/span")$clickElement()

Selenium message:No active session with ID b3685d1143434ead399da8235261106f

Error:   Summary: NoSuchDriver
     Detail: A session is either terminated or not started
     Further Details: run errorDetails method

but get this error.
If anyone has an idea please help :))

A: You can try using xpath to click Expand and Collapse
url = 'https://finance.yahoo.com/quote/ADESE.IS/financials?p=ADESE.IS'
library(RSelenium)
driver = rsDriver(port = 4492L, browser = c("firefox"))
remDr <- driver[["client"]]
remDr$navigate(url)
remDr$findElement('xpath', '//*[@id="Col1-1-Financials-Proxy"]/section/div[2]/button')$clickElement()


text:
Q: how to combine angular2 with jinja2 templates and flask I'm getting started on Angular 2 after much success with Angular 1. I followed both the Quickstart and the Tour of Heroes tutorials and everything works like a charm.
The lite server gets kicked off, I see tsc running in watch mode and I even see BrowserSync is hooked up. Great!
However, I need to start making things a bit more real world.
Instead of using lite server, how do I get all this working using a flask dev or gunicorn server, serving the initial index.html file as a rendered jinja template?
Giving the flask dev server a very näive try, I basically copy the contents of the example index.html from the tutorial into my jinja template, then run npm run tsc:w and finally fire up my flask dev server and hope for the best. Things compile fine. But in the browser I see problems:
angular2-polyfills.js:332 Error: SyntaxError: Unexpected token <
    at ZoneDelegate.invoke (http://127.0.0.1:5000/static/node_modules/angular2/bundles/angular2-polyfills.js:332:29)
    at Zone.run (http://127.0.0.1:5000/static/node_modules/angular2/bundles/angular2-polyfills.js:227:44)
    at http://127.0.0.1:5000/static/node_modules/angular2/bundles/angular2-polyfills.js:576:58
Evaluating http://127.0.0.1:5000/app/main.js
Error loading http://127.0.0.1:5000/app/main.js`

Looking at the culprit transpile main.js file I see:
(function(System, SystemJS, require) {<!doctype html>
<html>
<head lang='en'>

So, yeah, that's not gonna work...clearly my wiring is haywire.
There is a lot of black magic going on with the shims, the polyfills, reactive extensions, systemjs, angular2 itself, and then toss in tsc and lite server. Admittedly, I don't have all this down yet and it will take time, but I'm hoping to get my project into a sane state fairly quickly.
(I don't mind using lite server (BrowserSync is a nice perk) in development as long as I can configure it to proxy the real flask server which will return the render jinja templates.)
Update
Here is the actual template index file with some minor changes that I've made:
<!doctype html>
<html>
  <head lang="en">
    {% block head %}

    <meta charset="utf-8">

    <title>Angular 2 QuickStart</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
    <!-- IE required polyfills, in this exact order -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>

    {% endblock %}
  </head>
  <!-- 3. Display the application -->
  <body>
    {% block content %}{% endblock %}

    <my-app>Loading...</my-app>

    <script>
      (function(globals) {
        this.MyConfig = {
          staticDir: '{{ config["STATIC_DIR"] }}'
        };
      }(this));
    </script>
  </body>
</html>

A: I had the same problem and here is how I solved it;
Step 1
With a directory structure as follows:
+- MyAppName
+-- ServerApp
+--- //...flask files here
+-- ClientApp
+--- node-modules
+--- app
+--- //...more node+angular application files
I exposed the ClientApp folder in my flask application at the URL .../client-app/... using the following code:
from flask import Flask, send_from_directory
import os

BASE_URL = os.path.abspath(os.path.dirname(__file__))
CLIENT_APP_FOLDER = os.path.join(BASE_URL, "ClientApp")

# This is required by zone.js as it need to access the
# "main.js" file in the "ClientApp\app" folder which it
# does by accessing "<your-site-path>/app/main.js"
@app.route('/app/<path:filename>')
def client_app_app_folder(filename):
    return send_from_directory(os.path.join(CLIENT_APP_FOLDER, "app"), filename)

# Custom static data
@app.route('/client-app/<path:filename>')
def client_app_folder(filename):
    return send_from_directory(CLIENT_APP_FOLDER, filename)

Step 2
Head over to your index.html file (I placed mine at ServerApp\templates\index.html so that I could simply do render_template('index.html')) and make it look something like this:
<html>
  <head>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="client-app/assets/css/style.css">

    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="client-app/node_modules/es6-shim/es6-shim.min.js"></script>

    <script src="client-app/node_modules/zone.js/dist/zone.js"></script>
    <script src="client-app/node_modules/reflect-metadata/Reflect.js"></script>
    <script src="client-app/node_modules/systemjs/dist/system.src.js"></script>

    <!-- 2. Configure SystemJS -->
    <script src="client-app/systemjs.config.js"></script>
    <script src=""></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

the 'client-app' prepended to the paths is the route I chose to expose my client_app_folder() function at
Step 3
Configure your client application's package finder to use the set route ('client-app/...' in this case). I use system.js and therefore I made my systemjs.config.js file look like this:
(function(global) {

  // map tells the System loader where to look for things
  var map = {
    'app':                        'client-app/app', // 'dist',
    'rxjs':                       'client-app/node_modules/rxjs',
    'angular2-in-memory-web-api': 'client-app/node_modules/angular2-in-memory-web-api',
    '@angular':                   'client-app/node_modules/@angular'
  };

  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' },
  };

  var packageNames = [
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    '@angular/router-deprecated',
    '@angular/testing',
    '@angular/upgrade',
  ];

  // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
  packageNames.forEach(function(pkgName) {
    packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
  });

  var config = {
    map: map,
    packages: packages
  }

  // filterSystemConfig - index.html's chance to modify config before we register it.
  if (global.filterSystemConfig) { global.filterSystemConfig(config); }

  System.config(config);

})(this);

I only modified the map variable
Godspeed!

A: When looking for the answer to this same question I was reminded about changing the interpolation characters in angular 1. Could find where two do that for angular 2, but it was simple enough to change on the jinja2 side. Set the jinja2 environment options characters however you want with this:
JINJA_ENV = jinja2.Environment(
  loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
  extensions=['jinja2.ext.autoescape'],
  block_start_string= '{[%',
  block_end_string='%]}',
  variable_start_string='{[',
  variable_end_string=']}',
  comment_start_string='{#',
  comment_end_string='#}',
  autoescape=True
)

Hopefully I am using compatible strings here, guess I will find out!
(see http://jinja.pocoo.org/docs/dev/api/ environment options)


text:
Q: Spyder failing to launch - "could not find or load the Qt platform plugin windows" I've recently had to do a fresh install of windows and reinstall all the software I was previously using including anaconda.
I still have all the data from before the reinstall. To save me from pip installing all the packages I was using, I thought it would be easier to copy and paste the environment info from pre windows reinstall (left image) into the environment folder of the freshly installed anaconda (right).(Information/Folders in question)
I'm getting this error message when I try to launch Spyder.
Juypter notebook seems to be working fine but I get the error shown when I attempt to launch Sypder in the 'imported environment' TensorFlow1.8CPU.
Can anyone tell me how to resolve this?
I'm also open to hear any other ways of importing the environment from pre windows install anaconda folder.

A: I solved this problem by installing spyder with a lower version.


text:
Q: BASH: determine which of three strings is in a file I need to determine which of three strings is found in a file. It is guaranteed that only one of the three is found in the file. Then I want to do a different thing based on which of the three is in the file.
I am currently trying to do:
myfile="/home/directory/file.xml"
case "stringOne" in
    *$myfile*)
    #Do thing A
    ;;
esac
case "stringTwo" in
    *$myfile*)
    #Do thing B
    ;;
esac
case "stringThree" in
    *$myfile*)
    #Do thing C
    ;;
esac

however, this is not working, and my program gets stuck. Is there a better way, or a quick way to fix this way?

A: Since the file is guaranteed to contain one of them, you can find which one it is and the use case statements:
myfile="/home/directory/file.xml"
str=$(grep -o -m 1 -E 'stringOne|stringTwo|stringThree' $myfile)

[[ -z ${str} ]] && { echo "No match found!"; exit 1; }

case "${str}" in
    stringOne)
       #Do thing A
       ;;

    stringTwo)
       #Do thing B
       ;;

    stringThree)
       #Do thing C
       ;;

esac

grep options:

*

*-o will print only the matching word. So you know which word is there in the input file.

*-m 1 will ensure it stops at first match. So it doesn't need to scan the rest of the file.

*-E is for regex match that match which is to match either one of the three strings.

A: You can read the file data once and then check each string's presence:
data=$(</home/directory/file.xml)

if [[ $data == *stringOne* ]]; then
   echo "process stringOne"
elif [[ $data == *stringTwo* ]]; then
   echo "process stringTwo"
elif [[ $data == *stringThree* ]]; then
   echo "process stringThree"
fi


text:
Q: Push notifications behaviour while app running in background (Parse/Unity/Android) I've been trying Parse's integration tutorials and examples, and I can't figure out how to make the push notifications show in tray when the app is running in background.
Notifications do appear when the app is closed, though!
Also, when in foreground, push notification events do trigger correctly.
Summing up, push notifications work perfectly except when running in background.
The notification shows in the log like this:

07-02 04:43:06.979: I/GCM(22111): GCM message com.parse.parseunitypushsample 0:1435804985959681%368c544ef9fd7ecd
07-02 04:43:07.033: W/GCM-DMM(22111): broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE pkg=com.parse.parseunitypushsample (has extras) }
07-02 04:43:07.041: I/ParsePushService(16145): Push notification received. Payload: {"alert":"A test push from Parse!","push_hash":"2bf06f5e2a92eab2fcb855fc1117fa33"}
07-02 04:43:07.041: I/ParsePushService(16145): Push notification is handled while the app is foregrounded.

Notice it says "foregrounded", even when some other app is in foreground. This bothers me a bit, as if Parse decided not to show the notification because it concludes that it's on foreground. Just my guess.
I'm using:

*

*Unity 5.1.1f1 (free)

*Android 5.1.1

*Parse and tutorial project provided here: https://parse.com/apps/quickstart#parse_push/unity/android/new (with only modifications needed to make it run in Unity 5.x)

*Provided manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  package="com.parse.parseunitypushsample" android:versionCode="1" android:versionName="1.0">

    <uses-sdk android:minSdkVersion="10" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:protectionLevel="signature" android:name="com.parse.parseunitypushsample.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.parse.parseunitypushsample.permission.C2D_MESSAGE" />

    <application android:label="@string/app_name" android:icon="@drawable/app_icon">
        <!-- Added "com.unity3d.player" below to avoid crash -->
        <activity android:name="com.unity3d.player.UnityPlayerActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="com.parse.ParsePushBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
               <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="com.parse.parseunitypushsample" />
            </intent-filter>
        </receiver>

        <service android:name="com.parse.ParsePushService" />
    </application>
</manifest>

I'm just building the tutorial project, but it needs Unity upgrade, and a couple small fixes to run. Otherwise, it's clean and seems to correctly receive push notifications, but not showing them while running on background.
Is that the expected behaviour, or am I doing something wrong?
Thank you :)

A: If you got that, then you are almost there! I think you need to add this script to one of your GameObjects:
using UnityEngine;
using System.Collections;
using Parse;

    public class ParsePushRegistration : MonoBehaviour {
        // Use this for initialization
        void Start () {
            #if UNITY_ANDROID
            ParsePush.ParsePushNotificationReceived += (sender, args) => {
                AndroidJavaClass parseUnityHelper = new AndroidJavaClass ("com.parse.ParseUnityHelper");
                AndroidJavaClass unityPlayer = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
                AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject> ("com.unity3d.player.UnityPlayerNativeActivity");

                // Call default behavior.
                parseUnityHelper.CallStatic ("handleParsePushNotificationReceived", currentActivity, args.StringPayload);
            };
            #endif
        }
    }

Check and keep track of this question, it might be usefull to you:
Parse Unity Push Sample not working

A: Not sure if this helps, but I was able to work around this by editing the plugin source available here. To do this I simply cached the string value of the push msg in the ParsePushUnityHelper.java class and then retrieved it from Unity c# via Android CallStatic method. You can then use one of the publicly available Json modules to convert this from a json string to a dictionary. Keep in mind you'll have to recompile and link the plugin .jar to your Unity project. Good luck!


text:
Q: Executing PostgreSql database function or stored procedure from spring boot JPA data initializer My database uses some functions to get some stuff done on data, in which I am trying not to have too much outside of code base.
Especially, when we run the application in a different environment like developer's local computer.
I would not to have to always manually create database functions/stored procedure for every Spring boot installation.
I attempted to initialise this using data.sql in /resources/data.sql
It is picking up, but results in errors.
CREATE SEQUENCE IF NOT EXISTS _wcode_seq
START WITH 8000
MAXVALUE 9999999999999
MINVALUE 1
^;
CREATE SEQUENCE IF NOT EXISTS _comcode_seq
START WITH 4000
MAXVALUE 99999999999999
MINVALUE 1
^;

CREATE SEQUENCE IF NOT EXISTS ggg_po_seq
START WITH 2000
MAXVALUE 99999999999999
MINVALUE 1
^;

CREATE OR REPLACE FUNCTION public.createreference()
RETURNS trigger
LANGUAGE 'plpgsql'
COST 100
VOLATILE NOT LEAKPROOF
AS $BODY$
begin
if(new.barcode is null) then

 if(new.consignment is true) then
    select nextval('_comcode_seq') into new.barcode;
    new.barcode := 'COM'||lpad(new.barcode,4,'0');
 else
    select nextval('_wcode_seq') into new.barcode;
    new.barcode := 'W'||lpad(new.barcode,4,'0');
end if;
select nextval('_po_seq') into new.po_code;
new.po_code := 'PO'||lpad(new.po_code,4,'0');
end if;

return new;
end^;
$BODY$^;

CREATE TRIGGER _refenence_ts
before insert
on watch
for each row
EXECUTE PROCEDURE createReference()^;

My issue maybe a syntax errors, but working well when executed on database GUI(Table Plus)


text:
Q: I want to make the fonts bigger in the Stack Exchange iOS app I think the fonts in the Stack Exchange iOS app are too small, and I want to regulate the length of them. Could you add this function?

A: You should be able to do this using iOS Settings by navigating to General, then Accessibility and then to Larger Fonts.


text:
Q: Power supply for 1.7A stepper motors I am an amateur making my own CNC machine.  This involves manufacturing or buying all component parts as appropriate. I am trying to understand what power supply I will have to provide to operate the stepper motors that I intend to use. Even though I will buy a suitable power supply if possible, I still need to design the system to suit the current required and the appropriate voltage to make the system operate properly but safely.
I'm told that 'just applying Ohms law' will not tell me the voltage I need but I don't understand how to work out what is needed.
I will have 3 stepper motors rated at 1.7A maximum each, with 1.5 Ohm coils. The driver ICs are A4988 rated at 35V, 2A max.
What would be the optimal power supply to use with 3 of these stepper motors and 3 A4988 drivers + GRBL stepper motor driver card
I am confused because the motors don't mention Voltage anywhere in their datasheet.

CNC Shield V3.0 features:
Latest CNC Shield Version 3.0
GRBL 0.8c compatible. (Open source firmware that runs on an Arduino UNO that turns G-code commands into stepper signals)
4-Axis support (X, Y, Z , A-Can duplicate X,Y,Z or do a full 4th axis with custom firmware using pins D12 and D13)
2 x End stops for each axis (6 in total)
Spindle enable and direction
Coolant enable
Uses removable Pololu A4988 compatible stepper drivers. (A4988, DRV8825 and others)
Jumpers to set the Micro-Stepping for the stepper drivers. (Some drivers like the DRV8825 can do up to 1/32 micro-stepping )
Compact design.
Stepper Motors can be connected with 4 pin molex connectors or soldered in place.
Runs on 12-36V DC. (At the moment only the Pololu DRV8825 drivers can handle up to 36V so please consider the operation voltage when powering the board.)
aliexpress link for the shield

A: Voltage is not mentioned in the motor datasheet because proper driving of stepper motors is done by controlling the current through their windings, not their voltage.
What is typically done is that you have a supply that must provide a voltage way higher than what is theoretically required (here 1.7Ohm * 1.5A = 2.55V), and you have a stepper driver that will chop this voltage before providing them to the windings, to ensure that the rated current (1.5A) is never exceeded. That will lead to a voltage across the windings that has a high peak at the beginning, and then decays to finally reach the steady state voltage. This way of driving the stepper will ensure best speed and torque performances.
In short: You can choose the voltage you want (higher is supposed to be better because it will drive the motors more easily, but stay within the specifications of the drivers you choose). Just ensure that the supply will be able to supply the peak current required a per the motor specifications.


text:
Q: MySQL Conditional Group By BigQuery I have the below table. I want to aggregate a few columns and GROUP BY store. The issue is if the upc is negative and there is a corresponding positive upc I  want it to always select the positive number. If there is not corresponding positive upc then keeping the negative is fine. Also when I try to run a similar query on Google BigQuery (which to my understanding uses MySQL)
 and leave out upc from the GROUP BY I get a error "SELECT list expression references column upc which is neither grouped nor aggregated". Any idea why BigQuery is behaving differently than MySQL workbench and how to force the query to always take the positive upc?
Thanks
CREATE TABLE upc (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
store  VARCHAR(30) NOT NULL,
amount DOUBLE,
total INT,
upc INT
);

INSERT INTO upc (store, amount, total, upc) VALUES
    ('123', 12.3, 1, 123),
    ('123', 45.6, 2, -666),
    ('789', 78.9, 3, 789),
    ('789', 78.9, 3, 789),
    ('456', 78.9, 3, -456),
    ('456', 78.9, 3, -456),
    ('123', 78.9, 3, 123);

SELECT store, SUM(amount), SUM(total), upc FROM upc
GROUP BY store;

A: BigQuery does not use MySQL. If you want a positive value of upc, then compute the MAX of the column:
SELECT store, SUM(amount), SUM(total), MAX(upc)
FROM upc
GROUP BY store;

A: Another variation is in using ANY_VALUE() instead of MAX() to eliminate computing the MAX function, which incurs an extra cost - this can apply to really high volume'd data. On small data this might be not even visible
#standardSQL
SELECT store, SUM(amount), SUM(total), ANY_VALUE(upc)
FROM `project.dataset.upc`
GROUP BY store


text:
Q: Question on UART parity check verilog source code Why is parity_value equal to value of 1 ?
check_parity verilog source code

module check_parity(clk, serial_in, received_data, data_is_valid, is_parity_stage, rx_error); // even parity checker

input clk, serial_in, data_is_valid, is_parity_stage;
input [7:0] received_data;
output reg rx_error = 0;

reg parity_value; // this is being computed from the received 8-bit data
reg parity_bit;  // this bit is received directly through UART

always @(posedge clk)
begin
    parity_value <= ^(received_data);
end

always @(posedge clk)
begin
    if (is_parity_stage)
        parity_bit <= serial_in;
end

always @(posedge clk)
begin
    if ((data_is_valid) && (parity_bit != parity_value))
        rx_error <= 1;
end

endmodule

A: I don't see any particular problem with your code as illustrated.  I would assume that either:

*

*received_data has a 0 time glitch to a non-zero value at the clock edge.  If you know how to enable delta cycles on your simulator you can investigate that.  You have events firing.  Are any of them affecting received_data?

*If your simulator behaves like Martin's and treats ^(exp) as !(exp) then your simulator is buggy.

If you run this code the first three columns should be equal
module top;

reg [3:0] a;

initial begin
   for (int i = 0; i < 16; i++) begin
      a = i;
      $display("%0d %0d %0d %0d", a[3] ^ a[2] ^ a[1] ^ a[0], ^a, ^(a), !a);
   end
end

endmodule