问:
Installing XGBoost on EC2
I am trying to install XGBoost on a EC2 instance and continually get the following error after trying "pip install xgboost":

```<code>> Collecting xgboost
  Using cached xgboost-0.6a2.tar.gz
    Complete output from command python setup.py egg_info:
    rm -f -rf build build_plugin lib bin *~ */*~ */*/*~ */*/*/*~ */*.o */*/*.o */*/*/*.o xgboost
    g++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/logging.o src/logging.cc >build/logging.d
    g++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/learner.o src/learner.cc >build/learner.d
    /bin/sh: g++: command not found
    make: *** [build/logging.o] Error 127
    make: *** Waiting for unfinished jobs....
    g++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/common/common.o src/common/common.cc >build/common/common.d
    /bin/sh: g++: command not found
    make: *** [build/learner.o] Error 127
    /bin/sh: g++: command not found
    make: *** [build/common/common.o] Error 127
    -----------------------------
    Building multi-thread xgboost failed
    Start to build single-thread xgboost
    rm -f -rf build build_plugin lib bin *~ */*~ */*/*~ */*/*/*~ */*.o */*/*.o */*/*/*.o xgboost
    g++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/logging.o src/logging.cc >build/logging.d
    g++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/learner.o src/learner.cc >build/learner.d
    /bin/sh: g++: command not found
    make: *** [build/logging.o] Error 127
    make: *** Waiting for unfinished jobs....
    g++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/common/common.o src/common/common.cc >build/common/common.d
    /bin/sh: g++: command not found
    make: *** [build/learner.o] Error 127
    /bin/sh: g++: command not found
    make: *** [build/common/common.o] Error 127
    Successfully build single-thread xgboost
    If you want multi-threaded version
    See additional instructions in doc/build.md
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-TkrTN6/xgboost/setup.py", line 29, in <module>
        LIB_PATH = libpath['find_lib_path']()
      File "/tmp/pip-build-TkrTN6/xgboost/xgboost/libpath.py", line 45, in find_lib_path
        'List of candidates:\n' + ('\n'.join(dll_path)))
    __builtin__.XGBoostLibraryNotFound: Cannot find XGBoost Libarary in the candicate path, did you install compilers and run build.sh in root path?
    List of candidates:
    /tmp/pip-build-TkrTN6/xgboost/xgboost/libxgboost.so
    /tmp/pip-build-TkrTN6/xgboost/xgboost/../../lib/libxgboost.so
    /tmp/pip-build-TkrTN6/xgboost/xgboost/./lib/libxgboost.so

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-TkrTN6/xgboost/
</code>```

I am using the latest version of Anaconda (Linux). I have tried using miniconda and installing all the need packages with no success.  Additionally, I have tried all of the suggestions that I found here.

Any suggestions / solutions are much appreciated.

答:
You are missing the g++ compiler.

You did not mention which Linux that you are running.

Amazon Linux:

yum install make glibc-devel gcc patch

Title: Installing XGBoost on EC2

Body:
I am trying to install XGBoost on a EC2 instance and continually get the following error after trying "pip install xgboost":

> Collecting xgboost
  Using cached xgboost-0.6a2.tar.gz
    Complete output from command python setup.py egg_info:
    rm -f -rf build build_plugin lib bin *~ */*~ */*/*~ */*/*/*~ */*.o */*/*.o */*/*/*.o xgboost
    g++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/logging.o src/logging.cc >build/logging.d
    g++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/learner.o src/learner.cc >build/learner.d
    /bin/sh: g++: command not found
    make: *** [build/logging.o] Error 127
    make: *** Waiting for unfinished jobs....
    g++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/common/common.o src/common/common.cc >build/common/common.d
    /bin/sh: g++: command not found
    make: *** [build/learner.o] Error 127
    /bin/sh: g++: command not found
    make: *** [build/common/common.o] Error 127
    -----------------------------
    Building multi-thread xgboost failed
    Start to build single-thread xgboost
    rm -f -rf build build_plugin lib bin *~ */*~ */*/*~ */*/*/*~ */*.o */*/*.o */*/*/*.o xgboost
    g++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/logging.o src/logging.cc >build/logging.d
    g++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/learner.o src/learner.cc >build/learner.d
    /bin/sh: g++: command not found
    make: *** [build/logging.o] Error 127
    make: *** Waiting for unfinished jobs....
    g++ -std=c++0x -Wall -O3 -msse2  -Wno-unknown-pragmas -funroll-loops -Iinclude   -Idmlc-core/include -Irabit/include -fPIC -fopenmp -MM -MT build/common/common.o src/common/common.cc >build/common/common.d
    /bin/sh: g++: command not found
    make: *** [build/learner.o] Error 127
    /bin/sh: g++: command not found
    make: *** [build/common/common.o] Error 127
    Successfully build single-thread xgboost
    If you want multi-threaded version
    See additional instructions in doc/build.md
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-TkrTN6/xgboost/setup.py", line 29, in <module>
        LIB_PATH = libpath['find_lib_path']()
      File "/tmp/pip-build-TkrTN6/xgboost/xgboost/libpath.py", line 45, in find_lib_path
        'List of candidates:\n' + ('\n'.join(dll_path)))
    __builtin__.XGBoostLibraryNotFound: Cannot find XGBoost Libarary in the candicate path, did you install compilers and run build.sh in root path?
    List of candidates:
    /tmp/pip-build-TkrTN6/xgboost/xgboost/libxgboost.so
    /tmp/pip-build-TkrTN6/xgboost/xgboost/../../lib/libxgboost.so
    /tmp/pip-build-TkrTN6/xgboost/xgboost/./lib/libxgboost.so

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-TkrTN6/xgboost/

I am using the latest version of Anaconda (Linux). I have tried using miniconda and installing all the need packages with no success.  Additionally, I have tried all of the suggestions that I found here.

Any suggestions / solutions are much appreciated.


来源: stackexchange

问:
How to move a tick label in matplotlib
I would like to move some ticks' labels horizontally along the x-axis,  without moving the corresponding ticks.

More specifically, when rotating labels with plt.setp, the centers of the labels' text stay aligned with the ticks. I would like to shift those labels to the right, so that the near ends of the labels get aligned instead as suggested on the image below.

I am aware of this post and this one, however the answers are interesting kludges rather than strict answers to the question.

my code:

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

# my fake data
dates = np.array([datetime.datetime(2000,1,1) + datetime.timedelta(days=i) for i in range(365*5)])
data = np.sin(np.arange(365*5)/365.0*2*np.pi - 0.25*np.pi) + np.random.rand(365*5) /3

# creates fig with 2 subplots
fig = plt.figure(figsize=(10.0, 6.0))
ax = plt.subplot2grid((2,1), (0, 0))
ax2 = plt.subplot2grid((2,1), (1, 0))
## plot dates
ax2.plot_date( dates, data )

# rotates labels
plt.setp( ax2.xaxis.get_majorticklabels(), rotation=-45 )

# try to shift labels to the right
ax2.xaxis.get_majorticklabels()[2].set_y(-.1)
ax2.xaxis.get_majorticklabels()[2].set_x(10**99)

plt.show()
</code>```

Strangely enough, set_y behaves as expected, but even if I set x to a fantasillion, the labels would not move by one iota.
(The use of plot_date may introduce additional confusion, but the same actually happens with plot.)

答:
Another way of doing a horizontal alignment:</p>

```<code>plt.xticks(ha='left')
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to move a tick label in matplotlib

Body:
I would like to move some ticks' labels horizontally along the x-axis,  without moving the corresponding ticks.

More specifically, when rotating labels with plt.setp, the centers of the labels' text stay aligned with the ticks. I would like to shift those labels to the right, so that the near ends of the labels get aligned instead as suggested on the image below.

I am aware of this post and this one, however the answers are interesting kludges rather than strict answers to the question.

my code:

import matplotlib.pyplot as plt
import numpy as np
import datetime

# my fake data
dates = np.array([datetime.datetime(2000,1,1) + datetime.timedelta(days=i) for i in range(365*5)])
data = np.sin(np.arange(365*5)/365.0*2*np.pi - 0.25*np.pi) + np.random.rand(365*5) /3

# creates fig with 2 subplots
fig = plt.figure(figsize=(10.0, 6.0))
ax = plt.subplot2grid((2,1), (0, 0))
ax2 = plt.subplot2grid((2,1), (1, 0))
## plot dates
ax2.plot_date( dates, data )

# rotates labels
plt.setp( ax2.xaxis.get_majorticklabels(), rotation=-45 )

# try to shift labels to the right
ax2.xaxis.get_majorticklabels()[2].set_y(-.1)
ax2.xaxis.get_majorticklabels()[2].set_x(10**99)

plt.show()

Strangely enough, set_y behaves as expected, but even if I set x to a fantasillion, the labels would not move by one iota.
(The use of plot_date may introduce additional confusion, but the same actually happens with plot.)

Body:
Another way of doing a horizontal alignment:

plt.xticks(ha='left')

ContentLicense: CC BY-SA 3.0


问:
How to parse this format of xml data?
i tried to parse data of this format of xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<root>
<list info="INFY, Jan 20 call, 40 cents or Lower" profit="60%" loss="gdh"/>
<list info="HPCL, Feb 20 PUT, 20 cents or Lower" profit="80%" loss="fgh"/>
<list info="AAPL, May 290 call, 90 cents or Lower" profit="ss" loss="20%"/>
<list info="DIA, April 105 call, 32 cents or Lower" profit="ghh" loss="20%"/>
<list info="GOOG, Aug 350 call, 47 cents or Lower" profit="100%" loss="sdgd"/>
</root>
</code>```

using this code:

```<code>Ext.regmodel('picks',{fields: ['info','profit','loss']});
alert();
var pickstore = new Ext.data.store({
                                    model: 'picks',
                                    proxy: {
                                            type: 'ajax',
                                            url: 'http://1........ksxml.xml',   //url is fine it's good and working..
                                            reader: {
                                                     type: 'xml',
                                                     record: 'list'
                                                    }
                                            },
                                    listeners: {
                                                single: true,
                                                datachanged: function(){
                                                                        pickstore.each(function(pr){
                                                                                alert(pr.get('@info'));
                                                                                });
                                                                        }
                                                }
                                   });
</code>```

pickstore.read();

i donno wats the reason but i couldnt parse even the first alert() is not displaying.

please help.....

答:
```
Ext.regModel( 'picks' ......
```

Capital M - Javascript is case sensitive

ContentLicense: CC BY-SA 2.5

Title: How to parse this format of xml data?

Body:
i tried to parse data of this format of xml:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<list info="INFY, Jan 20 call, 40 cents or Lower" profit="60%" loss="gdh"/>
<list info="HPCL, Feb 20 PUT, 20 cents or Lower" profit="80%" loss="fgh"/>
<list info="AAPL, May 290 call, 90 cents or Lower" profit="ss" loss="20%"/>
<list info="DIA, April 105 call, 32 cents or Lower" profit="ghh" loss="20%"/>
<list info="GOOG, Aug 350 call, 47 cents or Lower" profit="100%" loss="sdgd"/>
</root>

using this code:

Ext.regmodel('picks',{fields: ['info','profit','loss']});
alert();
var pickstore = new Ext.data.store({
                                    model: 'picks',
                                    proxy: {
                                            type: 'ajax',
                                            url: 'http://1........ksxml.xml',   //url is fine it's good and working..
                                            reader: {
                                                     type: 'xml',
                                                     record: 'list'
                                                    }
                                            },
                                    listeners: {
                                                single: true,
                                                datachanged: function(){
                                                                        pickstore.each(function(pr){
                                                                                alert(pr.get('@info'));
                                                                                });
                                                                        }
                                                }
                                   });

pickstore.read();

i donno wats the reason but i couldnt parse even the first alert() is not displaying.

please help.....

Body:
Ext.regModel( 'picks' ......

Capital M - Javascript is case sensitive


问:
Count matches at the end of a string
I want to count the number of occurrences of a string at the end of the string.  I want it to ignore occurrences that are not at the end and I want it to return zero if there are none.

terminal string to find: "-1"

```<code>e.g. string = 1
// 0
e.g. string = 1-1
// 1
e.g. string = 1-1-1
// 2
e.g. string = 1-2-1
// 1
e.g. string = 1-2-1-2-1
// 1
e.g. string = 2-1-1-1-1
// 4
e.g. string = 1-1-2
// 0
</code>```

I want it to count all of the occurrences at the end of the string, not just the occurrences anywhere in the string.

I tried:

```<code>var occurrences = string.match(/(-1)*$/).length;
</code>```

I have a JS Fiddle here: JS Fiddle

It returns "2", no matter what my string.

答:
Non regex version:</p>

```<code>var occurences = 0;
string.split("-1").reduceRight((exit, space) => {
  if(exit || space) return true;
  occurences++;
  return false;
}, false);
</code>```

Title: Count matches at the end of a string

Body:
I want to count the number of occurrences of a string at the end of the string.  I want it to ignore occurrences that are not at the end and I want it to return zero if there are none.

terminal string to find: "-1"

e.g. string = 1
// 0
e.g. string = 1-1
// 1
e.g. string = 1-1-1
// 2
e.g. string = 1-2-1
// 1
e.g. string = 1-2-1-2-1
// 1
e.g. string = 2-1-1-1-1
// 4
e.g. string = 1-1-2
// 0

I want it to count all of the occurrences at the end of the string, not just the occurrences anywhere in the string.

I tried:

var occurrences = string.match(/(-1)*$/).length;

I have a JS Fiddle here: JS Fiddle

It returns "2", no matter what my string.

Body:
Non regex version:

var occurences = 0;
string.split("-1").reduceRight((exit, space) => {
  if(exit || space) return true;
  occurences++;
  return false;
}, false);


问:
(Jsoup) How to parse a specific column and row?
Basically I have this bus schedule table:

```<code><table id="smsBusResults" width="100%" cellpadding="0" cellspacing="0" border="0">
            <tbody><tr>
                <th>Linha</th>
                <th>Hora Prevista</th>
                <th>Tempo de Espera</th>
            </tr>
                            <tr class="even">
                <td>        <ul class="linhasAssoc">
                <li><a target="_self" class="linha_502" title="" href="/pt/viajar/linhas/?linha=502 ">502 </a></li>
                </ul>
     MATOSINHOS M</td>
                <td><i>17:09</i></td>
                <td>2min</td>
            </tr>
                            <tr class="even">
                <td>        <ul class="linhasAssoc">
                <li><a target="_self" class="linha_201" title="" href="/pt/viajar/linhas/?linha=201 ">201 </a></li>
                </ul>
     VISO - C2</td>
                <td><i>17:13</i></td>
                <td>5min</td>
            </tr>
                            <tr class="even">
                <td>        <ul class="linhasAssoc">
                <li><a target="_self" class="linha_203" title="" href="/pt/viajar/linhas/?linha=203 ">203 </a></li>
                </ul>
     CAST. QUEIJO</td>
                <td><i>17:18</i></td>
                <td>10min</td>
            </tr>
                            <tr class="even">
                <td>        <ul class="linhasAssoc">
                <li><a target="_self" class="linha_502" title="" href="/pt/viajar/linhas/?linha=502 ">502 </a></li>
                </ul>
     MATOSINHOS M</td>
                <td><i>17:20</i></td>
                <td>12min</td>
            </tr>
                            <tr class="even">
                <td>        <ul class="linhasAssoc">
                <li><a target="_self" class="linha_201" title="" href="/pt/viajar/linhas/?linha=201 ">201 </a></li>
                </ul>
     VISO - C2</td>
                <td><i>17:22</i></td>
                <td>15min</td>
            </tr>
                        </tbody></table>
</code>```

"Linha" means "Bus No. and Dest. Name", "Hora Prevista" - "ETA", "Tempo de Espera" - "Waiting Time".

For example, the first bus is the bus 502 with destination to Matosinhos, he should arrive at 17:09, and the waiting time is 2 mins.

How do I print only the first bus' name? (col 1, row 0)?

 What have I tried...

```<code>public class Main {

public static void main(String[] args) throws IOException {
        Document doc = Jsoup.connect("http://www.stcp.pt/pt/itinerarium/soapclient.php?codigo=ACRD1").get();

    ArrayList<String> nomesLinhas = new ArrayList<>();
    Elements smsBusResults = doc.select("smsBusResults");
    Elements filas = smsBusResults.select("tr");
    Elements colunas = smsBusResults.select("td");

    for (int i = 0; i < filas.size(); i++) {
        Element fila = filas.get(i);
        Elements cols = fila.select("td");

        System.out.println(cols.get(1).text());
    }

}
</code>```

}

答:
You can first get doc.select() method. If your document has name doc, then the following code will bring you row 0 col 1:

```<code>Element row = doc.select("tr").get(0);
Element col = row.select("td").get(1);
String text = col.text();
System.out.println(text);
</code>```

Body:
Basically I have this bus schedule table:

                Linha
                Hora Prevista
                Tempo de Espera

502

     MATOSINHOS M
                17:09
                2min

201

     VISO - C2
                17:13
                5min

203

     CAST. QUEIJO
                17:18
                10min

502

     MATOSINHOS M
                17:20
                12min

201

     VISO - C2
                17:22
                15min

"Linha" means "Bus No. and Dest. Name", "Hora Prevista" - "ETA", "Tempo de Espera" - "Waiting Time".

For example, the first bus is the bus 502 with destination to Matosinhos, he should arrive at 17:09, and the waiting time is 2 mins.

How do I print only the first bus' name? (col 1, row 0)?

 What have I tried...

public class Main {

public static void main(String[] args) throws IOException {
        Document doc = Jsoup.connect("http://www.stcp.pt/pt/itinerarium/soapclient.php?codigo=ACRD1").get();

    ArrayList<String> nomesLinhas = new ArrayList<>();
    Elements smsBusResults = doc.select("smsBusResults");
    Elements filas = smsBusResults.select("tr");
    Elements colunas = smsBusResults.select("td");

    for (int i = 0; i < filas.size(); i++) {
        Element fila = filas.get(i);
        Elements cols = fila.select("td");

        System.out.println(cols.get(1).text());
    }

}

}

Body:
You can first get doc.select() method. If your document has name doc, then the following code will bring you row 0 col 1:

Element row = doc.select("tr").get(0);
Element col = row.select("td").get(1);
String text = col.text();
System.out.println(text);


问:
Creating selector menu from array of objects
I'm trying to create a selector menu from an array of ojbects. Here is a sample of the object:

```<code>let states = [
      {id: 1, state: "Alabama", district: "1st District", url:"Alabama_1st.pdf"},
      {id: 2, state: "Alabama", district: "2nd District", url:"Alabama_1st.pdf"},
      {id: 3, state: "Alabama", district: "3rd District", url:"Alabama_1st.pdf"},
      {id: 4, state: "Alabama", district: "4th District", url:"Alabama_1st.pdf"},
      {id: 5, state: "Alabama", district: "5th District", url:"Alabama_1st.pdf"},
      {id: 6, state: "Alabama", district: "6th District", url:"Alabama_1st.pdf"},
      {id: 7, state: "Alabama", district: "7th District", url:"Alabama_1st.pdf"},
      {id: 9, state: "Alaska", district: "Statewide District", url:"Alaska_1st.pdf"},
      {id: 10, state: "Arizona", district: "1st District", url:"Arizona_1st.pdf"},
      {id: 11, state: "Arizona", district: "2nd District", url:"Arizona.2nd.pdf"},
      {id: 12, state: "Arizona", district: "3rd District", url:"Arizona_3rd.pdf"},
</code>```

I have the following jQuery so far but am struggling to get the states.state and states.district to populate in my selector menu. My console log is coming back correct so I know I am accessing the data, just can't get it to append to my selector menu.

```<code><script>
        for(let i = 0; i < states.length; i++) {
           if(states[i].id > 0){
             $("#listed_states").append(states[i].state +" "+ states[i].district);
              console.log(states[i].state +" "+ states[i].district);
            }
          }
</script>

<body>

    <select>
      <option>Find Your District Here<option>
      <option id="listed_states"> <option>
    </select>
</body>
</code>```

I'll be adding an .change() function to this after it fires to load a url with a _target.

答:
You should append to the select element, not the option.  You also need to create the option element in jQuery.

HTML

```<code><select id="listed_states">
  <option>Find Your District Here</option>
</select>
</code>```

jQuery

```<code>$(document).ready(function() {
  for (let i = 0; i < states.length; i++) {
    if (states[i].id > 0) {
      var option = $("<option>", {
        text: states[i].state + " " + states[i].district,
        value: states[i].id
      });
      $('#listed_states').append($(option));
    }
  }
});
</code>```

Don't forget to wrap your code that is appending the options in $(document).ready so that it waits for the DOM to load before executing (since you are appending to an element in the DOM)

Here is a Fiddle Demo: https://jsfiddle.net/zephyr_hex/bztgwubf/

Body:
I'm trying to create a selector menu from an array of ojbects. Here is a sample of the object:

let states = [
      {id: 1, state: "Alabama", district: "1st District", url:"Alabama_1st.pdf"},
      {id: 2, state: "Alabama", district: "2nd District", url:"Alabama_1st.pdf"},
      {id: 3, state: "Alabama", district: "3rd District", url:"Alabama_1st.pdf"},
      {id: 4, state: "Alabama", district: "4th District", url:"Alabama_1st.pdf"},
      {id: 5, state: "Alabama", district: "5th District", url:"Alabama_1st.pdf"},
      {id: 6, state: "Alabama", district: "6th District", url:"Alabama_1st.pdf"},
      {id: 7, state: "Alabama", district: "7th District", url:"Alabama_1st.pdf"},
      {id: 9, state: "Alaska", district: "Statewide District", url:"Alaska_1st.pdf"},
      {id: 10, state: "Arizona", district: "1st District", url:"Arizona_1st.pdf"},
      {id: 11, state: "Arizona", district: "2nd District", url:"Arizona.2nd.pdf"},
      {id: 12, state: "Arizona", district: "3rd District", url:"Arizona_3rd.pdf"},

I have the following jQuery so far but am struggling to get the states.state and states.district to populate in my selector menu. My console log is coming back correct so I know I am accessing the data, just can't get it to append to my selector menu.

    <select>
      <option>Find Your District Here<option>
      <option id="listed_states"> <option>
    </select>

I'll be adding an .change() function to this after it fires to load a url with a _target.

Body:
You should append to the select element, not the option.  You also need to create the option element in jQuery.

HTML

<select id="listed_states">
  <option>Find Your District Here</option>
</select>

jQuery

$(document).ready(function() {
  for (let i = 0; i < states.length; i++) {
    if (states[i].id > 0) {
      var option = $("<option>", {
        text: states[i].state + " " + states[i].district,
        value: states[i].id
      });
      $('#listed_states').append($(option));
    }
  }
});

Don't forget to wrap your code that is appending the options in $(document).ready so that it waits for the DOM to load before executing (since you are appending to an element in the DOM)

Here is a Fiddle Demo: https://jsfiddle.net/zephyr_hex/bztgwubf/


问:
make targets depend on variables
I want (GNU) make to rebuild when variables change. How can I achieve this?

For example,

```<code>$ make project
[...]
$ make project
make: `project' is up to date.
</code>```

...like it should, but then I'd prefer

```<code>$ make project IMPORTANTVARIABLE=foobar
make: `project' is up to date.
</code>```

to rebuild some or all of project.

答:
I might be late with an answer, but here is another way of doing such a dependency with Make conditional syntax (works on GNU Make 4.1, GNU bash, Bash on Ubuntu on Windows version 4.3.48(1)-release (x86_64-pc-linux-gnu)):

```<code>1 ifneq ($(shell cat config.sig 2>/dev/null),prefix $(CONFIG))
2 .PHONY: config.sig
3 config.sig:
4   @(echo 'prefix $(CONFIG)' >config.sig &)
5 endif
</code>```

In the above sample we track the $(CONFIG) variable, writing it's value down to a signature file, by means of the self-titled target which is generated under condition when the signature file's record value is different with that of $(CONFIG) variable. Please, note the prefix on lines 1 and 4: it is needed to distinct the case, when signature file doesn't exist yet.

Of course, consumer targets specify config.sig as a prerequisite.

Title: make targets depend on variables

Body:
I want (GNU) make to rebuild when variables change. How can I achieve this?

For example,

$ make project
[...]
$ make project
make: `project' is up to date.

...like it should, but then I'd prefer

$ make project IMPORTANTVARIABLE=foobar
make: `project' is up to date.

to rebuild some or all of project.

Body:
I might be late with an answer, but here is another way of doing such a dependency with Make conditional syntax (works on GNU Make 4.1, GNU bash, Bash on Ubuntu on Windows version 4.3.48(1)-release (x86_64-pc-linux-gnu)):

1 ifneq ($(shell cat config.sig 2>/dev/null),prefix $(CONFIG))
2 .PHONY: config.sig
3 config.sig:
4   @(echo 'prefix $(CONFIG)' >config.sig &)
5 endif

In the above sample we track the $(CONFIG) variable, writing it's value down to a signature file, by means of the self-titled target which is generated under condition when the signature file's record value is different with that of $(CONFIG) variable. Please, note the prefix on lines 1 and 4: it is needed to distinct the case, when signature file doesn't exist yet.

Of course, consumer targets specify config.sig as a prerequisite.


问:
Is the size of log file effecting performance of the database? How to Shrink log file?
I just checked my logfile and its almost 45GB.
I have two questions:

Is it effecting performance of database in general?
How to shrink it with SQL query? (please give me an example)

Thank you

答:
Shrinking your Transaction Log file under normal circumstances should not be necessary.

It oftens means you are in FULL Recovery Mode and not regular performing Transaction Log backups.

The size of the Log file will not affect performance per se. BUT Virtual Log File (VLF) fragmentation can (and often will) have very adverse effects on performance.

Please see: Transaction Log VLFs - too many or too few?
To determine how many VLFs are in teh log run:

```<code>DBCC LOGINFO
</code>```

You could shrink your Log, but that wouldn't remove the cause of it growing so large in the first place.

The canonical reference is: 8 Steps to better Transaction Log throughput

[Note: If your database is NOT a production database, you could set Recovery Mode to Simple.]

Shrinking the Transaction Log

Body:
Shrinking your Transaction Log file under normal circumstances should not be necessary.

It oftens means you are in FULL Recovery Mode and not regular performing Transaction Log backups.

The size of the Log file will not affect performance per se. BUT Virtual Log File (VLF) fragmentation can (and often will) have very adverse effects on performance.

Please see: Transaction Log VLFs - too many or too few?
To determine how many VLFs are in teh log run:

DBCC LOGINFO

You could shrink your Log, but that wouldn't remove the cause of it growing so large in the first place.

The canonical reference is: 8 Steps to better Transaction Log throughput

[Note: If your database is NOT a production database, you could set Recovery Mode to Simple.]

Shrinking the Transaction Log


问:
How to style material ui next components with styled components and SASS
We want to use the material ui next components in our application where we're using styled components with SASS. To achieve this we use webpack and a raw-loader to import the generated CSS and apply the styles like so:

```<code>const sidebarStyles = require('./Sidebar.sass');

const StyledDrawer = styled(Drawer)`
    ${sidebarStyles}
    `
</code>```

We're trying this approach because styled components seem like a good method for styling react components, but we want to use regular sass files so our designers can create the styles like normal, without having to write css-in-js.

Now the issue I'm facing with material ui components is that many components have children (e.g. the Drawer component has a Paper component as its child) and I'm struggling to find a good way to style those with our approach - I know the recommended way is to use the classes prop:

```<code>const styles = theme => ({
    drawerPaper: {
        width: 250
    }
});

classes={{
    paper: classes.drawerPaper,
}}
</code>```

But this doesn't work with our requirement to import the styles as text from an external .sass file.

Would this even be possible at all and what would be the best way?

答:
You should be able to pass the name of the class from your sass file to the classes object.

```<code>classes={{
  paper: `SASS_CLASS_NAME_HERE`,
}}
</code>```

More Info: https://material-ui-next.com/customization/overrides/#overriding-with-classes

Body:
We want to use the material ui next components in our application where we're using styled components with SASS. To achieve this we use webpack and a raw-loader to import the generated CSS and apply the styles like so:

const sidebarStyles = require('./Sidebar.sass');

const StyledDrawer = styled(Drawer)`
    ${sidebarStyles}
    `

We're trying this approach because styled components seem like a good method for styling react components, but we want to use regular sass files so our designers can create the styles like normal, without having to write css-in-js.

Now the issue I'm facing with material ui components is that many components have children (e.g. the Drawer component has a Paper component as its child) and I'm struggling to find a good way to style those with our approach - I know the recommended way is to use the classes prop:

const styles = theme => ({
    drawerPaper: {
        width: 250
    }
});

classes={{
    paper: classes.drawerPaper,
}}

But this doesn't work with our requirement to import the styles as text from an external .sass file.

Would this even be possible at all and what would be the best way?

Body:
You should be able to pass the name of the class from your sass file to the classes object.

classes={{
  paper: `SASS_CLASS_NAME_HERE`,
}}

More Info: https://material-ui-next.com/customization/overrides/#overriding-with-classes


问:
TypeScript Mocha: Module '"mocha"' has no exported member 'describe'. (2305)
```<code>import {describe, it} from 'mocha'
import {expect} from "chai"

describe('Example Mocha Test 1', function () {
    it('Should test foo', function () {
        let foo = 'bar'
        expect(foo, 'because foo is str').to.be.a('string')
    })
})
</code>```

Getting the errors:

```<code>Module '"mocha"' has no exported member 'describe'. (2305)
Module '"mocha"' has no exported member 'it'. (2305)
</code>```

This way of importing worked yesterday so I changed my whole project to this format and today suddenly it decided not to work.

The reason I want to import describe and it is because the IDE (WebStorm) starts autocompleting when I import it like this.

When I change the code to:

```<code>import 'mocha'
</code>```

The code compiles and tests start to run again. But I don't get the autocomplete.

I have "@types/mocha": "2.2.44", installed.

What should I do?

答: @types/mocha/index.d.ts v. 2.2.44 doesn't include any named exports for describe, etc., so compiler errors are expected. import * as mocha from 'mocha'; works, but is not actually required - you don't need importing describe, etc. explicitly, as mocha adds them to global namespace

Body:
import {describe, it} from 'mocha'
import {expect} from "chai"

describe('Example Mocha Test 1', function () {
    it('Should test foo', function () {
        let foo = 'bar'
        expect(foo, 'because foo is str').to.be.a('string')
    })
})

Getting the errors:

Module '"mocha"' has no exported member 'describe'. (2305)
Module '"mocha"' has no exported member 'it'. (2305)

This way of importing worked yesterday so I changed my whole project to this format and today suddenly it decided not to work.

The reason I want to import describe and it is because the IDE (WebStorm) starts autocompleting when I import it like this.

When I change the code to:

import 'mocha'

The code compiles and tests start to run again. But I don't get the autocomplete.

I have "@types/mocha": "2.2.44", installed.

What should I do?


问:
swift firebase nested children count
```<code>groups
--group1(autoid)
---subgroup1(autoid)
----id
----ownerId
----description
--group2(autoid)
---subgroup2(autoid)
----id
----ownerId
----description
</code>```

In a structure like over here i have to count all occurrencies of ownerId that are equal to my id (currentUserId) in all groups, can somebody help me?

what i've done so far:

root.child("groups").observe(.value, with: {(snapshot) in
    if let result = snapshot.children.allObjects as? [DataSnapshot] {
        var count = 0
        for child in result {
            let orderID = child.key as String //get autoID
            self.root.child("groups/\(orderID)/").queryOrdered(byChild: "ownerId").queryEqual(toValue: self.currentUserId).observe(.value, with: { (snapshot: DataSnapshot!) in
                print(snapshot.childrenCount, "quanti sono")
                count += (Int(snapshot.childrenCount))
                print(count)
            })
        }
    }
})
```

with this i can get a count but it updates all cycles... i need i need the final value outside

答:
One important aspect of Firebase Structures is denormalizing or flattening the structure. Denormalized data generally makes queries much easier and while conceptually the structure you are using works for some tasks, it makes doing the query you want challenging.

So, I would suggest an alternate structure that would make the query super simple, and not loose other functionality.

A change to the structure like this:

```<code>groups
  group1: true
  group2: true

subgroups
  subgroup1(autoid)
     id
     ownerId
     description
     belongs_to_group: "group1"
  subgroup2(autoid)
     id
     ownerId
     description
     belongs_to_group: "group2"
</code>```

Then if you want to count all of subgroups with a particular ownerId

```<code>let subGroupsRef = self.ref.child("subgroups")
let query = subGroupsRef.queryOrdered(byChild: "ownerId").queryEqual(toValue: "their id")
query.observeSingleEvent(of: .value) { snapshot in
    let count = snapshot.childrenCount
    print(count)
}
</code>```

Edit:

Based on the comment, here's an way to get the count based on your current structure. It's pretty brute force and the code could be reduced considerably but I left it verbose for readability

```<code>let groupsRef = self.ref.child("groups")
groupsRef.observeSingleEvent(of: .value, with: { snapshot in
    var count = 0
    for groupChild in snapshot.children {
        let groupSnap = groupChild as! DataSnapshot
        for subGroupChild in groupSnap.children {
            let subGroupSnap = subGroupChild as! DataSnapshot
            let dict = subGroupSnap.value as! [String: Any]
            let uid = dict["owner_id"] as! String
            if uid == "uid_0" {
                count += 1
                print(count)
            }
        }
    }
    print("total found \(count)")
})
</code>```

Where this fails is if you have a lot of nodes as they are all initially loaded in (by .value) so it could be iterated over in code. If it's a few thousand it works well and is very fast.

Title: swift firebase nested children count

Body:
groups
--group1(autoid)
---subgroup1(autoid)
----id
----ownerId
----description
--group2(autoid)
---subgroup2(autoid)
----id
----ownerId
----description

In a structure like over here i have to count all occurrencies of ownerId that are equal to my id (currentUserId) in all groups, can somebody help me?

what i've done so far:

root.child("groups").observe(.value, with: {(snapshot) in
    if let result = snapshot.children.allObjects as? [DataSnapshot] {
        var count = 0
        for child in result {
            let orderID = child.key as String //get autoID
            self.root.child("groups/\(orderID)/").queryOrdered(byChild: "ownerId").queryEqual(toValue: self.currentUserId).observe(.value, with: { (snapshot: DataSnapshot!) in
                print(snapshot.childrenCount, "quanti sono")
                count += (Int(snapshot.childrenCount))
                print(count)
            })
        }
    }
})

with this i can get a count but it updates all cycles... i need i need the final value outside

Body:
One important aspect of Firebase Structures is denormalizing or flattening the structure. Denormalized data generally makes queries much easier and while conceptually the structure you are using works for some tasks, it makes doing the query you want challenging.

So, I would suggest an alternate structure that would make the query super simple, and not loose other functionality.

A change to the structure like this:

groups
  group1: true
  group2: true

subgroups
  subgroup1(autoid)
     id
     ownerId
     description
     belongs_to_group: "group1"
  subgroup2(autoid)
     id
     ownerId
     description
     belongs_to_group: "group2"

Then if you want to count all of subgroups with a particular ownerId

let subGroupsRef = self.ref.child("subgroups")
let query = subGroupsRef.queryOrdered(byChild: "ownerId").queryEqual(toValue: "their id")
query.observeSingleEvent(of: .value) { snapshot in
    let count = snapshot.childrenCount
    print(count)
}

Edit:

Based on the comment, here's an way to get the count based on your current structure. It's pretty brute force and the code could be reduced considerably but I left it verbose for readability

let groupsRef = self.ref.child("groups")
groupsRef.observeSingleEvent(of: .value, with: { snapshot in
    var count = 0
    for groupChild in snapshot.children {
        let groupSnap = groupChild as! DataSnapshot
        for subGroupChild in groupSnap.children {
            let subGroupSnap = subGroupChild as! DataSnapshot
            let dict = subGroupSnap.value as! [String: Any]
            let uid = dict["owner_id"] as! String
            if uid == "uid_0" {
                count += 1
                print(count)
            }
        }
    }
    print("total found \(count)")
})

Where this fails is if you have a lot of nodes as they are all initially loaded in (by .value) so it could be iterated over in code. If it's a few thousand it works well and is very fast.


问:
uncaught typeerror cannot read property 'touppercase' of undefined Observable._subscribe
I have an issue. I develop mobile app with ionic framework. It's movie app. I found one example on github and tried to implement some functions and design into my project.

I have the page 'Store'. When I start the project I get the error

Uncaught (in promise): TypeError: Cannot read property 'toUpperCase' of undefined TypeError: Cannot read property 'toUpperCase' of undefined at Observable._subscribe

It come from ngOnInit function, but I can't see what is wrong. I just recently started to learn mobile development with ionic framework, ts and angular. I will be glad for any help.

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { MovieService } from '../../services/movie-service';
import { MovieDetailsPage } from '../movie-details/movie-details';

@Component({
  selector: 'page-store',
  templateUrl: 'store.html'
})
 export class StorePage {

  movies: Array<any>;

     constructor(public navCtrl: NavController, private movieService:
 MovieService) {

     }

     ngOnInit(){
        this.movieService.send('getMovies').subscribe(a => {
            console.log(a);
            this.movies = a.results.map(b => {
                return {
                    id: b.id,
                    title: b.title,
                    image: b.poster_path,
                    overview: b.overview,
                    rating: b.vote_average
                }
            })
        });
     }

     searchMovieDB(event, key) {
         if(event.target.value.length > 2) {
             this.movieService.searchMovies(event.target.value).subscribe(
                 data => {
                     this.movies = data.results;
                     console.log(data);
                 },
                 err => {
                     console.log(err);
                 },
                 () => console.log('Movie Search Complete')
              );
         }
     }

     itemTapped(event, movie) {
         //console.log(movie);
         this.movieService.send('getSingleMovie', movie.id).subscribe(data
  => console.log(data));
         this.navCtrl.push(MovieDetailsPage, {
             movie: movie
         });
     }

 }
</code>```

Here is 'MovieService' which I use to create api requests:

```<code>import { Injectable } from '@angular/core';
import {Http, Headers, RequestMethod, Request} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class MovieService {

    constructor(private http:Http) {

    }

    searchMovies(movieName) {
        var url = 'http://api.themoviedb.org/3/search/movie?query=&query=' +
encodeURI(movieName) + '&api_key=xxxxxxxxxxxxxxxxxx';

        var response = this.http.get(url).map(res => res.json());
        return response;
    }

    send(name, id?, item?) {

                let url: string,
                    body: any,
                    api_key: string = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

                if(name == 'getMovies')
                    url = 'http://api.themoviedb.org/3/movie/'+id+'?
api_key=' + api_key;
                else if (name == 'getMoviesByPage')
                    url = 'http://api.themoviedb.org/3/movie/popular?
api_key='+api_key+'&page=' + id;
                else if (name == 'getSingleMovie')
                    url = 'https://api.themoviedb.org/3/movie/'+id+'?
api_key=' + api_key;
                else if (name == 'getVideo')
                    url = 'https://api.themoviedb.org/3/movie/'+id+'/videos?
api_key=' + api_key;
                else if (name == 'getImages')
                    url = 'https://api.themoviedb.org/3/movie/'+id+'/images?
api_key=' + api_key;

                let options = {
                    url: url,
                    body: null
                };

                if (item) {
                    body = typeof item === 'string' ? item :
 JSON.stringify(item);
                    options.body = body;
                }

                return this.http.request(new Request(options))
                    .map(res => res.json())

            }
}
</code>```

答:
The problem is when you are using Request (which is deprecated along with Http by the way). You would want to just make get request, nothing else needed really. I see some problems in your code, for example when getting a single movie based on id, your app would throw an error at the mapping inside subscribe, since the data you would get back from fetching one movie would just return an object, not an array. So you need to rethink that!

But here's a sample with getting one movie based on id:

```<code>send(name, id?, item?) {
  let url: string,
  api_key: string = 'xxxxxxxxxxxxxxxxxxxxxxx';

  if (name == 'getMovies')
    url = 'https://api.themoviedb.org/3/movie/' + id + '?api_key=' + api_key

  return this.http.get(url)
    .map(res => res.json())
}
</code>```

Component:

```<code>ngOnInit() {
  this.movieService.send('getMovies').subscribe(a => {
    this.movies = a // will not be an array in this case, just an object!
  });
}
</code>```

Body:
I have an issue. I develop mobile app with ionic framework. It's movie app. I found one example on github and tried to implement some functions and design into my project.

I have the page 'Store'. When I start the project I get the error

Uncaught (in promise): TypeError: Cannot read property 'toUpperCase' of undefined TypeError: Cannot read property 'toUpperCase' of undefined at Observable._subscribe

It come from ngOnInit function, but I can't see what is wrong. I just recently started to learn mobile development with ionic framework, ts and angular. I will be glad for any help.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { MovieService } from '../../services/movie-service';
import { MovieDetailsPage } from '../movie-details/movie-details';

@Component({
  selector: 'page-store',
  templateUrl: 'store.html'
})
 export class StorePage {

  movies: Array<any>;

     constructor(public navCtrl: NavController, private movieService:
 MovieService) {

     }

     ngOnInit(){
        this.movieService.send('getMovies').subscribe(a => {
            console.log(a);
            this.movies = a.results.map(b => {
                return {
                    id: b.id,
                    title: b.title,
                    image: b.poster_path,
                    overview: b.overview,
                    rating: b.vote_average
                }
            })
        });
     }

     searchMovieDB(event, key) {
         if(event.target.value.length > 2) {
             this.movieService.searchMovies(event.target.value).subscribe(
                 data => {
                     this.movies = data.results;
                     console.log(data);
                 },
                 err => {
                     console.log(err);
                 },
                 () => console.log('Movie Search Complete')
              );
         }
     }

     itemTapped(event, movie) {
         //console.log(movie);
         this.movieService.send('getSingleMovie', movie.id).subscribe(data
  => console.log(data));
         this.navCtrl.push(MovieDetailsPage, {
             movie: movie
         });
     }

 }

Here is 'MovieService' which I use to create api requests:

import { Injectable } from '@angular/core';
import {Http, Headers, RequestMethod, Request} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class MovieService {

    constructor(private http:Http) {

    }

    searchMovies(movieName) {
        var url = 'http://api.themoviedb.org/3/search/movie?query=&query=' +
encodeURI(movieName) + '&api_key=xxxxxxxxxxxxxxxxxx';

        var response = this.http.get(url).map(res => res.json());
        return response;
    }

    send(name, id?, item?) {

                let url: string,
                    body: any,
                    api_key: string = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

                if(name == 'getMovies')
                    url = 'http://api.themoviedb.org/3/movie/'+id+'?
api_key=' + api_key;
                else if (name == 'getMoviesByPage')
                    url = 'http://api.themoviedb.org/3/movie/popular?
api_key='+api_key+'&page=' + id;
                else if (name == 'getSingleMovie')
                    url = 'https://api.themoviedb.org/3/movie/'+id+'?
api_key=' + api_key;
                else if (name == 'getVideo')
                    url = 'https://api.themoviedb.org/3/movie/'+id+'/videos?
api_key=' + api_key;
                else if (name == 'getImages')
                    url = 'https://api.themoviedb.org/3/movie/'+id+'/images?
api_key=' + api_key;

                let options = {
                    url: url,
                    body: null
                };

                if (item) {
                    body = typeof item === 'string' ? item :
 JSON.stringify(item);
                    options.body = body;
                }

                return this.http.request(new Request(options))
                    .map(res => res.json())

            }
}

Body:
The problem is when you are using Request (which is deprecated along with Http by the way). You would want to just make get request, nothing else needed really. I see some problems in your code, for example when getting a single movie based on id, your app would throw an error at the mapping inside subscribe, since the data you would get back from fetching one movie would just return an object, not an array. So you need to rethink that!

But here's a sample with getting one movie based on id:

send(name, id?, item?) {
  let url: string,
  api_key: string = 'xxxxxxxxxxxxxxxxxxxxxxx';

  if (name == 'getMovies')
    url = 'https://api.themoviedb.org/3/movie/' + id + '?api_key=' + api_key

  return this.http.get(url)
    .map(res => res.json())
}

Component:

ngOnInit() {
  this.movieService.send('getMovies').subscribe(a => {
    this.movies = a // will not be an array in this case, just an object!
  });
}


问:
ZF3 form element classes get encoded with unicode entities
I'm trying to figure out why ZF3 encodes my element's class string, but can't find anything about that behaviour on the internet.

```<code>$this->add([
    'type'  => 'Button',
    'name' => 'submitLogin',
    'options' => [
        'label' => '<i class="zmdi zmdi-check"></i>',
        'label_options' => [
            'disable_html_escape' => true,
        ]
    ],
    'attributes' => [
        'type' => 'submit',
        'class' => 'btn btn--icon login__block__btn',
    ],
]);
</code>```

becomes

```<code><button type="submit" name="submitLogin" class="btn btn--icon login__block__btn" value=""><i class="zmdi zmdi-check"></i></button>
</code>```

答:
I think this is an abstract concept. Generally we take some steps when we work with data. We filter input values and escape outputs. This is a security philosophy.

Zend Framework did the same thing while something is about security. This means this behavior is by default. ZF escapes attributes' values when it is being displayed onto the browser. ZF only allows non-escaping through explicit options like you did for the label's content above.

You will get some concept via this issue on github where Matthew said:

Secure by default is the mantra

Body:
I'm trying to figure out why ZF3 encodes my element's class string, but can't find anything about that behaviour on the internet.

$this->add([
    'type'  => 'Button',
    'name' => 'submitLogin',
    'options' => [
        'label' => '',
        'label_options' => [
            'disable_html_escape' => true,
        ]
    ],
    'attributes' => [
        'type' => 'submit',
        'class' => 'btn btn--icon login__block__btn',
    ],
]);

becomes

<button type="submit" name="submitLogin" class="btn btn--icon login__block__btn" value=""></button>


问:
How to get all columns from the child table and parent table in PostgreSQL?
I currently have a several tables of different types of items. Each table has different columns, and they all inherit the primary items table. Here is a brief example:

```<code>CREATE TABLE items
(
    id serial,
    name character varying,
    description character varying
)

CREATE TABLE weapons
(
    damage smallint,
    accuracy smallint
) INHERITS (items)
</code>```

I am trying to allow users to search for an item by name, and get all of the information regarding that item, not only the columns from the items table. Since I do not know which child table the item will be in, I cannot do:

```<code>SELECT * FROM ONLY parent NATURAL FULL JOIN child;
</code>```

Is there any way to get all the columns of all child tables without knowning what the child table is? And if not, what would be the best way to make this feature work?

Solution

Use the following to get the origin tabe, which will then be used to query all the information from that table:

```<code>SELECT id, tableoid::regclass AS origin FROM items WHERE name = $1;
</code>```

答:
The query planner needs to know what tables are going to be read, and what columns included in the final result, so I don't think there will be any single query that can say "include column X if Y, but column Z if not".

The best that I can think of is to LEFT JOIN all the child tables, so your result set contains all the possible columns, but most of them will be NULL.

Body:
I currently have a several tables of different types of items. Each table has different columns, and they all inherit the primary items table. Here is a brief example:

CREATE TABLE items
(
    id serial,
    name character varying,
    description character varying
)

CREATE TABLE weapons
(
    damage smallint,
    accuracy smallint
) INHERITS (items)

I am trying to allow users to search for an item by name, and get all of the information regarding that item, not only the columns from the items table. Since I do not know which child table the item will be in, I cannot do:

SELECT * FROM ONLY parent NATURAL FULL JOIN child;

Is there any way to get all the columns of all child tables without knowning what the child table is? And if not, what would be the best way to make this feature work?

Solution

Use the following to get the origin tabe, which will then be used to query all the information from that table:

SELECT id, tableoid::regclass AS origin FROM items WHERE name = $1;


问:
Python copy and concatenate linked lists, preserve order
I have a basic linked-list implementation in python. Each Cell has some data associated with it and a next object, used to include the rest of the linked list (and null if only the first param of data is given in the constructor).

I want to copy and concatenate two lists together, so that the final product preserves the order and is independent of the two original lists.

Here is what I have:
```<code>def list_concat_copy(A, B):
        C = Cell(A)
        while A.next != None:
                A = A.next
                C = Cell(A,C)
        C = Cell(B,C)
        while B.next != None:
                B = B.next
                C = Cell(B,C)
        return C```

The issue that I am having is that this reverses the order:
```<code>A = Cell(8,Cell(9,Cell(10)))
B = Cell(11,Cell(12,Cell(13)))
C = list_concat_copy(A,B)```

Now if I walk_and_print(C) I get 13 12 11 10 9 8

Any thoughts?

答:
You do some weird stuff:

```<code>A = Cell(8,Cell(9,Cell(10)))
</code>```

suggests that your Cell is something like

```<code>class Cell(object):
    def __init__(self, val, nxt=None):
        self.val = val
        self.next = nxt
</code>```

but doing

```<code>C = Cell(A)
</code>```

never copies anything, it just creates a new Cell with the same A as a value.

So, lets start with a Cell that can actually copy itself:

```<code>class Cell(object):
    def __init__(self, val, nxt=None):
        self.val = val
        self.next = nxt

    def copy(self):
        if self.next is None:
            return Cell(self.value)
        else:
            return Cell(self.value, self.next.copy())
</code>```

Now your concat is easy:

```<code>def concat_copy(a, b):
        new = a.copy()

        # find the end of the copy
        last = new
        while last.next is not None:
            last = last.next
        # append a copy of the other list
        last.next = b.copy()
</code>```

For completeness, here is what your tried to do:

```<code>def copy( cells ):
    new = Cell(cells.value)
    current = new
    old = cells

    while old.next is not None:
        # copy the current cell
        ccopy = Cell(old.value)

        # add it
        current.next = ccopy

        # prepare for the next round
        current = ccopy
        old = old.next

    return new
</code>```

I think this helps to understand how you accidentally reversed your cells: You walked the list forwards but the C = Cell(A,C) puts a new Cell before the old C, so that builds the new list from the end.

Body:
I have a basic linked-list implementation in python. Each Cell has some data associated with it and a next object, used to include the rest of the linked list (and null if only the first param of data is given in the constructor).

I want to copy and concatenate two lists together, so that the final product preserves the order and is independent of the two original lists.

Here is what I have:

def list_concat_copy(A, B):
        C = Cell(A)
        while A.next != None:
                A = A.next
                C = Cell(A,C)
        C = Cell(B,C)
        while B.next != None:
                B = B.next
                C = Cell(B,C)
        return C

The issue that I am having is that this reverses the order:

A = Cell(8,Cell(9,Cell(10)))
B = Cell(11,Cell(12,Cell(13)))
C = list_concat_copy(A,B)

Now if I walk_and_print(C) I get 13 12 11 10 9 8

Any thoughts?

Body:
You do some weird stuff:

A = Cell(8,Cell(9,Cell(10)))

suggests that your Cell is something like

class Cell(object):
    def __init__(self, val, nxt=None):
        self.val = val
        self.next = nxt

but doing

C = Cell(A)

never copies anything, it just creates a new Cell with the same A as a value.

So, lets start with a Cell that can actually copy itself:

class Cell(object):
    def __init__(self, val, nxt=None):
        self.val = val
        self.next = nxt

    def copy(self):
        if self.next is None:
            return Cell(self.value)
        else:
            return Cell(self.value, self.next.copy())

Now your concat is easy:

def concat_copy(a, b):
        new = a.copy()

        # find the end of the copy
        last = new
        while last.next is not None:
            last = last.next
        # append a copy of the other list
        last.next = b.copy()

For completeness, here is what your tried to do:

def copy( cells ):
    new = Cell(cells.value)
    current = new
    old = cells

    while old.next is not None:
        # copy the current cell
        ccopy = Cell(old.value)

        # add it
        current.next = ccopy

        # prepare for the next round
        current = ccopy
        old = old.next

    return new

I think this helps to understand how you accidentally reversed your cells: You walked the list forwards but the C = Cell(A,C) puts a new Cell before the old C, so that builds the new list from the end.


问:
Javascript is not parsing JSON
NOTE:- I am just beginning with JSON with javascript and was trying this simple script. I want to make use of JSON.parse() here to fetch the data

Here is a snippet of my code

```

Nothing is getting displayed. I don't understand what is the problem. Can anyone help?
Edit- I corrected the string which spanned multiple lines but it still doesn't work

答:
Your json format is invalid. You shouldn't use multilines in javascript strings and quotes must be converted to double quotes. Like this;

```<code>var text = '{"college":{"stream":{"commerce":{"junior":["FY","SY"],"bachelor":["Bcom","BMM"]},"science":{"junior":["FY","SY"],"bachelor":["Bsc","BTech"]},"arts":{"junior":["FY","SY"],"bachelor":["BA","B.Ed"]}}}}';
JSON.parse(text);
</code>```

Also you can validate your json using online Json validator websites. Like this.

Title: Javascript is not parsing JSON

Body:
NOTE:- I am just beginning with JSON with javascript and was trying this simple script. I want to make use of JSON.parse() here to fetch the data

Here is a snippet of my code

Nothing is getting displayed. I don't understand what is the problem. Can anyone help?
Edit- I corrected the string which spanned multiple lines but it still doesn't work

Body:
Your json format is invalid. You shouldn't use multilines in javascript strings and quotes must be converted to double quotes. Like this;

var text = '{"college":{"stream":{"commerce":{"junior":["FY","SY"],"bachelor":["Bcom","BMM"]},"science":{"junior":["FY","SY"],"bachelor":["Bsc","BTech"]},"arts":{"junior":["FY","SY"],"bachelor":["BA","B.Ed"]}}}}';
JSON.parse(text);

Also you can validate your json using online Json validator websites. Like this.


问:
How can i calling a function within a Class method
I would like to call a function within a class method, I created this script but not work as I can do?

Fatal error: Call to a member function function2() on null in /.../.../index.php on line 12

```<code>    public static function table($name_t, callable  $callback){
    self::databaseConnection();
    try {

        $matches = array(
            .....
        );

        function engine($var){
            Gaia::$engine__ = $var[0];
        }

        $eng = new Table_call;
        echo $eng;

        $callback($matches);

        if(isset(self::$s)){
            //self::$instance->exec("CREATE TABLE IF NOT EXISTS ".$name_t."( ".trim(self::$s,',')." ) ENGINE=MyISAM DEFAULT CHARSET=utf8;");

            echo "Dump Success!<br> ".self::$engine__ ;
        }

        //return $bgj;
    } catch (Exception $e) {
        self::$instance = null;
        echo ("Oh noes! There's an error in the query: ". $e);
    }

}
</code>```

Class File 2

```<code>class Table_call extends Gaia{

     public function __call($name,$arg){
      call_user_func($name,$arg);
     }
 }
</code>```

Index File

```<code>Gaia::table('test', function($table){
   $table['autoIncrement']('id');
})->engine('MyISAM');
</code>```

how can i add function this way ??

```<code>" ->function2('hello') "?
</code>```

答:
I don't know if this is what you want but it's the smallest example I could do.  It's not clear to me in your question what exactly you are trying to do as there is no function2 in any code you posted so I have to guess what that is.  Anyway...

```<code><?php
class Gaia{
    public static function table(){
        return new Table_call();
    }
}

class Table_call extends Gaia{

    public function function2(){
        echo __METHOD__;
    }

}

Gaia::table()->function2();
</code>```

You can try it here.

http://sandbox.onlinephpfunctions.com/code/dd1c5db302448e8f075a081acfc33cb00c3f71b5

Looking at your code, your not returning any objects to call the second function on.  Think about it this way

```<code>$var =  Gaia::table();
 //var is an instance of Table_call
$var->function2();
</code>```

Also your error

Fatal error: Call to a member function function2() on null in /.../.../index.php on line 12

The default return type is NULL so...

Body:
I would like to call a function within a class method, I created this script but not work as I can do?

Fatal error: Call to a member function function2() on null in /.../.../index.php on line 12

    public static function table($name_t, callable  $callback){
    self::databaseConnection();
    try {

        $matches = array(
            .....
        );

        function engine($var){
            Gaia::$engine__ = $var[0];
        }

        $eng = new Table_call;
        echo $eng;

        $callback($matches);

        if(isset(self::$s)){
            //self::$instance->exec("CREATE TABLE IF NOT EXISTS ".$name_t."( ".trim(self::$s,',')." ) ENGINE=MyISAM DEFAULT CHARSET=utf8;");

            echo "Dump Success!
 ".self::$engine__ ;
        }

        //return $bgj;
    } catch (Exception $e) {
        self::$instance = null;
        echo ("Oh noes! There's an error in the query: ". $e);
    }

}

Class File 2

class Table_call extends Gaia{

     public function __call($name,$arg){
      call_user_func($name,$arg);
     }
 }

Index File

Gaia::table('test', function($table){
   $table['autoIncrement']('id');
})->engine('MyISAM');

how can i add function this way ??

" ->function2('hello') "?

Body:
I don't know if this is what you want but it's the smallest example I could do.  It's not clear to me in your question what exactly you are trying to do as there is no function2 in any code you posted so I have to guess what that is.  Anyway...

<?php
class Gaia{
    public static function table(){
        return new Table_call();
    }
}

class Table_call extends Gaia{

    public function function2(){
        echo __METHOD__;
    }

}

Gaia::table()->function2();

You can try it here.

http://sandbox.onlinephpfunctions.com/code/dd1c5db302448e8f075a081acfc33cb00c3f71b5

Looking at your code, your not returning any objects to call the second function on.  Think about it this way

$var =  Gaia::table();
 //var is an instance of Table_call
$var->function2();

Also your error

Fatal error: Call to a member function function2() on null in /.../.../index.php on line 12

The default return type is NULL so...


问:
redirect_to != return
I'm looking for some clarification regarding the behaviour of redirect_to.

I have this code:

```<code>if some_condition
   redirect_to(path_one)
end

redirect_to(path_two)
</code>```

If some_condition == true I get this error:

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action.

It seems that the method continues to execute after the redirect_to call.  Do I need to write code like this:

```<code>if some_condition
   redirect_to(path_one)
   return
end

redirect_to(path_two)
</code>```

答:
To consolidate the "rubyish way" example in Eimantas' answer to two lines of code:</p>

```<code>return redirect_to(path_one) if some_condition

redirect_to(path_two)
</code>```

Title: redirect_to != return

Body:
I'm looking for some clarification regarding the behaviour of redirect_to.

I have this code:

if some_condition
   redirect_to(path_one)
end

redirect_to(path_two)

If some_condition == true I get this error:

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action.

It seems that the method continues to execute after the redirect_to call.  Do I need to write code like this:

if some_condition
   redirect_to(path_one)
   return
end

redirect_to(path_two)

Body:
To consolidate the "rubyish way" example in Eimantas' answer to two lines of code:

return redirect_to(path_one) if some_condition

redirect_to(path_two)


问:
Is there a cocoa sample code to demonstrate how to access global instance/variable via delegate?
I prefer to access the global instance/variable via delegate.
( I do not like the mode as

```<code>extern  NSInteger  myInstance
</code>```

)
This means that all global instances/variables are in a delegate object.
In cocoa touch, I know I can use

```<code>appDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];
UIApplication *app=[UIApplication sharedApplication];
appDelegate.myInstance=1;
</code>```

to access the global instance(myInstance), but I am not sure if it is same as the mode in Cocoa.
Is there a cocoa sample code to demonstrate how to access global instance/variable via delegate?

Welcome any comment

Thanks

interdev

答:
In Cocoa it's [NSApplication sharedApplication] and [[NSApplication sharedApplication] delegate].

You can also use the global NSApp as shorthand; see the NSApplication Class Reference

Body:
I prefer to access the global instance/variable via delegate.
( I do not like the mode as

extern  NSInteger  myInstance

)
This means that all global instances/variables are in a delegate object.
In cocoa touch, I know I can use

appDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];
UIApplication *app=[UIApplication sharedApplication];
appDelegate.myInstance=1;

to access the global instance(myInstance), but I am not sure if it is same as the mode in Cocoa.
Is there a cocoa sample code to demonstrate how to access global instance/variable via delegate?

Welcome any comment

Thanks

interdev


问:
How do I remove the title bar from my app?
In my app there is this title bar at the top where the overflow menu would be, but I don't need settings and only have one screen.
When I change the theme like described in many other questions I get the old 2.2 theme. I want to have the modern theme just without the bar at the top.</p>

答:
This works for me</p>

```<code>getSupportActionBar().hide();
</code>```

Body:
This works for me

getSupportActionBar().hide();


问:
Keep only dataframe rows closest to given values
I have a dataframe df1 with some variables, given for certain values A:

```<code>df1 = pd.DataFrame({"A": [110.035,110.078,110.732,112.828,112.930],
               "var1": np.random.random(5),
               "var2":np.random.random(5)})

       A          var1        var2
0   110.035     0.500537    0.571497
1   110.078     0.234550    0.732815
2   110.732     0.337149    0.098250
3   112.828     0.190261    0.366118
4   112.930     0.990539    0.892640
</code>```

and a dataframe df2 of values A like

```<code>df2 = pd.DataFrame({"A": [110.04, 112.83]})

      A
0   110.04
1   112.83
</code>```

Now I want to keep all values in df1, that are closest to one of the values in df2 and drop all the others. In my example I want to keep rows 0 and 3 only.

My idea is to build the absolute differences and use argsort():

```<code>(df1.A-x).abs().argsort()[:1]
</code>```

but this works for one value x only, how can I extend this to all values in df2?

答:
Op1  numpy.searchsorted

Using numpy.searchsorted then using index slice the df1

```<code>df1.loc[np.searchsorted(df1.A, df2.A)-1]
Out[826]:
         A      var1      var2
0  110.035  0.007591  0.768843
3  112.828  0.426480  0.902606
</code>```

Op2  merge_asof

```<code>pd.merge_asof(df2,df1,on='A',direction='nearest')
Out[819]:
        A      var1      var2
0  110.04  0.007591  0.768843
1  112.83  0.426480  0.902606
</code>```

Body:
I have a dataframe df1 with some variables, given for certain values A:

df1 = pd.DataFrame({"A": [110.035,110.078,110.732,112.828,112.930],
               "var1": np.random.random(5),
               "var2":np.random.random(5)})

       A          var1        var2
0   110.035     0.500537    0.571497
1   110.078     0.234550    0.732815
2   110.732     0.337149    0.098250
3   112.828     0.190261    0.366118
4   112.930     0.990539    0.892640

and a dataframe df2 of values A like

df2 = pd.DataFrame({"A": [110.04, 112.83]})

      A
0   110.04
1   112.83

Now I want to keep all values in df1, that are closest to one of the values in df2 and drop all the others. In my example I want to keep rows 0 and 3 only.

My idea is to build the absolute differences and use argsort():

(df1.A-x).abs().argsort()[:1]

but this works for one value x only, how can I extend this to all values in df2?

Body:
Op1  numpy.searchsorted

Using numpy.searchsorted then using index slice the df1

df1.loc[np.searchsorted(df1.A, df2.A)-1]
Out[826]:
         A      var1      var2
0  110.035  0.007591  0.768843
3  112.828  0.426480  0.902606

Op2  merge_asof

pd.merge_asof(df2,df1,on='A',direction='nearest')
Out[819]:
        A      var1      var2
0  110.04  0.007591  0.768843
1  112.83  0.426480  0.902606


问:
Differences between ConstraintLayout and RelativeLayout
What is the difference between ConstraintLayout and RelativeLayout?

答:
In addition to @dhaval-jivani answer.

I've updated the project github project to latest version of constraint layout v.1.1.0-beta3

I've measured and compared the time of onCreate method and time between a start of onCreate and end of execution of last preformDraw method which visible in CPU monitor. All test were done on Samsung S5 mini with android 6.0.1
Here results:

Fresh start (first screen opening after application launch)

Relative Layout

OnCreate:       123ms

Last preformDraw time - OnCreate time:  311.3ms

Constraint Layout

OnCreate:       120.3ms

Last preformDraw time - OnCreate time:  310ms

Besides that, I've checked performance test from this article , here the code
and found that on loop counts less than 100 constraint layout variant is faster during execution of inflating, measure, and layout then variants with Relative Layout. And on old Android devices, like Samsung S3 with Android 4.3, the difference is bigger.

As a conclusion I agree with comments from the article:

Does it worth to refactor old views switch on it from RelativeLayout or LinearLayout?

As always: It depends

I wouldn’t refactor anything unless you either have a performance problem with your current layout hierarchy or you want to make significant changes to the layout anyway. Though I haven’t measured it lately, I haven’t found any performance issues in the last releases. So I think you should be safe to use it. but – as I’v said – don’t just migrate for the sake of migrating. Only do so, if there’s a need for and benefit from it.
  For new layouts, though, I nearly always use ConstraintLayout. It’s so much better compare to what we had before.


问:
R: using param_get
I am new to R, migrating from SAS :) I have the following df:

```<code>id      scd     cat     qs
700689  1       di      NS=Ev12&id=1048&id2=1048&id3=ZX&HId=xl
</code>```

The qs is a url decoded query string and I am trying to get the following output

```<code>id      scd  cat    qs                               NS   id  id2  id3 HId
700689  1    di     NS=Ev12&id=1&id2=10&id3=Z&HId=x  Ev12  1   10  Z    X
</code>```

I am using the following code and the output seems to add a"q." to every column. I am unable to use any function on the added columns.

raw2$q <- param_get(raw2$qs, c("NS","id","id2","id3",HId"))

e.g. test <- na.omit(raw2$NS) does not work.

Any suggestion and help will be appreciated

答:
This fails because param_get (assuming it is the function from the package urltools) does not return a single value, and you are telling it to bind it to the column named q.

If all you want to do is bind the columns to the data frame, you could use cbind from base r

```<code># To recreate your example
library(urltools)
id <- 700689
scd  <- 1
cat <- 'di'
qs <- 'NS=Ev12&id=1048&id2=1048&id3=ZX&HId=xl'
raw <- data.frame(id, scd, cat, qs)

# The line you need
cbind(raw, param_get(raw$qs, c("NS","id","id2","id3","HId")))
</code>```

Which returns

```<code>      id scd cat                                      qs   NS   id  id2 id3 HId
1 700689   1  di NS=Ev12&id=1048&id2=1048&id3=ZX&HId=xl  Ev12 1048 1048  ZX  xl
</code>```

Title: R: using param_get

Body:
I am new to R, migrating from SAS :) I have the following df:

id      scd     cat     qs
700689  1       di      NS=Ev12&id=1048&id2=1048&id3=ZX&HId=xl

The qs is a url decoded query string and I am trying to get the following output

id      scd  cat    qs                               NS   id  id2  id3 HId
700689  1    di     NS=Ev12&id=1&id2=10&id3=Z&HId=x  Ev12  1   10  Z    X

I am using the following code and the output seems to add a"q." to every column. I am unable to use any function on the added columns.

raw2$q <- param_get(raw2$qs, c("NS","id","id2","id3",HId"))

e.g. test <- na.omit(raw2$NS) does not work.

Any suggestion and help will be appreciated

Body:
This fails because param_get (assuming it is the function from the package urltools) does not return a single value, and you are telling it to bind it to the column named q.

If all you want to do is bind the columns to the data frame, you could use cbind from base r

# To recreate your example
library(urltools)
id <- 700689
scd  <- 1
cat <- 'di'
qs <- 'NS=Ev12&id=1048&id2=1048&id3=ZX&HId=xl'
raw <- data.frame(id, scd, cat, qs)

# The line you need
cbind(raw, param_get(raw$qs, c("NS","id","id2","id3","HId")))

Which returns

      id scd cat                                      qs   NS   id  id2 id3 HId
1 700689   1  di NS=Ev12&id=1048&id2=1048&id3=ZX&HId=xl  Ev12 1048 1048  ZX  xl


问:
MSBuild restore target - MSB4057: The target "restore" does not exist in the project
We have over 20 solutions in our main product portfolio (over 880 projects), and we have a complex set of build scripts that work well, but we are trying to automate the restore of nuget packages from within the msbuild pipeline. Currently this is done with a manual call out to nuget to restore the packages.

According to https://learn.microsoft.com/en-us/nuget/schema/msbuild-targets I should be able to run this command and have the restore run:

```<code># works
& $script:msBuildPath $solutionName /t:build /v:q /clp:ErrorsOnly /nologo /p:...
# doesn't works
& $script:msBuildPath $solutionName /t:restore,build /v:q /clp:ErrorsOnly /nologo /p:...
</code>```

However, when I add the restore, to the above it throws an error

```<code>MSB4057: The target "restore" does not exist in the project
</code>```

Where do I start researching to understand why it can't find this target? We are predominantly on VS 2015 and .NET 4.6.2, so anything specific to VS2017 is not an option for me at this time.

If I omit the /v:q and /clp:ErrorsOnly flags I do get this (slightly sanitized solution/project names and paths)

```<code>PS Z:\git\company> build c
building Common\Common.sln
Build started 11/15/2017 11:08:54 AM.
     1>Project "Z:\git\company\Common\Common.sln" on node 1 (restore;build target(s)).
     1>ValidateSolutionConfiguration:
         Building solution configuration "DEBUG|Any CPU".
     1>Z:\git\company\Common\Common.sln.metaproj : error MSB4057: The target "restore" does not exist in the project. [Z:\git\company\Common\Common.sln]
     1>Done Building Project "Z:\git\company\Common\Common.sln" (restore;build target(s)) -- FAILED.

Build FAILED.

       "Z:\git\company\Common\Common.sln" (restore;build target) (1) ->
         Z:\git\company\Common\Common.sln.metaproj : error MSB4057: The target "restore" does not exist in the project. [Z:\git\company\Common\Common.sln]

    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:00.03
runBuildPackage :  ... failed
At Z:\git\company\psincludes\buildFunctions.ps1:11 char:5
+     runBuildPackage "Common\Common.sln"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,runBuildPackage

msbuild failed
At Z:\git\company\psincludes\buildInternals.ps1:63 char:21
+                     throw "msbuild failed";
+                     ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (msbuild failed:String) [], RuntimeException
    + FullyQualifiedErrorId : msbuild failed
</code>```

I realize some of this around is our internal tooling, I just didn't feel the need to obscure that part.

According to "the internet" this should just be "free" as part of the build process, and I'm not sure what we are missing in the csproj files here.

答:
The msbuild-integrated NuGet functionality is available in NuGet 4.0+ in conjunction with MSBuild 15, which means only in VS 2017. There is no support for the restore target for VS 2015.

The integrated restore in VS 2017 / NuGet 4 only works for projects using the new PackageReference style of referencing NuGet packages. It does not work for projects using packages.config. This new way of referencing packages is the default option for ASP.NET Core (both on .NET Framework / .NET Core), .NET Core and .NET Standard projects. It is opt-in for all other project types by selecting the style before the first install in the NuGet properties (Tools->Options->NuGet).

Note that calling /t:Restore,Build is not a good way to call this target, since restore may generate or change files that msbuild then doesn't reload. MSBuild 15.5 (upcoming update to VS 2017) introduces a /restore option instead that will call the restore target, then clear all caches which could not be cleared before and execute the normal build as requested. Before 15.5, it is best to make two distinct calls to msbuild.

Body:
We have over 20 solutions in our main product portfolio (over 880 projects), and we have a complex set of build scripts that work well, but we are trying to automate the restore of nuget packages from within the msbuild pipeline. Currently this is done with a manual call out to nuget to restore the packages.

According to https://learn.microsoft.com/en-us/nuget/schema/msbuild-targets I should be able to run this command and have the restore run:

# works
& $script:msBuildPath $solutionName /t:build /v:q /clp:ErrorsOnly /nologo /p:...
# doesn't works
& $script:msBuildPath $solutionName /t:restore,build /v:q /clp:ErrorsOnly /nologo /p:...

However, when I add the restore, to the above it throws an error

MSB4057: The target "restore" does not exist in the project

Where do I start researching to understand why it can't find this target? We are predominantly on VS 2015 and .NET 4.6.2, so anything specific to VS2017 is not an option for me at this time.

If I omit the /v:q and /clp:ErrorsOnly flags I do get this (slightly sanitized solution/project names and paths)

PS Z:\git\company> build c
building Common\Common.sln
Build started 11/15/2017 11:08:54 AM.
     1>Project "Z:\git\company\Common\Common.sln" on node 1 (restore;build target(s)).
     1>ValidateSolutionConfiguration:
         Building solution configuration "DEBUG|Any CPU".
     1>Z:\git\company\Common\Common.sln.metaproj : error MSB4057: The target "restore" does not exist in the project. [Z:\git\company\Common\Common.sln]
     1>Done Building Project "Z:\git\company\Common\Common.sln" (restore;build target(s)) -- FAILED.

Build FAILED.

       "Z:\git\company\Common\Common.sln" (restore;build target) (1) ->
         Z:\git\company\Common\Common.sln.metaproj : error MSB4057: The target "restore" does not exist in the project. [Z:\git\company\Common\Common.sln]

    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:00.03
runBuildPackage :  ... failed
At Z:\git\company\psincludes\buildFunctions.ps1:11 char:5
+     runBuildPackage "Common\Common.sln"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,runBuildPackage

msbuild failed
At Z:\git\company\psincludes\buildInternals.ps1:63 char:21
+                     throw "msbuild failed";
+                     ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (msbuild failed:String) [], RuntimeException
    + FullyQualifiedErrorId : msbuild failed

I realize some of this around is our internal tooling, I just didn't feel the need to obscure that part.

According to "the internet" this should just be "free" as part of the build process, and I'm not sure what we are missing in the csproj files here.


问:
Gracefully remove a datasource from VS VB 2008 project?
What is the best way to remove a data source you no longer need from a VB2008 project?

Deleting the Data source in the Solution Explorer throws up loads of errors. Deleting tables in the design view of the Dataset designer throws errors. Deleting the Table Adapters at the bottom of the form throws up errors, and now my Toolbox is littered with old data source components in the <ProjectName> Components palette.

How do I remove a data source gracefully? Am I missing something obvious?

答:
Through a bit of reading of all the objects created, and a bit of logical thinking, a satisfactory order I have found is.

Delete Binding Source

Delete table adapter

DO NOT DELETE TABLE ADAPTER MANAGER if there are any other data sources.

Remove lines of code placed in form Load event

Delete schema from Solution Explorer

I still don't know how to remove the extra bits from the Toolbox though. Can anyone help with this bit?

LastEditorDisplayName: Kent Fredric


问:
Shift all elements of a increasing list to another list
I have a synchronized ArrayList which is getting it's size increased by multiple threads by adding objects to the list. I need to read this list in chunks and keep appending to a file. I need a code using which I can move first few elements of the ArrayList to another ArrayList and use the second arraylist to append to the file. All the elements of second arraylist should be removed from the synchronized ArrayList. I need to repeat this function till the synchronized ArrayList becomes empty. Please suggest a code for same.</p>

答:
Use Blocking queues.

```<code>BlockingQueue<String> queue = new ArrayBlockingQueue<>(1000);
</code>```

Add to queue from your threads just the way you do in your list now.

In a seperate thread do this:

```<code>while(queue.peek()!=null){
    String s=queue.poll();
    //Write to file
}
</code>```

Body:
Use Blocking queues.

BlockingQueue<String> queue = new ArrayBlockingQueue<>(1000);

Add to queue from your threads just the way you do in your list now.

In a seperate thread do this:

while(queue.peek()!=null){
    String s=queue.poll();
    //Write to file
}


问:
HTML5 video tag on IOS 11
I have working code for a video element within my site thats fully functioning on ios 9/10 and all the normal browsers (chrome/ff/ie) etc.

I've noticed that since the ios 11 update the videos no longer play or even work at all. They appear as a blank box with the controls but pressing play does nothing and opening the video full screen does nothing.

Here is my relatively simple code

```<code>         <video playsinline onclick="play()" controls autoplay
         controlsList="nodownload">
           <source src="assets/images/video_im.mp4" type="video/mp4">
         </video>
</code>```

I've tried different variations of using playsinline="true" and controls="true". They have no effect.

I've tried to google the issue but there seems to be nothing except a podcast taking about ios 11 removing html5 video support, surely there is a fix?

Any insight/help would be much appreciated.

Cheers

答:
It looks like the following code:

<video>
    <source src="path/to/video.mp4">
</video>
```

<p>stopped working on ios11 (with many other features too...). I confirm that <code>source</code> tag did work on ios9 here). Try placing the <code>src="path/to/video.mp4"</code> into the <code>video</code> tag directly, it should work on ios11.</p>

<p>A working example taken from webkit.org post on New video Policies for iOS:</p>

<pre class="lang-html prettyprint-override"><code><div id="either-gif-or-video">
  <video src="image.mp4" autoplay loop muted playsinline></video>
  <img src="image.gif">
</div>
</code>```

Safari on MacOS seems to have a similar problem, maybe it's easier to test there. Looks like we lost the multiple source feature tho :(

Title: HTML5 video tag on IOS 11

Body:
I have working code for a video element within my site thats fully functioning on ios 9/10 and all the normal browsers (chrome/ff/ie) etc.

I've noticed that since the ios 11 update the videos no longer play or even work at all. They appear as a blank box with the controls but pressing play does nothing and opening the video full screen does nothing.

Here is my relatively simple code

         <video playsinline onclick="play()" controls autoplay
         controlsList="nodownload">
           <source src="assets/images/video_im.mp4" type="video/mp4">
         </video>

I've tried different variations of using playsinline="true" and controls="true". They have no effect.

I've tried to google the issue but there seems to be nothing except a podcast taking about ios 11 removing html5 video support, surely there is a fix?

Any insight/help would be much appreciated.

Cheers

Body:
It looks like the following code:

<video>
    <source src="path/to/video.mp4">
</video>

stopped working on ios11 (with many other features too...). I confirm that source tag did work on ios9 here). Try placing the src="path/to/video.mp4" into the video tag directly, it should work on ios11.

A working example taken from webkit.org post on New video Policies for iOS:

<div id="either-gif-or-video">
  <video src="image.mp4" autoplay loop muted playsinline></video>
  <img src="image.gif">
</div>

Safari on MacOS seems to have a similar problem, maybe it's easier to test there. Looks like we lost the multiple source feature tho :(


问:
One-liner version of this function? (Ruby 1.8.6)
In the version of Ruby i'm using, (1.8.6 - don't ask), the Hash class doesn't define the Hash#hash method, which means that calling uniq on an array of hashes doesn't test whether the content is the same - it tests whether the objects are the same (using the default base Object#hash method).

To get around this, I can use include?, like so:

```<code>hashes = <a big list of hashes>
uniq_hashes = []
hashes.each do |hash|
  unless uniq_hashes.include?(hash)
    uniq_hashes << hash
  end
end;uniq_hashes.size
</code>```

Can anyone think of a way to condense this into a one-line method?

答:
Rather than using include? to check if each hash matches a previously-examined hash, one can speed things up by making use of a set. Recall that a set is implemented with a hash under the covers, which explains why lookups are so fast.

```<code>require 'set'

def uniq_hashes(arr)
  st = Set.new
  arr.select { |h| st.add?(h) }
end

uniq_hashes [{ a: 1, b: 2 }, { b: 2, a: 1 }, { a: 1, c: 2 }]
  #=> [{:a=>1, :b=>2}, {:a=>1, :c=>2}]
</code>```

See Set#add?.

Body:
In the version of Ruby i'm using, (1.8.6 - don't ask), the Hash class doesn't define the Hash#hash method, which means that calling uniq on an array of hashes doesn't test whether the content is the same - it tests whether the objects are the same (using the default base Object#hash method).

To get around this, I can use include?, like so:

hashes =
uniq_hashes = []
hashes.each do |hash|
  unless uniq_hashes.include?(hash)
    uniq_hashes << hash
  end
end;uniq_hashes.size

Can anyone think of a way to condense this into a one-line method?

Body:
Rather than using include? to check if each hash matches a previously-examined hash, one can speed things up by making use of a set. Recall that a set is implemented with a hash under the covers, which explains why lookups are so fast.

require 'set'

def uniq_hashes(arr)
  st = Set.new
  arr.select { |h| st.add?(h) }
end

uniq_hashes [{ a: 1, b: 2 }, { b: 2, a: 1 }, { a: 1, c: 2 }]
  #=> [{:a=>1, :b=>2}, {:a=>1, :c=>2}]

See Set#add?.


答:
As @OliverCharlesworth said, this is a job for a queue, and in java, that is handled by the Deque interface.

You don't need 2 lists. You just need a single Deque, either a BlockingLinkedDeque or a ConcurrentLinkedDeque
This will handle the thread-safety.
Comparison

A deque has 2 sides that can be added to or removed from accordingly
The workflow would be like so:

```<code>worker threads >> deque >> file
</code>```

Worker threads add to the beginning of the deque
The file code polls the end of the deque until it's empty and appends to the file.

```<code>// in the workers
dueue.addFirst(aString);

// in the monitor
String current;
while((current = deque.pollLast()) != null){
    // append to File or buffer
}
</code>```

Title: Shift all elements of a increasing list to another list

Body: I have a synchronized ArrayList which is getting it's size increased by multiple threads by adding objects to the list. I need to read this list in chunks and keep appending to a file. I need a code using which I can move first few elements of the ArrayList to another ArrayList and use the second arraylist to append to the file. All the elements of second arraylist should be removed from the synchronized ArrayList. I need to repeat this function till the synchronized ArrayList becomes empty. Please suggest a code for same.

Body:
As @OliverCharlesworth said, this is a job for a queue, and in java, that is handled by the Deque interface.

You don't need 2 lists. You just need a single Deque, either a BlockingLinkedDeque or a ConcurrentLinkedDeque
This will handle the thread-safety.
Comparison

A deque has 2 sides that can be added to or removed from accordingly
The workflow would be like so:

worker threads >> deque >> file

Worker threads add to the beginning of the deque
The file code polls the end of the deque until it's empty and appends to the file.

// in the workers
dueue.addFirst(aString);

// in the monitor
String current;
while((current = deque.pollLast()) != null){
    // append to File or buffer
}


问:
How can Guava just cast future to listenable future?
Exploring the classes in guava to understand the benefits what guava brings, even though with the introduction of java 8, it does not matter that much now, but I am still wondering about how listenableFuture is introduced.

in AbstractListeningExecutorService, there is code snippet like this:

```<code>  @Override
  public ListenableFuture<?> submit(Runnable task) {
    return (ListenableFuture<?>) super.submit(task);
  }
</code>```

here super indicates the super class of AbstractListeningExecutorService, namely ExecutorService, but how can we just cast a superclass (Future) to a subclass (ListenableFuture) like this ?

答:
You'll notice the direct superclass of AbstractListeningExecutorService is AbstractExecutorService which

Provides default implementations of ExecutorService execution methods.
  This class implements the submit, invokeAny and invokeAll methods
  using a RunnableFuture returned by newTaskFor, which defaults to the
  FutureTask class provided in this package.

That default is overriden in AbstractListeningExecutorService

Abstract ListeningExecutorService implementation that creates
  ListenableFuture instances for each Runnable and Callable submitted to
  it

You can also see that in the source code you linked to

```<code>  /** @since 19.0 (present with return type {@code ListenableFutureTask} since 14.0) */
  @Override
  protected final <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
    return TrustedListenableFutureTask.create(runnable, value);
  }
</code>```

That create returns a TrustedListenableFutureTask value, which is a subtype of ListenableFuture.

Those methods in AbstractListeningExecutorService are redeclared so that their return type can be made more specific, ie. ListenableFuture.

Since super.submit(..) has a return type of Future, the return value must be cast to the appropriate subtype, ie. ListenableFuture in this case. And since all calls return the instance created by newTaskFor, it is known that they will be instances of type ListenableFuture. The cast is therefore safe.

Body:
Exploring the classes in guava to understand the benefits what guava brings, even though with the introduction of java 8, it does not matter that much now, but I am still wondering about how listenableFuture is introduced.

in AbstractListeningExecutorService, there is code snippet like this:

  @Override
  public ListenableFuture<?> submit(Runnable task) {
    return (ListenableFuture<?>) super.submit(task);
  }

here super indicates the super class of AbstractListeningExecutorService, namely ExecutorService, but how can we just cast a superclass (Future) to a subclass (ListenableFuture) like this ?

Body:
You'll notice the direct superclass of AbstractListeningExecutorService is AbstractExecutorService which

Provides default implementations of ExecutorService execution methods.
  This class implements the submit, invokeAny and invokeAll methods
  using a RunnableFuture returned by newTaskFor, which defaults to the
  FutureTask class provided in this package.

That default is overriden in AbstractListeningExecutorService

Abstract ListeningExecutorService implementation that creates
  ListenableFuture instances for each Runnable and Callable submitted to
  it

You can also see that in the source code you linked to

  /** @since 19.0 (present with return type {@code ListenableFutureTask} since 14.0) */
  @Override
  protected final <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
    return TrustedListenableFutureTask.create(runnable, value);
  }

That create returns a TrustedListenableFutureTask value, which is a subtype of ListenableFuture.

Those methods in AbstractListeningExecutorService are redeclared so that their return type can be made more specific, ie. ListenableFuture.

Since super.submit(..) has a return type of Future, the return value must be cast to the appropriate subtype, ie. ListenableFuture in this case. And since all calls return the instance created by newTaskFor, it is known that they will be instances of type ListenableFuture. The cast is therefore safe.