text:
Q: Is there something wrong with my KMP algorithm? I am doing a project to compare the time complexity of 2 string search algorithms.
I lost my previous code due to some issues and so have had to rewrite the majority.
However, this time around, my KMP algorithm seems to be running a lot slower, and I can never actually get it to run faster than my Boyer-Moore no matter what I input.
Here is my code:
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
#include <chrono>
using namespace std;

//set number of characters for lookup table
# define number_chars 256

//type alias for clock
typedef chrono::steady_clock clocktime;

void boyer_moore(string text, string pattern, int textlength, int patlength) {

    //start timer
    clocktime::time_point start = clocktime::now();

    //create vector list of all the locations the pattern was found
    vector<int> indexes;

    //create array for lookup table
    int lookup[number_chars];

    //initially fill every index of lookup table with -1
    for (int i = 0; i < number_chars; i++) {
        lookup[i] = -1;
    }
    //for every character in pattern, set lookup table at index = integer value for character to be the index of the character within the pattern
    for (int i = 0; i < patlength; i++) {
        lookup[(int)pattern[i]] = i;
    }
    //shift variable for keeping track of location in text
    int shift = 0;

    while (shift <= (textlength - patlength)) {
        int j = patlength - 1;

        //works through pattern from end to start checking if characters in text match, stops when j<0 or character in text doesn't match character in pattern
        while (j >= 0 && pattern[j] == text[shift + j]) {
            j--;
        }
        //if pattern found
        if (j < 0) {

            //add location pattern was found to location list
            indexes.push_back(shift);

            //if have not reached end of text
            if (shift + patlength < textlength) {

                //skip over pattern just found so next character in text lines up with last character of pattern
                shift += patlength - lookup[text[shift + patlength]];
            }

            //if pattern occurs at end of text add 1 to shift -> next while loop will fail
            else {
                shift += 1;
            }
        }
        //if pattern not found
        else {

            //checks if current character in text is an ASCII character -> if not it would be negative
            //(was having some issues previously with non-ASCII characters setting my array to out of bounds so added this condition)
            if (lookup[text[shift + j]] > -1) {

                //shifts pattern so unmtaching character in text lines up with last character in pattern
                shift += max(1, j - lookup[text[shift + j]]);
            }

            //if non-ASCII character, then it is not in pattern being searched anyway -> skip to next character
            else {
                shift += 1;
            }
        }
    }
    //end timer
    clocktime::time_point end = clocktime::now();

    //calculate time taken
    auto time_taken = chrono::duration_cast<chrono::milliseconds>(end - start).count();

    //display index locations of pattern
    cout << "Index locations of '" << pattern << "':" << endl;
    for (int in : indexes) {
        cout << in << ", ";
    }

    //display time taken
    cout << endl << endl << endl << "Boyer-Moore: time taken: " << time_taken << "ms" << endl << endl << endl;
}

void kmp(string text, string pattern, int textlength, int patlength) {

    //start time
    clocktime::time_point start = clocktime::now();

    //create vector list of all the locations the pattern was found
    vector<int> indexes;

    //creates prefix table
    //had to use vector as compiler was complaining about patlength not being a constant value, even when I set it it const int
    vector<int> table(patlength);

    //keeps track of length of previous longest prefix suffix
    int k = 0;

    //filling in prefix table
    for (int i = 1; i < patlength; i++) {
        while (k > 0 && pattern[k] != pattern[i]) {
            //u
            k = table[k-1];
        }
        if (pattern[k] == pattern[i]) {

            //update longest suffix
            k = k + 1;
        }
        table[i] = k;
    }
    int textindex = 0;
    int patindex = 0;
    while (textindex < textlength) {
        if (pattern[patindex] == text[textindex]) {
            textindex++;
            patindex++;
        }
        if (patindex == patlength) {
            indexes.push_back(textindex-patlength);
            patindex = table[patindex - 1];
        }
        else if (textindex < textlength && pattern[patindex] != text[textindex]){
            if (patindex != 0) {
                patindex = table[patindex - 1];
            }
            else {
                textindex++;
            }
        }
    }

    //end timer
    clocktime::time_point end = clocktime::now();
    auto time_taken = chrono::duration_cast<chrono::milliseconds>(end - start).count();
    cout << "Index locations of '" << pattern << "':" << endl;
    for (int in : indexes) {
        cout << in << ", ";
    }
    cout << endl << endl << endl << "KMP: time taken: " << time_taken << "ms" << endl << endl << endl;
}

//load file method borrowed from lab exercise
string load_file() {
    std::string directory = "";
    string text;
    for (int i = 0; i < 6; i++) {
        const string & filename = "dna.txt";
        //https://www.kaggle.com/ashishsinhaiitr/lord-of-the-rings-text/version/1#01%20-%20The%20Fellowship%20Of%20The%20Ring.txt
        ifstream f(directory + filename, std::ios_base::binary);
        if (!f.good()) {
            directory = "../" + directory;
            continue;
        }

        f.seekg(0, std::ios_base::end);
        const size_t length = f.tellg();

        vector<char> buf(length);
        f.seekg(0);
        f.read(buf.data(), length);
        text.assign(buf.begin(), buf.end());

        return text;
    }
}

void main() {

    //loads text file
    string text = load_file();
    bool end = false;
    while (end == false) {

        //gets pattern from user
        cout << "pattern: ";
        string pattern;
        cin >> pattern;
        int n = text.size();
        int m = pattern.size();

        //call both string search algorithms
        boyer_moore(text, pattern, n, m);
        kmp(text, pattern, n, m);

        //ask user if they want to end the program
        cout << "Close program? (1 = yes, 0 = no): ";
        bool valid = false;

        //checks if user provided valid response -> asks for another if not
        while (valid == false) {
            int userend;
            cin >> userend;
            if ((int)userend == 1) {
                valid = true;
                end = true;
            }
            else if ((int)userend == 0) {
                valid = true;
            }
            else {
                "Please enter a valid number: ";
            }
        }
    }
}

As an example, in my previous results, for the word "the", Boyer-Moore took around 260ms and KMP took around 184ms. Now, Boyer-Moore of course still takes roughly 260ms, however KMP now takes around 330ms.
Any pointers in the right direction would be greatly appreciated.
Thank you.


text:
Q: save a list of different Dataframes to json I have different pandas dataframes, which I put in a list.
I want to save this list in json (or any other format) which can be read by R.
import pandas as pd

def create_df_predictions(extra_periods):
    """
    make a empty df for predictions
    params: extra_periods = how many prediction in the future the user wants
    """
    df = pd.DataFrame({ 'model': ['a'], 'name_id': ['a'] })
    for col in range(1, extra_periods+1):
        name_col = 'forecast' + str(col)
        df[name_col] = 0

    return df

df1 = create_df_predictions(9)
df2 = create_df_predictions(12)
list_df = [df1, df2]

The question is how to save list_df in a readable format for R? Note that df1 and df2 are have a different amount of columns!

A: don't know panda DataFrames in detail, so maybe this won't work. But in case it is kind of a traditional dict, you should be able to use the json module.
df1 = create_df_predictions(9)
df2 = create_df_predictions(12)
list_df = [df1, df2]

You can write it to a file, using json.dumps(list_df), which will convert your list of dicts to a valid json representation.
import json
with open("my_file", 'w') as outfile:
    outfile.write(json.dumps(list_df))

Edit: as commented by DaveR dataframes are't serializiable. You can convert them to a dict and then dump the list to json.
import json
with open("my_file", 'w') as outfile:
    outfile.write(json.dumps([df.to_dict() for df in list_df]))

Alternatively pd.DataFrame and pd.Series have a to_json() method, maybe have a look at those as well.

A: To export the list of DataFrames to a single json file, you should convert the list into a DataFrame and then use the to_json() function as shown below:
df_to_export = pd.DataFrame(list_df)
json_output = df_to_export.to_json()
with open("output.txt", 'w') as outfile:
    outfile.write(json_output)

This will export the full dataset to a single json string and export it to a file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why cant we draw a square like triangle? I found the code in android documentation.
public class Square {

private FloatBuffer vertexBuffer;
private ShortBuffer drawListBuffer;

// number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 3;
static float squareCoords[] = {
        -0.5f,  0.5f, 0.0f,   // top left
        -0.5f, -0.5f, 0.0f,   // bottom left
         0.5f, -0.5f, 0.0f,   // bottom right
         0.5f,  0.5f, 0.0f }; // top right

private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices

public Square() {
    // initialize vertex byte buffer for shape coordinates
    ByteBuffer bb = ByteBuffer.allocateDirect(
    // (# of coordinate values * 4 bytes per float)
            squareCoords.length * 4);
    bb.order(ByteOrder.nativeOrder());
    vertexBuffer = bb.asFloatBuffer();
    vertexBuffer.put(squareCoords);
    vertexBuffer.position(0);

    // initialize byte buffer for the draw list
    ByteBuffer dlb = ByteBuffer.allocateDirect(
    // (# of coordinate values * 2 bytes per short)
            drawOrder.length * 2);
    dlb.order(ByteOrder.nativeOrder());
    drawListBuffer = dlb.asShortBuffer();
    drawListBuffer.put(drawOrder);
    drawListBuffer.position(0);
}

}
why can't we write simply the following code to accomplish the task?
private short drawOrder[] = {0,1,2,3};

Is this written so only for performance reasons or is it the only way to do this?

A: You can use {0,1,2,3} as the content of the index buffer. Instead of using GL_TRIANGLES as the primitive type, you'll have to specify GL_TRIANGLE_FAN as the first argument of glDrawElements() instead.
Or, if you swap the last two indices to make it {0,1,3,2}, you can draw them with the more commonly used GL_TRIANGLE_STRIP primitive type.
Both GL_TRIANGLE_STRIP and GL_TRIANGLE_FAN are used to draw sets of connected triangles.
In fact, if your indices form just a simple sequence, you don't need them at all. You can simply get rid of the whole drawOrder stuff, and draw your square with glDrawArrays() instead of glDrawElements():
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

A: OpenGL ES doesn't support quads as a native primitive type; only points, lines, and triangles.


text:
Q: Add a subject field to PHP email form I have an email form in PHP and I want to add a subject to the body of the email:
<?php
    if (isset($_POST["submit"])) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        $from = 'Camino Contact Form';
        $to = 'emailo@example.com';
        $subject = 'Message from Camino.bo ';
        $body ="From: $name\n E-Mail: $email\n Message:\n $message";

// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage) {
    if (mail ($to, $subject, $body, $from)) {
        $result='
Thank You! I will be in touch
';
    } else {
        $result='
Sorry there was an error sending your message. Please try again.
';
    }
}
    }
?>

This form submits an email with the subject "Message from Camino.bo", that's ok but I want to submit in the body of the email the value the user selects from a dropdown menu:
HTML:
<select name="subject" id="email_subject">
    <option value="default subject">Select a subject</option>
    <option>Product A</option>
    <option>Product B</option>
    <option>Product C</option>
</select>

How can I do this?
PS: the subject field in my form is optional with no validation required.

A: Your variables are a bit mixed up.  The 4th parameter of the mail() function is not 'From', it is 'Email Headers', which can be any number of header values in the correct format, each separated with a new line.  The 'From' will just be one of those headers..
$to = 'you@youremailaddress.com';

$subject = 'My Email Subject';

$body = 'The body text of your email....';

$headers  = "MIME-Version: 1.0\r\n".
            "Content-type: text/html; charset=iso-8859-1\r\n".
            "From: YOU <your@email.com>\r\n";
            // and others as required

mail($to, $subject, $body, $headers);

Add your POSTed options to the $body tag as required

A: I'm not sure if I'm missing something, but in your HTML, you want to add values to the remainder of your options:
<select name="subject" id="email_subject">
    <option value="default subject">Select a subject</option>
    <option value="Product A">Product A</option>
    <option value="Product B">Product B</option>
    <option value="Product C">Product C</option>
</select>

Then your PHP could be as follows:
<?php
if (isset($_POST["submit"])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'Camino Contact Form <youremailaddress@domain.com>';
    $to = 'emailo@example.com';
    $subject = 'Message from Camino.bo ';
    $select_subject = $_POST['subject'];

    $body ="From: $name\n E-Mail: $email\n Message: $message\n Subject: $select_subject";

    $headers = "From: " . $from;

    // If there are no errors, send the email
    if (!$errName && !$errEmail && !$errMessage) {
        if (mail ($to, $subject, $body, $headers)) {
            $result='
Thank You! I will be in touch
';
        } else {
            $result='
Sorry there was an error sending your message. Please try again.
';
        }
    }
}
?>

Notice that I've added $select_subject and added it to your email $body variable. Also please replace 'youremailaddress@domain.com' with the FROM email address you wish to use.
Also, I don't know if you already handle this elsewhere in your code, but I think you should display a message to screen if either $errName, $errEmail or $errMessage evaluate to true. Right now, if either one of those is true (assuming the code you pasted here is complete) your end user would get nothing displayed on their screen upon form submission and they might be confused by what happened and try to resubmit.


text:
Q: higher direct image: proof of the proper case. Hi.
Let $f:X→S$ be a proper, open, surjective morphism of complex reduced spaces with constant fiber dimension n (or universally open morphism with n-fibers between locally noetherian excellent without embedded component schemes on field of characteristic 0). Let $G$ be a coherent sheaf on X.
Claim: $R^{n}f_*G=0$ if and only if $Supp(G)\cap X_{s}$ is nowhere dense in the fiber $X_{s}$.
Outline of the proof:
1) If $Supp(G)\cap X_{s}$ is nowhere dense in the fiber $X_{s}$ and then
 $dim(Supp(G)\cap X_{s})<n$, it is not hard to see that $R^{n}f_∗G=0$.
For this, we use the fact that $Supp(G)\cap X_{s}$ is a compact subspace of dimension $\leq n-1$ and then admit a fundamental system of $n-1$-complete neighboorhoods (Demailly result on top degre cohomology...) each of them satisfies, in particular, $H^{n}(V, G)=0$; it suffices to write the definition of the germ $R^{n}f_∗G(s)$ as an inductive limit.
2) Suppose now $R^{n}f_∗G=0$. Then we have, by duality, $\pi_*\mathcal{H}om(G, \omega^{n}_{X/S}=0$. The openness and generic smoothness)  of $\pi$ imply that $\mathcal{H}om(G, \omega^{n}_{X/S})=0$. Therefore, we can use local $S$-embedding or local $S$ parametrization:
$\begin{array}{ccc} X & \overset{\sigma}{\to} & Z \\
& \underset{\pi}{\searrow} & \downarrow q \\
& & S \end{array}$
where $Z$ is an $n+p$-dimensional $S$-smooth complex space, or
$\begin{array}{ccc} X & \overset{f}{\to} & Y \\
& \underset{\pi}{\searrow} & \downarrow q \\
& & S \end{array}$
where $f$ is finite, open and surjective over  $Y:=S\times U$ of relative dimension $n$.
Then the isomorphism
$$f_{*}{\cal H}om(G,\omega^{n}_{X/S})\simeq{\cal H}om(f_{*}G, {\cal O}_{Y})$$
$$\sigma_{*}{\cal H}om(G,\omega^{n}_{X/S})\simeq {\cal E}xt^{p}(\sigma_{*}G, \Omega^{n+p}_{Z/S})$$
proves the claim.
We see that the problem reduce to the case of the projection
$q:S\times U\rightarrow S$, where $U$ is either a Stein in ${\Bbb C}^{n+p}$ or in $ {\Bbb C}^{n}$,  and coherent  sheaf $ G$ on $S\times U$ satisfiying one of this conditions:
$$ {\cal H}om( G, {\cal O}_{S\times U})=0,\,\,{\rm or }\,\,{\cal E}xt^{p}( G, {\cal O}_{S\times U})=0$$ `
We deduce what we want thanks to this:

Let $k$ be a noetherian local ring with residual field $\mathfrak{k}$, $R$ be a $k$-algebra formally smooth over $k$, $N$ be the Krull dimension of the regular local ring
    $R{\otimes_{k}}\mathfrak{k}$. Let $q$ be an integer and $M$ an  $R$-module of finite type. Then
    $${\rm dim}_{(R{\otimes_{k}}\mathfrak{k})} M\otimes_{k}\mathfrak{k}\leq q\,\Longleftrightarrow {\rm E}xt_{R}^{j}(M, R)= 0 \quad \text{for} \quad j<N-q$$


text:
Q: When running my program, nothing is shown in the console public class quartz {

    public static void main (String[] args) {
        int i = 0;
        int sum = 0;
        int[] n1 = {54, 40, 37, 64, 81, 15, 65, 72, 61, 57, 83, 3, 67, 12, 30, 54, 11, 51, 3, 78, 48, 31, 68, 77, 64, 68, 95, 68, 35, 82, 57, 26, 67, 41, 47, 80, 36, 88, 5, 9, 55, 87, 77, 8, 65, 31, 7, 79, 49, 22, 32, 94, 34, 12, 20, 30, 91, 12, 57, 77, 37, 96, 22, 29, 17, 76, 36, 56, 80, 33, 20, 65, 57, 40, 50, 97, 20, 92, 25, 14, 19, 84, 12, 62, 20, 42, 99, 52, 88, 29, 75, 48, 27, 73, 46, 72, 48, 84, 19, 55};
        while (i < n1.length)
            sum += n1[i];
        i = 0;
        System.out.println("Sum: " + sum + ".");
        System.out.println("Average: " + (sum/n1.length) + ".");

        double[] NE = {-0.6179074665219488, 0.012080423982449795, -0.21346000509541063, 0.08299652983289585, 2.44401680106775, 4.902778859313734, 1.7132831483350532, -4.2004763396051725, -4.043856195861675, -2.6728507023602326, 5.181911533071974, -2.1235877432845354, 7.603895698367564, -5.6730748575837975, -3.5868701412258464, 8.50824673494424, 1.9530312960520657, 1.4057711751329447, -6.6010520166956885, -0.8889270825881894, -3.066437913144831, -1.047977711607209, -0.6183425325427638, -1.9567474971238643, -1.6108985491087715, -3.4762343504063105, -0.7819967483948718, 1.2787199500848474, -1.724036624119682, 4.134045084705252, -4.302090407212001, 4.522452909896921, -9.510982189042458, 4.483571903648103, 4.734972592935479, 1.3007048393668028, -1.5733757395516363, -1.9343054344201707, 6.787212280236046, -0.35603892339489995, -1.3414921239899753, -0.9393551256779856, -1.9298884254368263, 6.043295105337908, 2.9330671137121733, 2.8561036619044047, -0.8293767467550212, 6.123622142714353, -2.2350961485598777, 7.20722805161423, 5.515389689089437, -2.7666432567169745, -4.344590134196103, 3.3453531590362613, 10.413288779778698, 0.3986583788822756, 1.8156402784897105, -6.495232639280744, -2.5586148068696852, 2.456750085945401, -2.0241915465317994, 2.6640207424833706, -3.221638093253812, -0.13291701098446618, 4.525894152095317, 3.833943185257407, -2.892260297173234, -3.247865929061468, 6.129696012756685, 4.451839001858698, -3.142375819178058, -1.0758596832313212, -7.85705595464708, -3.376343621066232, -3.993944532318441, 13.146850947670861, -1.3900676627648902, 3.8600378751921256, 3.9652071948870447, -2.4382860496298324, 3.0864605092488304, -10.769089293963074, 1.9773754511588617, 4.826841112732377, 7.9219782116860324, -3.266132871461332, 1.8118819669439024, 0.698579723806034, 7.119629551067371, -0.9141128559070014, 1.5143207368301361, -8.587596597534729, -0.9387144566983379, 2.5641381148921805, 10.628593146418485, 3.794317923770138, 6.2802756227726615, -0.05171930511667566, 0.8736426098894451, 0.6226851580000003};
        double[] NW = {9.631212195521316, -2.1235831279282698, 3.7468670477204773, -4.559878135521824, 3.2444286767576545, 6.2877828741148605, 6.520597627024687, 2.642307472836288, 1.2002893113069557, 0.32620641006622675, -3.368962812990781, -2.588868228199504, 4.356518441561512, -0.5955112302723241, 0.3875648501871751, -2.9311051175998064, 2.0095554763173666, -1.228769483871199, 5.900445902470515, 0.41527619439744434, 2.9752128071432145, 4.805920315662717, -4.797853823364673, 5.752192282393844, 2.9073605365834556, 2.4870719041084497, -1.7994046436584152, 7.79554996548367, 4.4174973514255536, 2.084039895979635, 0.6281302992116424, -3.1466915662704524, 3.646400672147826, 0.9609952887592054, -6.070082172976056, -0.9392599054917704, 0.904301836858967, 5.926867039519574, 3.238559698585232, -4.439332575192746, 1.352444182896236, -0.24594080100384297, -1.6395807550351367, 3.591208179788307, 4.15757174804611, -3.5334824535956173, 0.5302366137985215, 9.564674975899017, 4.175389023096817, -0.9827335882191762, 4.305890552392608, 3.059083687714633, 2.3224548745551488, 0.1934380213592375, 1.0235814, 1.1716370685853148, -2.931711339626567, -4.214035402157694, -1.0093422753964358, -4.843082160061708, -7.148710177896536, -1.910725804980465, -0.22905523068711164, 3.8200222938181367, -1.744095856344644, 1.354958988184811, 0.9933832752568843, 0.8820951391051288, -2.062035935350486, -7.633897329029599, 0.49911238393151325, -1.1684033502541722, 4.090099097765502, 4.566828839384462, 0.6901115935421007, -4.30695891725898, -5.637531096381548, 2.6920329212478507, -1.522395621132775, 6.351734133984433, 0.4895678835360122, -4.755548841958967, -2.826990702897114, 1.974618789378563, -6.999938959339396, 0.6289774718852977, 3.2732671487606266, -1.2781272997669557, 6.725303989648547, -7.163688015215646, 5.547683884070125, -3.0189942298996213, -0.2487963910538069, -0.46314538549764894, 5.3913279138183645, -4.018219623545416, 6.491084381355617, -1.5629014732514819, -6.557894883162792, -3.856421007612216};
        int sumEeven = 0, sumEodd = 0, sumWeven = 0, sumWodd = 0;
        while (i < 99) {
            sumEeven += NE[i];
            sumEodd += NE[i+1];
            i += 2;
        }
        i = 0;
        while (i < 99) {
            sumWeven += NW[i];
            sumWodd += NW[i+1];
            i += 2;
        }
        System.out.println("Front coordinates:");
        System.out.println("Latitude: " + sumEeven + "  Longitude: " + sumEodd);
        System.out.println();
        System.out.println("Back coordinates:");
        System.out.println("Latitude: " + sumWeven + "  Longitude: " + sumWodd);
    }
}

This code has no errors, and runs, but the console is empty. I have my run configurations set up correctly, so not sure what the issue is. I also made sure that my console was linked to this project and not another, and it is.
I'm running Eclipse Neon if that changes anything.
Some info about the project, although seemingly irrelevant:
n1 calculates the sum of that array of ints and then take the average of the sum
NE and NW calculate the sum of the even parts of each array and the odd parts of each array, and adds each up individually, and they end up being latitudinal and longitudinal coordinates.

A: I think your program will never leave this loop what are you trying to do here:
while (i < n1.length)
            sum += n1[i];

0 < n1.lenth  it's always true

try this and see
 while (i < n1.length){
            sum += n1[i];
            i++;
 }


text:
Q: Tuples in where condition Given that in F#

Tuples have an automatically defined equality operation

and therefore
let myQueryable = [| (1, 1); (2,2)|].AsQueryable()
let check =
    query {
        for x in myQueryable do
        } |> Seq.where(fun x -> x = (2,2))

is {(2,2)}, then why
let check =
        query {
            for x in myQueryable do
            where(x = (2, 2))
            }

is Empty?

A: It seems a compatibility issue between C# System.Tuple and F# reference tuples.
It is interesting that the compatibility issue seems to be solved between C# 7 and F# 4.1 with the new ValueTuple equivalent to F# struct tuples.
let myQueryableNew = [| ValueTuple.Create(1, 1); ValueTuple.Create(2,2) |].AsQueryable()
let resultFSharp1 =
    query {
            for x in myQueryableNew do
          } |> Seq.where(fun x -> x = ValueTuple.Create(2,2))

let resultFSharp2 =
        query {
            for x in myQueryableNew do
            where (x.Equals(ValueTuple.Create(2, 2)))
            }

Btw, notice also that the new type has a more coherent default (in case of this related issue)
let testDefault =
        query {
            for x in myQueriable1 do
            where (x.Equals(ValueTuple.Create(1, 2)))
            select x
            headOrDefault
            }

A: You probably have System.Linq open.
The following returns (2,2) for me in both cases:
//open System
//open System.Linq

let myQueryable = [| (1, 1); (2,2) |] //.AsQueryable()
let check =
    query {
            for x in myQueryable do
            select x
          } |> Seq.where(fun x -> x = (2,2))

check //val it : seq<int * int> = seq [(2, 2)]
let check' =
        query {
            for x in myQueryable do
            where (x = (2, 2))
            select x
            }

check' //val it : seq<int * int> = seq [(2, 2)]

So within an IQueryable this structural equality doesn't hold. I don't know if it's because of the IQueryable type, i.e. it becomes reference equality, or where gets redefined, or a possible bug.


text:
Q: BC3016: Variable 'myConnection' hides a variable in an enclosing block I'm am not quite sure why I am getting this error.
Dim numUsers as Integer
Using myConnection as New System.Data.SqlClient.SqlConnection("Data Source=(local);InitialCatalog=dbtest;Integrated Security=True")
   Dim queryString As String = "SELECT COUNT(*) AS Num_Of_User FROM tblusers WHERE username=@username AND password=@password"
   Using myCommand as New System.Data.SqlClient.SqlCommand(queryString, myConnection)
      myConnection.Open
      myCommand.Parameters.AddWithValue("@username", requestName)
      myCommand.Parameters.AddWithValue("@password", requestPass)
      numUsers = myCommand.ExecuteScalar()
   End Using
End Using

This error occurs on the first using statment. Can anyone help resolve this?

A: the variable myConnection is declared at a higher level of scope above the Using statement.  The Using statement is trying to create myConnection with the scope of the Using block but that would conflict with myConnection which has scope above that.


text:
Q: How to convert Vlookup to Index/match? Puzzle 1 | Attempt 1 | 0
         |           |7.1

Suppose I have 3 columns like the above, the blank spaces have nothing in the cell. I want to get the value of 7.1
I've tried
VLOOKUP("Puzzle 1",A:D,1)

To get the value "puzzle 1" and then trying to enclose that in an OFFSET(VLOOKUPVLAUE, 1,2,11) which does not work.

A: =INDEX(C:C,MATCH("Puzzle 1",A:A,0)+1)

would work for that.


text:
Q: Getting runtime error when doing fast enumeration over an NSArray of entities from Core Data in iOS I have an NSArray of Objects of type NSManagedObject that are returned from a fetch result I perform in Core Data.  The NSArray contains objects, as I am able to verify this after the query by printing the contents of the NSArray to the console.  My problem however is that I am unable to do fast enumeration over this array using objects of the type of entity that I have retrieved from the query.  The exact error I am getting at runtime is the following:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[My_Entity_Name countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xa9f0090'

My for loop that I am using doesn't even get to run because it breaks at the for loop condition:
for (MyEntityType *entityType in self.entityArray) {
...
}

The actual fetch command I use to populate the array self.entityArray is:
self.entityArray = [[Singleton sharedInstance] retrieveEntities:self.mainEntity.relationshipEntity.relationshipEntityId];

in turn, this is how my retrieveEntity method looks like:
- (NSArray *)retrieveEntities:(NSNumber *)relationshipEntityAttributeId {

    NSManagedObjectContext *context = [[DataEngine sharedInstance] managedObjectContext];
    NSError *error;

    // Create fetch request
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:ENTITY_NAME inManagedObjectContext:context];
    [fetchRequest setEntity:entity];

    // Create predicate
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"relationshipEntity.relationshipAttributeId == %@", relationshipEntityAttributeId];
    [fetchRequest setPredicate:pred];

    NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
    if ([items count]>0) {
        return items[0];
    } else {
        return nil;
    }
}

Why am I getting the above error?

A: It says what the error is in the error message.
You have a class My_Entity_Name. An instance of My_Entity_Name is assigned to the property self.entityArray. When you do for (MyEntityType *entityType in self.entityArray), it passes the -countByEnumeratingWithState:objects:count: message to the instance, and you get the unrecognized selector error.
I would look for places where the the value is assigned (either self.entityArray = … or [self setEntityArray:…]) to figure out how self.entityArray is getting the bad value. Perhaps you should post how you are doing the fetch, or if there are other ways that self.entityArray can get assigned a value.

UPDATE
I'm not sure what -[Singleton retrieveEntity:] does. It's not a class that's a part of the standard framework, and I don't know of any 3rd party library which uses such generic naming.
What I can tell you is that based on the method name -retrieveEntity:, it looks like it returns a single object not an array of objects. Usually methods that return arrays are pluralised, so I would have expected the name to be more like -retrieveEntities:.
You got an exception because is because self.entityArray doesn't contain an NSArray. The method name doesn't look like it would return an array.
Are you absolutely sure that [[Singleton sharedInstance] retrieveEntity:…] should return an NSArray? Perhaps you should post the code for -retrieveEntity:.

UPDATE
You are not returning an array.
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
if ([items count]>0) {
    return items[0];
} else {
    return nil;
}

If the items array has any elements, then the first element is returned. This is what items[0] does.
If you want to return the array change it to:
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
if ([items count]>0) {
    return items;
} else {
    return nil;
}

Notice I've replaced return items[0]; (return the first element of the array) with return items; (return the whole array).

A: There is a typo in the code, you populate self.entityAray, en draw from self.entityArray. Either this is a small typo in your example here, or it explains your error. When looking for self.entityArray it cannot find it because of the spelling error en throws the NSInalidArgumentException


text:
Q: How to change footer of UITableViewSection in a STATIC UITableView? You know how in the Settings app in iOS, you can select an setting from a UITableView of settings, and the footer of the UITableViewSection in which the setting cells are in will change. Like when you access your app's "Allow Location Access" settings, when you switch between "Never", "While Using App", or "Always", the text below the settings changes. In my app, I would like to achieve a similar function. I have tried reloadSection:, and I have implemented tableView:titleForFooterInSection:, but when I call reloadSection: it hides my UITableViewSection completely. So how do you access the footer of a UITableViewSection of a static UITableView and change it without hiding the whole thing? Thanks.

A: Override the table controller's tableView(titleForFooterInSection:) and add there the logic to choose a string according to the state of the data. When the user taps a cell that should change the footer, call UITableView.reloadSections(withRowAnimation:) to smoothly change the footer.


text:
Q: How to save scrolling position of recyclerview list by updating RecyclerViewAdapter per second (notifyDataSetChanged in onBindViewHolder is not working to update whole list per second . So I have updated list by creating new adapter per second time interval .)
To update counter and other chat data I have executed below lines periodically per second. It is getting scrolled up again and again.
So how to save scrollposition of the list even if it is updated periodically.
mAdapter = new ChatInfoRecyclerViewAdapter(getDataSet1());
                //mAdapter.notifyDataSetChanged();
                mRecyclerView.setAdapter(mAdapter);


text:
Q: Directory/file names confusion I wasn't sure how to word this but the easiest way to describe what I mean is just by giving an example.
Take this site -> http://lolprofile.net/summoner/lan/rimortix . When you search for a summoner the user in this case rimortix changes but the page renders the same just with a different users info. They don't use index.php?user=rimortix which would make sense to me on how it would work. How do they dynamically query for user info in this url layout?
The site I used was just an example but I have seen this same layout many times.

A: I came across this and it was exactly what I was going for.
Dynamic url in php without filename


text:
Q: Can't make toast in onViewCreated() This is inside a fragment and I am learning fragment lifecycle. This is the code and my Toast does not work. Can anyone help me out?
 @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        *Toast.makeText(requireActivity(), "View Created", Toast.LENGTH_SHORT).show();*

        Button btn = view.findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent(requireActivity(),MainActivity2.class);
//                startActivity(intent);
                frag = new Frag();
                getFragmentManager().beginTransaction().replace(R.id.frame_container,frag).addToBackStack(null).commit();
            }
        });
    }

A: Methods which would give you the context like getActivity(), getContext() would only work after onActivityCreated is called. As you are calling this in onViewCreated(), which I guess is called before onActivityCreated this would these API's would return null.
You can either try calling your toast from onActivityCreated, or will have to try out some way of passing context from your application class.

A: Use this instead of getActivity() or requireActivity()
Toast.makeText(getActivity().getApplicationContext(), "TEST TEST", Toast.LENGTH_LONG).show();

Also, check in your onCreateView if you inflated the layout like this:
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_blank, container, false);
}

If you don't provide a layout with R.layout.fragment_layout that could be the reason why it isn't working. But even without getApplicationContext() and only using getActivity() it should work. So maybe your problem is in the onCreateView method.


text:
Q: Html Helper "Select2": Submit normal form i'm about to submit normal html (MVC-Razor) form. though I'm new to MVC and i don't wanna use unnecessary Ajax because it take time for me to learn, and I'm in hurry and also with my complex model which contain other models i'm wonder how should i take back data...
in this form, i'm using Select2, which is feeded from a normal select tag...
what i want is to submit my form on any change to this control, and send its value back to server.
the issue is in some of my test, it has name but no value, and in some it even doesn't appear to have a container name.
here is my page code:
@model SinglePage.Models.SinglePageIndexViewModel

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

خانه

@using(Html.BeginForm()){
    @Html.ValidationSummary(true)

    @Html.HiddenFor(c=>Model.Customer.Code)

    <fieldset>
        <select id="selectCustomer" name="selectCustomer">
            <option></option>
            @foreach (var customer in Model.CustomerList)
            {
                <option value="@customer.Code">@Html.DisplayFor(c => customer.FirstName) @Html.DisplayFor(c=>customer.LastName)</option>
            }
        </select>

    </fieldset>
}

and here is my post request which does not contain "selectCustomer" and value for it.

-Extra Help (help is recommended but not required)
Also if you have any suggestion for me to read my data, or name my item, that i can read them back through model, i'll be happy to take advice, for now i'm going to use "Request.Form[]".
but my model structure is like this:
namespace SinglePage.Models
{
    public class SinglePageIndexViewModel
    {
        public List<Models.Customer> CustomerList { set; get; }
        public List<Models.Item> ItemList { set; get; }
        public Models.Customer Customer { set; get; }
        public Models.Factor Factor { set; get; }
        public List<Models.FactorItem> FactorItemList { set; get; }
    }
}

namespace SinglePage.Models
{
    public class SinglePageIndexViewModel
    {
        public List<Models.Customer> CustomerList { set; get; }
        public List<Models.Item> ItemList { set; get; }
        public Models.Customer Customer { set; get; }
        public Models.Factor Factor { set; get; }
        public List<Models.FactorItem> FactorItemList { set; get; }
    }
}

namespace SinglePage.Models
{
    public class FactorItem
    {
        public int Code { set; get; }
        public int FactorCode { set; get; }
        public string Name { set; get; }
        public int Count { set; get; }
        public decimal ItemPrice { set; get; }

        public decimal TotalPrice
        {
            get
            {
                return ItemPrice*Count;
            }
        }
    }
}

namespace SinglePage.Models
{
    public class Factor
    {
        public int Code { set; get; }
        public int CustomerCode { set; get; }
        public DateTime Date { set; get; }
        public decimal PaidPrice { set; get; }
    }
}

namespace SinglePage.Models
{
    public class Customer
    {
        public int Code { set; get; }
        public string FirstName { set; get; }
        public string LastName { set; get; }
        public string IdentityNo { set; get; }
        public string Telephone { set; get; }
        public string Address { set; get; }
    }
}

And i pass data using first model which contains all model.
Thank you all,
Hassan F.

A: you are submitting the form before selecting the value. submit it after selecting value. try submitting the form on change


text:
Q: WPF: Nested collection binding My application shows a question and possible answers on that question. Now I want to give the correct answer (specified in the "CorrectAnswer" property) a green color. Can someone help me? Thanks.
public class Exercise
{
    public string QuestionText { get; set; }
    public int CorrectAnswer { get; set; }
    public Answer[] Answers { get; set; }
    ...
}

public class Answer
{
    public string AnswerText { get; set; }
    ...
}

XAML:
    <StackPanel Orientation="Vertical">

        <ItemsControl ItemsSource="{Binding Path=Answers}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>

                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>

A: If you have some idea on ValueConverter in WPF, better make use of that. That will give you a lot of flexibility and easy to implement. Please let me know, if you still have some doubt.


text:
Q: How to write a test to confirm that a perl script waits (or doesn't wait) for interactive user input (based on supplied options) I have a perl script for which I would like to write a few tests.  If the perl script gets supplied a specific option, the user is allowed to paste or type out multi-line input and end their input using control-d.
These are the tests I want to write:

*

*The script (when an interactive flag is supplied) waits for (multiple lines of) input on STDIN until the user hits control-d

*[this test is already implemented - but provided for completeness] The script (when a flag is supplied that indicates a redirect/pipe) consumes all input on STDIN and does not wait for control-d

*The script (when no input flag is provided [interactive or redirect]) does not wait for interactive user input

Test 1 toy example
I wrote a test for test 1 that confirms input was received (it works by the parent test script printing to the child's input handle and the child modifies and prints that input back out), but that test doesn't wait for an end of input signal (e.g. control-d) (which I don't know how to send anyway).  So in other words, I can confirm it receives input, but I don't know how to confirm that it waits for the user to intentionally end the input entry.  I.e. How do I know that the input consumption won't stop until the user types control-d?
Here's what I have so far for test 1.  I wrote a 3rd little IO::Pipe::Consumer module to be able to send input to the child process that I'm testing and I wrote a toy example of the script that allows input on STDIN from a tty.
Here is a toy version of the script I'm testing:
>perl -e 'while(<STDIN>){print("*$_")}'
test
*test
^d
>

And here is the toy test code (that I want to improve) for the above script:
>perl -e '
   use IO::Pipe::Consumer;
   $obj = new IO::Pipe::Consumer;
   $si = $obj->getSubroutineConsumer(
      sub { while(<STDIN>) print("*$_") } }
   );
   print $si "test\n"
'
*test
>

I thought the parent would have to print an EOF (e.g. like what you get from "control-d") to end the input in the test, but the test ends immediately even though I'm not sending any such end-of-input character.  I can see that it's getting, modifying, and printing the input.  Is that sufficient to confirm that the script will wait for user input (and that the user will be able to intentionally end the input) or is there something else I should do to confirm it waits for all user input until the user intends to end it?
Test 2 - done
Test 3 toy - don't know how to write it...
Even if modified input spit back out is sufficient proof of "waiting for input" for test 1, I also wish to test that a script doesn't consume input on STDIN when no input option (interactive or redirect) is provided - but since it doesn't seem to wait even when I do send it input without an end-of-input signal, how would I test that the script wouldn't hang waiting for input?  Note, the script has other options for consuming redirected or piped input, so my intent is specifically to know if it's waiting on input from the tty.  All of the STDIN consumption options (whether from the tty or via redirect/pipe) are optional, which is why I want to write these tests.
My manual testing shows everything works as intended.  I would just like some tests to assure that behavior for the future.
IO::Pipe::Consumer
I feel like the thing I'm missing is not relevant to IO::Pipe::Consumer, so WRT that, I'll just describe it instead of paste in 30 or so lines of code... All it does is it sets a pipe to the child's STDIN and gives that handle back to the parent for it to print to.  I haven't put it on cpan.  I'm just experimenting to see if I can use it to write these tests.
IO::Pipe::Consumer is basically the opposite of IO::Pipe::Producer (a module I published on cpan looong ago, say 2001-ish, when I was new to perl, or programming for that matter).  The main difference, aside from swapping STDIN for STDOUT and Reader with Writer (and vice versa), is that the open is open(STDIN,"<",\${$stdin_pipe}).

A:
I thought the parent would have to print an "end-of-input" (e.g. "control-d") character to end the input in the test,

Ctrl-D doesn't produce an "end of input character"; it causes the terminal to return EOF.
I don't know what IO::Pipe::Consumer is —it's not on CPAN— but I presume it creates a pipe. Exiting the program causes the writer end of the pipe to be closed and thus cause the reader end to return EOF.

is there something else I should do to confirm it waits for all user input until the user intends to end it?

<> reads until one of the following things happen:

*

*A line feed is encountered (returning what was read including the line feed)

*EOF is encountered (returning what was read up to an including the line feed)

*An error is encountered (returning false).

You can confirm it waits by putting sleep statements between what you send. Be aware that buffering may interfere.


text:
Q: PHP include - failed to open stream: No such file I wrote a website in HTML but then I wanted the header and navbar portion in one file so I just had to change it once.  I changed all the pages to .php and added the php includes. However now I get an error on pages that I've put in folders so I could create cruftless links.
Header file: /test/assets/header.php
Works: /test/index.php contains <?php include 'assets/header.php'; ?>
Throws Error: /test/company/index.php contains <?php include '/test/assets/header.php'; ?>
Error:
Warning: include(/test/assets/header.php) [function.include]: failed to open stream: No such file or directory

Warning: include() [function.include]: Failed opening '/test/assets/header.php' for inclusion (include_path='.:/usr/local/lib/php:/usr/local/php5/lib/pear')

I am having an issue linking to the header file that is in a folder in the root folder. I believe it is a simple issue of just not knowing how to input the URL.  If I attempt to include the full path to the header.php I get a URL file-access is disabled error

A: I was also facing the same warnings:
Warning: include(/test/assets/header.php) [function.include]: failed to open stream: No such file or directory
Warning: include() [function.include]: Failed opening '/test/assets/header.php' for inclusion (include_path='.:/usr/local/lib/php:/usr/local/php5/lib/pear')

I solved them with the following solution:
You have to define your path then use include function as below:
define('DOC_ROOT_PATH', $_SERVER['DOCUMENT_ROOT'].'/');
require DOC_ROOT_PATH . "../includes/pagedresults.php";

After that, you can use any directory structure.

A: If you start a path with a / then it's an absolute path. Absolute mains to the actual filesystem root directory, not the virtual document root. This is why it fails.
Commonly this is what was meant:
include "$_SERVER[DOCUMENT_ROOT]/test/assets/header.php";
// Note: array key quotes only absent in double quotes context

A: It's not a URL; it's a filepath (although you can use full URLs when the server configuration allows it).


text:
Q: Parameterized tests vs Test method for each case NUnit I'm watching a course for NUnit and I came to this exercise to write a test method for below function
public static string GetOutput(int number)
    {
        if ((number % 3 == 0) && (number % 5 == 0))
            return "FizzBuzz";

        if (number % 3 == 0)
            return "Fizz";

        if (number % 5 == 0)
            return "Buzz";

        return number.ToString();
    }

What I did is that I have created a Parameterized test to cover all the cases like below
 [Test]
    [TestCase(15 , "FizzBuzz")]
    [TestCase(3, "Fizz")]
    [TestCase(5, "Buzz")]
    public void GetOutput_WhenCalled_ReturnString(int number , string word)
    {
        var result = FizzBuzz.GetOutput(number);
        Assert.That(result, Is.EqualTo(word));
    }

But the mentor has wrote each case in a seperate method like for example
public void GetOutput_NumberDivisiableNy3And5_ReturnFizzBuzz()
{
    var result = FizzBuzz.GetOutput(15);
    Assert.That(result, Is.EqualTo("FizzBuzz"));
}

public void GetOutput_NumberDivisiableBy3_ReturnFizz()
{
    var result = FizzBuzz.GetOutput(3);
    Assert.That(result, Is.EqualTo("FizzBuzz"));
}

My question is why he wrote it like that? does separating it like this has some advantage?
or is it simply a personal preference. I'm very new to unit test and Nunit

A: At bottom, it's a personal preference. However, when the method you are testing takes an argument, it seems very natural to use a parameterized test. OTOH, do not use a parameterized test to write a test for two or more entirely different things... in fact, don't write a test for more than one purpose at a time at all!
My guess is that your instructor is trying to start with a fundamental approach and will only introduce parameterized tests in a later lesson. But of course that's only a guess.

A: It's a personal preference.
An important guideline when testing is that the names you choose for your tests should describe the desired behavior of the method being tested for a given input. Think of the test names as being akin to executable documentation: "under circumstance X, the method should exhibit behavior Y."
Using parameterized tests means that the test name is by its very nature less descriptive, which makes it more difficult to identify at a glance exactly what's failing -- you have to look at the test parameters to determine the failing case, as the test name isn't providing you with that information.
This is apparent even in your implementation: Your test name says it "returns string" "when called". Which is technically correct, but is not descriptive. What string should it return when called with a given value?
The individual test cases, on the other hand, make the desired behavior very clear: A number divisible by 3 and 5 should return "FizzBuzz", and so on.
Also, think of it like this: What happens if you're asked to go back to this method and expand it to print Fuzz when a number is divisible by 7? And Biz when divisible by 9? And so on. Your single test method can do all of that heavy lifting, but the more requirements you have, the more burden is being put on that single test case and the harder it becomes to clearly identify which scenarios are failing and why.
Your approach isn't wrong, but if I were writing these tests, I would write one test case for each scenario: Fizz, Buzz, FizzBuzz, and not divisible by anything.
Each test case can still be parameterized, so you can test a larger number of values that satisfy each test case.


text:
Q: Sort by Double Value and not String Value I'm currently pulling info from an sql DB where the 'cachedDist' column is set as a double.  However when I pull it into my app and create my array I turn it into an String and the sort will obviously be off, 18.15 will come before 2.15.  How do I fix that in my code so it will sort distance as a Double and not a String?
In Bar object.
NSString *cachedDist
@property(nonatomic,copy) NSString *cachedDist;

@synthesize cachedDist;

My while loop in the View Controller.
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
            Bar * bar = [[Bar alloc] init];
            bar.barName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
            bar.barAddress = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
            bar.barCity = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)];
            bar.barState = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)];
            bar.barZip = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 5)];
            bar.barLat = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 8)];
            bar.barLong = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 9)];

            if (currentLoc == nil) {
                NSLog(@"current location is nil %@", currentLoc);
            }else{

            CLLocation *barLocation = [[CLLocation alloc] initWithLatitude:[bar.barLat doubleValue] longitude:[bar.barLong doubleValue]];
            bar.cachedDist = [NSNumber numberWithDouble:[currentLoc distanceFromLocation: barLocation]/1000];

            [thebars addObject:bar];

            }

My sorting
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"cachedDist"  ascending:YES];
sortedArray = [thebars sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];

return sortedArray;

A: NSString has a method doubleValue to make this quite simple:
double cachedDistance = [cachedDistanceString doubleValue];

which you can use in a custom comparator for your sorting, or else make the property an NSNumber or double to make sorting that much easier. (I'm not sure how you are sorting...)
edit:
I re-evaluated your code, and now it looks like we are going from a double to a string to a double... we can cut out the middle-man, so to speak.
In your @prototype section, change the @property:
// @property(nonatomic,copy) NSString *cachedDist; // old way
@property(nonatomic) double cachedDist;

then assign it like this:
bar.cachedDistance = [currentLoc distanceFromLocation: barLocation]/1000;

and remove the lines which create a string from the distance (which is actually just a double).
Alternatively, if you want to be more object oriented, you can (should?) use NSNumber objects:
@property(nonatomic,copy) NSNumber *cachedDist;
...
bar.cachedDistance = [NSNumber numberWithDouble:[currentLoc distanceFromLocation: barLocation]/1000];


text:
Q: my linked list not filling C I'm trying to fill a linkedlist (dic).
dataPtr will be a word coming from kitap.txt file and ID will be 0,1,2 sequentally.
I couldn't fix this, can you see anything wrong?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define WORD_LENGHT 30

typedef struct numnode//MY STRUCTURE
{
    char dataPtr[1000];
    int ID;
    struct numnode* next;

} NUMNODE;

typedef struct num
{
   NUMNODE* head;
} NUM;

//////
//////
//////

int main()
{
    char word[1000];
    int total=0;
    FILE *test= fopen("kitap.txt", "r");

    NUM* dic;
    dic=(NUM*)malloc(sizeof(NUM));
    NUMNODE* temp;
    temp=dic->head;
    temp=malloc(sizeof(NUMNODE));

    while (!feof(test))//getting all words and trying to fill linkedlist
    {
        fscanf (test, "%s",word);
        strcpy(temp->dataPtr,word);//filling dataPtr part
        temp->ID=total;//filling ID
        printf("%d-%s\n",temp->ID,temp->dataP1tr);//i can print here but its not filling
        total++;
        temp=temp->next;
        temp=malloc(sizeof(NUMNODE));
    }

    //printf("-----------");
    FILE*file= fopen("kitap.txt", "r");
    //FILE*dictionary=fopen("dictionary.txt","w");

    temp=dic->head;//point to head
    /*while(!feof(file))//trying to print linked list
    {

        printf("%d-%s\n",temp->ID,temp->dataPtr); //it only prints head node
        temp=temp->next;
    }
     return;
}

A: try to exchange these two instructions :
temp=temp->next;
temp=malloc(sizeof(NUMNODE));

with these:
temp->next=malloc(sizeof(NUMNODE));
temp=temp->next;


text:
Q: Difference between logistic regression and logistic neuron What is the difference between a logistic neuron in a neural net and a logit regression?

*

*They both follow the Sigmoid function plotted below

Here is the R Code for reasons of reproducibility
f <- function(x) {
   1 / (1 + exp(-x))
}

curve(f, xlim = c(-6,6), ylim= c(-0.5,1.5), main = "Sigmoid function", col.main = "red")

*They are both binary classifiers

*Both classifiers are symmetric and give the same output for the same input.
But what is the difference between the two?

A: A neural network can be considered as a networked set of logistic regression units.
While a single logistic regression can perform as a classifier on it's own it's not suited for problems where input dimensions are very high and your data is not linearly separable.
By using multiple such units, a neural network attempts to approximate any given function. The more important aspect in using a neural network however is in knowing how to train each of these units.
Here's another question similar to yours: Difference between logistic regression and neural networks


text:
Q: Mac app installation: How to get the destination disk when installing an app? I'm now confused by the Mac app installation steps after packaging my app to .pkg. When the mac contains more than one disk, and when installing the app, after I change the destination disk to another one, like '/Volumes/Disk2', I need to know the disk name after the installation. But I can not find a way to get it.
I am using Iceberg to package the app. Can anyone help?

A: After some digging, I got the solution to this question: define my own installer plugin, use cocoa api

tVol = [[[self section] state] targetVolumePath];

to get the Volume path. reference from mactech


text:
Q: Locale code for iPhone's localizable strings What's the locale code for traditional Chinese and French Canadian to be used for iPhone localizable strings file.  I know the code for simplified Chinese and French, which is zh and fr, but not its counterpart.

A: Set it on your device and execute
NSLog(@"localeIdentifier: %@", [[NSLocale currentLocale] localeIdentifier]);

A: After some experiments, I found out that the locale code used to name the localization strings file for Chinese are:
zh_hant (traditional)
zh_hans (simplified)

A: You can change your language in the iPhone Simulator (though 'Settings').  The following code will show the language code:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
NSString *currentLanguage = [languages objectAtIndex:0];
NSLog(@"Current language: %@", currentLanguage);


text:
Q: Get all keys from a Map() according to their property value in Javascript I am currently trying to get all keys from a Map() structure in JS/TS which met a specific criteria, so I am able to change a value of another property of the same elements:

const map1 = new Map();

map1.set('a', {price:1, stock:true});
map1.set('b', {price:3, stock:false});
map1.set('c', {price:5, stock:true});

How can I get to know, for example, all keys where price > 1? The output could be an array of anything else that can be used to handle the map and change its properties according to the respective constraint. In case I would like to change all 'stock' properties to false when price > 1.
Thanks!

A: [...map1].filter should do

const map1 = new Map();

map1.set('a', {price:1, stock:true});
map1.set('b', {price:3, stock:false});
map1.set('c', {price:5, stock:true});

const map2 = new Map([ ...map1 ].filter(([key, value]) => value.price > 3))

console.log([...map2])

A: You could iterate the map directly and apply update if necessary.

const map1 = new Map([['a', { price: 1, stock: true }], ['b', { price: 3, stock: false }], ['c', { price: 5, stock: true }]]);

map1.forEach(value => {
    if (value.price > 1) value.stock = false;
});

console.log([...map1]);


text:
Q: Content pulled via Headless Selenium Chromedriver does not reflect dynamically updating content on webpage (as it does in "headful" mode) TL;DR: content from a webpage that is known to dynamically update over time only updates in the headful Chromedriver, but does not dynamically update if the Chromedriver is headless. How can I preserve the headful updates in the headless driver condition?
I am using Python Selenium (version=3.141.0) Chromedriver (chromedriver version = 104.0.5112.79; browser version = 105.0.5195.125) to pull information from websites that dynamically update their content over time in the absence of explicit browser refreshes, e.g:
https://www.paddypower.com/football?tab=in-play
If I run a "headful" Chromedriver (e.g. without passing the headless=True argument when instantiating the driver)  and pull the data, the pulled content reflects the updated information over time without having to explicitly refresh the page, i.e. every time I pull I get the most up-to-date information without having to run driver.refresh() (note my pulls simply send JavaScript commands via the driver to the webpage to pull all text from specific elements)
However, if I run my exact same data pulls but now with a headless Chromedriver, I can only ever pull the information that was displayed on the page at the time of the driver's deployment, and repeated pulls after this do not reflect changes in that page's information over time unless I explicitly refresh the page (now using driver.refresh()).
Note I want to avoid explicit page refreshes as they can take significant time, and I want to avoid using headful Chromedrivers as I want to open several pages simultaneously.
I routinely pass the following arguments to Chromedriver, none make a difference:
    options = Options()
    options.headless=headless
    options.add_argument('window-size=2000x1500')

    options.add_argument('--no-proxy-server')
    options.add_argument("--proxy-server='direct://'");
    options.add_argument("--proxy-bypass-list=*");
    options.add_argument('--disable-gpu');
    # bypass OS security
    options.add_argument('--no-sandbox')
    # don't tell chrome that it is automated
    options.add_experimental_option(
        "excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    # disable images
    prefs = {"profile.managed_default_content_settings.images": 2}
    options.add_experimental_option("prefs", prefs)

Thanks for any help you can give!

A: The Chromium developers recently added a 2nd headless mode that functions the same way as normal Chrome.
--headless=chrome
(the old way was: --headless or options.headless = True)
The New Headless Mode Usage:
options.add_argument("--headless=chrome")

You should be able to use that mode and get the same results as headed mode.
There's more info on that here: https://bugs.chromium.org/p/chromium/issues/detail?id=706008#c36

A: To provide extra help to the answer provied by Michael Mintz is very good.
Create a headless browser like so:
options = webdriver.ChromeOptions()
options.add_argument("--headless=chrome")

It's good to note that when this crashes, the browser will still be open. In this case, trying to open a new browser might result in an error if you are using chrome user profiles:
  (The process started from chrome location C:\Program Files\Google\Chrome\Application\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

It'll just be invisible and might be difficult to close. It can be closed by the following:
import os

os.system("taskkill /f /im geckodriver.exe /T")
os.system("taskkill /f /im chromedriver.exe /T")
os.system("taskkill /f /im IEDriverServer.exe /T")


text:
Q: It is always neccesary to use definition to show that a function is not differentiable at a given point? Suppose we are given $f(x)=x^{1/3}$. We know that Dom($f$) = $\mathbb{R}$ and $f'(x)=\frac{1}{3}x^{-2/3}$.
It is enough to conclude that $f$ is not differentiable at $x=0$ because $f'(x)=\frac{1}{3}x^{-2/3}$
is not defined at $0$ or it must be shown by definition that $f'(0)$ does not exist ?
More generally, if $f(x)$ is a function with domain $A$, and $g(x)$ is the derivate of $f(x)$ obtained by applying differentiation rules. If $g$ has domain $B \subset A$. It is enough to conclude that $f$ is not differentiable at any point $x\in A/B$ just because $g$ is not defined there or it must be shown by definition ?

A: In general, this must be shown by definition. For instance $f(x)=x^2\sin(1/x)$ has derivative $2x\sin(1/x)-\cos(1/x)$ for $x\neq 0$ but is still differentiable at $0$. There are a few general things that can be said, though; while derivatives can be discontinuous, as the previous example shows, they cannot have jump discontinuities. So if the formula giving the derivative on $B$ would lead to a jump discontinuity if extended to more of $A$, then you know the function is not differentiable at the missing points.


text:
Q: tool to make /var/report errors readable Just what the subject says. Is there anything to reformat the /var/report errors to be more readable? Strip the slashes, replace the new lines?
I've been dicking with the damn thing all morning and can't seem to fully get the

A: As of now, I don't think that there is any tool to beautify report errors.
If you want to see report errors in a better-rendered format (in the browser), then you need to:

*

*Go to /pub/errors folder

*Rename local.xml.sample to local.xml

*Refresh the website in the browser.

If you don't want to see the error in the browser and instead see the errors in the files under /var/report folder, then:
Note: I assume that you are aware of NetBeans editor. If not, the steps mentioned below may vary based on the editor you use to see the files.

*

*Open the error file in NetBeans editor.

*Press CTRL + H, and find all occurrences of "/" and replace it with "/".

*Press CTRL + H again, and find all occurrences of "\" and replace it with "****".

*Press CTRL + H again. This time, click on Regular Expression button also. Now, find all occurrences of "#" and replace it with "\n#".

You will get a properly rendered report file now.
Please let me know if you have any problem.


text:
Q: const struct { x } vs struct { const x} This is a rather simple question, but somehow difficult to find a simple answer for.
In C++, what is the difference between an (edit) const-modified struct variable, and a(edit:) non-const  struct variable, but with the struct having all-const members? :
typedef struct mystruct {
    const int x;
} t1;
const t1 s1;

vs
typedef struct {
    int x;
} t2;
const t2 s2;

? (If the answer is "the same as for classes", then please either explain it for classes or link to the explanation.)

A: There's no such thing as a const struct. You may have seen something like this:
const struct {
    int x;
} y;

This is a declaration of a variable y with struct type. The variable y is const, not the struct. You can think of it as similar to:
struct mystruct {
    int x;
};

const mystruct y;

without giving the struct type a name.

A: There's effectively very little difference between the two objects a and b below:
struct A
{
   int x, y;
};

struct B
{
   const int x, y;
};

const A a;   // (plus initialiser)
B b;         // (plus initialiser)

(You know, of course, that other instances of A may not be const-qualified and then you have an obvious difference.)
You can't access the members any differently in the one case than in the other. But:

*

*You will have to ensure that you initialise the members, in both cases (which I haven't done here);

*const-qualifiying the type (rather than the members) affects reference-binding:
void foo(A& a);
void foo(B& b);

int main()
{
   const A a;
   B b;

   foo(a);  // Error!
   foo(b);  // OK
}

The same is true, of course, if you use a pointer instead of a reference. The const context only spreads to calling code when it's applied to the type rather than encapsulated within the members.

A: Assuming
const struct mystruct1 {
    int x1;
    int x2;
} s1;

and
struct mystruct2  {
    const int x1;
    int x2;
} s2;

For s1 you should not assign values to any members.
For s2 only the member x1 should not be assigned a value. One is free to do so for x2.

To get closer to your example, one could do:
typedef const struct mystruct1 {
    int x1;
    int x2;
} S1;

typedef struct mystruct2 {
    const int x1;
    int x2;
} S2;

S1 s1;
S2 s2;

For s1 and s2 here the same rules apply as above.

Upate:
Referring your question literally (implying the corrections as by my examples), there is no practical difference between the two construct in terms constantness of the value they carry.


text:
Q: Unloading AppDomain Is there a way to unload parent AppDomain?
I am trying to load a different version of an assembly in my new AppDomain, but it keeps loading the version from the parent domain. When I am loading the assembly in the new AppDomain I am showing the correct path.
Or maybe there is another way I can do that?

Thanks in advance.

EDIT
AppDomain MailChimpDomain = AppDomain.CreateDomain("MailChimpDomain");
string path = AppDomain.CurrentDomain.BaseDirectory + "ServiceStack_V3\\ServiceStack.Text.dll";
MailChimpDomain.Load(AssemblyName.GetAssemblyName(path));

EDIT2
Code 2:
var MailDom = AppDomain.CreateDomain("MailChimpDomain");
            MailDom.AssemblyLoad += MailDom_AssemblyLoad;
            MailDom.AssemblyResolve += new ResolveEventHandler(MailDom_AssemblyResolve);
            MailDom.DoCallBack(() =>
            {

                string name = @"ServiceStack.Text.dll";
                var assembly = AppDomain.CurrentDomain.Load(name);
                string name2 = @"MailChimp.dll";
                var assembly2 = AppDomain.CurrentDomain.Load(name2);

                //mailChimp object with API key found in mailChimp profile
                MailChimp.MailChimpManager mc = new MailChimp.MailChimpManager("111111111111222f984b9b1288ddf6f0-us1");
                //After this line there are both versions of ServiceStack.Text Assembly
                MailChimp.Helper.EmailParameter em = new MailChimp.Helper.EmailParameter();
                em.Email = strEmailTo;

                //Creating email parameters
                string CampaignName = "Digest for " + strEmailTo + " " + DateTime.Now.ToShortDateString();
                MailChimp.Campaigns.CampaignCreateOptions opt = new MailChimp.Campaigns.CampaignCreateOptions();
                opt.ListId = "l338dh";
                opt.Subject = strSubject;
                opt.FromEmail = strEmailFrom;
                opt.FromName = strNameFrom;
                opt.Title = CampaignName;

                //creating email content
                MailChimp.Campaigns.CampaignCreateContent content = new MailChimp.Campaigns.CampaignCreateContent();
                content.HTML = strEmailContent;

                //Creating new email and sending it
                MailChimp.Campaigns.CampaignFilter par = null;
                MailChimp.Campaigns.CampaignSegmentOptions SegOpt = null;
                MailChimp.Campaigns.CampaignTypeOptions typeOpt = null;

                mc.CreateCampaign("regular", opt, content, SegOpt, typeOpt);
                MailChimp.Campaigns.CampaignListResult camp2 = mc.GetCampaigns(par, 0, 5, "create_time", "DESC");
                foreach (var item in camp2.Data)
                {
                    if (item.Title == CampaignName)
                    {
                        mc.SendCampaign(item.Id);
                        break;
                    }
                }

            });
static Assembly MailDom_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            byte[] rawAssembly = File.ReadAllBytes(Path.Combine(path, args.Name));
            return Assembly.Load(rawAssembly);
        }

A: What your code actually does is it loads assembly to your parent domain. If you want to load assembly into child domain you have to do it from inside child domain. This is kind of chicken-egg problem,  because the parent assembly (which loads child assembly into child domain) has to be loaded into your child domain as well in order to be executed.
Assuming simple example that you have console application and assembly called MyAssembly.dll it can be done like this:
static void Main(string[] args) {
  var domain = AppDomain.CreateDomain("MailChimpDomain");
  domain.AssemblyResolve +=new ResolveEventHandler(domain_AssemblyResolve);
  domain.DoCallBack(() => {
    string path = @"MyAssembly.dll";
    var assembly = AppDomain.CurrentDomain.Load(path);

    // to do something with the assembly
    var type = assembly.GetType("MailChimp.MailChimpManager");
    var ctor = type.GetConstructor(new[] { typeof(string) });
    var mc = ctor.Invoke(new object[] { "111111111111222f984b9b1288ddf6f0" });
  });
}

static Assembly domain_AssemblyResolve(object sender, ResolveEventArgs args) {
  byte[] rawAssembly = File.ReadAllBytes(Path.Combine(@"c:\MyAssemblyPath", args.Name));
  return Assembly.Load(rawAssembly);
}

In this case child domain has same root directory for resolving assemblies as parent domain (and thus it can execute the code which loads "MyAssembly.dll").
If the code working with reflection is longer than this, you may consider using bootstrapper instead.
I.E. you create new library called MyBootstrapper.dll, you'll reference directly version of ServiceStack.Text.dll and MailChimp.dll you like from MyBootstrapper.dll, and you'll create bootstrap class - lets call it Bootstrapper that will be static and will have single public static method called Run that will do dirty work.
Then inside DoCallBack() method you'll call this bootstrapper instead.
string path = @"MyBootstrapper.dll";
var assembly = AppDomain.CurrentDomain.Load(path);

// to do something with the assembly
var type = assembly.GetType("MyBootstrapper.Bootstrapper");
var method = type.GetMethod("Run", BindingFlags.Static);
method.Invoke(null, null);
// or if the Run method has one parameter of "string" type
var method = type.GetMethod("Run", BindingFlags.Static, Type.DefaultBinder, new[] { typeof(string) }, null);
method.Invoke(null, new object[] { "Parameter to run" });

A: No, you may not unload the default AppDomain or any assemblies loaded in the default AppDomain.
What you can do, however, is load both versions of the ServiceStack assembly in two child domains. You should be able to unload either of them. However, using types from these domains may prove more difficult than usual. You'll have to do it via remoting.
Given the overhead imposed by this, you should consider using only one version of that assembly (even if this means adapting part of your app, the one that runs in the default domain).


text:
Q: How to read a json file that is embedded as part of an MSI package and populate the values in a combo box in the MSI UI? I am developing an MSI installer using Wixsharp.Net and need to update the combo box in the custom managed UI with the data from (Serialized) JSON configuration file.
Request to throw some light on how to implement this using .NET and Wixsharp


text:
Q: AngularJS- Error: 10 $digest() iterations reached. Aborting! in a custom directive I'm writing a snipped to evaluate users answer. If his answer is right, then I'm appending a correct icon in the end. I've created a custom directive to evaluate the answer. But I keep encountering the infamous Error: 10 $digest() iterations reached. Aborting! error.
Here is a snapshot of my partial,

and this my directive,
app.directive('evaluateMe', function() {
    return {
        restrict : 'A',
        scope:{
            answer: '=isCorrect'
        },
        link : function(scope, element, attrs) {
            var prepend;
            console.log(scope.answer.isCorrect);
            if(scope.answer.isCorrect){
                prepend = '';
            }else{
                prepend = '';
            }
            element.append(prepend);
        }
    };
});

It's my understanding that, this error happens when you're incorrectly updating the model from the view or in the middle of a loop. But in this case, I'm just evaluating the model. And the wierdest part is the directive execution completes and appends my HTML string inside the DOM. the error happens after that(Please refer to the screenshot)

NOTE: I've referred to the other posts, but I'm not able to figure out a solution.
Please help me with this issue.

A: I'm not sure if this will help you (a fiddle/plunk would be useful) but:
1) You are adding unecessary complexity to the variable passed to the directive; try:

and in the code:
scope:{
    answer: '='
},

Or if you only want to pass the isCorrect flag:

and in the code:
scope:{
    isCorrect: '='
},

And then use scope.isCorrect directly.

Could you also give a try to a directive using transclusion, that does not need the DOM manipulation logic, preferring Angular templates instead:
app.directive('evaluateMe', function() {
    return {
        restrict : 'A',
        template:
            "
" +
                "

" +
                ""
            "
",
        transclude: true,
        scope:{
            isCorrect: '='
        }
    };
});

Used as:


text:
Q: Booking system remove all saved bookings during a period I have multiple bookings in pending status. But 1 of them is paid and the status is now confirmed.
Here is an example of what I have :
id |       start_date       |        end_date       |  status
   |                        |                       |
1  |   2019-06-10 08:00:00  |  2019-06-10 20:00:00  |  pending    <-- To delete
2  |   2019-06-10 10:00:00  |  2019-06-10 13:00:00  |  confirmed
3  |   2019-06-09 06:00:00  |  2019-06-11 11:00:00  |  pending    <-- To delete
4  |   2019-06-10 21:00:00  |  2019-06-10 22:00:00  |  pending    <-- Keep it
5  |   2019-06-10 11:00:00  |  2019-06-10 12:00:00  |  pending    <-- To delete

The id 2 is confirmed and I need to delete all other bookings in pending status who are in the same period of the confirmed status.
So I need to delete ids 1, 3 and 5
How can I do that with SQL query ?
I thought about but I'm not sure it will cover all possible cases:
DELETE FROM booking
WHERE status = 'pending'
AND start_date <= '2019-06-10 10:00:00'
AND end_date >= '2019-06-10 13:00:00'

A: I think you want overlapping intervals.  This would be:
DELETE b
    FROM booking b
    WHERE b.status = 'pending' AND
          b.end_date >= '2019-06-10 10:00:00' AND
          b.start_date <= '2019-06-10 13:00:00';

Two intervals overlap if the second ends on or after the first starts, and the second starts on or before the first ends.

A: DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,start_date DATETIME NOT NULL
,end_date DATETIME NOT NULL
,status VARCHAR(12) NOT NULL
);

INSERT INTO my_table VALUES
(1,'2019-06-10 08:00:00','2019-06-10 20:00:00','pending'),
(2,'2019-06-10 10:00:00','2019-06-10 13:00:00','confirmed'),
(3,'2019-06-09 06:00:00','2019-06-11 11:00:00','pending'),
(4,'2019-06-10 21:00:00','2019-06-10 22:00:00','pending'),
(5,'2019-06-10 11:00:00','2019-06-10 12:00:00','pending');

DELETE y
  FROM my_table x
  JOIN my_table y
    ON y.start_date <= x.end_date
   AND y.end_date > x.start_date
 WHERE x.status = 'confirmed'
   AND y.id <> x.id;

Query OK, 3 rows affected (0.00 sec)

SELECT * FROM my_table;
+----+---------------------+---------------------+-----------+
| id | start_date          | end_date            | status    |
+----+---------------------+---------------------+-----------+
|  2 | 2019-06-10 10:00:00 | 2019-06-10 13:00:00 | confirmed |
|  4 | 2019-06-10 21:00:00 | 2019-06-10 22:00:00 | pending   |
+----+---------------------+---------------------+-----------+
2 rows in set (0.00 sec)


text:
Q: Symfony 4 - Custom GuardAuthenticator doesn't set remember me cookie I'm building a custom GuardAuthenticator to login with a token on a specific route. According to the documentation if supportsRememberMe() returns true and remember_me is activated in the firewall, the remember me cookie should be set, but it's not (although it is set if I use a form login authentication on another route).
The route:
/**
 * @Route("/login/token/{id}/{token}/{force}", defaults={"force"=0}, name="login_token")
 */
public function loginToken()
{

}

The GuardAuthenticator:
<?php

namespace App\Security;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Http\Util\TargetPathTrait;

class TokenLoginAuthenticator extends AbstractGuardAuthenticator
{
    use TargetPathTrait;

    private $em;
    private $force;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function supports(Request $request)
    {
        return 'login_token' === $request->attributes->get('_route') && $request->isMethod('GET');
    }

    public function getCredentials(Request $request)
    {
        $credentials = [
            'id' => $request->attributes->get('id'),
            'token' => $request->attributes->get('token')
        ];

        $this->force = $request->attributes->get('force');

        return $credentials;
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $user = $this->em->getRepository(User::class)->find($credentials['id']);

        if (!$user) {
            // fail authentication with a custom error
            throw new CustomUserMessageAuthenticationException('No user found.');
        }

        return $user;
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        if ($user->getToken() === $credentials['token']) {
            return true;
        }
        throw new HttpException(403, "Forbidden");
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        throw new HttpException(403, "Forbidden");
    }

    public function start(Request $request, AuthenticationException $authException = null)
    {
    }

    public function supportsRememberMe()
    {
        return true;
    }
}

The security config:
security:
    encoders:
        App\Entity\User:
            id: 'App\Security\PasswordEncoder'

    providers:
        in_memory: { memory: ~ }
        orm:
            entity:
                class: App\Entity\User
                property: email

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            anonymous: true
            form_login:
                login_path: login
                check_path: login
                provider: orm
                csrf_token_generator: security.csrf.token_manager
                default_target_path: homepage

            logout:
                path:   /logout
                target: /

            remember_me:
                secret:   '%kernel.secret%'
                lifetime: 604800 # 1 week in seconds
                path: /
                # by default, the feature is enablered by checking a
                # checkbox in the login form (see below), uncomment the
                # following line to always enable it.
                # always_remember_me: true

            guard:
                provider: orm
                authenticators:
                    - App\Security\TokenLoginAuthenticator

A: In Symfony 5.2.6 dont forget to add new RememberMeBadge() to the authenticate function:
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge;

class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
{
    public function authenticate(Request $request): PassportInterface
    {
        $email = $request->request->get('email', '');

        $request->getSession()->set(Security::LAST_USERNAME, $email);

        return new Passport(
            new UserBadge($email),
            new PasswordCredentials($request->request->get('password', '')),
            [
                new CsrfTokenBadge('authenticate', $request->get('_csrf_token')),
                new RememberMeBadge(),
            ]
        );
    }
}

A: Remember me cookie will be set if all of the following are met:

*

*The supportsRememberMe() method returns true.

*The remember_me key in the firewall is configured.

*The (default) _remember_me parameter is sent in the request. This is usually done by having a _remember_me checkbox in a login form (but it can be sent as url param (?_remember_me=1), or we can configure the  firewall remember_me key to always_remember_me.

*The onAuthenticationSuccess() method returns a Response object.


text:
Q: javascript url value to multiple fields I am building a form and all is going well except for the final part. I am trying to have a value carried from the URL into multiple fields i can get it into the first field but not the others.
Here is code from the form hopefully enough to see.

<form name="MakeQuote" method="post" action="QuoteProcess.php">

          Weight
          QuoteID

          Sand
          <input name="Weight[]" type="number" id="Weight[]" size="8" maxlength="4" value="0.00">
          Kg
            <input type="hidden" name="ProductID[]" id="ProductID[]" value="2">
            <input name="QuoteID1[]" type="number"  size="8" maxlength="8"  id="QuoteID1[]" value="">

          Shingle
          <input name="Weight[]" type="number" id="Weight[]" size="8" maxlength="4" value="0.00">
          Kg
            <input type="hidden" name="ProductID[]" id="ProductID[]" value="3">
            <input name="QuoteID1[]" type="number"  size="8" maxlength="8"  id="QuoteID1[]" value="" >

          Topsoil
          <input name="Weight[]" type="number" id="Weight[]" size="8" maxlength="4" value="0.00">
          Kg
            <input type="hidden" name="ProductID[]" id="ProductID[]" value="4">
            <input name="QuoteID1[]" type="number"  size="8" maxlength="8"  id="QuoteID1[]">

          Mulch
          <input name="Weight[]" type="number" id="Weight[]" size="8" maxlength="4" value="0.00">
          Kg
            <input type="hidden" name="ProductID[]" id="ProductID[]" value="4">
            <input name="QuoteID1[]" type="number"  size="8" maxlength="8"  id="QuoteID1[]">

          </form>

any help will be greatly recieved.

A: That's because you have multiple elements with the same ID. IDs are supposed to be unique. getElementById only selects the first element with that ID.
You can select the elements by their name and iterate over them to set their value:
var inputs = document.getElementsByName('QuoteID1[]');

for (var i = 0, l = inputs.length; i < l; i++) {
    inputs[i].value = varValue;
}

FYI, you don't have to add [] to the IDs, they are only relevant in the names of the elements, and only if you are using PHP on the server side.


text:
Q: IIS URL Rewrite Rule with Params I am having a hard time getting a URL rewrite rule to work.
I want this url:
http://www.mysite.com/oldpage.aspx?oldid=123
To rewrite to:
http://www.mysite.com/sub/newpage.aspx?newid=123
Here is what I have, but it's not working:
<rule name="Old2New" stopProcessing="true">
    <match url="^oldpage.aspx?oldid=([0-9]+)" />
    <action type="Rewrite"
            url="/sub/newpage.aspx?newid={R:1}"
            appendQueryString="true"  />
</rule>

What am I missing?

A: Use the conditions to catch the query string part {C:1}, like this:
<rule name="My rule" stopProcessing="true">
    <match url="^oldpage\.aspx" ignoreCase="true" />
    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{QUERY_STRING}" pattern="oldid=([0-9]+)" />
    </conditions>
    <action type="Redirect" url="/sub/newpage.aspx?newid={C:1}" appendQueryString="false" />
</rule>

Tested and working.

A: The regex index starts at 0 not 1. so your rule should be:
<rule name="Old2New" stopProcessing="true">
    <match url="^oldpage.aspx?oldid=([0-9]+)" />
    <action type="Rewrite"
            url="/sub/newpage.aspx?newid={R:0}"
            appendQueryString="true"  />
</rule>

You can easily test your rule in IIS7 interface.


text:
Q: How to use mvc page as angular 5 templateUrl I am migrating my old project that used systemjs, to start use webpack, but now i having problems with the loading of templateUrl.
My old project use mvc views on templateUrl property of angular componentes, but with my new project this not work.
When i use the templateUrl calling a html file, all work good.
@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

But, when i call a mvc route that provide a page, not work. (The route are work if you write manually in the browser)
@Component({
    selector: 'app',
    templateUrl: '/Teste/Index',
    styleUrls: ['./app.component.css']
})

My mvc controller class:
public class TesteController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

So, i need load my mvc views as templateUrl, can anyone help me ?

A: This can be done, it requires using your own webpack configuration rather than angular-cli, so that you can use one of the standard typescript compilers in webpack that won't try to access the templateUrl path at build time.
Assuming that you are currently using angular-cli to build your angular app (you haven't mentioned your current configuration?) then you'd need to eject the angular-cli config so that angular creates a webpack.config.js file, then you can go about altering the configuration to suit your needs.
The following 2 commands will get you out of angular-cli and ready to use webpack directly (if you are on angular 6 then I think the eject functionality may have been disabled but it should work with angular 4/5):
ng eject tells Angular CLI to generate the webpack.config.js file
npm install then installs new dependencies required to use the webpack config directly to build your app.
You'll need to then go through the webpack.config.js and make changes for it to work for you (you'll need to read up on webpack quite a bit as when you first go through it most of it won't make much sense but it's worth getting your head around so you can configure it properly), for the mvc views to work you'll need to alter the modules configuration, updating the loader for typescript files (we use ts-loader as it offers extensions that allow for faster builds with threading to speed things up but there are others out there as well) and adding a loader for html / cshtml files.
Below is a snippet of our configuration that has us using mvc view paths for component templates:
    module: {
        rules: [
            {
                test: /\.aspx$/i,
                loader: 'raw-loader'
            },
            {
                test: /\.(cs)?html$/,
                loader: 'raw-loader'
            },
            {
                test: /\.(eot|svg|cur)$/,
                loader: 'file-loader',
                options: {
                    name: '[name].[hash:20].[ext]',
                    limit: 10000
                }
            },
            {
                test: /\.(jpg|png|webp|gif|otf|ttf|woff|woff2|ani)$/,
                loader: 'url-loader',
                options: {
                    name: '[name].[hash:20].[ext]',
                    limit: 10000
                }
            },
            {
                test: /\.ts$/,
                use: [
                    { loader: 'cache-loader' },
                    {
                        loader: 'thread-loader',
                        options: {
                            // there should be 1 cpu for the fork-ts-checker-webpack-plugin
                            workers: require('os').cpus().length - 1
                        }
                    },
                    {
                        loader: 'ts-loader',
                        options: {
                            happyPackMode: true // IMPORTANT! use happyPackMode mode to speed-up compilation and reduce errors reported to webpack
                        }
                    },
                ]
            },
            {
                test: /\.(ts|js)$/,
                loaders: [
                    'angular-router-loader'
                ]
            }
        ]
    }

It's a bit of a painful process but it can definitely be done.
Bear in mind that with this configuration, you won't be able to use AOT compliation to improve performance...


text:
Q: How can I keep a connection not idle I have a node.js backend that does operations that take over a minute to complete and the result of these operations is returned to the user.
This node.js application is behind an aws load balancer, which has a timeout of 60 seconds (I cannot change it) so when the user does an api call to my backend, the operation takes over 60 seconds so the load balancer times out as the connection was idle for too long.
My question: is it possible for the backend to send some sort of information/packets back to the user every 30 seconds, so the connection is not considered idle?

A: The timeouts are there  for preserving server and intermediary resources  mainly.
Consider the following timeouts -

*

*Connection Timeout - The time a client has to wait until the connection is made

*Socket Timeout - How long a connection can be idle without data

*Request Timeout - How long the fulfillment of a request should take
Even though you can fight off the 2nd type of timeout by periodically sending data to the client, you cannot overcome the 3rd type which maybe even imposed by intermediary gateways or proxies.
So, rather than planning on flavoring the connection with periodic data, go for HTTP polling. In short, your server can take the request, initiate the long process, issue a token and end the connection. The clients can poll with the token and get the processed data when done.


text:
Q: Return named JSON object from c# service in .NET I have a wcf service in .net, which i want to return a named JSON object. This is how i want to return the JSON object:
{"file":"\/9j\/4AAQSkZJRgABAQEASABIAAD\/4"}

But this is how it is returned from the service in c#
"\"\/9j\/4AAQSkZJRgABAQEASABIAAD\/4

This is the code i use to return it
[WebInvoke(Method = "GET",
                ResponseFormat = WebMessageFormat.Json,
                UriTemplate = "getFile/{fname}")]
    public string GetFile(string name)
    {
        /*
         * Some code (not important)
         */

        return JsonConvert.SerializeObject(System.Convert.ToBase64String(image));
    }

A: Create an object with that string as a property. This should work:
return JsonConvert.SerializeObject(
  new { file = System.Convert.ToBase64String(image) }
);

A: You have to create an new object.
var file = JsonConvert.SerializeObject(System.Convert.ToBase64String(image));
return Json(new {file},JsonRequstBehavior.AllowGet);


text:
Q: I'm looking for a way to turn output into an Octet I'm writing a program that handles binary numbers in C#, after i convert the decimal numbers to binary, it will only take as much space as needed, but i need all 4 outputs to be octets (8 characters).
Let's say i convert 255.255.255.0 to binary i get the following outputs
11111111
11111111
11111111
0

what i would want is to get 7 zeroes behind the 0, as it needs to fill out all 8 spaces.
It is always 8 since I'm working with Subnet masks
I hope any of you can help, thank you. :)

A: You can use the below code. You can split the string and pad left each string.
string binary = String.Join(Environment.NewLine, (input.Split('.').Select(x => Convert.ToString(Int32.Parse(x), 2).PadLeft(8, '0'))).ToArray());


text:
Q: tq_mutate() and Volume indicators in R I am using the tidyquant package in R to calculate indicators for every symbol in the SP500.
As a sample of code:
stocks_w_price_indicators<- stocks2 %>%
group_by(symbol)%>%
tq_mutate(select=close,mutate_fun=RSI) %>%
tq_mutate(select=c(high,low,close),mutate_fun=CLV)

This works for price-based indicators, but not indicators that include volume.
I get "Evaluation error: argument "volume" is missing, with no default."
stocks_w_price_indicators<- stocks2 %>%
group_by(symbol)%>%
tq_mutate(select=close,mutate_fun=RSI) %>%
tq_mutate(select=c(high,low,close,volume),mutate_fun=CMF)

How can I get indicators that include volume to calculate properly?

A: There are a few functions from the TTR package that cannot be used with tidyquant. Reason being they need 3 inputs like adjRatios or need an HLC object and a volume column like the CMF function. Normally you would solve this by using the tq_mutate_xy function but this one cannot handle the HCL needed for the CMF function. If you would use the OBV function from TTR that needs a price and a volume column and works fine with tq_mutate_xy.
Now there are 2 options. One the CMF function needs to be adjusted to handle a (O)HLCV object. Or two, create your own function.
The last option is the fastest. Since the internals of the CMF function call on the CLV function you could use the first code block you have and extend it with a normal dplyr::mutate call to calculate the cmf.
# create function to calculate the chaikan money flow
tq_cmf <- function(clv, volume, n = 20){
  runSum(clv * volume, n)/runSum(volume, n)
}

stocks_w_price_indicators <- stocks2 %>%
  group_by(symbol) %>%
  tq_mutate(select = close, mutate_fun = RSI) %>%
  tq_mutate(select = c(high, low, close), mutate_fun = CLV) %>%
  mutate(cmf = tq_cmf(clv, volume, 20))

# A tibble: 5,452 x 11
# Groups:   symbol [2]
   symbol date        open  high   low close   volume adjusted   rsi    clv   cmf
   <chr>  <date>     <dbl> <dbl> <dbl> <dbl>    <dbl>    <dbl> <dbl>  <dbl> <dbl>
 1 MSFT   2008-01-02  35.8  36.0  35    35.2 63004200     27.1    NA -0.542    NA
 2 MSFT   2008-01-03  35.2  35.7  34.9  35.4 49599600     27.2    NA  0.291    NA
 3 MSFT   2008-01-04  35.2  35.2  34.1  34.4 72090800     26.5    NA -0.477    NA
 4 MSFT   2008-01-07  34.5  34.8  34.2  34.6 80164300     26.6    NA  0.309    NA
 5 MSFT   2008-01-08  34.7  34.7  33.4  33.5 79148300     25.7    NA -0.924    NA
 6 MSFT   2008-01-09  33.4  34.5  33.3  34.4 74305500     26.5    NA  0.832    NA
 7 MSFT   2008-01-10  34.3  34.5  33.8  34.3 72446000     26.4    NA  0.528    NA
 8 MSFT   2008-01-11  34.1  34.2  33.7  33.9 55187900     26.1    NA -0.269    NA
 9 MSFT   2008-01-14  34.5  34.6  34.1  34.4 52792200     26.5    NA  0.265    NA
10 MSFT   2008-01-15  34.0  34.4  34    34   61606200     26.2    NA -1        NA