text:
Q: Removing unused information from JSON I am currently working with a SonicWall router. I am trying to get some information from it for a project. I am connecting to it via SSH and I have selected JSON as an output format to get all the information. The problem I have is the following. For simple commands the returned is pretty straightforward to parse but for more complex ones the returned JSON might not valid.
Here is a short example (these are NAT policies):
    {
    "success": true,
    "cli": [
        { "command": [ { "token": "nat-policy" }, { "token": "inbound" }, { "token": "X1" }, { "token": "outbound" }, { "token": "X1" }, { "token": "destination" }, { "token": "name" }, { "token": "WAN Primary IP" }, { "token": "service" }, { "token": "name" }, { "token": "SNMP" } ] },
        { "submode": [
            { "command": [ { "token": "id" }, { "token": "0" } ] },
            { "command": [ { "token": "inbound" }, { "token": "X1" } ] },
            { "command": [ { "token": "outbound" }, { "token": "X1" } ] },
            { "command": [ { "token": "source" }, { "token": "any" } ] },
            { "command": [ { "token": "translated-source" }, { "token": "original" } ] },
            { "command": [ { "token": "destination" }, { "token": "name" }, { "token": "WAN Primary IP" } ] },
            { "command": [ { "token": "translated-destination" }, { "token": "original" } ] },
            { "command": [ { "token": "service" }, { "token": "name" }, { "token": "SNMP" } ] },
            { "command": [ { "token": "translated-service" }, { "token": "original" } ] },
            { "command": [ { "token": "enable" } ] },
            { "command": [ { "token": "comment" }, { "token": "Management NAT Policy" } ] },
            { "command": [ { "token": "exit" } ] }
        ] },
      { "command": [ { "token": "end" } ] }
    ] }

So as far as I can understand the return JSON contains a field "success" and a field "cli" which contains a field "command" that is a list of tokens and a field "submode" that is a list of commands that each hold a list of tokens.
I would like to remove the field "command" along with the list of token it holds so the result would be something like this:
{
"success": true,
"cli": [
    { "submode": [
        { "command": [ { "token": "id" }, { "token": "0" } ] },
        { "command": [ { "token": "inbound" }, { "token": "X1" } ] },
        { "command": [ { "token": "outbound" }, { "token": "X1" } ] },
        { "command": [ { "token": "source" }, { "token": "any" } ] },
        { "command": [ { "token": "translated-source" }, { "token": "original" } ] },
        { "command": [ { "token": "destination" }, { "token": "name" }, { "token": "WAN Primary IP" } ] },
        { "command": [ { "token": "translated-destination" }, { "token": "original" } ] },
        { "command": [ { "token": "service" }, { "token": "name" }, { "token": "SNMP" } ] },
        { "command": [ { "token": "translated-service" }, { "token": "original" } ] },
        { "command": [ { "token": "enable" } ] },
        { "command": [ { "token": "comment" }, { "token": "Management NAT Policy" } ] },
        { "command": [ { "token": "exit" } ] }
    ] }
] }

In essence I would only like to keep the "submode" field with the command list.
I am doing this in Java and cannot find a way to substring the returned JSON to get the expected result. Can anyone help with this?

A: You can use java jsonp:
JsonReader reader = Json.createReader(myJsonStream);
JsonObject obj = reader.readObject();

JsonBuilderFactory factory = Json.createBuilderFactory(null);
JsonObject myJson = factory.createObjectBuilder()
    .add("success", obj.get("success"))
    .add("cli", factory.createArrayBuilder()
        .add(factory.createObjectBuilder()
            .add("submode", obj.getJsonArray("cli").getJsonObject(1).get("submode")))).build();

FileOutputStream fs = new FileOutputStream("my_new_json_path");
JsonWriter wr = Json.createWriter(fs);
wr.writeObject(myJson);
wr.close();

Is bind to your json structure but it works!


text:
Q: Why does it show that the variable "img" is not defined even though it is global? This is a simple application to make a browse button to allow the user to choose an image and then show it, but when I tried to use the variable img or path (when defined as global) the following error shows up:
    cv2.imshow(" ",img)
  NameError: name 'img' is not defined

Code:
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
from cv2 import *

root=Tk()
root.title("filter applicator")

def open():
   global my_image
   root.filename=filedialog.askopenfilename(
                        initialdir="/", title="select a file",
                        filetypes=(("png files","*.png"),("allfiles","*.*")))

   lbl=Label(root,text=root.filename).pack()
   my_image=ImageTk.PhotoImage(Image.open(root.filename))
   myimagelbl=Label(image=my_image).pack()
   #global path
   path=root.filename
   global img
   img=cv2.imread(path)

mybtn=Button(root,text="browse",command=open).pack()
cv2.imshow(" ",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
root.mainloop()

A: You are trying to show the image before he pressed the "browse" button to select it. Make another button to allow the user to show the image after selecting it.
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
import cv2
root=Tk()
root.title("filter applicator")

def open():
   global my_image
   root.filename=filedialog.askopenfilename(initialdir="/",
                                         title="select a file",
                                         filetypes=(("png files","*.png"),("allfiles","*.*")))

   lbl=Label(root,text=root.filename).pack()
   my_image=ImageTk.PhotoImage(Image.open(root.filename))
   myimagelbl=Label(image=my_image).pack()
   #global path
   path=root.filename
   global img
   img=cv2.imread(path)

def show_im():
    global img
    cv2.imshow(" ", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

mybtn=Button(root,text="browse",command=open).pack()
showbtn = Button(root,text="show",command=show_im).pack()

root.mainloop()

A: I don't have cv2 installed so couldn't really test this, but think it will solve the problem — including several others you haven't encountered yet. I've also made other changes like renaming your open() function browse() because the former is the nama of a Python built-in, as well as reformatting the code so it follows the PEP 8 - Style Guide for Python Code to make it more readable.
The problem with img not being defined is because it doesn't exist until your open() function is called. That just one of the problems with using global variables so I have tried to eliminate them whenever possible.
One common newbie tkinter mistake you made repeatably was to assign the value of the pack() widget method to a variable. That's a mistake because pack() always return None. In many (but not all) of those cases there was not even a need to assign anything to variable since it wasn't ever referenced again.
import cv2
from PIL import ImageTk, Image
import tkinter as tk
from tkinter.filedialog import askopenfilename

root = tk.Tk()
root.title("filter applicator")

def browse():
    filename = askopenfilename(initialdir="./", title="select a file",
                               filetypes=(("png files","*.png"),("allfiles","*.*")))
    if not filename:
        return  # User didn't select a file.

    tk.Label(root, text=filename).pack()
    my_image = ImageTk.PhotoImage(Image.open(filename))
    img_lbl = tk.Label(image=my_image)
    img_lbl.img = my_image  # Save reference to image.
    img_lbl.pack()

    img = cv2.imread(filename)
    show_image(img)

def show_image(img):
    cv2.imshow(" ", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

tk.Button(root, text="Browse", command=browse).pack()

root.mainloop()

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL query to find *best* row per group where *best* is a complex metrics My table foobar has the following columns:

val: tinyint NOT NULL
date: timestamp NOT NULL
type: enum('A', 'B', 'C') NOT NULL
extra: tinyint NOT NULL

For each type I would like to find the row that matches an arbitrary condition on the columns (e.g. extra > 12 AND val > 0), that minimizes val and, in case of equal val, minimizes date. I assume that for each type such a row exists and is unique. Finally, I'd like the result (as many rows as there are different type values) to be ordered by val, date.
If foobar contains the following rows:
+------+---------------------+------+-------+
| val  | date                | type | extra |
+------+---------------------+------+-------+
| -1   | 2014-04-10 00:00:00 | A    | 40    |
|  1   | 2014-04-15 00:00:00 | A    | 15    |
|  2   | 2014-04-12 00:00:00 | A    | 77    |
|  1   | 2014-04-11 00:00:00 | A    |  2    |
|  1   | 2014-04-14 00:00:00 | A    | 22    |
|  1   | 2014-04-10 00:00:00 | B    | 40    |
|  1   | 2014-04-15 00:00:00 | B    | 15    |
|  1   | 2014-04-12 00:00:00 | B    | 77    |
|  1   | 2014-04-11 00:00:00 | B    |  2    |
|  1   | 2014-04-14 00:00:00 | B    | 22    |
|  4   | 2014-04-10 00:00:00 | C    | 40    |
|  3   | 2014-04-15 00:00:00 | C    | 15    |
|  3   | 2014-04-12 00:00:00 | C    | 77    |
|  1   | 2014-04-11 00:00:00 | C    |  2    |
|  3   | 2014-04-14 00:00:00 | C    | 22    |
+------+---------------------+------+-------+

the query shall return:
+------+---------------------+------+-------+
| val  | date                | type | extra |
+------+---------------------+------+-------+
|  1   | 2014-04-10 00:00:00 | B    | 40    |
|  1   | 2014-04-14 00:00:00 | A    | 22    |
|  3   | 2014-04-12 00:00:00 | C    | 77    |
+------+---------------------+------+-------+

This seems to work:
SELECT a.* FROM (
    SELECT MIN(val * 4294967296 + UNIX_TIMESTAMP(date)) AS score
        FROM foobar WHERE extra > 12 AND val > 0
        GROUP BY type
    ) AS b
INNER JOIN foobar AS a
    ON a.val * 4294967296 + UNIX_TIMESTAMP(a.date) = b.score
ORDER BY val, date;

but I find it over-complicated and I suspect that there must be a better way. Moreover, transforming my multi-columns criteria in a single numeric value (val * 4294967296 + UNIX_TIMESTAMP(date)) works in this simple case but may be more difficult in more complex scenarios.
Are there other, more generic schemes, that would do the same?

A: DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(val INT SIGNED NOT NULL
,date TIMESTAMP NOT NULL
,type CHAR(1) NOT NULL
,extra TINYINT NOT NULL
,PRIMARY KEY(val,date,type)
);

INSERT INTO my_table VALUES
(-1,'2014-04-10 00:00:00','A',40),
( 1,'2014-04-15 00:00:00','A',15),
( 2,'2014-04-12 00:00:00','A',77),
( 1,'2014-04-11 00:00:00','A', 2),
( 1,'2014-04-14 00:00:00','A',22),
( 1,'2014-04-10 00:00:00','B',40),
( 1,'2014-04-15 00:00:00','B',15),
( 1,'2014-04-12 00:00:00','B',77),
( 1,'2014-04-11 00:00:00','B', 2),
( 1,'2014-04-14 00:00:00','B',22),
( 4,'2014-04-10 00:00:00','C',40),
( 3,'2014-04-15 00:00:00','C',15),
( 3,'2014-04-12 00:00:00','C',77),
( 1,'2014-04-11 00:00:00','C', 2),
( 3,'2014-04-14 00:00:00','C',22);

SELECT a.*
  FROM my_table a
  JOIN
     ( SELECT x.val
            , x.type
            , MIN(x.date) date
         FROM my_table x
         JOIN
            ( SELECT MIN(val) val
                   , type
                FROM my_table
               WHERE extra > 12
                 AND val > 0
               GROUP
                  BY type
            ) y
           ON y.type = x.type
          AND y.val = x.val
        WHERE x.extra > 12
        GROUP
           BY val
            , type
     ) b
    ON b.val = a.val
   AND b.type = a.type
   AND b.date = a.date;

+-----+---------------------+------+-------+
| val | date                | type | extra |
+-----+---------------------+------+-------+
|   1 | 2014-04-14 00:00:00 | A    |    22 |
|   1 | 2014-04-10 00:00:00 | B    |    40 |
|   3 | 2014-04-12 00:00:00 | C    |    77 |
+-----+---------------------+------+-------+


text:
Q: Creating a WebSocket Clock For school project reasons I would like to create a WebSocket based clock (hello world kind of thing), where the user would go to my website and it would only display a clock running, except that the current-server-time would not be "retrived" via javascript or anything like that, but "pushed"! Where should I start?

A: If you want to implement the server in C#, the first decision you'll probably have to make which WebSocket framework to use. One of those is SuperWebSocket.
If you are undecided about server-side language, and like Python, you could checkout this example. It sends out a tick message every second to all connected WebSocket clients (JavaScript included) - it'll also broadcast any messages received from a client to all the others.


text:
Q: How to make a unique name for each file in C? How are you today. I have a question about file name handling :D. My code doesn't want to work it gives me false segmentation.
The idea is to make unique file name and create it if the the file with same name already exists. The first is the exception without file so the for loop starts from 1 instead of 0.
unistd.h is required!
char fileName[15][100];
sprintf(fileName[0],"output.txt");
FILE *output;

   for(int i = 1 ;i < 100; i++){
        sprintf(fileName[i],"Output%d.txt",i+1);

        //File exists
        if(!access(fileName[i],F_OK))
        {
            //Create and open a file
            output = fopen(fileName[i], "w");
            break;
        }
    }

I just need to make a try function (like while) till it finds the name which is not taken. I just put the for loop there to have limit to 100.

A: you have to malloc memory for the strings.
example
char** fileName;
int Number_Of_Strings, String_Length, i;
fileName = malloc(Number_Of_Strings * sizeof(char*));

for ( i = 0; i < Number_Of_String; i++)   // For each string
    fileName = malloc(String_Length * sizeof(char));

Number_If_Strings : How many strings do you need?
String_Length : The length of each string

A: What you have here:
char* fileName[100];

...is an array of 100 char pointers.  However, you have not made space for the actual strings themselves.
When you do this:
sprintf(&fileName[0],"output.txt");

...you write "output.txt" to the location pointed to by the address in fileName[0], most likely 0x0 or some random value depending on your compiler and whether you allocate the array on the stack or the heap, etc.     This normally results in a segmentation violation and your program terminates.

A: You did not allocate any memory for your array of pointers to point to. Also your syntax was a bit off here and there. This simple example shows how to allocate memory for an array of strings, assign some values, print them and free the memory.
#include <stdio.h>
#include <stdlib.h>

#define MAXNAMES 10
#define MAXLEN   32

int main(void)
{
    char* fileName[MAXNAMES];
    int i;

    for(i=0; i<MAXNAMES; i++)
        if ((fileName[i] = malloc(MAXLEN)) == NULL)
            exit(1);

    sprintf(fileName[0],"Output.txt");     // your first name is an exception
    for(i = 1; i<MAXNAMES; i++)            // the rest of the names
        sprintf(fileName[i], "Output%d.txt", i+1);    // using your offset of 1

    for(i = 0; i<MAXNAMES; i++)
        printf("%s\n", fileName[i]);

    for(i = 0; i<MAXNAMES; i++)
        free(fileName[i]);

    return 0;
}

Program output:
Output.txt
Output2.txt
Output3.txt
Output4.txt
Output5.txt
Output6.txt
Output7.txt
Output8.txt
Output9.txt
Output10.txt


text:
Q: Scanner throws when user input is a small float I'm working on a project and I've found a bug that has been a recurring problem with some of my previous assignments. Basically, I have a method that prompts user input and then returns that value. I check to make sure the user has inputted a value greater than 0 and my code works as expected EXCEPT for really small negative or positive float values close to 0. Now, I believe it's because the variable I am setting this user input to is an integer so it's throwing when the value is a float... I could be totally wrong though, I'm still very new to programming.
Here is the user input code:
public static int userNumber(){

        Scanner input = new Scanner(System.in);

        int n = 0;

        while(n <= 0){
            System.out.println("Please enter a positive integer");
            n = input.nextInt();
        }

        return n;

    }

And this is the error it returns when a user enters 0.1523156:
0.1523156
Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Unknown Source)
    at java.base/java.util.Scanner.next(Unknown Source)
    at java.base/java.util.Scanner.nextInt(Unknown Source)
    at java.base/java.util.Scanner.nextInt(Unknown Source)
    at Lab5.userNumber(Lab5.java:22)
    at Lab5.main(Lab5.java:7)

I've tried closing the scanner but that also causes an error... Can someone help me understand what's going on? I want to prompt the user to enter a valid integer and if the input isn't valid, to continue prompting.
Thanks!

A: Use hasNextInt().
    int n=0;
    Scanner input = new Scanner(System.in);
    while(!input.hasNextInt() && n <= 0) {
        System.out.println("Please enter a positive Integer.");
        input.next();
    }
    n = input.nextInt();
    System.out.println(n);
    input.close();

A: You should use nextInt() only if you are sure of user will input int only. As per javadoc of the method, it will throw exception if entered value can't be parsed to int:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
You should rather use next() which will give you string, and then try to parse it until you get valid int.
public class InputRead {

    public static void main(String[] args){
        System.out.println("UserNumber entered:" + userNumber());
    }

    public static int userNumber(){

        Scanner input = new Scanner(System.in);

        int n = 0;

        while(n <= 0){
            try{
                System.out.println("Please enter a positive integer");
                String read = input.next();
                n = Integer.parseInt(read);
            } catch(NumberFormatException e){
                //ignore
            }
        }

        input.close();
        return n;
    }
}

UPDATE
Solution using hasNextInt():
public class InputIntRead {

    public static void main(String[] args){
        System.out.println("UserNumber entered:" + userNumber());
    }

    public static int userNumber(){

        try (Scanner scanner = new Scanner(System.in)) {
            String msg = "Please, enter a positive integer:";
            int n = 0;

            while(n <= 0){
                System.out.println(msg);
                if(scanner.hasNextInt()){
                    n = scanner.nextInt();
                } else {
                    scanner.next();
                }
            }

            return n;
        }
    }
}

A: Scanner.nextInt() throws InputMismatchException if the next token doesn't match the Integer.
As an option, before scanning the input, you can use a Scanner.hasNextInt() method in order to check whether the input is a valid Integer.
Example:
try (Scanner sc = new Scanner(System.in)) {
    String msg = "Please, enter a positive Integer:";
    int n = 0;

    do {
        System.out.println(msg);
        // make the user keep entering the input until it's an Integer
        while (!sc.hasNextInt()) {
            System.out.println(msg);
            sc.next();
        }
        n = sc.nextInt();
    }
    while (n <= 0); // run until the input is a positive Integer

    return n;
}


text:
Q: how to get the value from a xml parser to an other class I'm searching all over the internet, but I didn't find anything, I could use. So here is my problem: I have an xml parser that works in an list view, but I want to give the id of the song to an other activity , so I can display it.

A: You can pass by using setTag() and getTag() methods look at my answer hereHow to acces variable in arrayadapter getView from onItemClick

A: 1. First you need OnItemClickListener() method for ListView
2. Then once you capture the index of the row on which you clicked, use Intent() to pass it to another activity.
Note:
For this to work, please make the Map as static, and please do map.clear() , everytime before loading the Map with parsed data.
3. When you go to the another Activity, I hope the Order of your Song in Map and in the ListView are same,
So Suppose you pressed the 2nd item on the ListView, the index passed will be 1, and in other Activity just call the Map's 1st index.
Note:
Adding header will effect the index of ListView so its better to use getItemIdAtPosition(arg) in the onClick() method.
Eg:
ListView lv = (ListView)findViewById(R.id.MyListView);

lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {

                i = new Intent(ProductActivity.this, ProductDetails.class);

                i.putExtra("keyAapo", (int) lv.getItemIdAtPosition(arg2));

                startActivity(i);

            }

        });

A: The Intent extra passing option was already said, however, if you are getting to the point where you are passing a bunch of data, you can always make the XML processor reusable and just pass the XML. It's already an encoded format


text:
Q: Errno 32 Broken Pipe when using easy.py in libsvm a few days ago, I was still able to use the easy.py, but today, when I tried again, I got this error [errorno 32] broken pipe, which I haven't had it before. Everything is still the same, I did not change a single thing, recently I only updated java to version 8... That's all...
line = ''
while True:
    last_line = line
    line = f.readline()
    if not line: break
c,g,rate = map(float,last_line.split())

and this is the error:
Scaling training data...
Cross validation...
[Errno 32] Broken pipe
Try "grid.py" for more information.
^CTraceback (most recent call last):
  File "easy.py", line 61, in <module>
    line = f.readline()
KeyboardInterrupt

Have anybody had this error before?
P/S: I tried running it on two different machines, both using mac os 10.9.2, it can run normally on another machine and can't on the other one... The only differernt between them is one uses java and netbean 8, one uses java and netbean 7. On the machine that failed to run the program, I upgraded MAMP PRO in it to 3.03 yesterday.

A: Probably too late, but did you ever fix this? I've had the same issue, and discovered it was a problem with gnuplot. It wasn't executing properly and once fixed it all went back to normal. It could be that the Java update meant that you also needed to update gnuplot.


text:
Q: Scrapy, developing scalable spiders - extract Xpath by Element properties So I'm working on a web-scraping project that essentially pulls a bunch of product information (like price, location, name, etc.) from a list of 20+ websites... So far i have created a generic MasterSpider ( similar to what is discussed here: Creating a generic scrapy spider ), from which I inherit and override depending on the site's specific architecture.
However, after essentially repeating much code and wanting to make this project scalable, I have started working towards generalizing my MaterSpider that way it could be extended to other websites, and ideally instantiated with minimal arguments like just the start_url. In other words, instead of locating elements by Xpath, which are not consistent across domains, I am now looking for html tag attribute values/text values.
This works fine for generic/consistent targets like identifying the category links from the start page (which typically contain the category in the link), but for things like finding the product name, price, etc. it is lacking. Having to build out a list of xpath conditions (like @class = a or b or c/contains(.,'a') or contains(.,'b') ) kind of defeats the purpose.
I realize i could also pass a few xpath conditions to instantiate the spider, which I may just have to do, but I would prefer to make this as easy to use and extensible as possible...
My idea is before parsing the individual product pages, to issue a dummy request that looks for the information I would like, and works backward to actually identify the xpath of the information-which is then used in the subsequent requests.
So I was wondering if anyone had any good ideas on how to extract the Xpath of an element given lets say a list of tag values it could contain, or the matching of text within... I realize a series of Try-catches could work, but again that would be more of a band-aid than a solution, and not very scalable. If I have to use something like selenium or a parser to do this that is also an option...
Really open to any ideas or fresh perspectives.
Thanks!

A: At work, I have to scrape thousands of news websites, and as you might expect there is no one fits all solution. So our strategy was to have a "generic" method, that through heuristics would try to extract the needed information and for troublesome websites we would have a list of specific xpaths for that website.
So our general structure is something like this:
parsers = {
    "domain1": {
        "item1":  "//div...",
        "item2":  "//div...",
    },
    "domain2": {
        "item1":  "//div...",
        "item2":  "//div...",
    },
}

def parse(self, response):
    domain = urlparse(response.url).netloc # urlparse comes from urllib.parse
    try:
        parser = self.parsers[domain]
        return self.parse_with_parser(response, parser)
    except Exception as e:
        return self.parse_generic(response)

The parsers dict I actually keep in a separate file. You could also keep it in a database or a file and access the information when the spider is loading so you do not to have to edit the crawler every time you need to change something.
Edit:
Answering the second part of your question, depending on what you need done, you could write xpaths that take into account several conditions. For instance:
"//a[contains(@class, 'foo') or contains(@class, 'bar')]"

Maybe even
"//a[contains(@class, 'foo') or contains(@class, 'bar')] | //div[@class='something'] | //td/span"

The pipe operator "|" will allow you to "chain" different expressions that might contain what you want extracted. A and/or operation on different expressions.


text:
Q: Selecting columns from one table, but WHERE clause from a different table? So I have 3 tables, and I was told to give in those 3 specific columns as parameters. My question is, would I be able to find the Investor's FirstName and LastName simply with Portfolio Description, or would I have to join the tables also?
(The first select statement refers to a table that I did not list)
Investor
InvestorNum   FirstName    LastName     Address
-----------    --------     -------     ------

Portfolio
Port num     Investor Num     Port Description    InvestorNum
---------   -------------     ----------------    ----------

Stock
Stock Code     Stock Name
----------     ----------

FUNCTION PKG_FN_Q4
(P_Portfolio_Description varchar2, P_Investor_Number number, P_Stock_Name varchar2)
RETURN varchar2
AS
V_Average_Cost varchar2(50);
V_Output varchar2(500);
V_Investor_First_Name varchar2(25);
V_Investor_Last_Name varchar2(30);
V_Stock_Name varchar2(50);
V_Portfolio_Desc varchar2(50);

BEGIN
SELECT TO_CHAR(sum(Quantity*Price_Per_Share)/sum(Quantity))
INTO V_Average_Cost
From Transaction
Where Portfolio_Description = P_Portfolio_Description AND
  Investor_Number = P_Investor_Number AND
      Stock_Name = P_Stock_Name AND Buy_Sell = 'B';

SELECT First_Name, Last_Name
INTO V_Investor_First_Name, V_Investor_Last_Name
From Investor
Where Portfolio_Description = P_Portfolio_Description
  AND Portfolio.Investor_Number = Investor.Investor_Number;

SELECT Stock_Name
INTO V_Stock_Name
From Stock
Where Stock_Name = P_Stock_Name;

SELECT Portfolio_Description
INTO V_Portfolio_Desc
From Portfolio
Where Portfolio_Description = P_Portfolio_Description;

RETURN V_Output = V_Investor_First_Name || V_Investor_Last_Name || 'paid, on average' ||
                    V_Average_Cost || 'for the stock' || V_Stock_Name || 'in the portfolio' || V_Portfolio_Desc;

A: Just using P_Investor_Number should work assuming Investor_Number is a primary key.
SELECT First_Name, Last_Name
INTO V_Investor_First_Name, V_Investor_Last_Name
From Investor
Where Investor.Investor_Number = P_Investor_Number;


text:
Q: $L^p$-estimates for elliptic pseudodifferential operators Assume we have an pseudodifferential operator
$P:\mathcal{S}(\mathbb{R}^n) \rightarrow \mathcal{S}(\mathbb{R}^n), Pf(x) = (2\pi)^{-n/2}\int\mathrm{d}\xi\; p(x,\xi)\,\hat{f}(\xi)e^{i\xi x}$
acting on Schwarz-functions. Assume it is of degree $m$, that is we have $|\partial_\xi^\alpha \partial_x^\beta p(x,\xi)| \leq C_{\alpha,\beta} \, (1 + |\xi|)^{m - |\alpha|}$ for some real $m$ and multiindices $\alpha,\beta$. Now, assume that P is elliptic, that is $c(1+|\xi|)^m \leq |p(x,\xi)|$ for some constant.
Now it is a standard result, that one has the following elliptic $L^2$-estimate:
$\lVert f \rVert_{W^{s,2}} \le C (\lVert Pf\rVert_{W^{s-m,2}} + \lVert f\rVert_{W^{s-m,2}})$
My question: Is there a $L^p$-generalization of this estimate? If yes, where can I find a reference to it?

A: Yes you do have a generalization of your elliptic inequality to the $L^p$ case for $p\in (1,+\infty)$. In fact the operators with symbols in the class $S^0_{1,0}$ (as in your question) are bounded on $L^p$ ($p$ in the same range as above). You can find a proof of this in the Astérisque book by R. Coifman & Y. Meyer "Au delà des opérateurs pseudo-différentiels".


text:
Q: Faster loading time for react in the browser? I'm using react in the browser. It works fine, but it's not fast enough. The initial load takes too much time while it compiles.
I'd like to use react/jsx in the browser and have it compile on the fly without introducing a build step via webpack or using "create-react-app". I find these things to be too much of a process for what I need. Sometimes I just need to write a quick little utility that doesn't need to take more than one (html) file and I'd like to to throw that one file on a static server.
The single-file-example below works but unfortunately the loading time is just too slow. Maybe someone found a creative way to cache things or make things faster? Maybe there's no way around the first time it loads, but how about the second time etc? maybe an intermediary server can compile+cache it, so that subsequent requests would be faster. not sure. Or maybe there's a super fast babel that I'm not aware of that could just work faster than the below?
https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html

    <meta charset="UTF-8" />
    <title>Hello World</title>

A: Pulling answer from comments.
Use npx babel script.js --watch --out-file script-compiled.js to compile your files and load those files. You will be required to reload to update the site.
https://babeljs.io/docs/en/babel-cli.html#compile-files


text:
Q: How do I create a custom ordered array from a list? I have a list that returns my data in the following format:
1,2,3,4,5,6

What if I wanted to return an array in the following format? :
[1,2],[3,4],[5,6]

Here's what I have written up so far:
List<string> list = new List<string>();
            foreach (var record in model.rows)
            {
                list.Add(record[0]);
                list.Add(record[1]);
            }

            Console.WriteLine(list);

A: The result you want is a list of arrays. You could try this:
List<int[]> list = new List<int[]>();

for(int i = 0; i < model.Length; i++)
    list.Add(new[] { model[i], i+1 >= model.Length ? 0 : model[++i] });

The ++i operator will increment the value of i and read. SO, the second element of the array is defined by an check if the i+1 is greater than the length of model collection. If yes, the 0 is set, otherwise the next element of the model selection.


text:
Q: Neural network - meaning of weights I am using feed-forward NN. I understand the concept, but my question is about weights. How can you interpret them, i.e. what do they represent or how can they be undestrood (besied just function coefficients)? I have found something called "space of weights", but I am not quite sure what does it means.

A: Individual weights represent the strength of connections between units. If the weight from unit A to unit B has greater magnitude (all else being equal), it means that A has greater influence over B (i.e. to increase or decrease B's level of activation).
You can also think of the the set of incoming weights to a unit as measuring what that unit 'cares about'. This is easiest to see at the first layer. Say we have an image processing network. Early units receive weighted connections from input pixels. The activation of each unit is a weighted sum of pixel intensity values, passed through an activation function. Because the activation function is monotonic, a given unit's activation will be higher when the input pixels are similar to the incoming weights of that unit (in the sense of having a large dot product). So, you can think of the weights as a set of filter coefficients, defining an image feature. For units in higher layers (in a feedforward network), the inputs aren't from pixels anymore, but from units in lower layers. So, the incoming weights are more like 'preferred input patterns'.
Not sure about your original source, but if I were talking about 'weight space', I'd be referring to the set of all possible values of all weights in the network.

A: Well, it depends on a network architecture and particular layer. In general NNs are not interpretable, this is their major drawback in commercial data analysis (where your goal is to uncover actionable insights from your model).
But I love convolutional networks, because they are different! Although their upper layers learn very abstract concepts, usable for transfer learning and classification, which could not be understood easily, their bottom layers learn Gabor filters straight from raw data (and thus are interpretable as such filters). Take a look at the example from a Le Cun lecture:

In addition, M. Zeiler (pdf) and many other researchers invented very creative method to "understand" convnet and ensure it learned something useful dubbed Deconvolutional networks, in which they 'trace' some convnet by making forward pass over input pictures and remembering which neurons had largest activations for which pics. This gives stunning introspection like this (a couple of layers were shown below):

Gray images at the left side are neuron activations (the more intensity -- the larger activation) by color pictures at the right side. We see, that these activations are skeletal representations of real pics, i.e., the activations are not random.  Thus, we have a solid hope, that our convnet indeed learned something useful and will have decent generalization in unseen pics.

A: I think you are trying too hard on the model that does not have too much interpretability. Neural network (NN) is one of the black box models that will give you better performance, but it is hard to understand what was going on inside. Plus, it is very possible to have thousands even millions of weights inside of NN.
NN is a very big non-linear non-convex function that can have large amount of local minima. If you train it multiple times, with different start point, the weights will be different. You can come up with some ways to visualize the internal weights, but it also does not give you too much insights.
Here is one example on NN visualization for MNIST data. The upper right figure (reproduced below) shows the transformed features after applying the weights.

A: Simple weights are probability.
How likely a connection will give the correct or wrong answer.
Even wrong results in multilayer nets can be usefull.
Telling that something is not that..


text:
Q: How do I update a div on a page using Spring Boot? I wanted to update my div, something like
document.getElementById("myDiv").innerHTML = springBootResponse.responseText;

But I cannot find a way to send plain text as a response from my controller.
How do I even do it?

A: Have you tried using @ResponseBody on a controller method?
@ResponseBody
@RequestMapping("/sendtext")
public String sendPlainText(){

    //You can use different methods here to retrieve your String

    return "Your text here.";
}

Then by doing an ajax call to /sendtext endpoint you should be able to get what you want.


text:
Q: How to redirect my app in Struts 2 with Azure SSO I am wanting to implement a SSO with Azure to an application that is built with Struts 2, I have already implemented the filter to make me the login from the microsoft page.

however the redirection issue when everything is correct is not quite clear to me as I am not very good with Struts as when you originally log into the app it redirects to a URL like this localhost:8080/Portal/login/loginAction_validateUser.action.
this is the original login class of the application
public class ActionLogin extends ActionSupport implements ServletRequestAware {

    private static Logger logger = LogManager.getLogger(ActionLogin.class);

    private HttpServletRequest request;

    private UtilHttp uhttp = new UtilHttp();

    private UtilFiles ufiles = new UtilFiles();

    private User user;

    private Person person;

    private int invalidateSession;

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public String validateUser() {
        try {

            HttpSession session = request.getSession();
            uhttp.cleanSession(request);
            LoginBusiness business = new LoginBusiness();
            String page = "menu";
            boolean loadMenu = true;

            if (invalidateSession == 1) {

                new LoginBusiness().createDifferentSession(session, user.getLogin());
                invalidateSession = 0;
            }

            user = business.validateUser(user.getLogin(), user.getPassword(), user.getIdProfile());
            if (business.isUserLocked(user.getIdUser())) {

                    addActionError(PortalAdministracionErrorCode.E0400.getMessage());
                return "blockedAccount";
                }

            if (user.isValidAuth()) {
                logger.info("user.isValidAuth()");

                if (user.isChangePassword()) {

                    loadMenu = false;
                    page = "change";
                }

                if (business.isPasswordExpired(user.getIdUser())) {

                    addActionError(getText(PortalAdministracionErrorCode.E0401.getMessage()));
                    loadMenu = false;
                    return "passwordexpired";
                }

                session = request.getSession(true);
                session.setAttribute(Constants.SESSION_USER, user);

            } else {

                addActionError(getText("label.error.login.password"));
                user.setAuthType("1");
                page = "login";
            }

            return page;

        } catch (Exception e) {
            addActionError(e.getMessage());
            return "login";
        }
    }

    public String logOut() {
        HttpSession session = request.getSession(false);
        if (session != null) {

            try {
                logger.info("Realiza un logOut el usuario ");
                uhttp.cleanSession(request);
                return "logout";
                //session.invalidate();
            } catch (Exception ex) {
                logger.error(ex);
                return "logout";
            }
        }
        return "logout";
    }

    public String invalidateSession() {
        invalidateSession = 0;
        return "login";
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public int getInvalidateSession() {
        return invalidateSession;
    }

    public void setInvalidateSession(int invalidateSession) {
        this.invalidateSession = invalidateSession;
    }
}

this is the XML that is configured with struts, when the login is ok it redirects to the JSP called entrada.jsp but in the url it does not change when it does this if it does not put the action of the login that was made, any idea how to adapt it?
my login.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
    <package name="login" namespace="/login" extends="struts-default,json-default">

        <interceptors>
            <interceptor-stack name="defaultSecurityStack">
                <interceptor-ref name="tokenSession">
                    <param name="excludeMethods">*</param>
                </interceptor-ref>
                <interceptor-ref name="defaultStack" />
            </interceptor-stack>
        </interceptors>

        <default-interceptor-ref name="defaultSecurityStack" />

        <global-results>
            <result name="error">/jsp/common/errorDetail.jsp</result>
            <result name="invalid.token">/jsp/Login.jsp</result>
        </global-results>

        <action name="loginAction_*" method="{1}" class="action.ActionLogin">
            <result name="login">/jsp/Login.jsp</result>
            <result name="menu">/jsp/menu/Entrada.jsp</result>

            <result name="platformAdmon">/jsp/profile/AddPlatformAdmon.jsp</result>
            <result name="change">/jsp/menu/ChangePassword.jsp</result>
            <result name="passwordexpired">/jsp/login/account/password-expired.jsp</result>
            <result name="success">/jsp/menu/ResultOperation.jsp</result>

            <result name="blockedAccount">/jsp/login/account/blocked.jsp</result>
            <result name="logout">/jsp/logout.jsp</result>
            <interceptor-ref name="defaultSecurityStack">
                <param name="tokenSession.excludeMethods">validatePlatformAdmin,logOut,editPassword</param>
            </interceptor-ref>
            <allowed-methods>toPageLogin, addPlatformAdmon, authType, changePassword, editPassword, logOut, showMenu, validatePlatformAdmin, validateUser</allowed-methods>
        </action>

        <action name="account_*" method="{1}" class="com.seguridata.rne.administracion.portal.action.LoginAccountAction">
            <result name="login">/jsp/Login.jsp</result>
            <result name="blocked">/jsp/login/account/blocked.jsp</result>
            <result name="resultblocked">/jsp/login/account/blocked-response.jsp</result>
            <result name="unlock">/jsp/login/account/unlock.jsp</result>
            <result name="resultunlock">/jsp/login/account/unlock-response.jsp</result>
            <result name="passwordexpired">/jsp/login/account/password-expired.jsp</result>
            <result name="passwordexpired_success">/jsp/login/account/password-expired-success.jsp</result>
            <interceptor-ref name="defaultSecurityStack">
                <param name="tokenSession.excludeMethods">*</param>
            </interceptor-ref>
            <allowed-methods>unlock, unlockRequest, updatePasswordExpired, validateUnlockRequest</allowed-methods>
        </action>
    </package>
</struts>

my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <filter>
        <filter-name>struts-prepare</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareFilter</filter-class>
    </filter>
    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
    </filter>
    <filter>
        <filter-name>struts-execute</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsExecuteFilter</filter-class>
    </filter>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts-prepare</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>struts-execute</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <jsp-config>
        <taglib>
            <taglib-uri>/struts-tags</taglib-uri>
            <taglib-location>/WEB-INF/struts-tags.tld</taglib-location>
        </taglib>

        <taglib>
            <taglib-uri>sitemesh-page</taglib-uri>
            <taglib-location>/WEB-INF/sitemesh-page.tld</taglib-location>
        </taglib>

        <taglib>
            <taglib-uri>sitemesh-decorator</taglib-uri>
            <taglib-location>/WEB-INF/sitemesh-decorator.tld</taglib-location>
        </taglib>
    </jsp-config>

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>/jsp/Login.jsp</welcome-file>
    </welcome-file-list>

    <listener>
        <listener-class>com.seguridata.rne.servlet.http.UserConnected</listener-class>
    </listener>
    <listener>
        <listener-class>com.seguridata.rne.servlet.http.SessionListener</listener-class>
    </listener>
     <context-param>
  <param-name>authority</param-name>
  <param-value>https://login.windows.net/</param-value>
 </context-param>
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
 </context-param>

 <context-param>
  <param-name>tenant</param-name>
  <param-value>mytenat</param-value>
 </context-param>

 <filter-mapping>
  <filter-name>BasicFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
  <filter>
  <filter-name>BasicFilter</filter-name>
  <filter-class>mx.prototype.adaj4jAzure.BasicFilter</filter-class>
  <init-param>
   <param-name>client_id</param-name>
   <param-value>myclientid</param-value>
  </init-param>
  <init-param>
   <param-name>secret_key</param-name>
   <param-value>secretkeyy</param-value>
  </init-param>
 </filter>
  <servlet>
  <servlet-name>mvc-dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>mvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>

my struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>

<!--
    <constant name="struts.enable.DynamicMethodInvocation" value="true"/>
    <constant name="struts.devMode" value="false" />
    <constant name="struts.configuration.xml.reload" value="false" />
    <constant name="struts.i18n.reload" value="false" />
    <constant name="struts.custom.i18n.resources" value="ApplicationResources" />
    <constant name="struts.multipart.maxSize" value="5242880"/>
   -->

    <constant name="struts.enable.DynamicMethodInvocation" value="true"/>
    <constant name="struts.custom.i18n.resources" value="ApplicationResources" />
    <constant name="struts.multipart.maxSize" value="524288000" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.i18n.reload" value="false"/>
    <constant name="struts.configuration.xml.reload" value="false"/>
    <constant name="struts.freemarker.templatesCache" value="true"/>
    <constant name="struts.freemarker.templatesCache.updateDelay" value="120"/>
    <constant name="struts.freemarker.mru.max.strong.size" value="120"/>
    <constant name="struts.action.excludePattern" value="/struts/webconsole.html" />
    <constant name="struts.action.excludePattern" value="/struts/webconsole.css"/>
    <constant name="struts.action.excludePattern" value="/struts/webconsole.js"/>

    <include file="strutsDomain.xml"/>
    <include file="strutsLogin.xml"/>
    <include file="strutsPasswordParameters.xml"/>
    <include file="strutsPersonalize.xml"/>
    <include file="strutsProfile.xml"/>
    <include file="strutsTemplate.xml"/>
    <include file="strutsRoute.xml"/>
    <include file="strutsPlantillas.xml"/>

    <package name="serveAll" namespace="" extends="struts-default">
        <action name="*">
            <result>/jsp/common/error.jsp</result>
        </action>
    </package>
</struts>

this is my filter code for the SSO redirection I don't really see the issue here but in the configuration in Azure
public class BasicFilter implements Filter {

    public static final String STATES = "states";
    public static final String STATE = "state";
    public static final Integer STATE_TTL = 3600;
    public static final String FAILED_TO_VALIDATE_MESSAGE = "Failed to validate data received from Authorization service - ";
    private String clientId = "";
    private String clientSecret = "";
    private String tenant = "";
    private String authority;

    public void destroy() {

    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

         HttpServletResponse httpResponse = (HttpServletResponse) response;
         if (request instanceof HttpServletRequest) {

            HttpServletRequest httpRequest = (HttpServletRequest) request;

            try {
                String currentUri = httpRequest.getRequestURL().toString();
                String queryStr = httpRequest.getQueryString();
                String fullUrl = currentUri + (queryStr != null ? "?" + queryStr : "");

                // check if user has a AuthData in the session
                if (!AuthHelper.isAuthenticated(httpRequest)) {
                    if (AuthHelper.containsAuthenticationData(httpRequest)) {
                        processAuthenticationData(httpRequest, currentUri, fullUrl);
                    } else {
                        // not authenticated
                        sendAuthRedirect(httpRequest, httpResponse);
                        return;
                    }
                }
                if (isAuthDataExpired(httpRequest)) {
                    updateAuthDataUsingRefreshToken(httpRequest);
                }
            } catch (AuthenticationException authException) {
                // something went wrong (like expiration or revocation of token)
                // we should invalidate AuthData stored in session and redirect to Authorization server
                removePrincipalFromSession(httpRequest);
                sendAuthRedirect(httpRequest, httpResponse);
                return;
            } catch (Throwable exc) {
                httpResponse.setStatus(500);
                request.setAttribute("error", exc.getMessage());
                request.getRequestDispatcher("/error.jsp").forward(request, response);
            }
        }

        chain.doFilter(request, response);

    }

    private boolean isAuthDataExpired(HttpServletRequest httpRequest) {
        AuthenticationResult authData = AuthHelper.getAuthSessionObject(httpRequest);
        return authData.getExpiresOnDate().before(new Date()) ? true : false;
    }

    private void updateAuthDataUsingRefreshToken(HttpServletRequest httpRequest) throws Throwable {
        AuthenticationResult authData =
                getAccessTokenFromRefreshToken(AuthHelper.getAuthSessionObject(httpRequest).getRefreshToken());
        setSessionPrincipal(httpRequest, authData);
    }

    private void processAuthenticationData(HttpServletRequest httpRequest, String currentUri, String fullUrl)
            throws Throwable {
            HttpSession session = httpRequest.getSession(false);
        HashMap<String, String> params = new HashMap<>();
        for (String key : httpRequest.getParameterMap().keySet()) {
            params.put(key, httpRequest.getParameterMap().get(key)[0]);
        }
        // validate that state in response equals to state in request
        StateData stateData = validateState(httpRequest.getSession(), params.get(STATE));

        AuthenticationResponse authResponse = AuthenticationResponseParser.parse(new URI(fullUrl), params);
        if (AuthHelper.isAuthenticationSuccessful(authResponse)) {
            AuthenticationSuccessResponse oidcResponse = (AuthenticationSuccessResponse) authResponse;
            // validate that OIDC Auth Response matches Code Flow (contains only requested artifacts)
            validateAuthRespMatchesCodeFlow(oidcResponse);

            AuthenticationResult authData =
                    getAccessToken(oidcResponse.getAuthorizationCode(), currentUri);
            // validate nonce to prevent reply attacks (code maybe substituted to one with broader access)
            validateNonce(stateData, getClaimValueFromIdToken(authData.getIdToken(), "nonce"));

            setSessionPrincipal(httpRequest, authData);
        } else {
            AuthenticationErrorResponse oidcResponse = (AuthenticationErrorResponse) authResponse;
            throw new Exception(String.format("Request for auth code failed: %s - %s",
                    oidcResponse.getErrorObject().getCode(),
                    oidcResponse.getErrorObject().getDescription()));
        }
    }

    private void validateNonce(StateData stateData, String nonce) throws Exception {
        if (StringUtils.isEmpty(nonce) || !nonce.equals(stateData.getNonce())) {
            throw new Exception(FAILED_TO_VALIDATE_MESSAGE + "could not validate nonce");
        }
    }

    private String getClaimValueFromIdToken(String idToken, String claimKey) throws ParseException {
        return (String) JWTParser.parse(idToken).getJWTClaimsSet().getClaim(claimKey);
    }

    private void sendAuthRedirect(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
        httpResponse.setStatus(302);

        // use state parameter to validate response from Authorization server
        String state = UUID.randomUUID().toString();

        // use nonce parameter to validate idToken
        String nonce = UUID.randomUUID().toString();

        storeStateInSession(httpRequest.getSession(), state, nonce);

        String currentUri = httpRequest.getRequestURL().toString();
        httpResponse.sendRedirect(getRedirectUrl(currentUri, state, nonce));
    }

    /**
     * make sure that state is stored in the session,
     * delete it from session - should be used only once
     *
     * @param session
     * @param state
     * @throws Exception
     */
    private StateData validateState(HttpSession session, String state) throws Exception {

        if (StringUtils.isNotEmpty(state)) {
            StateData stateDataInSession = removeStateFromSession(session, state);
            if (stateDataInSession != null) {
                return stateDataInSession;
            }
        }
        throw new Exception(FAILED_TO_VALIDATE_MESSAGE + "could not validate state");
    }

    private void validateAuthRespMatchesCodeFlow(AuthenticationSuccessResponse oidcResponse) throws Exception {
        if (oidcResponse.getIDToken() != null || oidcResponse.getAccessToken() != null ||
                oidcResponse.getAuthorizationCode() == null) {
            throw new Exception(FAILED_TO_VALIDATE_MESSAGE + "unexpected set of artifacts received");
        }
    }

    @SuppressWarnings("unchecked")
    private StateData removeStateFromSession(HttpSession session, String state) {

        Map<String, StateData> states = (Map<String, StateData>) session.getAttribute(STATES);
        if (states != null) {
            eliminateExpiredStates(states);
            StateData stateData = states.get(state);
            if (stateData != null) {
                states.remove(state);
                return stateData;
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    private void storeStateInSession(HttpSession session, String state, String nonce) {

        if (session.getAttribute(STATES) == null) {
            session.setAttribute(STATES, new HashMap<String, StateData>());
        }
        ((Map<String, StateData>) session.getAttribute(STATES)).put(state, new StateData(nonce, new Date()));
    }

    private void eliminateExpiredStates(Map<String, StateData> map) {
        Iterator<Map.Entry<String, StateData>> it = map.entrySet().iterator();

        Date currTime = new Date();
        while (it.hasNext()) {
            Map.Entry<String, StateData> entry = it.next();
            long diffInSeconds = TimeUnit.MILLISECONDS.
                    toSeconds(currTime.getTime() - entry.getValue().getExpirationDate().getTime());

            if (diffInSeconds > STATE_TTL) {
                it.remove();
            }
        }
    }

    private AuthenticationResult getAccessTokenFromRefreshToken(
            String refreshToken) throws Throwable {
        AuthenticationContext context;
        AuthenticationResult result = null;
        ExecutorService service = null;
        try {
            service = Executors.newFixedThreadPool(1);
            context = new AuthenticationContext(authority + tenant + "/", true,
                    service);
            Future<AuthenticationResult> future = context
                    .acquireTokenByRefreshToken(refreshToken, new ClientCredential(clientId, clientSecret), null, null);
            result = future.get();
        } catch (ExecutionException e) {
            throw e.getCause();
        } finally {
            service.shutdown();
        }

        if (result == null) {
            throw new ServiceUnavailableException("authentication result was null");
        }
        return result;
    }

    private AuthenticationResult getAccessToken(
            AuthorizationCode authorizationCode, String currentUri)
            throws Throwable {
        String authCode = authorizationCode.getValue();
        ClientCredential credential = new ClientCredential(clientId,
                clientSecret);
        AuthenticationContext context;
        AuthenticationResult result = null;
        ExecutorService service = null;
        try {
            service = Executors.newFixedThreadPool(1);
            context = new AuthenticationContext(authority + tenant + "/", true,
                    service);
            Future<AuthenticationResult> future = context
                    .acquireTokenByAuthorizationCode(authCode, new URI(
                            currentUri), credential, null);
            result = future.get();
        } catch (ExecutionException e) {
            throw e.getCause();
        } finally {
            service.shutdown();
        }

        if (result == null) {
            throw new ServiceUnavailableException("authentication result was null");
        }
        return result;
    }

    private void setSessionPrincipal(HttpServletRequest httpRequest,
                                     AuthenticationResult result) {
        httpRequest.getSession().setAttribute(AuthHelper.PRINCIPAL_SESSION_NAME, result);
    }

    private void removePrincipalFromSession(HttpServletRequest httpRequest) {
        httpRequest.getSession().removeAttribute(AuthHelper.PRINCIPAL_SESSION_NAME);
    }

    private String getRedirectUrl(String currentUri, String state, String nonce)
            throws UnsupportedEncodingException {
        String redirectUrl = authority
                + this.tenant
                + "/oauth2/authorize?response_type=code&scope=directory.read.all&response_mode=form_post&redirect_uri="
                + URLEncoder.encode(currentUri, "UTF-8") + "&client_id="
                + clientId + "&resource=https%3a%2f%2fgraph.microsoft.com"
                + "&state=" + state
                + "&nonce=" + nonce;

        return redirectUrl;
    }

    public void init(FilterConfig config) throws ServletException {
        clientId = config.getInitParameter("client_id");
        authority = config.getServletContext().getInitParameter("authority");
        tenant = config.getServletContext().getInitParameter("tenant");
        clientSecret = config.getInitParameter("secret_key");
    }

    private class StateData {
        private String nonce;
        private Date expirationDate;

        public StateData(String nonce, Date expirationDate) {
            this.nonce = nonce;
            this.expirationDate = expirationDate;
        }

        public String getNonce() {
            return nonce;
        }

        public Date getExpirationDate() {
            return expirationDate;
        }
    }
}

A: I think what you are wanting is to use the result type "redirect" to redirect the user after the filter runs.
<result name="login" type="redirect">${redirectUrl}</result>

In order for the ${redirectUrl} to be filled, you need to add/set it in your LoginAccountAction.class
private String redirectUrl
public String getRedirectUrl() {
    return redirectUrl;
}

Full definition
<action name="account_*" method="{1}" class="com.seguridata.rne.administracion.portal.action.LoginAccountAction">
    <!--
    <result name="login">/jsp/Login.jsp</result>
    -->
    <result name="login" type="redirect">${redirectUrl}</result>
    <result name="blocked">/jsp/login/account/blocked.jsp</result>
    <result name="resultblocked">/jsp/login/account/blocked-response.jsp</result>
    <result name="unlock">/jsp/login/account/unlock.jsp</result>
    <result name="resultunlock">/jsp/login/account/unlock-response.jsp</result>
    <result name="passwordexpired">/jsp/login/account/password-expired.jsp</result>
    <result name="passwordexpired_success">/jsp/login/account/password-expired-success.jsp</result>
    <interceptor-ref name="defaultSecurityStack">
        <param name="tokenSession.excludeMethods">*</param>
    </interceptor-ref>
    <allowed-methods>unlock, unlockRequest, updatePasswordExpired, validateUnlockRequest</allowed-methods>
</action>


text: Q: Using Latex in a C++ Program I want to write a program that allows me to type in plain text and LaTex code into a text field and displays in real time that text parsed with LaTex, essentially how the preview panel works in stackexchange. For example, as I'm typing this, $this code$ would be displayed in typeset format (if I was on mathexchange) in real type as I'd be typing this message. Is there a libarary I can use for C++ that would let me write a program like that? Where should I begin? Thanks for your time! (Oh, I also plan on developing this through QT).


text:
Q: Use Windows Speech Recognition API in Unity I am trying to add System.Speech.dll to my Unity project but I get System.BadImageFormatException. I am using a 64 bit Windows 10. The build setting is set for x86_64 and the scripting runtime version I am using is ".Net 4.x equivalent".
That .dll I got it from "Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.6". What it is interesting is in MS Visual Studio it actually detect that dll and I can write: using System.Speech but Unity does not want to accept that .dll. I look over different posts but nothing worked for me. Any help appreciated.

A: You don't need System.Speech.dll and there are many issues that comes with it because it it using Mono. Just import the UnityEngine.Windows.Speech namespace an you should be good to go. This requires Unity 5.4.0b2 and above to work on Windows.
You have different types of spech API such as DictationRecognizer,GrammarRecognizer, KeywordRecognizer, PhraseRecognitionSystem, and PhraseRecognizer. The doc has many examples on how to use each one.
Below is an example of the KeywordRecognizer from the doc:
[SerializeField]
private string[] m_Keywords;

private KeywordRecognizer m_Recognizer;

void Start()
{
    m_Recognizer = new KeywordRecognizer(m_Keywords);
    m_Recognizer.OnPhraseRecognized += OnPhraseRecognized;
    m_Recognizer.Start();
}

private void OnPhraseRecognized(PhraseRecognizedEventArgs args)
{
    StringBuilder builder = new StringBuilder();
    builder.AppendFormat("{0} ({1}){2}", args.text, args.confidence, Environment.NewLine);
    builder.AppendFormat("\tTimestamp: {0}{1}", args.phraseStartTime, Environment.NewLine);
    builder.AppendFormat("\tDuration: {0} seconds{1}", args.phraseDuration.TotalSeconds, Environment.NewLine);
    Debug.Log(builder.ToString());
}

This is for Windows only since you're targeting Window-64 bit. For other platforms, see this post.


text:
Q: Addiing captions above images in wordpress So I added some code in my css and there are boxes that appear over every image that is attached to a post. I've wanted to number the images and show the image number in the box(1...n). I have this in my functions.php
edit: code was added here http://pastebin.com/gVszwf75
If I run only count_images it will show the correct number of attached images to a post(let's say 15). But for some reason the number that is shown in the boxes over the images is always 1. I've seen this done on several blogs with just php so there has to be a way(even if I have to change my whole code).

A: The problem with your code is that you're looping through the array each time you call your callback function caption_image_callback() ... it has no memory of how many times it's looped!
The easiest way to fix this is to add a global variable at the beginning of the plug-in, I call it $caption_image_count and set it equal to zero.  Then call the variable in caption_image_callback() and increment by 1 each time you call the function.  This will keep track of the number of captioned images you have on the page.
If you want, you can also re-set the variable to zero before you return $post_body_content in caption_image().  I've posted the full solution to your pastebin: http://pastebin.com/sFe6dhqL


text:
Q: associate existing fields from class methods sequelize I have this two Sequelize models generated from the CLI

'use strict';
module.exports = function(sequelize, DataTypes) {
  var ticket_sold = sequelize.define('ticket_sold', {
    ticket_id: DataTypes.INTEGER,
    bus_id: DataTypes.INTEGER,
    departure: DataTypes.INTEGER,
    destination: DataTypes.INTEGER,
    passenger_id: DataTypes.INTEGER,
    amount: DataTypes.FLOAT,
    status: DataTypes.BOOLEAN,
    is_deleted: DataTypes.BOOLEAN
  }, {
    classMethods: {
      associate: function(models) {

      }
    }
  });
  return ticket_sold;
};

and

'use strict';
module.exports = function(sequelize, DataTypes) {
  var locations = sequelize.define('locations', {
    name: DataTypes.STRING,
    status: DataTypes.BOOLEAN,
    is_deleted: DataTypes.BOOLEAN
  }, {
    classMethods: {
      associate: function(models) {

      }
    }
  });
  return locations;
};

I need to associate the Departure and Destination to the Id of the location field. I could not just use the has many/belongsto as it creates another field.
I tried doing
tickets_sold.departure.belongsTo(models.locations,{
          onDelete:"CASCADE",
          foreignKey:{
            allowNull:false
          }
        })
but it was of no use.
How can I associate the two fields with the location table?

A: You need to use the targetKey property
From the docs :

The target key is the column on the target model that the foreign key column on the source model points to. By default the target key for a belongsTo relation will be the target model's primary key. To define a custom column, use the targetKey option.

So in your case you will need to do something like :
tickets_sold.belongsTo( models.locations, { targetKey: 'departure' } );
tickets_sold.belongsTo( models.locations, { targetKey: 'destination' } );


text:
Q: Changing the text colour in the Appbar without changing the text colour in rest of app I would like to set the text color in my app bar to white and leave the text in the rest of my application as the default black colour.
Setting the android:textColorPrimary to white make the app bar text to white, but also make the text in drop downs and calendar dialog fragments white.
How do I make the text in the app bar white, without changing the colour of the text in drop downs and calendar dialog fragments?

A: I'd suggest you to manually add a Toolbar to your activity and have a TextView inside of it-
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/text_view"
            android:layout_width="match_parent"
            android:text="App Title"
            android:textColor="@colors/colorBlack"/>

    </androidx.appcompat.widget.Toolbar>

You might also need to set the parent theme to

Theme.AppCompat.Light.NoActionBar

A: you can try this to make default text color white in app bar:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        ...
        <item name="actionBarStyle">@style/CustomActionBar</item>
    </style>

    <style name="CustomActionBar" parent="@style/Widget.AppCompat.ActionBar">
        <item name="titleTextStyle">@style/CustomTextAppearance</item>
    </style>

    <style name="CustomTextAppearance" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:textColor">#FFFFFF</item>
    </style>

    ...

</resources>

A: In your styles.xml add :
<style name="ToolbarTheme" parent="@style/ThemeOverlay.AppCompat.ActionBar">
    <!-- Customize color of navigation drawer icon and back arrow -->
    <item name="colorControlNormal">#fff</item>
</style>

Then in your layout file add custom toolbar:
<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/anyId"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:title="Yor title here"
        app:titleTextColor="#fff"
        android:theme="@style/ToolbarTheme"
        app:layout_scrollFlags="scroll|enterAlways"/>

</android.support.design.widget.AppBarLayout>


text:
Q: MVC 3 dynamic authorization of multiple roles and users I recently starded developing for MVC 3 but have experience in both C# and ASP.NET since earlier. So i'll start with what i'm trying to accomplish. I've developed a small site for hosting articles. I've implemented SQLServer based membership managament to the site. Now i want to create a credentials system that restricts and allows the right users to create, delete and update articles. There is one simple solution to this and that is to do it like this:
[Authorize(Roles="Admin")]
    public ActionResult UpdateArticle(ArticleModel model, int articleid)
    {
        return View();
    }

Now this is really simple. I simply say that only members that are in the role "Admin" are allowed to update an article. But that's just to static. So i created a credentials table in my database that in the end tells me that "Article 5 can be edited by roles 1,2,3 & 4 and by users A, b & C". So far so good. But how would i implement that with the Authorize solution?
I would like to do something like this:
[Authorize(getAuthorizedusers("update",this.articleid))]

where getAuthorizedusers returns which users and roles are authorized to update the article with the articleid that was passed to it.
So I have (at least) two problems here:
-Getting the Authorize method to accept multiple users and roles.
-Passing the supplied articleid, that was sent to the UpdateArticle method, to the getAuthorizedusers method.

A: You can create your own custom attribute that inherits from AuthorizeAttribute and override the OnAuthorize method to do what you need.
This should get you started:
public class ArticleAuthorizeAttribute : AuthorizeAttribute
{
    public enum ArticleAction
    {
        Read,
        Create,
        Update,
        Delete
    }

    public ArticleAction Action { get; set; }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        //do custom authorizization using Action and getting ArticleID
        //from filterContext.HttpContext.Request.QueryString or
        //filterContext.HttpContext.Request.Form
    }
}

The usage would look like this:
[ArticleAuthorize(Action=ArticleAuthorizeAttribute.ArticleAction.Update)]

Edit: After looking into this a bit more, it looks like you can't pass this.articleID in to the attribute. However, you do have access to the parameters from filterContext.HttpContext.Request through the QueryString property or the Form property, depending on how you are passing the values. I have updated the code sample appropriately.
A more complete example can be found here
To check for authorization using user role and user list you would do something like this:
        var allowedUsers = new List<string>();
        //populate allowedUsers from DB

        If (User.IsInRole("Update") || allowedUsers.Contains(User.Identity.Name))
        {
            //authorized
        }

Alternatively, you can do both checks against the DB directly in a single method to keep from making two calls.

A: Here's a much easier way to accomplish the same thing:
[Authorize]
public ActionResult UpdateArticle(ArticleModel model, int articleid)
{
    // if current user is an article editor
    return View();
    // else
    return View("Error");
}

A: I got it working as I wanted when I overrode the AuthorizeCore method and authorizes the way I want to.
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }

        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated)
        {
            return false;
        }

        if ((_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) && (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)))
        {
            return false;
        }

        return true;
    }


text:
Q: java.lang.IllegalStateException: Unable to create layer for v I have this exception on crashlytics and have no idea how to reproduce or what the cause might be. Does anyone have any pointers as to where I should start looking? Only affects Android 5+.
Fatal Exception: java.lang.IllegalStateException: Unable to create layer for v
       at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
       at android.os.MessageQueue.next(MessageQueue.java:323)
       at android.os.Looper.loop(Looper.java:135)
       at android.app.ActivityThread.main(ActivityThread.java:5585)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

Thanks.
Edit: I would like to update that it doesn't only affect Android 5, it seems to affect Android 5+

A: Fatal Exception: java.lang.IllegalStateException: Unable to create layer for LinearLayout, size 1080x4160 exceeds max size 4096
       at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
       at android.os.MessageQueue.next(MessageQueue.java:323)
       at android.os.Looper.loop(Looper.java:136)
       at android.app.ActivityThread.main(ActivityThread.java:6186)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

I have same issue for RecyclerView inside NestedScrollView
RecyclerView <- inside NestedScrollView
Solution:
As RecyclerView inside scrollview or nestedscrollview try to load all items at once. As RecyclerView loads all items at once, also loads items that are not visible right now on screen. If you put log inside onBindViewHolder of RecylerView you find that all items loads at the start instead of based on the visibility of the item.
This causes UI to load more than 1-1.5 screens of content at a time. This causes the parent LinearLayout (inside the ScrollView) to throw exception. It's suggested to paginate your content and load no more than 1-1.5 screens of content at a time. I had also issue related to same with Recyclerview without animation.

A: adding android:hardwareAccelerated="false" to application tag in manifest solve my problem
EDIT:
please see comment by @inteist

A: I also faced this issue when I tried to create a simple View. I just had to set android:forceHasOverlappingRendering="false" in its xml. Note that it only works from API level 24.

A: This issue seems related to Scene transition with hero elements throws Layer exceeds max. dimensions supported by the GPU.
You should look at any activity transaction you are making and particularly for the effects of makeSceneTransitionAnimation().

A: In my case, it was a silly mistake and Android Studio didn't show any warning.
I had a view set with the id of @+id/myView yet I had also set in the same view/tag android:layout_below=@id/myView.
Something like this:
<TextView
    android:id="@+id/textview"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_below="@id/textview" /> <!-- The traitor :( -->


text:
Q: Play music on background , Ruby on rails What is SIMPLE and good practice to play background music in Rails App.
It's a really simple rails website. It has several static pages.
How do I playing music on background?
thanks!
I am not looking for detailed answer or code.
I just want somebody kindly point me some links, or some keywords I can search.
I googled around and did not find what I want/ Or I didnt realize that was I need.

A: with HTML 5, you can now use the  tag like this. You can place this on any page that you want your music to play on. (layouts/application.html.erb if you want site-wide)
<audio src="public/my_audio_file.mp3" autoplay controls loop>

Your browser does not support HTML5 audio playback

</audio>

This link provides further details and options
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_HTML5_audio_and_video

A: Add this to the pages on which you want the sound
<embed src="path/to/background.mp3" autostart="true" loop="true" hidden="true"><embed>

Add it to the layout if you want it in all the pages


text:
Q: probability generating function with die
Given a fair six-sided die. Find the probability generating functions for the number of the throw on which the rth six appears. Hence find the probability that the fifth six occurs on the 20th throw.

For the rth six is it true that $X~Geo((1/6)^r)$, so PGF is $(1/6)^rt+(1/6)^r\times(1-(1/6)^r)t^2$ etc? And for the 20th throw do I look for the coefficient of $t^{20}$?

A: We will calculate the PGF as asked for in the problem. The probability that the $r$-th six occurs after $n$ rolls of the die is
$$ \frac{1}{6} \binom{n-1}{r-1}
\left(\frac{5}{6}\right)^{n-r}  \left(\frac{1}{6}\right)^{r-1}.$$
Therefore the PGF is
$$p(z) = \sum_{n\ge r}  \binom{n-1}{r-1}
\left(\frac{5}{6}\right)^{n-r}  \left(\frac{1}{6}\right)^r z^n =
 \left(\frac{1}{6}\right)^r  \left(\frac{6}{5}\right)^r
\sum_{n\ge r}  \binom{n-1}{r-1}
\left(\frac{5}{6}\right)^n  z^n \\=
\left(\frac{1}{5}\right)^r
\sum_{n\ge r}  \binom{n-1}{r-1}
\left(\frac{5}{6}\right)^n  z^n =
\left(\frac{1}{5}\right)^r
\sum_{n\ge 0}  \binom{n+r-1}{r-1}
\left(\frac{5z}{6}\right)^{n+r} \\=
\left(\frac{z}{6}\right)^r
\sum_{n\ge 0}  \binom{n+r-1}{r-1}
\left(\frac{5z}{6}\right)^n.$$
Now note that $$ \sum_{n\ge 0}  \binom{n+r-1}{r-1} q^n = \frac{1}{(1-q)^r}$$
so that $$ p(z) = \left(\frac{z}{6}\right)^r  \frac{1}{(1-5z/6)^r} =
\left(\frac{z}{6-5z} \right)^r$$
It follows that the desired probability is
$$ [z^{20}]  \left(\frac{z}{6}\right)^5  \frac{1}{(1-5z/6)^5} =
\left(\frac{1}{6}\right)^5 [z^{15}] \frac{1}{(1-5z/6)^5} =
\left(\frac{1}{6}\right)^5 \binom{15+4}{4}
\left( \frac{5}{6}\right)^{15} \sim
0.0323525. $$

A: See "negative binomial". With parameters r and p, a negative binomial random variable represents the trial number of the rth success when each trial is independently a success with probability p.
r = 5
p = 1/6
i = 20
(sorry in advance for formatting, coding errors etc.)
$p(i=20)$ = ${19 \choose 4}$$(1/6)^5$$(5/6)^{15} $

A: A straight forward application of the Negative Binomial Distribution where the number of trials $n$ is fixed and made up of $k$ failures and $r$ successes, the $r$th success occurring on the $n$th trial
$$X \sim NB(k;r,p)=\binom {k+r-1}{r-1}p^r(1-p)^k$$
$k$ is the number of failures within the $n$ trials, the number of times a six was not rolled
$r$ is the number of successes within the $n$ trials, the number of times a six was rolled
$p$ is the probability of success, of rolling a six
$$X \sim NB(15;5,\frac{1}{6})=\binom {19}{4}\bigr(\frac{1}{6}\bigr)^5\bigr(\frac{5}{6}\bigr)^{15}$$
With a little effort, Marko Riedel's answer could be generalised to prove the result I've quoted


text:
Q: C# Directory of windows How to find the partition in which windows is installed using java or c#? so that the file access will be dynamic in different computers ie it will access the C: of D: where windows is installed

A: Try this in c#. This will help you to get Windows directory.
String Text= Environment.GetEnvironmentVariable("windir");

A: This should be Path.GetPathRoot(Environment.SystemDirectory) in C#.

A: You can use the property SystemDirectory of the System.Environment class in C#.

A: For C# that would be Path.GetPathRoot(Environment.SystemDirectory), this will give you the root path like "C:\"


text:
Q: firebase security-rules write access to only one specific field is it possible to give update access to only one specific field ?
users
  + gaglajasdfer32fasfa
    - Name: Luke     // not allowed to update
    - likes: 3       // allowed to update

A: You will have to specify the rule for each field in that case as shown below:
{
  "rules": {
    "users": {
      "$uid": {
        "Name": {
         ".write": "!data.exists()"
        }
      }
    }
  }
}

!data.exists() allows write operation only when it's absent now and hence allowing "Create" operations only and not "update" or "delete".
Checkout the documentation to learn more about security rules.


text:
Q: General formula for $\int_a^b(x-a)^m(x-b)^ndx$ Recently, I stumbled upon this:

$$\int_a^b (x-a)^3(x-b)^4dx$$

I did this in many ways - using IBP multiple times and by even expanding both terms like a madman.
The result was: $$\frac{(a-b)^8}{280}$$
I was astonished by this cute little result. So I started wondering about evaluating the following:
$$\int_a^b(x-a)^m(x-b)^ndx$$
I wanted to use reduction to obtain a result similar to Wallis' formula for sine and cosine

Any other method is always welcome

A: Start using IBP:
$$I_{(m,n)}=\int_a^b(x-a)^m(x-b)^ndx=0-\int_a^b m(x-a)^{m-1}\frac{(x-b)^{n+1}}{n+1}dx=-\frac{m}{n+1}I_{(m-1,n+1)}$$
Applying IBP multiple times, we obtain $$I_{(m,n)}=(-1)^{m+1}\frac{m!.n!}{(n+m)!}I_{(0,n+m)}$$
$$\boxed{I_{(m,n)}=(-1)^{m+1}\frac{m!.n!}{(n+m+1)!}(a-b)^{n+m+1}}$$

A: Let $u=(x-a)/(b-a)$ so that
\begin{align}
\int_a^b(x-a)^m(x-b)^ndx=(-1)^m(b-a)^{m+n+1}\int_0^1u^m\left(1-u\right)^ndx
\end{align}
and latter integral is a well-known quantity.

A: I liked your method the best.But if you are fine with using wallis formula,here is a hint;
Hint use the substituition $$x=a+({b-a})\sin^2 \theta$$
$$dx=2(b-a)\sin \theta \cos \theta d\theta$$
can you take it from here?


text:
Q: Error Injecting FeignClient from another Project I am having trouble auto wiring a feign client from another project. It appears that the implementation of the feign client is not being generated and injected.
This is the error I am getting.
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'passportRestController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private com.wstrater.service.contacts.client.ContactService com.wstrater.service.passport.server.controllers.PassportRestController.contactService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.wstrater.service.contacts.client.ContactService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}

The feign client is pretty straight forward. I have removed the imports for brevity.
package com.wstrater.service.contacts.client;

@FeignClient("contact-service")
public interface ContactService {

  @RequestMapping(method = RequestMethod.GET, value = ContactConstants.CONTACTS_USER_ID_PATH)
  public Collection<Contact> contactsByUserId(@PathVariable("userId") String userId);

}

I added the component scan to my project to include the application and it's controllers and to include the feign client in the other project.
package com.wstrater.service.passport.server;

@EnableEurekaClient
@EnableFeignClients
@SpringCloudApplication
@ComponentScan({"com.wstrater.service.passport.server",
                "com.wstrater.service.contacts.client"})
public class PassportServiceApplication {

  public static void main(String[] args) {
    ApplicationContext ctx = SpringApplication.run(PassportServiceApplication.class, args);
  }

}

The rest controller with most of the imports removed for brevity.
package com.wstrater.service.passport.server.controllers;

import com.wstrater.service.contacts.client.ContactService;

@RestController
public class PassportRestController {

  @Autowired
  private ContactService contactService;

  @RequestMapping(PassportContstants.PASSPORT_USER_ID_PATH)
  public ResponseEntity<Passport> passportByUserId(@PathVariable String userId) {
    ResponseEntity<Passport> ret = null;

    Collection<Contact> contacts = contactService.contactsByUserId(userId);
    if (contacts == null || contacts.isEmpty()) {
      ret = new ResponseEntity(HttpStatus.NOT_FOUND);
    } else {
      ret = ResponseEntity.ok(new Passport(contacts));
    }

    return ret;
  }

}

I have tried defining the feign client interface in different projects and different packages and have only seen success when it put it in the same package as the application. This make be believe that it is a component scan issue even though I am including the package in the scan. I would like to keep the feign client interface in a shared project to define a reusable "contract" and for each project to have a unique package structure instead of defining the feign client with the application using it.
Thanks, Wes.

A: You need to tell the Feign scanner where to locate the interfaces.
You can use @EnableFeignClients(basePackages = {"my.external.feign.client.package", "my.local.package"}).

A: Direct Class/Interface name can be given like below
@EnableFeignClients(basePackageClasses=com.abc.xxx.client.XXFeignClient.class)

This parameter accept single or multiple class name

A: My main class was in package "com.abc.myservicename" and my main class name was "myservicename.java". I was using @SpringBootApplication(scanBasePackages="com.abc") annotation in my main class.
Changing the main class package name to "com.abc" has resolved the issue for me.

A: Thanks for the help. I added the right external package in
@EnableFeignClients(basePackages = {})
It still did not pick up the feign client implementation.
I had a PACT contract test where I was autowiring the api client bean. I had used @ExtendWith(SpringExtension.class) which was the issue.
I replaced with @SpringBootTest, which allowed the feign client bean to be exposed in this class

A: Faced the Same issue where i was not able to @Autowire the FeignClient interface, Changing the Version of Feign Client in pom.xml to 3.0.1 or latest has helped me in resolving the issue.

A: This worked for me.
Adding annotation to main class
@EnableFeignClients(defaultConfiguration = {FeignBasicConfiguration.class}, basePackages = {"com.example"})


text:
Q: Html + JavaScript + CSV parsing + Google Charts help oh joy xD ... So I am trying to make a program that will take a csv file and generate a google chart, it deals with listing current virtual machines, then how much memory in gb they have used vs how much is free. I am pretty noob with javascript and spent most my work day trying to get this crap so any help is highly appreciated! So currently what I used is jquery.csv-0.71 extension. and to give you a sample of my csv I will just paste some right here:
"Name","UsedSpace","Capacity"
"GVLVNX00","378","500"
"GVLVNX01","421","500"
"GVLVNX02","351","500"
"GVLVNX04","421","500"
"GVLVNX05","283","500"

With that sample in mind and the knowledge of my helper jquery csv file what is going wrong now in here. I am sure there are lots, and one error I get is related to the horizontal data cant be a string? Which makes no sense, I want the VM names to go on the x axis derp :/ ... But otherwise here is the code. My goal is to make a graph that actually has the bars overlap and I know this one doesn't have that but its at least a start. I could not even find any that had the bars overlap like I wanted to show free vs used memory but if you find a graph better suited please show me the code to accomplish it :) . So here is my html / javascript portion some might be commented out etc cause I was getting an error or debugging. Sorry if you read all that, I ramble slightly.
<!DOCTYPE html>
<html>
<head>
   <title>Google Chart Example</title>
   <script src="https://www.google.com/jsapi"></script>
   <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
   <script src="jquery.csv-0.71.js"></script>

   <script>
   // load the visualization library from Google and set a listener
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawChart);

   function drawChart() {
   // grab the CSV
   $.get("DBdatastores.csv", function(csvString) {

   // transform the CSV string into an array
    var arrayData = $.csv.toArrays(csvString);

    // this new DataTable object holds all the data
    var data = new google.visualization.arrayToDataTable(arrayData);

    var options = {
          title: 'Virtual Machine Storage(GB)',
          hAxis: {title: "Virtual Machine Names", titleTextStyle: {color: 'red'}}
        //  vAxis: {title: "Memory In GB", minValue: 0, maxValue: data.getColumnRange(2).max}
        };

    var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
    chart.draw(data, options);
     });
    }
   </script>

</head>
<body>
    <div id="chart">

   </div>
</body>
</html>

Thanks for the help if anyone knows how to do this kinda crap, I am a php/mysql dev this is
not my ideal task haha.

A: The problem is likely in one of two places: either in your CSV file, or with the jQuery CSV plugin.  Your "UsedSpace" and "Capacity" data series are being interpreted as "string" type, which isn't valid to draw a chart with - they must be "number" type.  The first thing I suggest is removing the quotes from around your numbers in the CSV:
"Name","UsedSpace","Capacity"
"GVLVNX00",378,500
"GVLVNX01",421,500
"GVLVNX02",351,500
"GVLVNX04",421,500
"GVLVNX05",283,500

You then need to tell the jQuery CSV plugin to parse your data as numbers when possible:
var arrayData = $.csv.toArrays(csvString, {
    onParseValue: $.csv.hooks.castToScalar
});


text:
Q: How to use mPDF in YII, when I want to generate PDF file from HTML? $mPDF1 = Yii::app()->ePdf->mpdf();
$mPDF1 = Yii::app()->ePdf->mpdf('', 'A4');
$html= $this->renderPartial('poPdfTemplate', array('pdfValues'=>$ponumberData,'po_number'=>$po_number), true);
$mPDF1->WriteHTML($html,0);
//$mPDF1->WriteHTML($html);
$mPDF1->Output();

The above code is using for generating PDF with YII framework.

A: First two lines will create css $pdf_style and html file $pdf_part and PDF will be write this file.
Include these 2 variables in the WriteHTML function.
    $pdf_style = \Yii::$app->view->renderFile(PROTECTEDPATH . 'common/views/contract/style.css', $data);
    $pdf_part = \Yii::$app->view->renderFile(PROTECTEDPATH . 'common/views/contract/file.tpl', $data);

    $mpdf = new \mPDF('utf-8','A4');

    $mpdf->autoScriptToLang = true;
    $mpdf->baseScript = 1;  // Use values in classes/ucdn.php  1 = LATIN
    $mpdf->autoVietnamese = true;
    $mpdf->autoArabic = true;
    $mpdf->autoLangToFont = true;

    $mpdf->SetMargins(null,null,40);
    $mpdf->SetDisplayMode('fullpage');
    $mpdf->SetHTMLHeader('

');

    $mpdf->setFooter(' | www.facebook.com | {PAGENO}');
    $mpdf->WriteHTML($pdf_style.'
'.$pdf_part.'
');

    $mpdf->Output('Contract-'.date("iYsmd"), $action, $dest);


text:
Q: Perform http request before switching to next route I want to perform a post request when navigating away from the page to any other route.
I have tried using:
  this.subscriptionGrade = router.events
      .pipe(filter((event) => event instanceof NavigationStart))
      .pipe(
        concatMap(() => {
          return this.submitScore();
        })
      )
      .subscribe((res) => {
        this.snackBar.openSnackBar("Score submitted", "");
      });

  submitScore() {
    const score = { score: this.scoreForm.get("score").value };
    if (this.scoreForm.get("score").value) {
      return this.learningContentService.gradeAssignment(
        this.selectedAttempt,
        score
      );
    } else {
      return of(null);
    }
  }

This performs the http reuquest but switches to next route before a response is recieved from the http request and the request is getting cancelled.

A: You can use canDeactivate on this route and check if the http call is successful or no
export interface CanComponentDeactivate {
 canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

...

@Injectable()
class CanDeactivateComponent implements CanDeactivate<CanComponentDeactivate>{
 constructor() {}
 canDeactivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
 let data= route.data.data;
 return this.service.post(url, data)
   .pipe(
     map(response => response.status === 'success'),
     catchError(error => of(false))
   );
 }
}

your route
{
 path: 'yourRoute',
 component: Component,
 canActivate: [CanDeactivateComponent ],
 data: { data: {...}}
}


text:
Q: How to filter out certain objects in a table with certain ids? (Rails 4, Postgresql) before I ask my question, I will provide some context.
I have 3 Models which interact with each other.
Scoreboard has many Teams. Team belongs to Scoreboard.

The following use a through table.
Scoreboard many-to-many with User.(let's call this Scoreboard.followers)

Team many-to-many with User.(Let's call this Team.members)

I have a Team_Members Controllers with the following method:
Team_member#new Method:
def new
        @selected = true
        @scoreboard = Scoreboard.find(params[:scoreboard_id])
        @team = Team.find(params[:team_id])
        @team_members = @team.members
        @followers = @scoreboard.followers.search(params[:search]).paginate(page: params[:page], per_page: 50)
end

What I'm attempting to do is display all the Scoreboard followers in my new.html.erb view. I can search through them and add members to a Team that is associated to the same Scoreboard.
Here's is the new.html.erb view:
<%= form_tag(new_scoreboard_team_team_member_path, :method => "get", id: "member-search-form", autocomplete: "off") do %>

        <%= text_field_tag :search, params[:search], placeholder: "Filter Members by Name", class:"form-control" %>

<% end %>

<% if @followers.any? %>

        <% @followers.each do |follower| %>
            <div class="row member-follower-div" id="follower_<%=follower.id%>">

                    <%= link_to follower.name, user_path(follower.id) %>

                    <%= link_to (add_scoreboard_team_team_member_path(@scoreboard,@team, follower)), method: :post, remote: true, :data => {:disable_with => ".."} do %>

                    <% end %>

        <% end %>

                <%= will_paginate @followers %>

<% end %>

Okay now for the question. The problem arises in the controller method. The @team.members and @scoreboard.followers both source objects from the Users table. How would I filter out the User objects from the @scoreboard.followers that exist in the @team.members? I don't want to display @followers on my view that are a part of the @team.members collection. Also, as a bonus, I would like to alphabetically order the followers by user.name.
I tried the .where("users.id NOT IN (?)", @team_members.pluck(:id)) but if @team_members collection is null, no results are displayed on the page.

A: I solved it like so:
def new
        @selected = true
        @scoreboard = Scoreboard.find(params[:scoreboard_id])
        @team = Team.find(params[:team_id])
        @team_members = @team.members
        if (@team_members.any?)
           @wonderful_humans = @scoreboard.favourited_by.where("users.id NOT IN (?)", @team_members.pluck(:id)).search(params[:search]).sort_by{ |a| a.name.downcase }
        else
           @wonderful_humans = @scoreboard.favourited_by.search(params[:search]).sort_by{ |a| a.name.downcase }
        end
        @followers = @wonderful_humans.paginate(page: params[:page], per_page: 50)
    end


text:
Q: Votes vs Score in review queue The review queue gives the reviewer an indication of the post quality by means of the post votes (3 in this case):

However, this is actually the post score (6 up-votes minus 3 down-votes = 3 score):

Can we change this to score rather than votes?