问:
Remove specific XML nodes using Clojure
I have the following XML structure:

```<code>(def xmlstr
"<ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>B</Type><Note>BB</Note></Item>
    <Item><Type>C</Type><Note>CC</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>")
</code>```

where I want to remove any Item, if it has a Type B or C. The result should be something like:

```<code><ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>
</code>```

I've found it pretty trivial to query such structures using data.xml and data.xml.zip, e.g:

;; lein try org.clojure/data.xml org.clojure/data.zip
(def xmldoc (clojure.data.xml/parse-str xmlstr))
(def zipxml (clojure.zip/xml-zip xmldoc))

(clojure.data.zip.xml/xml-> zipxml :Items :Item [:Type "A"] :Note clojure.data.zip.xml/text)
;; => ("AA" "AA")
```

but didn't find similar declarative features for removing/editing children.

答:
Examples below use full namespaces, not aliases. One way of solving this was using zippers:

(defn remove-types-loc [types loc]
  (loop [loc loc]
    (if (clojure.zip/end? loc)
      (clojure.zip/root loc)
      (if (and (clojure.zip/branch? loc)
               (some #(and (= (:tag %) :Type)
                           (contains? types (first (:content %)))) (clojure.zip/children loc)))
        (recur (clojure.zip/remove loc))
        (recur (clojure.zip/next loc))))))

(clojure.data.xml/emit-str (remove-types-loc #{"B" "C"} zipxml))
;; => emits the expected result, with the two Type A Items
```

<p>The following gives the same result using core functions, but has quite a new nested levels and 'needs' two functions:</p>

<pre class="lang-clj prettyprint-override"><code>(defn remove-types-in* [remove-types content]
  (update-in content [:content]
             (fn [items]
               (remove (fn [item]
                         (some #(and
                                 (= (:tag %) :Type)
                                 (contains? remove-types (first (:content %)))) (:content item)))
                items))))

(defn remove-types-in [remove-types xmldoc]
  (update-in xmldoc [:content] #(map (partial remove-types-in* remove-types) %)))

(clojure.data.xml/emit-str (remove-types-in #{"B" "C"} xmldoc))
;; => same result as above
</code>```

Finally, when the structure is fixed and as simple as this one, it is easy to just construct the result manually. But this would break if the source gets more elements or attributes.

(clojure.data.xml/emit-str
 (clojure.data.xml/sexp-as-element
  [:ROOT
   [:Items
    (for [i (clojure.data.zip.xml/xml-> zipxml :Items :Item)
          :let [t (clojure.data.zip.xml/xml1-> i :Type clojure.data.zip.xml/text)
                n (clojure.data.zip.xml/xml1-> i :Note clojure.data.zip.xml/text)]
          :when (not (contains? #{"B" "C"} t))]
      [:Item
       [:Type t]
       [:Note n]])]]))
;; same as above
```

<p>Possibly a better version of the above, which will work even if Item structure changes:</p>

<pre class="lang-clj prettyprint-override"><code>(clojure.data.xml/emit-str
 (clojure.data.xml/element
  :ROOT {}
  (clojure.data.xml/element
   :Items {}
   (for [n (xml-seq xmldoc)
         :when (and
                (= :Item (:tag n))
                (not (some #(and (= (:tag %) :Type)
                                 (contains? #{"B" "C"} (first (:content %))))
                           (:content n))))] n))))
</code>```

Didn't find any oneliners for doing it. Not sure if there are better / more readable ways of doing this using org.clojure or other libraries.

For more complex XML editing, XSLT or XQuery Update is arguably a more 'native' solution. Here's a quick and dirty XSLT 2.0 solution using the open-source Saxon-HE S9API:

;; lein try net.sf.saxon/Saxon-HE "9.7.0-18"
(defn remove-types-xslt [remove-types xmlstr]
  (let [processor (net.sf.saxon.s9api.Processor. false)
         compiler (.newXsltCompiler processor)
         exp (.compile compiler (javax.xml.transform.stream.StreamSource. (java.io.StringReader. "<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:param name='remove-types'/><xsl:template match='@*|node()'><xsl:copy><xsl:apply-templates select='@*|node()'/></xsl:copy></xsl:template><xsl:template match='Item[Type[. = $remove-types]]'/></xsl:transform>")))
         src (.build (.newDocumentBuilder processor) (javax.xml.transform.stream.StreamSource. (java.io.StringReader. xmlstr)))
         sw (java.io.StringWriter.)
         out (doto (net.sf.saxon.s9api.Serializer.) (.setOutputWriter sw))
         t (doto (.load exp) (.setInitialContextNode src) (.setDestination out) (.setParameter (net.sf.saxon.s9api.QName. "remove-types") (net.sf.saxon.s9api.XdmValue. (for [remove-type remove-types] (net.sf.saxon.s9api.XdmAtomicValue. remove-type)))) (.transform))]
    sw))
(str (remove-types-xslt #{"B" "C"} xmlstr))
```

<p>And for completeness, here's an even dirtier version using XQuery Update Facility. Note that this particular example uses Saxon-EE, and therefore requires a paid EE license.</p>

<pre class="lang-clj prettyprint-override"><code>(defn remove-types-xq [remove-types xmlstr]
  (let [processor (net.sf.saxon.s9api.Processor. true)
        compiler (doto (.newXQueryCompiler processor) (.setUpdatingEnabled true))
        exp (.compile compiler "declare variable $remove-types as xs:string+ external;delete nodes //Items/Item[Type[. = $remove-types]]")
        src (.build (doto (.newDocumentBuilder processor) (.setTreeModel net.sf.saxon.om.TreeModel/LINKED_TREE)) (javax.xml.transform.stream.StreamSource. (java.io.StringReader. xmlstr)))
        e (doto (.load exp) (.setContextItem src) (.setExternalVariable (net.sf.saxon.s9api.QName. "remove-types") (net.sf.saxon.s9api.XdmValue. (for [remove-type remove-types] (net.sf.saxon.s9api.XdmAtomicValue. remove-type)))) (.run))]
    (when-let [res (first (iterator-seq (.getUpdatedDocuments e)))]
      (let [sw (java.io.StringWriter.)
            out (doto (net.sf.saxon.s9api.Serializer.) (.setOutputWriter sw))]
        (.writeXdmValue processor res out)
        sw))))
(str (remove-types-xq #{"B" "C"} xmlstr))
</code>```

Except for all the stuff, delete nodes //Items/Item[Type[. = $remove-types]] is pretty succinct.

Title: Remove specific XML nodes using Clojure

Body:
I have the following XML structure:

(def xmlstr
"<ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>B</Type><Note>BB</Note></Item>
    <Item><Type>C</Type><Note>CC</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>")

where I want to remove any Item, if it has a Type B or C. The result should be something like:

<ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>

I've found it pretty trivial to query such structures using data.xml and data.xml.zip, e.g:

;; lein try org.clojure/data.xml org.clojure/data.zip
(def xmldoc (clojure.data.xml/parse-str xmlstr))
(def zipxml (clojure.zip/xml-zip xmldoc))

(clojure.data.zip.xml/xml-> zipxml :Items :Item [:Type "A"] :Note clojure.data.zip.xml/text)
;; => ("AA" "AA")

but didn't find similar declarative features for removing/editing children.

Body:
Examples below use full namespaces, not aliases. One way of solving this was using zippers:

(defn remove-types-loc [types loc]
  (loop [loc loc]
    (if (clojure.zip/end? loc)
      (clojure.zip/root loc)
      (if (and (clojure.zip/branch? loc)
               (some #(and (= (:tag %) :Type)
                           (contains? types (first (:content %)))) (clojure.zip/children loc)))
        (recur (clojure.zip/remove loc))
        (recur (clojure.zip/next loc))))))

(clojure.data.xml/emit-str (remove-types-loc #{"B" "C"} zipxml))
;; => emits the expected result, with the two Type A Items

The following gives the same result using core functions, but has quite a new nested levels and 'needs' two functions:

(defn remove-types-in* [remove-types content]
  (update-in content [:content]
             (fn [items]
               (remove (fn [item]
                         (some #(and
                                 (= (:tag %) :Type)
                                 (contains? remove-types (first (:content %)))) (:content item)))
                items))))

(defn remove-types-in [remove-types xmldoc]
  (update-in xmldoc [:content] #(map (partial remove-types-in* remove-types) %)))

(clojure.data.xml/emit-str (remove-types-in #{"B" "C"} xmldoc))
;; => same result as above

Finally, when the structure is fixed and as simple as this one, it is easy to just construct the result manually. But this would break if the source gets more elements or attributes.

(clojure.data.xml/emit-str
 (clojure.data.xml/sexp-as-element
  [:ROOT
   [:Items
    (for [i (clojure.data.zip.xml/xml-> zipxml :Items :Item)
          :let [t (clojure.data.zip.xml/xml1-> i :Type clojure.data.zip.xml/text)
                n (clojure.data.zip.xml/xml1-> i :Note clojure.data.zip.xml/text)]
          :when (not (contains? #{"B" "C"} t))]
      [:Item
       [:Type t]
       [:Note n]])]]))
;; same as above

Possibly a better version of the above, which will work even if Item structure changes:

(clojure.data.xml/emit-str
 (clojure.data.xml/element
  :ROOT {}
  (clojure.data.xml/element
   :Items {}
   (for [n (xml-seq xmldoc)
         :when (and
                (= :Item (:tag n))
                (not (some #(and (= (:tag %) :Type)
                                 (contains? #{"B" "C"} (first (:content %))))
                           (:content n))))] n))))

Didn't find any oneliners for doing it. Not sure if there are better / more readable ways of doing this using org.clojure or other libraries.

For more complex XML editing, XSLT or XQuery Update is arguably a more 'native' solution. Here's a quick and dirty XSLT 2.0 solution using the open-source Saxon-HE S9API:

;; lein try net.sf.saxon/Saxon-HE "9.7.0-18"
(defn remove-types-xslt [remove-types xmlstr]
  (let [processor (net.sf.saxon.s9api.Processor. false)
         compiler (.newXsltCompiler processor)
         exp (.compile compiler (javax.xml.transform.stream.StreamSource. (java.io.StringReader. "<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:param name='remove-types'/><xsl:template match='@*|node()'><xsl:copy><xsl:apply-templates select='@*|node()'/></xsl:copy></xsl:template><xsl:template match='Item[Type[. = $remove-types]]'/></xsl:transform>")))
         src (.build (.newDocumentBuilder processor) (javax.xml.transform.stream.StreamSource. (java.io.StringReader. xmlstr)))
         sw (java.io.StringWriter.)
         out (doto (net.sf.saxon.s9api.Serializer.) (.setOutputWriter sw))
         t (doto (.load exp) (.setInitialContextNode src) (.setDestination out) (.setParameter (net.sf.saxon.s9api.QName. "remove-types") (net.sf.saxon.s9api.XdmValue. (for [remove-type remove-types] (net.sf.saxon.s9api.XdmAtomicValue. remove-type)))) (.transform))]
    sw))
(str (remove-types-xslt #{"B" "C"} xmlstr))

And for completeness, here's an even dirtier version using XQuery Update Facility. Note that this particular example uses Saxon-EE, and therefore requires a paid EE license.

(defn remove-types-xq [remove-types xmlstr]
  (let [processor (net.sf.saxon.s9api.Processor. true)
        compiler (doto (.newXQueryCompiler processor) (.setUpdatingEnabled true))
        exp (.compile compiler "declare variable $remove-types as xs:string+ external;delete nodes //Items/Item[Type[. = $remove-types]]")
        src (.build (doto (.newDocumentBuilder processor) (.setTreeModel net.sf.saxon.om.TreeModel/LINKED_TREE)) (javax.xml.transform.stream.StreamSource. (java.io.StringReader. xmlstr)))
        e (doto (.load exp) (.setContextItem src) (.setExternalVariable (net.sf.saxon.s9api.QName. "remove-types") (net.sf.saxon.s9api.XdmValue. (for [remove-type remove-types] (net.sf.saxon.s9api.XdmAtomicValue. remove-type)))) (.run))]
    (when-let [res (first (iterator-seq (.getUpdatedDocuments e)))]
      (let [sw (java.io.StringWriter.)
            out (doto (net.sf.saxon.s9api.Serializer.) (.setOutputWriter sw))]
        (.writeXdmValue processor res out)
        sw))))
(str (remove-types-xq #{"B" "C"} xmlstr))

Except for all the stuff, delete nodes //Items/Item[Type[. = $remove-types]] is pretty succinct.


来源: stackexchange

问:
Deleting from array javascript
I am looping through an array and displaying it on the screen. I have a problem, though. I tried to add a function that when you click on the text, it deletes that clicked text. Here is my code:

```<code>var div = document.querySelector('div');
var array = [
"Banana",
"Chocolate",
"Oranges"
];

for(let i = 0; i < array.length; i++){

var p = document.createElement('p');
p.textContent = array[i];
div.appendChild(p);

p.onclick = function(){

    array.splice(array[i], 1);
    console.log(array);
}

}
</code>```

When I click on it, it deletes the item from the array and logs it to the console. But it doesn't show on the screen. Any help?

Thank you,
Scratch Cat

答:
```<code>for(let i = 0; i < array.length; i++){
let p = document.createElement('p');//note the block scoping
p.textContent = array[i];
div.appendChild(p);

p.onclick = function(){
    array.splice(i, 1);//splice wants an index...
    p.remove();//remove el from document tree
    console.log(array);
}

}
</code>```

You may also want to remove the html element?

ContentLicense: CC BY-SA 3.0

Title: Deleting from array javascript

Body:
I am looping through an array and displaying it on the screen. I have a problem, though. I tried to add a function that when you click on the text, it deletes that clicked text. Here is my code:

var div = document.querySelector('div');
var array = [
"Banana",
"Chocolate",
"Oranges"
];

for(let i = 0; i < array.length; i++){

var p = document.createElement('p');
p.textContent = array[i];
div.appendChild(p);

p.onclick = function(){

    array.splice(array[i], 1);
    console.log(array);
}

}

When I click on it, it deletes the item from the array and logs it to the console. But it doesn't show on the screen. Any help?

Thank you,
Scratch Cat

Body:
for(let i = 0; i < array.length; i++){
let p = document.createElement('p');//note the block scoping
p.textContent = array[i];
div.appendChild(p);

p.onclick = function(){
    array.splice(i, 1);//splice wants an index...
    p.remove();//remove el from document tree
    console.log(array);
}

}

You may also want to remove the html element?


问:
How to read in url in python and then print each URL on the website?
I am trying to figure out how to only read in each line that is a url from a website, every time I run the code I get the error:

AttributeError: module 'urllib' has no attribute 'urlopen'

My code is below

```<code>import os
import subprocess
import urllib

datasource = urllib.urlopen("www.google.com")

while 1:
        line = datasource.readline()
        if line == "": break
        if (line.find("www") > -1) :
                print (line)

li = ['www.apple.com', 'www.google.com']
os.chdir('..')
os.chdir('..')
os.chdir('..')
os.chdir('Program Files (x86)\\LinkChecker')

for s in li:
    os.system('Start .\linkchecker ' + s)
</code>```

答:
Seems python3X, so you should use</p>

```<code>urllib.request.urlopen
</code>```

Body:
I am trying to figure out how to only read in each line that is a url from a website, every time I run the code I get the error:

AttributeError: module 'urllib' has no attribute 'urlopen'

My code is below

import os
import subprocess
import urllib

datasource = urllib.urlopen("www.google.com")

while 1:
        line = datasource.readline()
        if line == "": break
        if (line.find("www") > -1) :
                print (line)

li = ['www.apple.com', 'www.google.com']
os.chdir('..')
os.chdir('..')
os.chdir('..')
os.chdir('Program Files (x86)\\LinkChecker')

for s in li:
    os.system('Start .\linkchecker ' + s)

Body:
Seems python3X, so you should use

urllib.request.urlopen


问:
Convert from one base to another in Java
Right now, I'm trying to find a way to convert a number from one base to another in Java, given a number, the base that the number is in, and the base to convert to.

```<code>public static void BaseConversion(String number, int base1, int base2){
    //convert the number from one base to another
}
</code>```

I found a solution for JavaScript, and I'm wondering if it would be possible to do something similar in Java:

```<code>function convertFromBaseToBase(str, fromBase, toBase){
    var num = parseInt(str, fromBase); //convert from one base to another
    return num.toString(toBase);
}
</code>```

答:
How about this ? </p>

```<code>public static void main(String[] args) {

    System.out.println(toDecimalBase("11111111", 2));
    System.out.println(toDecimalBase("Ff", 16));
    System.out.println(toDecimalBase("377", 8));
    System.out.println(toDecimalBase("255", 10));
}

private static int toDecimalBase(String number, int base) {

    int lenght = number.length();
    int result = 0;

    for (int i = 0; i < lenght; i++) {

        // get char in a reverse order from the array
        int character = number.charAt(lenght - i - 1);

        // convert range [A-F] to range of [0-6]
        if (character >= 'A' && character <= 'F') {
            character = character - 'A' + 10;
        }
        else if (character >= 'a' && character <= 'f') {
            character = character - 'a' + 10;
        }
        // Unicode to int
        else {
            character = Character.getNumericValue(character);
        }
        result += (Math.pow(base, i)) * character;
    }

    return result;
}
</code>```

Body:
Right now, I'm trying to find a way to convert a number from one base to another in Java, given a number, the base that the number is in, and the base to convert to.

public static void BaseConversion(String number, int base1, int base2){
    //convert the number from one base to another
}

I found a solution for JavaScript, and I'm wondering if it would be possible to do something similar in Java:

function convertFromBaseToBase(str, fromBase, toBase){
    var num = parseInt(str, fromBase); //convert from one base to another
    return num.toString(toBase);
}

Body:
How about this ?

public static void main(String[] args) {

    System.out.println(toDecimalBase("11111111", 2));
    System.out.println(toDecimalBase("Ff", 16));
    System.out.println(toDecimalBase("377", 8));
    System.out.println(toDecimalBase("255", 10));
}

private static int toDecimalBase(String number, int base) {

    int lenght = number.length();
    int result = 0;

    for (int i = 0; i < lenght; i++) {

        // get char in a reverse order from the array
        int character = number.charAt(lenght - i - 1);

        // convert range [A-F] to range of [0-6]
        if (character >= 'A' && character <= 'F') {
            character = character - 'A' + 10;
        }
        else if (character >= 'a' && character <= 'f') {
            character = character - 'a' + 10;
        }
        // Unicode to int
        else {
            character = Character.getNumericValue(character);
        }
        result += (Math.pow(base, i)) * character;
    }

    return result;
}


问:
Parse an XML as fast as possible
I have a VB.Net app that reads a zip file that has an XML file in it.  I need to parse the XML file into row segments, pull one node value out as the application id and send it on it's way to a MS SQL database.  The XML file looks like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<PROJECTS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
<APPLICATION_ID>9243987</APPLICATION_ID>
<ACTIVITY>P30</ACTIVITY>
<ADMINISTERING_IC>AR</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE>
<ARRA_FUNDED>N</ARRA_FUNDED>
<AWARD_NOTICE_DATE>05/22/2017</AWARD_NOTICE_DATE>
<BUDGET_START>04/01/2017</BUDGET_START>
</row>
<row>
<APPLICATION_ID>9243988</APPLICATION_ID>
<ACTIVITY>P30</ACTIVITY>
<ADMINISTERING_IC>AR</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE>
<ARRA_FUNDED>N</ARRA_FUNDED>
<AWARD_NOTICE_DATE>05/22/2017</AWARD_NOTICE_DATE>
<BUDGET_START>04/01/2017</BUDGET_START>
</row>
<row>
<APPLICATION_ID>9243989</APPLICATION_ID>
<ACTIVITY>P30</ACTIVITY>
<ADMINISTERING_IC>AR</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE>
<ARRA_FUNDED>N</ARRA_FUNDED>
<AWARD_NOTICE_DATE>05/22/2017</AWARD_NOTICE_DATE>
<BUDGET_START>04/01/2017</BUDGET_START>
</row>
</PROJECTS>
</code>```

The file could contain a million records and be close to 100mg in size.  My current code isbelow and could take as long as 8 hours to run for a million records.

My VB code that parses the file is:

```<code>            If ofdXML.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
            stopWatch.Start()
            Dim result As String
            Dim fName As String = ofdXML.FileName
            If fName.EndsWith("zip") Then
                Dim ePath As String = "E:\Downloads\WEEKLY"
                fileName = ExtractArchive(fName, ePath)
                fName = Path.Combine(ePath, fileName)
            End If

            result = Path.GetFileNameWithoutExtension(fName)
            Dim rdr As New StreamReader(fName)
            While (rdr.Peek >= 0)
                varLine = rdr.ReadLine
                sTag = varLine.Contains("<row>")
                eTag = varLine.Contains("</row>")
                If sTag And eTag Then
                    appLine = varLine
                    If appLine.Contains("<row><APPLICATION_ID>") Then
                        appID = appLine.Substring(Len("<row><APPLICATION_ID>"), appLine.IndexOf("/APPLICATION_ID") - Len("<row><APPLICATION_ID>") - 1)
                    End If
                ElseIf sTag Then
                    v1 = True
                    appLine = varLine
                    If appLine.Contains("<row><APPLICATION_ID>") Then
                        appID = appLine.Substring(Len("<row><APPLICATION_ID>"), appLine.IndexOf("/APPLICATION_ID") - Len("<row><APPLICATION_ID>") - 1)
                    End If
                ElseIf eTag Then
                    appLine = appLine & varLine
                    v1 = False
                ElseIf v1 Then
                    appLine = appLine & varLine
                    If appLine.Contains("<APPLICATION_ID>") Then
                        Dim xi As Integer = appLine.IndexOf("_ID>") + 4
                        appID = appLine.Substring(xi, appLine.IndexOf("/APPLICATION_ID") - (xi + 1))
                    End If
                End If

                If Trim(Len(varLine)) > 0 And appLine.Contains("<row>") And appLine.Contains("</row") And Not varLine.Contains("</PROJECTS>") Then
                    TextBox2.Text = i.ToString
                    TextBox3.Text = appID
                    sb.Append(appID + ",")
                    Application.DoEvents()
                    i += 1
                    ADMIN_Save_To_Database(appLine, appID, result)
                End If
            End While

        End If
</code>```

Any help is greatly appreciated.

答:
I suggest you investigate actual XML parsing - either into a DOM you can query or SAX you can "listen" to. You're only interested in a specific tag so it should be pretty easy to set up a SAX listener for that tag and ignore everything else.

This should get you started:

https://www.tutorialspoint.com/vb.net/vb.net_xml_processing.htm

If you insist on sticking with your string parsing look for optimizations. Loops are killer! You don't want to do expensive things inside a loop if you can get away with it.

For example, you calculate the length of "< row >< APPLICATION_ID >" twice for every row (depending on the format). Not only is that expensive, but the result is a constant! Set or calculate it once outside of the loop.

All the .Contains() calls are very expensive. And many of yours are redundant. For example, you check for the existence of "< row >" and "< /row >" near the top of your loop and then you do it again near the bottom of the loop.

In short, your best bet is XML parsing tools. If you don't want to do that, look very carefully thru your code for expensive operations that you can either pull outside of the loop altogether or just do once each time thru.

Title: Parse an XML as fast as possible

Body:
I have a VB.Net app that reads a zip file that has an XML file in it.  I need to parse the XML file into row segments, pull one node value out as the application id and send it on it's way to a MS SQL database.  The XML file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<PROJECTS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
<APPLICATION_ID>9243987</APPLICATION_ID>
<ACTIVITY>P30</ACTIVITY>
<ADMINISTERING_IC>AR</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE>
<ARRA_FUNDED>N</ARRA_FUNDED>
<AWARD_NOTICE_DATE>05/22/2017</AWARD_NOTICE_DATE>
<BUDGET_START>04/01/2017</BUDGET_START>
</row>
<row>
<APPLICATION_ID>9243988</APPLICATION_ID>
<ACTIVITY>P30</ACTIVITY>
<ADMINISTERING_IC>AR</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE>
<ARRA_FUNDED>N</ARRA_FUNDED>
<AWARD_NOTICE_DATE>05/22/2017</AWARD_NOTICE_DATE>
<BUDGET_START>04/01/2017</BUDGET_START>
</row>
<row>
<APPLICATION_ID>9243989</APPLICATION_ID>
<ACTIVITY>P30</ACTIVITY>
<ADMINISTERING_IC>AR</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE>
<ARRA_FUNDED>N</ARRA_FUNDED>
<AWARD_NOTICE_DATE>05/22/2017</AWARD_NOTICE_DATE>
<BUDGET_START>04/01/2017</BUDGET_START>
</row>
</PROJECTS>

The file could contain a million records and be close to 100mg in size.  My current code isbelow and could take as long as 8 hours to run for a million records.

My VB code that parses the file is:

            If ofdXML.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
            stopWatch.Start()
            Dim result As String
            Dim fName As String = ofdXML.FileName
            If fName.EndsWith("zip") Then
                Dim ePath As String = "E:\Downloads\WEEKLY"
                fileName = ExtractArchive(fName, ePath)
                fName = Path.Combine(ePath, fileName)
            End If

            result = Path.GetFileNameWithoutExtension(fName)
            Dim rdr As New StreamReader(fName)
            While (rdr.Peek >= 0)
                varLine = rdr.ReadLine
                sTag = varLine.Contains("<row>")
                eTag = varLine.Contains("</row>")
                If sTag And eTag Then
                    appLine = varLine
                    If appLine.Contains("<row><APPLICATION_ID>") Then
                        appID = appLine.Substring(Len("<row><APPLICATION_ID>"), appLine.IndexOf("/APPLICATION_ID") - Len("<row><APPLICATION_ID>") - 1)
                    End If
                ElseIf sTag Then
                    v1 = True
                    appLine = varLine
                    If appLine.Contains("<row><APPLICATION_ID>") Then
                        appID = appLine.Substring(Len("<row><APPLICATION_ID>"), appLine.IndexOf("/APPLICATION_ID") - Len("<row><APPLICATION_ID>") - 1)
                    End If
                ElseIf eTag Then
                    appLine = appLine & varLine
                    v1 = False
                ElseIf v1 Then
                    appLine = appLine & varLine
                    If appLine.Contains("<APPLICATION_ID>") Then
                        Dim xi As Integer = appLine.IndexOf("_ID>") + 4
                        appID = appLine.Substring(xi, appLine.IndexOf("/APPLICATION_ID") - (xi + 1))
                    End If
                End If

                If Trim(Len(varLine)) > 0 And appLine.Contains("<row>") And appLine.Contains("</row") And Not varLine.Contains("</PROJECTS>") Then
                    TextBox2.Text = i.ToString
                    TextBox3.Text = appID
                    sb.Append(appID + ",")
                    Application.DoEvents()
                    i += 1
                    ADMIN_Save_To_Database(appLine, appID, result)
                End If
            End While

        End If

Any help is greatly appreciated.


问:
C++ how to check if among N objects some of them are equal
I have some C++ objects and I would like to check if some of them are equal.

```<code>bool IsEqual(const Board& b)
{
    if( b.From() != from_ )
        return false;

    if (b.To() != to_ )
        return false;

    if( b.Selection() != selection_ )
        return false;

    return true;
}
</code>```

My objects consist of some integers ( from_, to_, selection_) and the class offers the IsEqual method to compare two objects.

calling obj1.IsEqual(obj2) returns true if both objects have the same values.

However how do I compare N objects? Is it possible to push_back objects to an std::vector<Board> and use std::unique?

答:
If you make an array of objects and then run a simple loop to compare them like this

```<code>> board[n];

for(int i=0; i<n ; i++)
  for(int j=i; j<n ; j++)
      board[i].Isequal(board[j]);
</code>```

You can always use more efficient algo to compare.

Body:
I have some C++ objects and I would like to check if some of them are equal.

bool IsEqual(const Board& b)
{
    if( b.From() != from_ )
        return false;

    if (b.To() != to_ )
        return false;

    if( b.Selection() != selection_ )
        return false;

    return true;
}

My objects consist of some integers ( from_, to_, selection_) and the class offers the IsEqual method to compare two objects.

calling obj1.IsEqual(obj2) returns true if both objects have the same values.

However how do I compare N objects? Is it possible to push_back objects to an std::vector<Board> and use std::unique?

Body:
If you make an array of objects and then run a simple loop to compare them like this

> board[n];

for(int i=0; i<n ; i++)
  for(int j=i; j<n ; j++)
      board[i].Isequal(board[j]);

You can always use more efficient algo to compare.


问:
PHP mysqli_real_escape_string() not working inside function
I have a function that adds a log entry to my database as follows:

```<code>function doLog($conn, $category, $result, $details){
    $category = mysqli_real_escape_string($conn, $category);
    $result = mysqli_real_escape_string($conn, $result);
    $details = mysqli_real_escape_string($conn, $details);

    mysqli_query($conn, "INSERT INTO log (category, result, details) VALUES('$category', '$result', '$details')");
    return $details; //for debug
}

echo doLog2($conn, "Test", "Test", "A 'test' entry"); //echo is for debug
</code>```

A 'test' entry is returned/echoed as A \'test\' entry, but is inserted into my database without the slashes.

How can this be?

答:
This is working correctly. The backslashes are to escape the quotes in the SQL query, so that the quote characters are inserted verbatim. It's not supposed to also insert the escape character \.

If you had applied escaping twice, you'd end up with an escaped backslash followed by an escaped quote like this:

```<code>A \\\'test\\\' entry
</code>```

What would be stored in the database would be:

```<code>A \'test\' entry
</code>```

All this is much simpler if you use parameterized statements. You don't do any quoting or escaping.

```<code>function doLog($conn, $category, $result, $details){
    $sql = "INSERT INTO log (category, result, details) VALUES (?, ?, ?)";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "sss", $category, $result, $details);
    mysqli_stmt_execute($stmt);

    return $details; //for debug
}
</code>```

Body:
I have a function that adds a log entry to my database as follows:

function doLog($conn, $category, $result, $details){
    $category = mysqli_real_escape_string($conn, $category);
    $result = mysqli_real_escape_string($conn, $result);
    $details = mysqli_real_escape_string($conn, $details);

    mysqli_query($conn, "INSERT INTO log (category, result, details) VALUES('$category', '$result', '$details')");
    return $details; //for debug
}

echo doLog2($conn, "Test", "Test", "A 'test' entry"); //echo is for debug

A 'test' entry is returned/echoed as A \'test\' entry, but is inserted into my database without the slashes.

How can this be?

Body:
This is working correctly. The backslashes are to escape the quotes in the SQL query, so that the quote characters are inserted verbatim. It's not supposed to also insert the escape character \.

If you had applied escaping twice, you'd end up with an escaped backslash followed by an escaped quote like this:

A \\\'test\\\' entry

What would be stored in the database would be:

A \'test\' entry

All this is much simpler if you use parameterized statements. You don't do any quoting or escaping.

function doLog($conn, $category, $result, $details){
    $sql = "INSERT INTO log (category, result, details) VALUES (?, ?, ?)";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "sss", $category, $result, $details);
    mysqli_stmt_execute($stmt);

    return $details; //for debug
}


问:
QGraphicsView Zooming in and out under mouse position using mouse wheel
I have an application with a QGraphicsView window in the middle of the screen. I want to be able to zoom in and out using a mouse wheel scroll.

Currently I have re-implemented QGraphicsView and overriden the mouse scroll function so that it doesn't scroll the image (like it does by default).

```<code>void MyQGraphicsView::wheelEvent(QWheelEvent *event)
{
    if(event->delta() > 0)
    {
        emit mouseWheelZoom(true);
    }
    else
    {
        emit mouseWheelZoom(false);
    }
}
</code>```

so when I scroll, I'm emitting a signal true if mouse wheel forward false if mouse wheel back.

I have then connected this signal to a slot (zoom function see below) in the class that handles my GUI stuff. Now basically I think my zoom function just isn't the best way to do it at all I have seen some examples of people using the overriden wheelevent function to set scales but I couldn't really find a complete answer.

So instead I have done this but it's not perfect by any means so I'm looking for this to be tweaked a bit or for a working example using scale in the wheel event function.

I initialize m_zoom_level to 0 in the constructor.

```<code>void Display::zoomfunction(bool zoom)
{
    QMatrix matrix;

    if(zoom && m_zoom_level < 500)
    {
        m_zoom_level = m_zoom_level + 10;
        ui->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
        matrix.scale(m_zoom_level, m_zoom_level);

        ui->graphicsView->setMatrix(matrix);
        ui->graphicsView->scale(1,-1);
    }
    else if(!zoom)
    {
        m_zoom_level = m_zoom_level - 10;
        ui->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
        matrix.scale(m_zoom_level, m_zoom_level);

        ui->graphicsView->setMatrix(matrix);
        ui->graphicsView->scale(1,-1);
    }
}
</code>```

As you can see above I'm using a QMatrix and scaling that and setting it to the Graphicsview and setting the transformation anchor to under mouse, but its just not working perfectly sometimes if I'm scrolling loads it will just start to zoom in only (which I think is to do with the int looping over or something).

As I said help with this or a good example of scale under mouse would be great.

答:
Here's a condensed version of the solution above; with just the code you need to put into the wheel event.  This works with/without scroll bars in my testing, perfectly ;)</p>

```<code>void MyGraphicsView::wheelEvent(QWheelEvent* pWheelEvent)
{
    if (pWheelEvent->modifiers() & Qt::ControlModifier)
    {
        // Do a wheel-based zoom about the cursor position
        double angle = pWheelEvent->angleDelta().y();
        double factor = qPow(1.0015, angle);

        auto targetViewportPos = pWheelEvent->pos();
        auto targetScenePos = mapToScene(pWheelEvent->pos());

        scale(factor, factor);
        centerOn(targetScenePos);
        QPointF deltaViewportPos = targetViewportPos - QPointF(viewport()->width() / 2.0, viewport()->height() / 2.0);
        QPointF viewportCenter = mapFromScene(targetScenePos) - deltaViewportPos;
        centerOn(mapToScene(viewportCenter.toPoint()));

        return;
    }
</code>```

Body:
I have an application with a QGraphicsView window in the middle of the screen. I want to be able to zoom in and out using a mouse wheel scroll.

Currently I have re-implemented QGraphicsView and overriden the mouse scroll function so that it doesn't scroll the image (like it does by default).

void MyQGraphicsView::wheelEvent(QWheelEvent *event)
{
    if(event->delta() > 0)
    {
        emit mouseWheelZoom(true);
    }
    else
    {
        emit mouseWheelZoom(false);
    }
}

so when I scroll, I'm emitting a signal true if mouse wheel forward false if mouse wheel back.

I have then connected this signal to a slot (zoom function see below) in the class that handles my GUI stuff. Now basically I think my zoom function just isn't the best way to do it at all I have seen some examples of people using the overriden wheelevent function to set scales but I couldn't really find a complete answer.

So instead I have done this but it's not perfect by any means so I'm looking for this to be tweaked a bit or for a working example using scale in the wheel event function.

I initialize m_zoom_level to 0 in the constructor.

void Display::zoomfunction(bool zoom)
{
    QMatrix matrix;

    if(zoom && m_zoom_level < 500)
    {
        m_zoom_level = m_zoom_level + 10;
        ui->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
        matrix.scale(m_zoom_level, m_zoom_level);

        ui->graphicsView->setMatrix(matrix);
        ui->graphicsView->scale(1,-1);
    }
    else if(!zoom)
    {
        m_zoom_level = m_zoom_level - 10;
        ui->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
        matrix.scale(m_zoom_level, m_zoom_level);

        ui->graphicsView->setMatrix(matrix);
        ui->graphicsView->scale(1,-1);
    }
}

As you can see above I'm using a QMatrix and scaling that and setting it to the Graphicsview and setting the transformation anchor to under mouse, but its just not working perfectly sometimes if I'm scrolling loads it will just start to zoom in only (which I think is to do with the int looping over or something).

As I said help with this or a good example of scale under mouse would be great.

Body:
Here's a condensed version of the solution above; with just the code you need to put into the wheel event.  This works with/without scroll bars in my testing, perfectly ;)

void MyGraphicsView::wheelEvent(QWheelEvent* pWheelEvent)
{
    if (pWheelEvent->modifiers() & Qt::ControlModifier)
    {
        // Do a wheel-based zoom about the cursor position
        double angle = pWheelEvent->angleDelta().y();
        double factor = qPow(1.0015, angle);

        auto targetViewportPos = pWheelEvent->pos();
        auto targetScenePos = mapToScene(pWheelEvent->pos());

        scale(factor, factor);
        centerOn(targetScenePos);
        QPointF deltaViewportPos = targetViewportPos - QPointF(viewport()->width() / 2.0, viewport()->height() / 2.0);
        QPointF viewportCenter = mapFromScene(targetScenePos) - deltaViewportPos;
        centerOn(mapToScene(viewportCenter.toPoint()));

        return;
    }


问:
Hibernate Many to Many Bidirectional Mapping with using Java List
I am trying to make a many to many example with hibernate using java List. My codes are as follows, I am getting some erros. If someone can help me to solve this, it would be great

A Student can take many courses
A course can be taken by many students

```<code>                     Student ---->STUDENT_COURSE<-----Course
</code>```

Student Class:

```<code>public class Student implements java.io.Serializable
{
    private long studentId;
    private String studentName;
    private List<Course> courses = new LinkedList<Course>();
        //other getters and setters

}
</code>```

Course Class:

```<code>public class Course implements java.io.Serializable {

    private long courseId;
    private String courseName;
    private List <Student> Stu = new LinkedList <Student>();
        //other getters and setters
}
</code>```

Course Mapping File:

```<code><?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 14, 2010 7:14:32 AM by Hibernate Tools 3.4.0.Beta1 -->
<hibernate-mapping>
    <class name="com.BiddingSystem.domain.Course" table="COURSE">
        <id name="courseId" type="long">
            <column name="COURSEID" />
            <generator class="native" />
        </id>
        <property name="courseName" type="java.lang.String">
            <column name="COURSENAME" />
        </property>
        <list name="Stu"  table="STUDENT_COURSE">
            <key>
                <column name="COURSEID" />
            </key>
            <many-to-many column="STUDENTID"  class="com.BiddingSystem.domain.Student" />
        </list>
    </class>
</hibernate-mapping>
</code>```

Student Mapping File:

```<code><?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 14, 2010 7:14:32 AM by Hibernate Tools 3.4.0.Beta1 -->
<hibernate-mapping>
    <class name="com.BiddingSystem.domain.Student" table="STUDENT">
        <id name="studentId" type="long">
            <column name="STUDENTID" />
            <generator class="native" />
        </id>
        <property name="studentName" type="java.lang.String">
            <column name="STUDENTNAME" />
        </property>
        <list name="courses"  table="STUDENT_COURSE">
            <key>
                <column name="STUDENTID" />
            </key>
            <many-to-many column="COURSEID" class="com.BiddingSystem.domain.Course" />
        </list>
    </class>
</hibernate-mapping>
</code>```

Error:

```<code>Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/BiddingSystem/domain/Student.hbm.xml
[WARN] /biddingsystem/greet
java.lang.ExceptionInInitializerError
    at com.BiddingSystem.server.HibernateUtil.<clinit>(HibernateUtil.java:16)
    at com.BiddingSystem.server.GreetingServiceImpl.<init>(GreetingServiceImpl.java:33)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at org.mortbay.jetty.servlet.Holder.newInstance(Holder.java:153)
    at org.mortbay.jetty.servlet.ServletHolder.getServlet(ServletHolder.java:339)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:463)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:324)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/BiddingSystem/domain/Student.hbm.xml
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:671)
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1679)
    at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1647)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1626)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1600)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1520)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1506)
    at com.BiddingSystem.server.HibernateUtil.<clinit>(HibernateUtil.java:12)
    ... 26 more
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from invalid mapping
    at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:604)
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:668)
    ... 33 more
Caused by: org.xml.sax.SAXParseException: The content of element type "list" must match "(meta*,subselect?,cache?,synchronize*,comment?,key,(index|list-index),(element|one-to-many|many-to-many|composite-element|many-to-any),loader?,sql-insert?,sql-update?,sql-delete?,sql-delete-all?,filter*)".
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleEndElement(XMLDTDValidator.java:2017)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.endElement(XMLDTDValidator.java:901)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1782)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2938)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.dom4j.io.SAXReader.read(SAXReader.java:465)
    at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:601)
    ... 34 more
[WARN] Nested in java.lang.ExceptionInInitializerError:
org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/BiddingSystem/domain/Student.hbm.xml
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:671)
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1679)
    at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1647)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1626)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1600)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1520)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1506)
    at com.BiddingSystem.server.HibernateUtil.<clinit>(HibernateUtil.java:12)
    at com.BiddingSystem.server.GreetingServiceImpl.<init>(GreetingServiceImpl.java:33)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at org.mortbay.jetty.servlet.Holder.newInstance(Holder.java:153)
    at org.mortbay.jetty.servlet.ServletHolder.getServlet(ServletHolder.java:339)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:463)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:324)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from invalid mapping
    at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:604)
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:668)
    ... 33 more
Caused by: org.xml.sax.SAXParseException: The content of element type "list" must match "(meta*,subselect?,cache?,synchronize*,comment?,key,(index|list-index),(element|one-to-many|many-to-many|composite-element|many-to-any),loader?,sql-insert?,sql-update?,sql-delete?,sql-delete-all?,filter*)".
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleEndElement(XMLDTDValidator.java:2017)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.endElement(XMLDTDValidator.java:901)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1782)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2938)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.dom4j.io.SAXReader.read(SAXReader.java:465)
    at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:601)
</code>```

答:
You need to use a Set rather than a List. To map a List you need an additional column which specifies the index within the list each member is present at (an  or  element).

In my experience, it's best to avoid Hibernate's List-mapping support.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to make a many to many example with hibernate using java List. My codes are as follows, I am getting some erros. If someone can help me to solve this, it would be great

A Student can take many courses
A course can be taken by many students

                     Student ---->STUDENT_COURSE<-----Course

Student Class:

public class Student implements java.io.Serializable
{
    private long studentId;
    private String studentName;
    private List<Course> courses = new LinkedList<Course>();
        //other getters and setters

}

Course Class:

public class Course implements java.io.Serializable {

    private long courseId;
    private String courseName;
    private List <Student> Stu = new LinkedList <Student>();
        //other getters and setters
}

Course Mapping File:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.BiddingSystem.domain.Course" table="COURSE">
        <id name="courseId" type="long">
            <column name="COURSEID" />
            <generator class="native" />
        </id>
        <property name="courseName" type="java.lang.String">
            <column name="COURSENAME" />
        </property>
        <list name="Stu"  table="STUDENT_COURSE">
            <key>
                <column name="COURSEID" />
            </key>
            <many-to-many column="STUDENTID"  class="com.BiddingSystem.domain.Student" />
        </list>
    </class>
</hibernate-mapping>

Student Mapping File:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.BiddingSystem.domain.Student" table="STUDENT">
        <id name="studentId" type="long">
            <column name="STUDENTID" />
            <generator class="native" />
        </id>
        <property name="studentName" type="java.lang.String">
            <column name="STUDENTNAME" />
        </property>
        <list name="courses"  table="STUDENT_COURSE">
            <key>
                <column name="STUDENTID" />
            </key>
            <many-to-many column="COURSEID" class="com.BiddingSystem.domain.Course" />
        </list>
    </class>
</hibernate-mapping>

Error:

Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/BiddingSystem/domain/Student.hbm.xml
[WARN] /biddingsystem/greet
java.lang.ExceptionInInitializerError
    at com.BiddingSystem.server.HibernateUtil.<clinit>(HibernateUtil.java:16)
    at com.BiddingSystem.server.GreetingServiceImpl.<init>(GreetingServiceImpl.java:33)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at org.mortbay.jetty.servlet.Holder.newInstance(Holder.java:153)
    at org.mortbay.jetty.servlet.ServletHolder.getServlet(ServletHolder.java:339)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:463)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:324)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/BiddingSystem/domain/Student.hbm.xml
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:671)
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1679)
    at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1647)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1626)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1600)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1520)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1506)
    at com.BiddingSystem.server.HibernateUtil.<clinit>(HibernateUtil.java:12)
    ... 26 more
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from invalid mapping
    at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:604)
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:668)
    ... 33 more
Caused by: org.xml.sax.SAXParseException: The content of element type "list" must match "(meta*,subselect?,cache?,synchronize*,comment?,key,(index|list-index),(element|one-to-many|many-to-many|composite-element|many-to-any),loader?,sql-insert?,sql-update?,sql-delete?,sql-delete-all?,filter*)".
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleEndElement(XMLDTDValidator.java:2017)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.endElement(XMLDTDValidator.java:901)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1782)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2938)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.dom4j.io.SAXReader.read(SAXReader.java:465)
    at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:601)
    ... 34 more
[WARN] Nested in java.lang.ExceptionInInitializerError:
org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/BiddingSystem/domain/Student.hbm.xml
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:671)
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1679)
    at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1647)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1626)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1600)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1520)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1506)
    at com.BiddingSystem.server.HibernateUtil.<clinit>(HibernateUtil.java:12)
    at com.BiddingSystem.server.GreetingServiceImpl.<init>(GreetingServiceImpl.java:33)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at org.mortbay.jetty.servlet.Holder.newInstance(Holder.java:153)
    at org.mortbay.jetty.servlet.ServletHolder.getServlet(ServletHolder.java:339)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:463)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:324)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from invalid mapping
    at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:604)
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:668)
    ... 33 more
Caused by: org.xml.sax.SAXParseException: The content of element type "list" must match "(meta*,subselect?,cache?,synchronize*,comment?,key,(index|list-index),(element|one-to-many|many-to-many|composite-element|many-to-any),loader?,sql-insert?,sql-update?,sql-delete?,sql-delete-all?,filter*)".
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleEndElement(XMLDTDValidator.java:2017)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.endElement(XMLDTDValidator.java:901)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1782)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2938)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.dom4j.io.SAXReader.read(SAXReader.java:465)
    at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:601)


问:
Call by name vs call by value in Scala, clarification needed
As I understand it, in Scala, a function may be called either

by-value or

by-name

For example, given the following declarations, do we know how the function will be called?

Declaration:

```<code>def  f (x:Int, y:Int) = x;
</code>```

Call

```<code>f (1,2)
f (23+55,5)
f (12+3, 44*11)
</code>```

What are the rules please?

答:
See this:

```<code>    object NameVsVal extends App {

  def mul(x: Int, y: => Int) : Int = {
    println("mul")
    x * y
  }
  def add(x: Int, y: Int): Int = {
    println("add")
    x + y
  }
  println(mul(3, add(2, 1)))
}
</code>```

y: => Int is call by name. What is passed as call by name is add(2, 1). This will be evaluated lazily. So output on console will be "mul" followed by "add", although add seems to be called first. Call by name acts as kind of passing a function pointer.

Now change from y: => Int to y: Int. Console will show "add" followed by "mul"! Usual way of evaluation.

Body:
As I understand it, in Scala, a function may be called either

by-value or

by-name

For example, given the following declarations, do we know how the function will be called?

Declaration:

def  f (x:Int, y:Int) = x;

Call

f (1,2)
f (23+55,5)
f (12+3, 44*11)

What are the rules please?

Body:
See this:

    object NameVsVal extends App {

  def mul(x: Int, y: => Int) : Int = {
    println("mul")
    x * y
  }
  def add(x: Int, y: Int): Int = {
    println("add")
    x + y
  }
  println(mul(3, add(2, 1)))
}

y: => Int is call by name. What is passed as call by name is add(2, 1). This will be evaluated lazily. So output on console will be "mul" followed by "add", although add seems to be called first. Call by name acts as kind of passing a function pointer.

Now change from y: => Int to y: Int. Console will show "add" followed by "mul"! Usual way of evaluation.


问:
How to make css reverse animation?
I want to animate a DIV element and change it's background and text color. Then change it back to original colors. So CSS below sets background green and text color white. How do I animate switching colors back, e.g. white background and black text? So first 2 seconds it's changing to green/white and next 2 seconds white/black.</p>

```<code>.myClass {
    background-color:           #4caf50;
    -webkit-animation-name:     anim1;  /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: 2s;     /* Safari 4.0 - 8.0 */
    animation-name:             anim1;
    animation-duration:         2s;
    color:                      white;
    font-weight:                bold;
}

@-webkit-keyframes anim1 {
    from {background-color: white;}
    to {background-color: #4caf50;}
}

@keyframes anim1 {
    from {background-color: white;}
    to {background-color: #4caf50;}
}
</code>```

答:
You can Control your animation with defining percentage for it's @keyframes.
change animation duration to 4s and change background-color at 50% and change it back again.

try this:

```<code>.myClass {
background-color:           #4caf50;
-webkit-animation-name:     anim1;  /* Safari 4.0 - 8.0 */
-webkit-animation-duration: 4s;     /* Safari 4.0 - 8.0 */
animation-name:             anim1;
animation-duration:         4s;
color:                      white;
font-weight:                bold;
}

@-webkit-keyframes anim1 {
0% {background-color: white;}
50% {background-color: #4caf50;}
100% {background-color: white;}
}

@keyframes anim1 {
0% {background-color: white;}
50% {background-color: #4caf50;}
100% {background-color: white;}
}
</code>```

Title: How to make css reverse animation?

Body:
I want to animate a DIV element and change it's background and text color. Then change it back to original colors. So CSS below sets background green and text color white. How do I animate switching colors back, e.g. white background and black text? So first 2 seconds it's changing to green/white and next 2 seconds white/black.

.myClass {
    background-color:           #4caf50;
    -webkit-animation-name:     anim1;  /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: 2s;     /* Safari 4.0 - 8.0 */
    animation-name:             anim1;
    animation-duration:         2s;
    color:                      white;
    font-weight:                bold;
}

@-webkit-keyframes anim1 {
    from {background-color: white;}
    to {background-color: #4caf50;}
}

@keyframes anim1 {
    from {background-color: white;}
    to {background-color: #4caf50;}
}

Body:
You can Control your animation with defining percentage for it's @keyframes.
change animation duration to 4s and change background-color at 50% and change it back again.

try this:

.myClass {
background-color:           #4caf50;
-webkit-animation-name:     anim1;  /* Safari 4.0 - 8.0 */
-webkit-animation-duration: 4s;     /* Safari 4.0 - 8.0 */
animation-name:             anim1;
animation-duration:         4s;
color:                      white;
font-weight:                bold;
}

@-webkit-keyframes anim1 {
0% {background-color: white;}
50% {background-color: #4caf50;}
100% {background-color: white;}
}

@keyframes anim1 {
0% {background-color: white;}
50% {background-color: #4caf50;}
100% {background-color: white;}
}


问:
Getting days since last occurence in Pandas DataFrame?
Let's say I have a Pandas DataFrame df:

```<code>Date      Value
01/01/17  0
01/02/17  0
01/03/17  1
01/04/17  0
01/05/17  0
01/06/17  0
01/07/17  1
01/08/17  0
01/09/17  0
</code>```

For each row, I want to efficiently calculate the days since the last occurence of Value=1.

So that df:

```<code>Date      Value    Last_Occurence
01/01/17  0        NaN
01/02/17  0        NaN
01/03/17  1        0
01/04/17  0        1
01/05/17  0        2
01/06/17  0        3
01/07/17  1        0
01/08/17  0        1
01/09/17  0        2
</code>```

I could do a loop:

```<code>for i in range(0, len(df)):
    last = np.where(df.loc[0:i,'Value']==1)
    df.loc[i, 'Last_Occurence'] = i-last
</code>```

But it seems very inefficient for extremely large data sets and probably isn't right anyway.

答:
You can use argmax:

```<code>df.apply(lambda x: np.argmax(df.iloc[x.name::-1].Value.tolist()),axis=1)
Out[85]:
0    0
1    0
2    0
3    1
4    2
5    3
6    0
7    1
8    2
dtype: int64
</code>```

If you have to have nan for the first 2 rows, use:

```<code>df.apply(lambda x: np.argmax(df.iloc[x.name::-1].Value.tolist()) \
                   if 1 in df.iloc[x.name::-1].Value.values \
                   else np.nan,axis=1)
Out[86]:
0    NaN
1    NaN
2    0.0
3    1.0
4    2.0
5    3.0
6    0.0
7    1.0
8    2.0
dtype: float64
</code>```

Body:
Let's say I have a Pandas DataFrame df:

Date      Value
01/01/17  0
01/02/17  0
01/03/17  1
01/04/17  0
01/05/17  0
01/06/17  0
01/07/17  1
01/08/17  0
01/09/17  0

For each row, I want to efficiently calculate the days since the last occurence of Value=1.

So that df:

Date      Value    Last_Occurence
01/01/17  0        NaN
01/02/17  0        NaN
01/03/17  1        0
01/04/17  0        1
01/05/17  0        2
01/06/17  0        3
01/07/17  1        0
01/08/17  0        1
01/09/17  0        2

I could do a loop:

for i in range(0, len(df)):
    last = np.where(df.loc[0:i,'Value']==1)
    df.loc[i, 'Last_Occurence'] = i-last

But it seems very inefficient for extremely large data sets and probably isn't right anyway.

Body:
You can use argmax:

df.apply(lambda x: np.argmax(df.iloc[x.name::-1].Value.tolist()),axis=1)
Out[85]:
0    0
1    0
2    0
3    1
4    2
5    3
6    0
7    1
8    2
dtype: int64

If you have to have nan for the first 2 rows, use:

df.apply(lambda x: np.argmax(df.iloc[x.name::-1].Value.tolist()) \
                   if 1 in df.iloc[x.name::-1].Value.values \
                   else np.nan,axis=1)
Out[86]:
0    NaN
1    NaN
2    0.0
3    1.0
4    2.0
5    3.0
6    0.0
7    1.0
8    2.0
dtype: float64


问:
Why Python tries to compute some calculations in multiprocessing in advance
I am using Ubuntu 17.04 64-bit with processor-Intel® Core™ i7-7500U CPU @ 2.70GHz × 4 and 16gb of RAM.

So when I run this program, it uses a single core instead of using all the 4 cores.

```<code>import time
import multiprocessing

def boom1(*args):
    print(5**10000000000)

def boom2(*args):
    print(5**10000000000)

def boom3(*args):
    print(5**10000000000)

def boom4(*args):
    print(5**10000000000)

if __name__=="__main__":
    array = []
    p1 = multiprocessing.Process(target=boom1, args=(array,))
    p2 = multiprocessing.Process(target=boom2, args=(array,))
    p3 = multiprocessing.Process(target=boom3, args=(array,))
    p4 = multiprocessing.Process(target=boom4, args=(array,))

    p1.start()
    p2.start()
    p3.start()
    p4.start()

    p1.join()
    p2.join()
    p3.join()
    p4.join()

    print('Done')
</code>```

Now if I print some low power of 10 in each function:

```<code>print(5 ** 10000000)
</code>```

Now for small duration of time, a single core is processing 100% and then all 4 cores are performing 100%.
Why is this so? Shouldn't it start with all cores performing 100%.

What I had come to know was that python performs some operation before itself and hence was doing that from a single core. If it is so then what is the point of python being an interpreted language or am I missing something?does

答:
I believe the previous answers are correct, but may not fully explain your observations.  As others have pointed out, that the single processor time you're seeing is the time that the interpreter is spending to calculate the value of the exponential expression.  Because you're using integers, and Python can do arbitrarily long integers, this takes quite awhile, probably exponential in terms of the number of 0's in your exponent.  In the first case, the calculation is taking so long that it appears to not get past that (I don't know if you ran to completion, or if your machine could even do it without running out of memory).

In the second case, you've removed enough zeros so that it can calculate it (single threaded interpreter) then proceed to print it (in parallel).  However long that took, it will probably take at least 1000 times longer to do the first case.

Body:
I am using Ubuntu 17.04 64-bit with processor-Intel® Core™ i7-7500U CPU @ 2.70GHz × 4 and 16gb of RAM.

So when I run this program, it uses a single core instead of using all the 4 cores.

import time
import multiprocessing

def boom1(*args):
    print(5**10000000000)

def boom2(*args):
    print(5**10000000000)

def boom3(*args):
    print(5**10000000000)

def boom4(*args):
    print(5**10000000000)

if __name__=="__main__":
    array = []
    p1 = multiprocessing.Process(target=boom1, args=(array,))
    p2 = multiprocessing.Process(target=boom2, args=(array,))
    p3 = multiprocessing.Process(target=boom3, args=(array,))
    p4 = multiprocessing.Process(target=boom4, args=(array,))

    p1.start()
    p2.start()
    p3.start()
    p4.start()

    p1.join()
    p2.join()
    p3.join()
    p4.join()

    print('Done')

Now if I print some low power of 10 in each function:

print(5 ** 10000000)

Now for small duration of time, a single core is processing 100% and then all 4 cores are performing 100%.
Why is this so? Shouldn't it start with all cores performing 100%.

What I had come to know was that python performs some operation before itself and hence was doing that from a single core. If it is so then what is the point of python being an interpreted language or am I missing something?does


答:
This is very simple example.

This works in Python 3.2 and greater.

```<code>import urllib.request
with urllib.request.urlopen("http://www.apple.com") as url:
    r = url.read()
print(r)
</code>```

For reference, go through this question. Urlopen attribute error.

Title: How to read in url in python and then print each URL on the website?

Body:
I am trying to figure out how to only read in each line that is a url from a website, every time I run the code I get the error:

AttributeError: module 'urllib' has no attribute 'urlopen'

My code is below

import os
import subprocess
import urllib

datasource = urllib.urlopen("www.google.com")

while 1:
        line = datasource.readline()
        if line == "": break
        if (line.find("www") > -1) :
                print (line)

li = ['www.apple.com', 'www.google.com']
os.chdir('..')
os.chdir('..')
os.chdir('..')
os.chdir('Program Files (x86)\\LinkChecker')

for s in li:
    os.system('Start .\linkchecker ' + s)

Body:
This is very simple example.

This works in Python 3.2 and greater.

import urllib.request
with urllib.request.urlopen("http://www.apple.com") as url:
    r = url.read()
print(r)

For reference, go through this question. Urlopen attribute error.


问:
Is importing headers bad?
What are your opinions on #importing header files?

If I import:

```<code>#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
</code>```

and many more headers, and only use them once in a while, is it a waste?  Does it slow down my app in any way?  More importantly, does it increase the size of my app?

Thanks.

答:
Nope, it doesn't do any of those things.

Headers are used by the compiler to determine how to find where various types and classes are defined. Extraneous #imports do--kinda sorta--make the process of compiling your app slower by some unmeasurably small amount.

But the resulting binary application will not be any different in size or execution speed if you have redundant headers imported in your files.

Title: Is importing headers bad?

Body:
What are your opinions on #importing header files?

If I import:

#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

and many more headers, and only use them once in a while, is it a waste?  Does it slow down my app in any way?  More importantly, does it increase the size of my app?

Thanks.


问:
Dynamic Mongoose Schema based on property
I have the following user schema (where all distinct properties of different user types are consolidated):

```<code>var UserSchema = new mongoose.Schema({
  status: String,
  firstName: String,
  lastName: String,
  address: Object,
  email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
  organization: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Organization' }],
  phone: {type: Number, unique: true, required: true, required: [true, "can't be blank"]},
  role: String,
  hash: String,
  salt: String,
  deliverySchedule:  [{type: String, required: true}]

}
</code>```

"Common" Schema (what all user types share in common):

```<code>var UserSchema = new mongoose.Schema({
  status: String,
  firstName: String,
  lastName: String,
  email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
  phone: {type: Number, unique: true, required: true, required: [true, "can't be blank"]},
  role: String,
  hash: String,
  salt: String
}
</code>```

Role = "Customer":

```<code>  address: [{type: Object, required: true}]
</code>```

Role = "DeliveryMan":

```<code>      deliverySchedule:  [{type: String, required: true}]
      organization: [{ type: mongoose.Schema.Types.ObjectId, required: true,
ref: 'Organization' }],
</code>```

Role = "Seller":

```<code>      organization: [{ type: mongoose.Schema.Types.ObjectId, required: true,
ref: 'Organization' }],
</code>```

I would like to add (and REQUIRE if possible) some fields to the "common" schema based on the user's role. However, I want to store them in the same collection.

How can I add a method to my models/Users.js to add properties to the schema based on "user.role"

答:
Make require validation optional for each role dependent fields.

```<code>var UserSchema = new mongoose.Schema({
  status: String,
  firstName: String,
  lastName: String,
  email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
  phone: {type: Number, unique: true, required: true, required: [true, "can't be blank"]},
  role: {type: String, enum: ['Customer', 'DeliveryMan', 'Seller'], required: true},
  address: {type: [Object],  required: isRequired("address")},
  deliverySchedule: {type: [String], required: isRequired("deliverySchedule")},
  organization: { type: [mongoose.Schema.Types.ObjectId], ref: 'Organization', required: isRequired("organization")},
  hash: String,
  salt: String
});

function isRequired(field){
    return function(){
        if(field == "address"){
            return this.role === "Customer"
        }
        else if(field == "deliverySchedule"){
            return this.role === "DeliveryMan"
        }
        else if(field == "organization"){
            return this.role === "Seller" || this.role === "DeliveryMan"
        }
    }
};
</code>```

Body:
I have the following user schema (where all distinct properties of different user types are consolidated):

var UserSchema = new mongoose.Schema({
  status: String,
  firstName: String,
  lastName: String,
  address: Object,
  email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
  organization: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Organization' }],
  phone: {type: Number, unique: true, required: true, required: [true, "can't be blank"]},
  role: String,
  hash: String,
  salt: String,
  deliverySchedule:  [{type: String, required: true}]

}

"Common" Schema (what all user types share in common):

var UserSchema = new mongoose.Schema({
  status: String,
  firstName: String,
  lastName: String,
  email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
  phone: {type: Number, unique: true, required: true, required: [true, "can't be blank"]},
  role: String,
  hash: String,
  salt: String
}

Role = "Customer":

  address: [{type: Object, required: true}]

Role = "DeliveryMan":

      deliverySchedule:  [{type: String, required: true}]
      organization: [{ type: mongoose.Schema.Types.ObjectId, required: true,
ref: 'Organization' }],

Role = "Seller":

      organization: [{ type: mongoose.Schema.Types.ObjectId, required: true,
ref: 'Organization' }],

I would like to add (and REQUIRE if possible) some fields to the "common" schema based on the user's role. However, I want to store them in the same collection.

How can I add a method to my models/Users.js to add properties to the schema based on "user.role"

Body:
Make require validation optional for each role dependent fields.

var UserSchema = new mongoose.Schema({
  status: String,
  firstName: String,
  lastName: String,
  email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
  phone: {type: Number, unique: true, required: true, required: [true, "can't be blank"]},
  role: {type: String, enum: ['Customer', 'DeliveryMan', 'Seller'], required: true},
  address: {type: [Object],  required: isRequired("address")},
  deliverySchedule: {type: [String], required: isRequired("deliverySchedule")},
  organization: { type: [mongoose.Schema.Types.ObjectId], ref: 'Organization', required: isRequired("organization")},
  hash: String,
  salt: String
});

function isRequired(field){
    return function(){
        if(field == "address"){
            return this.role === "Customer"
        }
        else if(field == "deliverySchedule"){
            return this.role === "DeliveryMan"
        }
        else if(field == "organization"){
            return this.role === "Seller" || this.role === "DeliveryMan"
        }
    }
};


问:
Knitr generating very large html files
I am trying to use Knitr to write simple text-only html pages, but the file sizes are extremely large - 700KB for a 1 line RMarkdown.  I am on R 3.4.0, and R Studio 1.0.143

For example, the following RMarkdown file generates a 695 kb file.  When I look at the source, that is because there is a huge amount of base 64 code under the script tag.  Is there anything that can be done to make the file size more compact, say a couple of KBs that I would expect it to be

(eg script src="data:application/x-javascript;base64,LyohIGpRdW...and this goes on and on forever)

```<code>---
title: "This is  a test"
author: "Mukul Pareek"
date: "June 7, 2017"
output: html_document
---

## This is a test file which when knit to html is 695KB
</code>```

答:
The key to reduce the HTML file size is to set theme: null, which means to get rid of the giant Twitter Bootstrap styles. Below are a few examples:

```<code>---
title: "This is  a test"
author: "Mukul Pareek"
date: "June 7, 2017"
output:
  html_document:
    theme: null
  html_vignette: default
  prettydoc::html_pretty: default
---

## This is a test file which when knit to html is 695KB
</code>```

html_document(theme = NULL) returns a 44kb file; html_vignette returns 6.1kb; prettydoc::html_pretty returns 63.7kb (you need to install the prettydoc package). If you want a "flashy" style, I think prettydoc has achieved a great balance between styles and file sizes; otherwise you have to bear with those "vanilla" styles.

Title: Knitr generating very large html files

Body:
I am trying to use Knitr to write simple text-only html pages, but the file sizes are extremely large - 700KB for a 1 line RMarkdown.  I am on R 3.4.0, and R Studio 1.0.143

For example, the following RMarkdown file generates a 695 kb file.  When I look at the source, that is because there is a huge amount of base 64 code under the script tag.  Is there anything that can be done to make the file size more compact, say a couple of KBs that I would expect it to be

(eg script src="data:application/x-javascript;base64,LyohIGpRdW...and this goes on and on forever)

---
title: "This is  a test"
author: "Mukul Pareek"
date: "June 7, 2017"
output: html_document
---

## This is a test file which when knit to html is 695KB

Body:
The key to reduce the HTML file size is to set theme: null, which means to get rid of the giant Twitter Bootstrap styles. Below are a few examples:

---
title: "This is  a test"
author: "Mukul Pareek"
date: "June 7, 2017"
output:
  html_document:
    theme: null
  html_vignette: default
  prettydoc::html_pretty: default
---

## This is a test file which when knit to html is 695KB

html_document(theme = NULL) returns a 44kb file; html_vignette returns 6.1kb; prettydoc::html_pretty returns 63.7kb (you need to install the prettydoc package). If you want a "flashy" style, I think prettydoc has achieved a great balance between styles and file sizes; otherwise you have to bear with those "vanilla" styles.


问:
OpenEdge ABL / Progress 4GL Query
I need help writing this progress query:
    find first a no-lock
      where a.a = variable
      and   a.b = variable2
      and   a.c = variable3
      and ((a.d <> variable4
      and   a.e <> variable5
      and   a.f <> variable6)
    /* this "or in" is just sudecode for what I want it to do */
      or in (first b no-lock where b.a = variable
      and (b.b = variable7 or b.b = variable8 no-error)))
      no-error.`

The "or in" is the thing I'm having trouble with.

答:
I believe the statement you are looking for is 'can-find'.</p>

```<code>... or can-find(first b where b.a = a.a ...
</code>```

Title: OpenEdge ABL / Progress 4GL Query

Body:
I believe the statement you are looking for is 'can-find'.

... or can-find(first b where b.a = a.a ...


问:
Unexpected behavior for stderr redirection in bash
My understanding of stdout/stderr is that a script can log to stderr, and produce 'useful' output in stdout, which will be piped or captured by the calling process if needed.

In practice, this doesn't work the way I thought it would.

```<code>➜ cat test.sh
echo diagnostic blah blah 1>&2
echo result
</code>```

My understanding is that if I do echo $(./test.sh), I should just get 'result', since 'diagnostic blah blah' was sent to stderr. However, I get:

```<code>➜ echo $(./test.sh)
diagnostic blah blah
result
</code>```

This works correctly which shows that the redirection to stderr is actually working:

```<code>➜ echo $(./test.sh 2>/dev/null)
result
</code>```

So I guess my understanding of how output is processed in shell scripts is wrong. What am I missing?

As another example, I wouldn't expect this to work:

```<code>➜ ./test.sh | grep diagnostic
diagnostic blah blah
</code>```

答:
Charles Duffy is right - the test.sh script works as expected.

The root cause of the initial problem I was investigating is simpler - I was redirecting all log outputs from my script to stderr, but I was not redirecting output from additional commands in the script (in my case pip install ...)

Body:
My understanding of stdout/stderr is that a script can log to stderr, and produce 'useful' output in stdout, which will be piped or captured by the calling process if needed.

In practice, this doesn't work the way I thought it would.

➜ cat test.sh
echo diagnostic blah blah 1>&2
echo result

My understanding is that if I do echo $(./test.sh), I should just get 'result', since 'diagnostic blah blah' was sent to stderr. However, I get:

➜ echo $(./test.sh)
diagnostic blah blah
result

This works correctly which shows that the redirection to stderr is actually working:

➜ echo $(./test.sh 2>/dev/null)
result

So I guess my understanding of how output is processed in shell scripts is wrong. What am I missing?

As another example, I wouldn't expect this to work:

➜ ./test.sh | grep diagnostic
diagnostic blah blah


问:
Out of memory with jack
I'm testing the new compilation chain to start using lambdas.

My build.gradle file contains:

```<code>android {
    ...
    compileSdkVersion 23
    buildToolsVersion "24 rc3"

    dexOptions {
        jumboMode true
    }

    defaultConfig {
        applicationId "my.app.id"
        minSdkVersion 14
        targetSdkVersion 23
        multiDexEnabled true

        jackOptions {
            enabled true
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
</code>```

I'm using Android Studio 2.1.1.

When I build the app the compilation takes ages and then ends with an Out of memory error:

Execution failed for task
  ':app:compileAppNameJavaWithJack'.

java.lang.RuntimeException: java.lang.OutOfMemoryError: GC overhead limit exceeded

Sometimes the compilation just hangs when performing:

```<code>:app:compileMyAppNameDebugJavaWithJack
</code>```

I found in the troubleshooting section here a way to fix it but I can't find the .jack file with the configuration.
In this bug report someone mentioned that the file could have been renamed to jack.settings but I can't find that file either.

Do you know where the file is? Do you know how to fix the Out of memory error?

答:
See also this question, which solved this problem for me:

Android source code compile error: "Try increasing heap size with java option '-Xmx<size>'"

I find that jack's virtual size is around ~8G by the time my build is done.

Title: Out of memory with jack

Body:
I'm testing the new compilation chain to start using lambdas.

My build.gradle file contains:

android {
    ...
    compileSdkVersion 23
    buildToolsVersion "24 rc3"

    dexOptions {
        jumboMode true
    }

    defaultConfig {
        applicationId "my.app.id"
        minSdkVersion 14
        targetSdkVersion 23
        multiDexEnabled true

        jackOptions {
            enabled true
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

I'm using Android Studio 2.1.1.

When I build the app the compilation takes ages and then ends with an Out of memory error:

Execution failed for task
  ':app:compileAppNameJavaWithJack'.

java.lang.RuntimeException: java.lang.OutOfMemoryError: GC overhead limit exceeded

Sometimes the compilation just hangs when performing:

:app:compileMyAppNameDebugJavaWithJack

I found in the troubleshooting section here a way to fix it but I can't find the .jack file with the configuration.
In this bug report someone mentioned that the file could have been renamed to jack.settings but I can't find that file either.

Do you know where the file is? Do you know how to fix the Out of memory error?


问:
Pandas: changing the row indices to column indices. Or Vice versa
```<code>import pandas as pd
df = pd.DataFrame(data={'start':[1,2,3],'zone':['a','b','c']});
df['end']=[4,5,6]
df.set_index('zone',drop=True,inplace=True,append=False)
print(df)

      start  end
zone
a         1    4
b         2    5
c         3    6
</code>```

I would like to modify this dataframe to become:

```<code>zone  a              b            c
      start  end     start  end   start  end
      1        4     2      5     3      6
</code>```

By changing the row indices to column indices. I need this because I want to melt the dataframe later, so it would become a long table. But I do not know how to melt the row index along with the column index. But getting this output would allow me to simply use:

```<code>pd.melt(df)
</code>```

To get the long table.
If there is a way to change the column indices to row indices, I could then skip the step where I change the row indices to column indices, and get the long table straight away.

Please help.

答:
Reconstruct from array manipulation and multi index construction.</p>

```<code>pd.DataFrame(
    df.values.reshape(1, -1),
    columns=pd.MultiIndex.from_product([df.index, df.columns])
)

      a         b         c
  start end start end start end
0     1   4     2   5     3   6
</code>```

Body:
import pandas as pd
df = pd.DataFrame(data={'start':[1,2,3],'zone':['a','b','c']});
df['end']=[4,5,6]
df.set_index('zone',drop=True,inplace=True,append=False)
print(df)

      start  end
zone
a         1    4
b         2    5
c         3    6

I would like to modify this dataframe to become:

zone  a              b            c
      start  end     start  end   start  end
      1        4     2      5     3      6

By changing the row indices to column indices. I need this because I want to melt the dataframe later, so it would become a long table. But I do not know how to melt the row index along with the column index. But getting this output would allow me to simply use:

pd.melt(df)

To get the long table.
If there is a way to change the column indices to row indices, I could then skip the step where I change the row indices to column indices, and get the long table straight away.

Please help.

Body:
Reconstruct from array manipulation and multi index construction.

pd.DataFrame(
    df.values.reshape(1, -1),
    columns=pd.MultiIndex.from_product([df.index, df.columns])
)

      a         b         c
  start end start end start end
0     1   4     2   5     3   6