问:
Command `run-android` unrecognized after installing any additional package in React Native project
I started working on a React Native project, everything was going very well. I was able to run my project on an android emulator, but then I wanted to add some other packages in my react native project.
I tried to run my project once again on android emulator and I got error Command run-android unrecognized. Make sure that you have run npm install and that you are inside a react-native project.
I tried to create a new project, and add any package just to see if it will work, and I got the same error.

Got on my Linux machine and tried the same thing, and I didn't get any errors, but on Windows it won't work.

I'm working on Windows 10 -.-
node version : 8.0.0
react-native : 0.44.2

答:
I had this exact same problem. This is most likely caused by after running npm install most of the library folders inside the node_modules become empty or gone. I'm not really sure whether this problems caused by npm or react-native itself (since both had release a new version recently).

A 'bruteforce' method to resolve this is copy node_modules folder from a fresh react-native app into your current project. cheers~

EDIT

I'm sorry if I caused a misleading. This problem occur because you use 2 differents package manager (in my case npm and yarn). If you install yarn, react-native-cli will automatically use yarn and populate a yarn package (which will make your package.json empty). So if you install a package via npm, it will generate empty node_modules folder (plus your new package). Try install the package using yarn (yarn add package-name), it works for me.


来源: stackexchange

问:
ListView column auto sizing
Let's say I have the following ListView:

```<code><ListView ScrollViewer.VerticalScrollBarVisibility="Auto">
  <ListView.View>
    <GridView>
      <GridViewColumn Header="Something"
                      DisplayMemberBinding="{Binding Path=ShortText}" />
      <GridViewColumn Header="Description"
                      DisplayMemberBinding="{Binding Path=VeryLongTextWithCRs}" />
      <GridViewColumn Header="Something Else"
                      DisplayMemberBinding="{Binding Path=AnotherShortText}" />
    </GridView>
  </ListView.View>
</ListView>
</code>```

I'd like the short text columns to always fit in the screen, and the long text column to use the remaining space, word-wrapping if necessary.

Is that possible?

答:
```<code><ListView ScrollViewer.VerticalScrollBarVisibility="Auto" Name="someList">
  <ListView.View>
    <GridView>
      <GridViewColumn Width={Binding ElementName=someList, Path=ActualWidth/3} Header="Something" DisplayMemberBinding="{Binding Path=ShortText}" />
      <GridViewColumn  Width={Binding ElementName=someList, Path=ActualWidth/3} Header="Description" DisplayMemberBinding="{Binding Path=VeryLongTextWithCRs}" />
      <GridViewColumn  Width={Binding ElementName=someList, Path=ActualWidth/3} Header="Something Else" DisplayMemberBinding="{Binding Path=AnotherShortText}" />
    </GridView>
  </ListView.View>
</ListView>
</code>```

ContentLicense: CC BY-SA 3.0

Title: ListView column auto sizing

Body:
Let's say I have the following ListView:

<ListView ScrollViewer.VerticalScrollBarVisibility="Auto">
  <ListView.View>
    <GridView>
      <GridViewColumn Header="Something"
                      DisplayMemberBinding="{Binding Path=ShortText}" />
      <GridViewColumn Header="Description"
                      DisplayMemberBinding="{Binding Path=VeryLongTextWithCRs}" />
      <GridViewColumn Header="Something Else"
                      DisplayMemberBinding="{Binding Path=AnotherShortText}" />
    </GridView>
  </ListView.View>
</ListView>

I'd like the short text columns to always fit in the screen, and the long text column to use the remaining space, word-wrapping if necessary.

Is that possible?


问:
Does HTML5 audio tag support serving mp3s from another domain?
So I am having a web application with domian "www.example.com" that needs to serve audio from "www.example2.com", but for some reason this is not working (the audio just does not stream)

<audio src="http://www.example2.com/song.mp3" controls preload></audio>

Given that if I put the sound source url directly into the browser the audio will be available

Anyone tried this? thanks

Wa'el

答: I think HTML5 does not allow you to take a source from another hosting provider / server. Maybe it's limited to your domain but I'm not 100% sure... I do remind that there was a little limitation about this html5 element...</p>

ContentLicense: CC BY-SA 2.5


问:
pymc3 Conditional deterministic likelihood function
I'm new to PyMC3 and trying to find a set of parameters that fit data from an experiment. My issue is that my likelihood function is conditional on previous responses of a participant.

The data has the following matrix-form:

```<code>participant | trial0 | trial1 | ... | trialn
p0 | x | x | ... | x
....
p1 | x | x | ... | x
</code>```

where x codifies the participants response in that trial, with values of 0, 1, or 2. Now, I'm interested in inferring likely parameters for each participant p. For simplicity, assume participants may be of one of three types, t1, t2, t3, and that there is a third parameter l held constant across these types. I want to infer the likely type of each participant given her behavior across the experiment, the general distribution of types over participants, and the best fit for l.

The issue: My likelihood function, call it lhs, is deterministic; plug in the participants type (t={1,2,3}), a value for l, and the past responses of the participant and it will give you the probability of the observed data x={0,1,2} in the current trial. My problem is that I don't know how to tell the PyMC3 model that for each response (0,1, or 2) at trial n, the likelihood function depend on the sequence of responses in the trials up to n. I need this because, after each trial, lhs is updated by the value of the trial (participants learn in the experiment, so the likelihood of them showing a particular response will change as well.

I'm assuming that there's either a clever way to codify the responses per trial in such a way that the model recursively computes the likelihood function for each response at trial n > 0, or that there is a functionality to tell it that data depends on previous data. Alas, I have not been able to find any examples of how either idea may work.

Here's what I have:

```<code>import numpy as np
import pymc3 as pm

#data is a pandas dataframe where each row
#is a participant, each column a trial, and
#each cell has value 0,1, or 2.

with pm.Model() as model:
    #Priors
    l = pm.Gamma('lam',10,1.0/0.5) #my prior for the value of l
    p_tau = pm.Dirichlet('p_tau',np.ones(3)) #unbiased prior over types
    tau = pm.Categorical('tau', p=p_tau, shape=3) #distr. over types I want to infer

    #data likelihood function
    lhs = ... #likelihood function; takes l, tau,
              #and sequentially observed data up to trial n-1
              #to compute the likelihood of the response of trial n

    #Here's the issue. data would be 0,1,2
    #But lhs should depend on previous trials
    pm.Categorical('obs', p=lhs, observed=data)
</code>```

Suggestions on the model, the data-codification or examples of implemented PyMC3 models that have similar characteristics would be greatly appreciated.

I left the likelihood unspecified because is quite long.

答:
It seems that what you're trying to do is to infer the probability of a type t1, t2 or t3 for each individual given a sequence of responses (I feel this model might be something like a Markov chain).

It would be helpful to post the likelihood code or some documentation about the model here in order for us to get an idea of how it might be implemented - this will be a bit of a vague answer until I can have a look at the likelihood.

The easiest way to do a conditional in pymc3 is to use Theano's switch op, which is documented here: http://deeplearning.net/software/theano/tutorial/conditions.html.

Basically switch can be used like: theano.switch(condition, expression_if_true, expression_if_false). You want to use this rather than ifelse in pymc3 likelihoods as switch can be used elementwise but ifelse can't.

Body:
I'm new to PyMC3 and trying to find a set of parameters that fit data from an experiment. My issue is that my likelihood function is conditional on previous responses of a participant.

The data has the following matrix-form:

participant | trial0 | trial1 | ... | trialn
p0 | x | x | ... | x
....
p1 | x | x | ... | x

where x codifies the participants response in that trial, with values of 0, 1, or 2. Now, I'm interested in inferring likely parameters for each participant p. For simplicity, assume participants may be of one of three types, t1, t2, t3, and that there is a third parameter l held constant across these types. I want to infer the likely type of each participant given her behavior across the experiment, the general distribution of types over participants, and the best fit for l.

The issue: My likelihood function, call it lhs, is deterministic; plug in the participants type (t={1,2,3}), a value for l, and the past responses of the participant and it will give you the probability of the observed data x={0,1,2} in the current trial. My problem is that I don't know how to tell the PyMC3 model that for each response (0,1, or 2) at trial n, the likelihood function depend on the sequence of responses in the trials up to n. I need this because, after each trial, lhs is updated by the value of the trial (participants learn in the experiment, so the likelihood of them showing a particular response will change as well.

I'm assuming that there's either a clever way to codify the responses per trial in such a way that the model recursively computes the likelihood function for each response at trial n > 0, or that there is a functionality to tell it that data depends on previous data. Alas, I have not been able to find any examples of how either idea may work.

Here's what I have:

import numpy as np
import pymc3 as pm

#data is a pandas dataframe where each row
#is a participant, each column a trial, and
#each cell has value 0,1, or 2.

with pm.Model() as model:
    #Priors
    l = pm.Gamma('lam',10,1.0/0.5) #my prior for the value of l
    p_tau = pm.Dirichlet('p_tau',np.ones(3)) #unbiased prior over types
    tau = pm.Categorical('tau', p=p_tau, shape=3) #distr. over types I want to infer

    #data likelihood function
    lhs = ... #likelihood function; takes l, tau,
              #and sequentially observed data up to trial n-1
              #to compute the likelihood of the response of trial n

    #Here's the issue. data would be 0,1,2
    #But lhs should depend on previous trials
    pm.Categorical('obs', p=lhs, observed=data)

Suggestions on the model, the data-codification or examples of implemented PyMC3 models that have similar characteristics would be greatly appreciated.

I left the likelihood unspecified because is quite long.


问:
How to $scope use a firebase object on an Angular App
I am new to coding, and a basic answer would be very much appreciated.

I am trying to use firebase object as a javascript array to use it on html using $scope. what would be the best method?

database:
database

I am using:

var mainApp = angular.module("bookWorm", []);

mainApp.controller('bookController', function($scope, $http) {

  var ref = firebase.database().ref("Fiction");

  ref.once("value", function(snapshot) {

    console.log(snapshot.val());
    $scope.fiction = snapshot.val();

  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="contents">
  <div class="heading">
    <h2 style="text-align:center">Fiction</h2>
  </div>
  <u1 style="cursor:pointer">
    <li ng-repeat="content in fiction"><img src="assets/fiction/{{content.book}}.png" width="200px" height="200px"></li>
  </u1>
</div></code>```

for which I am getting the following in the console:

```<code>Object {-Km712C_iBij3OkXCR1s: Object, -Km71G_rHgirXWZi1xh6: Object, -Km71Rje4ZeluNYtK8x_: Object, -Km71gTdrfgC1BeXIPPU: Object, -Km71x6C-s_FFTcEMYCc: Object…}
</code>```

-Km71G_rHgirXWZi1xh6
:
Object
author
:
"Ashwin Sanghi"
book
:
"chanakya'sChant"
cost
:
"300"
proto
:
Object
-Km71Rje4ZeluNYtK8x_
:
Object
-Km71gTdrfgC1BeXIPPU
:
Object
-Km71x6C-s_FFTcEMYCc
:
Object
-Km72Bg8o63vuNBqnU4D
:
Object
-Km72VI64weNgpMJTXCL
:
Object
-Km72d4OIl3pz5BylWc4
:
Object
-Km72kkzjTksropLmXzY
:
Object
-Km72tZ4u2CIPpK8FU_n
:
Object
-Km73NBgknkSUHytQmY5
:
Object
-Km74QCIFrgrOhzp7IIP
:
Object
-Km712C_iBij3OkXCR1s
:
Object
-Km739xvEa1StJHvWcka
:
Object
proto
:
Object

but I am not able to list the "book" elements. please help with some examples.

答:
You should probably just use the angular firebase module so it will handle triggering the apply/digest on the rootScope when changes occur to get the view to update:

https://github.com/firebase/angularfire

You could also add $scope.$apply to your code but without understanding this it is ill advised.

Body:
I am new to coding, and a basic answer would be very much appreciated.

I am trying to use firebase object as a javascript array to use it on html using $scope. what would be the best method?

database:
database

I am using:

var mainApp = angular.module("bookWorm", []);

mainApp.controller('bookController', function($scope, $http) {

  var ref = firebase.database().ref("Fiction");

  ref.once("value", function(snapshot) {

    console.log(snapshot.val());
    $scope.fiction = snapshot.val();

  });

});

Fiction

  <u1 style="cursor:pointer">

  </u1>

for which I am getting the following in the console:

Object {-Km712C_iBij3OkXCR1s: Object, -Km71G_rHgirXWZi1xh6: Object, -Km71Rje4ZeluNYtK8x_: Object, -Km71gTdrfgC1BeXIPPU: Object, -Km71x6C-s_FFTcEMYCc: Object…}

-Km71G_rHgirXWZi1xh6
:
Object
author
:
"Ashwin Sanghi"
book
:
"chanakya'sChant"
cost
:
"300"
proto
:
Object
-Km71Rje4ZeluNYtK8x_
:
Object
-Km71gTdrfgC1BeXIPPU
:
Object
-Km71x6C-s_FFTcEMYCc
:
Object
-Km72Bg8o63vuNBqnU4D
:
Object
-Km72VI64weNgpMJTXCL
:
Object
-Km72d4OIl3pz5BylWc4
:
Object
-Km72kkzjTksropLmXzY
:
Object
-Km72tZ4u2CIPpK8FU_n
:
Object
-Km73NBgknkSUHytQmY5
:
Object
-Km74QCIFrgrOhzp7IIP
:
Object
-Km712C_iBij3OkXCR1s
:
Object
-Km739xvEa1StJHvWcka
:
Object
proto
:
Object

but I am not able to list the "book" elements. please help with some examples.


问:
Can a plane cast shadow on another plane in Three.js?
I have a plane with a transparent PNG (a world map).

Can I cast shadows from one plane onto another plane?

I am having no success with this code:

```<code>plane = new THREE.Mesh(new THREE.PlaneGeometry(200,200), new THREE.MeshLambertMaterial({color: 0xcccccc}));

var mapTexture = new THREE.ImageUtils.loadTexture("img/map_transp2.png");
    mapTexture.needsUpdate = true;
    var mapMaterial = new THREE.MeshBasicMaterial({
        color:0xaaaaaa,
        transparent:true,
        map:mapTexture,
        side:THREE.DoubleSide
    });

mapPlane = new THREE.Mesh(new THREE.PlaneGeometry(800/5,370/5), mapMaterial);

plane.receiveShadow = true;
mapPlane.castShadow = true;
</code>```

答:
See https://github.com/mrdoob/three.js/issues/9315

Set

```<code>renderer.shadowMap.renderReverseSided = false
</code>```

or/and

```<code>renderer.shadowMap.renderSingleSided = false
</code>```

can solve the problem.

When disabled, an appropriate shadow.bias must be set on the light source for surfaces that can both cast and receive shadows at the same time to render correctly:

```<code>let dl = new THREE.DirectionalLight()
dl.shadow.bias = -0.0001
</code>```

three.js r.85

Body:
I have a plane with a transparent PNG (a world map).

Can I cast shadows from one plane onto another plane?

I am having no success with this code:

plane = new THREE.Mesh(new THREE.PlaneGeometry(200,200), new THREE.MeshLambertMaterial({color: 0xcccccc}));

var mapTexture = new THREE.ImageUtils.loadTexture("img/map_transp2.png");
    mapTexture.needsUpdate = true;
    var mapMaterial = new THREE.MeshBasicMaterial({
        color:0xaaaaaa,
        transparent:true,
        map:mapTexture,
        side:THREE.DoubleSide
    });

mapPlane = new THREE.Mesh(new THREE.PlaneGeometry(800/5,370/5), mapMaterial);

plane.receiveShadow = true;
mapPlane.castShadow = true;

Body:
See https://github.com/mrdoob/three.js/issues/9315

Set

renderer.shadowMap.renderReverseSided = false

or/and

renderer.shadowMap.renderSingleSided = false

can solve the problem.

When disabled, an appropriate shadow.bias must be set on the light source for surfaces that can both cast and receive shadows at the same time to render correctly:

let dl = new THREE.DirectionalLight()
dl.shadow.bias = -0.0001

three.js r.85


问:
Using jquery to get value of text area in closest table cell
I have the following table

```<code><tr>
<td data-toggle="tooltip" title="Not Started"><img  src="images/small_info_icon.png"></td>
<td>Demo Demo</td>
<td>January</td>
<td class="updaterow"><textarea class="form-control" rows="5" id="notes34455" name="editcomments">Not Started</textarea></td>
<td id="34455"><button type="button" id="updatestatus" class="btn btn-info btn-sm">Update</button> </td>
</tr>
</code>```

I want to use jquery to get the value of the textarea.
I am using the following, but it is giving undefined.

```<code>$("button#updatestatus").click(function(){
var id = $(this).closest('td').attr('id');
var data = $(this).closest("updaterow").text;
alert(data);
var data = {
            id: id,

            };
$.ajax({
type: "POST",
url: "updatestatus.php",
data: data
}).done(function(msg) {
console.log(msg);
});
</code>```

Is it possible to get the textvalue of the textarea?

答:
.closest() looks for the closest containing element that matches the selector. .updaterow doesn't contain button#updatestatus, so it won't find it. .updaterow is the previous td, so it should be:

```<code>var data = $(this).closest("tr").siblings(".updaterow").text();
</code>```

You also forgot the . in .updaterow and the () in .text().

Body:
I have the following table

Demo Demo
January
<textarea class="form-control" rows="5" id="notes34455" name="editcomments">Not Started</textarea>
<button type="button" id="updatestatus" class="btn btn-info btn-sm">Update</button>

I want to use jquery to get the value of the textarea.
I am using the following, but it is giving undefined.

$("button#updatestatus").click(function(){
var id = $(this).closest('td').attr('id');
var data = $(this).closest("updaterow").text;
alert(data);
var data = {
            id: id,

            };
$.ajax({
type: "POST",
url: "updatestatus.php",
data: data
}).done(function(msg) {
console.log(msg);
});

Is it possible to get the textvalue of the textarea?

Body:
.closest() looks for the closest containing element that matches the selector. .updaterow doesn't contain button#updatestatus, so it won't find it. .updaterow is the previous td, so it should be:

var data = $(this).closest("tr").siblings(".updaterow").text();

You also forgot the . in .updaterow and the () in .text().


问:
Applying Functions to a Dictionary
I'm still learning Python and the basic rules here as well so please correct me if I'm making a faux pas.  One can't grow without proper criticism and coaching.

I'm trying to help my wife with a volunteer schedule for a fund raiser she is conducting.  The day contains 7 hourly events and I have 7 hourly schedules that will have a person working for 4 of the 7 events, for the volunteers to pick from.

What this code does is calculate the number of each schedule I'll need to meet the event volunteer requirements based on the number of volunteers I have available.  I currently do not know the exact number of volunteers she will have available.

```<code>import random
    # Volunteer Requirements for each of the 7 events
r = [6, 12, 14, 14, 12, 16, 10]
    # Available Schedules where 0 = hour off and 1 = hour working
s = []
s.append([0,1,1,1,1,0,0])
s.append([0,0,1,1,1,1,0])
s.append([0,0,0,1,1,1,1])
s.append([1,1,1,1,0,0,0])
s.append([1,1,0,0,0,1,1])
s.append([1,1,1,0,0,0,1])
s.append([1,0,0,0,1,1,1])

number_of_schedules = len(s)
number_of_vols = 21
number_of_hours = len(s[0])

while True:
    q = [0]*number_of_schedules
    for i in range(number_of_vols):
        q[random.randint(0,len(q)-1)] += 1
    t = [sum([q[j]*s[j][i] for j in range(number_of_schedules)]) for i in range(number_of_hours)]
    if sum([r[i] <= t[i] for i in range(number_of_hours)]) == number_of_hours:
        print '\n'.join(map(str,q))
        print '\n'.join(map(str,s))
        break
</code>```

When I run the code it prints as:

```<code>3
8
2
1
6
2
0
[0, 1, 1, 1, 1, 0, 0]
[0, 0, 1, 1, 1, 1, 0]
[0, 0, 0, 1, 1, 1, 1]
[1, 1, 1, 1, 0, 0, 0]
[1, 1, 0, 0, 0, 1, 1]
[1, 1, 1, 0, 0, 0, 1]
[1, 0, 0, 0, 1, 1, 1]
</code>```

This tells me that in order to meet the requirements I will need 3 people to take the first schedule, 8 to take the second, 2 to take the third, and so on.

What I want to do is build the list 's' as a dict so that I can give a name to each schedule, i.e. 'Schedule A', 'Schedule B', etc.  This way I can call the print function to print each schedule the number of times it is needed.

The preferred end result would look something like this when I call the print function.

```<code>    Schedule A
    Schedule A
    Schedule B
    Schedule B
    Schedule B
    Schedule B
    Schedule B
    ........
    Schedule G
</code>```

Then each volunteer can put their name next to an available schedule.

The problem I run into is that regardless of what method I attempt, I cannot get it to work correctly.  I'm hoping to get this done by Friday as my wife wants to send out a volunteer request email this weekend.  Any help/direction anyone can provide would be greatly appreciated.

Thanks in advance.

答:
For interest I coded this as a genetic search:

```<code>import numpy as np
from random import choice, randrange
from string import ascii_uppercase

# volunteer requirements for each of the 7 events
NEEDED = np.array([6, 12, 14, 14, 12, 16, 10], dtype=np.int32)

# available schedules where 0 = hour off and 1 = hour working
SCHEDULES = np.array([
    [0,1,1,1,1,0,0],
    [0,0,1,1,1,1,0],
    [0,0,0,1,1,1,1],
    [1,1,1,1,0,0,0],
    [1,1,0,0,0,1,1],
    [1,1,1,0,0,0,1],
    [1,0,0,0,1,1,1]
], dtype=np.int32)

NAMES = ["Schedule {}".format(ch) for ch in ascii_uppercase[:len(SCHEDULES)]]

def alloc_random(num, schedules):
    """
    Create a random allocation of schedules
    """
    num_schedules = len(schedules)
    alloc = np.zeros(num_schedules, dtype=np.int32)
    for _ in range(num):
        alloc[randrange(num_schedules)] += 1
    return alloc

def alloc_mutate(alloc):
    """
    Randomly replace one schedule with another
    """
    alloc = np.copy(alloc)   # make a new allocation (instead of modifying the parent)
    num_schedules = len(alloc)
    while True:
        from_ = randrange(num_schedules)
        to_ = randrange(num_schedules)
        if from_ != to_ and alloc[from_] > 0:
            alloc[from_] -= 1
            alloc[to_] += 1
            return alloc

def alloc_fitness(alloc):
    """
    Given a schedule allocation,
      return the minimum (volunteers present / needed) of any period
    """
    return np.min(alloc.dot(SCHEDULES) / NEEDED)

def alloc_find_best(num_volunteers, needed, schedules, population=20, children=100, generations=1000):
    """
    Find the best way to assign schedules to volunteers
    """
    # generate starting population
    pop = [alloc_random(num_volunteers, schedules) for _ in range(population)]
    # evolve!
    for gen in range(generations):
        # create evolved children
        ch = [alloc_mutate(choice(pop)) for _ in range(children)]
        # add the parents to the evaluation pool
        ch.extend(pop)
        # sort from most to least fit
        ch.sort(key=alloc_fitness, reverse=True)
        # decimate
        pop = ch[:population]
    # return the best solution found
    return pop[0]

def main():
    for num_volunteers in range(21, 25):
        best = alloc_find_best(num_volunteers, NEEDED, SCHEDULES)
        print("\n{:>2d} volunteers:  fitness = {:0.1f}%".format(num_volunteers, 100. * alloc_fitness(best)))
        for label,val in zip(NAMES, best):
            print("{:>14s}: {:>2d}".format(label, val))

if __name__ == "__main__":
    main()
</code>```

which gives output like

```<code>21 volunteers:  fitness = 92.9%
    Schedule A:  4
    Schedule B:  7
    Schedule C:  2
    Schedule D:  0
    Schedule E:  6
    Schedule F:  2
    Schedule G:  0

22 volunteers:  fitness = 100.0%
    Schedule A:  3
    Schedule B:  8
    Schedule C:  2
    Schedule D:  1
    Schedule E:  6
    Schedule F:  2
    Schedule G:  0

23 volunteers:  fitness = 100.0%
    Schedule A:  2
    Schedule B:  9
    Schedule C:  2
    Schedule D:  2
    Schedule E:  6
    Schedule F:  2
    Schedule G:  0

24 volunteers:  fitness = 107.1%
    Schedule A:  4
    Schedule B:  9
    Schedule C:  2
    Schedule D:  0
    Schedule E:  7
    Schedule F:  2
    Schedule G:  0
</code>```

There are a couple of points of interest:

just adding up the needed volunteer slots shows you need a minimum of 84 / 4 == 21 volunteers

running this a couple of times shows that you need a minimum of 22 volunteers to actually be able to schedule everything, and at least 24 to have a spare in every time slot

your randomly discovered solution is actually exactly the same as what I got, but my algorithm runs much faster - 0.8s vs an average of 36s (anything from 12s to 86s in my testing).

To get the final result format you want,

```<code>for name,num,sched in zip(NAMES, best, SCHEDULES):
    for _ in range(num):
        print(name + "  " + str(sched))
</code>```

which gives something like

```<code>Schedule A  [0 1 1 1 1 0 0]
Schedule A  [0 1 1 1 1 0 0]
Schedule A  [0 1 1 1 1 0 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule C  [0 0 0 1 1 1 1]
Schedule C  [0 0 0 1 1 1 1]
Schedule D  [1 1 1 1 0 0 0]
Schedule E  [1 1 0 0 0 1 1]
Schedule E  [1 1 0 0 0 1 1]
Schedule E  [1 1 0 0 0 1 1]
Schedule E  [1 1 0 0 0 1 1]
Schedule E  [1 1 0 0 0 1 1]
Schedule E  [1 1 0 0 0 1 1]
Schedule F  [1 1 1 0 0 0 1]
Schedule F  [1 1 1 0 0 0 1]
</code>```

I also did a bit of sensitivity analysis like

```<code>from collections import Counter
Counter(tuple(alloc_find_best(22, NEEDED, SCHEDULES)) for _ in range(100))
</code>```

which gave

```<code>{
    (2, 8, 2, 2, 6, 2, 0): 32,
    (3, 8, 2, 1, 6, 2, 0): 39,
    (4, 8, 2, 0, 6, 2, 0): 29
}
</code>```

which says that only 3 solutions were found in 100 trials, that the second solution was found slightly more often, but that all three were roughly as likely. It is interesting to note that the only difference between them is a trade-off between schedules A and D == time slots 1 and 5.

Title: Applying Functions to a Dictionary

Body:
I'm still learning Python and the basic rules here as well so please correct me if I'm making a faux pas.  One can't grow without proper criticism and coaching.

I'm trying to help my wife with a volunteer schedule for a fund raiser she is conducting.  The day contains 7 hourly events and I have 7 hourly schedules that will have a person working for 4 of the 7 events, for the volunteers to pick from.

What this code does is calculate the number of each schedule I'll need to meet the event volunteer requirements based on the number of volunteers I have available.  I currently do not know the exact number of volunteers she will have available.

import random
    # Volunteer Requirements for each of the 7 events
r = [6, 12, 14, 14, 12, 16, 10]
    # Available Schedules where 0 = hour off and 1 = hour working
s = []
s.append([0,1,1,1,1,0,0])
s.append([0,0,1,1,1,1,0])
s.append([0,0,0,1,1,1,1])
s.append([1,1,1,1,0,0,0])
s.append([1,1,0,0,0,1,1])
s.append([1,1,1,0,0,0,1])
s.append([1,0,0,0,1,1,1])

number_of_schedules = len(s)
number_of_vols = 21
number_of_hours = len(s[0])

while True:
    q = [0]*number_of_schedules
    for i in range(number_of_vols):
        q[random.randint(0,len(q)-1)] += 1
    t = [sum([q[j]*s[j][i] for j in range(number_of_schedules)]) for i in range(number_of_hours)]
    if sum([r[i] <= t[i] for i in range(number_of_hours)]) == number_of_hours:
        print '\n'.join(map(str,q))
        print '\n'.join(map(str,s))
        break

When I run the code it prints as:

3
8
2
1
6
2
0
[0, 1, 1, 1, 1, 0, 0]
[0, 0, 1, 1, 1, 1, 0]
[0, 0, 0, 1, 1, 1, 1]
[1, 1, 1, 1, 0, 0, 0]
[1, 1, 0, 0, 0, 1, 1]
[1, 1, 1, 0, 0, 0, 1]
[1, 0, 0, 0, 1, 1, 1]

This tells me that in order to meet the requirements I will need 3 people to take the first schedule, 8 to take the second, 2 to take the third, and so on.

What I want to do is build the list 's' as a dict so that I can give a name to each schedule, i.e. 'Schedule A', 'Schedule B', etc.  This way I can call the print function to print each schedule the number of times it is needed.

The preferred end result would look something like this when I call the print function.

    Schedule A
    Schedule A
    Schedule B
    Schedule B
    Schedule B
    Schedule B
    Schedule B
    ........
    Schedule G

Then each volunteer can put their name next to an available schedule.

The problem I run into is that regardless of what method I attempt, I cannot get it to work correctly.  I'm hoping to get this done by Friday as my wife wants to send out a volunteer request email this weekend.  Any help/direction anyone can provide would be greatly appreciated.

Thanks in advance.

Body:
For interest I coded this as a genetic search:

import numpy as np
from random import choice, randrange
from string import ascii_uppercase

# volunteer requirements for each of the 7 events
NEEDED = np.array([6, 12, 14, 14, 12, 16, 10], dtype=np.int32)

# available schedules where 0 = hour off and 1 = hour working
SCHEDULES = np.array([
    [0,1,1,1,1,0,0],
    [0,0,1,1,1,1,0],
    [0,0,0,1,1,1,1],
    [1,1,1,1,0,0,0],
    [1,1,0,0,0,1,1],
    [1,1,1,0,0,0,1],
    [1,0,0,0,1,1,1]
], dtype=np.int32)

NAMES = ["Schedule {}".format(ch) for ch in ascii_uppercase[:len(SCHEDULES)]]

def alloc_random(num, schedules):
    """
    Create a random allocation of schedules
    """
    num_schedules = len(schedules)
    alloc = np.zeros(num_schedules, dtype=np.int32)
    for _ in range(num):
        alloc[randrange(num_schedules)] += 1
    return alloc

def alloc_mutate(alloc):
    """
    Randomly replace one schedule with another
    """
    alloc = np.copy(alloc)   # make a new allocation (instead of modifying the parent)
    num_schedules = len(alloc)
    while True:
        from_ = randrange(num_schedules)
        to_ = randrange(num_schedules)
        if from_ != to_ and alloc[from_] > 0:
            alloc[from_] -= 1
            alloc[to_] += 1
            return alloc

def alloc_fitness(alloc):
    """
    Given a schedule allocation,
      return the minimum (volunteers present / needed) of any period
    """
    return np.min(alloc.dot(SCHEDULES) / NEEDED)

def alloc_find_best(num_volunteers, needed, schedules, population=20, children=100, generations=1000):
    """
    Find the best way to assign schedules to volunteers
    """
    # generate starting population
    pop = [alloc_random(num_volunteers, schedules) for _ in range(population)]
    # evolve!
    for gen in range(generations):
        # create evolved children
        ch = [alloc_mutate(choice(pop)) for _ in range(children)]
        # add the parents to the evaluation pool
        ch.extend(pop)
        # sort from most to least fit
        ch.sort(key=alloc_fitness, reverse=True)
        # decimate
        pop = ch[:population]
    # return the best solution found
    return pop[0]

def main():
    for num_volunteers in range(21, 25):
        best = alloc_find_best(num_volunteers, NEEDED, SCHEDULES)
        print("\n{:>2d} volunteers:  fitness = {:0.1f}%".format(num_volunteers, 100. * alloc_fitness(best)))
        for label,val in zip(NAMES, best):
            print("{:>14s}: {:>2d}".format(label, val))

if __name__ == "__main__":
    main()

which gives output like

21 volunteers:  fitness = 92.9%
    Schedule A:  4
    Schedule B:  7
    Schedule C:  2
    Schedule D:  0
    Schedule E:  6
    Schedule F:  2
    Schedule G:  0

22 volunteers:  fitness = 100.0%
    Schedule A:  3
    Schedule B:  8
    Schedule C:  2
    Schedule D:  1
    Schedule E:  6
    Schedule F:  2
    Schedule G:  0

23 volunteers:  fitness = 100.0%
    Schedule A:  2
    Schedule B:  9
    Schedule C:  2
    Schedule D:  2
    Schedule E:  6
    Schedule F:  2
    Schedule G:  0

24 volunteers:  fitness = 107.1%
    Schedule A:  4
    Schedule B:  9
    Schedule C:  2
    Schedule D:  0
    Schedule E:  7
    Schedule F:  2
    Schedule G:  0

There are a couple of points of interest:

just adding up the needed volunteer slots shows you need a minimum of 84 / 4 == 21 volunteers

running this a couple of times shows that you need a minimum of 22 volunteers to actually be able to schedule everything, and at least 24 to have a spare in every time slot

your randomly discovered solution is actually exactly the same as what I got, but my algorithm runs much faster - 0.8s vs an average of 36s (anything from 12s to 86s in my testing).

To get the final result format you want,

for name,num,sched in zip(NAMES, best, SCHEDULES):
    for _ in range(num):
        print(name + "  " + str(sched))

which gives something like

Schedule A  [0 1 1 1 1 0 0]
Schedule A  [0 1 1 1 1 0 0]
Schedule A  [0 1 1 1 1 0 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule B  [0 0 1 1 1 1 0]
Schedule C  [0 0 0 1 1 1 1]
Schedule C  [0 0 0 1 1 1 1]
Schedule D  [1 1 1 1 0 0 0]
Schedule E  [1 1 0 0 0 1 1]
Schedule E  [1 1 0 0 0 1 1]
Schedule E  [1 1 0 0 0 1 1]
Schedule E  [1 1 0 0 0 1 1]
Schedule E  [1 1 0 0 0 1 1]
Schedule E  [1 1 0 0 0 1 1]
Schedule F  [1 1 1 0 0 0 1]
Schedule F  [1 1 1 0 0 0 1]

I also did a bit of sensitivity analysis like

from collections import Counter
Counter(tuple(alloc_find_best(22, NEEDED, SCHEDULES)) for _ in range(100))

which gave

{
    (2, 8, 2, 2, 6, 2, 0): 32,
    (3, 8, 2, 1, 6, 2, 0): 39,
    (4, 8, 2, 0, 6, 2, 0): 29
}

which says that only 3 solutions were found in 100 trials, that the second solution was found slightly more often, but that all three were roughly as likely. It is interesting to note that the only difference between them is a trade-off between schedules A and D == time slots 1 and 5.


问:
C# 20,000 records selected from oracle need to be inserted into SQL2005
i have a console app in c# that extracts 20 fields from an oracle DB witht he code below and i wanted an efficient way to insert them into SQL 2005.

i dotn want to insert each one of the 20,000 within the while loop, obviously. i was thinking to change the code to use a data set to cache all the records and then do a bulk insert...

thoughts?

pseudo code would be nice since i am new to oracle.

this is my code where i was testing getting a connection to oracle and seeing if i can view the data... now i can view it i want to get it out and into sql2005... what do i do from here?

```<code>static void getData()
{
    string connectionString = GetConnectionString();
    using (OracleConnection connection = new OracleConnection())
    {
        connection.ConnectionString = connectionString;
        connection.Open();

        OracleCommand command = connection.CreateCommand();
        string sql = "SELECT * FROM BUG";
        command.CommandText = sql;

        OracleDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            //string myField = (string)reader["Project"];
            string myField = reader[0].ToString();
            Console.WriteLine(myField);
        }
    }

}
</code>```

答:
The "bulk" insert with the cached Dataset will work exactly like the while loop you are not wanting to write! The problem is that you'll lose control of the process if you try to use the "bulk" insert of the Dataset class. It is extraneous work in the end.

Maybe the best solution is to use a DataWriter so that you have complete control and no Dataset overhead.

Body:
i have a console app in c# that extracts 20 fields from an oracle DB witht he code below and i wanted an efficient way to insert them into SQL 2005.

i dotn want to insert each one of the 20,000 within the while loop, obviously. i was thinking to change the code to use a data set to cache all the records and then do a bulk insert...

thoughts?

pseudo code would be nice since i am new to oracle.

this is my code where i was testing getting a connection to oracle and seeing if i can view the data... now i can view it i want to get it out and into sql2005... what do i do from here?

static void getData()
{
    string connectionString = GetConnectionString();
    using (OracleConnection connection = new OracleConnection())
    {
        connection.ConnectionString = connectionString;
        connection.Open();

        OracleCommand command = connection.CreateCommand();
        string sql = "SELECT * FROM BUG";
        command.CommandText = sql;

        OracleDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            //string myField = (string)reader["Project"];
            string myField = reader[0].ToString();
            Console.WriteLine(myField);
        }
    }

}


问:
Tensorflow image reading & display
I've got a bunch of images in a format similar to Cifar10 (binary file, size = 96*96*3 bytes per image), one image after another (STL-10 dataset). The file I'm opening has 138MB.

I tried to read & check the contents of the Tensors containing the images to be sure that the reading is done right, however I have two questions -

Does the FixedLengthRecordReader load the whole file, however just provide inputs one at a time? Since reading the first size bytes should be relatively fast. However, the code takes about two minutes to run.

How to get the actual image contents in a displayable format, or display them internally to validate that the images are read well? I did sess.run(uint8image), however the result is empty.

The code is below:

```<code>import tensorflow as tf
def read_stl10(filename_queue):
  class STL10Record(object):
    pass
  result = STL10Record()

  result.height = 96
  result.width = 96
  result.depth = 3
  image_bytes = result.height * result.width * result.depth
  record_bytes = image_bytes

  reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)
  result.key, value = reader.read(filename_queue)
  print value
  record_bytes = tf.decode_raw(value, tf.uint8)

  depth_major = tf.reshape(tf.slice(record_bytes, [0], [image_bytes]),
                       [result.depth, result.height, result.width])
  result.uint8image = tf.transpose(depth_major, [1, 2, 0])
  return result
# probably a hack since I should've provided a string tensor

filename_queue = tf.train.string_input_producer(['./data/train_X'])
image = read_stl10(filename_queue)

print image.uint8image
with tf.Session() as sess:
  result = sess.run(image.uint8image)
  print result, type(result)
</code>```

Output:

```<code>Tensor("ReaderRead:1", shape=TensorShape([]), dtype=string)
Tensor("transpose:0", shape=TensorShape([Dimension(96), Dimension(96), Dimension(3)]), dtype=uint8)
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 4
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 4
[empty line for last print]
Process finished with exit code 137
</code>```

I'm running this on my CPU, if that adds anything.

EDIT: I found the pure TensorFlow solution thanks to Rosa. Apparently, when using the string_input_producer, in order to see the results, you need to initialize the queue runners.
The only required thing to add to the code above is the second line from below:

```<code>...
with tf.Session() as sess:
    tf.train.start_queue_runners(sess=sess)
...
</code>```

Afterwards, the image in the result can be displayed with matplotlib.pyplot.imshow(result). I hope this helps someone. If you have any further questions, feel free to ask me or check the link in Rosa's answer.

答:
I used CIFAR10 format instead of STL10 and code came out like

```<code>filename_queue = tf.train.string_input_producer(filenames)
read_input = read_cifar10(filename_queue)
with tf.Session() as sess:
    tf.train.start_queue_runners(sess=sess)
    result = sess.run(read_input.uint8image)
img = Image.fromarray(result, "RGB")
img.save('my.jpg')
</code>```

The snippet is identical with mttk and Rosa Gronchi, but Somehow I wasn't able to show the image during run-time, so I saved as the JPG file.

Title: Tensorflow image reading & display

Body:
I've got a bunch of images in a format similar to Cifar10 (binary file, size = 96*96*3 bytes per image), one image after another (STL-10 dataset). The file I'm opening has 138MB.

I tried to read & check the contents of the Tensors containing the images to be sure that the reading is done right, however I have two questions -

Does the FixedLengthRecordReader load the whole file, however just provide inputs one at a time? Since reading the first size bytes should be relatively fast. However, the code takes about two minutes to run.

How to get the actual image contents in a displayable format, or display them internally to validate that the images are read well? I did sess.run(uint8image), however the result is empty.

The code is below:

import tensorflow as tf
def read_stl10(filename_queue):
  class STL10Record(object):
    pass
  result = STL10Record()

  result.height = 96
  result.width = 96
  result.depth = 3
  image_bytes = result.height * result.width * result.depth
  record_bytes = image_bytes

  reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)
  result.key, value = reader.read(filename_queue)
  print value
  record_bytes = tf.decode_raw(value, tf.uint8)

  depth_major = tf.reshape(tf.slice(record_bytes, [0], [image_bytes]),
                       [result.depth, result.height, result.width])
  result.uint8image = tf.transpose(depth_major, [1, 2, 0])
  return result
# probably a hack since I should've provided a string tensor

filename_queue = tf.train.string_input_producer(['./data/train_X'])
image = read_stl10(filename_queue)

print image.uint8image
with tf.Session() as sess:
  result = sess.run(image.uint8image)
  print result, type(result)

Output:

Tensor("ReaderRead:1", shape=TensorShape([]), dtype=string)
Tensor("transpose:0", shape=TensorShape([Dimension(96), Dimension(96), Dimension(3)]), dtype=uint8)
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 4
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 4
[empty line for last print]
Process finished with exit code 137

I'm running this on my CPU, if that adds anything.

EDIT: I found the pure TensorFlow solution thanks to Rosa. Apparently, when using the string_input_producer, in order to see the results, you need to initialize the queue runners.
The only required thing to add to the code above is the second line from below:

...
with tf.Session() as sess:
    tf.train.start_queue_runners(sess=sess)
...

Afterwards, the image in the result can be displayed with matplotlib.pyplot.imshow(result). I hope this helps someone. If you have any further questions, feel free to ask me or check the link in Rosa's answer.

Body:
I used CIFAR10 format instead of STL10 and code came out like

filename_queue = tf.train.string_input_producer(filenames)
read_input = read_cifar10(filename_queue)
with tf.Session() as sess:
    tf.train.start_queue_runners(sess=sess)
    result = sess.run(read_input.uint8image)
img = Image.fromarray(result, "RGB")
img.save('my.jpg')

The snippet is identical with mttk and Rosa Gronchi, but Somehow I wasn't able to show the image during run-time, so I saved as the JPG file.


问:
Changing sources on videosphere updates DOM but doesn't render
I have two video assets which I would like to switch between based on a user interaction.

```<code><a-assets>
  <video id="video" src="./<filename>.mp4" autoplay loop crossorigin></video>
  <video id="video2" src="./<filename>.mp4" autoplay loop crossorigin></video>
</a-assets>
</code>```

These assets are referenced in a videosphere within the same .

```<code><a-videosphere id="videosphere" src="#video" rotation="0 270 0"></a-videosphere>
</code>```

When the interactive element, an , is focused by the camera cursor, logic is triggered which swaps the videosphere source and plays the new video.

```<code>document.querySelector('<interactive element>').addEventListener('mouseenter', function () {
  var videosphere = document.querySelector('#videosphere');
  videosphere.setAttribute('src', '#video2');

  var video = document.querySelector(videosphere.getAttribute('src'));
  video.play();
});
</code>```

The event fires successfully and the src change is reflected in the DOM, but the new video is not rendered. I have tried using  in place of  but with the same result.

Both videos play as expected when set as the default src of . For repro purposes, I'm testing in Firefox Nightly 55.0a1

Thanks in advance for your help!

答:
It appears that changing the material attribute works while changing the src attribute does not.

videosphere.setAttribute('src', '#video'); // NO CHANGE
videosphere.setAttribute('material', 'src: #video;'); // SUCCESS

see aframevr issue #2636

Body:
I have two video assets which I would like to switch between based on a user interaction.

  <video id="video" src="./<filename>.mp4" autoplay loop crossorigin></video>
  <video id="video2" src="./<filename>.mp4" autoplay loop crossorigin></video>

These assets are referenced in a videosphere within the same .

When the interactive element, an , is focused by the camera cursor, logic is triggered which swaps the videosphere source and plays the new video.

document.querySelector('<interactive element>').addEventListener('mouseenter', function () {
  var videosphere = document.querySelector('#videosphere');
  videosphere.setAttribute('src', '#video2');

  var video = document.querySelector(videosphere.getAttribute('src'));
  video.play();
});

The event fires successfully and the src change is reflected in the DOM, but the new video is not rendered. I have tried using  in place of  but with the same result.

Both videos play as expected when set as the default src of . For repro purposes, I'm testing in Firefox Nightly 55.0a1

Thanks in advance for your help!


问:
Invalid ELF header xgboost (using a pkl in a Docker container)
I have a pkl file which uses the library xgboost.
In my code I just import this pkl and load it:

```<code>def _init_model(self):
    self.model = joblib.load(QueryClassifier.MODEL_FILE)
</code>```

Also I am running my code inside a Docker container.
I have a requirements file like this one:

```<code>scipy
sklearn
numpy
xgboost
pandas
flask
</code>```

I have this error when I try to run the Docker Container:

```<code>Traceback (most recent call last):
  File "server.py", line 12, in <module>
    c = classifier.QueryClassifier()
  File "/app/classifier_controller/classifier.py", line 43, in __init__
    self._init_model()
  File "/app/classifier_controller/classifier.py", line 62, in _init_model
    self.model = joblib.load(QueryClassifier.MODEL_FILE)
  File "/usr/local/lib/python3.5/site-packages/sklearn/externals/joblib/numpy_pickle.py", line 575, in load
    obj = _unpickle(fobj, filename, mmap_mode)
  File "/usr/local/lib/python3.5/site-packages/sklearn/externals/joblib/numpy_pickle.py", line 507, in _unpickle
    obj = unpickler.load()
  File "/usr/local/lib/python3.5/pickle.py", line 1039, in load
    dispatch[key[0]](self)
  File "/usr/local/lib/python3.5/pickle.py", line 1334, in load_global
    klass = self.find_class(module, name)
  File "/usr/local/lib/python3.5/pickle.py", line 1384, in find_class
    __import__(module, level=0)
  File "/usr/local/lib/python3.5/site-packages/xgboost/__init__.py", line 11, in <module>
    from .core import DMatrix, Booster
  File "/usr/local/lib/python3.5/site-packages/xgboost/core.py", line 112, in <module>
    _LIB = _load_lib()
  File "/usr/local/lib/python3.5/site-packages/xgboost/core.py", line 106, in _load_lib
    lib = ctypes.cdll.LoadLibrary(lib_path[0])
  File "/usr/local/lib/python3.5/ctypes/__init__.py", line 425, in LoadLibrary
    return self._dlltype(name)
  File "/usr/local/lib/python3.5/ctypes/__init__.py", line 347, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: /usr/local/lib/python3.5/site-packages/xgboost/./lib/libxgboost.so: invalid ELF header
</code>```

Any help?

答:
You need to build xhboost .

See https://github.com/dmlc/xgboost/issues/463

Body:
I have a pkl file which uses the library xgboost.
In my code I just import this pkl and load it:

def _init_model(self):
    self.model = joblib.load(QueryClassifier.MODEL_FILE)

Also I am running my code inside a Docker container.
I have a requirements file like this one:

scipy
sklearn
numpy
xgboost
pandas
flask

I have this error when I try to run the Docker Container:

Traceback (most recent call last):
  File "server.py", line 12, in <module>
    c = classifier.QueryClassifier()
  File "/app/classifier_controller/classifier.py", line 43, in __init__
    self._init_model()
  File "/app/classifier_controller/classifier.py", line 62, in _init_model
    self.model = joblib.load(QueryClassifier.MODEL_FILE)
  File "/usr/local/lib/python3.5/site-packages/sklearn/externals/joblib/numpy_pickle.py", line 575, in load
    obj = _unpickle(fobj, filename, mmap_mode)
  File "/usr/local/lib/python3.5/site-packages/sklearn/externals/joblib/numpy_pickle.py", line 507, in _unpickle
    obj = unpickler.load()
  File "/usr/local/lib/python3.5/pickle.py", line 1039, in load
    dispatch[key[0]](self)
  File "/usr/local/lib/python3.5/pickle.py", line 1334, in load_global
    klass = self.find_class(module, name)
  File "/usr/local/lib/python3.5/pickle.py", line 1384, in find_class
    __import__(module, level=0)
  File "/usr/local/lib/python3.5/site-packages/xgboost/__init__.py", line 11, in <module>
    from .core import DMatrix, Booster
  File "/usr/local/lib/python3.5/site-packages/xgboost/core.py", line 112, in <module>
    _LIB = _load_lib()
  File "/usr/local/lib/python3.5/site-packages/xgboost/core.py", line 106, in _load_lib
    lib = ctypes.cdll.LoadLibrary(lib_path[0])
  File "/usr/local/lib/python3.5/ctypes/__init__.py", line 425, in LoadLibrary
    return self._dlltype(name)
  File "/usr/local/lib/python3.5/ctypes/__init__.py", line 347, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: /usr/local/lib/python3.5/site-packages/xgboost/./lib/libxgboost.so: invalid ELF header

Any help?


问:
Selecting the file with the biggest size in a folder than applying couple of functions in Python
I am interested in finding the files with the biggest size in terms of kbs in a folder and then apply a function. After that, I want to apply a different function to remaining files in the same folder. If I knew which files I was going to use, names and sizes of the files, I would use the following code:

```<code>with open(big_file, 'r') as bigfile:
   bigfile.rotate #predefined function
   minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(bigfile) #predefined function
   w1 = maxx - minx
   l1 = maxy - miny
   h1 = maxz - minz
   copies = copy_obj(bigfile, (w1, l1, h1), 2, 2, 1)
with open(small_file, 'r') as smallfile:
    minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(smallfile)
    w2 = maxx - minx
    l2 = maxy - miny
    h2 = maxz - minz
    translate(smallfile, w1, w1 / 10., 3, 'x')
    copies2 = copy_obj(smallfile, (w2, l2, h2), 2, 2, 1)
    combined = mesh.Mesh(numpy.concatenate([bigfile.data, smallfile.data] +
                                [copy.data for copy in copies] +
                                [copy.data for copy in copies2]))
    combined.save(folder + '.stl', mode=stl.Mode.ASCII)  # save as ASCII
</code>```

How I could apply it to many folders that consist of many files

答:
This finds the biggest file in a given directory:</p>

```<code>import os
path = '/path/to/directory'
print(max(os.listdir(path), key=lambda x: os.stat(os.path.join(path,x)).st_size))
</code>```

Body:
I am interested in finding the files with the biggest size in terms of kbs in a folder and then apply a function. After that, I want to apply a different function to remaining files in the same folder. If I knew which files I was going to use, names and sizes of the files, I would use the following code:

with open(big_file, 'r') as bigfile:
   bigfile.rotate #predefined function
   minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(bigfile) #predefined function
   w1 = maxx - minx
   l1 = maxy - miny
   h1 = maxz - minz
   copies = copy_obj(bigfile, (w1, l1, h1), 2, 2, 1)
with open(small_file, 'r') as smallfile:
    minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(smallfile)
    w2 = maxx - minx
    l2 = maxy - miny
    h2 = maxz - minz
    translate(smallfile, w1, w1 / 10., 3, 'x')
    copies2 = copy_obj(smallfile, (w2, l2, h2), 2, 2, 1)
    combined = mesh.Mesh(numpy.concatenate([bigfile.data, smallfile.data] +
                                [copy.data for copy in copies] +
                                [copy.data for copy in copies2]))
    combined.save(folder + '.stl', mode=stl.Mode.ASCII)  # save as ASCII

How I could apply it to many folders that consist of many files

Body:
This finds the biggest file in a given directory:

import os
path = '/path/to/directory'
print(max(os.listdir(path), key=lambda x: os.stat(os.path.join(path,x)).st_size))


问:
string.endswith("") does not work in IE(not sure how to use a Polyfill)
I am using string.endswith() to loop through JSON objects and find out if the any property of the object endswith a "Value" substring.

After finding out if the the object property ends with "Value", i am trying to round off the value of the property to 2 decimals which are by default 5 decimals.

Here is my code

```<code>var MyObj= [{"$id":"1","GeoName":"EAST","ReachValue":87.88221970554928,"ReachValue":90.71955219607294,"DepthValue":18.44377295716579,"ShareValue":16.732108234801206},{"$id":"2","GeoName":"WEST","ReachValue":87.88221970554928,"ReachValue":90.71955219607294,"DepthValue":18.44377295716579,"ShareValue":16.732108234801206}];
Obj = JSON.parse(JSON.stringify(MyObj)).map(function (e) {
            return Object.keys(e).reduce(function (p, n) {
                if (n.endsWith("Value"))
                    p[n] = Math.round(e[n] * 100) / 100;
                else
                    p[n] = e[n];
                return p;
            }, {})
        });
</code>```

The above code works absolutely fine in chrome and Firefox, While IE it throws endsWith is not a function exception.

I found out for such issues pollyfills are used, which i tried and i failed. I am not even sure if i used the pollyfill correctly.

so here is how i did it,

```<code>function polyFillEndswith(searchString, position) {
            if (!String.prototype.endsWith) {
                String.prototype.endsWith = function (searchString, position) {
                    var subjectString = this.toString();
                    if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
                        position = subjectString.length;
                    }
                    position -= searchString.length;
                    var lastIndex = subjectString.lastIndexOf(searchString, position);
                    return lastIndex !== -1 && lastIndex === position;
                }
            }
        }

Obj = JSON.parse(JSON.stringify(BubbleObj)).map(function (e) {
                return Object.keys(e).reduce(function (p, n) {
                    if (n.polyFillEndswith("Value", "0"))
                        p[n] = Math.round(e[n] * 100) / 100;
                    else
                        p[n] = e[n];
                    return p;
                }, {})
            });
</code>```

is the above code even correct? if not how can i change it to  achieve my objective?

答:
Given requirement you can use String.prototype.slice() with parameter -5

```<code>if (n.slice(-5) === "Value")
</code>```

or RegExp.prototype.test() with RegExp /Value$/

```<code>if (/Value$/.test(n))
</code>```

Body:
I am using string.endswith() to loop through JSON objects and find out if the any property of the object endswith a "Value" substring.

After finding out if the the object property ends with "Value", i am trying to round off the value of the property to 2 decimals which are by default 5 decimals.

Here is my code

var MyObj= [{"$id":"1","GeoName":"EAST","ReachValue":87.88221970554928,"ReachValue":90.71955219607294,"DepthValue":18.44377295716579,"ShareValue":16.732108234801206},{"$id":"2","GeoName":"WEST","ReachValue":87.88221970554928,"ReachValue":90.71955219607294,"DepthValue":18.44377295716579,"ShareValue":16.732108234801206}];
Obj = JSON.parse(JSON.stringify(MyObj)).map(function (e) {
            return Object.keys(e).reduce(function (p, n) {
                if (n.endsWith("Value"))
                    p[n] = Math.round(e[n] * 100) / 100;
                else
                    p[n] = e[n];
                return p;
            }, {})
        });

The above code works absolutely fine in chrome and Firefox, While IE it throws endsWith is not a function exception.

I found out for such issues pollyfills are used, which i tried and i failed. I am not even sure if i used the pollyfill correctly.

so here is how i did it,

function polyFillEndswith(searchString, position) {
            if (!String.prototype.endsWith) {
                String.prototype.endsWith = function (searchString, position) {
                    var subjectString = this.toString();
                    if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
                        position = subjectString.length;
                    }
                    position -= searchString.length;
                    var lastIndex = subjectString.lastIndexOf(searchString, position);
                    return lastIndex !== -1 && lastIndex === position;
                }
            }
        }

Obj = JSON.parse(JSON.stringify(BubbleObj)).map(function (e) {
                return Object.keys(e).reduce(function (p, n) {
                    if (n.polyFillEndswith("Value", "0"))
                        p[n] = Math.round(e[n] * 100) / 100;
                    else
                        p[n] = e[n];
                    return p;
                }, {})
            });

is the above code even correct? if not how can i change it to  achieve my objective?

Body:
Given requirement you can use String.prototype.slice() with parameter -5

if (n.slice(-5) === "Value")

or RegExp.prototype.test() with RegExp /Value$/

if (/Value$/.test(n))


问:
Syntax for ASP.Net MVC Phil Haack's Repeater syntax using Razor (MVC 3)?
I have recently started using ASP.Net MVC 3 RC 2 and have attempted to migrate an existing website in MVC 2 across using the Razor syntax.  In the MVC 2 application I am using the code base repeater that Phil Haack kindly provided in the following:
Phil Haack's Code Based Repeater

My question is around the syntax for Razor.  I dont understand how the template in the following block can be rewritten in Razor and cannot find any documentation to help out (early days for documentation or my simplicity...):

```<code><% Html.Repeater<ObjectToUse>(Model, "", "alt", (item, css) =>
   { %>
        <tr class="<%= item.Enabled ? css : "disabled" %>">
            <td><%= item.Name%></td>
            <td><%= item.Description%></td>
            <td><%= Html.RouteLink("Edit", item.ObjectToUseRouteValues("Edit"))%></td>
            <td></td>
            <td><%= Html.RouteLink("Select", item.ObjectToUseRouteValues())%></td>
        </tr>
<% }); %>
</code>```

The problem comes when applying the template between the braces (the tr's).  I have attempted using the WebGrid control, however it doesnt provide the functionality I require for setting a "disabled" row (I think).

答:
Actually, now that I think about it some more I don't think you can use Action parameters like that in Razor. I recall running into this before.

Updated

With answer from Andrew Nurse:
"Unfortunately this is by design in the current parser, though I should note that we'd like to improve upon it.  The issue is that markup is only valid at the start of a statement (which technically is where you've put it), but our C# "parser" is not intelligent enough to detect lambdas at the moment."

Though that might be out dated :)

```<code>@Html.Repeater(Model, "row", "row-alt",
    @<tr class="@item.ClassType : "disabled"">
        <td>@item.Name</td>
        <td>@item.Description</td>
        <td>@Html.RouteLink("Edit", item.ObjectToUseRouteValues("Edit"))</td>
        <td></td>
        <td>@Html.RouteLink("Select", item.ObjectToUseRouteValues())</td>
    </tr>
)

    public static IHtmlString Repeater<T>(this HtmlHelper html, IEnumerable<T> items,
         string className, string classNameAlt, Func<T, HelperResult> render) {
        if (items == null)
            return new HtmlString("");

        int i = 0;
        StringBuilder sb = new StringBuilder();
        foreach (var item in items) {
            item.ClassType = item.Enabled ? (i++ % 2 == 0 ? className : classNameAlt) : "disabled";
            sb.Append(render(item).ToHtmlString());
        }

        return new HtmlString(sb.ToString());
    }

}
</code>```

Body:
I have recently started using ASP.Net MVC 3 RC 2 and have attempted to migrate an existing website in MVC 2 across using the Razor syntax.  In the MVC 2 application I am using the code base repeater that Phil Haack kindly provided in the following:
Phil Haack's Code Based Repeater

My question is around the syntax for Razor.  I dont understand how the template in the following block can be rewritten in Razor and cannot find any documentation to help out (early days for documentation or my simplicity...):

<% Html.Repeater<ObjectToUse>(Model, "", "alt", (item, css) =>
   { %>
        <tr class="<%= item.Enabled ? css : "disabled" %>">
            <%= item.Name%>
            <%= item.Description%>
            <%= Html.RouteLink("Edit", item.ObjectToUseRouteValues("Edit"))%>

            <%= Html.RouteLink("Select", item.ObjectToUseRouteValues())%>

<% }); %>

The problem comes when applying the template between the braces (the tr's).  I have attempted using the WebGrid control, however it doesnt provide the functionality I require for setting a "disabled" row (I think).

Body:
Actually, now that I think about it some more I don't think you can use Action parameters like that in Razor. I recall running into this before.

Updated

With answer from Andrew Nurse:
"Unfortunately this is by design in the current parser, though I should note that we'd like to improve upon it.  The issue is that markup is only valid at the start of a statement (which technically is where you've put it), but our C# "parser" is not intelligent enough to detect lambdas at the moment."

Though that might be out dated :)

@Html.Repeater(Model, "row", "row-alt",
    @<tr class="@item.ClassType : "disabled"">
        <td>@item.Name</td>
        <td>@item.Description</td>
        <td>@Html.RouteLink("Edit", item.ObjectToUseRouteValues("Edit"))</td>
        <td></td>
        <td>@Html.RouteLink("Select", item.ObjectToUseRouteValues())</td>
    </tr>
)

    public static IHtmlString Repeater<T>(this HtmlHelper html, IEnumerable<T> items,
         string className, string classNameAlt, Func<T, HelperResult> render) {
        if (items == null)
            return new HtmlString("");

        int i = 0;
        StringBuilder sb = new StringBuilder();
        foreach (var item in items) {
            item.ClassType = item.Enabled ? (i++ % 2 == 0 ? className : classNameAlt) : "disabled";
            sb.Append(render(item).ToHtmlString());
        }

        return new HtmlString(sb.ToString());
    }

}


问:
First Come First set
I have a problem because I write a program in C # about the fcfs algorithm and I have a question how to import from a datagridview into an algorithm and then show on my datagridview2 here is my code:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Projekt
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }
        DataTable table = new DataTable();

        private void Form1_Load(object sender, EventArgs e)
        {
            table.Columns.Add("Process", typeof(int));
            table.Columns.Add("Arrival Time", typeof(string));
            table.Columns.Add("Burst Time", typeof(string));
            table.Columns.Add("Piority", typeof(int));

            table.Rows.Add("1");
            table.Rows.Add("2");
            table.Rows.Add("3");
            table.Rows.Add("4");

            dataGridView1.DataSource = table;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Random rand = new Random();
            dataGridView1[1, 0].Value = rand.Next(5, 30);
            dataGridView1[2, 0].Value = rand.Next(5, 30);
            dataGridView1[3, 0].Value = rand.Next(5, 30);
            dataGridView1[1, 1].Value = rand.Next(5, 30);
            dataGridView1[2, 1].Value = rand.Next(5, 30);
            dataGridView1[3, 1].Value = rand.Next(5, 30);
            dataGridView1[1, 2].Value = rand.Next(5, 30);
            dataGridView1[2, 2].Value = rand.Next(5, 30);
            dataGridView1[3, 2].Value = rand.Next(5, 30);
            dataGridView1[1, 3].Value = rand.Next(5, 30);
            dataGridView1[2, 3].Value = rand.Next(5, 30);
            dataGridView1[3, 3].Value = rand.Next(5, 30);
        }

        private void FCFS_Click(object sender, EventArgs e)
        {

        }
    }
}
</code>```

could you help me i this problem

答:
Try code below.  Columns 0 & 3 are int, while columns 1 & 2 arre strings.  You cannot put an int into a string column</p>

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Projekt
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }
        DataTable table = new DataTable();
        DataTable table2 = new DataTable();

        private void Form1_Load(object sender, EventArgs e)
        {
            table.Columns.Add("Process", typeof(int));
            table.Columns.Add("Arrival Time", typeof(string));
            table.Columns.Add("Burst Time", typeof(string));
            table.Columns.Add("Piority", typeof(int));

            table.Rows.Add("1");
            table.Rows.Add("2");
            table.Rows.Add("3");
            table.Rows.Add("4");

            dataGridView1.DataSource = table;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Random rand = new Random();
            table.Rows[0][0] = rand.Next(5, 30);
            table.Rows[1][0] = rand.Next(5, 30);
            table.Rows[2][0] = rand.Next(5, 30);
            table.Rows[3][0] = rand.Next(5, 30);
            table.Rows[0][3] = rand.Next(5, 30);
            table.Rows[1][3] = rand.Next(5, 30);
            table.Rows[2][3] = rand.Next(5, 30);
            table.Rows[3][3] = rand.Next(5, 30);

            dataGridView1 = null;  //to force update
            dataGridView1.DataSource = table;
        }

        private void FCFS_Click(object sender, EventArgs e)
        {
            table2 = table.Clone();
            dataGridView2.DataSource = table2;

        }
    }
}
</code>```

Title: First Come First set

Body:
I have a problem because I write a program in C # about the fcfs algorithm and I have a question how to import from a datagridview into an algorithm and then show on my datagridview2 here is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Projekt
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }
        DataTable table = new DataTable();

        private void Form1_Load(object sender, EventArgs e)
        {
            table.Columns.Add("Process", typeof(int));
            table.Columns.Add("Arrival Time", typeof(string));
            table.Columns.Add("Burst Time", typeof(string));
            table.Columns.Add("Piority", typeof(int));

            table.Rows.Add("1");
            table.Rows.Add("2");
            table.Rows.Add("3");
            table.Rows.Add("4");

            dataGridView1.DataSource = table;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Random rand = new Random();
            dataGridView1[1, 0].Value = rand.Next(5, 30);
            dataGridView1[2, 0].Value = rand.Next(5, 30);
            dataGridView1[3, 0].Value = rand.Next(5, 30);
            dataGridView1[1, 1].Value = rand.Next(5, 30);
            dataGridView1[2, 1].Value = rand.Next(5, 30);
            dataGridView1[3, 1].Value = rand.Next(5, 30);
            dataGridView1[1, 2].Value = rand.Next(5, 30);
            dataGridView1[2, 2].Value = rand.Next(5, 30);
            dataGridView1[3, 2].Value = rand.Next(5, 30);
            dataGridView1[1, 3].Value = rand.Next(5, 30);
            dataGridView1[2, 3].Value = rand.Next(5, 30);
            dataGridView1[3, 3].Value = rand.Next(5, 30);
        }

        private void FCFS_Click(object sender, EventArgs e)
        {

        }
    }
}

could you help me i this problem

Body:
Try code below.  Columns 0 & 3 are int, while columns 1 & 2 arre strings.  You cannot put an int into a string column

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Projekt
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }
        DataTable table = new DataTable();
        DataTable table2 = new DataTable();

        private void Form1_Load(object sender, EventArgs e)
        {
            table.Columns.Add("Process", typeof(int));
            table.Columns.Add("Arrival Time", typeof(string));
            table.Columns.Add("Burst Time", typeof(string));
            table.Columns.Add("Piority", typeof(int));

            table.Rows.Add("1");
            table.Rows.Add("2");
            table.Rows.Add("3");
            table.Rows.Add("4");

            dataGridView1.DataSource = table;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Random rand = new Random();
            table.Rows[0][0] = rand.Next(5, 30);
            table.Rows[1][0] = rand.Next(5, 30);
            table.Rows[2][0] = rand.Next(5, 30);
            table.Rows[3][0] = rand.Next(5, 30);
            table.Rows[0][3] = rand.Next(5, 30);
            table.Rows[1][3] = rand.Next(5, 30);
            table.Rows[2][3] = rand.Next(5, 30);
            table.Rows[3][3] = rand.Next(5, 30);

            dataGridView1 = null;  //to force update
            dataGridView1.DataSource = table;
        }

        private void FCFS_Click(object sender, EventArgs e)
        {
            table2 = table.Clone();
            dataGridView2.DataSource = table2;

        }
    }
}


问:
Use common edit/delete buttons in index page
I know how to create an index list of items and show an Edit / Delete / etc buttons for each row. I Have been searching for days for a way to use a single Edit / Delete / etc button for all rows.

Let me explain. I want to have a series of buttons on the right of my index page that would show my Edit, Delete. etc, buttons. I would then use a checkbox located a the front of each row to select the record I wish to edit/delete, etc. and pass this checked value to the button and to the controller.

Not sure if this makes sense.
index page

I want to eliminate the Duplicate, Edit and Delete buttons for each row and use the ones on the right.

Any help would be appreciated.
Thanks

答:
To achieve this, i would recomend using JQUERY to send ajax posts.
This has the looks of something I would do.</p>

```<code>function deleteData() {
var id_delete = $('input[name="yourRadioButton"]:checked').val();
$.ajax({
    url: "{{route('routeUrlHere')}}",
    type: 'POST',
    dataType: 'JSON',
    data: {
        _token : "{{Session::token()}}",
        id_delete: id_delete
    }
})
.success(function (response) {
    console.log(response);
    // Continue Jquery here

})
.error(function (xhr, status, response) {
    console.log(xhr.responseText);
});

}
</code>```

Body:
To achieve this, i would recomend using JQUERY to send ajax posts.
This has the looks of something I would do.

function deleteData() {
var id_delete = $('input[name="yourRadioButton"]:checked').val();
$.ajax({
    url: "{{route('routeUrlHere')}}",
    type: 'POST',
    dataType: 'JSON',
    data: {
        _token : "{{Session::token()}}",
        id_delete: id_delete
    }
})
.success(function (response) {
    console.log(response);
    // Continue Jquery here

})
.error(function (xhr, status, response) {
    console.log(xhr.responseText);
});

}


问:
Attempting to append a value to a dictionary
Trying to append a value to a dictionary

```<code>public typealias Parameters = [String: Any]

   var parameters: Parameters = [
        "username" : username,
        "first_name" : firstName,
        "last_name" : lastName,
        "profession" : profession
    ]
    if let imageURl = imageUrl {
        parameters[4] = ["image_url" : imageUrl]
    }
</code>```

I get back ambiguous reference to member 'subscript' at line parameters[4] = ["image_url" : imageUrl]

How can I solve this?

答:
You should access parameters dictionary by its String key, i.e. "image_url", not by its index 4:

```<code>if let imageURl = imageUrl {
    parameters["image_url"] = imageUrl
}
</code>```

Body:
Trying to append a value to a dictionary

public typealias Parameters = [String: Any]

   var parameters: Parameters = [
        "username" : username,
        "first_name" : firstName,
        "last_name" : lastName,
        "profession" : profession
    ]
    if let imageURl = imageUrl {
        parameters[4] = ["image_url" : imageUrl]
    }

I get back ambiguous reference to member 'subscript' at line parameters[4] = ["image_url" : imageUrl]

How can I solve this?

Body:
You should access parameters dictionary by its String key, i.e. "image_url", not by its index 4:

if let imageURl = imageUrl {
    parameters["image_url"] = imageUrl
}


问:
In IntelliJ, is it possible to find usages of a typed method with a specific type?
Say I have a typed method:

public interface Foo {

    public <T> T bar();
}
```

<p>In Intellij, can I search for the method usages only with a specific type? Say, only with <code>String</code>?</p>

<pre class="lang-java prettyprint-override"><code>foo.<String>bar(); // will be listed in the search result

foo.<Integer>bar(); // won't
</code>```

答:
This is possible, but it requires a little bit of work. Use Edit > Find > Search Structurally and type a search pattern like the following:

```<code>$a$.<String>bar()
</code>```

Click Edit Variables in the Structural Search dialog, put Foo in the Expression type (regexp) text field and enable Apply constraint within type hierarchy. Click OK and then Find and all calls with <String> will be found, even where the type parameter is implicit, for example:

String s = foo.bar();

Body:
Say I have a typed method:

public interface Foo {

    public <T> T bar();
}

In Intellij, can I search for the method usages only with a specific type? Say, only with String?

foo.<String>bar(); // will be listed in the search result

foo.<Integer>bar(); // won't

Body:
This is possible, but it requires a little bit of work. Use Edit > Find > Search Structurally and type a search pattern like the following:

$a$.<String>bar()

Click Edit Variables in the Structural Search dialog, put Foo in the Expression type (regexp) text field and enable Apply constraint within type hierarchy. Click OK and then Find and all calls with <String> will be found, even where the type parameter is implicit, for example:

String s = foo.bar();


问:
How to remove "GivenStory Scenarios" section from Jbehave report
Jbehave displayes "GivenStory Scenarios" section in Jbehave report, which i dnt need in Jbehave report.

How to remove "GivenStory Scenarios" from Jbehave Report.

Please see attched image. Sample Report

答:
Your problem might be that you're not at version 4.1.

One of the listed improvements on this page mentions that it no longer processes GivenStories if the the story-level has scenarios.  I'm not sure if this affects the report, but I would think it does.


问:
Catching Cascading Errors in PowerShell
I'm working with a wrapper script that calls a function which queries some databases inside specified servers and inserts metadata to a specific database on a separate server. I use the $error.count variable to determine if the script was successful or not. I anticipate some permission/extraction errors to happen and want these to be caught and ignored (no increase in the $error.count variable but having a warning written in the job log). I can confirm one permission error is happening and is being properly caught. The $error.count variable is not increased but a warning is printed from the catch showing the database that could not be accessed.

My problem occurs after the extraction/insertion function is finished running. Immediately after this function returns to the wrapper script, I have the $error.count variable print again. This time, it returns a 1 as if the error previously caught cascades into the wrapper script. As I mentioned previously, I do not want this to be included in the error count. I'm not sure how or why the $error.count is increased from this function.

Should I use a different variable to determine if the script "failed" or not? Is there some underlying reason why the $error.count would increase outside of the function that has the error while not increasing after the error is caught? Any guidance on this issue would be appreciated.

Code for reference:
Wrapper function:

```<code>$errorCount = $error.count
    Write-Warning ("$errorCount Before function")
    Extraction/Insertion_Function -serverList $serverList -insertionDB $insertionDB -ErrorAction SilentlyContinue
    $errorCount = $error.count
    Write-Warning ("$errorCount After function")
    } catch {
    Write-Error "Error caught by wrapper: $_"
    }
</code>```

Extraction/Insertion_Function:

```<code>ForEach ($db in $dbList) {
Write-Warning "$errorCount database
.
.
.
    try {
            $totalProperties = Get-ServerDBMetadata -DBConnectionString ($connStr) -DatabaseName $dbName -EA SilentlyContinue
            } catch {
                Write-Warning "Unable to extract metadata from $dbname in $server"
                }
}
</code>```

I then have the error count printing out inside the loop that extracts/inserts the metadata from each database to the insertion database, as well as in the loop for each server that contains the databases:

```<code>WARNING: 0 Before function
WARNING: 0 database
.
.
.
WARNING: 0 database
WARNING: Unable to extract metadata from *database* in *server*
WARNING: 0 database
.
.
.
WARNING: 0 database
**WARNING: 1 After function**
</code>```

The error (permission issue) is caught inside the function but cascades to my wrapper script. I want this particular error to be ignored while NOT ignoring other, more serious errors (like being unable to connect to the server I'm inserting the metadata into) so placing -EA Ignore on the driver function inside the wrapper script is out of the question.

答:
Replace SilentlyContinue with Ignore to ignore the error and not have it increase the count.

```<code>Extraction/Insertion_Function -serverList $serverList -insertionDB $insertionDB -ErrorAction Ignore
</code>```

To catch it inside the function, use -ErrorAction Stop as in thepip3r's answer as try/catch statements only catch terminating errors.

Title: Catching Cascading Errors in PowerShell

Body:
I'm working with a wrapper script that calls a function which queries some databases inside specified servers and inserts metadata to a specific database on a separate server. I use the $error.count variable to determine if the script was successful or not. I anticipate some permission/extraction errors to happen and want these to be caught and ignored (no increase in the $error.count variable but having a warning written in the job log). I can confirm one permission error is happening and is being properly caught. The $error.count variable is not increased but a warning is printed from the catch showing the database that could not be accessed.

My problem occurs after the extraction/insertion function is finished running. Immediately after this function returns to the wrapper script, I have the $error.count variable print again. This time, it returns a 1 as if the error previously caught cascades into the wrapper script. As I mentioned previously, I do not want this to be included in the error count. I'm not sure how or why the $error.count is increased from this function.

Should I use a different variable to determine if the script "failed" or not? Is there some underlying reason why the $error.count would increase outside of the function that has the error while not increasing after the error is caught? Any guidance on this issue would be appreciated.

Code for reference:
Wrapper function:

$errorCount = $error.count
    Write-Warning ("$errorCount Before function")
    Extraction/Insertion_Function -serverList $serverList -insertionDB $insertionDB -ErrorAction SilentlyContinue
    $errorCount = $error.count
    Write-Warning ("$errorCount After function")
    } catch {
    Write-Error "Error caught by wrapper: $_"
    }

Extraction/Insertion_Function:

ForEach ($db in $dbList) {
Write-Warning "$errorCount database
.
.
.
    try {
            $totalProperties = Get-ServerDBMetadata -DBConnectionString ($connStr) -DatabaseName $dbName -EA SilentlyContinue
            } catch {
                Write-Warning "Unable to extract metadata from $dbname in $server"
                }
}

I then have the error count printing out inside the loop that extracts/inserts the metadata from each database to the insertion database, as well as in the loop for each server that contains the databases:

WARNING: 0 Before function
WARNING: 0 database
.
.
.
WARNING: 0 database
WARNING: Unable to extract metadata from *database* in *server*
WARNING: 0 database
.
.
.
WARNING: 0 database
**WARNING: 1 After function**

The error (permission issue) is caught inside the function but cascades to my wrapper script. I want this particular error to be ignored while NOT ignoring other, more serious errors (like being unable to connect to the server I'm inserting the metadata into) so placing -EA Ignore on the driver function inside the wrapper script is out of the question.

Body:
Replace SilentlyContinue with Ignore to ignore the error and not have it increase the count.

Extraction/Insertion_Function -serverList $serverList -insertionDB $insertionDB -ErrorAction Ignore

To catch it inside the function, use -ErrorAction Stop as in thepip3r's answer as try/catch statements only catch terminating errors.


问:
pandas groupby function will not sum >8 columns
I have a pandas dataframe that contains 13 text columns and 16 numeric columns (29 columns in total, around 13k rows).  I would like to aggregate the data by the first 13 columns and return the sum of the results for the 16 numeric columns.  I have tried the following:

```<code>df.groupby(1,2,3,4,5,6,7,8,9,10,11,12,13)[14,15,26,17,18,19,20,21,22,23,24,25,26,27,28,29].sum()
</code>```

but this returns an error "groupby() takes from 1 to 8 positional arguments but 14 were given"

I am essentially trying to do the following as it would be in SQL syntax:

```<code>select 1,2,3,4,5,6,7,8,9,10,11,12,13,sum(14),sum(15),sum(16),sum(17),sum(18),sum(19),sum(20),sum(21),sum(22),sum(23),sum(24),sum(25),sum(26),sum(27),sum(28),sum(29)
from df group by 1,2,3,4,5,6,7,8,9,10,11,12,13
</code>```

I'd also like the process done in place so I end up with a dataframe the same shape as the old one (with fewer rows, obviously!)

any help appreciated, thanks!

答:
A slightly more general approach that uses .select_dtypes(docs) to isolate numeric columns:

```<code>import pandas as pd
import numpy as np

numerical_columns = df.select_dtypes(include=[np.number]).columns.tolist()
other_columns = df.select_dtypes(exclude=[np.number]).columns.tolist()

df.groupby(other_columns)[numerical_columns].sum()
</code>```

As for why your code is not working, it is because you need to pass a list of column names to groupby.

Body:
I have a pandas dataframe that contains 13 text columns and 16 numeric columns (29 columns in total, around 13k rows).  I would like to aggregate the data by the first 13 columns and return the sum of the results for the 16 numeric columns.  I have tried the following:

df.groupby(1,2,3,4,5,6,7,8,9,10,11,12,13)[14,15,26,17,18,19,20,21,22,23,24,25,26,27,28,29].sum()

but this returns an error "groupby() takes from 1 to 8 positional arguments but 14 were given"

I am essentially trying to do the following as it would be in SQL syntax:

select 1,2,3,4,5,6,7,8,9,10,11,12,13,sum(14),sum(15),sum(16),sum(17),sum(18),sum(19),sum(20),sum(21),sum(22),sum(23),sum(24),sum(25),sum(26),sum(27),sum(28),sum(29)
from df group by 1,2,3,4,5,6,7,8,9,10,11,12,13

I'd also like the process done in place so I end up with a dataframe the same shape as the old one (with fewer rows, obviously!)

any help appreciated, thanks!

Body:
A slightly more general approach that uses .select_dtypes(docs) to isolate numeric columns:

import pandas as pd
import numpy as np

numerical_columns = df.select_dtypes(include=[np.number]).columns.tolist()
other_columns = df.select_dtypes(exclude=[np.number]).columns.tolist()

df.groupby(other_columns)[numerical_columns].sum()

As for why your code is not working, it is because you need to pass a list of column names to groupby.


问:
Unknown plugin specified in .babelrc, attempted to resolve relative to path
So I've started a new react-native project and copied over the .babelrc file from my previous project.  I've installed the necessary plugins but I'm getting the error

Unknown plugin transform-decorators-legacy specified in .babelrc, attempted to resolve relative to "/mypath/project"

I've checked the node_modules in the path and see that the plugin was installed using yarn add.  I'm also getting similar errors with my eslint plugins.  Am I missing something in my project setup to have babel and eslint see the node_modules?

Is it perhaps caused by installing react-native-code-push?  I think it had some errors when I installed codepush where it duplicated the react pod in the pod install - and so I removed it from the podfile.  Is it trying to use a cached code-push js even though I don't have code push implemented in my react js files?

答:
try this :</p>

```<code>yarn add babel-plugin-transform-decorators-legacy -g
</code>```

Body:
try this :

yarn add babel-plugin-transform-decorators-legacy -g


问:
Delete a git commit pushed on a remote branch
We use git and GitFlow as versioning tools, and I'm facing a problem that I am quite sure some people have already encountered.

In a feature branch, a colleague did a commit in which a lot of useless files were inserted (all binary and IDE metadata files). This commit was pushed. Now this colleague submits a pull request, and I don't want to integrate all these useless files into develop.

Now, my git repository is quite huge, and a git clone becomes a long and boring process...

The first (and easy) solution is to remove these files from the feature branch, and commit without these files (or do a revert commit). But if I do that, my git repository will remain quite big because objects (files) will not be removed from the history (because git still knows about them!).

What I would like is to "cancel" this commit.

The following picture shows my problem (the topmost commit is the oldest):

How can I remove this commit and make my git clone quick again ?

PS: Thanks to GitGraphJS for their useful tools to draw git graphs!

答:
There are several methods to delete or undo the commit. In that case, you can use git revert or git rebase or git reset.

One information, git rebase don't add one extra commit compared to using git revert. git revert adds one extra commit during the merge. If you're not familiar with using git rebase, I suggest you use git revert then.

Revert

```<code>git revert <commit-ID>
</code>```

after that you commit the changes and push that commit to your origin.

Reset

You can delete the last pushed commit, after doing this you have to push your branch. You can decide either to merge or rebase the feature branch to development branch.

```<code>git reset –-hard HEAD~1
</code>```

or

```<code>git reset HEAD^ --hard
</code>```

Rebase

This command will lead to interactive section of editor, from there you can pick

```<code> git rebase -i HEAD~
</code>```

In the interactive section, it lists all the commits. Delete the one you want to get rid off. Finish the rebase and push force to the repo.

git rebase --continue then push your branch.

Body:
There are several methods to delete or undo the commit. In that case, you can use git revert or git rebase or git reset.

One information, git rebase don't add one extra commit compared to using git revert. git revert adds one extra commit during the merge. If you're not familiar with using git rebase, I suggest you use git revert then.

Revert

git revert <commit-ID>

after that you commit the changes and push that commit to your origin.

Reset

You can delete the last pushed commit, after doing this you have to push your branch. You can decide either to merge or rebase the feature branch to development branch.

git reset –-hard HEAD~1

or

git reset HEAD^ --hard

Rebase

This command will lead to interactive section of editor, from there you can pick

 git rebase -i HEAD~

In the interactive section, it lists all the commits. Delete the one you want to get rid off. Finish the rebase and push force to the repo.

git rebase --continue then push your branch.


问:
Pandas: Drop duplicates, with a constraint in another column
```<code>  Title URL Price Address Rental_Type
0 House URL $600  Auburn  Apartment
1 House URL $600  Auburn  Apartment
2 House URL $900  NY      Apartment
3 Room! URL $1018 NaN     Office
4 Room! URL $910  NaN     Office
</code>```

I'm trying to drop duplicates under Title. But I only want to drop rows that have Rental_Type == 'Office'. I also have a second constraint. I would like to drop the rows with Rental_Type == 'Apartment', but I want to keep the first duplicate in this scenario. So in this situation row 3 and 4 would drop, and then only row 1 out of row 0/1.

答:
I would build this up in steps to construct a list of incidences you wish to drop.</p>

```<code>offices = df['Rental_Type'] == 'Office'
apts = df['Rental_Type'] == 'Apartment'

dup_offices = df[offices].duplicated('Title', keep=False)
dup_apts = df[apts].duplicated('Title', keep='first')

to_drop = pd.Index(dup_apts[dup_apts].index.tolist() + \
                   dup_offices[dup_offices].index.tolist())

df = df.drop(to_drop)
</code>```

Body:
  Title URL Price Address Rental_Type
0 House URL $600  Auburn  Apartment
1 House URL $600  Auburn  Apartment
2 House URL $900  NY      Apartment
3 Room! URL $1018 NaN     Office
4 Room! URL $910  NaN     Office

I'm trying to drop duplicates under Title. But I only want to drop rows that have Rental_Type == 'Office'. I also have a second constraint. I would like to drop the rows with Rental_Type == 'Apartment', but I want to keep the first duplicate in this scenario. So in this situation row 3 and 4 would drop, and then only row 1 out of row 0/1.

Body:
I would build this up in steps to construct a list of incidences you wish to drop.

offices = df['Rental_Type'] == 'Office'
apts = df['Rental_Type'] == 'Apartment'

dup_offices = df[offices].duplicated('Title', keep=False)
dup_apts = df[apts].duplicated('Title', keep='first')

to_drop = pd.Index(dup_apts[dup_apts].index.tolist() + \
                   dup_offices[dup_offices].index.tolist())

df = df.drop(to_drop)


问:
C# DAL returing generic List<T>
Could I return List  from my DAL ?, In internet I read somewhere that it's not good.
What is the problem if return List ?</p>

答:
You can return a List<T> object, but the property should be typed IList<T> instead.  This will allow you to change the list implementation that you use at a later time, without breaking binary compatibility with existing assemblies compiled against your library.

This example probably won't match your constructor pattern, but it demonstrates what I mean (returning a List<T> through an IList<T> property):

```<code>public class Foo
{
    public IList<string> AListOfStrings { get; private set; }

    public Foo()
    {
        AListOfStrings = new List<string>();
    }
}
</code>```

Title: C# DAL returing generic List<T>

Body:
You can return a List<T> object, but the property should be typed IList<T> instead.  This will allow you to change the list implementation that you use at a later time, without breaking binary compatibility with existing assemblies compiled against your library.

This example probably won't match your constructor pattern, but it demonstrates what I mean (returning a List<T> through an IList<T> property):

public class Foo
{
    public IList<string> AListOfStrings { get; private set; }

    public Foo()
    {
        AListOfStrings = new List<string>();
    }
}


问:
is the kaa application modularity？
Kaa demo show lots of example of application&client,but actually in the fact solution, may need some of function together,
so,question is:
one client (e.g. android app) access the multiple function (e.g. 2 function:event and notifications)in the server,so:

i need put all function in one application,or

create 2 applications,android app access the different function separate?

答:
You can use some of the SDK API (functions) or all at the same time (within single client application). The Kaa Sample Applications were made with an intent to be as simple (thus clear and easy to understand) as possible. Therefore, just for simplicity most of the samples use just one Kaa feature. This does not mean that they cannot be used in a single application at the same time.

Please feel free putting them all into a single application.

Title: is the kaa application modularity？