问:
Concatenating values from SQL select statement
I am doing a basic SQL select from an oracle database.

```<code>select DISTINCT spriden_pidm, a.saracmt_comment_text, spriden_id, c.saracmt_comment_text, '2017' as "YEAR", szrspdc_prog_code
from spriden, sarappd, saradap, stvapdc, saracmt a, saracmt c, szrspdc
where blah blah blah
</code>```

The following three fields are used as a key in another system I am doing an import into so I need to get the following into one field: c.saracmt_comment_text, '2017' as "YEAR", szrspdc_prog_code.

Thanks in advance for your help.

答:
The string concatenation operator in Oracle is ||. So, you need to use the following query:

```<code>select DISTINCT
c.saracmt_comment_text || '2017' || szrspdc_prog_code as key_field
spriden_pidm, a.saracmt_comment_text, spriden_id,
c.saracmt_comment_text, '2017' as "YEAR", szrspdc_prog_code
from spriden, sarappd, saradap, stvapdc, saracmt a, saracmt c, szrspdc
where blah blah blah
</code>```

Body:
I am doing a basic SQL select from an oracle database.

select DISTINCT spriden_pidm, a.saracmt_comment_text, spriden_id, c.saracmt_comment_text, '2017' as "YEAR", szrspdc_prog_code
from spriden, sarappd, saradap, stvapdc, saracmt a, saracmt c, szrspdc
where blah blah blah

The following three fields are used as a key in another system I am doing an import into so I need to get the following into one field: c.saracmt_comment_text, '2017' as "YEAR", szrspdc_prog_code.

Thanks in advance for your help.

Body:
The string concatenation operator in Oracle is ||. So, you need to use the following query:

select DISTINCT
c.saracmt_comment_text || '2017' || szrspdc_prog_code as key_field
spriden_pidm, a.saracmt_comment_text, spriden_id,
c.saracmt_comment_text, '2017' as "YEAR", szrspdc_prog_code
from spriden, sarappd, saradap, stvapdc, saracmt a, saracmt c, szrspdc
where blah blah blah


来源: stackexchange

问:
Finding n tuples from a list whose aggregation satisfies a condition
I have a list of two-element vectors. From this list, I'd like to find n vectors (not necessarily distinct) (x,y), such that the sum of the ys of these vectors is larger or equal to a number k. If multiple vectors satisfy this condition, select the one where the sum of the xs is the smallest.

For example, I'd like to find n=2 vectors (x1,y1) and (x2,y2) such that y1+y2 >= k. If there are more than just one which satisfies this condition, select the one where x1+x2 is the smallest.

I've so far only managed to set-up the following code:

```<code>X <- c(3, 2, 3, 8, 7, 7, 13, 11, 12, 12)
Y <- c(2, 1, 3, 6, 5, 6, 8, 9, 10, 9)

df <- data.frame(A, B)
l <- list()
for (i in seq(1:nrow(df))){
  n <- as.numeric(df[i,])
  l[[i]] <- n
}
</code>```

Using the values above, let's say n=1, k=9, then I'll pick the tuple (x,y)=(11,9) because even though (12,9) also matches the condition that y=k, the x is smaller.

If n=2, k=6, then I'll pick (x1,y1)=(3,3) and (x2,y2)=(3,3) because it's the smallest x1+x2 that satisfies y1+y2 >= 6.

If n=2, k=8, then I'll pick (x1,y1)=(3,3) and (x2,y2)=(7,5) because y1+y2>=8 and in the next alternative tuples (3,3) and (8,6), 3+8=11 is larger than 3+7.

I feel like a brute-force solution would be possible: all possible n-sized combinations of each vector with the rest, for each permutation calculate yTotal=y1+y2+y3... find all yTotal combinations that satisfy yTotal>=k and of those, pick the one where xTotal=x1+x2+x3... is minimal.

I definitely struggle putting this into R-code and wonder if it's even the right choice. Thank you for your help!

答:
First, it seems from your question that you allow to select from Y with replacement. The code basically does your brute-force approach: use the permutations in the gtools library to generate the permutations. Then basically do the filtering for sum(Y)>=k, and ordering first by smallest sum(Y) and then sum(X).

```<code>X <- c(3, 2, 3, 8, 7, 7, 13, 11, 12, 12)
Y <- c(2, 1, 3, 6, 5, 6, 8, 9, 10, 9)
n<-1
perm<-gtools::permutations(n=length(Y),r=n, repeats.allowed=T)
result<-apply(perm,1,function(x){ c(sum(Y[x]),sum(X[x])) })
dim(result) # 2 10

k=9 ## Case of n=1, k=9
keep<-which(result[1,]>=k)
result[,keep[order(result[1,keep],result[2,keep])[1]]] # 9 and 11

##### n=2 cases ##########
n<-2
perm<-gtools::permutations(n=length(Y),r=n, repeats.allowed=T)
result<-apply(perm,1,function(x){ c(sum(Y[x]),sum(X[x])) })
dim(result) # 2 100

## n=2, k=6
keep<-which(result[1,]>=6)
        keep[order(result[1,keep],result[2,keep])[1]]  # the 23 permutation
perm[23,]                                              # 3 3 is (Y1,Y2)
result[,keep[order(result[1,keep],result[2,keep])[1]]] # sum(Y)=6 and sum(X)=6

## n=2, k=8
keep<-which(result[1,]>=8)
        keep[order(result[1,keep],result[2,keep])[1]]  # the 6 permutation
perm[6,]                                               # 1 6 is (Y1,Y2)
result[,keep[order(result[1,keep],result[2,keep])[1]]] # sum(Y)=8 and sum(X)=10
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a list of two-element vectors. From this list, I'd like to find n vectors (not necessarily distinct) (x,y), such that the sum of the ys of these vectors is larger or equal to a number k. If multiple vectors satisfy this condition, select the one where the sum of the xs is the smallest.

For example, I'd like to find n=2 vectors (x1,y1) and (x2,y2) such that y1+y2 >= k. If there are more than just one which satisfies this condition, select the one where x1+x2 is the smallest.

I've so far only managed to set-up the following code:

X <- c(3, 2, 3, 8, 7, 7, 13, 11, 12, 12)
Y <- c(2, 1, 3, 6, 5, 6, 8, 9, 10, 9)

df <- data.frame(A, B)
l <- list()
for (i in seq(1:nrow(df))){
  n <- as.numeric(df[i,])
  l[[i]] <- n
}

Using the values above, let's say n=1, k=9, then I'll pick the tuple (x,y)=(11,9) because even though (12,9) also matches the condition that y=k, the x is smaller.

If n=2, k=6, then I'll pick (x1,y1)=(3,3) and (x2,y2)=(3,3) because it's the smallest x1+x2 that satisfies y1+y2 >= 6.

If n=2, k=8, then I'll pick (x1,y1)=(3,3) and (x2,y2)=(7,5) because y1+y2>=8 and in the next alternative tuples (3,3) and (8,6), 3+8=11 is larger than 3+7.

I feel like a brute-force solution would be possible: all possible n-sized combinations of each vector with the rest, for each permutation calculate yTotal=y1+y2+y3... find all yTotal combinations that satisfy yTotal>=k and of those, pick the one where xTotal=x1+x2+x3... is minimal.

I definitely struggle putting this into R-code and wonder if it's even the right choice. Thank you for your help!

Body:
First, it seems from your question that you allow to select from Y with replacement. The code basically does your brute-force approach: use the permutations in the gtools library to generate the permutations. Then basically do the filtering for sum(Y)>=k, and ordering first by smallest sum(Y) and then sum(X).

X <- c(3, 2, 3, 8, 7, 7, 13, 11, 12, 12)
Y <- c(2, 1, 3, 6, 5, 6, 8, 9, 10, 9)
n<-1
perm<-gtools::permutations(n=length(Y),r=n, repeats.allowed=T)
result<-apply(perm,1,function(x){ c(sum(Y[x]),sum(X[x])) })
dim(result) # 2 10

k=9 ## Case of n=1, k=9
keep<-which(result[1,]>=k)
result[,keep[order(result[1,keep],result[2,keep])[1]]] # 9 and 11

##### n=2 cases ##########
n<-2
perm<-gtools::permutations(n=length(Y),r=n, repeats.allowed=T)
result<-apply(perm,1,function(x){ c(sum(Y[x]),sum(X[x])) })
dim(result) # 2 100

## n=2, k=6
keep<-which(result[1,]>=6)
        keep[order(result[1,keep],result[2,keep])[1]]  # the 23 permutation
perm[23,]                                              # 3 3 is (Y1,Y2)
result[,keep[order(result[1,keep],result[2,keep])[1]]] # sum(Y)=6 and sum(X)=6

## n=2, k=8
keep<-which(result[1,]>=8)
        keep[order(result[1,keep],result[2,keep])[1]]  # the 6 permutation
perm[6,]                                               # 1 6 is (Y1,Y2)
result[,keep[order(result[1,keep],result[2,keep])[1]]] # sum(Y)=8 and sum(X)=10


问:
d3 v4: Stacked histogram with some series below x axis?
Say I have some data (e.g. book loans and book returns). I want to plot this in a histogram, but I also want it to be 'stacked' in that book loans should be positive (above the x axis) while book returns should be negative (below the x axis). I've not been able to find any documentation on this, and the closest example is this one, but it uses the old v3 of d3 (which has changed a LOT regarding the stack api), and it also doesn't have negative stacks. The key thing here is that originally the book return data point isn't negative (in fact, it can't be, since the histogram api generates the bins), so I can't simply force that one series to appear below the axis in that way.

edit: after struggling with histograms + bins for a while, I finally got an example going at this pen. In my case, I'd like for the 'FixedRemaining' series to appear below the axis while the 'Remaining' series stays above. The data is pretty simple, and the code for drawing the rects is taken mostly from this example. In particular, I suspect this line would have to change:

```<code>  .attr("y", function(d) { return y(d[1]); })
</code>```

since it currently just sets the height to be above the axis. I know the domain would also have to be modified to take into account the below-axis part.

答: Answered by mbostock in this block here: https://bl.ocks.org/mbostock/b5935342c6d21928111928401e2c8608</p>

Body:
Say I have some data (e.g. book loans and book returns). I want to plot this in a histogram, but I also want it to be 'stacked' in that book loans should be positive (above the x axis) while book returns should be negative (below the x axis). I've not been able to find any documentation on this, and the closest example is this one, but it uses the old v3 of d3 (which has changed a LOT regarding the stack api), and it also doesn't have negative stacks. The key thing here is that originally the book return data point isn't negative (in fact, it can't be, since the histogram api generates the bins), so I can't simply force that one series to appear below the axis in that way.

edit: after struggling with histograms + bins for a while, I finally got an example going at this pen. In my case, I'd like for the 'FixedRemaining' series to appear below the axis while the 'Remaining' series stays above. The data is pretty simple, and the code for drawing the rects is taken mostly from this example. In particular, I suspect this line would have to change:

  .attr("y", function(d) { return y(d[1]); })

since it currently just sets the height to be above the axis. I know the domain would also have to be modified to take into account the below-axis part.


问:
Use CSS Framework in every Vue Component with own variables
I'm fairly new to the world of VueJS and Webpack so I need some help.

I've installed VueJS and Webpack via the console with the command

```<code>vue init webpack my-project
</code>```

and after this I've installed the bulma CSS Framework in this directory. with

```<code>npm install bulma
</code>```

I've override some bulma variables in a variables.scss. If I import both files in the style section of my App.vue everything works fine.

My App.vue looks like this:

```<code><template>
  <div id="app">
    <top-navigation/>
    <div class="has-text-centered">
      <img src="./assets/logo.png">
      <p>Test</p>
      <router-view></router-view>
    </div>

  </div>
</template>

<script>
  import TopNavigation from './components/shared/TopNavigation.vue'

  export default {
    name: 'app',
    components: {
      'top-navigation': TopNavigation
    }
  }
</script>

<style lang="scss">
  @import 'assets/scss/_variables.scss';
  @import '~bulma';

</style>
</code>```

My TopNavigation.vue looks like this:

```<code><template>
  <div>
    <div class="blue-bg">
      <div class="container">
        <h2 class="title">Test</h2>
      </div>
    </div>
  </div>
</template>

<script>

  export default {
    data () {
      return {
        msg: 'hello vue'
      }
    }
  }
</script>

<style lang="scss">
  .blue-bg {
    height: 80px;
    background-color: $blue;
  }
</style>
</code>```

But I get an error:

error  in ./src/components/shared/TopNavigation.vue

Module build failed:
      background-color: $blue;

        Undefined variable: "$blue".

I've searched a while and tried to import the files directly in my webpack utils.js file like this:

```<code>scss: generateLoaders(['css', 'sass?data=@import "./src/assets/scss/_variables.scss";@import "~bulma";']),
</code>```

Now I don't get an error and in my TopNavigation is using the right blue color. But now the bulma-variable don't get override.

I hope you guys understand my problem and someone can help me with this.

答:
I don't think you can use scss, since bulma uses sass. Just change your TopNavigation.vue style to:

```<code><style lang="sass" scoped>
  @import '~bulma/sass/utilities/variables.sass'
  .blue-bg
    height: 80px;
    background-color: $blue;
</style>
</code>```

And I think this should do the trick.

Body:
I'm fairly new to the world of VueJS and Webpack so I need some help.

I've installed VueJS and Webpack via the console with the command

vue init webpack my-project

and after this I've installed the bulma CSS Framework in this directory. with

npm install bulma

I've override some bulma variables in a variables.scss. If I import both files in the style section of my App.vue everything works fine.

My App.vue looks like this:

<template>

    <top-navigation/>

Test

      <router-view></router-view>

</template>

My TopNavigation.vue looks like this:

<template>

Test

</template>

But I get an error:

error  in ./src/components/shared/TopNavigation.vue

Module build failed:
      background-color: $blue;

        Undefined variable: "$blue".

I've searched a while and tried to import the files directly in my webpack utils.js file like this:

scss: generateLoaders(['css', 'sass?data=@import "./src/assets/scss/_variables.scss";@import "~bulma";']),

Now I don't get an error and in my TopNavigation is using the right blue color. But now the bulma-variable don't get override.

I hope you guys understand my problem and someone can help me with this.

Body:
I don't think you can use scss, since bulma uses sass. Just change your TopNavigation.vue style to:

<style lang="sass" scoped>
  @import '~bulma/sass/utilities/variables.sass'
  .blue-bg
    height: 80px;
    background-color: $blue;
</style>

And I think this should do the trick.


问:
Vertical position of div element
I have this so far: [![enter image description here][1]][1]

https://iamsteve.me/uploads/blog/inline-block-example.png

Problem here is that I don't know how to change vertical postion of this div elements. I'm allowed to use CSS1 and CSS2 for old browsers.

HTML

```<code><div id="graph">
    <div style="height: 100px;" class="row"></div>
    <div style="height: 200px;" class="row"></div>
    <div style="height: 100px;" class="row"></div>
    <div style="height: 250px;" class="row"></div>
    <div style="height: 300px;" class="row"></div>

    <div id="legend">
      <div class="text">10</div>
      <div class="text">20</div>
      <div class="text">30</div>
      <div class="text">40</div>
      <div class="text">50</div>
    </div>
  </div>
</code>```

CSS

```<code>.text {
    background-color: gray;
    width: 18%;
    float: left;
    margin: 1%;
    text-align: center;
}

.row {
    background-color: gray;
    width: 18%;
    float: left;
    margin: 1%;
}
</code>```

答:
I like to use: display: inline-block instead of floating the elements.

Note that I set font-size: 0 in #graph to eliminate the spacing between inline-block as seen here.

#graph{
  font-size: 0;
}
.text {
  background-color: gray;
  width: 18%;
  float: left;
  margin: 1%;
  text-align: center;
  font-size: 10px;
}

.row {
  position: relative;
  bottom: 0;
  display: inline-block;
  background-color: gray;
  width: 18%;
  margin: 1%;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="graph">
  <div style="height: 100px;" class="row"></div>
  <div style="height: 200px;" class="row"></div>
  <div style="height: 100px;" class="row"></div>
  <div style="height: 250px;" class="row"></div>
  <div style="height: 300px;" class="row"></div>

  <div id="legend">
    <div class="text">10</div>
    <div class="text">20</div>
    <div class="text">30</div>
    <div class="text">40</div>
    <div class="text">50</div>
  </div>
</div></code>```

In regards to using float the specification states for both float left and right:

Left: The element generates a block box that is floated to the left. Content flows on the right side of the box, starting at the top.

I do not believe there is a way to override this (unfortunately).

Further reading on float logic.

Title: Vertical position of div element

Body:
I have this so far: [![enter image description here][1]][1]

https://iamsteve.me/uploads/blog/inline-block-example.png

Problem here is that I don't know how to change vertical postion of this div elements. I'm allowed to use CSS1 and CSS2 for old browsers.

HTML

10

20

30

40

50

CSS

.text {
    background-color: gray;
    width: 18%;
    float: left;
    margin: 1%;
    text-align: center;
}

.row {
    background-color: gray;
    width: 18%;
    float: left;
    margin: 1%;
}

Body:
I like to use: display: inline-block instead of floating the elements.

Note that I set font-size: 0 in #graph to eliminate the spacing between inline-block as seen here.

#graph{
  font-size: 0;
}
.text {
  background-color: gray;
  width: 18%;
  float: left;
  margin: 1%;
  text-align: center;
  font-size: 10px;
}

.row {
  position: relative;
  bottom: 0;
  display: inline-block;
  background-color: gray;
  width: 18%;
  margin: 1%;

}

<div id="graph">
  <div style="height: 100px;" class="row"></div>
  <div style="height: 200px;" class="row"></div>
  <div style="height: 100px;" class="row"></div>
  <div style="height: 250px;" class="row"></div>
  <div style="height: 300px;" class="row"></div>

  <div id="legend">
    <div class="text">10</div>
    <div class="text">20</div>
    <div class="text">30</div>
    <div class="text">40</div>
    <div class="text">50</div>
  </div>
</div>

In regards to using float the specification states for both float left and right:

Left: The element generates a block box that is floated to the left. Content flows on the right side of the box, starting at the top.

I do not believe there is a way to override this (unfortunately).

Further reading on float logic.


问:
What is the standard way of initializing a boolean vector in C++
I have researched around but haven't found any clear answer.

How do I initialize a boolean vector of a particular size all set to either true or false?

答:
This will uniformly initialize the vector:

```<code>const size_t SIZE = 10; // However many elements you want in the vector.
const bool initial_value = false; // All elements will be set to this value
std::vector<bool> m_allFalse(SIZE, initial_value);
</code>```

General,
to initialize boolean values at the beginning, you can use this:

```<code>bool temp[] = { true, false, false, true };
std::vector<bool> variousBool ( temp, temp + sizeof(tempBool) / sizeof(bool) );
</code>```

Body:
This will uniformly initialize the vector:

const size_t SIZE = 10; // However many elements you want in the vector.
const bool initial_value = false; // All elements will be set to this value
std::vector<bool> m_allFalse(SIZE, initial_value);

General,
to initialize boolean values at the beginning, you can use this:

bool temp[] = { true, false, false, true };
std::vector<bool> variousBool ( temp, temp + sizeof(tempBool) / sizeof(bool) );


问:
strange text in CoordinatorLayout
I have app name show's in my CoordinatorLayout but i want to remove it , so were to find that text or view , my XML file doesn't have this text view

XML file code :

```<code> <android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<android.support.design.widget.AppBarLayout
    android:id="@+id/htab_appbar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/htab_collapse_toolbar"
        android:layout_width="match_parent"
        android:layout_height="400dp">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="100dp" />

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>
</code>```

答:
it should use  </p>

```<code>app:titleEnabled="false"
</code>```

<p>in CollapsingToolbarLayout </p>

Title: strange text in CoordinatorLayout

Body:
I have app name show's in my CoordinatorLayout but i want to remove it , so were to find that text or view , my XML file doesn't have this text view

XML file code :

 <android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<android.support.design.widget.AppBarLayout
    android:id="@+id/htab_appbar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/htab_collapse_toolbar"
        android:layout_width="match_parent"
        android:layout_height="400dp">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="100dp" />

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

Body:
it should use

app:titleEnabled="false"

in CollapsingToolbarLayout


问:
cplex: define custom mathematical function
I want to define a custom function f in the implementation of my optimisation model in cplex, but some mathematical functions are not available. I want to use my customised function f to make a relation between two of my model variables decisions. Here in how is defined f(x) (it is the CDF of normal distribution):

Thank you for any detail!

答: You won't be able to do so directly. CPLEX will only allow linear and a small subset of non-linear relations such as quadratic or second-order cone functions. You may be able to approximate your function with a piecewise linear function.</p>


问:
React Native Navigator: Can I remove navigation gestures from a scene after a user action?
I want to disable the swipe from left pop gesture on the navigator after the side menu has been accessed within a scene. I don't want to disable it when the scene first renders, only when the side menu is open. I have an onOpen function I can call, but I don't know how to programatically change the navigation gestures without pushing another route.

I tried setting the configureScene prop of the navigator like this:

configureScene={() => {
    return this.state.swipeBackNavigation ? FloatFromRight : Navigator.SceneConfigs.FloatFromRight;
}

and changing the state, but the component doesn't rerender

ideas would be appreciated

答:
I believe you can just set gestures to null (effectively disabling it):

gestures: {}

I can't test this currently, but I suspect it will work (if I didn't screw up some syntax somewhere):

```<code>export default class Foo extends Component {
  constructor(props){
    super(props);
      this.state = {
        //initialize gestureChoice
        gestureChoice: {},
      }
  }

  disablePop(){
    setState({ gestureChoice:{ gestures:{} } });
  }
  enablePop(){
    setState({gestureChoice: ...Navigator.SceneConfigs.FloatFromRight});
  }

  render(){
    return(
      <Navigator
        renderScene={(route, navigator) =>
          return <SomeScene navigator={navigator} {...route.passprops} />
        }
        configureScene={(route, routeStack) =>
          this.state.gestureChoice;
        )}
      />
    );
  }
}
</code>```

The idea being, you could use enablePop() and disablePop() whenever you would like.

This thread is probably helpful: https://github.com/facebook/react-native/issues/1014

Body:
I believe you can just set gestures to null (effectively disabling it):

gestures: {}

I can't test this currently, but I suspect it will work (if I didn't screw up some syntax somewhere):

export default class Foo extends Component {
  constructor(props){
    super(props);
      this.state = {
        //initialize gestureChoice
        gestureChoice: {},
      }
  }

  disablePop(){
    setState({ gestureChoice:{ gestures:{} } });
  }
  enablePop(){
    setState({gestureChoice: ...Navigator.SceneConfigs.FloatFromRight});
  }

  render(){
    return(
      <Navigator
        renderScene={(route, navigator) =>
          return <SomeScene navigator={navigator} {...route.passprops} />
        }
        configureScene={(route, routeStack) =>
          this.state.gestureChoice;
        )}
      />
    );
  }
}

The idea being, you could use enablePop() and disablePop() whenever you would like.

This thread is probably helpful: https://github.com/facebook/react-native/issues/1014


问:
Load data if connected to the Internet
Helle Stack community,

I created a simple app that loads a json and loads the data in a recyclerview.

The recyclerview includes cardviews.

The activity shows me a blank page if I haven't any internet connection,
but normally I want to see some blank cardviews like in the 9GAG app.

In the 9GAG app you get all data on swipe the display.

My app should load all data on internet connection is available. I googled something about broadcast receiver, but can't find a simple example for my need.

Maybe someone can show me a simple example or the way to do some action like in the 9GAG app. Info: The app is for api 21 User.

I would appreciate it.

答:
```<code>public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        if (Network.isNetworkAvailable(Constants.ApplicationContext)) {

        } else {

        }
    }

}
public class Network {
public static boolean isNetworkAvailable(Context context) {
    int retriesNum = Constants.checkConnectionRetriesNum;// a number that I put as 5 for retries to make consideration for bad connections
    if(context!=null)
    while (retriesNum > 0) {
       try {
           ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
           NetworkInfo network = connectivityManager.getActiveNetworkInfo();
           boolean isConnected = network != null &&
                   network.isConnectedOrConnecting();
           if (isConnected) {
               return true;
           } else {

               network = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
               isConnected = network != null && network.isConnectedOrConnecting();
               if (isConnected) {
                   return true;
               } else {
                   network = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                   isConnected = network != null && network.isConnectedOrConnecting();
                   if (isConnected) {
                       return true;
                   } else {
                       retriesNum--;

                   }
               }
           }
       }catch (Exception ex){
           return true;
       }
    }
    return false;
}
</code>```

Title: Load data if connected to the Internet


问:
Modifying state with promises

Why do my promises not actually update the state in Redux?

I'm using redux-promise-middleware. When I make a call to my API, it goes through the promise steps of _PENDING and _FULFILLED, but the state is never updated to reflect the changes.

How do I do this properly, so that I actually get my data.

Here's a picture of my state:

As you can see, isFetched does not become true after the promise is fulfilled, and data is never loading the returned response data into itself.

This is my API helper:

```<code>class UserAPI {

     ...

     async testPhone(user) {
         await axios.post(this.testPhonePath, {
             phone: user.phone
         })
         .then(function(response) {
             return response.data
         })
         .catch(function(error) {
             return error.response.data
         })
     }
}
</code>```

My action:

```<code>import { UserAPI } from '../../constants/api'

const userAPI = new UserAPI()

export const TEST_USER_PHONE = 'TEST_USER_PHONE'

export const testUserPhone = (user) => ({
    type: TEST_USER_PHONE,
    payload: userAPI.testPhone(user)
})
</code>```

And my reducer:

import {
    TEST_USER_PHONE
} from './actions'

const INITIAL_STATE = {
    testedByPhone: {
        data: [],
        isFetched: false,
        error: {
            on: false,
            message: null
        }
    }
}

export default (state = INITIAL_STATE, action) => {
    switch(action.type) {
        case '${TEST_USER_PHONE}_PENDING':
            return INITIAL_STATE
        case '${TEST_USER_PHONE}_FULFILLED':
            return {
                testedByPhone: {
                    data: action.payload,
                    isFetched: true,
                    error: {
                        on: false,
                        message: null
                    }
                }
            }
        case '${TEST_USER_PHONE}_REJECTED':
            return {
                testedByPhone: {
                    data: [],
                    isFetched: true,
                    error: {
                        on: true,
                        message: action.payload
                    }
                }
            }
        default:
            return state
    }
}```
</div>
</div>
</p>

<hr>

<p>Here's my Store</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { createStore, applyMiddleware, compose } from 'redux'
import promiseMiddleware from 'redux-promise-middleware'

import reducers from './reducers'

const middleware = [
    promiseMiddleware()
]

if (__DEV__) {
    const logger = require('redux-logger')

    middleware.push(logger())
}

const enhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

export default createStore(
    reducers,
    undefined,
    enhancers(applyMiddleware(...middleware))
)</code>```

答:
I suspect you wanted to use either

```<code>testPhone(user) {
    return axios.post(this.testPhonePath, {
        phone: user.phone
    }).then(function(response) {
        return response.data
    }, function(error) {
        return error.response.data
    });
}
</code>```

or

```<code>async testPhone(user) {
    try {
        const response = await axios.post(this.testPhonePath, {
            phone: user.phone
        });
        return response.data
    } catch(error) {
        return error.response.data
    }
}
</code>```

but not that current mix which always returns a promise for undefined - it only uses await but not return.

Title: Modifying state with promises

Body:
Why do my promises not actually update the state in Redux?

I'm using redux-promise-middleware. When I make a call to my API, it goes through the promise steps of _PENDING and _FULFILLED, but the state is never updated to reflect the changes.

How do I do this properly, so that I actually get my data.

Here's a picture of my state:

As you can see, isFetched does not become true after the promise is fulfilled, and data is never loading the returned response data into itself.

This is my API helper:

class UserAPI {

     ...

     async testPhone(user) {
         await axios.post(this.testPhonePath, {
             phone: user.phone
         })
         .then(function(response) {
             return response.data
         })
         .catch(function(error) {
             return error.response.data
         })
     }
}

My action:

import { UserAPI } from '../../constants/api'

const userAPI = new UserAPI()

export const TEST_USER_PHONE = 'TEST_USER_PHONE'

export const testUserPhone = (user) => ({
    type: TEST_USER_PHONE,
    payload: userAPI.testPhone(user)
})

And my reducer:

import {
    TEST_USER_PHONE
} from './actions'

const INITIAL_STATE = {
    testedByPhone: {
        data: [],
        isFetched: false,
        error: {
            on: false,
            message: null
        }
    }
}

export default (state = INITIAL_STATE, action) => {
    switch(action.type) {
        case '${TEST_USER_PHONE}_PENDING':
            return INITIAL_STATE
        case '${TEST_USER_PHONE}_FULFILLED':
            return {
                testedByPhone: {
                    data: action.payload,
                    isFetched: true,
                    error: {
                        on: false,
                        message: null
                    }
                }
            }
        case '${TEST_USER_PHONE}_REJECTED':
            return {
                testedByPhone: {
                    data: [],
                    isFetched: true,
                    error: {
                        on: true,
                        message: action.payload
                    }
                }
            }
        default:
            return state
    }
}

Here's my Store

import { createStore, applyMiddleware, compose } from 'redux'
import promiseMiddleware from 'redux-promise-middleware'

import reducers from './reducers'

const middleware = [
    promiseMiddleware()
]

if (__DEV__) {
    const logger = require('redux-logger')

    middleware.push(logger())
}

const enhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

export default createStore(
    reducers,
    undefined,
    enhancers(applyMiddleware(...middleware))
)

Body:
I suspect you wanted to use either

testPhone(user) {
    return axios.post(this.testPhonePath, {
        phone: user.phone
    }).then(function(response) {
        return response.data
    }, function(error) {
        return error.response.data
    });
}

or

async testPhone(user) {
    try {
        const response = await axios.post(this.testPhonePath, {
            phone: user.phone
        });
        return response.data
    } catch(error) {
        return error.response.data
    }
}

but not that current mix which always returns a promise for undefined - it only uses await but not return.


问:
java.io.FileNotFoundException: Access denied on Image.IO.write
Im cropping 64x128 pixel Images in 4x8 and 8x16 grids and saving them in a Temp Folder to extract features from for image classification. While im doing this in a loop for multiple Images (I crop the first Image, get 8x16 subimages, extract features for each subimage, move to the next image and overwrite the existing subimages) I get an "File not found" Exception at random grid cells because access is denied for said grid cell. This only occurs when working with a big number (say 20+) of Images. How can I work around this ?

My code for the cropping part:

```<code>package imageProcess;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Crop_Raster {

BufferedImage src;
BufferedImage dst;

public Crop_Raster(BufferedImage src) {
    super();
    this.src = src;
}

public void cropImage_4x8() throws IOException{
    int filenumber = 1;
    for (int y = 0;y<4;y++){
        for (int x = 0; x<8;x++){
            File output = new File("Temp/"+filenumber+".jpg");
            dst = src.getSubimage(16*x,16*y, 16, 16);
            ImageIO.write(dst, "jpg", output);
            filenumber ++;
        }
    }
}

public void cropImage_8x16() throws IOException{
    int filenumber = 1;
    for (int y = 0;y<8;y++){
        for (int x = 0; x<16;x++){
            File output = new File("Temp/"+filenumber+".jpg");
            dst = src.getSubimage(8*x,8*y, 8, 8);
            ImageIO.write(dst, "jpg", output);
            filenumber ++;
        }
    }
}
</code>```

I get the following Exception, happening while handling the second subimage of my 6th Training Image:

```<code>java.io.FileNotFoundException: Temp\2.jpg (Zugriff verweigert)
at java.io.RandomAccessFile.open0(Native Method)
at java.io.RandomAccessFile.open(Unknown Source)
at java.io.RandomAccessFile.<init>(Unknown Source)
at javax.imageio.stream.FileImageOutputStream.<init>(Unknown Source)
at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(Unknown Source)
at javax.imageio.ImageIO.createImageOutputStream(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)
at imageProcess.Crop_Raster.cropImage_8x16(Crop_Raster.java:38)
at svm.CreateVektor.createVector_8x16(CreateVektor.java:94)
at Main_Test.main(Main_Test.java:107)
</code>```

The error occurs during the cropping part, the rest of my methods should work fine.

答: Clearing the Temp folder after each Image fixed the issue.</p>

Body:
Im cropping 64x128 pixel Images in 4x8 and 8x16 grids and saving them in a Temp Folder to extract features from for image classification. While im doing this in a loop for multiple Images (I crop the first Image, get 8x16 subimages, extract features for each subimage, move to the next image and overwrite the existing subimages) I get an "File not found" Exception at random grid cells because access is denied for said grid cell. This only occurs when working with a big number (say 20+) of Images. How can I work around this ?

My code for the cropping part:

package imageProcess;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Crop_Raster {

BufferedImage src;
BufferedImage dst;

public Crop_Raster(BufferedImage src) {
    super();
    this.src = src;
}

public void cropImage_4x8() throws IOException{
    int filenumber = 1;
    for (int y = 0;y<4;y++){
        for (int x = 0; x<8;x++){
            File output = new File("Temp/"+filenumber+".jpg");
            dst = src.getSubimage(16*x,16*y, 16, 16);
            ImageIO.write(dst, "jpg", output);
            filenumber ++;
        }
    }
}

public void cropImage_8x16() throws IOException{
    int filenumber = 1;
    for (int y = 0;y<8;y++){
        for (int x = 0; x<16;x++){
            File output = new File("Temp/"+filenumber+".jpg");
            dst = src.getSubimage(8*x,8*y, 8, 8);
            ImageIO.write(dst, "jpg", output);
            filenumber ++;
        }
    }
}

I get the following Exception, happening while handling the second subimage of my 6th Training Image:

java.io.FileNotFoundException: Temp\2.jpg (Zugriff verweigert)
at java.io.RandomAccessFile.open0(Native Method)
at java.io.RandomAccessFile.open(Unknown Source)
at java.io.RandomAccessFile.<init>(Unknown Source)
at javax.imageio.stream.FileImageOutputStream.<init>(Unknown Source)
at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(Unknown Source)
at javax.imageio.ImageIO.createImageOutputStream(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)
at imageProcess.Crop_Raster.cropImage_8x16(Crop_Raster.java:38)
at svm.CreateVektor.createVector_8x16(CreateVektor.java:94)
at Main_Test.main(Main_Test.java:107)

The error occurs during the cropping part, the rest of my methods should work fine.


问:
Unexpected infinite loop in Javascript
I was doing a cookie practice in javascript and developed the following code:

```<code>function getCookie(kname) {
  var fullkeyname = kname + "=";
  var fullcookie = document.cookie;
  var acookies = fullcookie.split(";");
  for (var i = 0; i < acookies.length; i++) {
    var cookie = acookies[i];
    while (acookies[i].charAt(0) == " ") { //THE ISSUE IS HERE
      cookie = cookie.substring(1);
    }
    if(cookie.indexOf(fullkeyname) == 0) {
    return cookie.substring(fullkeyname.length, cookie.length);
  }
}
return "";
}
</code>```

It didnt worked and seemed to rise and infinite loop so I tracked my code with "document.write" in various parts and discovered that if I change the "while" condition it will work as follows:

```<code>function getCookie(kname) {
  var fullkeyname = kname + "=";
  var fullcookie = document.cookie;
  var acookies = fullcookie.split(";");
  for (var i = 0; i < acookies.length; i++) {
    var cookie = acookies[i];
    while (cookie.charAt(0) == " ") { //RIGHT HERE
      cookie = cookie.substring(1);
    }
    if (acookies[i].indexOf(fullkeyname) == 0) {
      return cookie.substring(fullkeyname.length, cookie.length);
    }
  }
  return "";
}
</code>```

Now my code works as expected, however I dont know why, since I have set the value of cookies to "cookie=acookies[i]" I dont understand why it should loop indefinetly if I dont use the "cookie" variable.
Question is: why does the code works with my "cookie" variable and not with the "acookies[i]" even though the sould have the same value at that given moment?

答:
It causes an infinite loop because you are checking if the first character of acookies is an empty space, then if it is, you are removing the first character of cookie (NOT acookies). Therefore, if acookies does have a space as the first character, the while statement will always be true because you aren't removing that space from acookies

function getCookie(kname) {
  var fullkeyname = kname + "=";
  var fullcookie = document.cookie;
  var acookies = fullcookie.split(";");
  for (var i = 0; i < acookies.length; i++) {

    while (acookies[i].charAt(0) == " ") { //THE ISSUE IS HERE
      acookies[i] = acookies[i].substring(1); // FIXED THIS LINE
    }

    var cookie = acookies[i];

    if(cookie.indexOf(fullkeyname) == 0) {
    return cookie.substring(fullkeyname.length, cookie.length);
  }
}
return "";
}
```

edited for typo, thank you FREE_AND_OPEN_SOURCE

Title: Unexpected infinite loop in Javascript

Body:
I was doing a cookie practice in javascript and developed the following code:

function getCookie(kname) {
  var fullkeyname = kname + "=";
  var fullcookie = document.cookie;
  var acookies = fullcookie.split(";");
  for (var i = 0; i < acookies.length; i++) {
    var cookie = acookies[i];
    while (acookies[i].charAt(0) == " ") { //THE ISSUE IS HERE
      cookie = cookie.substring(1);
    }
    if(cookie.indexOf(fullkeyname) == 0) {
    return cookie.substring(fullkeyname.length, cookie.length);
  }
}
return "";
}

It didnt worked and seemed to rise and infinite loop so I tracked my code with "document.write" in various parts and discovered that if I change the "while" condition it will work as follows:

function getCookie(kname) {
  var fullkeyname = kname + "=";
  var fullcookie = document.cookie;
  var acookies = fullcookie.split(";");
  for (var i = 0; i < acookies.length; i++) {
    var cookie = acookies[i];
    while (cookie.charAt(0) == " ") { //RIGHT HERE
      cookie = cookie.substring(1);
    }
    if (acookies[i].indexOf(fullkeyname) == 0) {
      return cookie.substring(fullkeyname.length, cookie.length);
    }
  }
  return "";
}

Now my code works as expected, however I dont know why, since I have set the value of cookies to "cookie=acookies[i]" I dont understand why it should loop indefinetly if I dont use the "cookie" variable.
Question is: why does the code works with my "cookie" variable and not with the "acookies[i]" even though the sould have the same value at that given moment?

Body:
It causes an infinite loop because you are checking if the first character of acookies is an empty space, then if it is, you are removing the first character of cookie (NOT acookies). Therefore, if acookies does have a space as the first character, the while statement will always be true because you aren't removing that space from acookies

function getCookie(kname) {
  var fullkeyname = kname + "=";
  var fullcookie = document.cookie;
  var acookies = fullcookie.split(";");
  for (var i = 0; i < acookies.length; i++) {

    while (acookies[i].charAt(0) == " ") { //THE ISSUE IS HERE
      acookies[i] = acookies[i].substring(1); // FIXED THIS LINE
    }

    var cookie = acookies[i];

    if(cookie.indexOf(fullkeyname) == 0) {
    return cookie.substring(fullkeyname.length, cookie.length);
  }
}
return "";
}

edited for typo, thank you FREE_AND_OPEN_SOURCE


问:
How can I avoid TimeOut exception using Entity Framework with a stored procedure?
I'm using Entity Framework to call a stored procedure which takes 2 minutes to execute. As a result, I get a timeout exception.

Is there any way I can use my stored procedure without getting a timeout exception?

答:
Entity Framework uses underlying connection provider and depends on the timeout provided by the provider. Usually its 30 seconds for the timeout if I am not mistaken.

However you can always increase the timeout by setting value of context.CommandTimeout  = 120 in seconds

Hope this helps.


问:
How do I do Entity Extraction in Lucene
I m trying to do Entity Extraction (more like matching) in Lucene. Here is a sample workflow:

Given some text (from a URL) AND a list people names, try to extract names of people from the text.

Note:

Names of people are not completely
  normalized. e.g. Some are Mr. X, Mrs.
  Y and some are just John Doe, X and Y.
  Other prefixes and suffixes to think
  about are Jr., Sr., Dr., I, II ...
  etc. (dont let me get started with non
  US names).

I am using Lucene MemoryIndex to create an in memory index of the text from each Url (stripping html tags) and am using StandardAnalyzer to query for the list of all names, one at a time (100k names, Is there any other way to do this? On an avg. this takes about 8 secs. on the average text I have).

A major problem is that to eliminate noise I m using a score of 0.01 as a base score and queries like "Mr. John Doe" have a significantly lower score as compared to "John Doe" if the text contains "John Doe" and in many cases miss the 0.01 threshold.

The other problem is that If I normalize all names and start removing all occurences of Dr. Mr. Mrs. etc. then I start missing good matches like "Dr. John Edward II" and end up with a lot of junk matches like "Mr. John Edward".

I understand that Lucene might not be the right tool for the job either, but so far it hasnt proved to be too bad. Any help appreciated.

答:
Disambiguation of human names is notoriously difficult. If you have other information such as locations, or co-occurrence of names this will be valuable. But there is a lot of work still going into author disambiguation and it cannot normally be solved just from a list of names.

Here is a typical project http://code.google.com/p/bibapp/wiki/AuthorAuthorities . And a typical publication http://www.springerlink.com/content/lk07h1m311t130w4/.

Here is a project on record deduplications which we find useful for author disambiguation http://datamining.anu.edu.au/projects/linkage.html

ContentLicense: CC BY-SA 2.5

Title: How do I do Entity Extraction in Lucene


问:
How to set production mode on the dashboard in a self hosted parse-server setup

I have tried setting NODE_ENV=production or production: true in js config. But the dashboard still shows DEV.

答:
production mode doesn't mean anything in self hosted parse-server.  Having said that, if you want the dashboard icon to turn green, you can set it in the parse-dashboard config by just setting production: true for that app that you want to have green.

It's spelled out in the docs

you can set custom icons too....cool


问:
Passing list as argument in pydblite
I've been trying to figure out how to pass a list of values as an individual parameter for pydblite.insert(*args). Each value from the list 'temp' and 'keys' must be an individual parameter for both the .insert() and .create() function respectively.</p>

```<code>def copyToMemory(self, table, items):
    db = Base(table + ".pdl")

    if not (db.exists()):
        keys = ""
        for key, val in items[0].items(): keys += key + ', '
        #db.create(keys)

    db.open()
    for i in items:
        temp = []
        for val in i.itervalues():
            temp += val
        #db.insert(temp)
</code>```

答:
For the db.create(), construct a list of the keys and pass them as unpacked arguments like this:

```<code>db.create(*items[0].keys())
</code>```

Since items is a list of dictionaries, you can simply use dict.keys() to get a list of the keys using the first item in the list. This list of keys is then unpacked to pass positional arguments to the create() function. For reference see * in function calls.

Because dict.keys() is unordered, the above assumes that you do not particularly care about the order of the fields in the table.

For db.insert() you can pass an unpacked dictionary using **:

```<code>for item in items:
    db.insert(**item)
</code>```

See ** in function calls. This will pass the arguments to the function as keyword arguments. Note that the order does not matter - the fields in the table will be properly associated with the corresponding item from the dictionary.

Title: Passing list as argument in pydblite

Body:
I've been trying to figure out how to pass a list of values as an individual parameter for pydblite.insert(*args). Each value from the list 'temp' and 'keys' must be an individual parameter for both the .insert() and .create() function respectively.

def copyToMemory(self, table, items):
    db = Base(table + ".pdl")

    if not (db.exists()):
        keys = ""
        for key, val in items[0].items(): keys += key + ', '
        #db.create(keys)

    db.open()
    for i in items:
        temp = []
        for val in i.itervalues():
            temp += val
        #db.insert(temp)

Body:
For the db.create(), construct a list of the keys and pass them as unpacked arguments like this:

db.create(*items[0].keys())

Since items is a list of dictionaries, you can simply use dict.keys() to get a list of the keys using the first item in the list. This list of keys is then unpacked to pass positional arguments to the create() function. For reference see * in function calls.

Because dict.keys() is unordered, the above assumes that you do not particularly care about the order of the fields in the table.

For db.insert() you can pass an unpacked dictionary using **:

for item in items:
    db.insert(**item)

See ** in function calls. This will pass the arguments to the function as keyword arguments. Note that the order does not matter - the fields in the table will be properly associated with the corresponding item from the dictionary.


问:
Neo4J Cypher calculate average across multiple properties
In Neo4J I have the following problem:

Nodes are arranged in a tree-like or parent/child style structure.
On the "leafs" or child nodes, every node has a set of nummerical attributes.

I need a Cypher query to calculate the average of each attribute and strore it in an attribute with the same name in the parent node.

Something like

```<code>MATCH (p:Parent)-[]->(c:Child)
SET p.attrib1 = avg(c.attrib1)
SET p.attrib2 = avg(c.attrib2)
</code>```

will do the job, BUT...

The amount of attributes in the child-nodes should be dynamic, I do not want to change the code when a Child-node comes up with an additional attribute name. As long as the property is a decimal, the code should adapt to this.

Is there a way to achieve this?

答:
You can accomplish this with help from the APOC procedure library. You can almost do this in native Cypher, but you can't dynamically specify the name of the property to create but we can use apoc.create.setProperty to do this:

```<code>MATCH (parent:Parent)<-[]-(child:Child)
WITH parent, child, keys(child) AS props
UNWIND props AS prop
WITH parent, prop, avg(child[prop]) AS mean
CALL apoc.create.setProperty(parent, prop, mean) YIELD node
RETURN *
</code>```

There is a simple example in this Neo4j Console.

Body:
In Neo4J I have the following problem:

Nodes are arranged in a tree-like or parent/child style structure.
On the "leafs" or child nodes, every node has a set of nummerical attributes.

I need a Cypher query to calculate the average of each attribute and strore it in an attribute with the same name in the parent node.

Something like

MATCH (p:Parent)-[]->(c:Child)
SET p.attrib1 = avg(c.attrib1)
SET p.attrib2 = avg(c.attrib2)

will do the job, BUT...

The amount of attributes in the child-nodes should be dynamic, I do not want to change the code when a Child-node comes up with an additional attribute name. As long as the property is a decimal, the code should adapt to this.

Is there a way to achieve this?

Body:
You can accomplish this with help from the APOC procedure library. You can almost do this in native Cypher, but you can't dynamically specify the name of the property to create but we can use apoc.create.setProperty to do this:

MATCH (parent:Parent)<-[]-(child:Child)
WITH parent, child, keys(child) AS props
UNWIND props AS prop
WITH parent, prop, avg(child[prop]) AS mean
CALL apoc.create.setProperty(parent, prop, mean) YIELD node
RETURN *

There is a simple example in this Neo4j Console.


问:
Private github repo as dependency is extraneous on npm install
This is my first time using a private repo as a dependency in another project. I think I am doing it right, but the dependency is not available in the new project after install and is not in node_modules.

Following this post I can see that I am including it in the package.json correctly like:

```<code>"myPackage": "git+https://github.com/myusername/mygitrepository.git"
</code>```

When I run npm install on this package, I see this that it does not have an error, but after this dependency in the list, it is shown with extraneous(git+https://github.com/myusername/mygitrepository.git).

Even though there is the extraneous issue, there is no error, and the dependency is not available or listed in node_modules.

Update: repo_A package.json

```<code>{
  "name": "project-name",
  "version": "1.0.0",
  "description": "Backend utility functions",
  "scripts": {
    "test": "mocha"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/user/repo.git"
  },
  "author": "me",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/user/repo/issues"
  },
  "homepage": "https://github.com/user/repo#readme",
  "dependencies": {
    "lodash": "^4.17.4",
    "mongodb": "^2.2.25",
    "redis": "^2.7.1",
    "winston": "^2.3.1"
  }
}
</code>```

Update: repo_B package.json

```<code>{
  "name": "main-project-name",
  "version": "1.0.0",
  "description": "",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/user/repo.git"
  },
  "author": "someone else",
  "homepage": "https://github.com/user/repo.git",
  "dependencies": {
    "async": "2.1.4",
    "chai": "^3.5.0",
    "langs": "1.1.0",
    "lodash": "4.13.1",
    "node-stopwatch": "0.0.1",
    "request": "2.74.0",
    "winston-loggly": "^1.3.1",
    "utils": "user/repo_A.git#master"
  },
  "scripts": {
    "test": "mocha"
  }
}
</code>```

Update for latest steps
Here are the steps I am following now to test each possible solution, followed by the output:

```<code>rm -rf node_modules
npm cache clean
npm install
</code>```

Output

```<code>├─┬ async@2.1.4
│ └── lodash@4.17.4
├─┬ chai@3.5.0
│ ├── assertion-error@1.0.2
│ ├─┬ deep-eql@0.1.3
│ │ └── type-detect@0.1.1
│ └── type-detect@1.0.0
├── util@1.0.0  extraneous (git+ssh://git@github.com/user/repo_A.git#commit-ish)
.......
</code>```

答:
If you specify https then that will be looking for a login user and password I believe, which I don't think it can load automatically.  I would list it simply as "user/repo" and make sure that machine has an ssh key on it that is in github like the setup described in help such as https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/#platform-linux and that things are setup so that pulling down that repo does not require user interaction.

EDIT: After testing, I think the issue is that your name in the package.json does not match how you have listed it in your main project's dependencies.  In my test, this resulted in the modules being installed but I got the extraneous message.

Body:
This is my first time using a private repo as a dependency in another project. I think I am doing it right, but the dependency is not available in the new project after install and is not in node_modules.

Following this post I can see that I am including it in the package.json correctly like:

"myPackage": "git+https://github.com/myusername/mygitrepository.git"

When I run npm install on this package, I see this that it does not have an error, but after this dependency in the list, it is shown with extraneous(git+https://github.com/myusername/mygitrepository.git).

Even though there is the extraneous issue, there is no error, and the dependency is not available or listed in node_modules.

Update: repo_A package.json

{
  "name": "project-name",
  "version": "1.0.0",
  "description": "Backend utility functions",
  "scripts": {
    "test": "mocha"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/user/repo.git"
  },
  "author": "me",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/user/repo/issues"
  },
  "homepage": "https://github.com/user/repo#readme",
  "dependencies": {
    "lodash": "^4.17.4",
    "mongodb": "^2.2.25",
    "redis": "^2.7.1",
    "winston": "^2.3.1"
  }
}

Update: repo_B package.json

{
  "name": "main-project-name",
  "version": "1.0.0",
  "description": "",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/user/repo.git"
  },
  "author": "someone else",
  "homepage": "https://github.com/user/repo.git",
  "dependencies": {
    "async": "2.1.4",
    "chai": "^3.5.0",
    "langs": "1.1.0",
    "lodash": "4.13.1",
    "node-stopwatch": "0.0.1",
    "request": "2.74.0",
    "winston-loggly": "^1.3.1",
    "utils": "user/repo_A.git#master"
  },
  "scripts": {
    "test": "mocha"
  }
}

Update for latest steps
Here are the steps I am following now to test each possible solution, followed by the output:

rm -rf node_modules
npm cache clean
npm install

Output

├─┬ async@2.1.4
│ └── lodash@4.17.4
├─┬ chai@3.5.0
│ ├── assertion-error@1.0.2
│ ├─┬ deep-eql@0.1.3
│ │ └── type-detect@0.1.1
│ └── type-detect@1.0.0
├── util@1.0.0  extraneous (git+ssh://git@github.com/user/repo_A.git#commit-ish)
.......


问:
jQuery Validation Plugin check if "total_cost" is greater than "user_credit" value in fields
I am having hard time understand how jQuery Validation Plugin works with custom method.For all the guides here i found, are either for input form or static values but mine is a bit different.

I have 2 div's like 2 values and one is value of "user_credit" which store how much user have credit. And another is "total_cost" which store total cost of some special options.

The problem and difference that i have and didn't found on any guide is that my "total_cost" is dynamically changed based on previous checkbox values.

Here's part of code from that:

```<code><div class="row">
                <div class="col-lg-12">
                    <label for="link_to_video">Link to video <i class="fa fa-question-circle" aria-hidden="true" data-toggle="tooltip" title="Add link to your product video. Youtube videos will be automatically embedded"></i></label>
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">
                                <input type="checkbox" name="show_video" id="show_video" value="1" data-price="40">
                            </span>
                            <input type="text" class="form-control" name="link_to_video" id="link_to_video" placeholder="https://youtube.com/watch?v">
                       </div>
                   </div>
                </div>
            </div>

            <div class="row">
                <div class="col-lg-12">
                    <label for="link_to_product">Link to product <i class="fa fa-question-circle" aria-hidden="true" data-toggle="tooltip" title="Add link to your product"></i></label>
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">
                                <input type="checkbox" name="show_product" id="show_product" value="1" data-price="40">
                            </span>
                            <input type="text" class="form-control" name="link_to_product" id="link_to_video" placeholder="http://yourwebsite.com/product-page">
                       </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="form-inline">
                    <div class="col-lg-12">
                        <h4>Your credit <span class="label label-default" id="user_credit">2000</span></h4>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="form-inline">
                    <div class="col-lg-12">
                        <h4>Total cost <span class="label label-default" id="total_price">0</span></h4>
                    </div>
                </div>
            </div>
</code>```

And here is part of code that change "total_price" value when some of checkboxes are checked from above.

```<code>$inputs=$('#show_product,#show_video').change(function(){
    var total=0;
    $inputs.filter(':checked').each(function(){
        total+= $(this).data('price');
    });
    $("#total_price").text(total);
});
</code>```

And another thing is that all guides activate validator in javascript while i activate in form it self

```<code><form action="" name="createListingForm" id="createListingForm" method="POST" role="form" data-toggle="validator" enctype="multipart/form-data">
</code>```

I have been following documentation from here https://jqueryvalidation.org/documentation/ and searched for alot of guides but no luck in finding solution.

答:
First off, you can not validate the text within a span container.  Using this plugin, you can only validate textarea, select, certain types of input elements, and elements with the contenteditable attribute... and they all must be within a form container.

Secondly, if you dynamically change the value of one of these form inputs, you simply call the .valid() method to programmatically trigger validation on this input.

```<code>$('#myinput').valid();  // trigger a validation test of #myinput element
</code>```

Body:
I am having hard time understand how jQuery Validation Plugin works with custom method.For all the guides here i found, are either for input form or static values but mine is a bit different.

I have 2 div's like 2 values and one is value of "user_credit" which store how much user have credit. And another is "total_cost" which store total cost of some special options.

The problem and difference that i have and didn't found on any guide is that my "total_cost" is dynamically changed based on previous checkbox values.

Here's part of code from that:

                    Link to video

                                <input type="checkbox" name="show_video" id="show_video" value="1" data-price="40">

                            <input type="text" class="form-control" name="link_to_video" id="link_to_video" placeholder="https://youtube.com/watch?v">

                    Link to product

                                <input type="checkbox" name="show_product" id="show_product" value="1" data-price="40">

                            <input type="text" class="form-control" name="link_to_product" id="link_to_video" placeholder="http://yourwebsite.com/product-page">

Your credit 2000

Total cost 0

And here is part of code that change "total_price" value when some of checkboxes are checked from above.

$inputs=$('#show_product,#show_video').change(function(){
    var total=0;
    $inputs.filter(':checked').each(function(){
        total+= $(this).data('price');
    });
    $("#total_price").text(total);
});

And another thing is that all guides activate validator in javascript while i activate in form it self

<form action="" name="createListingForm" id="createListingForm" method="POST" role="form" data-toggle="validator" enctype="multipart/form-data">

I have been following documentation from here https://jqueryvalidation.org/documentation/ and searched for alot of guides but no luck in finding solution.

Body:
First off, you can not validate the text within a span container.  Using this plugin, you can only validate textarea, select, certain types of input elements, and elements with the contenteditable attribute... and they all must be within a form container.

Secondly, if you dynamically change the value of one of these form inputs, you simply call the .valid() method to programmatically trigger validation on this input.

$('#myinput').valid();  // trigger a validation test of #myinput element


问:
How can I show only the first result in ng-repeat
I have an ecommerce angularjs project that uses ng-repeat. On a product detail page, I am getting more than 1 result. So I have to use ng-repeat.

How can I show only the first result/array of the response?

My response looks like this:

What I want to do is just show that first response [0]. I don't want to show the 2nd array until later.

Controller:

```<code>unarcoQS.controller ('prodCtrl', ['$scope', 'productService', 'ngCart',
'$route', '$routeParams', '$resource', function($scope, productService, ngCart,
$route, $routeParams, $resource)
{
id = $routeParams.PartNumber;

productService.query({PartNumber: id}, function(response){
   $scope.products = response;
});
</code>```

HTML:

```<code><div class="col-md-7" ng-repeat="product in products">
    <div class="product-title">{{product[0].Description}}</div>
    <div class="product-desc">{{product[0].Category}}</div>
</div>
</code>```

答:
"What I want to do is just show that first response [0]. I don't want to show the 2nd array until later."

Thanh answer is pretty good, but could you elaborate on "until later": if you want to keep the array but display only the first item on this page you can do the following:

```<code><div class="col-md-7">
    <div class="product-title">{{products[0].Description}}</div>
    <div class="product-desc">{{products[0].Category}}</div>
</div>
</code>```

Unless you have a need to use the second item in the ng-repeat I would avoid it.

Body:
I have an ecommerce angularjs project that uses ng-repeat. On a product detail page, I am getting more than 1 result. So I have to use ng-repeat.

How can I show only the first result/array of the response?

My response looks like this:

What I want to do is just show that first response [0]. I don't want to show the 2nd array until later.

Controller:

unarcoQS.controller ('prodCtrl', ['$scope', 'productService', 'ngCart',
'$route', '$routeParams', '$resource', function($scope, productService, ngCart,
$route, $routeParams, $resource)
{
id = $routeParams.PartNumber;

productService.query({PartNumber: id}, function(response){
   $scope.products = response;
});

HTML:

{{product[0].Description}}

{{product[0].Category}}

Body:
"What I want to do is just show that first response [0]. I don't want to show the 2nd array until later."

Thanh answer is pretty good, but could you elaborate on "until later": if you want to keep the array but display only the first item on this page you can do the following:

<div class="col-md-7">
    <div class="product-title">{{products[0].Description}}</div>
    <div class="product-desc">{{products[0].Category}}</div>
</div>

Unless you have a need to use the second item in the ng-repeat I would avoid it.


问:
Show filename of error in popup in vscode

At any file change this error appears and i don't know from where its generated or how to fix/hide it.

Any suggestion?

The error is not related to the opened file.. adding the filename can help me but i don't know how to do that.

答:
The problem seems related to an extension (maybe Angular?). You could try starting VS Code via command line with --disable-extensions param to be sure. It will start VS Code with no extension loaded. After that, if confirmed an extension error, open an issue in the respective repo.

About the message, it should be related to the focused file, but as you say it is not. In this case, it is probably related to the previous focused file, since the extensions uses a lot of assyncronous operations.


问:
A little help needed catching events being raised inside a seperate thread
To begin, I'm working on a pretty high level file system where I need to be able to (with very pin point accuracy) identify and process files in a timely manner.  With that said, I am working on a system that will be using the FileSystemWatcher.  The whole problem with the watcher though is the fact that it tends to have issues when throwing events when there are large files involved.

To remedy this I'm working on an abstract class that can handle the files individualy once they are created by the file system watcher.

The current road block that I am running into is that my out of process validation on the file is throwing an event, I'm just having problems catching it.

```<code>public abstract class absFile
    {
        public delegate void FileAvailable(object sender, FileEventArgs e);
        public event FileAvailable OnFileAvailable;

        public void isAvailable()
        {
            // Create a new threaded instance of the AvailableCheck private void
            // This method will be run out of process to allow other operations to continue.
            Thread toAvailableCheck = new Thread(new ThreadStart(AvailableCheck));

            // Once the threaded object is created, start it.
            toAvailableCheck.Start();
        }

 private void AvailableCheck()
        {
            // Declaring the file stream toThisFile to be used later with the File.Open
            FileStream toThisFile;

            // Declaring and instantiating the attempt counter for the loop
            int tiAttemptNumber = 0;

            // Declaring the event args for returning the events that are
            // used by this object.

            FileEventArgs toFileEventArgs = new FileEventArgs();

            do {
                try
                {
                    // Attempt to open the file.  If this fails the try
                    // will interrupt the processing and it will be caught.
                    toThisFile = File.Open(this.FilePath, FileMode.Open);

                    // If the file.open method does not fail, the isFileAvailable
                    // property will be set to true by updating the mbIsAvailable
                    // private boolean.
                    mbIsAvailable = true;

                    // populate the file event args to send back
                    // the number of attempts made at the file and the pause lenght
                    toFileEventArgs.Attempts = tiAttemptNumber;
                    toFileEventArgs.Pause = this.AttemptPause / 1000;

                    // This event is called when the file is complete.
                    // The client application will be able to handle this event.
                    OnFileAvailable(this, toFileEventArgs);

                    // close and dispose of the filestream.
                    toThisFile.Close();
                    toThisFile.Dispose();
                }
                catch (Exception toException)
                {
                    // Since the open failed, add 1 to the counter so that
                    // it will eventually time out.
                    tiAttemptNumber++;

                    // Set the isFileAvailable property to false.  This property
                    // will default as false, but as a part of standard, make sure that
                    // if the open fails that the flag IS set to false by updating the
                    // mbIsAvailable private boolean.
                    mbIsAvailable = false;

                    // Put the thread to sleep for the ammount of time specified
                    // by the AttemptPause.  This will give the file time to finish
                    // whatever process it is involved in.
                    Thread.Sleep(this.AttemptPause);
                }

              // Continue to make attempts until either the file is marked as available
              // or the number of current attempts is the same as or greater than the
              // AccessAttempts property.
            } while (!this.isFileAvailable && this.AccessAttempts > tiAttemptNumber);
        }
</code>```

this is the code that I am running as you can see in the private void AvailableCheck, OnfileAvailable is the delegate called passing back this and the file event args.

now i have inherited this abstract class, and i need to be able to catch that event.

```<code>        toWatcher.Created += new FileSystemEventHandler(OnCreated);
</code>```

is called in the main and farther down the code is the following method

```<code>private void OnCreated(object source, FileSystemEventArgs e)
{
    lstStatus.Invoke(new MethodInvoker(delegate {
        lstStatus.Items.Add(DateTime.Now.ToString("g") + " - " + e.Name + " - File Created Event Detected for: " + e.FullPath);
        lstStatus.TopIndex = lstStatus.Items.Count - 1;
        tgtFile ThisFile = new tgtFile(e.FullPath);
        lstStatus.Items.Add(DateTime.Now.ToString("g") + " - " + e.Name + " - Creating tgtFile Object");
    }));
}
</code>```

The instatiation of the tgtFile object is passed the path which makes its way down the pike to the is available method.

as you can see the chance exists for the OnFileAvailable event to be fired from the tgtFile object.

Also as you can see, the the possibility for multiple tgtFile objects to exist in memory at the same time is there as well based on the threading design of the filesystemwatcher.

in my main application then i want to be able to do something like:

```<code>public tgtFile ThisFile;
ThisFile.OnFileAvailable += new EventHandler(OnFileAvailable);
</code>```

but the EventHandler errors out, and that is where I am stuck.

答:
If it is giving you a compiler error, it's probably because your "OnFileAvailable" method referenced in this line (from the bottom of your post):

```<code>ThisFile.OnFileAvailable += new EventHandler(OnFileAvailable);
</code>```

is not expecting an EventHandler - it's expecting a FileAvailable delegate.  Change it to:

```<code>ThisFile.OnFileAvailable += new absFile.FileAvailable(OnFileAvailable);
//note that this can also just be ThisFile.OnFileAvailable += OnFileAvailable;
</code>```

and make sure OnFileAvailable looks like this:

```<code>public void OnFileAvailable(object sender, FileEventArgs e)
{
   //...
}
</code>```

Body:
To begin, I'm working on a pretty high level file system where I need to be able to (with very pin point accuracy) identify and process files in a timely manner.  With that said, I am working on a system that will be using the FileSystemWatcher.  The whole problem with the watcher though is the fact that it tends to have issues when throwing events when there are large files involved.

To remedy this I'm working on an abstract class that can handle the files individualy once they are created by the file system watcher.

The current road block that I am running into is that my out of process validation on the file is throwing an event, I'm just having problems catching it.

public abstract class absFile
    {
        public delegate void FileAvailable(object sender, FileEventArgs e);
        public event FileAvailable OnFileAvailable;

        public void isAvailable()
        {
            // Create a new threaded instance of the AvailableCheck private void
            // This method will be run out of process to allow other operations to continue.
            Thread toAvailableCheck = new Thread(new ThreadStart(AvailableCheck));

            // Once the threaded object is created, start it.
            toAvailableCheck.Start();
        }

 private void AvailableCheck()
        {
            // Declaring the file stream toThisFile to be used later with the File.Open
            FileStream toThisFile;

            // Declaring and instantiating the attempt counter for the loop
            int tiAttemptNumber = 0;

            // Declaring the event args for returning the events that are
            // used by this object.

            FileEventArgs toFileEventArgs = new FileEventArgs();

            do {
                try
                {
                    // Attempt to open the file.  If this fails the try
                    // will interrupt the processing and it will be caught.
                    toThisFile = File.Open(this.FilePath, FileMode.Open);

                    // If the file.open method does not fail, the isFileAvailable
                    // property will be set to true by updating the mbIsAvailable
                    // private boolean.
                    mbIsAvailable = true;

                    // populate the file event args to send back
                    // the number of attempts made at the file and the pause lenght
                    toFileEventArgs.Attempts = tiAttemptNumber;
                    toFileEventArgs.Pause = this.AttemptPause / 1000;

                    // This event is called when the file is complete.
                    // The client application will be able to handle this event.
                    OnFileAvailable(this, toFileEventArgs);

                    // close and dispose of the filestream.
                    toThisFile.Close();
                    toThisFile.Dispose();
                }
                catch (Exception toException)
                {
                    // Since the open failed, add 1 to the counter so that
                    // it will eventually time out.
                    tiAttemptNumber++;

                    // Set the isFileAvailable property to false.  This property
                    // will default as false, but as a part of standard, make sure that
                    // if the open fails that the flag IS set to false by updating the
                    // mbIsAvailable private boolean.
                    mbIsAvailable = false;

                    // Put the thread to sleep for the ammount of time specified
                    // by the AttemptPause.  This will give the file time to finish
                    // whatever process it is involved in.
                    Thread.Sleep(this.AttemptPause);
                }

              // Continue to make attempts until either the file is marked as available
              // or the number of current attempts is the same as or greater than the
              // AccessAttempts property.
            } while (!this.isFileAvailable && this.AccessAttempts > tiAttemptNumber);
        }

this is the code that I am running as you can see in the private void AvailableCheck, OnfileAvailable is the delegate called passing back this and the file event args.

now i have inherited this abstract class, and i need to be able to catch that event.

        toWatcher.Created += new FileSystemEventHandler(OnCreated);

is called in the main and farther down the code is the following method

private void OnCreated(object source, FileSystemEventArgs e)
{
    lstStatus.Invoke(new MethodInvoker(delegate {
        lstStatus.Items.Add(DateTime.Now.ToString("g") + " - " + e.Name + " - File Created Event Detected for: " + e.FullPath);
        lstStatus.TopIndex = lstStatus.Items.Count - 1;
        tgtFile ThisFile = new tgtFile(e.FullPath);
        lstStatus.Items.Add(DateTime.Now.ToString("g") + " - " + e.Name + " - Creating tgtFile Object");
    }));
}

The instatiation of the tgtFile object is passed the path which makes its way down the pike to the is available method.

as you can see the chance exists for the OnFileAvailable event to be fired from the tgtFile object.

Also as you can see, the the possibility for multiple tgtFile objects to exist in memory at the same time is there as well based on the threading design of the filesystemwatcher.

in my main application then i want to be able to do something like:

public tgtFile ThisFile;
ThisFile.OnFileAvailable += new EventHandler(OnFileAvailable);

but the EventHandler errors out, and that is where I am stuck.

Body:
If it is giving you a compiler error, it's probably because your "OnFileAvailable" method referenced in this line (from the bottom of your post):

ThisFile.OnFileAvailable += new EventHandler(OnFileAvailable);

is not expecting an EventHandler - it's expecting a FileAvailable delegate.  Change it to:

ThisFile.OnFileAvailable += new absFile.FileAvailable(OnFileAvailable);
//note that this can also just be ThisFile.OnFileAvailable += OnFileAvailable;

and make sure OnFileAvailable looks like this:

public void OnFileAvailable(object sender, FileEventArgs e)
{
   //...
}


问:
How to handle error properly in Promise chain?
Say we have 3 asynchronous tasks that return Promises: A, B and C. We want to chain them together (that is, for sake of clarity, taking the value returned by A and calling B with it), but also want to handle the errors correctly for each, and break out at the first failure. Currently, I see 2 ways of doing this:

```<code>A
.then(passA)
.then(B)
.then(passB)
.then(C)
.then(passC)
.catch(failAll)
</code>```

Here, the passX functions handle each of the success of the call to X. But in the failAll function, we'd have to handle all of the errors of A, B and C, which may be complex and not easy to read, especially if we had more than 3 async tasks. So the other way takes this into consideration:

```<code>A
.then(passA, failA)
.then(B)
.then(passB, failB)
.then(C)
.then(passC, failC)
.catch(failAll)
</code>```

Here, we separated out the logic of the original failAll into failA, failB and failC, which seems simple and readable, since all errors are handled right next to its source. However, this does not do what I want.

Let's see if A fails (rejected), failA must not proceed to call B, therefore must throw an exception or call reject. But both of these gets caught by failB and failC, meaning that failB and failC needs to know if we had already failed or not, presumably by keeping state (i.e. a variable).

Moreover, it seems that the more async tasks we have, either our failAll function grows in size (way 1), or more failX functions gets called (way 2). This brings me to my question:

Is there a better way to do this?

Consideration: Since exceptions in then is handled by the rejection method, should there be a Promise.throw method to actually break off the chain?

A possible duplicate, with an answer that adds more scopes inside the handlers. Aren't promises supposed to honor linear chaining of functions, and not passing functions that pass functions that pass functions?

答:
You can branch the promise-chain, but honestly, early error handling is not the proper way to do it, especially for woolly reasons like readability. True for synchronous code as well, i.e. don't try/catch every single function, or readability just goes in the trash.

Always pass up errors and "handle" them at the point where positive code flow resumes.

If you need to know how far things got, a trick I use is a simple progression counter:

```<code>let progress = "";
A()
.then(a => (progress = "A passed", passA(a)))
.then(B)
.then(b => (progress = "B passed", passB(b)))
.then(C)
.then(c => (progress = "C passed", passC(c)))
.catch(err => (console.log(progress), failAll(err)))
</code>```

Body:
Say we have 3 asynchronous tasks that return Promises: A, B and C. We want to chain them together (that is, for sake of clarity, taking the value returned by A and calling B with it), but also want to handle the errors correctly for each, and break out at the first failure. Currently, I see 2 ways of doing this:

A
.then(passA)
.then(B)
.then(passB)
.then(C)
.then(passC)
.catch(failAll)

Here, the passX functions handle each of the success of the call to X. But in the failAll function, we'd have to handle all of the errors of A, B and C, which may be complex and not easy to read, especially if we had more than 3 async tasks. So the other way takes this into consideration:

A
.then(passA, failA)
.then(B)
.then(passB, failB)
.then(C)
.then(passC, failC)
.catch(failAll)

Here, we separated out the logic of the original failAll into failA, failB and failC, which seems simple and readable, since all errors are handled right next to its source. However, this does not do what I want.

Let's see if A fails (rejected), failA must not proceed to call B, therefore must throw an exception or call reject. But both of these gets caught by failB and failC, meaning that failB and failC needs to know if we had already failed or not, presumably by keeping state (i.e. a variable).

Moreover, it seems that the more async tasks we have, either our failAll function grows in size (way 1), or more failX functions gets called (way 2). This brings me to my question:

Is there a better way to do this?

Consideration: Since exceptions in then is handled by the rejection method, should there be a Promise.throw method to actually break off the chain?

A possible duplicate, with an answer that adds more scopes inside the handlers. Aren't promises supposed to honor linear chaining of functions, and not passing functions that pass functions that pass functions?

Body:
You can branch the promise-chain, but honestly, early error handling is not the proper way to do it, especially for woolly reasons like readability. True for synchronous code as well, i.e. don't try/catch every single function, or readability just goes in the trash.

Always pass up errors and "handle" them at the point where positive code flow resumes.

If you need to know how far things got, a trick I use is a simple progression counter:

let progress = "";
A()
.then(a => (progress = "A passed", passA(a)))
.then(B)
.then(b => (progress = "B passed", passB(b)))
.then(C)
.then(c => (progress = "C passed", passC(c)))
.catch(err => (console.log(progress), failAll(err)))


问:
Python Requests: Allow more retries
I have a website that has two servers - one is dedicated to client-facing web services, and the other is a beefier data processing server.

I currently have a process in which the web server contacts the data server for multiple requests that typically look like this:

```<code>payload = {'req_type':'data_processing', 'sub_type':'data_crunch', 'id_num':12345}
r = requests.get('https://data.mywebsite.com/_api_route', params = payload)
</code>```

...which has been running like clockwork for the better part of the past year.  However, after creating a pandas-heavy function on the data server, I've been getting the following error (which I can't imagine has anything to do with pandas, but thought I'd throw it out there anyway):

```<code>HTTPSConnectionPool(host='data.mywebsite.com', port=443):
    Max retries exceeded with url: /_api_route?......
    (Caused by <class 'httplib.BadStatusLine'>: '')
</code>```

Both servers are running ubuntu, with python, and the Requests library to handle communication between the servers.

There is a similar question here:
Max retries exceeded with URL, but the OP is asking about contacting a server over which he has no control - I can code both sides, so I'm hoping I can change something on my data server, but am not sure what it would be.

答:
I've scoured the known internet for solutions to this problem, and I don't think I'm going to find one in the near future.

Instead, I built in an internal retry loop (in python) on a 1-second delay that looks something like this:

```<code>counter   = 0
max_tries = 10

while counter < max_tries:
    try:
        r       = requests.get('https://data.mywebsite.com/_api_route', params = payload)
        counter = max_tries
        code    = r.json()['r']['code']
        res     = r.json()['r']['response']

        return code, res

    except requests.exceptions.ConnectionError, e:
        counter += 1
        time.sleep(1)
</code>```

It's definitely not a solution as much as it is a workaround, but for now, it does just that, it works... assuming it doesn't have to retry more than 10 times.

Title: Python Requests: Allow more retries

Body:
I have a website that has two servers - one is dedicated to client-facing web services, and the other is a beefier data processing server.

I currently have a process in which the web server contacts the data server for multiple requests that typically look like this:

payload = {'req_type':'data_processing', 'sub_type':'data_crunch', 'id_num':12345}
r = requests.get('https://data.mywebsite.com/_api_route', params = payload)

...which has been running like clockwork for the better part of the past year.  However, after creating a pandas-heavy function on the data server, I've been getting the following error (which I can't imagine has anything to do with pandas, but thought I'd throw it out there anyway):

HTTPSConnectionPool(host='data.mywebsite.com', port=443):
    Max retries exceeded with url: /_api_route?......
    (Caused by <class 'httplib.BadStatusLine'>: '')

Both servers are running ubuntu, with python, and the Requests library to handle communication between the servers.

There is a similar question here:
Max retries exceeded with URL, but the OP is asking about contacting a server over which he has no control - I can code both sides, so I'm hoping I can change something on my data server, but am not sure what it would be.

Body:
I've scoured the known internet for solutions to this problem, and I don't think I'm going to find one in the near future.

Instead, I built in an internal retry loop (in python) on a 1-second delay that looks something like this:

counter   = 0
max_tries = 10

while counter < max_tries:
    try:
        r       = requests.get('https://data.mywebsite.com/_api_route', params = payload)
        counter = max_tries
        code    = r.json()['r']['code']
        res     = r.json()['r']['response']

        return code, res

    except requests.exceptions.ConnectionError, e:
        counter += 1
        time.sleep(1)

It's definitely not a solution as much as it is a workaround, but for now, it does just that, it works... assuming it doesn't have to retry more than 10 times.

ContentLicense: CC BY-SA 4.0


问:
Linq List to share all except duplicate with certain status
Ok, folks.  I have a list that contains two properties: ID and Status.
ex)

1001 Shipped

1002 Shipped

1003 Shipped

1003 Cancelled

From this list, I need to get all EXCEPT duped items with 'Cancelled' status. Essentially, see if they are duped (would only be duped once) and if so, do not include the 'Cancelled' one in the new list.  So the new list should contain 1001, 1002 and 1003.

So that if I had:

1001 Cancelled

1002 Cancelled

1003 Cancelled

1004 Cancelled

The list would contain 1001, 1002, 1003 and 1004.  I'm able to construct this initial list using linq in C# (as in "Items.GroupBy(product => new { product.ProductID, product.Status }).ToList()" ), but cannot proceed any further.  Any help would be appreciated.  Thank you.

答:
From rules which you specified, simple selecting unique product ids with Distinct() will do the job:

```<code>Items.Select(product => product.ProductID).Distinct()
</code>```

That gives you 1001, 1002, 1003 for the first sample and 1001, 1002, 1003, 1004 for the second sample.

If you don't want to select ids of products which have last status as cancelled and timeline is represented only by order of items in your initial list:

```<code> Items.GroupBy(product => product.ProductID)
      .Where(g => g.Last().Status != "Cancelled")
      .Select(g => g.Key)
</code>```

Body:
From rules which you specified, simple selecting unique product ids with Distinct() will do the job:

Items.Select(product => product.ProductID).Distinct()

That gives you 1001, 1002, 1003 for the first sample and 1001, 1002, 1003, 1004 for the second sample.

If you don't want to select ids of products which have last status as cancelled and timeline is represented only by order of items in your initial list:

 Items.GroupBy(product => product.ProductID)
      .Where(g => g.Last().Status != "Cancelled")
      .Select(g => g.Key)


问:
parsing url with regular expressions and KRL's replace method
I want to take the current page's URL (using page:env("caller")) and extract a section of it.

For instance, I want to take

```<code>http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=cats
</code>```

and assign

```<code>cats
</code>```

to a variable.

How would I do this with KRL?

I have tried

```<code>url = page:env("caller");
query = url.replace("http://www\.google\.com/search\?sourceid=chrome&ie=UTF-8&q=", "");
</code>```

but it simply assigns the entire page:env("caller") to the variable query (e.g. http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=cats).

Edit: a jQuery solution would most likely work, as well.

Edit2: @JAM --

The select statement you posted doesn't seem to work. I tested it on http://www.google.com/search?q=cats and it didn't fire. Not sure if the URL doesn't match pageview or what (it looks like it should match to me).

The app I put it in:

```<code>ruleset a835x36 {
  meta {
    name "regex testing2"
    description <<
 >>
author ""
logging on
}

rule get_query {
    select when pageview "http://www.google.com/search.*(?:&|?)q=(\w+)(?:&|$)"    setting(query)
      notify("Query",query) with sticky = true;
   }
}
</code>```

Also, I'm looking for a more robust way to get at the query, since Google has many ways to land on a search results page with URLs that won't look like http://www.google.com/search?q=cats. For example, going to google and searching for cats just gave http://www.google.com/webhp?hl=en#sclient=psy&hl=en&site=webhp&source=hp&q=cats&aq=f&aqi=&aql=&oq=&gs_rfai=&pbx=1&fp=8ac6b4cea9b27ecb for the URL of the results. I guess I could parse anything with a regex, though...

答:
This can be done in the select statement using a regular expression and a capturing group (()'s).

```<code>select when pageview "http://www.google.com/search.*(?:&|?)q=(\w+)(?:&|$)" setting(query)
</code>```

Regular expressions make the select statement powerful. Be sure to learn them! Here is an excellent Regular Expression (or Regex) site.

Body:
I want to take the current page's URL (using page:env("caller")) and extract a section of it.

For instance, I want to take

http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=cats

and assign

cats

to a variable.

How would I do this with KRL?

I have tried

url = page:env("caller");
query = url.replace("http://www\.google\.com/search\?sourceid=chrome&ie=UTF-8&q=", "");

but it simply assigns the entire page:env("caller") to the variable query (e.g. http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=cats).

Edit: a jQuery solution would most likely work, as well.

Edit2: @JAM --

The select statement you posted doesn't seem to work. I tested it on http://www.google.com/search?q=cats and it didn't fire. Not sure if the URL doesn't match pageview or what (it looks like it should match to me).

The app I put it in:

ruleset a835x36 {
  meta {
    name "regex testing2"
    description <<
 >>
author ""
logging on
}

rule get_query {
    select when pageview "http://www.google.com/search.*(?:&|?)q=(\w+)(?:&|$)"    setting(query)
      notify("Query",query) with sticky = true;
   }
}

Also, I'm looking for a more robust way to get at the query, since Google has many ways to land on a search results page with URLs that won't look like http://www.google.com/search?q=cats. For example, going to google and searching for cats just gave http://www.google.com/webhp?hl=en#sclient=psy&hl=en&site=webhp&source=hp&q=cats&aq=f&aqi=&aql=&oq=&gs_rfai=&pbx=1&fp=8ac6b4cea9b27ecb for the URL of the results. I guess I could parse anything with a regex, though...

Body:
This can be done in the select statement using a regular expression and a capturing group (()'s).

select when pageview "http://www.google.com/search.*(?:&|?)q=(\w+)(?:&|$)" setting(query)

Regular expressions make the select statement powerful. Be sure to learn them! Here is an excellent Regular Expression (or Regex) site.


问:
NUXEO Attach Multiple Files on Single Document
I am newer to Nuxeo. I had integrated my Portal with Nuxeo 8.1 CE & now using Java Automation Client API I am performing Operations in Nuxeo from my Portal. My problem is I want to attach Multiple Files on Single Document. I found its operation as BlobHolder.Attach from http://explorer.nuxeo.com/nuxeo/site/distribution/Nuxeo%20DM-5.5/listOperations

But I am not able to find any such example of this Operation. Any example of this Operation will be of great help.

答:
https://www.nuxeo.com/blog/qa-friday-add-extra-files-document-content-automation/

Here is documentation for setting few blobs to document.
I`m not sure but you can try to set Blobs on chain call like in example below.

```<code>HttpAutomationClient client = new HttpAutomationClient("http://localhost:8080/nuxeo/site/automation");
Session session = client.getSession("Administrator", "Administrator");
File dummyFile = new File("/tmp/dummy");
session.newRequest("Blob.AttachOnDocument")
    .set("document", "/path/to/my/doc")
    .set("xpath", "files:files")
    .setInput(new Blobs(Arrays.asList(
            new FileBlob(dummyFile),
            new FileBlob(dummyFile),
            new FileBlob(dummyFile)
    ))).execute();
</code>```

Body:
https://www.nuxeo.com/blog/qa-friday-add-extra-files-document-content-automation/

Here is documentation for setting few blobs to document.
I`m not sure but you can try to set Blobs on chain call like in example below.

HttpAutomationClient client = new HttpAutomationClient("http://localhost:8080/nuxeo/site/automation");
Session session = client.getSession("Administrator", "Administrator");
File dummyFile = new File("/tmp/dummy");
session.newRequest("Blob.AttachOnDocument")
    .set("document", "/path/to/my/doc")
    .set("xpath", "files:files")
    .setInput(new Blobs(Arrays.asList(
            new FileBlob(dummyFile),
            new FileBlob(dummyFile),
            new FileBlob(dummyFile)
    ))).execute();