问:
How to read XML to a list of POJOs in Java?
I'm new to XML and im trying to read in an XML page and store its contents in an arraylist.

So far i seem to have been able to get the arraylist filled with the first content, as when i tried an isEmpty, it returned false. so there is definitely containing something.
However, when i try to call the overided tostring method, or even try to call any individual category for that matter, it just returns empty?

can anyone help?

heres the code im working with:

```<code>package test;

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class xmlmx {

   public static void main(String[] args) {
      ArrayList<Anime> list = new ArrayList<Anime>();
      try {
         File inputFile = new File("c:\\code\\ad\\XMLDB.xml");
         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
         Document doc = dBuilder.parse(inputFile);
         doc.getDocumentElement().normalize();
         System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
         NodeList nList = doc.getElementsByTagName("Anime");
         System.out.println("----------------------------");

         for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
               Element eElement = (Element) nNode;
               list.add(new Anime(eElement.getAttribute("ID"),
                                  eElement.getAttribute("name"),
                                  eElement.getAttribute("altname"),
                                  eElement.getAttribute("seasons"),
                                  eElement.getAttribute("episodes"),
                                  eElement.getAttribute("status"),
                                  eElement.getAttribute("DS"),
                                  eElement.getAttribute("have"),
                                  eElement.getAttribute("left"),
                                  eElement.getAttribute("plot"),
                                  eElement.getAttribute("connect"),
                                  eElement.getAttribute("image")));
               System.out.println(list.get(0).toString());
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
</code>```

the arraylist is of type anime, a class here:

```<code>    package test;

class Anime{
    private String ID;
    private String name;
    private String altname;
    private String seasons;
    private String episodes;
    private String status;
    private String DS;
    private String have;
    private String left;
    private String plot;
    private String connect;
    private String image;

    public Anime(String ID,
                 String name,
                 String altname,
                 String seasons,
                 String episodes,
                 String status,
                 String DS,
                 String have,
                 String left,
                 String plot,
                 String connect,
                 String image) {
        this.ID = ID;
        this.name = name;
        this.altname = altname;
        this.seasons = seasons;
        this.episodes = episodes;
        this.status = status;
        this.DS = DS;
        this.have = have;
        this.left = left;
        this.plot = plot;
        this.connect = connect;
        this.image = image;
    }

/*
 getters and setters here...
*/
    @Override
    public String toString() {
        return "Anime [ID=" + ID +
               ", name=" + name +
               ", altname=" + altname +
               ", seasons=" + seasons +
               ", episodes=" + episodes +
               ", status=" + status +
               ", DS=" + DS +
               ", have=" + have +
               ", left=" + left +
               ", plot=" + plot +
               ", connect=" + connect +
               ", image=" + image + "]";
    }
}
</code>```

finally, heres the xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Anime>
    <record ID="BL1">
        <name>Bleach</name>
        <altname>Burichi</altname>
        <seasons>16</seasons>
        <episodes>366</episodes>
        <status>Finished</status>
        <sound>Dubbed</sound>
        <have>All</have>
        <left>-/-</left>
        <plot>Ichigo gets grim reaper powers, fights reapers, hollows and everything in between</plot>
        <connect>Bleach movies</connect>
        <image>images/bleach.jpg</image>
    </record>
</Anime>
</code>```

any help would be greatly appreciated, thank you

答:
Hi basically your understanding about the w3c dom xml element is wrong. "name:, "altname" etc are not attributes of "Animie" element. those are "child nodes" of "record" node. So first you have to fetch "record" node by iterating child nodes of "Animie" element. Then you can iterate through the child nodes of "record" element so that you can populate your Anime object.

Here's a simple implementation of your "xmlmx class that works. I had to use a map because you have ommitted the setter methods, this can be improved just trying to fix the xml concepts in your head.

Just replace your class with this.

```<code>package test;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import com.sun.org.apache.xerces.internal.dom.DeferredElementImpl;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class xmlmx {

    public static void main(String[] args) {
        ArrayList<Anime> list = new ArrayList<Anime>();
        try {
            File inputFile = new File("test.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();
            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());

            Node recordNode = null;
            NodeList childNodes = doc.getFirstChild().getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                if (childNodes.item(i).getNodeName().equals("record")) {
                    recordNode = childNodes.item(i);
                    break;
                }
            }
            System.out.println("----------------------------");

            Map<String, String> map = new HashMap<>();
            if (recordNode != null) {
                NodeList subNodes = recordNode.getChildNodes();
                for (int i = 0; i < subNodes.getLength(); i++) {
                    if (subNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                        map.put(subNodes.item(i).getNodeName(), subNodes.item(i).getTextContent());
                    }
                }
            }

            String id = ((DeferredElementImpl) recordNode).getAttribute("ID");
            list.add(new Anime(id,
                    map.get("name"),
                    map.get("altname"),
                    map.get("seasons"),
                    map.get("episodes"),
                    map.get("status"),
                    map.get("DS"),
                    map.get("have"),
                    map.get("left"),
                    map.get("plot"),
                    map.get("connect"),
                    map.get("image")));

            System.out.println(list.get(0));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
I'm new to XML and im trying to read in an XML page and store its contents in an arraylist.

So far i seem to have been able to get the arraylist filled with the first content, as when i tried an isEmpty, it returned false. so there is definitely containing something.
However, when i try to call the overided tostring method, or even try to call any individual category for that matter, it just returns empty?

can anyone help?

heres the code im working with:

package test;

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class xmlmx {

   public static void main(String[] args) {
      ArrayList<Anime> list = new ArrayList<Anime>();
      try {
         File inputFile = new File("c:\\code\\ad\\XMLDB.xml");
         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
         Document doc = dBuilder.parse(inputFile);
         doc.getDocumentElement().normalize();
         System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
         NodeList nList = doc.getElementsByTagName("Anime");
         System.out.println("----------------------------");

         for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
               Element eElement = (Element) nNode;
               list.add(new Anime(eElement.getAttribute("ID"),
                                  eElement.getAttribute("name"),
                                  eElement.getAttribute("altname"),
                                  eElement.getAttribute("seasons"),
                                  eElement.getAttribute("episodes"),
                                  eElement.getAttribute("status"),
                                  eElement.getAttribute("DS"),
                                  eElement.getAttribute("have"),
                                  eElement.getAttribute("left"),
                                  eElement.getAttribute("plot"),
                                  eElement.getAttribute("connect"),
                                  eElement.getAttribute("image")));
               System.out.println(list.get(0).toString());
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

the arraylist is of type anime, a class here:

    package test;

class Anime{
    private String ID;
    private String name;
    private String altname;
    private String seasons;
    private String episodes;
    private String status;
    private String DS;
    private String have;
    private String left;
    private String plot;
    private String connect;
    private String image;

    public Anime(String ID,
                 String name,
                 String altname,
                 String seasons,
                 String episodes,
                 String status,
                 String DS,
                 String have,
                 String left,
                 String plot,
                 String connect,
                 String image) {
        this.ID = ID;
        this.name = name;
        this.altname = altname;
        this.seasons = seasons;
        this.episodes = episodes;
        this.status = status;
        this.DS = DS;
        this.have = have;
        this.left = left;
        this.plot = plot;
        this.connect = connect;
        this.image = image;
    }

/*
 getters and setters here...
*/
    @Override
    public String toString() {
        return "Anime [ID=" + ID +
               ", name=" + name +
               ", altname=" + altname +
               ", seasons=" + seasons +
               ", episodes=" + episodes +
               ", status=" + status +
               ", DS=" + DS +
               ", have=" + have +
               ", left=" + left +
               ", plot=" + plot +
               ", connect=" + connect +
               ", image=" + image + "]";
    }
}

finally, heres the xml:

<?xml version="1.0" encoding="UTF-8"?>
<Anime>
    <record ID="BL1">
        <name>Bleach</name>
        <altname>Burichi</altname>
        <seasons>16</seasons>
        <episodes>366</episodes>
        <status>Finished</status>
        <sound>Dubbed</sound>
        <have>All</have>
        <left>-/-</left>
        <plot>Ichigo gets grim reaper powers, fights reapers, hollows and everything in between</plot>
        <connect>Bleach movies</connect>
        <image>images/bleach.jpg</image>
    </record>
</Anime>

any help would be greatly appreciated, thank you

Body:
Hi basically your understanding about the w3c dom xml element is wrong. "name:, "altname" etc are not attributes of "Animie" element. those are "child nodes" of "record" node. So first you have to fetch "record" node by iterating child nodes of "Animie" element. Then you can iterate through the child nodes of "record" element so that you can populate your Anime object.

Here's a simple implementation of your "xmlmx class that works. I had to use a map because you have ommitted the setter methods, this can be improved just trying to fix the xml concepts in your head.

Just replace your class with this.

package test;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import com.sun.org.apache.xerces.internal.dom.DeferredElementImpl;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class xmlmx {

    public static void main(String[] args) {
        ArrayList<Anime> list = new ArrayList<Anime>();
        try {
            File inputFile = new File("test.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();
            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());

            Node recordNode = null;
            NodeList childNodes = doc.getFirstChild().getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                if (childNodes.item(i).getNodeName().equals("record")) {
                    recordNode = childNodes.item(i);
                    break;
                }
            }
            System.out.println("----------------------------");

            Map<String, String> map = new HashMap<>();
            if (recordNode != null) {
                NodeList subNodes = recordNode.getChildNodes();
                for (int i = 0; i < subNodes.getLength(); i++) {
                    if (subNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                        map.put(subNodes.item(i).getNodeName(), subNodes.item(i).getTextContent());
                    }
                }
            }

            String id = ((DeferredElementImpl) recordNode).getAttribute("ID");
            list.add(new Anime(id,
                    map.get("name"),
                    map.get("altname"),
                    map.get("seasons"),
                    map.get("episodes"),
                    map.get("status"),
                    map.get("DS"),
                    map.get("have"),
                    map.get("left"),
                    map.get("plot"),
                    map.get("connect"),
                    map.get("image")));

            System.out.println(list.get(0));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


来源: stackexchange

ContentLicense: CC BY-SA 3.0

Title: Bash script part data in row with regex

Body:
Let say I have file test.txt and it look like this:

14.03.2016  12:01:58    0001039 28,427    0,200     28,427  28,437  28,427
14.03.2016  12:02:28    0001090 28,442    0,200     28,442  28,439  28,444
14.03.2016  12:02:58    0001139 28,469    0,230     28,459  28,469  28,504

I need to parse this with bash script so that I get for each row:

a = 14.03.2016
b = 12:01:58
c = 0001039
d = 0,200

I am not sure how to do this with grep.

Body:
AWK to the rescue

cat myscript.awk
BEGIN { RS = "\n" ; FS = " " }

{
      print "a = ", $1
      print "b = ", $2
      print "c = ", $3
      print "d = ", $5
}

awk -f myscript.awk inputfile

a =  14.03.2016
b =  12:01:58
c =  0001039
d =  0,200
a =  14.03.2016
b =  12:02:28
c =  0001090
d =  0,200
a =  14.03.2016
b =  12:02:58
c =  0001139
d =  0,230


问:
Inaccurate values of x-axis in plot
I am trying to plot a specific course (acceleration over time) using matplotlib. The plot works so far and is being shown (see image). J equals 35 and represents the derivative of acceleration over time (which in this case is a constant).

```<code>import numpy as np
import matplotlib.pyplot as plt

def limits_acc_course():
limits_acc_course.t1 = 0.14285714285714285
limits_acc_course.t2 = 0.14285714285714285 + 0.10714285714285715
limits_acc_course.t3 = 2*0.14285714285714285 + 0.10714285714285715
limits_acc_course.t4 = 2*0.14285714285714285 + 0.10714285714285715 + 0.5*0.24714285714285716

limits_acc_course()

t_end = 2*limits_acc_course.t4
t_1 = np.linspace(0, limits_acc_course.t1)
t_2 = np.linspace(limits_acc_course.t1, limits_acc_course.t2)
t_3 = np.linspace(limits_acc_course.t2, limits_acc_course.t3)
t_4 = np.linspace(limits_acc_course.t3, limits_acc_course.t4)

tk1 = np.array([])
tk2 = np.array([])
tk3 = np.array([])
tk4 = np.array([])

for value1 in t_1:
    tk1 = np.append(tk1, value1*j)

for value2 in t_2:
    tk2 = np.append(tk2, limits_acc_course.t1*j)

for value3 in t_3:
    tk3 = np.append(tk3, (limits_acc_course.t3-value3)*j)

for value4 in t_4:
    tk4 = np.append(tk4, value4*0)
    if value4 == (2*limits_acc_course.t4-limits_acc_course.t3)*j:
        break

t = np.concatenate((tk1, tk2, tk3, tk4), axis=0)
t_neg = (-1)*np.concatenate((tk1, tk2, tk3), axis=0)

t_final = np.concatenate((t, t_neg), axis=0)

t_range = np.linspace(0, t_end, t_final.size)

fig, t = plt.subplots()

t.plot(t_range, t_final)
t.get_xaxis().get_major_formatter().set_useOffset(False)
plt.show()
</code>```

The problem is that the x-coordinates in plot do not match the calculated values.

The x-values in the plot (see image)) should be:
0.142857142857       0.25
(Or at least with such an accuracy:0.1429)

The x-values in the plot are.
0.144777             0.295348

I have tried to turn off the offset and i have played with range from 100 to 2500 values for each part and I have tried to round the values but it didn't work either. Further I have tried using endpoint=False in creating the ranges t_1 to t_4.

By now I ran out of ideas.

enter image description here

答:
The plot is created in an axes which will extent over ~500 pixels on screen. The x axis shows 1.1 units. Hence you have 1.1/500 = 0.0022 units per pixel. The mouse cursor cannot know its position more accurate than 1 pixel. Hence the coordiante shown by the mouse cursor is accurate to ~±0.0022 units.

The observed coordinate (0.144777) deviates from the actual coordinate (0.142857142857) by 0.0019 units, which is well within the accuracy of the cursor.

Title: Inaccurate values of x-axis in plot

Body:
I am trying to plot a specific course (acceleration over time) using matplotlib. The plot works so far and is being shown (see image). J equals 35 and represents the derivative of acceleration over time (which in this case is a constant).

import numpy as np
import matplotlib.pyplot as plt

def limits_acc_course():
limits_acc_course.t1 = 0.14285714285714285
limits_acc_course.t2 = 0.14285714285714285 + 0.10714285714285715
limits_acc_course.t3 = 2*0.14285714285714285 + 0.10714285714285715
limits_acc_course.t4 = 2*0.14285714285714285 + 0.10714285714285715 + 0.5*0.24714285714285716

limits_acc_course()

t_end = 2*limits_acc_course.t4
t_1 = np.linspace(0, limits_acc_course.t1)
t_2 = np.linspace(limits_acc_course.t1, limits_acc_course.t2)
t_3 = np.linspace(limits_acc_course.t2, limits_acc_course.t3)
t_4 = np.linspace(limits_acc_course.t3, limits_acc_course.t4)

tk1 = np.array([])
tk2 = np.array([])
tk3 = np.array([])
tk4 = np.array([])

for value1 in t_1:
    tk1 = np.append(tk1, value1*j)

for value2 in t_2:
    tk2 = np.append(tk2, limits_acc_course.t1*j)

for value3 in t_3:
    tk3 = np.append(tk3, (limits_acc_course.t3-value3)*j)

for value4 in t_4:
    tk4 = np.append(tk4, value4*0)
    if value4 == (2*limits_acc_course.t4-limits_acc_course.t3)*j:
        break

t = np.concatenate((tk1, tk2, tk3, tk4), axis=0)
t_neg = (-1)*np.concatenate((tk1, tk2, tk3), axis=0)

t_final = np.concatenate((t, t_neg), axis=0)

t_range = np.linspace(0, t_end, t_final.size)

fig, t = plt.subplots()

t.plot(t_range, t_final)
t.get_xaxis().get_major_formatter().set_useOffset(False)
plt.show()

The problem is that the x-coordinates in plot do not match the calculated values.

The x-values in the plot (see image)) should be:
0.142857142857       0.25
(Or at least with such an accuracy:0.1429)

The x-values in the plot are.
0.144777             0.295348

I have tried to turn off the offset and i have played with range from 100 to 2500 values for each part and I have tried to round the values but it didn't work either. Further I have tried using endpoint=False in creating the ranges t_1 to t_4.

By now I ran out of ideas.

enter image description here


问:
MAC OS X Terminal force print f to ignore some variables
i am experiencing a Problem with the printf function on MAC OS X terminal.
I already declared a variable and when i call it, it works. The problem is the following:

On the text i have some variables that start with "$" but belong to another system. I just want them to be printed on the file i am creating exactly this way ($foo) without bash trying to read them as its own variables. The result i get is an empty string.

I have the following code (dummy code):

```<code>echo "Type the wished folder name followed by [ENTER]:"

read baseName

echo '' > ext_emconf.php

printf " $VARIABLE[$ANOTHERVARIABLE] = [
'title' => '%s - Templates'
];
" $basename> ext_emconf.php
</code>```

The result i get is this after the user gave for example "Amazon":

```<code>[] = [
    'title' => 'Amazon - Templates'
];
</code>```

Although i was expecting:

```<code>$VARIABLE[$ANOTHERVARIABLE] = [
    'title' => 'Amazon - Templates'
];
</code>```

Thanks in advance

答:
It is double-quotes in bash tries to expand them as variables, but it has no definition for it. Use single quotes or better use here strings to print nice multi line formatted strings. Here is a sample way to do with some variables.

```<code>foo=bar
bar=foo
basename=foobar

tee ext_emconf.php <<EOF
$foo[$bar] = [
'title' => '$basename- Templates'
];
EOF
</code>```

The above example uses tee to write both to stdout and to the file mentioned.  Also you can also just redirect stdout to /dev/null if you don't want it to be seen in console.

```<code>tee ext_emconf.php <<EOF > /dev/null
$foo[$bar] = [
'title' => '$basename- Templates'
];
EOF
</code>```

Body:
i am experiencing a Problem with the printf function on MAC OS X terminal.
I already declared a variable and when i call it, it works. The problem is the following:

On the text i have some variables that start with "$" but belong to another system. I just want them to be printed on the file i am creating exactly this way ($foo) without bash trying to read them as its own variables. The result i get is an empty string.

I have the following code (dummy code):

echo "Type the wished folder name followed by [ENTER]:"

read baseName

echo '' > ext_emconf.php

printf " $VARIABLE[$ANOTHERVARIABLE] = [
'title' => '%s - Templates'
];
" $basename> ext_emconf.php

The result i get is this after the user gave for example "Amazon":

[] = [
    'title' => 'Amazon - Templates'
];

Although i was expecting:

$VARIABLE[$ANOTHERVARIABLE] = [
    'title' => 'Amazon - Templates'
];

Thanks in advance

Body:
It is double-quotes in bash tries to expand them as variables, but it has no definition for it. Use single quotes or better use here strings to print nice multi line formatted strings. Here is a sample way to do with some variables.

foo=bar
bar=foo
basename=foobar

tee ext_emconf.php <<EOF
$foo[$bar] = [
'title' => '$basename- Templates'
];
EOF

The above example uses tee to write both to stdout and to the file mentioned.  Also you can also just redirect stdout to /dev/null if you don't want it to be seen in console.

tee ext_emconf.php <<EOF > /dev/null
$foo[$bar] = [
'title' => '$basename- Templates'
];
EOF


问:
How to extract and import Wikipedia pages?
I'm building a search engine, and to test it well, it needs more articles. Best source for them is Wikipedia.

I have searched for some dumps, but some are XML (which I am having troubles to import), some are not with content there.

So, how to get a dump, preferably in MySQL form. It has to be a non-English language.

Any idea?

答:
Here is a page explaining how to import Wikipedia to Solr.

Here is a step-by-step explanation of loading a Wikipedia dump into Mysql to run a local clone.

ContentLicense: CC BY-SA 2.5


问:
find missing entries - improve efficiency by eliminating nested loop
I would like to eliminate nested loop used to create data in m inside the function. The missing_entries() function is trying to identify and return values of col1 missing for groups in col2. Is there any alternative way to approach this problem in order to improve efficiency?

```<code>missing_entries <- function( data, x, y )
{
  # find missing entries in x for the group in y
  # by comparing other groups in y
  require( 'data.table' )

  # require class of data to be data.table
  stopifnot( "data.table" %in% class(data) )

  # the outer loop with i refers to each unique value of column y
  # the inner loop with j refers to all unique values of column y
  # except the value in i under current iteration
  uniq_col2 <- unique( data[, get(y) ] )
  m <- lapply( uniq_col2, function(i){
    lapply( setdiff( uniq_col2, i ), function( j ) {
      z <- setdiff( data[ get(y) == i, get(x)], data[ get(y) == j, get(x)])
      if( length(z) > 0 ){
        return( data.frame( v1 = z, v2 = j,
                            stringsAsFactors = FALSE ) )
      } else{
        return()
      }
    } )
  })

  # row bind
  m <- lapply( m, function(k) {
    if(!is.null(k)) {
      rbindlist(l = k)
    }})

  # collect only not null data
  m <- rbindlist( l = m[lapply(m, nrow) > 0] )
  colnames( m ) <- c( x, y )

  return( m )
}

# testing
test_data <- structure(list(cardnty = c("many", "many", "many", "many", "many", "many",
                                        "many", "many", "many", "many", "many", "many",
                                        "many", "many", "many", "many", "many", "many",
                                        "many", "many", "many", "many", "many", "many"),
                            col1 = c(2L, 4L, 3L, 13L, 5L, 6L, 7L, 17L, 9L, 4L, 3L,
                                           2L, 8L, 5L, 6L, 7L, 14L, 17L, 19L, 13L,
                                           9L, 12L, 11L, 20L),
                            N = c(599L, 43L, 111L, 12L, 11L, 5L, 4L,
                                  8L, 2L, 72L, 230L, 617L, 13L, 58L, 19L, 9L,
                                  5L, 3L, 2L, 1L, 11L, 1L, 1L, 1L),
                            col2 = c("cat", "cat", "cat", "cat", "cat",
                                   "cat", "cat", "cat", "cat", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog" )),
                       .Names = c("cardnty", "col1", "N", "col2"),
                       row.names = c(NA, -24L),
                       class = "data.frame")

require('data.table')
setDT(test_data)
results <- missing_entries(data = test_data, x = "col1", y = "col2")
setDF(results)

test_results <- structure(list(col1 = c(8L, 14L, 19L, 12L, 11L, 20L),
                               col2 = c("cat", "cat", "cat", "cat", "cat", "cat")),
                          .Names = c("col1", "col2"),
                          row.names = c(NA, -6L),
                          class = "data.frame")

identical( results, test_results)
# TRUE
</code>```

答:
As far as I have understood the question, the OP is seeking for missing combinations of col1 and col2 in test_data.

We can get all unique combinations of col1 and col2 using data.table's CJ() (cross join) or expand.grid() from base R. Then we can find the missing elements using an anti-join which removes the already existing combinations.

```<code>library(data.table)
setDT(test_data)[, CJ(col1 = col1, col2 = col2, unique = TRUE)][
  !test_data, on = .(col1, col2)]
</code>```

```<code>   col1 col2
1:    8  cat
2:   11  cat
3:   12  cat
4:   14  cat
5:   19  cat
6:   20  cat
</code>```

Body:
I would like to eliminate nested loop used to create data in m inside the function. The missing_entries() function is trying to identify and return values of col1 missing for groups in col2. Is there any alternative way to approach this problem in order to improve efficiency?

missing_entries <- function( data, x, y )
{
  # find missing entries in x for the group in y
  # by comparing other groups in y
  require( 'data.table' )

  # require class of data to be data.table
  stopifnot( "data.table" %in% class(data) )

  # the outer loop with i refers to each unique value of column y
  # the inner loop with j refers to all unique values of column y
  # except the value in i under current iteration
  uniq_col2 <- unique( data[, get(y) ] )
  m <- lapply( uniq_col2, function(i){
    lapply( setdiff( uniq_col2, i ), function( j ) {
      z <- setdiff( data[ get(y) == i, get(x)], data[ get(y) == j, get(x)])
      if( length(z) > 0 ){
        return( data.frame( v1 = z, v2 = j,
                            stringsAsFactors = FALSE ) )
      } else{
        return()
      }
    } )
  })

  # row bind
  m <- lapply( m, function(k) {
    if(!is.null(k)) {
      rbindlist(l = k)
    }})

  # collect only not null data
  m <- rbindlist( l = m[lapply(m, nrow) > 0] )
  colnames( m ) <- c( x, y )

  return( m )
}

# testing
test_data <- structure(list(cardnty = c("many", "many", "many", "many", "many", "many",
                                        "many", "many", "many", "many", "many", "many",
                                        "many", "many", "many", "many", "many", "many",
                                        "many", "many", "many", "many", "many", "many"),
                            col1 = c(2L, 4L, 3L, 13L, 5L, 6L, 7L, 17L, 9L, 4L, 3L,
                                           2L, 8L, 5L, 6L, 7L, 14L, 17L, 19L, 13L,
                                           9L, 12L, 11L, 20L),
                            N = c(599L, 43L, 111L, 12L, 11L, 5L, 4L,
                                  8L, 2L, 72L, 230L, 617L, 13L, 58L, 19L, 9L,
                                  5L, 3L, 2L, 1L, 11L, 1L, 1L, 1L),
                            col2 = c("cat", "cat", "cat", "cat", "cat",
                                   "cat", "cat", "cat", "cat", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog", "dog",
                                   "dog", "dog" )),
                       .Names = c("cardnty", "col1", "N", "col2"),
                       row.names = c(NA, -24L),
                       class = "data.frame")

require('data.table')
setDT(test_data)
results <- missing_entries(data = test_data, x = "col1", y = "col2")
setDF(results)

test_results <- structure(list(col1 = c(8L, 14L, 19L, 12L, 11L, 20L),
                               col2 = c("cat", "cat", "cat", "cat", "cat", "cat")),
                          .Names = c("col1", "col2"),
                          row.names = c(NA, -6L),
                          class = "data.frame")

identical( results, test_results)
# TRUE

Body:
As far as I have understood the question, the OP is seeking for missing combinations of col1 and col2 in test_data.

We can get all unique combinations of col1 and col2 using data.table's CJ() (cross join) or expand.grid() from base R. Then we can find the missing elements using an anti-join which removes the already existing combinations.

library(data.table)
setDT(test_data)[, CJ(col1 = col1, col2 = col2, unique = TRUE)][
  !test_data, on = .(col1, col2)]

   col1 col2
1:    8  cat
2:   11  cat
3:   12  cat
4:   14  cat
5:   19  cat
6:   20  cat


问:
mongoose driver not inserting data while in a loop
I am trying to load a bunch of data from a file into my mongoDB;
Using node: v8.9.1, mongoose: ^4.10.8, MongoDB v3.4.1 - running on Win 10.

only a couple elements from the document are being inserted. I suspect something in the schema, but I cant be sure, the console.log reflects the date 100% correctly.

This is my data:    /_mock_data/test.json

```<code>[{
    "AUTHOR":"Anthony Johnson",
    "TITLE":"A Little March",
    "COLLECTION_TITLE":"Classic Fairytails for Children",
    "FORMAT":"Trade Paperback",
    "PUBLISHER":"Randon House",
    "SKU":"10055",
    "SUGGESTED_GRADE_LEVEL":[6],
    "STATE_RATING":[{"NY":[1]}, {"PA":[1]}, {"VA":[3]}],
    "AUDIO_LINK":""
},...]
</code>```

Here's the code: app.js (reduced to what's relevant)

```<code>var express = require( 'express' );
var app = express();
var bodyParser = require( 'body-parser' );
var mongoose = require( 'mongoose' );
    mongoose.Promise = require( 'bluebird' );

app.use( bodyParser.json() );

var Catalog = require( './models/catalog' );

mongoose.connect('mongodb://localhost:27017/test', {server: { poolSize: 5 }});
var db = mongoose.connection;

app.get( '/api/loadCatalog', function( req, res ) {
    var catalog = require( './_mock_data/test.json' );

    for ( var i in catalog ) {

        Catalog.create( catalog[i] );
        console.log( catalog[i] );

    };

});

app.listen( 3000, function() {
    console.log( 'server started on port 3000' );
});
</code>```

/models/catalog

```<code>var mongoose = require( 'mongoose' );

// catalog schema
var catalogSchema = mongoose.Schema({
    author : {
        type: String
        ,required: false
    }
    ,title : {
        type: String
        ,required: false
    }
    ,collection_title : {
        type: String
        ,required: false
    }
    ,format : {
        type: String
        ,required: false
    }
    ,publisher : {
        type: String
        ,required: false
    }
    ,sku : {
        type: String
        ,required: false
    }
    ,suggested_grade_level : {
        type: Array
        ,required: false
    }
    ,state_rating : {
        type: [mongoose.Schema.Types.Mixed]
        ,required: false
    }
    ,audio_link : {
        type: String
        ,required: false
    }
});

var Catalog = module.exports = mongoose.model( 'Catalog', catalogSchema );

// Get Items
module.exports.getItems = function( callback, limit ) {
    Catalog.find( callback ).limit( limit );
};

// Add Item
module.exports.addItem = function( item, callback ) {
    Catalog.create( item, callback );
};
</code>```

and the errors I'm getting -

```<code>Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in Anthony Johnson
Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in A Little March
Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in Classic Fairytails for Children
Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in Trade Paperback
Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in Randon House
Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in 10055
Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in 6
</code>```

So the data I get looks like this

```<code>{
    "_id" : ObjectId("5a28fa8503511d1d14054c92"),
    "state_rating" : [ ],
    "suggested_grade_level" : [ ],
    "__v" : 0
}
</code>```

All the string data errored and the object data went in, The "actual" data is an array of 1000's, and this is a one time import, yes I could use mongo cli to do the import, but I am only developing locally, Eventually I'll be shoving this data to an Atlas account, and as far as I can tell, this will be the way to get the data in place.

the console.log inside the loop gives me the actual data

```<code>Anthony Johnson
A Little March
Classic Fairytails for Children
Trade Paperback
Randon House
10055
[ 6 ]
[ { NY: [ 1 ] }, { PA: [ 1 ] }, { VA: [ 3 ] } ]
</code>```

I'm pretty sure Im missing something basic about using the model to use the schema in this way... my "get" and "add" work fine...maybe I should do the loop in the model, not the app...

答:
You need to make a small change that loop,

```<code>   for ( var i in catalog ) {
    var key = convertStringToCamelCase(i);
    Catalog.create( {key : catalog[i]} );
    console.log( {key : catalog[i]} );

    };
</code>```

To convert the key to lower and camel case to match with the schema, you can create a small helper function like this

```<code>function convertStringToCamelCase(str_original){
    var str = str_original.toLowerCase();
    return str.split(' ').map(function(item, index){
        return index !== 0
            ? item.charAt(0).toUpperCase() + item.substr(1)
            : item.charAt(0).toLowerCase() + item.substr(1);
    }).join('');
</code>```

}

Body:
I am trying to load a bunch of data from a file into my mongoDB;
Using node: v8.9.1, mongoose: ^4.10.8, MongoDB v3.4.1 - running on Win 10.

only a couple elements from the document are being inserted. I suspect something in the schema, but I cant be sure, the console.log reflects the date 100% correctly.

This is my data:    /_mock_data/test.json

[{
    "AUTHOR":"Anthony Johnson",
    "TITLE":"A Little March",
    "COLLECTION_TITLE":"Classic Fairytails for Children",
    "FORMAT":"Trade Paperback",
    "PUBLISHER":"Randon House",
    "SKU":"10055",
    "SUGGESTED_GRADE_LEVEL":[6],
    "STATE_RATING":[{"NY":[1]}, {"PA":[1]}, {"VA":[3]}],
    "AUDIO_LINK":""
},...]

Here's the code: app.js (reduced to what's relevant)

var express = require( 'express' );
var app = express();
var bodyParser = require( 'body-parser' );
var mongoose = require( 'mongoose' );
    mongoose.Promise = require( 'bluebird' );

app.use( bodyParser.json() );

var Catalog = require( './models/catalog' );

mongoose.connect('mongodb://localhost:27017/test', {server: { poolSize: 5 }});
var db = mongoose.connection;

app.get( '/api/loadCatalog', function( req, res ) {
    var catalog = require( './_mock_data/test.json' );

    for ( var i in catalog ) {

        Catalog.create( catalog[i] );
        console.log( catalog[i] );

    };

});

app.listen( 3000, function() {
    console.log( 'server started on port 3000' );
});

/models/catalog

var mongoose = require( 'mongoose' );

// catalog schema
var catalogSchema = mongoose.Schema({
    author : {
        type: String
        ,required: false
    }
    ,title : {
        type: String
        ,required: false
    }
    ,collection_title : {
        type: String
        ,required: false
    }
    ,format : {
        type: String
        ,required: false
    }
    ,publisher : {
        type: String
        ,required: false
    }
    ,sku : {
        type: String
        ,required: false
    }
    ,suggested_grade_level : {
        type: Array
        ,required: false
    }
    ,state_rating : {
        type: [mongoose.Schema.Types.Mixed]
        ,required: false
    }
    ,audio_link : {
        type: String
        ,required: false
    }
});

var Catalog = module.exports = mongoose.model( 'Catalog', catalogSchema );

// Get Items
module.exports.getItems = function( callback, limit ) {
    Catalog.find( callback ).limit( limit );
};

// Add Item
module.exports.addItem = function( item, callback ) {
    Catalog.create( item, callback );
};

and the errors I'm getting -

Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in Anthony Johnson
Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in A Little March
Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in Classic Fairytails for Children
Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in Trade Paperback
Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in Randon House
Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in 10055
Unhandled rejection TypeError: Cannot use 'in' operator to search for '_id' in 6

So the data I get looks like this

{
    "_id" : ObjectId("5a28fa8503511d1d14054c92"),
    "state_rating" : [ ],
    "suggested_grade_level" : [ ],
    "__v" : 0
}

All the string data errored and the object data went in, The "actual" data is an array of 1000's, and this is a one time import, yes I could use mongo cli to do the import, but I am only developing locally, Eventually I'll be shoving this data to an Atlas account, and as far as I can tell, this will be the way to get the data in place.

the console.log inside the loop gives me the actual data

Anthony Johnson
A Little March
Classic Fairytails for Children
Trade Paperback
Randon House
10055
[ 6 ]
[ { NY: [ 1 ] }, { PA: [ 1 ] }, { VA: [ 3 ] } ]

I'm pretty sure Im missing something basic about using the model to use the schema in this way... my "get" and "add" work fine...maybe I should do the loop in the model, not the app...

Body:
You need to make a small change that loop,

   for ( var i in catalog ) {
    var key = convertStringToCamelCase(i);
    Catalog.create( {key : catalog[i]} );
    console.log( {key : catalog[i]} );

    };

To convert the key to lower and camel case to match with the schema, you can create a small helper function like this

function convertStringToCamelCase(str_original){
    var str = str_original.toLowerCase();
    return str.split(' ').map(function(item, index){
        return index !== 0
            ? item.charAt(0).toUpperCase() + item.substr(1)
            : item.charAt(0).toLowerCase() + item.substr(1);
    }).join('');

}


问:
React Native API implementations causing errors
I'm absolutely new in React Native.

So I start learn to create a simple application.

I want to use Zomato API for my application.

Everything works fine until I try to use an API which causing this error :

I really need help for this, so I can continue to learn.

Any help would be really appreciated. Thank you.

Here are my Homescreen and Api files :

MainViewScreen.js

import React, { Component } from 'react'
import { Picker, TouchableOpacity, View, ListView, Text } from 'react-native'
import { connect } from 'react-redux'
import { Icon, Header } from 'react-native-elements'
import { Button, Container, Content, Footer, Title} from 'native-base'
import API from '../Services/Api'

// For empty lists
// import AlertMessage from '../Components/AlertMessage'

// Styles
import styles from './Styles/MainRestoStyles'

class MainRestoScreen extends React.Component {
  constructor (props) {
    super(props)

    /* ***********************************************************
    * STEP 1
    * This is an array of objects with the properties you desire
    * Usually this should come from Redux mapStateToProps
    *************************************************************/
    const dataObjects = []
    /* ***********************************************************
    * STEP 2
    * Teach datasource how to detect if rows are different
    * Make this function fast!  Perhaps something like:
    *   (r1, r2) => r1.id !== r2.id}
    *   The same goes for sectionHeaderHasChanged
    *************************************************************/
    const rowHasChanged = (r1, r2) => r1 !== r2
    const sectionHeaderHasChanged = (s1, s2) => s1 !== s2

    // DataSource configured
    this.ds = new ListView.DataSource({rowHasChanged, sectionHeaderHasChanged})

    // Datasource is always in state
    this.state = {
      dataSource: this.ds.cloneWithRowsAndSections(dataObjects)
    }

    this.stateCity = { city: "ny" }

    this.getRestoCategories
  }

  /* ***********************************************************
  * STEP 3
  * `renderRow` function -How each cell/row should be rendered
  * It's our best practice to place a single component here:
  *
  * e.g.
    return <MyCustomCell title={rowData.title} description={rowData.description} />
  *************************************************************/
  renderRow (rowData, sectionID) {
    // You can condition on sectionID (key as string), for different cells
    // in different sections
    return (
      <TouchableOpacity style={styles.row}>
        <Text style={styles.boldLabel}>Section {sectionID} - {rowData.title}</Text>
        <Text style={styles.label}>{rowData.description}</Text>
      </TouchableOpacity>
    )
  }

  /* ***********************************************************
  * STEP 4
  * If your datasource is driven by Redux, you'll need to
  * reset it when new data arrives.
  * DO NOT! place `cloneWithRowsAndSections` inside of render, since render
  * is called very often, and should remain fast!  Just replace
  * state's datasource on newProps.
  *
  * e.g.
    componentWillReceiveProps (newProps) {
      if (newProps.someData) {
        this.setState(prevState => ({
          dataSource: prevState.dataSource.cloneWithRowsAndSections(newProps.someData)
        }))
      }
    }
  *************************************************************/

  // Used for friendly AlertMessage
  // returns true if the dataSource is empty
  noRowData () {
    return this.state.dataSource.getRowCount() === 0
  }

  render () {
    return (
      <Container>
        <View style={styles.toolbar}>
          <Text style={styles.toolbarButton}></Text>
          <Icon name='bowl' type='entypo' size={40} color='white'/>
          <Picker
            style={styles.dropdown}
            selectedValue={this.state.city}
            onValueChange={(city) => this.setState({city})}>
            <Picker.Item label="New York City" value="ny" />
            <Picker.Item label="New Jersey" value="nj" />
            <Picker.Item label="Los Angeles" value="la" />
            <Picker.Item label="Oklahoma City" value="oc" />
          </Picker>
        </View>
        <View  style={styles.viewDropdown}>

        </View>
        <Content>
          <ListView
            contentContainerStyle={styles.listContent}
            dataSource={this.state.dataSource}
            onLayout={this.onLayout}
            renderRow={this.renderRow}
            enableEmptySections
          />
        </Content>

          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='location' type='entypo' color='white' size={30}/>
          </Button>
          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='heart' type='foundation' color='white' size={30}/>
          </Button>
          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='bell' type='entypo' color='white' size={30}/>
          </Button>

      </Container>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    // ...redux state to props here
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
  }
}

getRestoCategories = async () => {
  const api = API.create()
  const categories = await api.getCategories()
  this.setState({
  datasource: this.ds.cloneWithRowsAndSections[categories.data]
  })
}

export default connect(mapStateToProps, mapDispatchToProps)(MainRestoScreen)```
</div>
</div>
</p>

<p>Api.js</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// a library to wrap and simplify api calls
import apisauce from 'apisauce'

// our "constructor"
const create = (baseURL = 'https://developers.zomato.com/api/v2.1/') => {
  // ------
  // STEP 1
  // ------
  //
  // Create and configure an apisauce-based api object.
  //
  const api = apisauce.create({
    // base URL is read from the "constructor"
    baseURL,
    // here are some default headers
    headers: {
      'Cache-Control': 'no-cache'
    },
    // 10 second timeout...
    timeout: 10000
  })

  // ------
  // STEP 2
  // ------
  //
  // Define some functions that call the api.  The goal is to provide
  // a thin wrapper of the api layer providing nicer feeling functions
  // rather than "get", "post" and friends.
  //
  // I generally don't like wrapping the output at this level because
  // sometimes specific actions need to be take on `403` or `401`, etc.
  //
  // Since we can't hide from that, we embrace it by getting out of the
  // way at this level.
  //
  const getCategories = () => api.get('categories')

  // ------
  // STEP 3
  // ------
  //
  // Return back a collection of functions that we would consider our
  // interface.  Most of the time it'll be just the list of all the
  // methods in step 2.
  //
  // Notice we're not returning back the `api` created in step 1?  That's
  // because it is scoped privately.  This is one way to create truly
  // private scoped goodies in JavaScript.
  //
  return {
    // a list of the API functions from step 2
    getCategories
  }
}

// let's return back our create method as the default.
export default {
  create
}</code>```

答:
so first of all, you should understand the component lifecycle of React:

You are trying to call the api in the constructor. Best practice would be to call the api on ComponentDidMount() Method.
Currently your calling your api in the constructor, when the initialState isn’t set.

What i also see is that the error is thrown from redux-saga. Did you integrate redux-saga in your project? If so, you should let redux-saga handle your side effects, like async calls.

Could you provide your full code of the Project?

Where do you configure your store?

And did you probably add redux-saga as middleware to redux?

Greetings

Body:
I'm absolutely new in React Native.

So I start learn to create a simple application.

I want to use Zomato API for my application.

Everything works fine until I try to use an API which causing this error :

I really need help for this, so I can continue to learn.

Any help would be really appreciated. Thank you.

Here are my Homescreen and Api files :

MainViewScreen.js

import React, { Component } from 'react'
import { Picker, TouchableOpacity, View, ListView, Text } from 'react-native'
import { connect } from 'react-redux'
import { Icon, Header } from 'react-native-elements'
import { Button, Container, Content, Footer, Title} from 'native-base'
import API from '../Services/Api'

// For empty lists
// import AlertMessage from '../Components/AlertMessage'

// Styles
import styles from './Styles/MainRestoStyles'

class MainRestoScreen extends React.Component {
  constructor (props) {
    super(props)

    /* ***********************************************************
    * STEP 1
    * This is an array of objects with the properties you desire
    * Usually this should come from Redux mapStateToProps
    *************************************************************/
    const dataObjects = []
    /* ***********************************************************
    * STEP 2
    * Teach datasource how to detect if rows are different
    * Make this function fast!  Perhaps something like:
    *   (r1, r2) => r1.id !== r2.id}
    *   The same goes for sectionHeaderHasChanged
    *************************************************************/
    const rowHasChanged = (r1, r2) => r1 !== r2
    const sectionHeaderHasChanged = (s1, s2) => s1 !== s2

    // DataSource configured
    this.ds = new ListView.DataSource({rowHasChanged, sectionHeaderHasChanged})

    // Datasource is always in state
    this.state = {
      dataSource: this.ds.cloneWithRowsAndSections(dataObjects)
    }

    this.stateCity = { city: "ny" }

    this.getRestoCategories
  }

  /* ***********************************************************
  * STEP 3
  * `renderRow` function -How each cell/row should be rendered
  * It's our best practice to place a single component here:
  *
  * e.g.
    return <MyCustomCell title={rowData.title} description={rowData.description} />
  *************************************************************/
  renderRow (rowData, sectionID) {
    // You can condition on sectionID (key as string), for different cells
    // in different sections
    return (
      <TouchableOpacity style={styles.row}>
        <Text style={styles.boldLabel}>Section {sectionID} - {rowData.title}</Text>
        <Text style={styles.label}>{rowData.description}</Text>
      </TouchableOpacity>
    )
  }

  /* ***********************************************************
  * STEP 4
  * If your datasource is driven by Redux, you'll need to
  * reset it when new data arrives.
  * DO NOT! place `cloneWithRowsAndSections` inside of render, since render
  * is called very often, and should remain fast!  Just replace
  * state's datasource on newProps.
  *
  * e.g.
    componentWillReceiveProps (newProps) {
      if (newProps.someData) {
        this.setState(prevState => ({
          dataSource: prevState.dataSource.cloneWithRowsAndSections(newProps.someData)
        }))
      }
    }
  *************************************************************/

  // Used for friendly AlertMessage
  // returns true if the dataSource is empty
  noRowData () {
    return this.state.dataSource.getRowCount() === 0
  }

  render () {
    return (
      <Container>
        <View style={styles.toolbar}>
          <Text style={styles.toolbarButton}></Text>
          <Icon name='bowl' type='entypo' size={40} color='white'/>
          <Picker
            style={styles.dropdown}
            selectedValue={this.state.city}
            onValueChange={(city) => this.setState({city})}>
            <Picker.Item label="New York City" value="ny" />
            <Picker.Item label="New Jersey" value="nj" />
            <Picker.Item label="Los Angeles" value="la" />
            <Picker.Item label="Oklahoma City" value="oc" />
          </Picker>
        </View>
        <View  style={styles.viewDropdown}>

        </View>
        <Content>
          <ListView
            contentContainerStyle={styles.listContent}
            dataSource={this.state.dataSource}
            onLayout={this.onLayout}
            renderRow={this.renderRow}
            enableEmptySections
          />
        </Content>

          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='location' type='entypo' color='white' size={30}/>
          </Button>
          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='heart' type='foundation' color='white' size={30}/>
          </Button>
          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='bell' type='entypo' color='white' size={30}/>
          </Button>

      </Container>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    // ...redux state to props here
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
  }
}

getRestoCategories = async () => {
  const api = API.create()
  const categories = await api.getCategories()
  this.setState({
  datasource: this.ds.cloneWithRowsAndSections[categories.data]
  })
}

export default connect(mapStateToProps, mapDispatchToProps)(MainRestoScreen)

Api.js

// a library to wrap and simplify api calls
import apisauce from 'apisauce'

// our "constructor"
const create = (baseURL = 'https://developers.zomato.com/api/v2.1/') => {
  // ------
  // STEP 1
  // ------
  //
  // Create and configure an apisauce-based api object.
  //
  const api = apisauce.create({
    // base URL is read from the "constructor"
    baseURL,
    // here are some default headers
    headers: {
      'Cache-Control': 'no-cache'
    },
    // 10 second timeout...
    timeout: 10000
  })

  // ------
  // STEP 2
  // ------
  //
  // Define some functions that call the api.  The goal is to provide
  // a thin wrapper of the api layer providing nicer feeling functions
  // rather than "get", "post" and friends.
  //
  // I generally don't like wrapping the output at this level because
  // sometimes specific actions need to be take on `403` or `401`, etc.
  //
  // Since we can't hide from that, we embrace it by getting out of the
  // way at this level.
  //
  const getCategories = () => api.get('categories')

  // ------
  // STEP 3
  // ------
  //
  // Return back a collection of functions that we would consider our
  // interface.  Most of the time it'll be just the list of all the
  // methods in step 2.
  //
  // Notice we're not returning back the `api` created in step 1?  That's
  // because it is scoped privately.  This is one way to create truly
  // private scoped goodies in JavaScript.
  //
  return {
    // a list of the API functions from step 2
    getCategories
  }
}

// let's return back our create method as the default.
export default {
  create
}


问:
Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory
I have a project on Laravel 5 and I work with it at the office and at home too. It works fine, but recently at home it stopped working. Laravel show me two ErrorException

```<code>file_put_contents(G:\project\storage\framework\views/751d8a0fd8a7d4138c09ceb6a34bb377aa2d6265.php):
failed to open stream: No such file or directory
</code>```

and

```<code>file_put_contents(G:\project\storage\framework/sessions/aIXycR4LIAUBVIqZu0T590paOMIpV8vfZGIroEp0):
failed to open stream: No such file or directory
</code>```

I'm searching problem decision with Google and find information about correct rights. All advice is about Linux, but I'am work in Windows at the office and at home too.

When I try to clear application cache and view cache, artisan talk to me - ...cleared. But cache data and views are present in storage.

How can I fix this problem?

答:
The best way to solve this problem is, go to directory laravel/bootstrap/cache and delete config.php file. or you can rename it as well like config.php.old
And your problem will be fixed.

ContentLicense: CC BY-SA 4.0

Body:
I have a project on Laravel 5 and I work with it at the office and at home too. It works fine, but recently at home it stopped working. Laravel show me two ErrorException

file_put_contents(G:\project\storage\framework\views/751d8a0fd8a7d4138c09ceb6a34bb377aa2d6265.php):
failed to open stream: No such file or directory

and

file_put_contents(G:\project\storage\framework/sessions/aIXycR4LIAUBVIqZu0T590paOMIpV8vfZGIroEp0):
failed to open stream: No such file or directory

I'm searching problem decision with Google and find information about correct rights. All advice is about Linux, but I'am work in Windows at the office and at home too.

When I try to clear application cache and view cache, artisan talk to me - ...cleared. But cache data and views are present in storage.

How can I fix this problem?


答:
Assuming that the first line of your input file is stored in variable line, you can do

```<code>arr=($line)
</code>```

to make an array consisting of the individual words in the line.

```<code>a=${arr[0]}
</code>```

would then assign the first word to variable a.

Title: Bash script part data in row with regex

Body:
Assuming that the first line of your input file is stored in variable line, you can do

arr=($line)

to make an array consisting of the individual words in the line.

a=${arr[0]}

would then assign the first word to variable a.


答:
Bash has this pretty much built in.</p>

```<code>while read -r a b c _ d rest; do
    : things with "$a", "$b", "$c", and "$d"
done <inputfile
</code>```

Title: Bash script part data in row with regex

Body:
Bash has this pretty much built in.

while read -r a b c _ d rest; do
    : things with "$a", "$b", "$c", and "$d"
done <inputfile


问:
Infinity loop in io.popen function in lua
I want to execute following code infinitely.
However, if two devices are connected, the infinity loop is freeze at second scanning section(The second scanning section means that infinity loop begins second time and scan command is executed). Why this problem appears?

```<code>while true do
print("Hi")
s = io.popen("iw wlan0 scan")
s:close()
print("Done")

dis = io.popen("iw wlan0 disconnect")
dis:close()

c = io.popen("iw wlan0 connect Name")
c:close()
print("Goes to Scan")
end
</code>```

Also, If I type commands in command line by hand(scan -> disconnect -> connect -> scan), then scan print result is repeat from 5 to 6 times automatically at second scanning. (When I execute scan command, the printed result is SYNC - End of SCAN, restore to 20MHz channel 32, Total BSS[02] bImprovedScan ............. Resume for bImprovedScan, SCAN_PENDING ............... and this printed text is repeat from 5 to 6 times). Is this situation is related to this problem?

答:
I don't know what the iw command does, but using a pipe without reading anything from it and closing it immediately after opening it opens the possibility that the program never executes.

I suggest using os.execute instead of io.popen:

```<code>while true do
   print("Hi")
   os.execute("iw wlan0 scan; iw wlan0 disconnect; iw wlan0 connect Name")
   print("Goes to Scan")
end
</code>```

Body:
I want to execute following code infinitely.
However, if two devices are connected, the infinity loop is freeze at second scanning section(The second scanning section means that infinity loop begins second time and scan command is executed). Why this problem appears?

while true do
print("Hi")
s = io.popen("iw wlan0 scan")
s:close()
print("Done")

dis = io.popen("iw wlan0 disconnect")
dis:close()

c = io.popen("iw wlan0 connect Name")
c:close()
print("Goes to Scan")
end

Also, If I type commands in command line by hand(scan -> disconnect -> connect -> scan), then scan print result is repeat from 5 to 6 times automatically at second scanning. (When I execute scan command, the printed result is SYNC - End of SCAN, restore to 20MHz channel 32, Total BSS[02] bImprovedScan ............. Resume for bImprovedScan, SCAN_PENDING ............... and this printed text is repeat from 5 to 6 times). Is this situation is related to this problem?

Body:
I don't know what the iw command does, but using a pipe without reading anything from it and closing it immediately after opening it opens the possibility that the program never executes.

I suggest using os.execute instead of io.popen:

while true do
   print("Hi")
   os.execute("iw wlan0 scan; iw wlan0 disconnect; iw wlan0 connect Name")
   print("Goes to Scan")
end


问:
Finding non-numeric values in varchar column
Requirement :

Generic query/function to check if the value provided in a varchar column in a table is actually a number & the precision does not exceed the allowed precision.

Available values:

Table_Name, Column_Name, Allowed Precision, Allowed Scale

General advise would be to create a function & use to_number() to validate the value however it won't validate the allowed length (precision-scale).

My solution:

Validate Number using Regexp NOT REGEXP_LIKE(COLUMN_NAME, '^-?[0-9.]+$')

Validate Length of left component (before decimal) (I have no idea what's its actually called) because for scale, oracle automatically rounds off if required. As the actual column is varchar i will use substr, instr to find the component on the left of decimal point.

As above Regexp allows number like 123...123124..55 I will also validate the number of decimal points. [If > 1 then error]

Query to find invalid number's:

```<code>Select * From Table_Name
Where
(NOT REGEXP_LIKE(COLUMN_NAME, '^-?[0-9.]+$')
OR
Function_To_Fetch_Left_Component(COLUMN_NAME) > (Precision-Scale)
/* Can use regexp_substr now but i already had a function for that */
OR
LENGTH(Column_Name) - LENGTH(REPLACE(Column_Name,'.','')) > 1
/* Can use regexp_count aswell*/)
</code>```

I was happy & satisfied with my solution until a column with only '.' value escaped my check and I saw the limitation of my checks. Although adding another check to validate this as well will solve my problem the solution as a whole looks very inefficient to me.

I will really appreciate a better solution [in any way].

Thanks in advance.

答:
The precision means that you want at most allowed_precision digits in the number (strictly speaking, not counting leading zeros, but I'll ignore that).  The scale means that at most allowed_scale can be after the decimal point.

This suggests a regular expression such as:

```<code>[-]?[0-9]{1,<before>}[.]?[0-9]{0,<after>}
</code>```

You can construct the regular expression:

```<code>NOT REGEXP_LIKE(COLUMN_NAME,
                REPLACE(REPLACE('[-]?[0-9]{1,<before>}[.]?[0-9]{0,<after>}', '<before>', allowed_precision - allowed_scale
                               ), '<after>', allowed_scale)
</code>```

Now, variable regular expressions are highly inefficient.  You can do the logic using like and other functions as well.  I think the conditions are:

```<code>(column_name not like '%.%.%' and
 column_name not like '_%-%' and
 translate(column_name, '0123456789-.x', 'x') is null and
 length(translate(column_name, '-.x', 'x') <= allowed_precision and
 length(translate(column_name, '-.x', 'x') >= 1 and
 instr(translate(column_name, '-.x', 'x'), '.') <= allowed_precision - allowed_scale
)
</code>```

Body:
Requirement :

Generic query/function to check if the value provided in a varchar column in a table is actually a number & the precision does not exceed the allowed precision.

Available values:

Table_Name, Column_Name, Allowed Precision, Allowed Scale

General advise would be to create a function & use to_number() to validate the value however it won't validate the allowed length (precision-scale).

My solution:

Validate Number using Regexp NOT REGEXP_LIKE(COLUMN_NAME, '^-?[0-9.]+$')

Validate Length of left component (before decimal) (I have no idea what's its actually called) because for scale, oracle automatically rounds off if required. As the actual column is varchar i will use substr, instr to find the component on the left of decimal point.

As above Regexp allows number like 123...123124..55 I will also validate the number of decimal points. [If > 1 then error]

Query to find invalid number's:

Select * From Table_Name
Where
(NOT REGEXP_LIKE(COLUMN_NAME, '^-?[0-9.]+$')
OR
Function_To_Fetch_Left_Component(COLUMN_NAME) > (Precision-Scale)
/* Can use regexp_substr now but i already had a function for that */
OR
LENGTH(Column_Name) - LENGTH(REPLACE(Column_Name,'.','')) > 1
/* Can use regexp_count aswell*/)

I was happy & satisfied with my solution until a column with only '.' value escaped my check and I saw the limitation of my checks. Although adding another check to validate this as well will solve my problem the solution as a whole looks very inefficient to me.

I will really appreciate a better solution [in any way].

Thanks in advance.

Body:
The precision means that you want at most allowed_precision digits in the number (strictly speaking, not counting leading zeros, but I'll ignore that).  The scale means that at most allowed_scale can be after the decimal point.

This suggests a regular expression such as:

[-]?[0-9]{1,<before>}[.]?[0-9]{0,<after>}

You can construct the regular expression:

NOT REGEXP_LIKE(COLUMN_NAME,
                REPLACE(REPLACE('[-]?[0-9]{1,<before>}[.]?[0-9]{0,<after>}', '<before>', allowed_precision - allowed_scale
                               ), '<after>', allowed_scale)

Now, variable regular expressions are highly inefficient.  You can do the logic using like and other functions as well.  I think the conditions are:

(column_name not like '%.%.%' and
 column_name not like '_%-%' and
 translate(column_name, '0123456789-.x', 'x') is null and
 length(translate(column_name, '-.x', 'x') <= allowed_precision and
 length(translate(column_name, '-.x', 'x') >= 1 and
 instr(translate(column_name, '-.x', 'x'), '.') <= allowed_precision - allowed_scale
)


问:
rstrip on python behaving awkwardly: 'HelloWorld'.rstrip('World') deletes everything after 'He'

I had started learning python recently, and I have encountered a awkward behavior with rstrip.

My understanding is that the str.rstrip() will delete all characters as soon as it encounters one of the character it took in an argument.

```<code>>>> a = 'HelloWorld'
>>> a.rstrip('l')
'HelloWorld'
>>> a = 'HelloWorld'
>>> a.rstrip('World')
'He'
</code>```

I'm totally confused by the result I've got.

Shouldn't the first code supposed be producing 'He' instead?

答:
string.rstrip returns a copy of the string with trailing characters removed.

So, a.rstrip('l') won't change anything as 'l' isn't at the end.

But, a.rstrip('World') will, as the string 'World' exists at the end, all characters in string 'World' are removed from the text.

Check this for a further read : http://python-reference.readthedocs.io/en/latest/docs/str/rstrip.html

Body:
I had started learning python recently, and I have encountered a awkward behavior with rstrip.

My understanding is that the str.rstrip() will delete all characters as soon as it encounters one of the character it took in an argument.

>>> a = 'HelloWorld'
>>> a.rstrip('l')
'HelloWorld'
>>> a = 'HelloWorld'
>>> a.rstrip('World')
'He'

I'm totally confused by the result I've got.

Shouldn't the first code supposed be producing 'He' instead?


问:
Getting this message in Xcode "XPC connection interrupted"

I am Using Xcode 9.1 with objective-c Project.

When I Normally run my code it's working fine,

But when I start debugging with breakpoints.
at last when I release all breakpoints always get this message "XPC connection interrupted", and application UI in the simulator is stacked.

答:
Please try this, the problem lied in the storyboard for me as well. I created a new project and laid out the views and everything seemed to be working fine. I found these couple lines in the storyboard source (right click on storyboard and select view as -> source code) which weren't common between the working version and the broken version:

```<code>  <keyCommands>
     <keyCommand/>
  </keyCommands>
</code>```

I have no idea what those lines are supposed to do, or how they crept into my storyboard file, but they were what was crashing the app so hard that the phone had to restart. I removed those lines from my main project and everything worked again.

Body:
Please try this, the problem lied in the storyboard for me as well. I created a new project and laid out the views and everything seemed to be working fine. I found these couple lines in the storyboard source (right click on storyboard and select view as -> source code) which weren't common between the working version and the broken version:

  <keyCommands>
     <keyCommand/>
  </keyCommands>

I have no idea what those lines are supposed to do, or how they crept into my storyboard file, but they were what was crashing the app so hard that the phone had to restart. I removed those lines from my main project and everything worked again.


问:
Dual-Core Hyperthreading: Should I use 4 threads or 3 or 2?
If you're spawning multiple threads (or processes) concurrently, is it better to spawn as many as the number of physical processors or the number of logical processors, assuming the task is CPU-bound? Or is it better to do something in between (say, 3 threads)?

Does the performance depend on the kind of instructions that are getting executed (say, would non-local memory access be much different from cache hits)? If so, in which cases is it better to take advantage of hyperthreading?

Update:

The reason I'm asking is, I remember reading somewhere that if you have as many tasks as the number of virtual processors, tasks on the same physical core can sometimes starve some CPU resources and prevent each other from getting as many resources as needed, possibly decreasing performance. That's why I'm wondering if having as many threads as virtual cores is a good idea.

答:
The performance depends on a huge variety of factors.  Most tasks are not strictly CPU bound, since even if all of the data is in memory it is usually not on-board in the processor cache.  I have seen examples (like this one) where memory access patterns can dramatically change the performance profile of a given 'parallel' process.

In short, there is no perfect number for all situations.


问:
Angular JS UI-Route Navigation
I'm trying to make a simple routing using UI-Route in Angular,but when I'm  typing url in browser with # like this http://localhost:8080/#/stateone it adds some weird symbols to it like this http://localhost:8080/#!#%2Fstateone. Can anybody explain me what`s wrong with that?

Here`s my code in app.js file :

```<code>angular
    .module('myApp', ["ngMaterial", "ui.router"])
    .config(function($mdThemingProvider, $stateProvider) {
    $mdThemingProvider.theme('default')
    .primaryPalette('teal')
    .accentPalette('orange');

    $stateProvider
        .state('stateone' , {
        url: '/stateone',
        template: '<h1>State One</h1>'
    })

    .state('statetwo', {
        url: '/statetwo',
        template: '<h1>State Two</h1>'
    });
});
</code>```

Template`s file code:

```<code><ui-view></ui-view>
</code>```

答:
You can encode your urls in AngularJS and avoid the hash-bang from your overall app by enabling html5mode mode by adding this simple line in your config block of app.js

$locationProvider.html5Mode(true);

Reference link: AngularJS: how to enable $locationProvider.html5Mode with deeplinking

Title: Angular JS UI-Route Navigation

Body:
I'm trying to make a simple routing using UI-Route in Angular,but when I'm  typing url in browser with # like this http://localhost:8080/#/stateone it adds some weird symbols to it like this http://localhost:8080/#!#%2Fstateone. Can anybody explain me what`s wrong with that?

Here`s my code in app.js file :

angular
    .module('myApp', ["ngMaterial", "ui.router"])
    .config(function($mdThemingProvider, $stateProvider) {
    $mdThemingProvider.theme('default')
    .primaryPalette('teal')
    .accentPalette('orange');

    $stateProvider
        .state('stateone' , {
        url: '/stateone',
        template: '
State One
'
    })

    .state('statetwo', {
        url: '/statetwo',
        template: '
State Two
'
    });
});

Template`s file code:

<ui-view></ui-view>


问:
Read FTP files without local folder in SSIS package
I'm using this link as a reference for reading a file from FTP folder. But this tutorial says that the files in the FTP folder should be loaded in a local folder and only then it can be used for processing using other tasks in SSIS.

My question is, Is it possible to read a file directly from the FTP folder without storing them in the local folder and do the ETL operations in SISS?

Any advice would be helpful, Thank you.

答:
Not with standard SSIS components. Standard SSIS allows you to download a file from FTP server to a local folder, and use local CSV-like file as a data source. Standard Flat File Source or XML Source allows only local and mapped network folders as sources for the source File.

If you really want to combine FTP download and Data source in single data source, you can write your own Script Source Component with C# or VB.NET. It will require more efforts than using standard two components.


问:
How to distinguish online and offline sorting algorithms?
I have the following sorting algorithms:

```<code> Bubble Sort, Selection Sort, Heap Sort, Merge Sort, Quick Sort, Insertion Sort
</code>```

Which of them are online or offline sorts?
Thank you in advance.

答:
It depends on how you define "online" sorting algorithm. If you're using the Wikipedia definition:

In computer science, an online algorithm is one that can process its
  input piece-by-piece in a serial fashion, i.e., in the order that the
  input is fed to the algorithm, without having the entire input
  available from the start.

then of the algorithms you list, only insertion sort fits the bill, because the others require that all items be in memory before sorting can begin.

With insertion sort, you're maintaining a sorted list: each item is put in its proper place as it's received. The list of items that you've received so far is always in order.

See also, https://cs.stackexchange.com/questions/55012/what-is-the-fastest-online-sorting-algorithm

Body:
I have the following sorting algorithms:

 Bubble Sort, Selection Sort, Heap Sort, Merge Sort, Quick Sort, Insertion Sort

Which of them are online or offline sorts?
Thank you in advance.


问:
How to load serverside function by ajax-request?
I asked myself if it would possible to load an associated PHP-function within one PHP-file by an Ajax-Request. For sure it should possible, but how?

Normaly, in my webapplication every Ajax-function (on the clientside) calls a specific PHP-file by its URL. For example this Ajax calls includes/ajax.php.

```<code>function ajaxRequest( ) {

    $( ".loading-overlay" ).show();
    $('#loading').show();
    $.ajax({
        url : "includes/ajax.php",
        type : "POST",
        data : $("#nodes").serialize(),
        dataType: "json",
        cache : false,
        success: function( data ) {
            drawChart( data.chart_data );
            currentGauge( data.current_data.current );
            tableMaxMin( data.maxmin_data );
            tableAvgDays( data.avg_data );
            $('#loading').hide();
            $( ".loading-overlay" ).hide();
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nERROR: "+ err);
        }
    });
}
</code>```

The most of my applications has more then one Ajax-request. I considered it is not very efficienty and especially confusing to create for each ajax-function a new PHP-file. A much better solution would be storing every different (serverside) response-engine in just one PHP-file with different function.

Only for understanding, I'm searching for something like this:

```<code>function ajaxRequest( ) {

    $( ".loading-overlay" ).show();
    $('#loading').show();
    $.ajax({
        url : "includes/ajax.php",
        function: parseData(),  //<--- This is not allowed
        type : "POST",
        data : $("#nodes").serialize(),
        dataType: "json",
        cache : false,
        success: function( data ) {
            drawChart( data.chart_data );
            currentGauge( data.current_data.current );
            tableMaxMin( data.maxmin_data );
            tableAvgDays( data.avg_data );
            $('#loading').hide();
            $( ".loading-overlay" ).hide();
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nERROR: "+ err);
        }
    });
}
</code>```

So, how to load a the specific response-engine by function not by url?

答:
ajax call from one file

```<code>$.ajax({
    url: "includes/ajax.php?action=login",
    method: "POST",
    success: function(response){
        console.log(response);
    }
})
</code>```

ajax call from another file

```<code>$.ajax({
    url: "includes/ajax.php?action=userdetail",
    method: "POST",
    data : {'userId': 1},
    success: function(response){
        console.log(response);
    }
});
</code>```

//ajax.php

```<code><?php

    $action = $_GET['action'];
    extract($_POST);
    switch($action){
        case 'login' :
            //code for login
        break;
        case 'userdetail' :
            //code for userdetail you can use directly $userId to access post variable as we have use `extract` method.
        break;
        default :
             echo json_encode(array("message"=>"Please provide proper action"));
        break;
    }
?>
</code>```

Body:
I asked myself if it would possible to load an associated PHP-function within one PHP-file by an Ajax-Request. For sure it should possible, but how?

Normaly, in my webapplication every Ajax-function (on the clientside) calls a specific PHP-file by its URL. For example this Ajax calls includes/ajax.php.

function ajaxRequest( ) {

    $( ".loading-overlay" ).show();
    $('#loading').show();
    $.ajax({
        url : "includes/ajax.php",
        type : "POST",
        data : $("#nodes").serialize(),
        dataType: "json",
        cache : false,
        success: function( data ) {
            drawChart( data.chart_data );
            currentGauge( data.current_data.current );
            tableMaxMin( data.maxmin_data );
            tableAvgDays( data.avg_data );
            $('#loading').hide();
            $( ".loading-overlay" ).hide();
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nERROR: "+ err);
        }
    });
}

The most of my applications has more then one Ajax-request. I considered it is not very efficienty and especially confusing to create for each ajax-function a new PHP-file. A much better solution would be storing every different (serverside) response-engine in just one PHP-file with different function.

Only for understanding, I'm searching for something like this:

function ajaxRequest( ) {

    $( ".loading-overlay" ).show();
    $('#loading').show();
    $.ajax({
        url : "includes/ajax.php",
        function: parseData(),  //<--- This is not allowed
        type : "POST",
        data : $("#nodes").serialize(),
        dataType: "json",
        cache : false,
        success: function( data ) {
            drawChart( data.chart_data );
            currentGauge( data.current_data.current );
            tableMaxMin( data.maxmin_data );
            tableAvgDays( data.avg_data );
            $('#loading').hide();
            $( ".loading-overlay" ).hide();
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nERROR: "+ err);
        }
    });
}

So, how to load a the specific response-engine by function not by url?

Body:
ajax call from one file

$.ajax({
    url: "includes/ajax.php?action=login",
    method: "POST",
    success: function(response){
        console.log(response);
    }
})

ajax call from another file

$.ajax({
    url: "includes/ajax.php?action=userdetail",
    method: "POST",
    data : {'userId': 1},
    success: function(response){
        console.log(response);
    }
});

//ajax.php

<?php

    $action = $_GET['action'];
    extract($_POST);
    switch($action){
        case 'login' :
            //code for login
        break;
        case 'userdetail' :
            //code for userdetail you can use directly $userId to access post variable as we have use `extract` method.
        break;
        default :
             echo json_encode(array("message"=>"Please provide proper action"));
        break;
    }
?>


问:
Race condition when multiple processes attempts to read / delete files in the same directory
I have a Python script which performs operations like read, write and delete on files in a directory. Before performing any of these operations, os.listdir is done to get the list of files. A file is picked at random and an operation is performed on it.

But I have to run multiple instances of the script. So there is a possibility of race condition. A file could get deleted by an instance while another instance still attempts to read it.

What is a good way to overcome this problem?

答:
You'll have to identify the critical regions first.
Then you'll have to protect them by some kind of semaphore. This could be a lock-file or a real semaphore as offered by your operating system.

The real challenge will be to keep the critical regions (timely) as small as possible.

Since you only have to protect the script against itself, a single semaphore should do it. But if you need more than one semaphore, be sure not to use more than one at a time, or be very careful not to produce potential deadlocks.


问:
Heap versus Stack allocation implications (.NET)
From an SO answer1 about Heap and Stack, it raised me a question: Why it is important to know where the variables are allocated?

At another answer someone pointed that the stack is faster. Is this the only implication? Could someone give a code example where a simple allocation location change could solve a problem (eg. performance)?

Note that this question is .NET specific

1 the question is removed from SO.

答:
(edit: My original answer contained the oversimplification "structs are allocated on the stack" and confused stack-vs-heap and value-vs-reference concerns a bit, because they are coupled in C#.)

Whether objects live on the stack or not is an implementation detail which is not very important. Jon has already explained this well. When choosing between using a class and struct, it is more important to realize that reference types work differently than value types. Take the following simple class as an example:

```<code>public class Foo
{
   public int X = 0;
}
</code>```

Now consider the following code:

```<code>Foo foo = new Foo();
Foo foo2 = foo;
foo2.X = 1;
</code>```

In this example, foo and foo2 are references to the same object. Setting X on foo2 will also affect foo1. If we change the Foo class to a struct then this is no longer the case. This is because structs are not accessed through references. Assigning foo2 will actually make a copy.

One of the reasons for putting stuff on the stack is that the garbage collector does not have to clean it up. You typically should not worry about such things; just use classes! Modern garbage collectors do a pretty good job. Some modern virtual machines (like java 1.6) can even determine whether it is safe to allocate objects on the stack even if they are not value types.

OwnerDisplayName: Vernicht

LastEditorDisplayName: Vernicht

Body:
(edit: My original answer contained the oversimplification "structs are allocated on the stack" and confused stack-vs-heap and value-vs-reference concerns a bit, because they are coupled in C#.)

Whether objects live on the stack or not is an implementation detail which is not very important. Jon has already explained this well. When choosing between using a class and struct, it is more important to realize that reference types work differently than value types. Take the following simple class as an example:

public class Foo
{
   public int X = 0;
}

Now consider the following code:

Foo foo = new Foo();
Foo foo2 = foo;
foo2.X = 1;

In this example, foo and foo2 are references to the same object. Setting X on foo2 will also affect foo1. If we change the Foo class to a struct then this is no longer the case. This is because structs are not accessed through references. Assigning foo2 will actually make a copy.

One of the reasons for putting stuff on the stack is that the garbage collector does not have to clean it up. You typically should not worry about such things; just use classes! Modern garbage collectors do a pretty good job. Some modern virtual machines (like java 1.6) can even determine whether it is safe to allocate objects on the stack even if they are not value types.

OwnerDisplayName: wcoenen

LastEditorDisplayName: wcoenen


问:
Key error when trying to drop rows in pandas dataframe
```<code>for i in [train]:
   if(i.creation_date>i.sell_date):
    train.drop(train.index[i], inplace=True)

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(),
a.item(), a.any() or a.all().
</code>```

Getting this error when I try to execute this code, train is a pandas dataframe and creation_date and sell_date are labels of columns.

I want to delete the rows where creation_date>sell_date"

Can someone please help me out

答:
When you do for i in [train], it gives you one item, the train dataframe. You want to iterate through the rows of the train dataframe instead:

```<code>for i, row in train.iterrows():
  if(row.creation_date > row.sell_date):
    train.drop(train.index[i], inplace=True)
</code>```

Body:
for i in [train]:
   if(i.creation_date>i.sell_date):
    train.drop(train.index[i], inplace=True)

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(),
a.item(), a.any() or a.all().

Getting this error when I try to execute this code, train is a pandas dataframe and creation_date and sell_date are labels of columns.

I want to delete the rows where creation_date>sell_date"

Can someone please help me out

Body:
When you do for i in [train], it gives you one item, the train dataframe. You want to iterate through the rows of the train dataframe instead:

for i, row in train.iterrows():
  if(row.creation_date > row.sell_date):
    train.drop(train.index[i], inplace=True)


问:
How to use Coroutines and Callback properly? Retrieving an array out of an IEnumerator
we have some trouble with an IEnumerator and don't know how to retrieve an array out of it. We found out that you have to do it with a callback , but we don't really know how to use it. Here is the code of the IEnumerator and the void that needs to receive a string array from it.

```<code>public void StartRoutineGetProjects(string username, string password, string url){
    StartCoroutine(GetProjects(username, password, url));

    // here we dont know how to receive the array, need some help here
}

public IEnumerator GetProjects (string username, string password, string url, Action<string[]> callback)
{
    string privateURL = "http://" + url + "/Unity/myprojects.php";

    WWWForm form = new WWWForm ();
    form.AddField ("username", username);
    form.AddField ("password", password);

    // Send WWWForm
    WWW projects_get = new WWW (privateURL, form);

    if (projects_get.error != null && projects_get.error != "") {
        Debug.Log ("Internal Error");
    } else {
        // splitting the result at "|"
        string[] tempProjects = projects_get.text.Split ("|".ToCharArray ());

        yield return tempProjects;

        callback(tempProjects) // <-- here we want to return the array

    }
}
</code>```

We would be glad for every help we can get.

答:
```<code>StartCoroutine(GetProjects(username, password, url, (tempProjectArray) =>
{
    // do stuff with your project array
}));
</code>```

or

```<code>void OnProjectRetrieved(string[] projects)
{
    // do stuff with your project array
}

public void StartRoutineGetProjects(string username, string password, string url)
{
    StartCoroutine(GetProjects(username, password, url, OnProjectRetrieved));
}
</code>```

Body:
we have some trouble with an IEnumerator and don't know how to retrieve an array out of it. We found out that you have to do it with a callback , but we don't really know how to use it. Here is the code of the IEnumerator and the void that needs to receive a string array from it.

public void StartRoutineGetProjects(string username, string password, string url){
    StartCoroutine(GetProjects(username, password, url));

    // here we dont know how to receive the array, need some help here
}

public IEnumerator GetProjects (string username, string password, string url, Action<string[]> callback)
{
    string privateURL = "http://" + url + "/Unity/myprojects.php";

    WWWForm form = new WWWForm ();
    form.AddField ("username", username);
    form.AddField ("password", password);

    // Send WWWForm
    WWW projects_get = new WWW (privateURL, form);

    if (projects_get.error != null && projects_get.error != "") {
        Debug.Log ("Internal Error");
    } else {
        // splitting the result at "|"
        string[] tempProjects = projects_get.text.Split ("|".ToCharArray ());

        yield return tempProjects;

        callback(tempProjects) // <-- here we want to return the array

    }
}

We would be glad for every help we can get.

Body:
StartCoroutine(GetProjects(username, password, url, (tempProjectArray) =>
{
    // do stuff with your project array
}));

or

void OnProjectRetrieved(string[] projects)
{
    // do stuff with your project array
}

public void StartRoutineGetProjects(string username, string password, string url)
{
    StartCoroutine(GetProjects(username, password, url, OnProjectRetrieved));
}


答:
The rstrip() in Python takes a set of characters as the argument.

If no argument is provided, the default is a whitespace.

It starts stripping the set of characters from the right if and only if it encounters character(s) mentioned in your character set, on the extreme right of the input string.

Which explains why l wasn't stripped in the first example.

In the second example World matches with the character set provided in the argument. So, World is stripped as well as the double l and o in Hello because World has has an l and an o in it.

Which leaves you with He which is the correct outcome.

Title: rstrip on python behaving awkwardly: 'HelloWorld'.rstrip('World') deletes everything after 'He'