text:
Q: Why is my Object array not keeping the object it is being assigned? I am currently attempting a genetic algorithm program and as such in trying to find a solution I am utilising the genetic operators reproduction, mutation and crossover on a group of tree objects. I have created an initial population according to the "FULL" tree method, after which I am attempting to run a while loop for N generations. The idea is to take the array of the initial population, manipulate it according to the genetic operators and then replace the original population with the new one.
The problem I am having is that my tree objects that are reproduced/mutated/crossed over are not mapping correctly to the correct row in the tree array. Below is a sample of my main method and my object class as well as the code I am using for creating a new population, labeled "regenerate"
tree= genTree.regenerate(tree,repRuns, mutRuns, crossRuns,param[7],tournSize,terms,Functs);

where tree is the original array
public static genTree[] regenerate(genTree[] original, int repRuns, int mutRuns, int crossRuns, int newDep, int tournSize, Function terms[][], Function Functs[]) {
    genTree[] copy = new genTree[original.length];
    int trace = 0;

    genTree tournResult;
    while (trace < repRuns) {
        tournResult = genTree.beginTourn(tournSize, original);
        genTree reprodOperation = genTree.reprodOperator(tournResult);

        copy[trace] = reprodOperation;
        trace++;
    }

    while (trace < (mutRuns + repRuns)) {
        tournResult = genTree.beginTourn(tournSize, original);

        genTree mutateOP = genTree.mutateOperator(tournResult, newDep, terms, Functs);

        copy[trace] = mutateOP;
        trace++;
    }

    while (trace < (repRuns + mutRuns + crossRuns)) {
        tournResult = genTree.beginTourn(tournSize, original);
        genTree winner2 = genTree.beginTourn(tournSize, original);
        genTree[] crossover = genTree.crossoverOperator(tournResult, winner2);
        copy[trace] = crossover[0];
        trace++;

        copy[trace] = crossover[1];
        trace++;
    }

    for (int i = 0; i < copy.length; i++) { //tried deep copy here
        original[i] = copy[i];
    }
  //used to trace through the original array,see what it looks like
    System.out.println("ORIGINAL ARRAY : ");
    for (int i = 0; i < original.length; i++) {
        System.out.println(original[i].displayTreeOnly());
    }
   //see whhat copy array looks like
    System.out.println("COPY ARRAY : ");
    for (int i = 0; i < copy.length; i++) {
        System.out.println(copy[i].displayTreeOnly());
    }

    //  original =copy.clone();
    copy = null;

    return original;
}

above is my attempt at creating a new population. I have tried .clone() but I still get the same results. As a test case consider the following. "Original" contains the following trees:
OR AND NOT NOT NOT AND d5 a0 d0 d1
  AND AND NOT OR NOT NOT a0 d4 d3 d6
  AND NOT AND AND AND OR a3 d1 d3 d1 d4 a3
  AND OR AND OR NOT NOT OR d0 d6 d4 d4 d5 a1
  OR AND AND AND AND AND AND d0 d2 d2 d7 d2 a1 a3 d7
And after running the method (before copy is made to equal original), copy should contain
AND AND NOT OR NOT NOT OR d2 d3 d6 OR AND OR OR NOT d2 d0 d7 d5 a0 d6
AND OR AND OR NOT NOT OR AND d6 d4 d4 d5 a1 d5 d4
AND OR AND OR NOT NOT OR AND d6 AND d4 d5 a1 d5 d4 NOT NOT d2 d3
AND NOT AND AND AND OR a3 d1 d3 d1 d4 d2
AND AND NOT OR NOT NOT OR d2 d3 d6 OR AND OR OR NOT a3 d0 d7 d5 a0 d6

However instead ,both "original" and "copy" contain the following:
AND AND NOT OR NOT NOT OR d2 d3 d6 OR AND OR OR NOT a3 d0 d7 d5 a0 d6
AND OR AND OR NOT NOT OR AND d6 AND d4 d5 a1 d5 d4 NOT NOT d2 d3
AND OR AND OR NOT NOT OR AND d6 AND d4 d5 a1 d5 d4 NOT NOT d2 d3
AND NOT AND AND AND OR a3 d1 d3 d1 d4 d2
AND AND NOT OR NOT NOT OR d2 d3 d6 OR AND OR OR NOT a3 d0 d7 d5 a0 d6

Where some trees are mapped to the correct position yet the array is not correctly mapped completely
Function class:
public class Function {
    private String label;
    private int arity;

    public Function() {

    }

    public void setArity(int arty) {
        arity = arty;
    }

    public void setLabel(String lbl) {
        label = lbl;
    }

    public String getLabel() {
        return label;
    }

    public int getArity() {
        return arity;
    }
}

genTree basic:
public class genTree {

    public Node root;
    private int hits = 0;
    static long seed = System.currentTimeMillis();
    static Random rand = new Random(seed);
    static Random randBool = new Random();
    static genTree[] newPop;
    static genTree winner;
    private int numberNodes = 0;
    private boolean success;

    public genTree() {
        numberNodes = 0;
    }

A: It is, but you're reusing the same object in different elements, so a change to one element affects them all.

A: So basically the main problem I had was that .clone() as well as deep copy methods weren't actually making copies of my objects and hence one change to an object was changing the value of all "copies" of the object. The solution was to create a copy method that manually used get and set methods to create a new copy of the object in question. This solved the problem.


text:
Q: What does save_base with the argument raw=True do in Django? New to Django and programming and can't seem to find any official documentation for save_base with the argument raw=True.  Can someone please spell it out to me what it does?  Haven't been able to find any google results that give a thorough explanation.

A: This seems to be undocumented in the latest Django release indeed.
Have a look at the comments in the source to find out what it does:

The 'raw' argument is telling save_base not to save any parent models
and not to do any changes to the values before save. This is used by
fixture loading.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP mysql_query not working with variable Database Structure Image showing database structure
Database view  Image showing database view
Query ExecutionQuery running perfectly fine when searching normal text
Failed query Query unable to fetch results when searching unicode text
I am facing a peculiar problem. I am storing my query in a variable where it is being constructed on run time though various search parameters being passed from the previous form(13 parameters to be precise). The query constructed is looking for unicode data stored in the database.
Sample of query constructed, which is stored in $query variable is
SELECT * from orders WHERE Court LIKE '%PBR%' AND App_Name LIKE '%काशी%'
the code for the query construction is given below:
$mysqli_link= new mysqli("localhost", "root", "", "revenue");
mysqli_set_charset( $mysqli_link, 'utf8');
if($_POST['id_sflag']=='1')
{
// define the list of fields
$fields = array('CaseNO', 'Yr', 'CaseType', 'Court', 'Dt_Disposal', 'App_Name', 'Res_Name', 'Pet_Cou_Name', 'Res_Cou_Name', 'District', 'Pro_Off_Name', 'Division', 'Tehsil');
$conditions = array();
}

// builds the query
$query = "SELECT * from orders";

// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && !empty($_POST[$field])) {
// create a new condition while escaping the value inputed by the user (SQL Injection)
 $conditions[] = "$field LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
    }
}
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions);
}

echo "$query";

$result = mysqli_query($mysqli_link, $query);
$num_rows=mysqli_num_rows($result);

mysqli_close($mysqli_link);

Now the  problem starts :
When I run the query above which the search criteria like PBR is met it is executed and finds the result. But when I include a wildcard search parameter like app_name it does not give any result whereas there is data in the table. If I copy / paste the query and run it in PHP Myadmin i get the results.
The code to display the results is given below:
$i=1;
$tot=0;
while($row = mysqli_fetch_array($result))
{
$dis=$row['District'];
$div=$row['Division'];
$teh=$row['Tehsil'];
$cnt1=$row['Page_Cnt'];
$dyear=$row['Dis_year'];
$filen=$row['CCY'];
$newfile=$string = str_replace("/","_",$filen);
$newfile1="judgements/"."$dyear"."/"."$newfile".".pdf";
$Appname=$row['App_Name'];
$resname=$row['Res_Name'];
$disposal=$row['Dt_Disposal'];
$officer=$row['Pro_Off_Name'];
$pcnt=$row['Page_Cnt'];
printf("

%s
%s
%s
%s
%s
%s
%s / %s  / %s
%s
View Order

\n",$i,$filen,$Appname,$resname,$disposal,$officer,$dis,$div,$teh,$pcnt,$newfile1);
$tot=$tot+$cnt1;
$i=$i+1;
}

A: Mysql query is now outdated use mysqli query or you can use PDO method. I have given a mysqli query example to fetch data from mysql server.
        $sql="SELECT * FROM commentview WHERE postid = $postid order by comid DESC LIMIT $count;";
        $result=mysqli_query($db,$sql);//$db is the connection string
        if(mysqli_num_rows($result)>0){

            while($row = mysqli_fetch_assoc($result))
            {

                $variable = $row['coulmnname'];//column name as in database
            }
        }
    else
    {
       echo 'Result not Found';
    }

Hope, it will help you. Happy Coding..


text:
Q: QPID 0.30 On Ubuntu 14.04 persistence not working I have installed qpid-0.30 on Ubuntu 14.04. I have compiled the same from source code using the cpp files available in Downloads section.
Everything is working fine. I can connect to QPID, send message and receive too. But I when I restart the process there is no persistence
I am unable to find how to enable the same. The code uses durable queues and persistent messages. Which I can confirm using qpid-stat
Any help or pointers are appreciated
Regards,
Tarun

A: I did find a solution. The problem was that not all the dependencies were resolved and that was causing the build file to ignore the store plugin. After installing all the dependencies. Its all been working fine I created a gist also for the same
http://gist.github.com/tarunlalwani/fdb774fa11de316615e3
#!/bin/sh
export DEBIAN_FRONTEND=noninteractive
QPID_VERSION=0.32
cd $HOME
echo "Creating new folder for qpid - $HOME/qpid"
mkdir qpid
cd qpid
echo "Downloading QPID Packages"
wget -nc http://www.us.apache.org/dist/qpid/$QPID_VERSION/qpid-cpp-$QPID_VERSION.tar.gz &
wget -nc http://www.us.apache.org/dist/qpid/$QPID_VERSION/qpid-tools-$QPID_VERSION.tar.gz &
wget -nc http://www.us.apache.org/dist/qpid/$QPID_VERSION/qpid-python-$QPID_VERSION.tar.gz &
wait
echo "Extracting all packages"
tar xf qpid-cpp-$QPID_VERSION.tar.gz &
tar xf qpid-tools-$QPID_VERSION.tar.gz &
tar xf qpid-python-$QPID_VERSION.tar.gz &
wait
echo "Packages Extracted"
echo "Installing dependcies"
sudo apt-get -qy install python-pip python
sudo apt-get -qy install pkg-config libaio-dev libdb++-dev libboost-all-dev ruby swig libnss3-dev gcc cmake doxygen libsasl2-dev uuid-dev valgrind e2fsprogs
echo "Building source files..."
cd qpid-cpp-$QPID_VERSION
mkdir bld
cd bld
cmake ..
cores=`nproc`
make -j$cores
make install
cd $HOME/qpid/qpid-tools-$QPID_VERSION
python setup.py install &
cd $HOME/qpid/qpid-python-$QPID_VERSION
python setup.py install &
wait


text:
Q: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version Hi I keep getting SQL syntax error when i'm running my code in php, however when i remove the variables and do it manually in MYSQL, not a problem. I've tried 2 different versions of query one with (') and other with (") and nothing. Could you please help?
Thank you.
            $produpdateid = $_GET ['id'];
        $varcat = $_POST['category'];
        $vartitle = strip_tags($_POST['title']);
        $varoverview = strip_tags($_POST['overview']);
        $varfeatures = strip_tags($_POST['features']);
        $varspecification = strip_tags($_POST['specification']);
        $varmaker = strip_tags($_POST['maker']);
        $varsize = $_POST['size'];
        $varprice = $_POST['price'];
        $varstock = $_POST['stock'];
        $vartype = $_POST['stock'];

$q = 'UPDATE products SET products_category_id=' . $varcat . ', title=' . $vartitle . ', overview=' . $varoverview . ', features=' . $varfeatures . ', specification=' . $varspecification . ', size=' . $varsize . ', size_type=' . $vartype . ', maker=' . $varmaker . ', image=' . $varimg . ', price=' . $varprice . ', stock=' . $varstock .' WHERE id=' .$produpdateid;

/*$test = "UPDATE products SET products_category_id=" . $varcat . ", title=" . $vartitle . ", overview=" . $varoverview . ", features=" . $varfeatures . ", specification=" . $varspecification . ", size=" . $varsize . ", size_type=" . $vartype . ", maker=" . $varmaker . ", image=" . $varimg . ", price=" . $varprice . ", stock=" . $varstock ." WHERE id=" .$produpdateid;*/

$updateresult = mysqli_query($dbc,$q);

A: Use double quotes around text.
'UPDATE products SET products_category_id="' . $varcat . '", title="' . $vartitle . '",

etc..


text:
Q: access a class file from local path to java code i am trying to execute testng test case from java code
so i got below code from testng.
TestListenerAdapter tla = new TestListenerAdapter();
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { Run2.class });
testng.addListener(tla);
testng.run();

now i want to provide .class(i.e. Run2) file from local path.
I don't want to place this class to my current package
please tell me how to access a .class file from local location to java code so that it will run the testng testcase from any location where class is present.

A: Try using an instance of java.net.URLClassloader with the url of the folder. And then use loadClass(classname) to load the class.


text:
Q: Indefinite integral question with cube roots Evaluate the following integral:
$$\int\sqrt[3]{x^3+\frac 1 {x^3}} dx$$
For $x^3=u$ and $1+\frac 1 {u^2}=v$, getting $$-\frac 1 6 \int(v-1)^{-\frac 4 3}v^{\frac 1 3} dv$$, what is the next step?

A: I would chose a different substitution:
$$I =\int \big(x^3 +\frac{1}{x^3} \big)^{\frac{1}{3}}dx$$
$$=\int \frac{(x^6 +1)^{\frac{1}{3}}}{x} dx $$
Let: $ u=(x^6+1)^{\frac{1}{3}} $, then:
$x^6=u^3-1 \text{ , and } dx= \frac{(x^6 +1)^{\frac{2}{3}}}{2x^5} du$ .
$$I=\frac{1}{2} \int \frac{u^3}{u^3-1}du$$
$$=\frac{1}{2} \int \frac{1}{u^3-1}du \text{ }+ \text{ } \frac{1}{2}u$$
The first integral can easily be solved now with partial fraction decomposition; and using the derivative of the arctan function.

A: Continue with
$$I=-\frac 1 6 \int(v-1)^{-\frac 4 3}v^{\frac 1 3} dv
= -\frac 1 6 \int \frac1{v-1} \sqrt[3]{\frac v{v-1} } dv
$$
and let $t^3 = \frac v{v-1}$. Then, the integral becomes
\begin{align}
I &= \frac12 \int \frac{t^3}{t^3-1}dt
= \frac12 t +\frac16\ln \frac {t-1}{\sqrt{t^2+t+1}}-\frac1{2\sqrt3}\tan^{-1}\frac{2t+1}{\sqrt3}
\end{align}


text:
Q: Can't use or change my system password. Lion 10.7.5 I've been having password problems for the past month or so. I first noticed that I couldn't update Flash because the installer rejected my system password. Today I tried to solve the problem, looking online for fixes, but nothing has worked so far.

*

*Tried to reset my password on the "Users & Groups" System Preferences pane.

*Restarted holding Option at the boot chimes > "Recovery HD" > "Mac OS X Utilities" > "Utilities" > "Terminal". Entered reset password on the command line. Kept terminal open. Completed the "Reset Password" pane. "Password not saved. You may not have permission to edit this disk or a general failure has occurred."

*Restarted in "Single-User Mode": Command+S at boot chimes. In the command line I entered:
mount -uw /
launchctl load /System/Library/LaunchDaemons/com.apple.opendirectoryd.plist
dscl . passwd /Users/myusername mypassword
reboot

After this third attempt, I attempted to install some software and received the following message: "An error prevented the installation of .... Authorization failed. 100022".
I also used Disk Utility on my "Macintosh HD" to verify and repair permissions, which was successful; however, when I tried to verify and repair the disk itself, I got "Incorrect number of thread records (4, 24418)".
I purchased a new SSD and battery earlier this summer, knowing that I would have to clone my existing HDD to the new drive, but now I can't do much of anything without my password. If I could get a working password, I could try to repair my HDD with DiskWarrior.
Here's another question: how can I create a "Repair Disk Partition" on my new SSD, using existing 10.7 software? Here's an article which seems to say the Disk Utility can do it: "OS X: About Recovery Disk Assistant" https://support.apple.com/en-us/HT202294.
If I only had a password! Thank you all in advance for your wisdom.

A: Perhaps try enabling the root user from single user mode?
launchctl load /System/Library/LaunchDaemons/com.apple.opendirectoryd.plist
passwd root

https://www.personalmacgeniuses.com/2013/10/31/case-of-the-missing-admin-account/#.V8qUxGW_2AU


text:
Q: Definite article for contextually clear references Do we use "the" if we understood from the context that a noun is specific? If your answer is Yes, and I cannot imagine another answer, then the above statement contradicts with the following example which is extracted from the Guardian:

Arriving in Plymouth all passengers were invited to take a leaflet to
claim compensation. I did so by post. A month later, I called
customer service to follow up my claim and.......

Although that previous paragraphs imply that the writer is specifically referring to the customer service of GWR, in the second paragraph, the speaker simply said "I called customer service" (without the). Obviously this is not a typo, I found several examples like this one. So either I don't fully understand the rules of the definite article or this is another special case.
Also this one

The regulator also banned Solarplicity from taking on new customers
because of poor customer service and problems with customer switching.

If I was the writer, I would write "of the poor customer service" because it is very obvious that we are talking about the customer service of Solarplicity.
Also I found the following examples, and I cannot explain why the writer used "the" or "zero article" here. See below

Perez alleges that her former boss, the US head of sales Brian Berner,
took only male employees to the Sundance independent film festival in
2016 and 17. She says employees spoke of "drug use" on these "boys'
trips" and alleges that one man got into a physical fight during one.
She claims these trips excluded more senior women.

I would write "the US head of the sales" because we talk about a specific sales department. It is the sales department of Spotify US. Why the writer did not use "the"?

Perez's suit also alleges that men in the sales department received
"higher compensation and equity" than their female counterparts. She
quotes the company's chief financial officer as having said that he
did not care about diversity at the company and that an HR executive
told staffers his favourite swear word was "cunt".

The writer finally did what I expect, he wrote "the" sales department. I guess because we are talking about the specific sales department of Spotify.

A:
...  I called customer service to follow up my claim and ...

"customer service" here is a department or section of an organization, in the example probably of the railroad. In many ways it is equivalent to "the complaint department", but grammatically similar to "I called reception" or 'I called student affairs" or "I called taxpayer assistance". None of these take an article, while if they are treated as modifiers an article is normal: "I called the reception desk.", "I called the student affairs office.", "I called the  taxpayer assistance hotline."
However in the later quote:

... because of poor customer service ...

"customer service" is an aspect or property of the organization, not a department. The organization may or may not have had a "customer service" department, but it did not deliver good customer service.  This could be recast as

... because of the poor customer service it had shown ...

and in that construction an article would be needed. But this once standard form is now considered a bit wordy and over-formal.
This use of "customer service" is analogous to

*

*... because of poor design ...

*... because of poor implementation ...

*... because of poor color choice ...

*... because of poor organization ...

None of these take an article, although each could be recast in a form which does use an article All of these are natural expressions.
In the quote:

... her former boss, the US head of sales Brian Berner

"US head of sales" is the title of a position, and "US head of the sales" would be both incorrect and sound very unnatural.
In short, the use of an article does not depend solely on whether the referent is specific or not, but on what kind of construction is being used, and to a sizable extent, on the specific habit of the particular phrase. Articles are often elided, and the elided forms may become fixed phrases or at least phrases in common use.


text:
Q: Can't retrieve params from rails form I've got this form tag from which I want to retrieve a starting date and end date (dd/mm/yy):
<%= form_with(url: "dashboard/index", method: "get") do %>
  <%= date_select :start_date, :date_att %>
  <%= date_select :end_date, :date_att %>
  <%= submit_tag("Apply") %>
<% end %>

This is what I'm doing in my controller once the 'Apply' button has been pushed:
start_f = params[:start_date]

which I expect to give me {"date_att(1i)"=>"2019", "date_att(2i)"=>"10", "date_att(3i)"=>"31"} but instead I get <ActionController::Parameters {"date_att(1i)"=>"2019", "date_att(2i)"=>"10", "date_att(3i)"=>"31"} permitted: false>
I tried looking for ways to make the permitted attribute TRUE but I don't understand.
Can anyone help me on this one ?
Cheers.

A: You need to use strong parameters, sth like:
start_f = params.permit(:start_date)[:start_date]


text:
Q: update SQL row with Javascript in it i want to update the below entire code into SQL row as row data but because of the special characters in javascript it is not letting me .
 [script]document.getElementById('form');document.getElementById('form2');[/script] [script]document.getElementById('form');document.getElementById('form2');[/script]


text:
Q: Robospice + Retrofit 2: assigning a Converter I have looked for examples of Robospice + Retrofit 2 in the internet but I couldn't find anything. I am building an example myself but got the following exception:
9:40:56.516 3553-3553/? E/AndroidRuntime: FATAL EXCEPTION: main
     Process: com.carlos.robospiceexample, PID: 3553
     java.lang.NoClassDefFoundError: Failed resolution of: Lretrofit/converter/GsonConverter;
         at com.octo.android.robospice.retrofit.RetrofitGsonSpiceService.createConverter(RetrofitGsonSpiceService.java:37)
         at com.octo.android.robospice.retrofit.RetrofitSpiceService.getConverter(RetrofitSpiceService.java:42)
         at com.octo.android.robospice.retrofit.RetrofitGsonSpiceService.createCacheManager(RetrofitGsonSpiceService.java:31)
         at com.octo.android.robospice.SpiceService.onCreate(SpiceService.java:108)
         at com.octo.android.robospice.retrofit.RetrofitSpiceService.onCreate(RetrofitSpiceService.java:27)
         at com.carlos.robospiceexample.SampleRetrofitSpiceService.onCreate(SampleRetrofitSpiceService.java:14)
         at android.app.ActivityThread.handleCreateService(ActivityThread.java:2761)
         at android.app.ActivityThread.access$1800(ActivityThread.java:151)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:135)
         at android.app.ActivityThread.main(ActivityThread.java:5254)
         at java.lang.reflect.Method.invoke(Native Method)
         at java.lang.reflect.Method.invoke(Method.java:372)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
      Caused by: java.lang.ClassNotFoundException: Didn't find class "retrofit.converter.GsonConverter" on path:
             DexPathList[[zip file "/data/app/com.carlos.robospiceexample-1/base.apk"],
             nativeLibraryDirectories=[/vendor/lib, /system/lib]]
         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
         at com.octo.android.robospice.retrofit.RetrofitGsonSpiceService.createConverter(RetrofitGsonSpiceService.java:37)
         at com.octo.android.robospice.retrofit.RetrofitSpiceService.getConverter(RetrofitSpiceService.java:42)
         at com.octo.android.robospice.retrofit.RetrofitGsonSpiceService.createCacheManager(RetrofitGsonSpiceService.java:31)
         at com.octo.android.robospice.SpiceService.onCreate(SpiceService.java:108)
         at com.octo.android.robospice.retrofit.RetrofitSpiceService.onCreate(RetrofitSpiceService.java:27)
         at com.carlos.robospiceexample.SampleRetrofitSpiceService.onCreate(SampleRetrofitSpiceService.java:14)
         at android.app.ActivityThread.handleCreateService(ActivityThread.java:2761)
         at android.app.ActivityThread.access$1800(ActivityThread.java:151)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:135)
         at android.app.ActivityThread.main(ActivityThread.java:5254)
         at java.lang.reflect.Method.invoke(Native Method)
         at java.lang.reflect.Method.invoke(Method.java:372)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
        Suppressed: java.lang.ClassNotFoundException: retrofit.converter.GsonConverter
         at java.lang.Class.classForName(Native Method)
         at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
         at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                ... 17 more
      Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
03-11 09:40:56.519 3553-3553/? I/Process: Sending signal. PID: 3553 SIG: 9

I think the error is because I haven't assigned a Converter. But when trying to declare a Converter the return type of the method is from Retrofit 1:

That makes me think that is not possible to use Retrofit 2 with Robospice.
Am I right? Can anything be done about this?
Thanks in advance.

A: It's not possible yet. But people are asking for it. From the developer:

...personnally I couldn't find time to maintain the lib as I have been
involved in other OSS projects. Contributors are welcome.
Stéphane


text:
Q: Proper organization and transformation of objects I have a complex SQL query that returns a table like this:

I have it described by this object - IEnumerable<Invoice> where:
public partial class Invoice
{
    public string DocumentNumber { get; set; }
    public DateTime? DocumentDate { get; set; }
    public string DocumentReference { get; set; }
    public string SerialNumber { get; set; }
    public string ProductCode { get; set; }
    public string Description { get; set; }
    public string Certificate { get; set; }
}

The peculiarity of the set of these objects is that they are grouped by the first three fields (if they are the same), the remaining fields are different.
My task is to implement a hierarchical representation of this data, which should look something like this:

I decided for myself that my final view-object should have the following structure - Dictionary<InvoiceHeader, List<InvoiceHierarchi>> where:
public class InvoiceHeader
{
   public string DocumentNumber { get; set; }
   public DateTime? DocumentDate { get; set; }
   public string DocumentReference { get; set; }
}

public class InvoiceHierarchi
{
   public string SerialNumber { get; set; }
   public string ProductCode { get; set; }
   public string Description { get; set; }
   public string Certificate { get; set; }
}

Question #1: Can I write LINQ query that converts IEnumerable<Invoice> to Dictionary<InvoiceHeader, List<InvoiceHierarchi>> and how to do it right?
Question #2: In general, did I choose the right approach to solve my task?

A:
Can I write LINQ query that converts IEnumerable<Invoice> to
  Dictionary<InvoiceHeader, List<InvoiceHierarchi>> and how to do it
  right?

Yes, you can. Try group invoices by InvoiceHeader and convert the result using ToDictionary method
var invoices = new List<Invoice>();
var result = invoices.GroupBy(i => new InvoiceHeader
{
    DocumentDate = i.DocumentDate,
    DocumentNumber = i.DocumentNumber,
    DocumentReference = i.DocumentReference
}).ToDictionary(g => g.Key, g => g.Select(i => new InvoiceHierarchi
{
    Certificate = i.Certificate,
    SerialNumber = i.SerialNumber,
    ProductCode = i.ProductCode,
    Description = i.Description
}).ToList());

Another option is to use ToLookup method
var anotherResult = invoices.ToLookup(i => new InvoiceHeader
    {
        DocumentDate = i.DocumentDate,
        DocumentNumber = i.DocumentNumber,
        DocumentReference = i.DocumentReference
    },
    i => new InvoiceHierarchi
    {
        Certificate = i.Certificate,
        SerialNumber = i.SerialNumber,
        ProductCode = i.ProductCode,
        Description = i.Description
    });

To properly use an InvoiceHeader as a Dictionary key you should override GetHashCode() and Equals() methods for this class, or implelement IEquatable<T> interface
public class InvoiceHeader : IEquatable<InvoiceHeader>
{
    public string DocumentNumber { get; set; }
    public DateTime? DocumentDate { get; set; }
    public string DocumentReference { get; set; }

    public override int GetHashCode()
    {
        return DocumentNumber.GetHashCode() ^ DocumentDate.GetHashCode() ^ DocumentReference.GetHashCode();
    }

    public bool Equals(InvoiceHeader other)
    {
        if (ReferenceEquals(null, other))
            return false;
        if (ReferenceEquals(this, other))
            return true;

        return DocumentNumber == other.DocumentNumber &&
               Nullable.Equals(DocumentDate, other.DocumentDate) &&
               DocumentReference == other.DocumentReference;
    }

    public override bool Equals(object? obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((InvoiceHeader)obj);
    }
}

You can get a warning, that non-readonly property is used in GetHashCode(), because it's not recommended to use GetHashCode() with mutable objects, since the state of object can be changed, but hash remains the same

You can override GetHashCode() for immutable reference types. In
  general, for mutable reference types, you should override
  GetHashCode() only if:
You can compute the hash code from fields that are not mutable;
You can ensure that the hash code of a mutable object
  does not change while the object is contained in a collection that
  relies on its hash code.
Otherwise, you might think that the mutable object is lost in the hash table.

So, it's better to make any (or all) properties of InvoiceHeader as readonly, initialize them from constructor and use to get a hash code


text:
Q: How can I connect geom_segment to geom_line? I would like to connect a segment from the bottom of the graph until it intersects with the geom_line at a given x. I think the best way to do this is with geom_segment. How do I programmatically find where geom_line will be for a given x? How can I expand this framework to support faceting?
mtcars %>%
  ggplot(aes(hp, wt)) +
  geom_line() +
  geom_segment(aes(x = 150, y = 0, xend = 150, yend = 3.248397), col = "red")

A: For this specific case this should work:
mtcars %>%
  ggplot(aes(hp, wt)) +
  geom_line() +
  geom_segment(aes(x = 150, y = 0, xend = 150, yend = min(mtcars[mtcars$hp == 150, "wt" ])), col = "red")

If you want it for a x that does not exist int the data you would have to interpolate.

For all available x values and with faceting:
library(dplyr)
df <-  mtcars %>% select(hp, wt, vs) %>% group_by(hp, vs) %>% summarise(min_wt = min(wt))
mtcars %>%
  ggplot(aes(hp, wt)) +
  geom_line() +
  geom_segment( aes(x = hp, y = 0, xend = hp, yend = min_wt),data = df, col = "red") +
  facet_grid(vs ~ .)

A: library(tidyverse)

mtcars %>%
  ggplot(aes(hp, wt)) +
  geom_line() +
  geom_segment(aes(x = 150, ####
                   y = 0, xend = 150, yend = 3.248397), col = "red")

data("mtcars")
# View(mtcars)
yy <- mtcars %>%
  dplyr::filter(hp == 150) %>%
  dplyr::select(hp, wt)
# length(yy$wt)

Since there are two values of interest, it may be interesting to use segment and curve for representation.
mtcars %>%
  ggplot(aes(hp, wt)) +
  geom_line() +
  geom_segment(aes(x = 150, y = 0, xend = 150, yend = min(yy$wt)), col = "red") +
  geom_curve(aes(x = 150, y = 0, xend = 150, yend = max(yy$wt)),
                 curvature = -0.2, col = "blue",
             arrow = arrow(length = unit(0.03, "npc")))


text:
Q: How to access a variable set at run time with a string? I have a variable I set at start up:
INFO = {:email => "foo@bar.com, :first_name => "foo", :last_name => "bar"}

Then I set param[:type] = "info".
When I type INFO into the console I get this:
 => {:email=>"foo@bar.com", :first_name=>"foo", :last_name=>"bar"}

I would like to get that from typing param[:type] or "info".

A: INFO is a constant and, if it's declared in the global scope, you can retrieve it with:
Object.const_get "info".upcase
Object.const_get param[:type].upcase


text:
Q: VBS script that runs on file selected in Windows Explorer? Is there a way to have a VBS script process a manually selected file in Windows Explorer?
I know about adding commands that are run by right-clicking in a Windows Explorer window (regedit HKEY CLASSES ROOT * Shell etc.): this means I can run a VBscript without actually dclicking it, which should make it possible to have the VB script process a manually selected file other than the script itself. My problem is I do not know how to tell the VBscript to process the file I manually select in windows explorer. In other words: I would like to be able to select a file in the file explorer, right click to launch the VB script - whatever the script does - and have that VB script process the file I just selected. I searched the web extensively but haven't found any coverage of this feature.
Any idea? Thanks!


text:
Q: Nginx Proxy Pass and remove .php extension from URL I'm trying to Proxy Pass /do/uploads.php?id=xxx to /do/upload?id=xxx in Nginx
Here is my try
location /do {
    rewrite /do/uploads\.php /do/uploads$1 break;
    proxy_pass          http://domain/do;
    proxy_set_header    Host $host;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Proto $scheme;
    proxy_set_header    X-Real-IP $remote_addr;
}

A: I found a solution. Here it is:
location = /do/uploads.php {
    proxy_pass          http://domain/switch/do;
    proxy_set_header    Host $host;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Proto $scheme;
    proxy_set_header    X-Real-IP $remote_addr;
}


text:
Q: Finding all possible combinations in a specific case Lets say I have a set such as (1, 1, 1, 1) where each number can be from 1 to 100.
All possible combinations will be (1, 1, 1, 1), (1, 1, 1, 2), ... , (1, 1, 1, 100), ... (100, 100, 100, 100).
Order does matter, (1, 1, 2, 3) is different from (2, 3, 1, 1).
How do I go about finding the number of possible combinations where only 2 numbers are the same. I.E. (1, 1, 2, 3) or even (1, 1, 2, 2) There needs to always be 2 numbers that are the same. I doesn't matter if there are 2 groups of 2 numbers that are the same. So not (1, 2, 3, 4) or (1, 1, 1, 2) or (1, 1, 1, 1).
I could find the total possible combinations which is 100^4 then subtract combinations were all 4 are the same and subtract combinations where 3 are the same and subtract combinations were none are the same.
But lets say that I cannot do that and have to do it using another method. How would I do it?
I thought it would be done by doing 100 x 99 x 98 x 6 but that gives me an answer of 5821200.
I believe the answer is 5890600, So I am off by a little and I am not sure what I am doing wrong.
Any help would be appreciated.

A: You then need to calculate the permutations of two different ordered strings:

*

*Permutations with a group of cardinality 2 and 2 groups of cardinality 1 over 4 positions, i.e. $\binom{4}{2,1,1}=\frac{4!}{2!1!1!}=12$

*Permutations with 2 groups of cardinality 2 over 4 positions, i.e. $\binom{4}{2,2}=\frac{4!}{2!2!}=6$
Now for each case you must add the variations of the groups that are permutating and after divide by the permutations of groups of the same cardinality because if not you are counting some strings twice.
The variations are counted over groups, so for the case 1 the variations will be $(100)_3=100*99*98$, and for the case 2 they will be $(100)_2=100*99$. And we must divide by $2!$ respectively because for each case you have two groups of the same cardinality.
Then we have
$$12*50*99*98+6*50*99=5850900$$

A: The answer is
$$6\cdot100\cdot99\cdot98+3\cdot100\cdot99=5{,}850{,}900$$
The first term counts the number of $4$-tuples with a single pair of identical entries; the second counts the number with two distinct pairs of identical entries.  The $6$ corresponds to the number of different possible pairs (i.e., $6={4\choose2}$), while the $3$ is the number of entries that can be paired with the first entry.

A: Let $X$ be the set of all the tuples you're interested in.
Let $Y$ be the set of tuples $(a,b,c)$ where $a,b,c$ are distinct integers from $1$ to $100$. (That is, we don't allow any of them to be the same.)
It should be easy to compute $|Y|$, so we want to relate $|X|$ to $|Y|$ somehow. If you could find some function $f : X \to Y$ and prove that $|f^{-1}(y)| = k$ for all $y \in Y$, this would show that $|X| = k|Y|$. Can you think of such an $f$? (Finding a good $f$ should be fairly easy. Finding the right value of $k$ will take a little thought.)
(Edit to add: your sentence "I doesn't matter if there are 2 groups of 2 numbers that are the same. So not (1, 2, 3, 4) or (1, 1, 1, 2) or (1, 1, 1, 1)." seems to be self-contradictory. Is (1,1,1,1) allowed or not? My answer is based on (1,1,1,1) not being allowed.)

A: You can have two cases
CASE I
only 2 numbers are same, rest 2 are different
$$\binom{100}{1}\binom{99}{2}*\frac{4!}{2!}  =5821200$$
CASE II  two numbers are same and rest two are also same
$$\binom{100}{1}\binom{99}{1}*\frac{4!}{2!*2!*2!}=29700$$
So the total combinations are 5850900


text:
Q: Put SQL and HTML value in echo isset($person['FS'] == "") i want my site to echo the html in to my site and take the SQL value that i put in it
in normal php echo it would look like this
echo "
<input type=\"checkbox\" name=\"inputFs\" value=\"1\" " . $person['Fs'] . "/>Syns på förstasidan"

but how do I do when i put it in to an isset?
echo isset($person['Fs'] == "")) ? "
<input type=\"checkbox\" name=\"inputFs\" value=\"1\" " . $person['Fs'] . "/>Syns på förstasidan" : "";

A: Can't figure it out why you are using $person["Fs"] inside input tag
May be this should help
echo (isset($person['Fs']) ? '
<input type="checkbox" name="inputFs" value="1"/>Syns på förstasidan' : '');

OR
If you are using $person["Fs"] for value then try this
echo (isset($person['Fs']) ? '
<input type="checkbox" name="inputFs" value="' . $person["Fs"] .'"/>Syns på förstasidan' : '');

If your checking for a variable if it is blank or contain some particular value.
Then you don't have to use isset it works without isset
Consider your checking if $person['Fs'] == "checked" then use
echo ($person['Fs'] == "checked" ? '
<input type="checkbox" name="inputFs" value="' . $person["Fs"] .'"/>Syns på förstasidan' : '');


text:
Q: Awk, little endian order and 4 hex digits I suppose that I have a decimal number, e.g., 97254 ---> 00017BE6 (hex value) using:
echo "" | awk '{printf("%08X", 97254)}'

Now, if I want to convert hex number (00017BE6, in this case) into 4 numbers of 2 digits (max 8 numbers in input) in little endian order and CSV format, i.e. (target):
E6,7B,01,00

using only Awk (a function ad-hoc and return value, for example), how to do?
With:
awk '{for (i=1;i<=7;i=i+2) array[i]=substr($1,i,2)} END{for(a in array) print array[a]}'

I have:
00
01
7B
E6

Using:
awk '{for (i=1;i<=7;i=i+2) array[i]=substr($1,i,2)} END{for(a in array) print array[a]}' ORS=","

I have:
00,01,7B,E6,

but how to remove last comma e convert it in little endian order?
How do I go about this?
Any ideas?

A: echo 00017BE6 | awk '{for (i=7;i>=1;i=i-2) printf "%s%s",substr($1,i,2),(i>1?",":"\n")}'
E6,7B,01,00

Using sprintf, we can start with the decimal number:
$ echo 97254 | awk '{hex=sprintf("%08X",$1); for (i=7;i>=1;i=i-2) printf "%s%s",substr(hex,i,2),(i>1?",":"\n");}'
E6,7B,01,00

How it works

*

*for (i=7;i>=1;i=i-2)
This starts a loop over index i in which we count down from 7 to 1.

*printf "%s%s",substr($1,i,2),(i>1?",":"\n")
This prints the desired substring followed by a comma or a newline.  The construct i>1?",":"\n" is awk's form of a ternary statement.  It returns , if i>1 or a newline otherwise.

A: You've asked for an awk command, but consider this generic bash function, which uses printf, sed, and tac / tail -r internally, and works on both BSD (including OSX) and Linux systems:
# SYNOPSIS
#   toHexBytes num [numBytes [littleEndian]]
# DESCRIPTION
#   Prints the bytes that num is composed of in hex. format separated by commas.
#   NUM can be in decimal, hexadecimal, or octal format.
#   NUMBYTES specifies the minimum number of *bytes* to output - defaults to *4*.
#   Specify 0 to only output as many bytes as needed to represent NUM, '' to
#   represent the default when also specifying LITTLEENDIAN.
#   By default, the bytes are printed in BIG-endian order; if LITTLEENDIAN is nonzero,
#   the bytes are printed in LITTLE-endian order.
# PLATFORM SUPPORT
#   BSD and Linux platforms
# EXAMPLES
#   toHexBytes 256      # -> '00,00,01,00'
#   toHexBytes 256 '' 1 # -> '00,01,00,00'
#   toHexBytes 0x100 0  # -> '01,00'
toHexBytes() {
  local numIn=$1 numBytes=${2:-4} littleEndian=${3:-0} numHex revCmd
  # Convert to hex.
  printf -v numHex '%X' "$numIn"
  # Determine number of 0s that must be prepended.
  padCount=$(( numBytes * 2 - ${#numHex} ))
  (( padCount < 0 && ${#numHex} % 2 )) && padCount=1
  # Apply 0-padding, if needed.
  (( padCount )) && printf -v numHex "%0$(( padCount + ${#numHex} ))X" "0x$numHex"
  if (( $littleEndian )); then # LITTLE-endianness
    # Determine command to use for reversing lines.
    [[ $(command -v tac) ]] && revCmd='tac' || revCmd='tail -r'
    # Insert a newline after every 2 digits, except for the last,
    # then reverse the resulting lines,
    # then read all resulting lines and replace all but the last newline
    # with ','.
    sed 's/../&\'$'\n''/g; s/\n$//' <<<"$numHex" |
      $revCmd |
        sed -e ':a' -e '$!{N;ba' -e '}; s/\n/,/g'
  else # BIG-endianness
    # Insert ',' after every 2 digits, except for the last pair.
    sed 's/../&,/g; s/,$//' <<<"$numHex"
  fi
}

Applied to your example number:
$ toHexBytes 97254 4 1 # 4 bytes, LITTLE-endian
E6,7B,01,00

$ toHexBytes 97254 # 4 bytes, BIG-endian
00,01,7B,E6


text:
Q: jQuery UI draggable not bound to parent bounds I have created a js-based node editor. I have a div element I use as a parent for the nodes. Although I define the containment to parent you can move the nodes outside of the parents bounds. You can not move it lower than the last document element though.

The important html code is:
    <button type="button" class="btn btn-primary" onclick="sendData(fetchData())">Send data</button>

        <svg id="svg"/>

    <button type="button" class="btn btn-primary" onclick="sendData(fetchData())">Send data</button>

And the js for the draggable is:
$(this.domElement).draggable({
    containment: 'parent',
    cancel: '.connection,.output,.data',
    drag: function(event, ui){
        that.updatePosition();
    }
});

Maybe I did something wrong with the parenting so here it is as well:
this.domElement = document.createElement('div');
document.getElementById('node-container').appendChild(this.domElement);

I haven't worked with JavaScript too much and am still learning!
EDIT: Here is the definition of the node-container:

Complete StoryNode.js:
https://hastebin.com/kiyoyekoce.js

// ===================================================================
// Node class. Represents a javascript version of the java Node class
// ===================================================================

var nodes = []; //Have second reduced node version running, maybe as a method in the Node? Call simple for loop in web-link

function StoryNode(name) {
    this.name = name;

    let that = this;

    nodes.push(this);

    // Add our graphical representation

    this.domElement = document.createElement('div');
    document.getElementById('node-container').appendChild(this.domElement);

    this.domElement.classList.add('node');
    this.domElement.classList.add('container-fixed');
    this.domElement.setAttribute('title', name.replace("Node",""));

    let remDom = document.createElement('div');
    remDom.classList.add('delete-node');
    remDom.innerHTML ='';
    this.domElement.appendChild(remDom);

    remDom.onclick = function (e) {

        that.detachAll();

        for( let i = 0; i < nodes.length; i++){
            if ( nodes[i] === that) {
                nodes.splice(i, 1);
            }
        }

        that.domElement.parentElement.removeChild(that.domElement);
    };

    // Add the node body

    // Directories
    var innerDomGroup = document.createElement('div');
    innerDomGroup.classList.add('row');
    this.domElement.appendChild(innerDomGroup);

    // Outputs
    this.outputDomGroup = document.createElement('div');
    this.outputDomGroup.classList.add('col-fixed-small-1');
    innerDomGroup.appendChild(this.outputDomGroup);

    // Inner Data
    this.dataDomGroup = document.createElement('div');
    this.dataDomGroup.classList.add('col-fixed-medium-1');
    innerDomGroup.appendChild(this.dataDomGroup);

    // Inputs
    this.inputDomGroup = document.createElement('div');
    this.inputDomGroup.classList.add('col-fixed-small-1');
    innerDomGroup.appendChild(this.inputDomGroup);

    //Node data
    this.inputs = [];
    this.data = [];
    this.outputs = [];
}

StoryNode.prototype.addInput = function(name, inputType){
    let input = new NodeInput(name, inputType);
    input.node = this;
    this.inputs.push(input);
    this.inputDomGroup.appendChild(input.domElement);

    return input;
};

StoryNode.prototype.addOutput = function(name, outputType){
    let output = new NodeOutput(name, outputType);
    output.node = this;
    this.outputs.push(output);
    this.outputDomGroup.appendChild(output.domElement);

    return output;
};

StoryNode.prototype.addData = function(name, outputType){
    let data = new NodeData(name, outputType);
    data.node = this;
    this.data.push(data);
    this.dataDomGroup.appendChild(data.domElement);

    return data;
};

StoryNode.prototype.ownsInput = function(input){
    for(let i = 0; i < this.inputs.length; i++){
        if(this.inputs[i] === input)
            return true;
    }
    return false;
};

Node.prototype.ownsOutput = function(output){
    for(let i = 0; i < this.outputs.length; i++){
        if(this.outputs[i] === output)
            return true;
    }
    return false;
};

StoryNode.prototype.detachAll = function(output){
    for(let item of this.inputs){
        if(item.output)
            item.output.detachInput();
    }

    for(let item of this.outputs){
        if(item.input)
            item.detachInput();
    }
};

StoryNode.prototype.updatePosition = function(){

    for(let j = 0; j < this.outputs.length; j++){
        if(this.outputs[j].input != null){
            let oP = this.outputs[j].getOutputPoint();
            let iP = this.outputs[j].input.getAttachPoint();

            let pStr = this.createPath(iP, oP);
            this.outputs[j].input.path.setAttributeNS(null, 'd', pStr);
        }
    }

    for(let j = 0; j < this.inputs.length; j++){
        if(this.inputs[j].output != null){
            let iP = this.inputs[j].getAttachPoint();
            let oP = this.inputs[j].output.getOutputPoint();

            let pStr = this.createPath(iP, oP);
            this.inputs[j].path.setAttributeNS(null, 'd', pStr);
        }
    }
};

StoryNode.prototype.createPath = function(a, b){
    let diff = {
        x: b.x - a.x,
        y: b.y - a.y
    };

    let pathStr = 'M' + a.x + ',' + a.y + ' ';
    pathStr += 'C';
    pathStr += a.x + diff.x / 3 * 2 + ',' + a.y + ' ';
    pathStr += a.x + diff.x / 3 + ',' + b.y + ' ';
    pathStr += b.x + ',' + b.y;

    return pathStr;
};

StoryNode.prototype.moveTo = function(point){
    this.domElement.style.top = point.y + 'px';
    this.domElement.style.left = point.x + 'px';
    this.updatePosition();
};

StoryNode.prototype.initUI = function(){
    let that = this;
    // Make draggable
    // noinspection JSValidateTypes
    $(this.domElement).draggable({
        containment: 'parent',
        cancel: '.connection,.output,.data',
        drag: function(event, ui){
            that.updatePosition();
        }
    });

    //Mak node design smaller as it holds no data inputs
    if(this.data.length === 0) {
        this.domElement.classList.remove('container-fixed');
        this.domElement.classList.add('container-fixed-min');

        this.dataDomGroup.classList.remove('col-fixed-medium-1');
        this.dataDomGroup.classList.add('col-fixed-medium-1-min');
    }

    // Fix positioning
    this.domElement.style.position = 'absolute';

    document.body.appendChild(this.domElement);
    // Update Visual
    this.updatePosition();
};

// Node 1
let node = new StoryNode('Page');

// Move to initial positions
node.moveTo({x: 150, y: 20});

// Connect Nodes

// Add to DOM
node.initUI();
body{
    background-color: #101010;
    color: #d4d4d4;
    font-family: sans-serif;
}
.node:before{
    content:attr(title) " ";
    display: block;
    border-top-left-radius:.75em;
    border-top-right-radius:.75em;
    background-color:#6e6e6e;
    padding:0.1em .3em 0em;
    margin:-.1em -.3em 0.2em;
}
.node{
    background-color: #4e4e4e;
    border-radius: .75em;
    display: inline-block;
    padding:0.1em .3em .25em;
    position:absolute;
    cursor: move;
}
.connection:after{
    position:absolute;
    border:solid 1px #dedede;
    background-color: #2e2e2e;
    width:0.5em;
    height:0.5em;
    border-radius:0.5em;

}

.delete-node{
    display: inline-block;
    font-weight: 400;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    font-size: 1rem;
    line-height: 1.5;
    transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;

    position:absolute;
    color: #b8b8b8;
    background-color: transparent;
    border-radius:0.5em;
    width:22px;
    height:22px;

    cursor: default;

    top: 3px;
    right: 8px;
}

.connection.filled:after{
    border:solid 1px transparent;
}
.connection:hover:after{
    border-color:red;
}
.output{
    left: .1em;
    top:.1em;
    cursor: pointer;
}
.input{
    left: 2em;
    top: .1em;
    cursor: pointer;
}
.connection{
    width:100%;
    position:relative;
    padding-right:0.5em;
    cursor:pointer;
}
.connection:after{
    content:"";
    right:0em;
    top:0.25em;
}

.filled-node:after{
    background-color: #d4d9de;
}
.empty-node:after{
    border: 2px solid #d4d9de;
}

.filled-boolean:after{
    background-color: #4f8fde;
}
.empty-boolean:after{
    border: 2px solid #4f8fde;
}

svg{
    position:absolute;
    top:0px;
    left:0px;
    z-index:-100;
    width:100%;
    height:100%;
}

textarea {
    resize: none;
}

/* The switch - the box around the slider */
.switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 34px;
}

/* Hide default HTML checkbox */
.switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

/* The slider */
.slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    -webkit-transition: .4s;
    transition: .4s;
}

.slider:before {
    position: absolute;
    content: "";
    height: 26px;
    width: 26px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    -webkit-transition: .4s;
    transition: .4s;
}

input:checked + .slider {
    background-color: #2196F3;
}

input:focus + .slider {
    box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
    -webkit-transform: translateX(26px);
    -ms-transform: translateX(26px);
    transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
    border-radius: 34px;
}

.slider.round:before {
    border-radius: 50%;
}

.round-edge {
    border-radius: 15px;
}
.container-fixed {
    width: 200px !important;
}

.container-fixed-min {
    width: 100px !important;
}

.col-fixed-small-1 {
    width: 5px;
}

.col-fixed-small-2 {
    width: 5px;
}
.col-fixed-medium-1 {
    width: 180px;
    padding-left: 15px;
    margin-right: -12px;
}

.col-fixed-medium-1-min {
    width: 80px;
    padding-left: 15px;
    margin-right: -12px;
}

.node-container {
    background-color: #2e2e2e;
    border-radius: 10px;
    height: 500px;
    width: 90%;
}

    <svg id="svg"/>

        <button type="button" class="btn btn-primary">Send data</button>

A: I suspect that the issue is when you append the element. If it's not appended when you initialize draggable, it may not understand the parent relationship.
Consider the following example:

$(function() {
  function addNode(title, content, tObj) {
    if (title == undefined) {
      title = "New Node";
    }
    if (content == undefined) {
      content = "

";
    }
    if (tObj == undefined) {
      tObj = $("#node-container");
    }
    var node = $("
", {
      class: "node-element"
    }).appendTo(tObj);

    $("
", {
      class: "node-title"
    }).html(title).appendTo(node);

    $("", {
      class: "btn btn-delete-node"
    }).html("x").click(function() {
      var r = confirm("Are you sure you want to delete this node?");
      if (r) {
        $(this).closest(".node-element").remove();
      }
    }).appendTo($(".node-title", node));

    $("
", {
      class: "node-content"
    }).html(content).appendTo(node);

    node.draggable({
      containment: 'parent',
      handle: ".node-title",
      cancel: '.connection,.output,.data',
      stop: function(e, ui) {
        // update position
      }
    });
  }
  $(".add-node-btn").click(function() {
    addNode();
  });
});
body {
  background-color: #000;
  font-family: "arial", san-seriff;
}

.node-container {
  background-color: #2a2a2a;
  border-radius: 10px;
  margin: 3px;
}

.btn-primary {
  border: 0;
  border-radius: 6px;
  padding: 4px;
  background-color: #0000ff;
  color: #FFF;
}

.node-container .node-element {
  background-color: #212121;
  border-radius: 6px;
  border: 0;
  width: 125px;
  height: 75px;
}

.node-container .node-element .node-title {
  background-color: #484848;
  border-radius: 6px 6px 0 0;
  border: 0;
  min-height: 1em;
  color: #fff;
  text-align: center;
}

.node-container .node-element .node-title .btn-delete-node {
  float: right;
  padding-right: 6px;
  cursor: pointer;
}

<button type="button" class="btn btn-primary">Send data</button> <button type="button" class="btn btn-primary add-node-btn">Add Node</button>

  <svg id="svg" />

<button type="button" class="btn btn-primary">Send data</button>

Since your example code is not a Minimal, Complete, or Verifiable example, it's difficult to determine when or how your elements are added versus initialized.
Hope that helps.


text:
Q: Npm prepublish script webpack not found I am trying to modify a npm module and I want to include the modified module as a local dependency.
When deploying this app on hosting, I am facing a strange webpack not found problem. I managed to reproduce the problem in my local machine by removing webpack globally.
My package.json:
1) I try to include the local module in package.json dependencies:
{
  "name": "parse-server-example",
  "version": "1.4.0",
  "description": "An example Parse API server using the parse-server module",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "https://github.com/ParsePlatform/parse-server-example"
  },
  "license": "MIT",
  "dependencies": {
    "webpack": "2.3.3",
    "express": "~4.11.x",
    "kerberos": "~0.0.x",
    "parse": "~1.8.0",
    "parse-dashboard-simple": "./parse-dashboard-simple",
    "parse-server": "*"
  },
  "scripts": {
    "start": "node index.js"
  },
  "engines": {
    "node": "7.6.0"
  }
}

Take note that I have a local module called "./parse-dashboard-simple".
My local module's package.json:
{
  "name": "parse-dashboard",
  "parseDashboardFeatures": [
    "Data Browser",
    "Cloud Code Viewer",
    "Cloud Code Jobs Viewer and Runner",
    "Parse Config",
    "API Console",
    "Class Level Permissions Editor",
    "Pointer Permissions Editor",
    "Send Push Notifications",
    "Logs Viewer",
    "Push Status Page",
    "Relation Editor"
  ],
  "description": "The Parse Dashboard",
  "keywords": [
    "parse",
    "dashboard"
  ],
  "homepage": "https://github.com/ParsePlatform/parse-dashboard",
  "bugs": "https://github.com/ParsePlatform/parse-dashboard/issues",
  "version": "1.0.25",
  "repository": {
    "type": "git",
    "url": "https://github.com/ParsePlatform/parse-dashboard"
  },
  "license": "SEE LICENSE IN LICENSE",
  "files": [
    "Parse-Dashboard",
    "bin",
    "README.md",
    "LICENSE"
  ],
  "dependencies": {
    "bcryptjs": "^2.3.0",
    "body-parser": "^1.15.2",
    "commander": "^2.9.0",
    "connect-flash": "^0.1.1",
    "cookie-session": "^2.0.0-alpha.1",
    "csurf": "^1.9.0",
    "express": "^4.13.4",
    "json-file-plus": "^3.2.0",
    "package-json": "^2.3.1",
    "passport": "^0.3.2",
    "passport-local": "^1.0.0",
    "webpack": "~1.12.0"
  },
  "devDependencies": {
    "babel-core": "~5.8.12",
    "babel-loader": "~5.3.0",
    "babel-plugin-remove-proptypes": "~1.0.0",
    "babel-polyfill": "^6.7.2",
    "babel-runtime": "~5.8.25",
    "css-loader": "~0.18.0",
    "file-loader": "^0.8.5",
    "history": "^2.1.2",
    "http-server": "~0.8.5",
    "immutable": "~3.7.5",
    "immutable-devtools": "~0.0.4",
    "jest-cli": "^12.0.2",
    "js-beautify": "~1.5.0",
    "marked": "^0.3.5",
    "node-sass": "^3.7.0",
    "parse": "1.6.14",
    "prismjs": "~1.2.0",
    "react": "^15.0.1",
    "react-addons-test-utils": "^15.0.1",
    "react-dnd": "~2.1.4",
    "react-dnd-html5-backend": "~2.0.0",
    "react-dom": "^15.0.1",
    "react-router": "^2.6.0",
    "request-promise": "^4.1.1",
    "sass-loader": "~3.1.2",
    "style-loader": "~0.12.3",
    "svg-prep": "~1.0.0",
    "transform-jest-deps": "^2.1.0",
    "webpack": "~1.12.0"
  },
  "scripts": {
    "dev": "node ./Parse-Dashboard/index.js & webpack --config webpack/build.config.js --devtool eval-source-map --progress --watch",
    "dashboard": "node ./Parse-Dashboard/index.js & webpack --config webpack/build.config.js --progress --watch",
    "pig": "http-server ./PIG -p 4041 -s & webpack --config webpack/PIG.config.js --progress --watch",
    "build": "NODE_ENV=production webpack --config webpack/production.config.js && webpack --config webpack/PIG.config.js",
    "test": "NODE_PATH=./node_modules jest",
    "generate": "node scripts/generate.js",
    "prepublish": "webpack --config webpack/publish.config.js",
    "start": "node ./Parse-Dashboard/index.js"
  },
  "bin": {
    "parse-dashboard": "./bin/parse-dashboard"
  },
  "engines": {
    "node": "7.6.0"
  },
  "main": "Parse-Dashboard/app.js",
  "jest": {
    "testPathDirs": [
      "src/lib"
    ],
    "scriptPreprocessor": "<rootDir>/testing/preprocessor.js",
    "testDirectoryName": "tests",
    "testFileExtensions": [
      "test.js"
    ],
    "unmockedModulePathPatterns": [
      "react",
      "react-dom",
      "react-addons-test-utils",
      "fbjs"
    ]
  }
}

If I run "npm install" at the root level of this project, I will get this error:
npm WARN prepublish-on-install As of npm@5, `prepublish` scripts will run only for `npm publish`.
npm WARN prepublish-on-install (In npm@4 and previous versions, it also runs for `npm install`.)
npm WARN prepublish-on-install See the deprecation note in `npm help scripts` for more information.

> parse-dashboard@1.0.25 prepublish /mypath/-dashboard-advanced
> webpack --config webpack/publish.config.js

sh: webpack: command not found
npm ERR! addLocal Could not install /mypath/-dashboard-advanced
npm ERR! addLocal Could not install /mypath/-dashboard-simple
npm WARN Local package.json exists, but node_modules missing, did you mean to install?
npm ERR! Darwin 16.5.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install"
npm ERR! node v7.6.0
npm ERR! npm  v4.1.2
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn

npm ERR! parse-dashboard@1.0.25 prepublish: `webpack --config webpack/publish.config.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the parse-dashboard@1.0.25 prepublish script 'webpack --config webpack/publish.config.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the parse-dashboard package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     webpack --config webpack/publish.config.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs parse-dashboard
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls parse-dashboard
npm ERR! There is likely additional logging output above.

So my understanding is that the webpack is needed in prepublish script but it is not found. But I have intentionally added webpack as dependencies in both root project or the local module (in both dev and production dependencies just to be safe), why is webpack still not found?


text:
Q: tmux does not start when using tty (ubuntu 11.10) I went through this similar question at https://stackoverflow.com/a/7410228/880040 and the 6th thing to check,

Make that your terminal capabilities file exists: ls -lh /usr/share/terminfo/*/$TERM

Is what doesn't pass. This entire folder is empty. tmux works as expected when starting it from a ssh session. On the tty session, it just hangs on a newline after the tmux command. Cannot kill it with ctrl-c either, have to ssh in and killall tmux.
$TERM is 'linux'
OS is Ubuntu 11.10 (server edition) 32 bit
Unfortunately the above post did not explain what to do if /usr/share/terminfo was empty.

A: In Ubuntu, the various terminfo files are provided by ncurses-base1 - you might first want to try reinstalling to see if that fixes your issue.
If that doesn't work, you can always copy the working terminfo (from the box you are SSH'ing from) across to your Ubuntu machine.
First, establish that you do not have an entry for linux on the Ubuntu box:
infocmp linux
Then, on the machine that you SSH from, make a copy of the terminfo:
infocmp linux > linux
copy it to your remote machine with scp and then, on the remote machine, install it with:
# tic /path/to/linux
You should also consider installing screen-256color as this is the terminfo tmux works best with.

1. http://packages.ubuntu.com/ko/natty/ncurses-base


text:
Q: convert an 1D array to multidimensional array in PHP I have this array:
Array
(
    [1] => animal
    [1-1] => turtle
    [1-1-1] => sea turtle
    [1-1-2] => box turtle
    [1-1-3] => green turtle
    [1-1-3-1] => green turtle with brown tail
)

and I want some how to convert it into:
Array
(
    [1-title] => animal
    [1-sons] => array(
            [1-1-title] => turtle
            [1-1-sons] => array(
                    [1-1-1] => sea turtle
                        [1-1-2] => box turtle
                    [1-1-3-title] => green turtle
                    [1-1-3-sons] => array(
                            [1-1-3-title] => green turtle
                                  )
                    )
              )
)

or maybe you can suggest a better way for organizing the outputted array..
but how to do that?
I know that's not easy task at all, I'm writing a parser that will walk on data and make tree out of them..
Thanks in advance for your help and advices..

A: The easiest way of organizing your data would be in such a way:
array (
  'Animal' =>
  array (
    'Turtle' =>
    array (
      'Sea Turtle',
      'Box Turtle',
      'Green Turtle' =>
      array (
        'Green Turtle With Brown Tail',
      ),
      'Common Turtle',
    ),
  ),
);

// Or, otherwise written (equivalent to the above)

$animals = array();
$animals['Animal'] = array();
$animals['Animal']['Turtle'] = array();
$animals['Animal']['Turtle'][] = 'Sea Turtle';
$animals['Animal']['Turtle'][] = 'Box Turtle';
$animals['Animal']['Turtle']['Green Turtle'] = array();
$animals['Animal']['Turtle']['Green Turtle'][] = 'Green Turtle With Brown Tail';
$animals['Animal']['Turtle'][] = 'Common Turtle';

Essentially, the name of the animal is the value, unless it has children, then the value is an array and the key is the animal name.

That way, you can easily parse the values by doing the following:
parse_animals($animals);

function parse_animals($array, $indent = 0) {
  if(!is_array($array)) return;    // A little safe guard in case.

  foreach($array as $key => $value) {
    echo str_repeat('  ', $indent) . "- ";

    if(is_array($value)) {
      echo $key . "\n";
      parse_animals($value, $indent + 1);
    } else {
      echo $value . "\n";
    }
  }
}

The above in the console will output the following:
- Animal
  - Turtle
    - Sea Turtle
    - Box Turtle
    - Green Turtle
      - Green Turtle With Brown Tail
    - Common Turtle

EDIT: And here is a version that will output it for a webpage.
function parse_animals_web($array) {
  if(!is_array($array)) return;    // A little safe guard in case.

  foreach($array as $key => $value) {
    echo '
';

    if(is_array($value)) {
      echo '
' . htmlentities($key) . "
";
      parse_animals_web($value);
    } else {
      echo '
' . htmlentities($value) . "
";
    }

    echo '
';
  }
}

The output is:

*

*Animal

*

*Turtle

*Sea Turtle

*Box Turtle

*Green Turtle

*

*Green Turtle With Brown Tail

*Common Turtle

Maybe you want to get the children of an animal.
function get_children_of($array, $name) {
  foreach($array as $key => $value) {
    if(is_array($value)) {
      if($key === $name) {
        return $value;
      } else {
        return get_children_of($value, $name);
      }
    }
  }

  return array();
}

Now we can get all the children of the Green Turtle and output them.
$green_turtle = get_children_of($animals, 'Green Turtle');
parse_array($green_turtle);

The output is:
- Green Turtle With Brown Tail

EDIT: Since you say you are stuck with the input array being in that weird format, here is a function that will convert your array into the format I specified above:
function convert_array($array) {
  $new_array = array();

  $keys = array_keys($array);
  foreach($keys as $key) {
    $level = explode('-', $key);
    $cur_level = &$new_array;
    $cur_key = '';

    foreach($level as $o_key) {
      $cur_key = ltrim($cur_key . '-' . $o_key, '-');
      $next_key = $cur_key . '-1';
      $value = $array[$cur_key];
      $has_child = array_key_exists($next_key, $array);

      if($has_child) {
        if(!array_key_exists($value, $cur_level)) {
          $cur_level[$value] = array();
        }
        $cur_level = &$cur_level[$value];
      } else {
        $cur_level[] = $value;
      }
    }
  }

  return $new_array;
}

A: That really depends on how/for what you are going to use the resulting tree. Can you perhaps write down more details about that?

A: Try this:
$array = array(
    '1' => 'animal',
    '1-1' => 'turtle',
    '1-1-1' => 'sea turtle',
    '1-1-2' => 'box turtle',
    '1-1-3' => 'green turtle',
    '1-1-3-1' => 'green turtle with brown tail'
);
$tree = array();
foreach ($array as $path => $val) {
    $segments = explode('-', $path);
    $last = array_pop($segments);
    $tmp = &$tree;
    $path = '';
    foreach ($segments as $segment) {
        $path .= $segment.'-';
        if (!isset($tmp[$path.'sons'])) {
            $tmp[$path.'sons'] = array();
        }
        $tmp = &$tmp[$path.'sons'];
    }
    $tmp[$path.$last.'-title'] = $val;
}
print_r($tree);

But your data structure doesn't make much sense.

A: $result = array();
foreach ($array as $position => $text) {
    $p = explode('-', $position);
    putIntoTree($result, $p, $text);
}

function putIntoTree( &$tree, $posInfo, $item ) {
    $index = array_shift($posInfo) - 1;

    if (!count($posInfo)) {
        $tree[$index]['name'] = $item;
    } else {
        if (!isset($tree[$index]['children'])) {
            $tree[$index]['children'] = array();
        }
        putIntoTree($tree[$index]['children'], $posInfo, $item);
    }
}

Results in this, which seems a reasonable way to hold the data.
Array
(
    [0] => Array
        (
            [name] => animal
            [children] => Array
                (
                    [0] => Array
                        (
                            [name] => turtle
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [name] => sea turtle
                                        )

                                    [1] => Array
                                        (
                                            [name] => box turtle
                                        )

                                    [2] => Array
                                        (
                                            [name] => green turtle
                                            [children] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [name] => green turtle with brown tail
                                                        )
                                                )
                                        )
                                )
                        )
                )
        )
)

A: What you are trying to achieve is some kind of a nested set and therefore the easiest way to implement it would be to save the parent id in the children's entry:
// the tree
0 => array(parent => NULL, name => turtle),
1 => array(parent => 0, name => green turtle),
2 => array(parent => 0, name => blue turtle),
3 => array(parent => 1, name => green turtle with yellow nose)

You can walk through this hierarchy using a simple recursive function.
If you use objects instead of associative arrays you even get some performance increase.


text:
Q: migrating from require to import syntax What is equivalent of
const pqr = require('abc').xyz,

in import syntax?
The object notation is causing a bit confusion, i know basic like, the equivalent of
const pqr = require('abc');

will be
import pqr from 'abc'

A: As @arslan2012 commented:
import { xyz as pqr } from 'abc';


text:
Q: need help to arabic text in wordpress I am doing a worpdress theme which is in Arabic language. When I write anything in Arabic. It turn into ????(question mark).
Please help to fix this.
Thanks

A: *

*Make sure all your files are encoded in UTF-8.

*Keep your theme language agnostic: Write all strings in English and use the proper translation functions to get the translated string (eg. Arabic):
_e( 'Hello world!', 'your_text_domain' );

A: *

*Files should be Encoded in UTF-8, this can be verified with your text editor

*Add a charset meta tag: <meta charset="<?php bloginfo("charset");?>" />
You shouldn't touch any php files in regards to this problem, the only time when you will do it is when you set the language for the blog, like this:
define ('WPLANG', 'ar');

A: In wp-config.php, make sure you have the following line (this is for the database, but it helps ensure everything is consistent):
define('DB_CHARSET', 'utf8');

Also you may want to switch your UI to arabic (however this is optional), but to do that, you can do change your language line in wp-admin to the following:
define( 'WPLANG', 'ar' );

Next, add the following code to appear in all your pages, a recommended spot of it is header.php
<!DOCTYPE html>

<html  <?php language_attributes(); ?>>
    <head>
        <meta charset="<?php bloginfo("charset") ?>">

        <!-- The rest of your code goes here -->


text:
Q: Remove everything starting from here to here using jQuery I have the following HTML, where I want to remove everything starting from the first "a" to the table. Since there is some text that isn't inside a container, I can't figure out how to simply go from one point to another

$('.MyDiv a').nextUntil('.MyDiv table').remove();
$('.MyDiv a').nextUntil('table').remove();

div1

div2

div3

  <!- Remove all below ->
  a1
  a2
  a3

ul1

  Text with no wrap more text with no wrap

div4

  Text with no wrap
  <!- Remove all above ->

table

New HTML should look like this

div1

div2

div3

table

A: Not as simple as I thought. I am using contents and a test
Possibly addBack could be used but this is easy to read and works

var found = false;
$('.MyDiv').contents().each(function() {

  // debugging
  var whitespace=this.nodeType==3, comment=this.nodeType==8, tag=this.nodeType==1;
  if (!whitespace) console.log(tag?this.tagName:"comment",this.textContent);
  // end debugging

  if (this.tagName=="A") found=true;
  if (found) {
    // stop at first table - to stop at comment, test nodeType==8 instead
    if (this.tagName =="TABLE") {
      console.log("stopped");
      return false;
    }
    else $(this).get(0).remove(); // dom / textnodes
  }
});
.as-console-wrapper { max-height: 3.5em !important; }

d1

d2

d3

  <!- Remove all below ->
  first a
  second a
  third a

an LI

  Text with no wrap more text with no wrap

d4

  Text with no wrap
  <!- Remove all above ->

Table An embedded anchor

  After table

A: One way is to traverse each element between the two comment nodes and remove those one by one. This solution assumes that the comments' contents are fixed, and solely depends on those.

var comments = $(".MyDiv").contents()
  .filter(function() {
    return this.nodeType == 8 && this.textContent.trim() === 'Remove all below' || this.textContent.trim() === 'Remove all above';
  }).get();

var elem = comments[0].nextSibling;

while (elem !== comments[1]) {
  var next = elem.nextSibling;
  elem.remove();
  elem = next;
}

before comment

  Text with no wrap more text with no wrap

  Text with no wrap

after comment

A: Just for fun, I took @mplungjan's answer and turned it into a function removeUntil that could be used like:
$('.MyDiv a').removeUntil('table');

But since any a elements after the table would also match $('.MyDiv a'), you would want to actually use:
$('.MyDiv a:first-of-type').removeUntil('table');

And since you probably don't want to remove content that is deeper than the first level of .MyDiv (like any as found inside the table), you would actually want to use:
$('.MyDiv > a:first-of-type').removeUntil('table');

Here is the removeUntil function code:
jQuery.fn.extend({
  removeUntil: function(untilSelector) {
    this.each(function() {
      var theStart = $(this);
      var theParent = theStart.parent();
      var found = false;
      theParent.contents().each(function() {
        if ($(this).is(theStart)) {
          found = true;
        }
        if (found) {
          if ($(this).is(untilSelector)) {
            return false;
          } else {
            $(this).get(0).remove(); // dom / textnodes
          }
        }
      });
    });
  }
});

A simple demo based on your original HTML, but with two .MyDiv sections:  https://jsfiddle.net/b7fkm8g3/


text:
Q: Angularjs way, conditionally to generate new form and append it to the page or state change i am  new to angularjs,
and wonder What is the angularjs way to complete such a task as conditionally generating or showing the form ?
Lets say
$scope.counter = function(){
   if ($scope.years < 5){

    // what is here? append or should  return true and use ng-if directive in html?

    }}

Thank you

A:

var myApp = angular.module('myApp',[]);

myApp.controller('ctrl', ['$scope', function($scope) {
  $scope.years = 10;
}]);

age :
  <input type="number" ng-model="years">
  <div ng-if="years<5"> show if years < 5

5"> show if years > 5

just like that

A: Ideally you should do it from HTML file via by ng-if\ng-show\ng-hide directives.
Like below (years should be part of controller\component):
<div ng-if="years<5"> html code


text:
Q: Calculating expected cost of a shipment Small electrical motors are shipped in lots of 50. Before such a shipment is accepted an inspector chooses 5 motors at random and tests them. If none of the motors are found to be defective, the shipment is accepted. If one or more are found to be defective, then the entire shipment is tested (all 50 motors). Suppose that it is known that there are 3 defective motors in the lot.
Suppose it costs $100 to test a motor.
What is the expected cost for any given shipment?
What is the expected cost until a shipment is accepted?
My friend and I are doing this to prep for our midterm and we can't come up with how to calculate the p values for p(x=0) and p($x\geq 1)$
We're super lost please walk us through this

A: Five motors are chosen out of $50$ for testing.  If none of the defective ones is chosen, all must be chosen from the $47$ good ones.  The probability that no defective motor is chosen for testing is $${{47\choose5}\over{50\choose5}}$$


text:
Q: Can't get async and await working Logic says: User 1 sends a message to User 2 via Server 1. Server 1 records it in DB (mysql) and sends the message to Server 2 to be sent to User 2. Server 1 responds to User 1 that message has been sent. While at the back-end (asynchonously) Server 1 keeps requesting Server 2 for the delivery of the message, when delivered, updates the database and set delivery status as delivered or failed (after few hours of re-trying).
But I don't think this code is working. Because database never gets updated.
SendMessage.aspx
protected void btnSend_Click(object sender, EventArgs e)
{
    global g = new global();
    g.CallUpdateSMSStatus(cmdSMS.LastInsertedId.ToString(), msgID);
}

global.cs
    public async void CallUpdateSMSStatus(string strMsgID, string strMsgID)
    {
        await updateMessageStatus(strMsgID, strMsgIDServer);
    }

    public async Task updateMessageStatus(string strMsgID, string strMsgID)
    {
        global g = new global();
        int timer = 10000;
        int intStatus = 2;
        // 2 - means Message Sent - Any other number finishes delivery request
        while (intStatus == 2)
        {
            await Task.Run(() =>
            {
                intStatus = g.checkSMSStatus(strMsgIDServer);
                //checkSMSStatus REQUEST SERVER 2 for status of message
                if (intStatus != 2)
                {
                    //Update Status in the Database
                }
                else
                {
                    if (timer < 3600000)
                    {
                        timer *= 10;
                    }
                    Thread.Sleep(timer);

                }
            });
        }
    }

A: I think that's what you want:
public async Task updateMessageStatus(string strMsgID, string strMsgIDServer, int timeToNext)
{
    await Task.Run(() =>
    {
        global g = new global();

        int intStatus = g.checkSMSStatus(strMsgIDServer);
        //checkSMSStatus REQUEST SERVER 2 for status of message
        if (intStatus != 2)
        {
            //Update Status in the Database
        }
        else
        if (timeToNext < 3600000)
            Task.Delay(timeToNext).ContinueWith((t) => updateMessageStatus(strMsgID, strMsgIDServer, timeToNext * 10));
    });
}


text:
Q: Equivalent of Python's comprehensive list operation on string in R I want to perform operations on a list of characters in R as describe below:

*

*Keep only what is after the '-'

*Then keep only the four first characters of the remaining (complete by 'J' if its length is lower than four)

*Put everything in upper case

Example in Python
lt = ['LTA-Yokudo', 'LTA-Luo', 'LTA-Kawasaki']
[str(x).split('-')[1][:4].upper().ljust(4, 'J') for x in lt]

Expected result
['YOKU', 'LUOJ', 'KAWA'] # in Python
c('YOKU', 'LUOJ', 'KAWA') # in R

Note that string in the list will always contain the character '-'.
What would be the best solution to do so in R ?
Thank you

A: A base R approach:
> x <- c('LTA-Yokudo', 'LTA-Luo', 'LTA-Kawasaki')
> x1 <- toupper(substr(x,5,8))
> ifelse(nchar(x1) == 3,paste0(x1,"J"),x1)
[1] "YOKU" "LUOJ" "KAWA"

A: A solution using stringr (and the pipe operation from magrittr).
library(magrittr)
library(stringr)

lt <- c('LTA-Yokudo', 'LTA-Luo', 'LTA-Kawasaki')

lt2 <- lt %>%
  str_extract(pattern = "(?<=-)[A-Za-z]*") %>% # Extract letters after -
  str_sub(start = 1, end = 4) %>% # Get four letters
  str_pad(width = 4, pad = "J", side = "right") %>% # Add J at the end
  str_to_upper() # To lower case
lt2
# [1] "YOKU" "LUOJ" "KAWA"

A: Consider following non-looped solution in base R
lt = c('LTA-Yokudo', 'LTA-Luo', 'LTA-Kawasaki')

n <- toupper(substr(lt, regexpr('-', lt)+1, regexpr('-', lt)+4))
ifelse(nchar(n)==3, paste0(n, 'J'), n)

# [1] "YOKU" "LUOJ" "KAWA"

A: Using the stringr package (within tidyverse), you could do something like this.
library(tidyverse)

lt = c('LTA-Yokudo', 'LTA-Luo', 'LTA-Kawasaki')

##If you want lower case
new_1 <- str_to_lower(str_sub(str_replace(lt, "^.*-",""),start = 1, end = 4))

new_1

##If you want upper case
new_2 <- str_to_upper(str_sub(str_replace(lt, "^.*-",""),start = 1, end = 4))
new_2


text:
Q: remove selected options from another dropdowns using angularjs 2 filters I am able to removing the selected options from another drop down using
angularjs 1. But how do i use same logic using angular2 filters?
can anyone help to write a filter using angular 2?

    <select ng-model="selected[$index]" ng-options="obj.id as obj.label for obj in foos | customFilter:selected:selected[$index]"></select>

controller
angular.module('myApp', [])
.filter('customFilter', function(filterFilter) {
  return function(input, filterEach, exclude) {
    filterEach.forEach(function(item) {
      if (angular.equals(item, exclude)) { return; }
      input = filterFilter(input, '!'+item);
    });
    return input;
  };
});

A: Instead of building it using a filter I think is more clear and explicit to bind options to a method, that returns options not selected... something like:
getOptions() {
   return this.model.filter((el)=>{
      return !(el in this.selectedOptions);
   })
}

A: import {Pipe, PipeTransform} from "@angular/core";
@Pipe({name: 'arrayDiff',  pure: false})
export class ArrayDiffPipe implements PipeTransform {
  public array1:any=[];
  transform(array: Array<any>, diff: Array<any>): Array<any> {
    var i, item,
      newArray = [],
      exception = Array.prototype.slice.call(arguments, 2);
    if (array && Array.isArray(array)) {
      for (i = 0; i < array.length; i++) {
        item = array[i].description;
        if(diff.indexOf(item) < 0 || exception.indexOf(item) >= 0) {
          newArray.push(item);
        }

      }
      console.log(newArray, 'newArray');
      return newArray;

    }

  }
}


text:
Q: Didn't find class "mono.android.app.Application" My Xamarin Android app is already in production, people are downloading it from Google play and everything seems to be fine, except from time to time I get following errors in Google Play Developer Console :
java.lang.RuntimeException: Unable to instantiate application mono.android.app.Application:          java.lang.ClassNotFoundException: Didn't find class "mono.android.app.Application" on path: DexPathList[[],nativeLibraryDirectories=[/vendor/lib, /system/lib, /vendor/lib]]
at android.app.LoadedApk.makeApplication(LoadedApk.java:559)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5119)
at android.app.ActivityThread.access$1500(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1418)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "mono.android.app.Application" on path: DexPathList[[],nativeLibraryDirectories=[/vendor/lib, /system/lib, /vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
at android.app.Instrumentation.newApplication(Instrumentation.java:982)
at android.app.LoadedApk.makeApplication(LoadedApk.java:550)
... 11 more

or similar but slightly different version:
java.lang.RuntimeException: Unable to instantiate application mono.android.app.Application: java.lang.ClassNotFoundException: Didn't find class "mono.android.app.Application" on path: /mnt/asec/myapp-1/pkg.apk
at android.app.LoadedApk.makeApplication(LoadedApk.java:504)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4563)
at android.app.ActivityThread.access$1400(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "mono.android.app.Application" on path: /mnt/asec/myapp-1/pkg.apk
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
at android.app.Instrumentation.newApplication(Instrumentation.java:985)
at android.app.LoadedApk.makeApplication(LoadedApk.java:499)
... 11 more

I've got zero google results for ClassNotFoundException + mono.android.app.Application. According to Developer console it comes from android 4.2 and 4.4., different devices (HTC, Samsung..), even from devices which i tested and everything works (HTC One).
Any ideas? Is this bug in mono? or Xamarin? Or am I doing something wrong?

A: Whenever xamarin app install in the device it is find to mono runtime support lib, if it is not installed in the device then it will stop to run so, if u have run without mono installation you can change some settings on:

Property => Android Option

Go to Packaging and select only one Bundle assemblies into native code, and also go to linker and select linking is None then run it.
I hope it might work.


text:
Q: temporary objects with variadic template arguments; another g++/clang++ difference The following code
struct foo
 {
   foo ()
    { }

   template <typename T0, typename ... Ts>
      foo (const T0 & t0, const Ts & ... ts)
       { foo(ts...); }
 };

int main()
 {
   foo f(1, 2);

   return 0;
 }

compile without problems with g++ (4.9.2) and give the following errors
tmp_002-11,14,gcc,clang.cpp:9:16: error: expected ')'
       { foo(ts...); }
               ^
tmp_002-11,14,gcc,clang.cpp:9:13: note: to match this '('
       { foo(ts...); }
            ^
tmp_002-11,14,gcc,clang.cpp:9:14: error: redefinition of 'ts'
           { foo(ts...); }
             ^
tmp_002-11,14,gcc,clang.cpp:8:42: note: previous definition is here
      foo (const T0 & t0, const Ts & ... ts)
                                         ^
2 errors generated.

with clang++ (3.5).
As usual my question is: who's right?
--- EDIT ---
Clarification: I know that foo(ts...) can't be a call to a delegate constructor but (I think that can be) the construction of a temporary foo object (another foo object).
But, as pointed by vsoftco, what's happening when sizeof...(ts) == 1U?
In that case, foo(ts...); is a (re)declaration of a single variable ts (so, I suppose, should be right clang++) or the variadic syntax avoid this problem (so, I suppose, should be right g++)?
There are C++11 standard experts that can clarify this?
p.s.: sorry for my bad English.

A: This looks like a clang bug. Here's a minimal reproduction:
template <typename ... Ts> void foo (Ts ... ts)
{
    int(ts...);
}

(there's no even need to instantiate the template).
Judging from the error messages, clang interprets int(ts...); as a declaration, which it cannot be, because (ts...) cannot be a declarator.
One could ask: when ts... is a parameter pack of size one, shouldn't it be parsed similarly to ts and thus cause the whole construct to be interpreted as a declaration? The answer is no.
There is a syntactic ambiguity in the C++ grammar between "declaration" and "expression-statement" productions. If an ambiguous construct can be parsed as a "declaration", it is a "declaration". int(ts...) cannot be parsed such, because the grammar does not have productions needed for such parse. Once the construct is classified as an expression statement, and not before that, we can interpret ts... as a parameter pack and calculate sizeof...(ts). If the construct is not classified as an expression, sizeof...(ts) has no meaning at all, because ts... has no meaning, as such syntax cannot be in a declaration.
Once it is established that int(ts...); is an expression statement and not a declaration, one may interpret it and instantiate relevant templates and expand parameter packs. At this point it's too late to go back and claim that it was a declaration all along, based on the fact that sizeof...(ts) == 1. One could not possibly deduce that sizeof...(ts) == 1 if it was a declaration (ts wouldn't be a parameter pack then).
Moreover, clang seemingly insinuates that it is not even a syntactically correct declaration. One cannot possibly derive facts like sizeof...(ts) == 1 out of something that is not syntactically correct.


text:
Q: Using pivot table to generate "training matrix" I have a table of "CertificateEntries" which goes along the lines of;
Entity_ID | Certificate_ID | CertificateExpiry
1         | 1              | dd/mm/YYYY
1         | 2              | dd/mm/YYYY

etc., etc. It's a many-to-many relationship essentially, entities can have many certs and certs can be assigned to many entities.
What I would like to do is have this pivoted so that the list of certificates is the columns;
Entity_ID | 1 | 2 | 3 | 4 |
1         | T | T | F | F |
2         | T | F | F | T |

I can't quite grasp how to get this done, all the online examples seem to indicate that you need COUNT, MAX, AVG, etc. Ideally I would love to have the expiry in place of the T/F but if that's not possible, I can understand...
If someone could help point me in the right direction, that would be fantastic. Thanks.

A: Try this :
begin try
create table #test
(Entity_ID int,Certificate_ID int,CertificateExpiry date)

insert into #test values(1,1,'01/01/2013')
insert into #test values(1,2,'05/01/2013')
insert into #test values(1,5,'01/05/2013')
insert into #test values(1,9,'05/12/2013')

insert into #test values(2,1,'10/05/2013')
insert into #test values(2,2,'12/03/2013')
insert into #test values(4,6,'2/05/2013')
insert into #test values(5,8,'4/09/2013')

--select * from #test

DECLARE @Certificate_Ids VARCHAR(8000)

SELECT @Certificate_Ids = COALESCE(@Certificate_Ids + '], [', '') + cast(Certificate_ID as varchar(20)) FROM
(select distinct Certificate_ID from #test ) as a

Set @Certificate_Ids='['+@Certificate_Ids+']'

--print @Certificate_Ids

Declare @query varchar(max)

Set @query=
'SELECT
Entity_ID, ' + @Certificate_Ids + '
FROM #test
PIVOT
(
  MAX(CertificateExpiry)
  FOR Certificate_ID in (' + @Certificate_Ids + ' )
) A'

print @query

exec(@query)

drop table #test
end try

begin catch
drop table #test
end catch


text:
Q: Can I customised default WP table I have a XML file that consist of product information.
Format of XML file :
<product>
    <name>Product-1</name>
    <description>this is product 1 description</description>
    <category>Category-1<category>
    <merchant>1234</merchant>
    <price>12</price>
    <instock>1<instock>
    <stockstatus>45</stockstatus>
    <image>http://www.example.com/1.jpg</image>
    <manufacture>987</manufacture>
</product>

I need to write a script that will add these detail as a product. For now I am not using any WP plugin for eCommerce  purpose.
I am planning to create a custom post type as wpproduct that will store these products details.
So for now I can use name as post  title, description as post content and image as post thumbnail. And for storing the meta data I can store it in postmeta table.
So I can create the post by using wp_insert_post and whatever ID it will return, I will use that ID in update_post_meta to update the meta data such as price, stock status , stock quantity, manufacturer etc.
Like this it can be done..
 Main Concern
So for a single product I need to write 1 wp_insert_post and then 6 update_meta_data query. So 7 query for 1 product. Not exactly 7 query as WP inbuilt function uses many query for validation check.
What will happen if my XML file has 1 lakh product. So for adding 1 lakh product 7 lakh mysql query will run.
 Assumption
I am just eager to know like can I add custom column in WP wp_posts table so that I can add 1 product in 1 query only. I might use raw mysql query to add it.
Please help me and guide the best way to do it.
Thanks

A: I've checked and WordPress does, by default, retrieve & cache all post meta along with the main query's posts, so you're perfectly fine storing a product's additional fields as standard post meta.
You might want to store Brands (merchants? manufacturers?) as a custom taxonomy so that you can take advantage of built-in templates and queries to show all products of a certain brand.

A: Import is inherently heavy operation, because it is bulk operation and writes are inherently very heavy (relative to reads).
If you are not time–constrained for the operation — does it really matter?

*

*Write your import as command line tool.

*Make sure you disable PHP timeout.

*Make sure you can efficiently restart process at certain point, in case something goes wrong.

After that it takes as long as it takes.
If you are time constrained (for example having to run this often/repeatedly) then you would need to approach this as general performance problem. That is you need to profile actual performance and determine what the bottlenecks are in the process.
In case if multiple queries are an issue you could consider staged process — when meta is first stored as single entry on import and then expanded into more convenient form at a later point.
I would recommend to stay away from modifying native tables since there seems to be little functional need to do so in this case.


text:
Q: httpd.conf deleted - now I can't load PDO driver I deleted my httpd.conf by accident.
I am trying to make a working httpd.conf again based on the default file.
I definitely haven't changed php.ini or any environment variables etc, but now my php doesn't seem to be able to use PDO (any new PDO() causes a PDOException).
Also, when I run phpinfo() I get these:
PDO support    enabled
PDO drivers    no value

I've tried this possible solution: PDO drivers no value in Windows but it doesn't work for my case.
Is there any other solution? And what could I be missing from httpd.conf that could cause this?
My new httpd.conf:
LoadModule php7_module "c:/php/php7apache2_4.dll"
AddType application/x-httpd-php .php

ServerRoot "c:/Apache24"

LoadModule access_compat_module modules/mod_access_compat.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule dir_module modules/mod_dir.so
LoadModule mime_module modules/mod_mime.so

#required modules for SSL (HTTPS):
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
Include conf/extra/httpd-ssl.conf

<Directory />
    AllowOverride none
    Require all denied
</Directory>

DocumentRoot "c:/Apache24/htdocs/public"
<Directory "c:/Apache24/htdocs/public">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

<IfModule dir_module>
    DirectoryIndex index.php
</IfModule>

<Files ".ht*">
    Require all denied
</Files>

ErrorLog "logs/error.log"
LogLevel notice

<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
    <IfModule logio_module>
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>
    CustomLog "logs/access.log" common
</IfModule>

<IfModule alias_module>
    ScriptAlias /cgi-bin/ "c:/Apache24/cgi-bin/"
</IfModule>

<Directory "c:/Apache24/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule headers_module>
    RequestHeader unset Proxy early
</IfModule>

<IfModule mime_module>
    TypesConfig conf/mime.types
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz
</IfModule>

<IfModule proxy_html_module>
Include conf/extra/proxy-html.conf
</IfModule>

<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>