问:
java.lang.AbstractMethodError: org.slf4j.impl.Log4jLoggerAdapter.log(ava/lang/Object;Ljava/lang/Throwable;)V
I am trying to do samll Camel Application but log4j related error is coming.I checked with many forums but unfortunately no use.Please help me to solve this.Thanks in advance.

gradle dependencies:

```<code>+--- org.slf4j:slf4j-api:1.7.6
|    |    \--- org.slf4j:jcl-over-slf4j:1.7.6
|    |         \--- org.slf4j:slf4j-api:1.7.6
</code>```

log4j related dependencies:

```<code>    compile group: 'org.slf4j', name: 'jcl-over-slf4j', version:'1.5.8'
    compile group: 'org.slf4j', name: 'slf4j-api', version:'1.5.8'
    compile group: 'org.slf4j', name: 'slf4j-log4j12', version:'1.5.8'
    compile group: 'log4j', name: 'log4j', version:'1.2.14'
</code>```

Exception trace:

```<code>INFO: Spring WebApplicationInitializers detected on classpath: [com.pluralsight.orderfulfillment.config.WebContextInitializer@513aec64]
SLF4J: The requested version 1.5.8 by your slf4j binding is not compatible with [1.6, 1.7]
SLF4J: See http://www.slf4j.org/codes.html#version_mismatch for further details.
Jul 05, 2017 12:58:12 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
java.lang.AbstractMethodError: org.slf4j.impl.Log4jLoggerAdapter.log(Lorg/slf4j/Marker;Ljava/lang/String;ILjava/lang/String;[Ljava/lang/Object;Ljava/lang/Throwable;)V
    at org.apache.commons.logging.impl.SLF4JLocationAwareLog.debug(SLF4JLocationAwareLog.java:133)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:118)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1075)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5368)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1571)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1561)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
</code>```

build.gradle:

```<code>apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'war'
apply plugin: "eclipse"

group = 'com.pluralsight.camel'
version = '1.0-SNAPSHOT'

description = """"""

sourceCompatibility = 1.7
targetCompatibility = 1.7

repositories {

     maven { url "http://central.maven.org/maven2/" }
}
dependencies {
    compile(group: 'org.springframework', name: 'spring-core', version:'4.0.4.RELEASE') {
            exclude(module: 'commons-logging')
    }
    compile group: 'org.springframework', name: 'spring-aop', version:'4.0.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-context', version:'4.0.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-tx', version:'4.0.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-aspects', version:'4.0.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-web', version:'4.0.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-webmvc', version:'4.0.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-jdbc', version:'4.0.4.RELEASE'
    compile(group: 'org.springframework.data', name: 'spring-data-jpa', version:'1.5.2.RELEASE') {
            exclude(module: 'spring-aop')
    }
    compile group: 'javax.validation', name: 'validation-api', version:'1.0.0.GA'
    compile group: 'org.hibernate', name: 'hibernate-validator', version:'4.3.1.Final'
    compile group: 'org.hibernate', name: 'hibernate-core', version:'4.3.5.Final'
    compile group: 'org.hibernate', name: 'hibernate-entitymanager', version:'4.3.5.Final'
    compile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.1-api', version:'1.0.0.Final'
    compile group: 'org.springframework', name: 'spring-orm', version:'4.0.4.RELEASE'
    compile group: 'org.slf4j', name: 'jcl-over-slf4j', version:'1.5.8'
    compile group: 'org.slf4j', name: 'slf4j-api', version:'1.5.8'
    compile group: 'org.slf4j', name: 'slf4j-log4j12', version:'1.5.8'
    compile group: 'log4j', name: 'log4j', version:'1.2.14'
    compile group: 'org.aspectj', name: 'aspectjrt', version:'1.7.4'
    compile group: 'cglib', name: 'cglib-nodep', version:'2.2'
    compile group: 'javax.inject', name: 'javax.inject', version:'1'
    compile group: 'postgresql', name: 'postgresql', version:'9.1-901.jdbc4'
    compile group: 'commons-dbcp', name: 'commons-dbcp', version:'1.4'
    compile group: 'jstl', name: 'jstl', version:'1.2'
    compile group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version:'1.9.9'
    compile group: 'org.apache.tiles', name: 'tiles-jsp', version:'2.2.2'
    compile group: 'org.apache.tiles', name: 'tiles-el', version:'2.2.2'
    compile group: 'org.apache.commons', name: 'commons-lang3', version:'3.3.2'
    compile group: 'net.sf.opencsv', name: 'opencsv', version:'2.3'
    compile group: 'org.apache.camel', name: 'camel-spring', version:'2.13.2'
    compile group: 'org.apache.camel', name: 'camel-spring-javaconfig', version:'2.13.2'
    compile group: 'org.apache.camel', name: 'camel-test-spring', version:'2.13.2'
    testCompile group: 'org.springframework', name: 'spring-test', version:'4.0.4.RELEASE'
    testCompile(group: 'junit', name: 'junit-dep', version:'4.10') {
exclude(module: 'hamcrest-core')
    }
    testCompile group: 'org.hamcrest', name: 'hamcrest-library', version:'1.3'
    testCompile group: 'org.mockito', name: 'mockito-core', version:'1.9.0'
    compile(group: 'javax.servlet', name: 'javax.servlet-api', version:'3.0.1') {
       /* This dependency was originally in the Maven provided scope, but the project was not of type war.
       This behavior is not yet supported by Gradle, so this dependency has been converted to a compile dependency.
       Please review and delete this closure when resolved. */
    }
    compile(group: 'javax.servlet.jsp', name: 'jsp-api', version:'2.2') {
       /* This dependency was originally in the Maven provided scope, but the project was not of type war.
       This behavior is not yet supported by Gradle, so this dependency has been converted to a compile dependency.
       Please review and delete this closure when resolved. */
    }
}
</code>```

答:
To work, the api version of SLF4J and its binding version should be compatible (same version generally).

At runtime, the SLF4J binding used is the 1.5.8 but the SLF4J API loaded is the 1.6/1.7 version :

SLF4J: The requested version 1.5.8 by your slf4j binding is not
  compatible with [1.6, 1.7]

You probably have a transitive dependency that pulls the 1.6/1.7 API version of SLF4J.

You could also have this jar specified in the classpath used at runtime.
Check both.

To check the dependencies of your Gradle project, you could use  gradle app:dependencies to get the tree of dependencies of your gradle project.

Body:
I am trying to do samll Camel Application but log4j related error is coming.I checked with many forums but unfortunately no use.Please help me to solve this.Thanks in advance.

gradle dependencies:

+--- org.slf4j:slf4j-api:1.7.6
|    |    \--- org.slf4j:jcl-over-slf4j:1.7.6
|    |         \--- org.slf4j:slf4j-api:1.7.6

log4j related dependencies:

    compile group: 'org.slf4j', name: 'jcl-over-slf4j', version:'1.5.8'
    compile group: 'org.slf4j', name: 'slf4j-api', version:'1.5.8'
    compile group: 'org.slf4j', name: 'slf4j-log4j12', version:'1.5.8'
    compile group: 'log4j', name: 'log4j', version:'1.2.14'

Exception trace:

INFO: Spring WebApplicationInitializers detected on classpath: [com.pluralsight.orderfulfillment.config.WebContextInitializer@513aec64]
SLF4J: The requested version 1.5.8 by your slf4j binding is not compatible with [1.6, 1.7]
SLF4J: See http://www.slf4j.org/codes.html#version_mismatch for further details.
Jul 05, 2017 12:58:12 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
java.lang.AbstractMethodError: org.slf4j.impl.Log4jLoggerAdapter.log(Lorg/slf4j/Marker;Ljava/lang/String;ILjava/lang/String;[Ljava/lang/Object;Ljava/lang/Throwable;)V
    at org.apache.commons.logging.impl.SLF4JLocationAwareLog.debug(SLF4JLocationAwareLog.java:133)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:118)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1075)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5368)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1571)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1561)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

build.gradle:

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'war'
apply plugin: "eclipse"

group = 'com.pluralsight.camel'
version = '1.0-SNAPSHOT'

description = """"""

sourceCompatibility = 1.7
targetCompatibility = 1.7

repositories {

     maven { url "http://central.maven.org/maven2/" }
}
dependencies {
    compile(group: 'org.springframework', name: 'spring-core', version:'4.0.4.RELEASE') {
            exclude(module: 'commons-logging')
    }
    compile group: 'org.springframework', name: 'spring-aop', version:'4.0.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-context', version:'4.0.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-tx', version:'4.0.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-aspects', version:'4.0.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-web', version:'4.0.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-webmvc', version:'4.0.4.RELEASE'
    compile group: 'org.springframework', name: 'spring-jdbc', version:'4.0.4.RELEASE'
    compile(group: 'org.springframework.data', name: 'spring-data-jpa', version:'1.5.2.RELEASE') {
            exclude(module: 'spring-aop')
    }
    compile group: 'javax.validation', name: 'validation-api', version:'1.0.0.GA'
    compile group: 'org.hibernate', name: 'hibernate-validator', version:'4.3.1.Final'
    compile group: 'org.hibernate', name: 'hibernate-core', version:'4.3.5.Final'
    compile group: 'org.hibernate', name: 'hibernate-entitymanager', version:'4.3.5.Final'
    compile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.1-api', version:'1.0.0.Final'
    compile group: 'org.springframework', name: 'spring-orm', version:'4.0.4.RELEASE'
    compile group: 'org.slf4j', name: 'jcl-over-slf4j', version:'1.5.8'
    compile group: 'org.slf4j', name: 'slf4j-api', version:'1.5.8'
    compile group: 'org.slf4j', name: 'slf4j-log4j12', version:'1.5.8'
    compile group: 'log4j', name: 'log4j', version:'1.2.14'
    compile group: 'org.aspectj', name: 'aspectjrt', version:'1.7.4'
    compile group: 'cglib', name: 'cglib-nodep', version:'2.2'
    compile group: 'javax.inject', name: 'javax.inject', version:'1'
    compile group: 'postgresql', name: 'postgresql', version:'9.1-901.jdbc4'
    compile group: 'commons-dbcp', name: 'commons-dbcp', version:'1.4'
    compile group: 'jstl', name: 'jstl', version:'1.2'
    compile group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version:'1.9.9'
    compile group: 'org.apache.tiles', name: 'tiles-jsp', version:'2.2.2'
    compile group: 'org.apache.tiles', name: 'tiles-el', version:'2.2.2'
    compile group: 'org.apache.commons', name: 'commons-lang3', version:'3.3.2'
    compile group: 'net.sf.opencsv', name: 'opencsv', version:'2.3'
    compile group: 'org.apache.camel', name: 'camel-spring', version:'2.13.2'
    compile group: 'org.apache.camel', name: 'camel-spring-javaconfig', version:'2.13.2'
    compile group: 'org.apache.camel', name: 'camel-test-spring', version:'2.13.2'
    testCompile group: 'org.springframework', name: 'spring-test', version:'4.0.4.RELEASE'
    testCompile(group: 'junit', name: 'junit-dep', version:'4.10') {
exclude(module: 'hamcrest-core')
    }
    testCompile group: 'org.hamcrest', name: 'hamcrest-library', version:'1.3'
    testCompile group: 'org.mockito', name: 'mockito-core', version:'1.9.0'
    compile(group: 'javax.servlet', name: 'javax.servlet-api', version:'3.0.1') {
       /* This dependency was originally in the Maven provided scope, but the project was not of type war.
       This behavior is not yet supported by Gradle, so this dependency has been converted to a compile dependency.
       Please review and delete this closure when resolved. */
    }
    compile(group: 'javax.servlet.jsp', name: 'jsp-api', version:'2.2') {
       /* This dependency was originally in the Maven provided scope, but the project was not of type war.
       This behavior is not yet supported by Gradle, so this dependency has been converted to a compile dependency.
       Please review and delete this closure when resolved. */
    }
}


来源: stackexchange

问:
iPhone: How to draw line between two points on MapKit?
I have Latitude and Longitude of two points and Want to Draw line between these two points with Pin on MapKit.

I have googled but Could not find some suitable solution because the one I found was drawing overlay with array of Data points but I do not have any array of points between these two points.

Just two points and want to draw line between these two points.

Please help.

答:
I took the great answer from @graver and did this for Swift 3:</p>

```<code>// Called from viewDidLoad
func setupMap() {
    mapView.delegate = self
    // BusStop implements the MKAnnotation protocol, I have an array of them
    let routeCoordinates = busStops.map({ $0.coordinate })
    let routeLine = MKPolyline(coordinates: routeCoordinates, count: routeCoordinates.count)
    mapView.setVisibleMapRect(routeLine.boundingMapRect, animated: false)
    mapView.add(routeLine)
}

// MARK: MKMapViewDelegate

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if let polyline = overlay as? MKPolyline {
        let polylineRenderer = MKPolylineRenderer(overlay: polyline)
        polylineRenderer.strokeColor = .blue
        polylineRenderer.lineWidth = 3
        return polylineRenderer
    }
    return MKOverlayRenderer(overlay: overlay)
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I took the great answer from @graver and did this for Swift 3:

// Called from viewDidLoad
func setupMap() {
    mapView.delegate = self
    // BusStop implements the MKAnnotation protocol, I have an array of them
    let routeCoordinates = busStops.map({ $0.coordinate })
    let routeLine = MKPolyline(coordinates: routeCoordinates, count: routeCoordinates.count)
    mapView.setVisibleMapRect(routeLine.boundingMapRect, animated: false)
    mapView.add(routeLine)
}

// MARK: MKMapViewDelegate

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if let polyline = overlay as? MKPolyline {
        let polylineRenderer = MKPolylineRenderer(overlay: polyline)
        polylineRenderer.strokeColor = .blue
        polylineRenderer.lineWidth = 3
        return polylineRenderer
    }
    return MKOverlayRenderer(overlay: overlay)
}


问:
Pandas groupby plot with different X-Axis order
I'm working on titanic.csv, and trying to make some plots. Running into one issue. How can I re-organize the x-axis to place the same pclass value next to each other.

my current code:

```<code>titanic.groupby(['Sex', 'Pclass'])['Survived'].mean().plot(kind='bar', color=my_colors)
</code>```

produce the following chart:

I'd like to place the male and female from same class next to each other to show the difference in survival rate. Any suggestion?

答:
Just change the order of columns in groupby:

```<code>import pandas as pd
import seaborn as sns
import matplotlib.pylab as plt

titanic = sns.load_dataset("titanic")

my_colors = ['r','g','b','k','y','magenta']
titanic.groupby(['pclass', 'sex'])['survived'].mean().plot(kind='bar', color=my_colors)
plt.show()
</code>```

Or you can stack the bars:

```<code>titanic.groupby(['pclass', 'sex'])['survived'].mean().unstack('sex').plot(kind='bar', stacked=True)
</code>```

Why you use mean instead of count?

Body:
I'm working on titanic.csv, and trying to make some plots. Running into one issue. How can I re-organize the x-axis to place the same pclass value next to each other.

my current code:

titanic.groupby(['Sex', 'Pclass'])['Survived'].mean().plot(kind='bar', color=my_colors)

produce the following chart:

I'd like to place the male and female from same class next to each other to show the difference in survival rate. Any suggestion?

Body:
Just change the order of columns in groupby:

import pandas as pd
import seaborn as sns
import matplotlib.pylab as plt

titanic = sns.load_dataset("titanic")

my_colors = ['r','g','b','k','y','magenta']
titanic.groupby(['pclass', 'sex'])['survived'].mean().plot(kind='bar', color=my_colors)
plt.show()

Or you can stack the bars:

titanic.groupby(['pclass', 'sex'])['survived'].mean().unstack('sex').plot(kind='bar', stacked=True)

Why you use mean instead of count?


问:
My JQuery post data to 'textbox' how to post it to 'div'?
I'm very new to JQuery.
I already can, get the data from textbox and do some calculation and show it to other 'textbox' though I want to post it to 'div' or 'p' whatever it is as long as not textbox.

here's my code

Participant fee (IDR):

Populi fee (IDR):

<input type="text" id="popcost">

Total Estimated Cost (IDR):

<input type="text" id="totcost">

$(document).ready(function(){
$('#calc').click(function(){
        var num_participant = parseInt($("num_participant").val());
        var reward = parseInt($("reward").val());
        var esttime = parseInt($("esttime").val());
        var parcost = num_participant*reward;
        var popcost = (parcost*0.1)+(num_participant*150);
        var totcost = parcost+popcost;
        /*
        document.getElementById("result").style.display = "block";
        document.getElementById("parcost").value = parcost;
        document.getElementById("popcost").value = popcost;
        document.getElementById("totcost").value = totcost;*/

        document.getElementById("result").style.display = "block";
        $("#parcost").html(parcost);
        $("#popcost").html(popcost);
        $("#totcost").html(totcost);

        return false;
});

});
```

Still wont work, if I change it from "document.getelementById" to "$".
and even using "document.getelementById" it won't showed on the "div".

any ideas?

答:
To update the content of a
 or
 element, you would use innerHTML instead of value.
So in your sample code you would update this line:

```<code>document.getElementById("parcost").value = parcost;
</code>```

into this:

```<code>document.getElementById("parcost").innerHTML= parcost;
</code>```

Furthemore, since you are already using jQuery, you can simplify your click function:

```<code>$('#calc').click(function(){
    var num_participant = parseInt($("#num_participant").val());
    var reward = parseInt($("#reward").val());
    var esttime = parseInt($("#esttime").val());
    var parcost = num_participant*reward;
    var popcost = (parcost*0.1)+(num_participant*150);
    var totcost = parcost+popcost;
    $("#result").css("display", "block");
    $("#parcost").html(parcost);
    $("#popcost").val(popcost);
    $("#totcost").val(totcost);
});
</code>```

Body:
I'm very new to JQuery.
I already can, get the data from textbox and do some calculation and show it to other 'textbox' though I want to post it to 'div' or 'p' whatever it is as long as not textbox.

here's my code

Participant fee (IDR):

Populi fee (IDR):

<input type="text" id="popcost">

Total Estimated Cost (IDR):

<input type="text" id="totcost">

$(document).ready(function(){
$('#calc').click(function(){
        var num_participant = parseInt($("num_participant").val());
        var reward = parseInt($("reward").val());
        var esttime = parseInt($("esttime").val());
        var parcost = num_participant*reward;
        var popcost = (parcost*0.1)+(num_participant*150);
        var totcost = parcost+popcost;
        /*
        document.getElementById("result").style.display = "block";
        document.getElementById("parcost").value = parcost;
        document.getElementById("popcost").value = popcost;
        document.getElementById("totcost").value = totcost;*/

        document.getElementById("result").style.display = "block";
        $("#parcost").html(parcost);
        $("#popcost").html(popcost);
        $("#totcost").html(totcost);

        return false;
});

});

Still wont work, if I change it from "document.getelementById" to "$".
and even using "document.getelementById" it won't showed on the "div".

any ideas?

Body:
To update the content of a <div> or <p> element, you would use innerHTML instead of value.
So in your sample code you would update this line:

document.getElementById("parcost").value = parcost;

into this:

document.getElementById("parcost").innerHTML= parcost;

Furthemore, since you are already using jQuery, you can simplify your click function:

$('#calc').click(function(){
    var num_participant = parseInt($("#num_participant").val());
    var reward = parseInt($("#reward").val());
    var esttime = parseInt($("#esttime").val());
    var parcost = num_participant*reward;
    var popcost = (parcost*0.1)+(num_participant*150);
    var totcost = parcost+popcost;
    $("#result").css("display", "block");
    $("#parcost").html(parcost);
    $("#popcost").val(popcost);
    $("#totcost").val(totcost);
});


问:
Use fade-in and delay with ng-repeat to display list items
I am trying to display list items one by one with some delay. For that I managed to do something like this:

```<code>  $("#dropDownMenu li").each(function(i) {
    $(this).delay(1000 * i).fadeIn(100);
});
</code>```

It works good when list is something like

```<code>    <li>one</li>
    <li>two</li>
    <li>three</li>
</code>```

JSFiddle

But it does't work when I use ng-repeat in a list, something like this

```<code><li ng-repeat="time in msg.time">{{time}}<li>
</code>```

How can I make it work with ng-repeat?

答:
I have created Plunkr example with angular animate effect. It works here

You should add ng-animate source into your html according to your angularjs version.

```<code><script src="//code.angularjs.org/1.5.6/angular-animate.js"></script>
</code>```

You can use angular $timeout service  with jquery $.each function in your angular controller like following.

// css

```<code>.item.ng-enter
{
    -webkit-transition: 1s;
    transition: 1s;
    opacity:0;
}
.item.ng-enter-active
{
    opacity:1;
}
</code>```

//html

```<code><li class="item" ng-repeat="time in msg.time">{{time}}<li>
</code>```

//controller

```<code>myApp.controller('ExampleController', ['$scope','$timeout', function($scope,$timeout) {

    $scope.msg = msg = {
         time : []
      };

    $scope.AddItem = function(){
      msg = {
         time : ["option1","option2","option3","option4"]
      }

      $.each(msg.time, function(i){
         $timeout(function(){
            $scope.msg.time.push(msg.time[i])
         }, 1000*i);
      })

    }

    $scope.AddItem();

}]);
</code>```

Body:
I am trying to display list items one by one with some delay. For that I managed to do something like this:

  $("#dropDownMenu li").each(function(i) {
    $(this).delay(1000 * i).fadeIn(100);
});

It works good when list is something like

one

two

three

JSFiddle

But it does't work when I use ng-repeat in a list, something like this

{{time}}

How can I make it work with ng-repeat?

Body:
I have created Plunkr example with angular animate effect. It works here

You should add ng-animate source into your html according to your angularjs version.

<script src="//code.angularjs.org/1.5.6/angular-animate.js"></script>

You can use angular $timeout service  with jquery $.each function in your angular controller like following.

// css

.item.ng-enter
{
    -webkit-transition: 1s;
    transition: 1s;
    opacity:0;
}
.item.ng-enter-active
{
    opacity:1;
}

//html

<li class="item" ng-repeat="time in msg.time">{{time}}<li>

//controller

myApp.controller('ExampleController', ['$scope','$timeout', function($scope,$timeout) {

    $scope.msg = msg = {
         time : []
      };

    $scope.AddItem = function(){
      msg = {
         time : ["option1","option2","option3","option4"]
      }

      $.each(msg.time, function(i){
         $timeout(function(){
            $scope.msg.time.push(msg.time[i])
         }, 1000*i);
      })

    }

    $scope.AddItem();

}]);


问:
How to use python to invoke events on a desktop?
how to use python to invoke events , like a torrent application and also feeding it with a torrent file in linux ?</p>

答:
Most bittorrent apps on Linux will accept a .torrent file as a command line parameter. With some (notable Azureus//Vuze) you may need to use a fully qualified pathname, which you can get with os.path.abspath. Then just use your favorite method of running programs from Python like the subprocess module or even os.system.

If you need to do anything more sophisticated than that you can try looking for a client that supports dbus.

ContentLicense: CC BY-SA 2.5


问:
How to concatenate some read-only text at the end of the text box?
How to make only some text in a text-box read-only while allowing the rest to be edited. I'm trying to make a text box that allow user to input text and then there is some read-only text (non-editable) at the end of the text box. How can I do this in Javascript/jquery?

Eg of an input field:

DELIVERY ADDRESS

Enter your home or apartment number, ABC Area, XYZ Town

In above eg user is asked to provide home or apartment number and ABC Area, XYZ Town is a predefined value (already provided at some stage). If I split them in 2, most user put their complete address in the text field resulting in duplication of data. I  need to avoid this duplication.

Thanks a mill in advance for your help.

答:
I would do in the following way.

I would create two text boxes:

- text_box_1 - ABC Area and

- text_box_2 - XYZ Town //but invisible (style="display:hidden")

the content of text_box_2 by using jQuery I would populate an Absolute element with position above the text_box_1 which would look inside of text_box_1 but it will not affect the editable content.

If makes sense, you can follow such approach.


问:
PHP: Wordpress update_user_meta not updating array correctly
I've been trying to figure out this issue with Wordpress update_user_meta and arrays.

This is what I currently have:

```<code>add_action('wp_login','user_last_logins', 0, 2);
function user_last_logins($login, $user) {
    $user = get_user_by('login',$login);
    // Get the existing meta for 'meta_key'
    $meta = get_user_meta($user->ID, 'last_logins');
    // Do some defensive coding - if it's not an array, set it up
    if ( ! array($meta) ) {
        $meta = array();
    }
    $month = date('m');
    // Push a new value onto the array
    $meta[] = $month;
    // Write the user meta record with the new value in it
    update_user_meta($user->ID, 'last_logins', $meta);
}
</code>```

So everytime a user logs in, it should save the current month in an array in the database.

First login in database:

```<code>a:1:{i:0;s:2:"07";}
</code>```

Second login in database:

```<code>a:2:{i:0;a:1:{i:0;s:2:"07";}i:1;s:2:"07";}
</code>```

As you can see it's saving the next login as an array within the previous one.

How can I get it to save to original array as or something similar:

```<code>a:2{
   i:0;s:2:"07", //First login
   i:1;s2:"07"   //Second login etc.
}
</code>```

I've tried changing $meta = get_user_meta($user->ID, 'last_logins');
to $meta = get_user_meta($user->ID, 'last_logins', true);

But the update in the database saves over the previous array.

Really would appreciate the help!

UPDATE

Changing the below fixed the array issue

```<code>$meta = get_user_meta($user->ID, 'last_logins');
</code>```

To

```<code>$meta = get_user_meta($user->ID, 'last_logins')[0];
</code>```

答:
When you do $meta = get_user_meta($user->ID, 'last_logins'); you get:

```<code>Array( [0] => Array ( [0] => 07 ) )
</code>```

then you do $meta[] = $month; so you have now:

```<code>Array( [0] => Array ( [0] => '07' ), [1] => '07')
</code>```

Since get_user_meta() is returning an array with an array inside, to append another value you should rather call: $meta = get_user_meta($user->ID, 'last_logins')[0];.

Body:
I've been trying to figure out this issue with Wordpress update_user_meta and arrays.

This is what I currently have:

add_action('wp_login','user_last_logins', 0, 2);
function user_last_logins($login, $user) {
    $user = get_user_by('login',$login);
    // Get the existing meta for 'meta_key'
    $meta = get_user_meta($user->ID, 'last_logins');
    // Do some defensive coding - if it's not an array, set it up
    if ( ! array($meta) ) {
        $meta = array();
    }
    $month = date('m');
    // Push a new value onto the array
    $meta[] = $month;
    // Write the user meta record with the new value in it
    update_user_meta($user->ID, 'last_logins', $meta);
}

So everytime a user logs in, it should save the current month in an array in the database.

First login in database:

a:1:{i:0;s:2:"07";}

Second login in database:

a:2:{i:0;a:1:{i:0;s:2:"07";}i:1;s:2:"07";}

As you can see it's saving the next login as an array within the previous one.

How can I get it to save to original array as or something similar:

a:2{
   i:0;s:2:"07", //First login
   i:1;s2:"07"   //Second login etc.
}

I've tried changing $meta = get_user_meta($user->ID, 'last_logins');
to $meta = get_user_meta($user->ID, 'last_logins', true);

But the update in the database saves over the previous array.

Really would appreciate the help!

UPDATE

Changing the below fixed the array issue

$meta = get_user_meta($user->ID, 'last_logins');

To

$meta = get_user_meta($user->ID, 'last_logins')[0];

Body:
When you do $meta = get_user_meta($user->ID, 'last_logins'); you get:

Array( [0] => Array ( [0] => 07 ) )

then you do $meta[] = $month; so you have now:

Array( [0] => Array ( [0] => '07' ), [1] => '07')

Since get_user_meta() is returning an array with an array inside, to append another value you should rather call: $meta = get_user_meta($user->ID, 'last_logins')[0];.


问:
How to loop through JSON object retrieved via Http Angular 2/ Typescript
I'm trying to fetch some specific data from my JSON file via http. JSON looks like this:

```<code>[{"name":"Name1","perc":33},{"name":"Name2","perc":22},{"name":"Name3","perc":41}]
</code>```

I'm trying to loop through this retrieved object, I'm retrieving it like so:

```<code>  this._postService.getParams(_url).subscribe(
  data => {
    this.results = data.Results
  },
  error => console.log(error),
  () => console.log('Done')
  );
</code>```

getParams() fetches the data like this

```<code>    getParams(url: string) {
    return this._http.get(url)
        .map(res => res.json());
}
</code>```

I made an interface for data retrieved, placed it in the same .component.ts file where the service is being called

```<code>/*Interface for Stats */
interface stats {
name: string;
percent: number;
}
</code>```

I plan to loop through the object I retrieved and store them in a local array and then loop through that and display them. How can I iterate through the JSON object in my component file? I tried many different for loops and they all failed.

I attempted this one and it failed, json was not being recognized by typescript

```<code>let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});
</code>```

I'm perfectly able to retrieve the data, because I console logged the 3 objects I received.

答:
You assigned received data on this.results

```<code>this.results = data.Results
</code>```

But then trying to go through json.Results

Replace json.Results on this.results

Body:
I'm trying to fetch some specific data from my JSON file via http. JSON looks like this:

[{"name":"Name1","perc":33},{"name":"Name2","perc":22},{"name":"Name3","perc":41}]

I'm trying to loop through this retrieved object, I'm retrieving it like so:

  this._postService.getParams(_url).subscribe(
  data => {
    this.results = data.Results
  },
  error => console.log(error),
  () => console.log('Done')
  );

getParams() fetches the data like this

    getParams(url: string) {
    return this._http.get(url)
        .map(res => res.json());
}

I made an interface for data retrieved, placed it in the same .component.ts file where the service is being called

/*Interface for Stats */
interface stats {
name: string;
percent: number;
}

I plan to loop through the object I retrieved and store them in a local array and then loop through that and display them. How can I iterate through the JSON object in my component file? I tried many different for loops and they all failed.

I attempted this one and it failed, json was not being recognized by typescript

let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});

I'm perfectly able to retrieve the data, because I console logged the 3 objects I received.

Body:
You assigned received data on this.results

this.results = data.Results

But then trying to go through json.Results

Replace json.Results on this.results


问:
Use web page framework (i.e. Bootstrap) only on application part, not (static) website pages?
I already have a design for a website. If I would use i.e. Bootstrap, it would take a lot of work to convert bootstrap to the design (more than I would gain from the framework). Yet this only applies to the design and relatively static pages (home, content).
I feel however that I would gain benefit if using Bootstrap for the application part (inputs with error messages, buttons, date picker, and so on).
Would there be a problem just using some elements without the "frame"  around it (no BS-grid)? </p>

答:
You can customise bootstrap to include only what you need, just go to this page:
http://getbootstrap.com/customize/

When you finish to add the elements you need, scroll to the bottom of the page and click "compile and download". You will then have a zip file with all you need from Bootstrap.

It is a good idea to keep your config.json file always available, so you can return to the same page, upload your config file and start from there, in case you want to add minor changes to your customised Bootstrap.


问:
Reusing docker environment variables in CLI
Imagine having a Dockerfile like this

```<code>FROM ubuntu:latest
ENV HELLO_WORLD=hello
CMD echo $HELLO_WORLD
</code>```

I'd like to reuse this variable from command line:

```<code>> docker build -t hello .
> docker run -e HELLO_WORLD='$HELLO_WORLD world' hello
$HELLO_WORLD world
</code>```

I'd like this to result in hello world instead.

Now, I know I can do that in docker-compose and in Dockerfile but I wonder is there any chance to achieve this composition/reuse from CLI?

Edit:
So I was trying to achieve the same thing in docker-compose and I wasn't able to reuse variable from container

```<code>> cat docker-compose.yml
version: '2'
services:
  hello:
    image: 'hello'
    environment:
     - HELLO_WORLD="${HELLO_WORLD} world"

> docker-compose up hello
 world
</code>```

It seems that only 2 places you can access the ENV from are the Dockerfile and then the executables/scripts running inside that docker image :(

答:
ENV directives are used at build time, not at runtime.

If you want to persist data, write it to a file.

Body:
Imagine having a Dockerfile like this

FROM ubuntu:latest
ENV HELLO_WORLD=hello
CMD echo $HELLO_WORLD

I'd like to reuse this variable from command line:

> docker build -t hello .
> docker run -e HELLO_WORLD='$HELLO_WORLD world' hello
$HELLO_WORLD world

I'd like this to result in hello world instead.

Now, I know I can do that in docker-compose and in Dockerfile but I wonder is there any chance to achieve this composition/reuse from CLI?

Edit:
So I was trying to achieve the same thing in docker-compose and I wasn't able to reuse variable from container

> cat docker-compose.yml
version: '2'
services:
  hello:
    image: 'hello'
    environment:
     - HELLO_WORLD="${HELLO_WORLD} world"

> docker-compose up hello
 world

It seems that only 2 places you can access the ENV from are the Dockerfile and then the executables/scripts running inside that docker image :(


问:
Rest Assured Framework complete JSON response matching
I am using Rest Assured Framework for API testing(Using Java).
At line (1),I am expecting error as there is mismatch in expected JSON response and Actual JSON response
But instead my code is executing successfully.
Can someone please tell me if I am doing anything wrong in below code?  </p>

```<code>     public void test123() {
            try {
                //Read the Curl Request Input file
                String json = input.readFromTextFile(
                        System.getProperty("user.dir") + "\\src\\test\\resources\\inputFile\\CurlDataFile.txt");
                json = json.replaceAll(" ", "");
                RestAssured.baseURI = "My URL";
                given().
                    contentType("application/json").
                    body(json).
                when().
                    post("").
                then().
assertThat().body(matchesJsonSchemaInClasspath("testCurlOuput1.json"));  (1)
            } catch (IOException e) {
                e.printStackTrace();
            }catch(JsonSchemaValidationException e){
                e.printStackTrace();
            }
        }
</code>```

答:
This is not directly relevant to REST-assured, but I suggest you take a look at Karate, because IMO it may be exactly what you are looking for.

One of the core features of Karate is that you can perform a full equality match of a JSON payload in one step.

And you can easily use JSON from files, which encourages the re-use of payloads across multiple tests.

Body:
I am using Rest Assured Framework for API testing(Using Java).
At line (1),I am expecting error as there is mismatch in expected JSON response and Actual JSON response
But instead my code is executing successfully.
Can someone please tell me if I am doing anything wrong in below code?

     public void test123() {
            try {
                //Read the Curl Request Input file
                String json = input.readFromTextFile(
                        System.getProperty("user.dir") + "\\src\\test\\resources\\inputFile\\CurlDataFile.txt");
                json = json.replaceAll(" ", "");
                RestAssured.baseURI = "My URL";
                given().
                    contentType("application/json").
                    body(json).
                when().
                    post("").
                then().
assertThat().body(matchesJsonSchemaInClasspath("testCurlOuput1.json"));  (1)
            } catch (IOException e) {
                e.printStackTrace();
            }catch(JsonSchemaValidationException e){
                e.printStackTrace();
            }
        }


问:
formValidation does not submit by ajax
enter image description here

This is my code from javascript, when i try to make a http post pettition this send the data as http get.

```<code>$(document).ready(function(){

    $('#formClient').bootstrapValidator({
        framework: 'bootstrap',
        feedbackIcons: {
          valid: 'glyphicon glyphicon-ok',
          invalid: 'glyphicon glyphicon-remove',
          validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
          phone: {
            validators: {
              integer: {
                  message: 'El valor no es un numero'
              },
              notEmpty: { message: 'La Numero de telefeno que se requiere y no puede estar vacío'},
              stringLength: {
                  min: 8,
                  max: 8,
                  message: 'El numero debe contener 8 caracteres'
              }

            }
          },
          email: {
            validators: {
              notEmpty: { message: 'La dirección de correo electrónico que se requiere y no puede estar vacío'},
              emailAddress: { message: 'la dirección electrónica es no valida'}
            }
          },
          name: {
            validators: {
              notEmpty: { message: 'El nombre esta vacio'},
              stringLength: {
                min: 3,
                max: 50,
                message: 'El nombre debe ser inferior a 50 caracteres'
              }
            }
          },
          lastname: {
                validators: {
                  notEmpty: { message: 'El apellido esta vacio'},
                  stringLength: {
                    min: 10,
                    max: 50,
                    message: 'El apellido debe ser inferior a 50 caracteres'
                  }
                }
              },
          city: {
            validators: {
              notEmpty: { message: 'El contenido es necesario y no puede estar vacío'}
            }
          }
        }
      })
     .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            var $form = $(e.target),
                fv    = $form.data('formValidation');

            var link = "/admin/clients/add";

            alert();

            // Use Ajax to submit form data
            $.ajax({
                url: link,
                type: 'POST',
                data: $form.serialize(),
                success: function(result) {
                    // ... Process the result ...
                    alert();
                }
            });

            $form.formValidation('disableSubmitButtons',  true);
        });

    //Log Out User and redirect to log in page

    $("#logoutBtn").click(function(){
        $("#formlogout").submit();
    });

});
</code>```

after dot that send the path as GET HTTP.

And this is my html form client:

```<code>                <!-- form to client -->
                <form id="formClient" class="form-horizontal form-label-left">

                <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
                <span class="section">Informacion Personal</span>

                  <div class="item form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12" for="telephone">Telefono <span class="required">*</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                      <input type="text" name="phone"  data-fv-integer-message="The value is not an integer" placeholder="Telefono" class="form-control col-md-7 col-xs-12"/>
                  </div>

                  </div>
                  <div class="item form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Nombre del Cliente <span class="required">*</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                      <input class="form-control col-md-7 col-xs-12" name="name" placeholder="Nombre" type="text"/>
                    </div>
                  </div>

                  <div class="item form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12" for="lastname">Apellidos <span class="required">*</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                      <input class="form-control col-md-7 col-xs-12" name="lastname" placeholder="Apellidos" type="text"/>
                    </div>
                  </div>

                  <div class="item form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12" for="city">Ciudad <span class="required">*</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                      <select name="city" class="form-control">
                        <option value="">Seleccione..</option>
                        <option value="Cartago">Cartago</option>
                        <option value="Heredia">Heredia</option>
                        <option value="Alajuela">Alajuela</option>
                        <option value="Limon">Limon</option>
                        <option value="San Jose">San jose</option>
                        <option value="Puntarenas">Puntarenas</option>
                        <option value="Alajuela">Guanacaste</option>
                      </select>
                    </div>
                  </div>

                  <div class="item form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12" for="email">Correo <span class="required">*</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                      <input type="email" name="email" placeholder="Correo" class="form-control col-md-7 col-xs-12"/>
                    </div>
                  </div>

                  <div class="item form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12" for="state">Permitir Fiado <span class="required"></span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                      <input type="checkbox" name="guarantor" class="js-switch" checked="checked" /> Fiado
                    </div>
                  </div>

                  <div class="item form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12" for="state">Usuario <span class="required"></span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                      <input type="checkbox" name="state" class="js-switch" checked="checked" /> Activo
                    </div>
                  </div>

                  <div class="ln_solid"></div>
                  <div class="form-group">
                    <div class="col-md-6 col-md-offset-3">
                      <button id="sendClient" type="submit" class="btn btn-success">Guardar Cliente</button>
                    </div>
                  </div>
                </form>
                <!-- /form to client -->
</code>```

答:
It Looks Like you have not used method while creating the form you can use  :

```<code><form id="formClient" class="form-horizontal form-label-left" method="post">
</code>```

I have created a fiddle : output seems to be changed after using method. Please let me know if any further assistance requried :
Fiddle

Title: formValidation does not submit by ajax

Body:
enter image description here

This is my code from javascript, when i try to make a http post pettition this send the data as http get.

$(document).ready(function(){

    $('#formClient').bootstrapValidator({
        framework: 'bootstrap',
        feedbackIcons: {
          valid: 'glyphicon glyphicon-ok',
          invalid: 'glyphicon glyphicon-remove',
          validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
          phone: {
            validators: {
              integer: {
                  message: 'El valor no es un numero'
              },
              notEmpty: { message: 'La Numero de telefeno que se requiere y no puede estar vacío'},
              stringLength: {
                  min: 8,
                  max: 8,
                  message: 'El numero debe contener 8 caracteres'
              }

            }
          },
          email: {
            validators: {
              notEmpty: { message: 'La dirección de correo electrónico que se requiere y no puede estar vacío'},
              emailAddress: { message: 'la dirección electrónica es no valida'}
            }
          },
          name: {
            validators: {
              notEmpty: { message: 'El nombre esta vacio'},
              stringLength: {
                min: 3,
                max: 50,
                message: 'El nombre debe ser inferior a 50 caracteres'
              }
            }
          },
          lastname: {
                validators: {
                  notEmpty: { message: 'El apellido esta vacio'},
                  stringLength: {
                    min: 10,
                    max: 50,
                    message: 'El apellido debe ser inferior a 50 caracteres'
                  }
                }
              },
          city: {
            validators: {
              notEmpty: { message: 'El contenido es necesario y no puede estar vacío'}
            }
          }
        }
      })
     .on('success.form.fv', function(e) {
            // Prevent form submission
            e.preventDefault();

            var $form = $(e.target),
                fv    = $form.data('formValidation');

            var link = "/admin/clients/add";

            alert();

            // Use Ajax to submit form data
            $.ajax({
                url: link,
                type: 'POST',
                data: $form.serialize(),
                success: function(result) {
                    // ... Process the result ...
                    alert();
                }
            });

            $form.formValidation('disableSubmitButtons',  true);
        });

    //Log Out User and redirect to log in page

    $("#logoutBtn").click(function(){
        $("#formlogout").submit();
    });

});

after dot that send the path as GET HTTP.

And this is my html form client:

                <form id="formClient" class="form-horizontal form-label-left">

                <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
                Informacion Personal

                    Telefono *

                      <input type="text" name="phone"  data-fv-integer-message="The value is not an integer" placeholder="Telefono" class="form-control col-md-7 col-xs-12"/>

                    Nombre del Cliente *

                      <input class="form-control col-md-7 col-xs-12" name="name" placeholder="Nombre" type="text"/>

                    Apellidos *

                      <input class="form-control col-md-7 col-xs-12" name="lastname" placeholder="Apellidos" type="text"/>

                    Ciudad *

                      <select name="city" class="form-control">
                        <option value="">Seleccione..</option>
                        <option value="Cartago">Cartago</option>
                        <option value="Heredia">Heredia</option>
                        <option value="Alajuela">Alajuela</option>
                        <option value="Limon">Limon</option>
                        <option value="San Jose">San jose</option>
                        <option value="Puntarenas">Puntarenas</option>
                        <option value="Alajuela">Guanacaste</option>
                      </select>

                    Correo *

                      <input type="email" name="email" placeholder="Correo" class="form-control col-md-7 col-xs-12"/>

                    Permitir Fiado

                      <input type="checkbox" name="guarantor" class="js-switch" checked="checked" /> Fiado

                    Usuario

                      <input type="checkbox" name="state" class="js-switch" checked="checked" /> Activo

                      <button id="sendClient" type="submit" class="btn btn-success">Guardar Cliente</button>

                </form>

Body:
It Looks Like you have not used method while creating the form you can use  :

<form id="formClient" class="form-horizontal form-label-left" method="post">

I have created a fiddle : output seems to be changed after using method. Please let me know if any further assistance requried :
Fiddle


问:
exception Convert ToInt32 dans c#
I have this code but  but when I run the program gives me this error System.FormatException: Input string was not in a correct format'.</p>

```<code>      public static void Main(string[] args)
    {

        string a =TextFormater("Teste teste ");

        Console.WriteLine(a);
    }
     public static string TextFormater(string ChaineTextArea)
    {
        string val = string.Empty;
        string Valreturn = string.Empty;
        int result;
        for (int i = 0; i <= ChaineTextArea.Length; i++)
        {
            val = ChaineTextArea.Substring(i, 1);
            var chars = val.ToCharArray();

            result = Convert.ToInt32(val);

            if (result != 13)
            {
                Valreturn= val;
            }

            else
            {
                Valreturn= "<br>" + val;
            }
        }
        return Valreturn;
    }
</code>```

答:
Try it to convert int.Parse(val)

or

```<code>Int32.TryParse(val, out number);
</code>```

Title: exception Convert ToInt32 dans c#

Body:
I have this code but  but when I run the program gives me this error System.FormatException: Input string was not in a correct format'.

      public static void Main(string[] args)
    {

        string a =TextFormater("Teste teste ");

        Console.WriteLine(a);
    }
     public static string TextFormater(string ChaineTextArea)
    {
        string val = string.Empty;
        string Valreturn = string.Empty;
        int result;
        for (int i = 0; i <= ChaineTextArea.Length; i++)
        {
            val = ChaineTextArea.Substring(i, 1);
            var chars = val.ToCharArray();

            result = Convert.ToInt32(val);

            if (result != 13)
            {
                Valreturn= val;
            }

            else
            {
                Valreturn= "
" + val;
            }
        }
        return Valreturn;
    }

Body:
Try it to convert int.Parse(val)

or

Int32.TryParse(val, out number);


问:
Using jQuery to change value of one dropdown from another
I have 2 drop down lists and I would like to make it so that when someone selects for example value 2 from dropdown1, dropdown2 is automitacally changed to value 2.  Is this possible using jquery?</p>

```<code><select id="dropdown1">
 <option value="1">Item1</option>
 <option value="2">Item2</option>
 <option value="3">Item3</option>
</select>

<select id="dropdown2">
 <option value="1">Item1</option>
 <option value="2">Item2</option>
 <option value="3">Item3</option>
</select>
</code>```

答:
This should do it:

```<code>$("#dropdwon1").change(function(){
    $("#dropdwon2").val($(this).val());
});
</code>```

working version here: http://jsfiddle.net/xkT3U/

Body:
I have 2 drop down lists and I would like to make it so that when someone selects for example value 2 from dropdown1, dropdown2 is automitacally changed to value 2.  Is this possible using jquery?

<select id="dropdown1">
 <option value="1">Item1</option>
 <option value="2">Item2</option>
 <option value="3">Item3</option>
</select>

<select id="dropdown2">
 <option value="1">Item1</option>
 <option value="2">Item2</option>
 <option value="3">Item3</option>
</select>

Body:
This should do it:

$("#dropdwon1").change(function(){
    $("#dropdwon2").val($(this).val());
});

working version here: http://jsfiddle.net/xkT3U/


问:
Group of combobox dynamically in ZK
I am totally new in ZK. I need to create N combobox with their labels dynamically and populate them. I already populate a combobox with its id, but as there can be many combobox I should not know their ids, so It does not solve my problem.

I need to add N combobox, their labels and populate them dynamically. Is there any way to create that group of combobox and set them dynamically? Any ideas?

The code bellow works to populate the combo already knowing its fixed id.

//In this example I assume I have a label and a combobox. But could have 0 to N of them.

private Label lblComboMetadatos;
private Combobox cmbMetadatos;

//THEN

if (cmbMetadatos.getItemCount() == 0) {
  lblComboMetadatos.setValue(trdMetaTipoDocumental.getNombreMetadato()); //Here I set the name of label but I should really can not know how many of them could be. There may exist 0..N
  for (TrdMetadato trdMetaDato: trdMetaTipoDocumental.getTrdMetadatos()) {

    String enumValores = trdMetaDato.getValoresEnumerado(); //Here I set the values of a combobox but I can not know how many of them could be. There may exist 0..N
    cmbMetadatos.appendItem(enumValores]);
}

}
```

<pre class="lang-html prettyprint-override"><code><zk>
  <window id="idWindow" title="nameWindow" apply="controller.java" border="normal" closable="true" sizable="true" maximizable="true" maximized="true" height="85%" width="150%" style="overflow:auto;">
    <!-- CONTINUES -->
    <groupbox>
      <hlayout>
        <label id="lblComboMetadatos" />
        <combobox id="cmbMetadatos"></combobox>
      </hlayout>
    </groupbox>
    <!-- CONTINUES -->
  </window>
</zk>
</code>```

答:
This question is very similar to your last question. You should wire the parent container (hlayout in this case) to your controller and then create the components there.

```<code>@Wire
private Component container; // your hlayout

@Override  // This method should be specified by a composer super class
public void doAfterCompose(Component comp) throws Exception
    for (<count an index or loop over data>) {
        hlayout.appendChild(new Label("Hello World");
        Combobox cb = new Combobox();
        // append Comboitems
        cb.addEventListener(Events.ON_SELECT, ...);
        hlayout.appendChild(cb);
    }
}
</code>```

If you used MVVM, you could use children binding to create the components in zul.

Title: Group of combobox dynamically in ZK

Body:
I am totally new in ZK. I need to create N combobox with their labels dynamically and populate them. I already populate a combobox with its id, but as there can be many combobox I should not know their ids, so It does not solve my problem.

I need to add N combobox, their labels and populate them dynamically. Is there any way to create that group of combobox and set them dynamically? Any ideas?

The code bellow works to populate the combo already knowing its fixed id.

//In this example I assume I have a label and a combobox. But could have 0 to N of them.

private Label lblComboMetadatos;
private Combobox cmbMetadatos;

//THEN

if (cmbMetadatos.getItemCount() == 0) {
  lblComboMetadatos.setValue(trdMetaTipoDocumental.getNombreMetadato()); //Here I set the name of label but I should really can not know how many of them could be. There may exist 0..N
  for (TrdMetadato trdMetaDato: trdMetaTipoDocumental.getTrdMetadatos()) {

    String enumValores = trdMetaDato.getValoresEnumerado(); //Here I set the values of a combobox but I can not know how many of them could be. There may exist 0..N
    cmbMetadatos.appendItem(enumValores]);
}

}

<zk>
  <window id="idWindow" title="nameWindow" apply="controller.java" border="normal" closable="true" sizable="true" maximizable="true" maximized="true" height="85%" width="150%" style="overflow:auto;">

    <groupbox>
      <hlayout>

        <combobox id="cmbMetadatos"></combobox>
      </hlayout>
    </groupbox>

  </window>
</zk>

Body:
This question is very similar to your last question. You should wire the parent container (hlayout in this case) to your controller and then create the components there.

@Wire
private Component container; // your hlayout

@Override  // This method should be specified by a composer super class
public void doAfterCompose(Component comp) throws Exception
    for (<count an index or loop over data>) {
        hlayout.appendChild(new Label("Hello World");
        Combobox cb = new Combobox();
        // append Comboitems
        cb.addEventListener(Events.ON_SELECT, ...);
        hlayout.appendChild(cb);
    }
}

If you used MVVM, you could use children binding to create the components in zul.


问:
Select element with specific data by using jQuery
Is it possible to set some data by using the jQuery data method and then later query it? Something like ... find all elements with data foo == true?</p>

答:
Not possible with just the data API without looping through each element in the DOM, and checking to see if it contains that data item with the specified value.

If the data is simple, perhaps you can use HTML5 data attributes which are also searchable through selectors.

```<code>$("selector").attr("data-key", "theKey");
</code>```

Later select all objects that have an attribute named "data-key" with the value true using

```<code>$('[data-key="true"]')
</code>```

Body:
Not possible with just the data API without looping through each element in the DOM, and checking to see if it contains that data item with the specified value.

If the data is simple, perhaps you can use HTML5 data attributes which are also searchable through selectors.

$("selector").attr("data-key", "theKey");

Later select all objects that have an attribute named "data-key" with the value true using

$('[data-key="true"]')


问:
django+nginx deployment not loading static files correctly
```<code>    server {
    listen 80;
    server_name 13.xx.xx.xxx;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/ubuntu/studykarma/django-react-redux-base/src/;
    }
    location / {
        include proxy_params;
        include  /etc/nginx/mime.types;
        proxy_pass http://unix:/home/ubuntu/studykarma/django-react-redux-base/src/djangoreactredux.sock;
    }
}
</code>```

my nginx config file

```<code>STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static_dist'),
)
</code>```

my settings.py

I have my static files in static_dist folder and my reactjs code in static
folder.

My static files are not loading and giving me 404,
If i change path to /static_dist/ then also i am getting empty content.

I am using this template: https://github.com/Seedstars/django-react-redux-base

答:
Use this,

```<code>location /static_root/ { root /home/ubuntu/studykarma/django-react-redux-base/src/static_root/; }
</code>```

it will work

Body:
    server {
    listen 80;
    server_name 13.xx.xx.xxx;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/ubuntu/studykarma/django-react-redux-base/src/;
    }
    location / {
        include proxy_params;
        include  /etc/nginx/mime.types;
        proxy_pass http://unix:/home/ubuntu/studykarma/django-react-redux-base/src/djangoreactredux.sock;
    }
}

my nginx config file

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static_dist'),
)

my settings.py

I have my static files in static_dist folder and my reactjs code in static
folder.

My static files are not loading and giving me 404,
If i change path to /static_dist/ then also i am getting empty content.

I am using this template: https://github.com/Seedstars/django-react-redux-base

Body:
Use this,

location /static_root/ { root /home/ubuntu/studykarma/django-react-redux-base/src/static_root/; }

it will work


问:
Trying to stop removing `div` if it's length at `0` or `1`. can someone help me?
Trying to stop removing div if it's length at 0 or 1. can someone help me?

Here is link: https://jsfiddle.net/Issact/ncqnv8zs/

HTML & JS:

$(document).ready(function() {

  $('.div').click(function() {
    $(this).remove();
    var divLength = $('.main div').length;
    $('.mainLength').text(divLength + " " + 'divs');

    if (divLength === 1) {
      $(this).stop().remove();
    }

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div class="div">Div one</div>
  <div class="div">Div Two</div>
  <div class="div">Div Three</div>
  <div class="div">Div Four</div>
</div>

<div class="mainLength">
</div></code>```

答:
I simplify your code as much as possible, check out bellow:

$('.div').click(function(){
  if($('.main .div').length > 1)
    $(this).remove()
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="main">
  <div class="div">Div one</div>
  <div class="div">Div Two</div>
  <div class="div">Div Three</div>
  <div class="div">Div Four</div>
</div>

<div class="mainLength">
</div></code>```

Body:
Trying to stop removing div if it's length at 0 or 1. can someone help me?

Here is link: https://jsfiddle.net/Issact/ncqnv8zs/

HTML & JS:

$(document).ready(function() {

  $('.div').click(function() {
    $(this).remove();
    var divLength = $('.main div').length;
    $('.mainLength').text(divLength + " " + 'divs');

    if (divLength === 1) {
      $(this).stop().remove();
    }

  });
});

Div one

Div Two

Div Three

Div Four

Body:
I simplify your code as much as possible, check out bellow:

$('.div').click(function(){
  if($('.main .div').length > 1)
    $(this).remove()
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="main">
  <div class="div">Div one</div>
  <div class="div">Div Two</div>
  <div class="div">Div Three</div>
  <div class="div">Div Four</div>
</div>

<div class="mainLength">
</div>


问:
Arrow function object iteration with condition
This question is about improving working code. I have a function showLabels that takes a value, iterates over an object and defines which label to return by comparing the value to the object keys.

```<code>  showLabels = (value) => {
    Object.keys(this.state.labels).forEach( key => {
      if (value <= key) this.tooltip = this.state.labels[key];
    });
    return this.tooltip;
  }
</code>```

The question: Is it possible to make this more succinct? Especially assigning the value of the function to this.tooltip and then returning it in the outer function seems unnecessarily verbose.

Example

Based on a comment here is an example:

```<code>this.state.labels = {0: "Smallest amount", 50: "In the middle", 100: "Top"}
value = 33
//showLabels(value=33) should return "In the middle"
</code>```

答:
showLabels = (value) => {
  let tooltip, { labels } = this.state
  Object.keys(labels).forEach( key => {
    if (value <= key) tooltip = labels[key];
  })
  return tooltip;
}```

Something like this is more succinct. Is there a reason you need to use Object.keys() here? It's rather slow.

Anyway, I've added a variable declaration and a destructuring in the beginning.

Body:
This question is about improving working code. I have a function showLabels that takes a value, iterates over an object and defines which label to return by comparing the value to the object keys.

  showLabels = (value) => {
    Object.keys(this.state.labels).forEach( key => {
      if (value <= key) this.tooltip = this.state.labels[key];
    });
    return this.tooltip;
  }

The question: Is it possible to make this more succinct? Especially assigning the value of the function to this.tooltip and then returning it in the outer function seems unnecessarily verbose.

Example

Based on a comment here is an example:

this.state.labels = {0: "Smallest amount", 50: "In the middle", 100: "Top"}
value = 33
//showLabels(value=33) should return "In the middle"

Body:
showLabels = (value) => {
  let tooltip, { labels } = this.state
  Object.keys(labels).forEach( key => {
    if (value <= key) tooltip = labels[key];
  })
  return tooltip;
}

Something like this is more succinct. Is there a reason you need to use Object.keys() here? It's rather slow.

Anyway, I've added a variable declaration and a destructuring in the beginning.


问:
Repeating a texture over a plane in SceneKit
I have a 32x32 .png image that I want to repeat over a SCNPlane. The code I've got (See below) results in the image being stretched to fit the size of the plane, rather than repeated.

CODE:

```<code>let planeGeo = SCNPlane(width: 15, height: 15)

let imageMaterial = SCNMaterial()
imageMaterial.diffuse.contents = UIImage(named: "art.scnassets/grid.png")

planeGeo.firstMaterial = imageMaterial

let plane = SCNNode(geometry: planeGeo)

plane.geometry?.firstMaterial?.diffuse.wrapS = SCNWrapMode.repeat
plane.geometry?.firstMaterial?.diffuse.wrapT = SCNWrapMode.repeat
</code>```

答: I fixed it. It seems like the image was zoomed in. If I do imageMaterial.diffuse.contentsTransform = SCNMatrix4MakeScale(32, 32, 0), the image repeats.

Body:
I have a 32x32 .png image that I want to repeat over a SCNPlane. The code I've got (See below) results in the image being stretched to fit the size of the plane, rather than repeated.

CODE:

let planeGeo = SCNPlane(width: 15, height: 15)

let imageMaterial = SCNMaterial()
imageMaterial.diffuse.contents = UIImage(named: "art.scnassets/grid.png")

planeGeo.firstMaterial = imageMaterial

let plane = SCNNode(geometry: planeGeo)

plane.geometry?.firstMaterial?.diffuse.wrapS = SCNWrapMode.repeat
plane.geometry?.firstMaterial?.diffuse.wrapT = SCNWrapMode.repeat


问:
How to use Saved Audience as a targeting Spec when creating Adsets
I am trying to create an adset with targeting specs and assign saved_audience id as a targeting specs. I looked at the API docs of targeting spec: https://developers.facebook.com/docs/marketing-api/targeting-specs/v2.8

It talks about custom_audience but not saved_audience. I tried to send it as a parameter saved_audience, saved_audiences etc. thinking that maybe it is not documented. API response is invalid parameter.

Here is the code:

```<code>$set->setData(array(
        AdSetFields::NAME => $obj_page->title.' '.time(),
        AdSetFields::CAMPAIGN_ID => $campaign_id,
        AdSetFields::DAILY_BUDGET => $daily_budget,
        AdSetFields::BID_AMOUNT => $daily_budget,
        AdSetFields::START_TIME => (new \DateTime($request->start_time))->format(\DateTime::ISO8601),
        AdSetFields::END_TIME => (new \DateTime($request->end_time))->format(\DateTime::ISO8601),
        AdSetFields::BILLING_EVENT => AdSetBillingEventValues::IMPRESSIONS,
        AdSetFields::TARGETING => (new Targeting())->setData(array(
            'custom_audiences' => array($audience_id), // works
            TargetingFields::PUBLISHER_PLATFORMS => array('facebook'),
            TargetingFields::DEVICE_PLATFORMS => array('desktop'),
        ))
    ));
</code>```

using 'saved_audience' => array($audience_id) doesn't work.

答: I've been dealing with the same problem (check my Stackoverflow question) and my conclusion is that it isn't possible right now. A work-around is to retrieve the targeting spec from your saved audience in a separate API call and copy over these settings to the new ad you're creating. Disadvantage is that when updating the saved audience, your ad won't be updated.

Body:
I am trying to create an adset with targeting specs and assign saved_audience id as a targeting specs. I looked at the API docs of targeting spec: https://developers.facebook.com/docs/marketing-api/targeting-specs/v2.8

It talks about custom_audience but not saved_audience. I tried to send it as a parameter saved_audience, saved_audiences etc. thinking that maybe it is not documented. API response is invalid parameter.

Here is the code:

$set->setData(array(
        AdSetFields::NAME => $obj_page->title.' '.time(),
        AdSetFields::CAMPAIGN_ID => $campaign_id,
        AdSetFields::DAILY_BUDGET => $daily_budget,
        AdSetFields::BID_AMOUNT => $daily_budget,
        AdSetFields::START_TIME => (new \DateTime($request->start_time))->format(\DateTime::ISO8601),
        AdSetFields::END_TIME => (new \DateTime($request->end_time))->format(\DateTime::ISO8601),
        AdSetFields::BILLING_EVENT => AdSetBillingEventValues::IMPRESSIONS,
        AdSetFields::TARGETING => (new Targeting())->setData(array(
            'custom_audiences' => array($audience_id), // works
            TargetingFields::PUBLISHER_PLATFORMS => array('facebook'),
            TargetingFields::DEVICE_PLATFORMS => array('desktop'),
        ))
    ));

using 'saved_audience' => array($audience_id) doesn't work.


答:
You should be able to simply cast the data into your array:

```<code>getParams(url: string) {
  return this._http.get(url)
    .map(res => <stats[]> res.json());
}
</code>```

Then in this code:

```<code>  this._postService.getParams(_url).subscribe(
  data => {
    this.results = data.Results
  },
  error => console.log(error),
  () => console.log('Done')
  );
</code>```

this.results should be your array of stats.

Title: How to loop through JSON object retrieved via Http Angular 2/ Typescript

Body:
I'm trying to fetch some specific data from my JSON file via http. JSON looks like this:

[{"name":"Name1","perc":33},{"name":"Name2","perc":22},{"name":"Name3","perc":41}]

I'm trying to loop through this retrieved object, I'm retrieving it like so:

  this._postService.getParams(_url).subscribe(
  data => {
    this.results = data.Results
  },
  error => console.log(error),
  () => console.log('Done')
  );

getParams() fetches the data like this

    getParams(url: string) {
    return this._http.get(url)
        .map(res => res.json());
}

I made an interface for data retrieved, placed it in the same .component.ts file where the service is being called

/*Interface for Stats */
interface stats {
name: string;
percent: number;
}

I plan to loop through the object I retrieved and store them in a local array and then loop through that and display them. How can I iterate through the JSON object in my component file? I tried many different for loops and they all failed.

I attempted this one and it failed, json was not being recognized by typescript

let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});

I'm perfectly able to retrieve the data, because I console logged the 3 objects I received.

Body:
You should be able to simply cast the data into your array:

getParams(url: string) {
  return this._http.get(url)
    .map(res => <stats[]> res.json());
}

Then in this code:

  this._postService.getParams(_url).subscribe(
  data => {
    this.results = data.Results
  },
  error => console.log(error),
  () => console.log('Done')
  );

this.results should be your array of stats.


问:
Why Android crashes instead of showing the error in debug mode
At first, my story:

So after a while, I have found the reason which causes the crashing of my app in debug mode!!
I used replace command to replace a fragment with another one, but it crashes and exits from debug mode. In the same sample, it works fine and finally, I got the problem that was about my forgetfulness about the implementation of its listener. Though, in the code, there was a throw command for unimplementation!

```<code>@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}
</code>```

In Android Monitor when the crash happens, only these lines are appended:

07-05 08:05:54.797 6171-6171/com.shoniz.saledistributemobility

  D/AndroidRuntime: Shutting down VM

07-05 08:05:54.799    6171-6171/com.shoniz.saledistributemobility
  I/art: System.exit    called, status: 2

07-05 08:05:54.799    6171-6171/com.shoniz.saledistributemobility
  I/AndroidRuntime: VM    exiting with result code 2, cleanup skipped.

07-05 08:05:54.801    1303-1576/system_process D/GraphicsStats: Buffer
  count: 3

Now my question

Is there any way to force Android Studio to stop running and show the reason of the crash to save our time?! Something like a work that Visual Studio does.

答:
use  fabric crash analytic tool https://try.crashlytics.com/
you will get all error in mail or dashboard with logcat .if you cant get error in logcat you will get in crashlytics dash board.only internet should be on</p>

Body:
At first, my story:

So after a while, I have found the reason which causes the crashing of my app in debug mode!!
I used replace command to replace a fragment with another one, but it crashes and exits from debug mode. In the same sample, it works fine and finally, I got the problem that was about my forgetfulness about the implementation of its listener. Though, in the code, there was a throw command for unimplementation!

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

In Android Monitor when the crash happens, only these lines are appended:

07-05 08:05:54.797 6171-6171/com.shoniz.saledistributemobility

  D/AndroidRuntime: Shutting down VM

07-05 08:05:54.799    6171-6171/com.shoniz.saledistributemobility
  I/art: System.exit    called, status: 2

07-05 08:05:54.799    6171-6171/com.shoniz.saledistributemobility
  I/AndroidRuntime: VM    exiting with result code 2, cleanup skipped.

07-05 08:05:54.801    1303-1576/system_process D/GraphicsStats: Buffer
  count: 3

Now my question

Is there any way to force Android Studio to stop running and show the reason of the crash to save our time?! Something like a work that Visual Studio does.


问:
Multiple showings of AngularJS Unit Tests in VS2015 Test Explorer with Chutzpah and Jasmin
I wrote some Unit Tests for my AngularJS stuff and use Chutzpah to run the tests in VS. That works like a charm but every test shows up 3 times in VS Test Explorer. Any idea why? My chutzpah.json looks like this:</p>

```<code>{
  "References": [
     { "Path": “Path of needed file” },
     { "Path": “Path of needed file” },
     { "Path": “Path of needed file” },
     { "Path": “Path of needed file” }
  ]
}
</code>```

答: I found the mistake in the weekend. I still had a html site for running the tests without Chutzpah. Chutzpah found the Tests on its own and toke them again from the html.</p>

Body:
I wrote some Unit Tests for my AngularJS stuff and use Chutzpah to run the tests in VS. That works like a charm but every test shows up 3 times in VS Test Explorer. Any idea why? My chutzpah.json looks like this:

{
  "References": [
     { "Path": “Path of needed file” },
     { "Path": “Path of needed file” },
     { "Path": “Path of needed file” },
     { "Path": “Path of needed file” }
  ]
}


问:
insert into with two selects and compare
It looks stupid in this example but here is what I want to do:

Table_a:

```<code>id    fk_b_id              full_name
1     [I want '10' here]   [I want 'John, Doe' here]
</code>```

Table_b:

```<code>id    first_name
10    John
</code>```

Table_c:

```<code>id    full_name    date
20    John, Doe    2020-01-01
</code>```

I get all the full names that is not already in c and meets the criteria like this:

```<code>select distinct full_name
from Table_c
where full_name not in (
    select full_name
    from Table_a ) and date > GETDATE()
</code>```

The result from the query should be inserted into Table_a together with Table_b's id (fk_b_id). So I need a compare between part of Table_a's full_name and Table_b's first_name to get the correct fk. I can do the compare like this:

```<code>where Table_b.first_name = LTRIM(RTRIM(RIGHT(Table_c.full_name, CHARINDEX(',', REVERSE(Table_c.full_name))-1 )))
</code>```

Can I insert all the full names from table c (that meets the criteria) and the fk from table b (where their first names match) into table a in one query?

答:
Sure, just use your condition to JOIN between tables B and C

```<code>INSERT INTO Table_a (fk_b_id, full_name)
SELECT DISTINCT b.id, c.full_name
FROM Table_c c
INNER JOIN Table_b b ON b.first_name = LTRIM(RTRIM(RIGHT(c.full_name, CHARINDEX(',', REVERSE(c.full_name))-1 )))
WHERE c.full_name not in (
    select a.full_name
    from Table_a a ) and c.date > GETDATE()
</code>```

EDIT:

Also note, that if your table_a.full_name column can have NULL values, NOT IN sub-query will fail to give you expected results. I suggest rewriting it to use NOT EXISTS

```<code>WHERE NOT EXISTS
  (SELECT * FROM Table_a WHERE Table_a.Full_Name = Table_c.FUll_Name )
</code>```

Body:
It looks stupid in this example but here is what I want to do:

Table_a:

id    fk_b_id              full_name
1     [I want '10' here]   [I want 'John, Doe' here]

Table_b:

id    first_name
10    John

Table_c:

id    full_name    date
20    John, Doe    2020-01-01

I get all the full names that is not already in c and meets the criteria like this:

select distinct full_name
from Table_c
where full_name not in (
    select full_name
    from Table_a ) and date > GETDATE()

The result from the query should be inserted into Table_a together with Table_b's id (fk_b_id). So I need a compare between part of Table_a's full_name and Table_b's first_name to get the correct fk. I can do the compare like this:

where Table_b.first_name = LTRIM(RTRIM(RIGHT(Table_c.full_name, CHARINDEX(',', REVERSE(Table_c.full_name))-1 )))

Can I insert all the full names from table c (that meets the criteria) and the fk from table b (where their first names match) into table a in one query?

Body:
Sure, just use your condition to JOIN between tables B and C

INSERT INTO Table_a (fk_b_id, full_name)
SELECT DISTINCT b.id, c.full_name
FROM Table_c c
INNER JOIN Table_b b ON b.first_name = LTRIM(RTRIM(RIGHT(c.full_name, CHARINDEX(',', REVERSE(c.full_name))-1 )))
WHERE c.full_name not in (
    select a.full_name
    from Table_a a ) and c.date > GETDATE()

EDIT:

Also note, that if your table_a.full_name column can have NULL values, NOT IN sub-query will fail to give you expected results. I suggest rewriting it to use NOT EXISTS

WHERE NOT EXISTS
  (SELECT * FROM Table_a WHERE Table_a.Full_Name = Table_c.FUll_Name )


问:
Mock a java web service Rest who invoke a static extern methode
I want to make an unit test of a web service (Rest- jersey) this is how my web service look likes

```<code>public class WebService {

        public string webServiceMethode {
               ...
               String a =   ExternalClass.staticMethode("aa");
               ..
              return b

           }
    }
</code>```

as you can see the web service methode invoke a static methode in a external class, in test class my idea is to call the web service by Rest-Assured and mock the statics methode by Powermock and here my test methode logic

```<code>public class WebServicetest {
      @Test
      public void testWebServiceMethode {
               mockStatic(ExternalClass.class);
               when(ExternalClass.staticMethode(Mockito.any()))
                                   .thenReturn("ok");
              given().accept(CotentType.JSON)
              .body(MyObject).when().post(new URI("/test"));
    }
  }
</code>```

the given() methode will call the web service and the when().theReturn() will replace the return of the external static methode so the call works good but not the mock.

Thank you in advance for your help

答:
A) Understand that static is an abnormality within good OOP. It kills polymorphism, and it leads to super tight coupling between your classes. The sane thing to do: avoid using static this way.

static can be OK, but as soon as it hampers your ability to do (easy) unit-testing, you are doing something wrong.

So, my first answer is: get rid of that static method.

B) In case you want to continue doing the wrong thing (using PowerMock) - simply read the tutorials or the documentation. There are various requirements in order make static mocking work. You need to use the @Runner(PowerMockRunner), and you need to use the @PrepareForTest annotation (for the class on which you want to mock static classes). So that PowerMock can go in and manipulate the byte code of your production code so it can do its magic.

Body:
I want to make an unit test of a web service (Rest- jersey) this is how my web service look likes

public class WebService {

        public string webServiceMethode {
               ...
               String a =   ExternalClass.staticMethode("aa");
               ..
              return b

           }
    }

as you can see the web service methode invoke a static methode in a external class, in test class my idea is to call the web service by Rest-Assured and mock the statics methode by Powermock and here my test methode logic

public class WebServicetest {
      @Test
      public void testWebServiceMethode {
               mockStatic(ExternalClass.class);
               when(ExternalClass.staticMethode(Mockito.any()))
                                   .thenReturn("ok");
              given().accept(CotentType.JSON)
              .body(MyObject).when().post(new URI("/test"));
    }
  }

the given() methode will call the web service and the when().theReturn() will replace the return of the external static methode so the call works good but not the mock.

Thank you in advance for your help


问:
How to use python to invoke events on a desktop?
how to use python to invoke events , like a torrent application and also feeding it with a torrent file in linux ?</p>

答:
If you want to invoke a program from python you can do it like this:

```<code>import os
cmd = '/path/to/program'
os.system(cmd)
</code>```

I cannot say anything about running your bittorrent program, since you haven't said anything about which program you are using, but calling it with an url is probably straight forward (just find the right switch and add the switch and url to the cmd variable above).

Body:
If you want to invoke a program from python you can do it like this:

import os
cmd = '/path/to/program'
os.system(cmd)

I cannot say anything about running your bittorrent program, since you haven't said anything about which program you are using, but calling it with an url is probably straight forward (just find the right switch and add the switch and url to the cmd variable above).


答:
You could use Array.prototype.find on Object.entries

 showLabels = value => Object.entries(this.state.labels)
                             // sort pairs by key
                             .sort(([keyA], [keyB]) => keyA > keyB)
                             .find(([key]) => key > value)[1]
 ```

BTW keep in mind that the order of iteration over keys is not guaranteed. So assuming you want to find the first label that is greater than value, you need to sort labels.

Title: Arrow function object iteration with condition

Body:
You could use Array.prototype.find on Object.entries

 showLabels = value => Object.entries(this.state.labels)
                             // sort pairs by key
                             .sort(([keyA], [keyB]) => keyA > keyB)
                             .find(([key]) => key > value)[1]

BTW keep in mind that the order of iteration over keys is not guaranteed. So assuming you want to find the first label that is greater than value, you need to sort labels.