问:
Jumping between object code with different (and unknown) calling convention in C
I have (mapped in memory) two object files, "A.o" and "B.o", with the same CPU Instruction Set (not necessarily Intel --it can be x86, x86_64, MIPS(32/64), ARM(32/64), PowerPC(32/64),..., but always the same in both object files).

Also, both object files are compiled with the same endianness (both little endian, or both big endian).

However (you knew there was a however, otherwise there wouldn't be any question), "A.o" and "B.o" can have a different function calling convention and, to make things worse, unknown to each other ("A.o" has not even the slightest idea about the calling convention for functions in "B.o", and vice versa).

"A.o" and "B.o" are obviously designed to call functions within their same object file, but there must be a (very) limited interface for communicating between them (otherwise, if execution starts at some function in "A.o", no function from "B.o" would ever be executed if there was no such interface).

The file where execution started (let's suppose it's "A.o") knows the addresses of all static symbols from "B.o" (the addresses of all functions and all global variables). But the opposite is not true (well, the limited interface I'm trying to write would overcome that, but "B.o" doesn't know any address from "A.o" before such interface is established).

Finally the question: How can execution jump from a function in "A.o" to a function in "B.o", and back, while also communicating some data?

I need it to:

Be done in standard C (no assembly).

Be portable C (not compiler-dependent, nor CPU-dependent).

Be thread safe.

Don't make any assumption about the calling conventions involved.

Be able to communicate data between the two object files.

My best idea, for the moment, seems that can meet all these requirements, except thread safety. For example, if I define an struct like this:

```<code>struct data_interface {
   int value_in;
   int value_out; };
</code>```

I could write a pointer to an struct like this from "A.o" into a global variable of "B.o" (knowing in advance that such global variable in "B.o" has space enough for storing a pointer).

Then, the interface function would be a void interface(void) (I'm assuming that calling void(void) functions is safe across different calling conventions... if this is not true, then my idea wouldn't work). Calling such a function from "A.o" to "B.o" would communicate the data to the code in "B.o". And, fingers crossed, when the called function in "B.o" returns, it would travel back nicely (supposing the different calling convention doesn't change the behaviour when returning from void(void) functions).

However, this is not thread safe, of course.

For it to be thread safe, I guess my only option is to access the stack.

But... can the stack be accessed in a portable way in standard C?

答:
the question implies that both object files are compiled differently except for the endianness and that they are linked together into one executable.

it says that A.o knows all static symbols from B.o, but the opposite is not true.

Don't make any assumption about the calling conventions involved.

so we'll be using only void f(void) type of functions.

you'll declare int X, Y; in B.o and extern int X, Y; in A.o so before you call the functions in B.o you check the Y flag, if raised wait until it falls. when a B's function is called it raises the Y flag, read the input from X, do some calculations, write the result back in X and return.

then the calling function in A.o copies the value from X into it's own compilation unit and clears the Y flag.

...if calling a void f(void) function just makes a wild jump from one point in the code to another.

another way to do it would be to declare static int Y = 0; in B.o and omit it entirely in A.o

then when a B.o function gets called it checks if Y == 0 and if so increase Y, read X, do calculations, write X, decrease Y and return. if not so then wait to become 0 and block the calling function.

or maybe even have a static flag in every B.o function, but i don't see the point in this waste since the communication data is global in B.o

Body:
I have (mapped in memory) two object files, "A.o" and "B.o", with the same CPU Instruction Set (not necessarily Intel --it can be x86, x86_64, MIPS(32/64), ARM(32/64), PowerPC(32/64),..., but always the same in both object files).

Also, both object files are compiled with the same endianness (both little endian, or both big endian).

However (you knew there was a however, otherwise there wouldn't be any question), "A.o" and "B.o" can have a different function calling convention and, to make things worse, unknown to each other ("A.o" has not even the slightest idea about the calling convention for functions in "B.o", and vice versa).

"A.o" and "B.o" are obviously designed to call functions within their same object file, but there must be a (very) limited interface for communicating between them (otherwise, if execution starts at some function in "A.o", no function from "B.o" would ever be executed if there was no such interface).

The file where execution started (let's suppose it's "A.o") knows the addresses of all static symbols from "B.o" (the addresses of all functions and all global variables). But the opposite is not true (well, the limited interface I'm trying to write would overcome that, but "B.o" doesn't know any address from "A.o" before such interface is established).

Finally the question: How can execution jump from a function in "A.o" to a function in "B.o", and back, while also communicating some data?

I need it to:

Be done in standard C (no assembly).

Be portable C (not compiler-dependent, nor CPU-dependent).

Be thread safe.

Don't make any assumption about the calling conventions involved.

Be able to communicate data between the two object files.

My best idea, for the moment, seems that can meet all these requirements, except thread safety. For example, if I define an struct like this:

struct data_interface {
   int value_in;
   int value_out; };

I could write a pointer to an struct like this from "A.o" into a global variable of "B.o" (knowing in advance that such global variable in "B.o" has space enough for storing a pointer).

Then, the interface function would be a void interface(void) (I'm assuming that calling void(void) functions is safe across different calling conventions... if this is not true, then my idea wouldn't work). Calling such a function from "A.o" to "B.o" would communicate the data to the code in "B.o". And, fingers crossed, when the called function in "B.o" returns, it would travel back nicely (supposing the different calling convention doesn't change the behaviour when returning from void(void) functions).

However, this is not thread safe, of course.

For it to be thread safe, I guess my only option is to access the stack.

But... can the stack be accessed in a portable way in standard C?


来源: stackexchange

问:
How can we get the objects in reverse order from list object?
in my List object(of generic type of pojo class objects) i am getting that list by calling service method, as per my requirement i have to place those object values in reverse order, for example

```<code>List<MyPojo> listData = serviceObj.getTableDate();//gets the total content of table
if(listData.size()>0){
  int i=0;
  while(i>=listData.size()){
    listData.get(i).getPojoId();
    listData.get(i).getPojoName();
  }
}
</code>```

Note: please dont tell to me use iterator or to use ListIterator, because i am showing the data in Grid(JQuery) some logic will fail while using iterator, the code what written was just sample of few lines only.

答: Guava has Iterables.reverse(List), which returns a reversed view of the original list without modifying it.

ContentLicense: CC BY-SA 2.5

Body:
in my List object(of generic type of pojo class objects) i am getting that list by calling service method, as per my requirement i have to place those object values in reverse order, for example

List<MyPojo> listData = serviceObj.getTableDate();//gets the total content of table
if(listData.size()>0){
  int i=0;
  while(i>=listData.size()){
    listData.get(i).getPojoId();
    listData.get(i).getPojoName();
  }
}

Note: please dont tell to me use iterator or to use ListIterator, because i am showing the data in Grid(JQuery) some logic will fail while using iterator, the code what written was just sample of few lines only.


问:
How can I get the combined script result for janusgraph?
Graph is below:

```<code>gremlin> a = graph.addVertex("name", "alice")
gremlin> b = graph.addVertex("name", "bobby")
gremlin> c = graph.addVertex("name", "cindy")
gremlin> d = graph.addVertex("name", "david")
gremlin> e = graph.addVertex("name", "eliza")
gremlin> a.addEdge("rates",b,"tag","ruby","value",9)
gremlin> b.addEdge("rates",c,"tag","ruby","value",8)
gremlin> c.addEdge("rates",d,"tag","ruby","value",7)
gremlin> d.addEdge("rates",e,"tag","ruby","value",6)
gremlin> e.addEdge("rates",a,"tag","java","value",10)
</code>```

I have 3 scripts below:

Script #1

```<code>gremlin> g.V().has('name','alice').
           repeat(out()).
             until(has('name','alice')).
           cyclicPath().
           path().by('name')`
==>[alice,bobby,cindy,david,eliza,alice]
</code>```

Script #2

```<code>gremlin> g.V().has('name','alice').
           repeat(outE().inV()).
             until(has('name','alice')).
           cyclicPath().
           group().
             by('name').
             by(path().unfold().has('value').values('value').fold()).
           next()
==>alice=[9, 8, 7, 6, 10]
</code>```

Script #3

```<code>gremlin> g.V().has('name','alice').
           repeat(outE().inV()).
             until(has('name','alice')).
           cyclicPath().
           group().
             by('name').
             by(path().unfold().has('value').values('value').fold()).
           next().collect { k, v ->
             k + '=' + v.withIndex().collect { Integer it, Integer idx ->
                 return it * (1/(idx + 1))
             }.inject(0.0) { acc,i -> acc + i }
           }
==>alice=18.8333333331
</code>```

My question is, how can I get the result as below listed? Just combine the 3

```<code>alice=[alice,bobby,cindy,david,eliza,alice]=[9, 8, 7, 6, 10]=18.8333333331
</code>```

答:
It's probably much easier or at least more maintainable to execute 3 queries and then merge the results as suggested by David. However, if you want to do it all in a single query, you can:

```<code>g.V().has('name','alice').as('v').
  repeat(outE().as('e').inV().as('v')).
    until(has('name','alice')).
  store('a').
    by('name').
  store('a').
    by(select(all, 'v').unfold().values('name').fold()).
  store('a').
    by(select(all, 'e').unfold().
       store('x').
         by(union(values('value'),
                  select('x').count(local)).fold()).
       cap('x').
       store('a').
         by(unfold().limit(local, 1).fold()).unfold().
       sack(assign).
         by(constant(1d)).
       sack(div).
         by(union(constant(1d),
                  tail(local, 1)).sum()).
       sack(mult).
         by(limit(local, 1)).
       sack().sum()).
  cap('a')
</code>```

Using your sample graph:

```<code>gremlin> g.V().has('name','alice').as('v').
......1>   repeat(outE().as('e').inV().as('v')).
......2>     until(has('name','alice')).
......3>   store('a').
......4>     by('name').
......5>   store('a').
......6>     by(select(all, 'v').unfold().values('name').fold()).
......7>   store('a').
......8>     by(select(all, 'e').unfold().
......9>        store('x').
.....10>          by(union(values('value'),
.....11>                   select('x').count(local)).fold()).
.....12>        cap('x').
.....13>        store('a').
.....14>          by(unfold().limit(local, 1).fold()).unfold().
.....15>        sack(assign).
.....16>          by(constant(1d)).
.....17>        sack(div).
.....18>          by(union(constant(1d),
.....19>                   tail(local, 1)).sum()).
.....20>        sack(mult).
.....21>          by(limit(local, 1)).
.....22>        sack().sum()).
.....23>   cap('a')
==>[alice,[alice,bobby,cindy,david,eliza,alice],[9,8,7,6,10],18.833333333333332]
</code>```

It has some benefits to do it all in a single query, especially as you don't have to traverse the same path over and over again, but again, it's hard to maintain such complex queries. It's probably better to just return the full path and then build the expected result on the client side.

ContentLicense: CC BY-SA 3.0

Body:
Graph is below:

gremlin> a = graph.addVertex("name", "alice")
gremlin> b = graph.addVertex("name", "bobby")
gremlin> c = graph.addVertex("name", "cindy")
gremlin> d = graph.addVertex("name", "david")
gremlin> e = graph.addVertex("name", "eliza")
gremlin> a.addEdge("rates",b,"tag","ruby","value",9)
gremlin> b.addEdge("rates",c,"tag","ruby","value",8)
gremlin> c.addEdge("rates",d,"tag","ruby","value",7)
gremlin> d.addEdge("rates",e,"tag","ruby","value",6)
gremlin> e.addEdge("rates",a,"tag","java","value",10)

I have 3 scripts below:

Script #1

gremlin> g.V().has('name','alice').
           repeat(out()).
             until(has('name','alice')).
           cyclicPath().
           path().by('name')`
==>[alice,bobby,cindy,david,eliza,alice]

Script #2

gremlin> g.V().has('name','alice').
           repeat(outE().inV()).
             until(has('name','alice')).
           cyclicPath().
           group().
             by('name').
             by(path().unfold().has('value').values('value').fold()).
           next()
==>alice=[9, 8, 7, 6, 10]

Script #3

gremlin> g.V().has('name','alice').
           repeat(outE().inV()).
             until(has('name','alice')).
           cyclicPath().
           group().
             by('name').
             by(path().unfold().has('value').values('value').fold()).
           next().collect { k, v ->
             k + '=' + v.withIndex().collect { Integer it, Integer idx ->
                 return it * (1/(idx + 1))
             }.inject(0.0) { acc,i -> acc + i }
           }
==>alice=18.8333333331

My question is, how can I get the result as below listed? Just combine the 3

alice=[alice,bobby,cindy,david,eliza,alice]=[9, 8, 7, 6, 10]=18.8333333331

Body:
It's probably much easier or at least more maintainable to execute 3 queries and then merge the results as suggested by David. However, if you want to do it all in a single query, you can:

g.V().has('name','alice').as('v').
  repeat(outE().as('e').inV().as('v')).
    until(has('name','alice')).
  store('a').
    by('name').
  store('a').
    by(select(all, 'v').unfold().values('name').fold()).
  store('a').
    by(select(all, 'e').unfold().
       store('x').
         by(union(values('value'),
                  select('x').count(local)).fold()).
       cap('x').
       store('a').
         by(unfold().limit(local, 1).fold()).unfold().
       sack(assign).
         by(constant(1d)).
       sack(div).
         by(union(constant(1d),
                  tail(local, 1)).sum()).
       sack(mult).
         by(limit(local, 1)).
       sack().sum()).
  cap('a')

Using your sample graph:

gremlin> g.V().has('name','alice').as('v').
......1>   repeat(outE().as('e').inV().as('v')).
......2>     until(has('name','alice')).
......3>   store('a').
......4>     by('name').
......5>   store('a').
......6>     by(select(all, 'v').unfold().values('name').fold()).
......7>   store('a').
......8>     by(select(all, 'e').unfold().
......9>        store('x').
.....10>          by(union(values('value'),
.....11>                   select('x').count(local)).fold()).
.....12>        cap('x').
.....13>        store('a').
.....14>          by(unfold().limit(local, 1).fold()).unfold().
.....15>        sack(assign).
.....16>          by(constant(1d)).
.....17>        sack(div).
.....18>          by(union(constant(1d),
.....19>                   tail(local, 1)).sum()).
.....20>        sack(mult).
.....21>          by(limit(local, 1)).
.....22>        sack().sum()).
.....23>   cap('a')
==>[alice,[alice,bobby,cindy,david,eliza,alice],[9,8,7,6,10],18.833333333333332]

It has some benefits to do it all in a single query, especially as you don't have to traverse the same path over and over again, but again, it's hard to maintain such complex queries. It's probably better to just return the full path and then build the expected result on the client side.


问:
How to convert Object array into String arrray and split individual elements from it?

The following is the question prompt:
Create a hash with the following information in the format -

countryname => "capital:population:currency name" create at least 5 records.

Print the details of the country having the largest population
Print the currency name of those countries where capital name starts with "L".

For doing this, I was thinking of populating records with put(), converting the values of hashmap into an array, splitting the array with ":" delimeter, and doing a loop to figure out largest value from the respective column.

I was wondering whether that would be the best way of doing it, or there would be a better approach. If that way is ideal, I am having trouble converting the Object [] countryValues (in the code below) into a String array, so I can use the split function on it.

I expect this to split the values with ":" delimeter.

```<code>HashMap<String,String> countrydata = new HashMap<String, String>();

    countrydata.put("USA", "Washington DC:323,000,000:Dollar");
    countrydata.put("Thailand", "Bangkok:69,000,000:Baht");
    countrydata.put("Vietnam", "Hanoi:93,000,000:Dong");
    countrydata.put("Laos", "Lientiane:7,000,000:Dollar");
    countrydata.put("Belize", "Belmopan:370,000:Dollar");

     Object [] countryValues = countrydata.keySet().toArray();

     for (int i=0; i<countryValues.length; i++){
        String [] splitted = countryValues[i].split(":");
     }

     for (int j=0; j<splitted.length; j++){
         System.out.println(splitted[i]);
     }
</code>```

Error:

Method split(String) is undefined for type Object.

答:
Let's examine the code together:

```<code>HashMap<String,String> countrydata = new HashMap<String, String>();

countrydata.put("USA", "Washington DC:323,000,000:Dollar");
countrydata.put("Thailand", "Bangkok:69,000,000:Baht");
countrydata.put("Vietnam", "Hanoi:93,000,000:Dong");
countrydata.put("Laos", "Lientiane:7,000,000:Dollar");
countrydata.put("Belize", "Belmopan:370,000:Dollar");
</code>```

So you have a Map where the keys are country names, and the values are various information as strings, to be split.

```<code>Object [] countryValues = countrydata.keySet().toArray();
</code>```

So you're create an array of objects, and each object in the array is a key of the map: a country name.

```<code>for (int i=0; i<countryValues.length; i++){
   String [] splitted = countryValues[i].split(":");
</code>```

and you're thus trying to split the keys, instead of the values. Moreover, there is no need at all to transform a collection into an array to do a for loop. You can iterate on the collection directly:

```<code>for (String value: countrydata.values()) {
    // split the value
}
</code>```

Body:
The following is the question prompt:
Create a hash with the following information in the format -

countryname => "capital:population:currency name" create at least 5 records.

Print the details of the country having the largest population
Print the currency name of those countries where capital name starts with "L".

For doing this, I was thinking of populating records with put(), converting the values of hashmap into an array, splitting the array with ":" delimeter, and doing a loop to figure out largest value from the respective column.

I was wondering whether that would be the best way of doing it, or there would be a better approach. If that way is ideal, I am having trouble converting the Object [] countryValues (in the code below) into a String array, so I can use the split function on it.

I expect this to split the values with ":" delimeter.

HashMap<String,String> countrydata = new HashMap<String, String>();

    countrydata.put("USA", "Washington DC:323,000,000:Dollar");
    countrydata.put("Thailand", "Bangkok:69,000,000:Baht");
    countrydata.put("Vietnam", "Hanoi:93,000,000:Dong");
    countrydata.put("Laos", "Lientiane:7,000,000:Dollar");
    countrydata.put("Belize", "Belmopan:370,000:Dollar");

     Object [] countryValues = countrydata.keySet().toArray();

     for (int i=0; i<countryValues.length; i++){
        String [] splitted = countryValues[i].split(":");
     }

     for (int j=0; j<splitted.length; j++){
         System.out.println(splitted[i]);
     }

Error:

Method split(String) is undefined for type Object.

Body:
Let's examine the code together:

HashMap<String,String> countrydata = new HashMap<String, String>();

countrydata.put("USA", "Washington DC:323,000,000:Dollar");
countrydata.put("Thailand", "Bangkok:69,000,000:Baht");
countrydata.put("Vietnam", "Hanoi:93,000,000:Dong");
countrydata.put("Laos", "Lientiane:7,000,000:Dollar");
countrydata.put("Belize", "Belmopan:370,000:Dollar");

So you have a Map where the keys are country names, and the values are various information as strings, to be split.

Object [] countryValues = countrydata.keySet().toArray();

So you're create an array of objects, and each object in the array is a key of the map: a country name.

for (int i=0; i<countryValues.length; i++){
   String [] splitted = countryValues[i].split(":");

and you're thus trying to split the keys, instead of the values. Moreover, there is no need at all to transform a collection into an array to do a for loop. You can iterate on the collection directly:

for (String value: countrydata.values()) {
    // split the value
}


问:
Solr 6.6.0 Case Insensitive Query Not Working
Solr 6.6.0 Case Insensitive Query Not Working.
I had tried all other option/answer available on internet.

I had tired with,

```<code><tokenizer class="solr.LowerCaseTokenizerFactory"/>
</code>```

but its not working.

I had tired with,

```<code><filter class="solr.LowerCaseFilterFactory"/>
</code>```

but its not working.

I had tired many different way, but none working.

i.e I want same result searching with title_s:iPhone and title_s:iphone.

I am not sure what would cause problem.

答:
I had tried in many different way, but none work.
Than I had implement as below and it work fine.

Let me know below method is correct or not, but works fine for me :)

I had remove below code from schema,

```<code><fieldType name="string" class="solr.StrField" sortMissingLast="true" docValues="true"/>
</code>```

And added (replace) below code,

```<code><fieldType name="string" class="solr.TextField">
  <analyzer type="index">
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>
</code>```

Body:
Solr 6.6.0 Case Insensitive Query Not Working.
I had tried all other option/answer available on internet.

I had tired with,

<tokenizer class="solr.LowerCaseTokenizerFactory"/>

but its not working.

I had tired with,

<filter class="solr.LowerCaseFilterFactory"/>

but its not working.

I had tired many different way, but none working.

i.e I want same result searching with title_s:iPhone and title_s:iphone.

I am not sure what would cause problem.

Body:
I had tried in many different way, but none work.
Than I had implement as below and it work fine.

Let me know below method is correct or not, but works fine for me :)

I had remove below code from schema,

<fieldType name="string" class="solr.StrField" sortMissingLast="true" docValues="true"/>

And added (replace) below code,

<fieldType name="string" class="solr.TextField">
  <analyzer type="index">
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>


答:
The culprit is this line:

```<code>Object [] countryValues = countrydata.keySet().toArray();
</code>```

In addition to being named a wrong thing (it's countryKeys or countryNames, not countryValues) it makes an array of Object type rather than a String array.

You do not need countryValues at all: instead, navigate entrySet of your hash map like this:

```<code>for (Map.Entry<String,String> e : countrydata.entrySet()) {
    String name = e.getKey();
    String data = e.getValue();
    ...
}
</code>```

If you'd like to take this a little further, make a class CountryData with four properties (name, capital, population, and currency), create instances of this class, and put them in your map. Change map's type to Map<String,CountryData>. This way you would not need to do split repeatedly if you need to do some additional processing.

Title: How to convert Object array into String arrray and split individual elements from it?

Body:
The culprit is this line:

Object [] countryValues = countrydata.keySet().toArray();

In addition to being named a wrong thing (it's countryKeys or countryNames, not countryValues) it makes an array of Object type rather than a String array.

You do not need countryValues at all: instead, navigate entrySet of your hash map like this:

for (Map.Entry<String,String> e : countrydata.entrySet()) {
    String name = e.getKey();
    String data = e.getValue();
    ...
}

If you'd like to take this a little further, make a class CountryData with four properties (name, capital, population, and currency), create instances of this class, and put them in your map. Change map's type to Map<String,CountryData>. This way you would not need to do split repeatedly if you need to do some additional processing.


问:
Ruby hash permutation
Is there any quick way to get a (random) permutation of a given hash? For example with arrays I can use the sample method as in

```<code>ruby-1.9.2-p180 :031 > a = (1..5).to_a
 => [1, 2, 3, 4, 5]
ruby-1.9.2-p180 :032 > a.sample(a.length)
 => [3, 5, 1, 2, 4]
</code>```

For hashes I can use the same method on hash keys and build a new hash with

```<code>ruby-1.9.2-p180 :036 > h = { 1 => 'a', 2 => 'b', 3 => 'c' }
 => {1=>"a", 2=>"b", 3=>"c"}
ruby-1.9.2-p180 :037 > h.keys.sample(h.length).inject({}) { |h2, k| h2[k] = h[k]; h2 }
 => {3=>"c", 2=>"b", 1=>"a"}
</code>```

but this is so ugly. Is there any 'sample' method for hashes which can avoid all that code?

Update As pointed out by @Michael Kohl in comments, this question is meaningful only for ruby 1.9.x. Since in 1.8.x Hash are unordered there is no way to do that.

答:
Do you really need to shuffle or do you just need a way to access/iterate on a random key ?

Otherwise, a maybe less expensive solution would be to shuffle the hash keys and access your items based on the permutation of those hash keys

```<code>h = your_hash
shuffled_hash_keys = hash.keys.shuffle

shuffled_hash_keys.each do |key|
  # do something with h[key]
end
</code>```

I believe (but would need a proof with a benchmark) that this avoids the need/cost to build a brand new hash and is probably more efficient if you have big hashes (you only need to pay the cost of an array permutation)

Title: Ruby hash permutation

Body:
Is there any quick way to get a (random) permutation of a given hash? For example with arrays I can use the sample method as in

ruby-1.9.2-p180 :031 > a = (1..5).to_a
 => [1, 2, 3, 4, 5]
ruby-1.9.2-p180 :032 > a.sample(a.length)
 => [3, 5, 1, 2, 4]

For hashes I can use the same method on hash keys and build a new hash with

ruby-1.9.2-p180 :036 > h = { 1 => 'a', 2 => 'b', 3 => 'c' }
 => {1=>"a", 2=>"b", 3=>"c"}
ruby-1.9.2-p180 :037 > h.keys.sample(h.length).inject({}) { |h2, k| h2[k] = h[k]; h2 }
 => {3=>"c", 2=>"b", 1=>"a"}

but this is so ugly. Is there any 'sample' method for hashes which can avoid all that code?

Update As pointed out by @Michael Kohl in comments, this question is meaningful only for ruby 1.9.x. Since in 1.8.x Hash are unordered there is no way to do that.

Body:
Do you really need to shuffle or do you just need a way to access/iterate on a random key ?

Otherwise, a maybe less expensive solution would be to shuffle the hash keys and access your items based on the permutation of those hash keys

h = your_hash
shuffled_hash_keys = hash.keys.shuffle

shuffled_hash_keys.each do |key|
  # do something with h[key]
end

I believe (but would need a proof with a benchmark) that this avoids the need/cost to build a brand new hash and is probably more efficient if you have big hashes (you only need to pay the cost of an array permutation)


问:
R: plot 3d interaction model and observations using plotly
I start from a simple interaction model z = 0.5*x*y. The goal is to plot simulated observations with add_markers() as well as the model with add_surface() using the plotly library.

So far I have manage to simulate the data and plot it:

```<code>library(plotly)
library(magrittr)

x <- rnorm(10000)
y <- rnorm(10000)
z <- 0.5 * x * y

plot_ly() %>% add_markers(x = x, y = y, z = z, marker = list(size = 1))
</code>```

This is what the plot looks like:

I then tried to surface plot the model:

```<code>plot_ly() %>%
   add_markers(x = x, y = y, z = z, marker = list(size = 1)) %>%
   add_surface(z = matrix(z, 100, 100))
</code>```

But it produces something completely different to what it would be expected. This is approximately the result that would be expect from the surface plot:

What am I doing wrong?

答:
An easy workaround is to use:

```<code>plot_ly(x = x, y = y, z= z, type = 'mesh3d')
</code>```

Or using surface plot:

```<code>  library(tidyverse)
  grid <- expand.grid(x = seq(from = -3, to = 3, length.out = 100),
                      y = seq(from = -3, to = 3, length.out = 100))

  grid %>%
    mutate(z = 0.5 * x * y) %>%
    spread(key = y, value = z) %>%
    as.matrix() -> z

  plot_ly() %>%
    add_surface(z = z, x = unique(grid$x), y = unique(grid$y)) %>%
    layout(scene = list(xaxis = list(range = c(-2.5, 2.5)),
                        yaxis = list(range = c(-2.5, 2.5)))) #odd artifact if all values are plotted - check without layout call
</code>```

or:

```<code>model = lm(z ~ x * y)

grid <- expand.grid(x = seq(from = -3, to = 3, length.out = 100),
                      y = seq(from = -3, to = 3, length.out = 100))

grid$z = predict(model, grid)
</code>```

and proceed as above

```<code> grid %>%
    spread(key = y, value = z) %>%
    as.matrix() -> z
</code>```

Body:
I start from a simple interaction model z = 0.5*x*y. The goal is to plot simulated observations with add_markers() as well as the model with add_surface() using the plotly library.

So far I have manage to simulate the data and plot it:

library(plotly)
library(magrittr)

x <- rnorm(10000)
y <- rnorm(10000)
z <- 0.5 * x * y

plot_ly() %>% add_markers(x = x, y = y, z = z, marker = list(size = 1))

This is what the plot looks like:

I then tried to surface plot the model:

plot_ly() %>%
   add_markers(x = x, y = y, z = z, marker = list(size = 1)) %>%
   add_surface(z = matrix(z, 100, 100))

But it produces something completely different to what it would be expected. This is approximately the result that would be expect from the surface plot:

What am I doing wrong?

Body:
An easy workaround is to use:

plot_ly(x = x, y = y, z= z, type = 'mesh3d')

Or using surface plot:

  library(tidyverse)
  grid <- expand.grid(x = seq(from = -3, to = 3, length.out = 100),
                      y = seq(from = -3, to = 3, length.out = 100))

  grid %>%
    mutate(z = 0.5 * x * y) %>%
    spread(key = y, value = z) %>%
    as.matrix() -> z

  plot_ly() %>%
    add_surface(z = z, x = unique(grid$x), y = unique(grid$y)) %>%
    layout(scene = list(xaxis = list(range = c(-2.5, 2.5)),
                        yaxis = list(range = c(-2.5, 2.5)))) #odd artifact if all values are plotted - check without layout call

or:

model = lm(z ~ x * y)

grid <- expand.grid(x = seq(from = -3, to = 3, length.out = 100),
                      y = seq(from = -3, to = 3, length.out = 100))

grid$z = predict(model, grid)

and proceed as above

 grid %>%
    spread(key = y, value = z) %>%
    as.matrix() -> z


问:
Scrapy Spider: crawl a list of urls, starting from line n
I am crawling a list of URLs from a text file using Scrapy Spider. I am rather new to Python and Scrapy, I am just having to wing it to get this task done.

My list of URLs is rather large, so this is how I have implemented it:

from scrapy.spider import BaseSpider
from scrapy.http.request import Request
import time

class MySpider(BaseSpider):
    name = "example"
    allowed_domains = ["example.com"]

    def __init__(self, filename=None, delay=5, start_line = 0):
        self.currentline = 0
        self.download_delay = int(delay)
        self.filename = filename
        self.start_line = int(start_line)

    def start_requests(self):
        with open(self.filename, 'r') as f:
            for url in f.readlines():
                self.currentline +=1

                if self.currentline < self.start_line:
                    continue
                else:
                    print(self.currentline)
                    yield Request(url.strip(), self.parse)

    def parse(self, response):
        logfilename = 'log'
        with open(logfilename, 'a') as f:
            f.write('Crawled line ' + str(self.currentline) + ' of ' + self.filename + ': ' + response.url + '\n')
```

<p>I am not parsing anything right now, I'll worry about that later, just logging it for now.</p>

<p>I call it with, say:</p>

<pre class="lang-py prettyprint-override"><code>scrapy runspider myfolder\kwdSpider.py -a filename=myfolder\urls.txt -a delay=10 -a start_line=124
</code>```

Because the url lists can be quite large I implemented the option to restart crawling from the specified start_line (and used yield Request()). It actually all works fine, EXCEPT this:

E:\Python27>scrapy runspider mysite\kwdSpider.py -a filename=example\urls.txt -a delay=8 -a start_line=124
E:\Python27\example\kwdSpider.py:5: ScrapyDeprecationWarning: kwdSpider.MySpider inherits from deprecated class scrapy.spider.BaseSpider, please inherit from scrapy.spider.Spider. (warning only on first subclass, there may be others)
  class MySpider(BaseSpider):
2017-12-06 12:27:35+0100 [scrapy] INFO: Scrapy 0.25.1 started (bot: scrapybot)
2017-12-06 12:27:35+0100 [scrapy] INFO: Optional features available: ssl, http11
2017-12-06 12:27:35+0100 [scrapy] INFO: Overridden settings: {}
2017-12-06 12:27:35+0100 [scrapy] INFO: Enabled extensions: LogStats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState
2017-12-06 12:27:35+0100 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2017-12-06 12:27:35+0100 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2017-12-06 12:27:35+0100 [scrapy] INFO: Enabled item pipelines:
2017-12-06 12:27:35+0100 [example] INFO: Spider opened
2017-12-06 12:27:35+0100 [example] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-12-06 12:27:35+0100 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6024
2017-12-06 12:27:35+0100 [scrapy] DEBUG: Web service listening on 127.0.0.1:6081
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
2017-12-06 12:27:38+0100 [example] DEBUG: Crawled (200) <GET https://www.example.com/139th url> (referer: None)
140
2017-12-06 12:27:47+0100 [example] DEBUG: Crawled (200) <GET https://www.example.com/140th url> (referer: None)
141
```

<p>See the way that the first dozen or so URLs are skipped? I'm obviously not understanding properly how the spider works, is it not initialised before the start_requests routine has finished counting through the txt file (which is by the way the only way I could think to implement this)?</p>

<p>Bonus question - what's this notice about?</p>

<pre class="lang-py prettyprint-override"><code>@kwdSpider.MySpider inherits from deprecated class scrapy.spider.BaseSpider, please inherit from scrapy.spider.Spider. (warning only on first subclass, there may be others)
  class MySpider(BaseSpider):
</code>```

Thanks.

答:
I'm going to answer the bonus question, while investigations are ongoing with the primary issue.

Regarding the warning:

```<code>@kwdSpider.MySpider inherits from deprecated class scrapy.spider.BaseSpider, please inherit from scrapy.spider.Spider. (warning only on first subclass, there may be others)
 class MySpider(BaseSpider):
</code>```

Following the message to the word, change the code to:

```<code>from scrapy.spider import Spider
from scrapy.http.request import Request
import time

class MySpider(Spider):
</code>```

That should resolve that issue at least.

Body:
I am crawling a list of URLs from a text file using Scrapy Spider. I am rather new to Python and Scrapy, I am just having to wing it to get this task done.

My list of URLs is rather large, so this is how I have implemented it:

from scrapy.spider import BaseSpider
from scrapy.http.request import Request
import time

class MySpider(BaseSpider):
    name = "example"
    allowed_domains = ["example.com"]

    def __init__(self, filename=None, delay=5, start_line = 0):
        self.currentline = 0
        self.download_delay = int(delay)
        self.filename = filename
        self.start_line = int(start_line)

    def start_requests(self):
        with open(self.filename, 'r') as f:
            for url in f.readlines():
                self.currentline +=1

                if self.currentline < self.start_line:
                    continue
                else:
                    print(self.currentline)
                    yield Request(url.strip(), self.parse)

    def parse(self, response):
        logfilename = 'log'
        with open(logfilename, 'a') as f:
            f.write('Crawled line ' + str(self.currentline) + ' of ' + self.filename + ': ' + response.url + '\n')

I am not parsing anything right now, I'll worry about that later, just logging it for now.

I call it with, say:

scrapy runspider myfolder\kwdSpider.py -a filename=myfolder\urls.txt -a delay=10 -a start_line=124

Because the url lists can be quite large I implemented the option to restart crawling from the specified start_line (and used yield Request()). It actually all works fine, EXCEPT this:

E:\Python27>scrapy runspider mysite\kwdSpider.py -a filename=example\urls.txt -a delay=8 -a start_line=124
E:\Python27\example\kwdSpider.py:5: ScrapyDeprecationWarning: kwdSpider.MySpider inherits from deprecated class scrapy.spider.BaseSpider, please inherit from scrapy.spider.Spider. (warning only on first subclass, there may be others)
  class MySpider(BaseSpider):
2017-12-06 12:27:35+0100 [scrapy] INFO: Scrapy 0.25.1 started (bot: scrapybot)
2017-12-06 12:27:35+0100 [scrapy] INFO: Optional features available: ssl, http11
2017-12-06 12:27:35+0100 [scrapy] INFO: Overridden settings: {}
2017-12-06 12:27:35+0100 [scrapy] INFO: Enabled extensions: LogStats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState
2017-12-06 12:27:35+0100 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2017-12-06 12:27:35+0100 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2017-12-06 12:27:35+0100 [scrapy] INFO: Enabled item pipelines:
2017-12-06 12:27:35+0100 [example] INFO: Spider opened
2017-12-06 12:27:35+0100 [example] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-12-06 12:27:35+0100 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6024
2017-12-06 12:27:35+0100 [scrapy] DEBUG: Web service listening on 127.0.0.1:6081
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
2017-12-06 12:27:38+0100 [example] DEBUG: Crawled (200) <GET https://www.example.com/139th url> (referer: None)
140
2017-12-06 12:27:47+0100 [example] DEBUG: Crawled (200) <GET https://www.example.com/140th url> (referer: None)
141

See the way that the first dozen or so URLs are skipped? I'm obviously not understanding properly how the spider works, is it not initialised before the start_requests routine has finished counting through the txt file (which is by the way the only way I could think to implement this)?

Bonus question - what's this notice about?

@kwdSpider.MySpider inherits from deprecated class scrapy.spider.BaseSpider, please inherit from scrapy.spider.Spider. (warning only on first subclass, there may be others)
  class MySpider(BaseSpider):

Thanks.

Body:
I'm going to answer the bonus question, while investigations are ongoing with the primary issue.

Regarding the warning:

@kwdSpider.MySpider inherits from deprecated class scrapy.spider.BaseSpider, please inherit from scrapy.spider.Spider. (warning only on first subclass, there may be others)
 class MySpider(BaseSpider):

Following the message to the word, change the code to:

from scrapy.spider import Spider
from scrapy.http.request import Request
import time

class MySpider(Spider):

That should resolve that issue at least.


问:
Silently use Java Robot to Screenshot
I have to made a Java application that capture screen every second
(for example).

But this application have to run silently like if we use (javaw for
windows user).

The problem is that Robot usage create a frame and the menu bar of application.

So the main question is :

How I can proceed to screen silently ?

答: Just using : apple.awt.UIElement=true on vm options for Apple

Title: Silently use Java Robot to Screenshot


问:
VS Program works in debug mode but not in release mode
I'm creating a program in visual studio using the fly capture camera libraries. My goal is to build the program into a standalone application. When run in debug mode the program behaves normally, but in release mode I get a 'System.IO.FileNotFoundExeception':

```<code>Could not load file or assembly 'FlyCapture2Managed_v140.dll' or one of its dependencies. The specified module could not be found.
</code>```

So I'm missing a dll file, but why do I only get this error in release mode? How can I properly link the file in visual studios?

答:
Check your configuration, it may well be that you release configuration isn't set to build the project that produces 'FlyCapture2Managed_v140.dll'.

Right-click on your solution, select Configuration Manager, choose Release configuration and confirm the project has the Build column ticked.

Body:
I'm creating a program in visual studio using the fly capture camera libraries. My goal is to build the program into a standalone application. When run in debug mode the program behaves normally, but in release mode I get a 'System.IO.FileNotFoundExeception':

Could not load file or assembly 'FlyCapture2Managed_v140.dll' or one of its dependencies. The specified module could not be found.

So I'm missing a dll file, but why do I only get this error in release mode? How can I properly link the file in visual studios?


问:
GLM regression prediction- understanding which factor level is success
I have built a binomial glm model. The model predicts output between two potential classes: AD or Control. These variables are factors with levels: {AD, Control}. I use this model to predict and obtain probabilities for each sample, but it is unclear to me if a probability over 0.5 indicates AD or Control.

Here is my dataset:

```<code>> head(example)
          cleaned_mayo$Diagnosis pca_results$x[, 1]
1052_TCX                      AD          0.9613241
1104_TCX                      AD         -0.9327390
742_TCX                       AD          1.6908874
1945_TCX                 Control          0.6819104
134_TCX                       AD          0.5184748
11386_TCX                Control          0.4669661
</code>```

And here is my code to compute the model and make predictions:

```<code># Randomize rows of top performer
example<- example[sample(nrow(example)),]

# Subset data for training and testing
N_train<- round(nrow(example)*0.75)
train<- example[1:N_train,]
test<- example[(N_train+1):nrow(example),]
colnames(train)[1:2]<- c("Diagnosis", "Eigen_gene")
colnames(test)[1:2]<- c("Diagnosis", "Eigen_gene")

# Build model and predict
model_IFGyel<- glm(Diagnosis ~ Eigen_gene, data = train, family = binomial())
pred<- predict(model_IFGyel, newdata= test, type= "response")

# Convert predictions to accuracy metric
pred[which(pred<0.5)]<- "AD"
pred[which(pred!="AD")]<- "Control"
test$Diagnosis<- as.character(test$Diagnosis)
example_acc<- sum(test$Diagnosis==pred, na.rm = T)/nrow(test)
</code>```

Any help clarifying what these prediction probabilities indicate is appreciated.

答:
From ?glm we note:

Details:

A typical predictor has the form ‘response ~ terms’ where
     ‘response’ is the (numeric) response vector and ‘terms’ is a
     series of terms which specifies a linear predictor for ‘response’.
     For ‘binomial’ and ‘quasibinomial’ families the response can also
     be specified as a ‘factor’ (when the first level denotes failure
     and all others success) or as a two-column matrix with the columns
     giving the numbers of successes and failures.

The key part is highlighted. Assuming you didn't specify the levels (i.e. R's default assignment took place), then AD would be failures and Control would be successes. Hence the coefficients/model would be in terms of the probability that observation is in the Control class.

If you want to change this, use factor(...., levels = c('Control', 'AD')) or just do 1 - prob(Control) (1 - predicted value) to get it in terms of AD.

Body:
I have built a binomial glm model. The model predicts output between two potential classes: AD or Control. These variables are factors with levels: {AD, Control}. I use this model to predict and obtain probabilities for each sample, but it is unclear to me if a probability over 0.5 indicates AD or Control.

Here is my dataset:

> head(example)
          cleaned_mayo$Diagnosis pca_results$x[, 1]
1052_TCX                      AD          0.9613241
1104_TCX                      AD         -0.9327390
742_TCX                       AD          1.6908874
1945_TCX                 Control          0.6819104
134_TCX                       AD          0.5184748
11386_TCX                Control          0.4669661

And here is my code to compute the model and make predictions:

# Randomize rows of top performer
example<- example[sample(nrow(example)),]

# Subset data for training and testing
N_train<- round(nrow(example)*0.75)
train<- example[1:N_train,]
test<- example[(N_train+1):nrow(example),]
colnames(train)[1:2]<- c("Diagnosis", "Eigen_gene")
colnames(test)[1:2]<- c("Diagnosis", "Eigen_gene")

# Build model and predict
model_IFGyel<- glm(Diagnosis ~ Eigen_gene, data = train, family = binomial())
pred<- predict(model_IFGyel, newdata= test, type= "response")

# Convert predictions to accuracy metric
pred[which(pred<0.5)]<- "AD"
pred[which(pred!="AD")]<- "Control"
test$Diagnosis<- as.character(test$Diagnosis)
example_acc<- sum(test$Diagnosis==pred, na.rm = T)/nrow(test)

Any help clarifying what these prediction probabilities indicate is appreciated.


问:
Cannot download S3 bucket contents even though bucket policy allows this ip address
I am trying to download a file from my S3 bucket using one of my ec2 instances using curl and wget. I set up my bucket policy originally as

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "HelpGetObject",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:GetObject",
        "Resource": ["arn:aws:s3:::name_of_bucket/*"],
        "Condition": {
            "IpAddress": {
                "aws:SourceIp": [
                    "10.152.0.0/15",
                    "10.154.0.0/17",
                    "10.154.128.0/17"
                ]
            }
        }
    }
]
}
</code>```

I then went to my instance that has the ip address 10-152-17-111 and did wget/curl with and without quotes

```<code>wget https://s3.amazonaws.com/name_of_bucket/my_file.tar.gz
</code>```

This gave me a 403
    curl https://s3.amazonaws.com/name_of_bucket/my_file.tar.gz

This gave me a 403

Now I changed my policy so that all s3 actions were available and my specific ip address was included

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "HelpGetObject",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:*",
        "Resource": [
            "arn:aws:s3:::name_of_bucket",
            "arn:aws:s3:::name_of_bucket/*"
        ],
        "Condition": {
            "IpAddress": {
                "aws:SourceIp": [
                    "10.152.0.0/15",
                    "10.154.0.0/17",
                    "10.154.128.0/17",
                    "10.152.17.111/32"
                ]
            }
        }
    }
]
}
</code>```

I then ran the same commands, again with and without quotes:

```<code>wget https://s3.amazonaws.com/name_of_bucket/my_file.tar.gz
</code>```

returns 403

```<code>curl https://s3.amazonaws.com/name_of_bucket/my_file.tar.gz
</code>```

returns 403

I have no idea what to do next, I just want to download my files from my s3 bucket. I should have permissions, but nothing is working.

答:
In your s3 bucket policy, you provide allowed IPs in the 10/8 range.  But the s3 endpoints you're hitting aren't on your private 10/8 network; they have public IPs, and your request will be seen as originating from your public IP, not your private IP.

https://wtfismyip.com/text is one way to determine your public IP.  Obviously this is going to change depending on what network you're on, and will also apply to anyone else on that network, which are 2 of the reasons why IP based permissions are not a common way of granting S3 access.  If your s3 content is truly public and not confidential, you might consider attaching a public-read ACL to the objects themselves at upload time; then the bucket policy is irrelevant.

tl;dr : put your public IP in the policy, not your private IP.

Body:
I am trying to download a file from my S3 bucket using one of my ec2 instances using curl and wget. I set up my bucket policy originally as

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "HelpGetObject",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:GetObject",
        "Resource": ["arn:aws:s3:::name_of_bucket/*"],
        "Condition": {
            "IpAddress": {
                "aws:SourceIp": [
                    "10.152.0.0/15",
                    "10.154.0.0/17",
                    "10.154.128.0/17"
                ]
            }
        }
    }
]
}

I then went to my instance that has the ip address 10-152-17-111 and did wget/curl with and without quotes

wget https://s3.amazonaws.com/name_of_bucket/my_file.tar.gz

This gave me a 403
    curl https://s3.amazonaws.com/name_of_bucket/my_file.tar.gz

This gave me a 403

Now I changed my policy so that all s3 actions were available and my specific ip address was included

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "HelpGetObject",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:*",
        "Resource": [
            "arn:aws:s3:::name_of_bucket",
            "arn:aws:s3:::name_of_bucket/*"
        ],
        "Condition": {
            "IpAddress": {
                "aws:SourceIp": [
                    "10.152.0.0/15",
                    "10.154.0.0/17",
                    "10.154.128.0/17",
                    "10.152.17.111/32"
                ]
            }
        }
    }
]
}

I then ran the same commands, again with and without quotes:

wget https://s3.amazonaws.com/name_of_bucket/my_file.tar.gz

returns 403

curl https://s3.amazonaws.com/name_of_bucket/my_file.tar.gz

returns 403

I have no idea what to do next, I just want to download my files from my s3 bucket. I should have permissions, but nothing is working.


问:
For the fit method in LinearRegression in scikit-learn, why is the second parameter consisting of y coordinates required?
The objects of LinearRegression from sklearn.linear_model can be used to fit data point to a line. As can be seen from the code below, the fit method takes two parameters, the list of points and another list of just y coordinates. </p>

```<code>from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit ([[0, 0], [1, 1], [2, 2]], [0, 1, 2])
</code>```

<p>My question is this: why is the second parameter even required? Is it not redundant information? </p>

答:
Linear models are not restricted to only 1 predictor variable and 1 response variable. In other words, you can have X and Y as the two predictors being used to predict the response variable Z, where Z might depend linearly on X and Y. In your case you are only trying to predict Y from X, so change your code to the following:</p>

```<code>from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit ([[0], [1], [2]], [0, 1, 2])
</code>```

Body:
The objects of LinearRegression from sklearn.linear_model can be used to fit data point to a line. As can be seen from the code below, the fit method takes two parameters, the list of points and another list of just y coordinates.

from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit ([[0, 0], [1, 1], [2, 2]], [0, 1, 2])

My question is this: why is the second parameter even required? Is it not redundant information?

Body:
Linear models are not restricted to only 1 predictor variable and 1 response variable. In other words, you can have X and Y as the two predictors being used to predict the response variable Z, where Z might depend linearly on X and Y. In your case you are only trying to predict Y from X, so change your code to the following:

from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit ([[0], [1], [2]], [0, 1, 2])


问:
How to map SQL Server text column with Entity Framework Core 2.0 Model property
I am using Entity Framework Core 2.0 and SQL Server 2016. I have a .cs class model that maps the SQL Server tables. I am able to insert long string in SQL Server text column, but I am not able to get that column with this model, it returns null with an error:

Object reference object reference not set to instance of object

Model property that holds data is type of string. Any ideas how to map a SQL Server text column with Entity Framework Core 2.0?

答:
```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Blog>(eb =>
    {
        eb.Property(b => b.Url).HasColumnType("ntext");
        eb.Property(b => b.ModernUrl).HasColumnType("nvarchar(MAX)");
    });
}
</code>```

<p>https://learn.microsoft.com/en-us/ef/core/modeling/relational/data-types </p>

Body:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Blog>(eb =>
    {
        eb.Property(b => b.Url).HasColumnType("ntext");
        eb.Property(b => b.ModernUrl).HasColumnType("nvarchar(MAX)");
    });
}

https://learn.microsoft.com/en-us/ef/core/modeling/relational/data-types


答: If you right click on the reference, select properties, then set 'Copy Local' to True it will be published when you release a build.</p>

Title: VS Program works in debug mode but not in release mode


问:
Is it Possible to Run a Python Code Forever?
I have coded a Python Script for Twitter Automation using Tweepy. Now, when i run on my own Linux Machine as python file.py The file runs successfully and it keeps on running because i have specified repeated Tasks inside the Script and I also don't want to stop the script either. But as it is on my Local Machine, the script might get stopped when my Internet Connection is off or at Night. So i couldn't keep running the Script Whole day on my PC..

So is there any way or website or Method where i could deploy my Script and make it Execute forever there ? I have heard about CRON JOBS before in Cpanel which can Help repeated Tasks but here in my case i want to keep running my Script on the Machine till i don't close the script .

Are their any such solutions. Because most of twitter bots i see are running forever, meaning their Script is getting executed somewhere 24x7 . This is what i want to know, How is that Task possible?

答:
You can add a systemd .service file, which can have the added benefit of:

logging (compressed logs at a central place, or over network to a log server)

disallowing access to /tmp and /home-directories

restarting the service if it fails

starting the service at boot

setting capabilities (ref setcap/getcap), disallowing file access if the process only needs network access, for instance


问:
Unity 2d win condition , game similar to TicTacToe
i'm creating a little game, and I've a problem.
Each players have 3 pieces. They've to put their pieces in case , like a Tic Tac Toe board.
The victory conditions are same than Tic Tac Toe. But in this game, you only have 3 pieces, and you can move them on the board , and after you placed  yours pieces on the board, one after one.

The pieces can only move from a case to an adjacent case.
My problem is for the verification , the victory condition.
I've a "Board" , and i wanted to know if i can do thoses victory conditions with the position of the pieces on the board , or i cant ?

Example:  If the 3 allies pieces are in x1,y1 x2 y2, and x3,y3, u have win.
Or if the 3 pieces are in 3 others objects, you win.

If u want more information about this, i can told more, so i thought about this tutorial code in Unity, about the Tic Tac Toe, but i didnt used panel.

```<code>using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class GameController : MonoBehaviour {

public Text[] buttonList;

private string playerSide;

void Awake ()
{
    SetGameControllerReferenceOnButtons();
    playerSide = "X";
}

void SetGameControllerReferenceOnButtons ()
{
    for (int i = 0; i < buttonList.Length; i++)
    {
        buttonList[i].GetComponentInParent<GridSpace>().SetGameControllerReference(this);

    }
}

public string GetPlayerSide ()
{
    return playerSide;
}

public void EndTurn ()
{
    if (buttonList [0].text == playerSide && buttonList [1].text == playerSide && buttonList [2].text == playerSide)
    {
        GameOver();
    }
}

void GameOver ()
{
    for (int i = 0; i < buttonList.Length; i++)
    {
        buttonList[i].GetComponentInParent<Button>().interactable = false;
    }
}
</code>```

}

Sorry for my english guys and if my explications are too bad ^^ .

答: Since there is no much win cases, you can make every win condition as an ArrayList and control it with ArrayList.Contains in an if condition.

Body:
i'm creating a little game, and I've a problem.
Each players have 3 pieces. They've to put their pieces in case , like a Tic Tac Toe board.
The victory conditions are same than Tic Tac Toe. But in this game, you only have 3 pieces, and you can move them on the board , and after you placed  yours pieces on the board, one after one.

The pieces can only move from a case to an adjacent case.
My problem is for the verification , the victory condition.
I've a "Board" , and i wanted to know if i can do thoses victory conditions with the position of the pieces on the board , or i cant ?

Example:  If the 3 allies pieces are in x1,y1 x2 y2, and x3,y3, u have win.
Or if the 3 pieces are in 3 others objects, you win.

If u want more information about this, i can told more, so i thought about this tutorial code in Unity, about the Tic Tac Toe, but i didnt used panel.

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class GameController : MonoBehaviour {

public Text[] buttonList;

private string playerSide;

void Awake ()
{
    SetGameControllerReferenceOnButtons();
    playerSide = "X";
}

void SetGameControllerReferenceOnButtons ()
{
    for (int i = 0; i < buttonList.Length; i++)
    {
        buttonList[i].GetComponentInParent<GridSpace>().SetGameControllerReference(this);

    }
}

public string GetPlayerSide ()
{
    return playerSide;
}

public void EndTurn ()
{
    if (buttonList [0].text == playerSide && buttonList [1].text == playerSide && buttonList [2].text == playerSide)
    {
        GameOver();
    }
}

void GameOver ()
{
    for (int i = 0; i < buttonList.Length; i++)
    {
        buttonList[i].GetComponentInParent<Button>().interactable = false;
    }
}

}

Sorry for my english guys and if my explications are too bad ^^ .


问:
Where statement with two criteria SQL
I have got pretty much everything in order apart from the last statement.

I am hoping for the query to narrow down my searches further and place a statement that says if one of the records within agencyprofilesetupcomplete is 0 then look to see if the date in agencyprofilecreateddate is less than 90 days of todays date, if it is I want to also include those results.

```<code>select
    distinct agencyprofilename,
    (select
         top 1 agencypayperiodfinalisestate
     from
       agencypayperiod as app
     where
       app.agencyprofileid = ap.agencyprofileid
     order by
       agencypayperiodpaydate)as 'Pay Period Finalise State',
     agencyprofilecreateddate, agencyprofilesetupcomplete,
     agencyemployertaxoffice

from
    Agencyprofile as ap

left join
   agencypayperiod as app on ap.agencyprofileid = app.agencyprofileid
left outer join
   agencyemployer as ae on ap.agencyemployerid = ae.agencyemployerid
where agencypayperiodfinalisestate <>0
   and agencyemployertaxoffice is not null
   and agencyemployertaxoffice <>''
   or (agencyprofilesetupcomplete = 0 and agencyprofilecreateddate >=
           (GetDate()-90))
order by agencyprofilename
</code>```

I'm also using Microsoft SQL Server if you need to know.

答:
Just a tweak on your date compare in the WHERE Clause...

You need to use DATEADD function on your GETDATE() - 90.

```<code>... >= DATEADD(dd, -90, GETDATE())
</code>```

Title: Where statement with two criteria SQL

Body:
I have got pretty much everything in order apart from the last statement.

I am hoping for the query to narrow down my searches further and place a statement that says if one of the records within agencyprofilesetupcomplete is 0 then look to see if the date in agencyprofilecreateddate is less than 90 days of todays date, if it is I want to also include those results.

select
    distinct agencyprofilename,
    (select
         top 1 agencypayperiodfinalisestate
     from
       agencypayperiod as app
     where
       app.agencyprofileid = ap.agencyprofileid
     order by
       agencypayperiodpaydate)as 'Pay Period Finalise State',
     agencyprofilecreateddate, agencyprofilesetupcomplete,
     agencyemployertaxoffice

from
    Agencyprofile as ap

left join
   agencypayperiod as app on ap.agencyprofileid = app.agencyprofileid
left outer join
   agencyemployer as ae on ap.agencyemployerid = ae.agencyemployerid
where agencypayperiodfinalisestate <>0
   and agencyemployertaxoffice is not null
   and agencyemployertaxoffice <>''
   or (agencyprofilesetupcomplete = 0 and agencyprofilecreateddate >=
           (GetDate()-90))
order by agencyprofilename

I'm also using Microsoft SQL Server if you need to know.

Body:
Just a tweak on your date compare in the WHERE Clause...

You need to use DATEADD function on your GETDATE() - 90.

... >= DATEADD(dd, -90, GETDATE())


问:
How to initialize a static variable in a multithreaded context?
I thought up a good use of the static keyword inside a function to be something like this:

```<code>void threadSafeWrite(int *array, int writeIndex, int writeData){
    static void *threadLock = Lock_create(); //in my code locks are void* to be cross-platform compatable
    Lock_aquire(threadLock);
    array[writeIndex] = writeData;
    Lock_release(threadLock);
}
</code>```

In short it seems like a good way to make a critical section. My question is though, how do I initialize the threadLock in a threadsafe manner? The problem with the example I fear is that the lock will get allocated multiple times and each thread will use a different lock. Any ideas on how to fix this? Seems like a chicken and egg problem. I want a solution (or solutions) which work with both pthreads and windows threads.

EDIT: the reason I want this functionality is because it provides a non-intrusive way to test whether there is a difference when running a piece of code single-threaded or multithreaded (meant for debug purposes).

答:
The whole idea of a Lock_create function is broken; the act of creating it would require synchronization, which you can't guarantee because you don't have a lock yet! Don't use pointers for locks. Instead create a struct and pass the address of that struct to your locking and unlocking functions. Or better yet, use the ones provided by your OS, since there's no way to implement locking yourself in plain C.

Also everyone who's said you need to make the lock "global" is wrong. Function level scope is fine as long as it's static storage duration, which you have. You just need to eliminate the allocation function Lock_create and use an appropriate type for the lock.

Body:
I thought up a good use of the static keyword inside a function to be something like this:

void threadSafeWrite(int *array, int writeIndex, int writeData){
    static void *threadLock = Lock_create(); //in my code locks are void* to be cross-platform compatable
    Lock_aquire(threadLock);
    array[writeIndex] = writeData;
    Lock_release(threadLock);
}

In short it seems like a good way to make a critical section. My question is though, how do I initialize the threadLock in a threadsafe manner? The problem with the example I fear is that the lock will get allocated multiple times and each thread will use a different lock. Any ideas on how to fix this? Seems like a chicken and egg problem. I want a solution (or solutions) which work with both pthreads and windows threads.

EDIT: the reason I want this functionality is because it provides a non-intrusive way to test whether there is a difference when running a piece of code single-threaded or multithreaded (meant for debug purposes).


问:
uint8_t and binary OR
Does someone know why uint8_t&uint8_t produce an int ?

```<code>#include <iostream>
#include <type_traits>
#include <cstdint>
#include <typeinfo>

using namespace std;

int main() {
    {
        uint8_t a {}, b{};
        auto c = a & b ;
        cout << is_unsigned<decltype(a)>::value << " "<< is_unsigned<decltype(b)>::value
        << " "<< is_unsigned<decltype(c)>::value << " "<< is_unsigned<decltype( a & b)>::value << " ";
        cout << "\t " << typeid(a).name() << " " << typeid(c).name() << endl;
    }
    cout << endl;
    {
        uint32_t a {}, b{};
        auto c = a & b ;
        cout << is_unsigned<decltype(a)>::value << " "<< is_unsigned<decltype(b)>::value
        << " "<< is_unsigned<decltype(c)>::value << " "<< is_unsigned<decltype( a & b)>::value << " ";
        cout << "\t " << typeid(a).name() << " " << typeid(c).name() << endl;

    }
    cout << endl;
    {
        size_t a {}, b{};
        auto c = a & b ;
        cout << is_unsigned<decltype(a)>::value << " "<< is_unsigned<decltype(b)>::value
        << " "<< is_unsigned<decltype(c)>::value << " "<< is_unsigned<decltype( a & b)>::value << " ";
        cout << "\t " << typeid(a).name() << " " << typeid(c).name() << endl;

    }
}
</code>```

live here : jdoodle

The output is :

```<code>1 1 0 0      h i

1 1 1 1      j j

1 1 1 1      m m
</code>```

I don't find any clue in cppreference, just:

The result of operator& is the bitwise AND value of the operands (after usual arithmetic conversions)

So, I don't know it's standard or implementation dependant.

Thank you for your help :)

答:
see http://en.cppreference.com/w/cpp/language/implicit_cast#Integral_promotion
all arithmetic operations promote integer types smaller than int to int or unsigned int.</p>

Title: uint8_t and binary OR

Body:
Does someone know why uint8_t&uint8_t produce an int ?

#include <iostream>
#include <type_traits>
#include <cstdint>
#include <typeinfo>

using namespace std;

int main() {
    {
        uint8_t a {}, b{};
        auto c = a & b ;
        cout << is_unsigned<decltype(a)>::value << " "<< is_unsigned<decltype(b)>::value
        << " "<< is_unsigned<decltype(c)>::value << " "<< is_unsigned<decltype( a & b)>::value << " ";
        cout << "\t " << typeid(a).name() << " " << typeid(c).name() << endl;
    }
    cout << endl;
    {
        uint32_t a {}, b{};
        auto c = a & b ;
        cout << is_unsigned<decltype(a)>::value << " "<< is_unsigned<decltype(b)>::value
        << " "<< is_unsigned<decltype(c)>::value << " "<< is_unsigned<decltype( a & b)>::value << " ";
        cout << "\t " << typeid(a).name() << " " << typeid(c).name() << endl;

    }
    cout << endl;
    {
        size_t a {}, b{};
        auto c = a & b ;
        cout << is_unsigned<decltype(a)>::value << " "<< is_unsigned<decltype(b)>::value
        << " "<< is_unsigned<decltype(c)>::value << " "<< is_unsigned<decltype( a & b)>::value << " ";
        cout << "\t " << typeid(a).name() << " " << typeid(c).name() << endl;

    }
}

live here : jdoodle

The output is :

1 1 0 0      h i

1 1 1 1      j j

1 1 1 1      m m

I don't find any clue in cppreference, just:

The result of operator& is the bitwise AND value of the operands (after usual arithmetic conversions)

So, I don't know it's standard or implementation dependant.

Thank you for your help :)


问:
Get unique from list as values in Pandas python
I have a dataframe with more rows and columns but example with one is here: </p>

```<code>id    values
1   [v1, v2, v1]
</code>```

<p>How to get unique values from list in pandas column?
Desired output in second column v1, v2
I have tried with df['values'].unique() but obviously it's not working. </p>

答:
Again

```<code>df['new']=list(map(set,df['values'].values))
</code>```

Timing

```<code>%timeit df['values'].agg(np.unique)
The slowest run took 6.78 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 6.99 ms per loop
%timeit list(map(set,df['values'].values))
The slowest run took 55.36 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 228 µs per loop
%timeit df['values'].apply(lambda x: list(set(x)))
1000 loops, best of 3: 743 µs per loop
</code>```

Body:
I have a dataframe with more rows and columns but example with one is here:

id    values
1   [v1, v2, v1]

How to get unique values from list in pandas column?
Desired output in second column v1, v2
I have tried with df['values'].unique() but obviously it's not working.

Body:
Again

df['new']=list(map(set,df['values'].values))

Timing

%timeit df['values'].agg(np.unique)
The slowest run took 6.78 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 6.99 ms per loop
%timeit list(map(set,df['values'].values))
The slowest run took 55.36 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 228 µs per loop
%timeit df['values'].apply(lambda x: list(set(x)))
1000 loops, best of 3: 743 µs per loop


问:
trying to extract complex numbers from strings
I am attempting to extract two columns of numbers from a text file. first column is the real part of the number and the second in the imaginary part. I managed to extract the list of numbers from the file as strings but I don't know how to separate the strings into two parts. I have attempted to use the sscanf function but just hasnt worked. The difficult part is the numbers can be both positive and negative therefore I cant use + and - in the delimiter of the strtok function since it will remove the negatives. Iv been stuck for a few days so any suggestions would be appreciated. Thanks in advance. Here is the code I worte which errors at the sscanf line.

```<code>        #include <stdio.h>
        #include <stdlib.h>
        #include <string.h>
        #include <complex.h>

        char array[35]= "[[[1+1i -4+100i 45-234i -56-78i]]]";
        char *arrayp[35];
        int count,n,i,j;
        double complex z1;
        double real = 0;
        double imaginary = 0;

        int main()
        {
            arrayp[0] = strtok(array," []");
            n=1;
            while (arrayp[n-1]!=NULL)
            {
               arrayp[n] = strtok(NULL, " []");
               n++;
            }
        // up to this point it has been tested to work. the remaining code is very
        // sloppy since I have tried 8 different things and have quickly written one of
        // the options tried.

            for(j=0;j<n;j++)
            {
                if (strchr(*arrayp, '+'))
                {
                    sscanf(arrayp[j],"%f+%fi", real, imaginary);
                }
                else if(arrayp string has equal to more than 1 '-')
                {
                     sscanf(arrayp[j],"%f%fi", real, imaginary);
                }
            }
        }
</code>```

The output should be something like this:

  0     0

  -4    100

  45    -234

  -56   -78

I noticed there are mistakes such are trying to search *arrayp in strchr but its a pointer I dont know how to convert a pointer into a string so i can put it into this file. Thank you for the help and effort in advance.

答: parse every number yourself.  start scanning the string from index 1 (since index 0 is either +/- or a number), looking for either a "=" or a "-".  once you find it, you know how to split the string. </p>

Body:
I am attempting to extract two columns of numbers from a text file. first column is the real part of the number and the second in the imaginary part. I managed to extract the list of numbers from the file as strings but I don't know how to separate the strings into two parts. I have attempted to use the sscanf function but just hasnt worked. The difficult part is the numbers can be both positive and negative therefore I cant use + and - in the delimiter of the strtok function since it will remove the negatives. Iv been stuck for a few days so any suggestions would be appreciated. Thanks in advance. Here is the code I worte which errors at the sscanf line.

        #include <stdio.h>
        #include <stdlib.h>
        #include <string.h>
        #include <complex.h>

        char array[35]= "[[[1+1i -4+100i 45-234i -56-78i]]]";
        char *arrayp[35];
        int count,n,i,j;
        double complex z1;
        double real = 0;
        double imaginary = 0;

        int main()
        {
            arrayp[0] = strtok(array," []");
            n=1;
            while (arrayp[n-1]!=NULL)
            {
               arrayp[n] = strtok(NULL, " []");
               n++;
            }
        // up to this point it has been tested to work. the remaining code is very
        // sloppy since I have tried 8 different things and have quickly written one of
        // the options tried.

            for(j=0;j<n;j++)
            {
                if (strchr(*arrayp, '+'))
                {
                    sscanf(arrayp[j],"%f+%fi", real, imaginary);
                }
                else if(arrayp string has equal to more than 1 '-')
                {
                     sscanf(arrayp[j],"%f%fi", real, imaginary);
                }
            }
        }

The output should be something like this:

  0     0

  -4    100

  45    -234

  -56   -78

I noticed there are mistakes such are trying to search *arrayp in strchr but its a pointer I dont know how to convert a pointer into a string so i can put it into this file. Thank you for the help and effort in advance.


问:
Inserted element in menu strange behavior on only 1 page
Updated an old javascript menu to a newer jquery platform menu here

Notice the arrows in the menu are top aligned to the letters in the menu, this is not desired. Every other page, the arrows are center aligned to the letters and working as desired, here

I have spent several hours inspecting the pages side by side, looking at both properties, thought the flexslider on the home page might be having an issue, so I disabled it and the issue still remained.

I just don't understand, the menu is 'included' in each page, so i am sure there is no difference in the instructions to the client, but something is interfering, and I just cant find the issue.

Just looking for a starting place, removed elements above and below the menu element and no change, so a point in the correct direction to solve this issue would be greatly appreciated.

Jeff

PS, would post code, but not sure what code to post?

答: The doctype is different on both pages. Try setting the doctype to <!DOCTYPE html>

OwnerDisplayName: anon


问:
C# asp.net build SQL Query dynamically from viewstate
On my C# asp.net webform I have a search page that has roughly 20 elements that "could" be used as part of the search.  There will be more added later.

What I have done is extend the textbox and dropdown listbox to include a few variables:

fieldname: Tablename.columnname
dbtype: DbType.Int32
Joinparam: LEFT Join on otherTable ON x.y = a.b

These are all stored in the viewstate and loaded back in.  The reason I do this is so that I can iterate through all the controls and pull out all the controls that are of my type.  I can then validate them to make sure they have input and are of the right type.  If so I can then pass them off to the database access layer and let the code dynamically generate the SQL statement.

I do not let anything but SELECT statements happen from this.  The fields selected and returned can not be changed and I use the dbparameter to try and avoid sql injection.

My worry is that I put the table and field names that will be used in the search criteria and the JOINS required all in the viewstate.  Is this a real bad idea?

I could obscurify this by just having some int index's into tables that hold this info in the DB but this would still need to be put into the viewstate and just mean they would have an extra layer to figure out.

The reason I went for this approach was that I did not want to have to put tons of IF statements in the DB layer to build the statement there.  It would be ugly as hell and a pain to maintain.

Thanks for any and all advice about this.

Jon

EDIT

Thanks all for the advice.  Thankfully this app is an internal thing only so the damage would be limited.  But I will never use this technique again and will work on the search template idea instead.

Cheers :)

答:
Okay, so ViewState defaults to being MACed, and can optionally be encrypted. So, though you can (by default) read viewstate, tampering isn't trivial.

Building your query dynamically like this most definitely opens you up to Sql Injection - you're parameterizing the search terms, but if I can inject a ;DROP TABLE statement into your JOIN clause, you're hosed (unless you've taken good care to set DB level security, of course).

That being said, I don't see any reason that your JOIN clauses and such would ever need to be in ViewState. I'd think you'd set them as properties of your subclassed textbox in the ASPX markup - there's no reason for them to change. The only thing you may need ViewState for is the search condition itself - which is appropriately parameterized. This is similar to how the SqlDataSource protects it's SelectCommand property - don't store it in ViewState so as not to leak information (or risk tampering - though I don't think that's a serious vulnerability).

As to the larger question of whether this is maintainable - well, you'll have to make that call I suppose.

OwnerDisplayName: Jon

LastEditorDisplayName: Jon

OwnerDisplayName: Mark Brackett


问:
PHP - compatibility of <?= shortcut

Possible Duplicates:

  Are PHP short tags acceptable to use?

  Reference - What does this symbol mean in PHP?

Hi Guys,

I can't seem to find any information about the <?= shortcut of php.
Does anyone of you know more about that?

Thanks in advance!

答:
The document when talking about short_open_tag directive says:

This directive also affects the shorthand <?=, which is identical to <? echo. Use of this shortcut requires short_open_tag to be on.

Title: PHP - compatibility of <?= shortcut


问:
Query including sum from two tables and join them
I have two tables:

Invoice

```<code>id | name | invoice_number | invoice_total
</code>```

Balancesheet

```<code>id | name | invoice_number | amount_received | discount
</code>```

I want an SQL query to join them grouped by name, and want to sum of invoice_total from the invoice table, and sum of amount_received and sum of discount for individual name from balancesheet table.

Result should be:

```<code>    name | sum(invoice_total) | sum(amount_received) | sum(discount)
</code>```

Any help would be greatly appreciated.

答:
It might need tweaking slightly to take into account your database structure, but try this:</p>

```<code>select
    sum(invoice.invoice_total) - sum(balancesheet.amount_received) - sum(balancesheet.discount) as total
from
    invoice
left join
    balancesheet
on
    invoice.name = balancesheet.name
group by
    invoice.name
</code>```

Body:
I have two tables:

Invoice

id | name | invoice_number | invoice_total

Balancesheet

id | name | invoice_number | amount_received | discount

I want an SQL query to join them grouped by name, and want to sum of invoice_total from the invoice table, and sum of amount_received and sum of discount for individual name from balancesheet table.

Result should be:

    name | sum(invoice_total) | sum(amount_received) | sum(discount)

Any help would be greatly appreciated.

Body:
It might need tweaking slightly to take into account your database structure, but try this:

select
    sum(invoice.invoice_total) - sum(balancesheet.amount_received) - sum(balancesheet.discount) as total
from
    invoice
left join
    balancesheet
on
    invoice.name = balancesheet.name
group by
    invoice.name


问:
Jumping between object code with different (and unknown) calling convention in C
I have (mapped in memory) two object files, "A.o" and "B.o", with the same CPU Instruction Set (not necessarily Intel --it can be x86, x86_64, MIPS(32/64), ARM(32/64), PowerPC(32/64),..., but always the same in both object files).

Also, both object files are compiled with the same endianness (both little endian, or both big endian).

However (you knew there was a however, otherwise there wouldn't be any question), "A.o" and "B.o" can have a different function calling convention and, to make things worse, unknown to each other ("A.o" has not even the slightest idea about the calling convention for functions in "B.o", and vice versa).

"A.o" and "B.o" are obviously designed to call functions within their same object file, but there must be a (very) limited interface for communicating between them (otherwise, if execution starts at some function in "A.o", no function from "B.o" would ever be executed if there was no such interface).

The file where execution started (let's suppose it's "A.o") knows the addresses of all static symbols from "B.o" (the addresses of all functions and all global variables). But the opposite is not true (well, the limited interface I'm trying to write would overcome that, but "B.o" doesn't know any address from "A.o" before such interface is established).

Finally the question: How can execution jump from a function in "A.o" to a function in "B.o", and back, while also communicating some data?

I need it to:

Be done in standard C (no assembly).

Be portable C (not compiler-dependent, nor CPU-dependent).

Be thread safe.

Don't make any assumption about the calling conventions involved.

Be able to communicate data between the two object files.

My best idea, for the moment, seems that can meet all these requirements, except thread safety. For example, if I define an struct like this:

```<code>struct data_interface {
   int value_in;
   int value_out; };
</code>```

I could write a pointer to an struct like this from "A.o" into a global variable of "B.o" (knowing in advance that such global variable in "B.o" has space enough for storing a pointer).

Then, the interface function would be a void interface(void) (I'm assuming that calling void(void) functions is safe across different calling conventions... if this is not true, then my idea wouldn't work). Calling such a function from "A.o" to "B.o" would communicate the data to the code in "B.o". And, fingers crossed, when the called function in "B.o" returns, it would travel back nicely (supposing the different calling convention doesn't change the behaviour when returning from void(void) functions).

However, this is not thread safe, of course.

For it to be thread safe, I guess my only option is to access the stack.

But... can the stack be accessed in a portable way in standard C?

答:
Remember that there are both caller saves and callee saves conventions out there, together with variations on use of registers to pass values, use or not of a frame pointer, and even (in some architectures, in some optimisation levels) the use of the delay slot in a branch to hold the first instruction of the subroutine. You are not going to be able to do this without some knowledge of the calling conventions in play, but fortunately the linker will need that anyway. Presumably there is some higher level entity that is responsible for loading those DLLs and that knows the calling conventions for both of them?

Anything you do here is going to be at best deep into implementation defined territory, if not technically undefined behaviour, and you will want to make a deep study of the linker and loader (In particular the linker must know how to resolve dynamic linkage in your unknown calling convention or you will not be able to load that shared object in a meaningful way, so you may be able to leaverage it using libbfd or such but that is outside the scope of C).

The place this sort of thing can go very wrong is if shared resources are allocated in A and freed in B (Memory springs to mind) as memory management is a usually a library based wrapper over the operating systems SBRK or similar, and these implementations of memory management are not inherently compatible in memory layout, other places you may be bitten by this include IO (see shennanigans you sometimes get when mixing printf and cout in c++ for a benign example), and locking.

Body:
I have (mapped in memory) two object files, "A.o" and "B.o", with the same CPU Instruction Set (not necessarily Intel --it can be x86, x86_64, MIPS(32/64), ARM(32/64), PowerPC(32/64),..., but always the same in both object files).

Also, both object files are compiled with the same endianness (both little endian, or both big endian).

However (you knew there was a however, otherwise there wouldn't be any question), "A.o" and "B.o" can have a different function calling convention and, to make things worse, unknown to each other ("A.o" has not even the slightest idea about the calling convention for functions in "B.o", and vice versa).

"A.o" and "B.o" are obviously designed to call functions within their same object file, but there must be a (very) limited interface for communicating between them (otherwise, if execution starts at some function in "A.o", no function from "B.o" would ever be executed if there was no such interface).

The file where execution started (let's suppose it's "A.o") knows the addresses of all static symbols from "B.o" (the addresses of all functions and all global variables). But the opposite is not true (well, the limited interface I'm trying to write would overcome that, but "B.o" doesn't know any address from "A.o" before such interface is established).

Finally the question: How can execution jump from a function in "A.o" to a function in "B.o", and back, while also communicating some data?

I need it to:

Be done in standard C (no assembly).

Be portable C (not compiler-dependent, nor CPU-dependent).

Be thread safe.

Don't make any assumption about the calling conventions involved.

Be able to communicate data between the two object files.

My best idea, for the moment, seems that can meet all these requirements, except thread safety. For example, if I define an struct like this:

struct data_interface {
   int value_in;
   int value_out; };

I could write a pointer to an struct like this from "A.o" into a global variable of "B.o" (knowing in advance that such global variable in "B.o" has space enough for storing a pointer).

Then, the interface function would be a void interface(void) (I'm assuming that calling void(void) functions is safe across different calling conventions... if this is not true, then my idea wouldn't work). Calling such a function from "A.o" to "B.o" would communicate the data to the code in "B.o". And, fingers crossed, when the called function in "B.o" returns, it would travel back nicely (supposing the different calling convention doesn't change the behaviour when returning from void(void) functions).

However, this is not thread safe, of course.

For it to be thread safe, I guess my only option is to access the stack.

But... can the stack be accessed in a portable way in standard C?


问:
ARCore : is arcore-preview.apk (= Tango Core app) required to run a ARCore app?
I would like to develop an app using ARCore. I have several questions:

is it required to install the arcore-preview.apk  to be able to run this ARCore app ?

Why does the arcore-preview.apk appears with the name "Tango Core" in the applications list of my device ?

Will the Android OS directly include the ARCore (Tango Core ?) SDK in the future ?

Will all the devices be compatible with ARCore ? (not just the S8 and a few devices...)

Thanks !

答:
Yes

Because ARCore is based on the much older Project Tango

Unclear but likely - at least a Tango Core App downloadable from the play store

No. But much more than the current choice:

Google plans to add support for other phones from Samsung, Huawei, LG,
  and Asus, among others. The goal is to bring ARCore support to “100
  million devices at the end of the preview." - source


问:
iterate through few UL lists looking for class in each. if not found throw error and continue
Sorry if title confuses. Hard to think of how to describe the problem in few words.

I have 3 different lists containing "level", "category", "time" for the game. Originally none of the lists' items have any class. When selected an item from each list, it gets a class 'activeSelection'.

I need to check if in each of the lists there is an item that has that class. If not, then show the warning under the list (there is a warning for each list) that at the moment is hidden. Also not let "startGame()" function to execute.

I need it to work so if 2 lists are missing that class, the warning would be shown under both of those lists. The same if all 3 lists are missing the class.

const levelList = document.querySelector('.levelList');
const categoryList = document.querySelector('.categoryList');
const timeList = document.querySelector('.timeList');

$(document).ready(function() {

  $(playButton).on('click', function() {
     if ($(levelList).children("li").hasClass('activeSelection') == false) {
       $(levelList).find('.warning').show();
     } else {
       startGame();
     } /** that's how I check one of the lists. I need to check all 3
      and if at least one does not have a class give a warning, but not
      stop checking until all 3 lists are checked to give the rest of
      the warnings if needed **/
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.warning {
display: none;
}</code>```

level

easy

medium

hard

! please select level !

 category

movies

songs

people

animals

random things

! please select Category !

time

1 min

2 min

3 min

! please select time !

```

答:
You can try doing all 3 checks separately:</p>

```<code>    $(document).ready(function() {
  $(playButton).on('click', function() {
     var status = 0;
     if ($(levelList).children("li").hasClass('activeSelection') == false) {
       $(levelList).find('.warning').show();
     } else {
        status += 1;
     }
     if ($(categoryList).children("li").hasClass('activeSelection') == false) {
       $(categoryList).find('.warning').show();
     } else {
        status += 1;
     }
     if ($(timeList).children("li").hasClass('activeSelection') == false) {
       $(timeList).find('.warning').show();
     } else {
        status += 1;
     }
      if (status === 3)
       startGame();
  });
</code>```

Body:
Sorry if title confuses. Hard to think of how to describe the problem in few words.

I have 3 different lists containing "level", "category", "time" for the game. Originally none of the lists' items have any class. When selected an item from each list, it gets a class 'activeSelection'.

I need to check if in each of the lists there is an item that has that class. If not, then show the warning under the list (there is a warning for each list) that at the moment is hidden. Also not let "startGame()" function to execute.

I need it to work so if 2 lists are missing that class, the warning would be shown under both of those lists. The same if all 3 lists are missing the class.

const levelList = document.querySelector('.levelList');
const categoryList = document.querySelector('.categoryList');
const timeList = document.querySelector('.timeList');

$(document).ready(function() {

  $(playButton).on('click', function() {
     if ($(levelList).children("li").hasClass('activeSelection') == false) {
       $(levelList).find('.warning').show();
     } else {
       startGame();
     } /** that's how I check one of the lists. I need to check all 3
      and if at least one does not have a class give a warning, but not
      stop checking until all 3 lists are checked to give the rest of
      the warnings if needed **/
  });

});

.warning {
display: none;
}

level

easy

medium

hard

! please select level !

 category

movies

songs

people

animals

random things

! please select Category !

time

1 min

2 min

3 min

! please select time !

Body:
You can try doing all 3 checks separately:

    $(document).ready(function() {
  $(playButton).on('click', function() {
     var status = 0;
     if ($(levelList).children("li").hasClass('activeSelection') == false) {
       $(levelList).find('.warning').show();
     } else {
        status += 1;
     }
     if ($(categoryList).children("li").hasClass('activeSelection') == false) {
       $(categoryList).find('.warning').show();
     } else {
        status += 1;
     }
     if ($(timeList).children("li").hasClass('activeSelection') == false) {
       $(timeList).find('.warning').show();
     } else {
        status += 1;
     }
      if (status === 3)
       startGame();
  });


答:
Assuming you need  only exact match for both the tales between tha names You can use inner join  and group by

```<code> select table_1.name, sum(a.invoce_total), sum(AMOUNT_RECEIVED), sum(DISCOUNT)
 from invoice table_1
 inner join BALANCESHEET table_2 on table_1.name = table_2.name
 group by table_1.name
</code>```

if you need  also partial match you can use left join

```<code> select table_1.name, sum(a.invoce_total), sum(AMOUNT_RECEIVED), sum(DISCOUNT)
 from invoice table_1
 left join BALANCESHEET table_2 on table_1.name = table_2.name
 group by table_1.name
</code>```

Title: Query including sum from two tables and join them

Body:
Assuming you need  only exact match for both the tales between tha names You can use inner join  and group by

 select table_1.name, sum(a.invoce_total), sum(AMOUNT_RECEIVED), sum(DISCOUNT)
 from invoice table_1
 inner join BALANCESHEET table_2 on table_1.name = table_2.name
 group by table_1.name

if you need  also partial match you can use left join

 select table_1.name, sum(a.invoce_total), sum(AMOUNT_RECEIVED), sum(DISCOUNT)
 from invoice table_1
 left join BALANCESHEET table_2 on table_1.name = table_2.name
 group by table_1.name


问:
Django URL invalid literal for int() with base 10
I have a Location model setup in Django and I originally set it up so that the URL was /location/3/ using the primary key. but the client want to change it to use a slug of the location name. I created a slug field in the model. And changed the URL pattern in urls.py.

```<code>urlpatterns = [
    url(r'^(?P<pk>[\w-]+)/$', views.LocationsSingleView.as_view(), name='detail'),
]
</code>```

I can link to them fine. But when it tries to actually load that page I get an error:

invalid literal for int() with base 10: 'eau-claire'

Where eau-claire is the slug for that Location.

Documentation doesn't say anything about this.

A lot of people with this issue have issues with their view. But my view is super simple. So I don't know what's wrong. Here is my view:

```<code>class LocationsSingleView(DetailView):
    model = models.Location
</code>```

答: You need to use slug instead of pk in the URL pattern to tell Django you want to look up by the slug.

Body:
I have a Location model setup in Django and I originally set it up so that the URL was /location/3/ using the primary key. but the client want to change it to use a slug of the location name. I created a slug field in the model. And changed the URL pattern in urls.py.

urlpatterns = [
    url(r'^(?P<pk>[\w-]+)/$', views.LocationsSingleView.as_view(), name='detail'),
]

I can link to them fine. But when it tries to actually load that page I get an error:

invalid literal for int() with base 10: 'eau-claire'

Where eau-claire is the slug for that Location.

Documentation doesn't say anything about this.

A lot of people with this issue have issues with their view. But my view is super simple. So I don't know what's wrong. Here is my view:

class LocationsSingleView(DetailView):
    model = models.Location