问:
What is FormCollection argument for? Is it a dummy argument?
Up to now I have no idea why does VS provide FormCollection argument by default?

```<code>    public ActionResult Edit(int id)
    {
        Dinner dinner = dinnerRepository.GetDinnerById(id);

        if (dinner == null)
            return View("NotFound");
        else
            return View(dinner);
    }

    [HttpPost]
    public ActionResult Edit(int id, object dummy/*, FormCollection collection*/)
    {
        Dinner temp = dinnerRepository.GetDinnerById(id);

        if (TryUpdateModel(temp))
        {
            dinnerRepository.Save();

            return RedirectToAction("Details", new { id = temp.DinnerId });
        }
        else
            return View(temp);
    }
</code>```

EDIT 1: In my experiment, any arguments other than id are dummy because they never be used in httppost Edit action method.

EDIT 2: Does TryUpdateModel use FormCollection behind the scene?

答:
FormCollection contains your form state coming back to your server.

If you need any custom operation on the processing of your data you use FormCollection. Otherwise you can happily remove it.

I am using it heavily for a hierarchical model processing.

Body:
Up to now I have no idea why does VS provide FormCollection argument by default?

    public ActionResult Edit(int id)
    {
        Dinner dinner = dinnerRepository.GetDinnerById(id);

        if (dinner == null)
            return View("NotFound");
        else
            return View(dinner);
    }

    [HttpPost]
    public ActionResult Edit(int id, object dummy/*, FormCollection collection*/)
    {
        Dinner temp = dinnerRepository.GetDinnerById(id);

        if (TryUpdateModel(temp))
        {
            dinnerRepository.Save();

            return RedirectToAction("Details", new { id = temp.DinnerId });
        }
        else
            return View(temp);
    }

EDIT 1: In my experiment, any arguments other than id are dummy because they never be used in httppost Edit action method.

EDIT 2: Does TryUpdateModel use FormCollection behind the scene?


来源: stackexchange

问:
Generator expressions Python
I have a list of dictionaries like the following:

```<code>lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]
</code>```

I wrote a generator expression like:

```<code>next((itm for itm in lst if itm['a']==5))
</code>```

Now the strange part is that though this works for the key value pair of 'a'
it throws an error for all other expressions the next time.
Expression:

```<code>next((itm for itm in lst if itm['b']==6))
</code>```

Error:

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
KeyError: 'b'
</code>```

答:
Maybe you can try this:

```<code>next(next((itm for val in itm.values() if val == 6) for itm in lst))
</code>```

This may be a little tricky, it generate two-tier generator, thus you need two next to get the result.

ContentLicense: CC BY-SA 3.0

Title: Generator expressions Python

Body:
I have a list of dictionaries like the following:

lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]

I wrote a generator expression like:

next((itm for itm in lst if itm['a']==5))

Now the strange part is that though this works for the key value pair of 'a'
it throws an error for all other expressions the next time.
Expression:

next((itm for itm in lst if itm['b']==6))

Error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
KeyError: 'b'

Body:
Maybe you can try this:

next(next((itm for val in itm.values() if val == 6) for itm in lst))

This may be a little tricky, it generate two-tier generator, thus you need two next to get the result.


问:
JavaScript in WebView - Android Studio
Is there a way to display of scripts JavaScript in WebView? /Android Studio

I want use WebView to display my website, but it use JavaScript.

答:
Yes there is.

```<code>WebView webview = (WebView) findViewById(R.id.yourwebview);
webview.getSettings().setJavaScriptEnabled(true);
</code>```

This will enable the javascript in your webview.

Hope this helps :)

Title: JavaScript in WebView - Android Studio

Body:
Yes there is.

WebView webview = (WebView) findViewById(R.id.yourwebview);
webview.getSettings().setJavaScriptEnabled(true);

This will enable the javascript in your webview.

Hope this helps :)


问:
How to load 15.000.000 registers into a table with pentaho?
I have created an ETL process with Pentaho that selects data from a table in a Database and load this into another database.

The main problem that I have to make front is that for 1.500.000 rows it takes 6 hours. The full table is 15.000.000 and I have to load 5 tables like that.

Can anyone explain how is supposed to load a large size of data with pentaho?

Thank you.

答:
There's no fixed answer covering all possible performance issues. You'll need to identify the bottlenecks and solve them in your environment.

If you look at the Metrics tab while running the job in Spoon, you can often see at which step the rows/s rate drops. It will be the one with the full input buffer and empty output buffer.

To get some idea of the maximum performance of the job, you can test each component individually.

Connect the Table Input to a dummy step only and see how many rows/s it reaches.

Define a Generate Rows step with all the fields that go to your destination and some representative data and connect it to the Table Output step. Again, check the rows/s to see the destination database's throughput.

Start connecting more steps/transformations to your Table Input and see where performance goes down.

Once you know your bottlenecks, you'll need to figure out the solutions. Bulk load steps often help the output rate. If network lag is holding you back, you might want to dump data to compressed files first and copy those locally. If your Table input has joins or where clauses, make sure the source database has the correct indexes to use, or change your query.


问:
import unicodecsv fails in jupyter
I tried to run
import unicodecsv
within jupyter by running a .ipynb file.
It failed.
Then I installed the unicodecsv file through the python install command and found it within c\python27 dir. But still the import did not happen.
How should it be installed. Does it need to be placed within the anaconda installation

Edit :
Error displayed -

```<code>---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-9c1521d8df38> in <module>()
      2 #                 1                 #
      3 #####################################
----> 4 import unicodecsv
      5 ## Read in the data from daily_engagement.csv and project_submissions.csv
      6 ## and store the results in the below variables.

ImportError: No module named unicodecsv
</code>```

答:
I had the same problem for the same file at Udacity.

Try changing the Kernel from Python2 to Python3 in the Kernel -> Change Kernel menu.

Hope that helps :)

Title: import unicodecsv fails in jupyter

Body:
I tried to run
import unicodecsv
within jupyter by running a .ipynb file.
It failed.
Then I installed the unicodecsv file through the python install command and found it within c\python27 dir. But still the import did not happen.
How should it be installed. Does it need to be placed within the anaconda installation

Edit :
Error displayed -

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-9c1521d8df38> in <module>()
      2 #                 1                 #
      3 #####################################
----> 4 import unicodecsv
      5 ## Read in the data from daily_engagement.csv and project_submissions.csv
      6 ## and store the results in the below variables.

ImportError: No module named unicodecsv


问:
Angular/Ionic NG-Class isnt doing anything
i have a problem:

im new to ionic/angular and im not able to make ng-class work

<ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col>
        <ion-row>
          <ion-col *ngFor="let field1 of gs.fields; let x = index; trackBy: trackByFn">

            <ion-col *ngFor="let field2 of field1; let y = index; trackBy: trackByFn">
              <ion-row>
                <ion-col class="ctr fc tile" *ngFor="let tile of field2; let z = index; trackBy: trackByFn" (click)="playerClick(x,y,z)">
                  {{(tile==0)? ' ': ((tile==1)? 'x' : 'o')}}
                </ion-col>
              </ion-row>
            </ion-col>
          </ion-col>
        </ion-row>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>```
</div>
</div>
</p>

```(click)="playerClick(x,y,z)"
```

<p>Is getting Called in my Service, so i shouldnt be mission any ng-model right?<br> I mean <code>{{(tile==0)? ' ': ((tile==1)? 'x' : 'o')}}</code> is working, so Angular should have every variable im using right?</p>

<p><strong>How its shown in the Browser:<br></strong></p>

```<ion-col class="ctr fc tile col">
x
</ion-col>
```

<p><br>I also tried to call a Function inside my Service from ng-style and console log inside the function to test if its called but it wasnt.<br>
Example: <code><span class="ctr" ng-style="{'color':getTileColor(tile)}">{{(tile==0)? ' ': ((tile==1)? 'x' : 'o')}}</span></code></p>

<p><br>Furthermore i would like to force a new row if x%3 == 0
Im thinking of something like (but it isnt working):</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-html lang-html prettyprint-override"><code><ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col>
        <ion-col *ngFor="let field1 of gs.fields; let x = index; trackBy: trackByFn">
          <ion-row ng-if "x % 3 == 0">
            <!-- new row if  -->
            <ion-col *ngFor="let field2 of field1; let y = index; trackBy: trackByFn">
              <ion-row>
                <ion-col class="ctr fc tile" *ngFor="let tile of field2; let z = index; trackBy: trackByFn" (click)="playerClick(x,y,z)">
                  <span class="ctr" ng-class="{'player1': tile==1, 'player2' : tile==2}">{{(tile==0)? ' ': ((tile==1)? 'x' : 'o')}}</span>
                </ion-col>
              </ion-row>
            </ion-col>
          </ion-row ng-if "x % 3 == 0">
        </ion-col>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content></code>```

^ I put ion-row inside the first nGFor there

```<code><ion-row ng-if "x % 3 == 0">
</code>```

ROWS how it is

ROWS how it should be

答:
i think you're confusing angular 1 with angular 2.

ng-style and ng-class are angular 1 syntax

in angular 2 and above the correct way to invoke these directives is:

```<code>[ngClass]="{'player1': tile==1, 'player2' : tile==2}"
[ngStyle]="{'font-size': fontSize+'px'}"
</code>```

link to docs

Body:
i have a problem:

im new to ionic/angular and im not able to make ng-class work

<ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col>
        <ion-row>
          <ion-col *ngFor="let field1 of gs.fields; let x = index; trackBy: trackByFn">

            <ion-col *ngFor="let field2 of field1; let y = index; trackBy: trackByFn">
              <ion-row>
                <ion-col class="ctr fc tile" *ngFor="let tile of field2; let z = index; trackBy: trackByFn" (click)="playerClick(x,y,z)">
                  {{(tile==0)? ' ': ((tile==1)? 'x' : 'o')}}
                </ion-col>
              </ion-row>
            </ion-col>
          </ion-col>
        </ion-row>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

(click)="playerClick(x,y,z)"

Is getting Called in my Service, so i shouldnt be mission any ng-model right?
 I mean {{(tile==0)? ' ': ((tile==1)? 'x' : 'o')}} is working, so Angular should have every variable im using right?

How its shown in the Browser:

<ion-col class="ctr fc tile col">
x
</ion-col>

I also tried to call a Function inside my Service from ng-style and console log inside the function to test if its called but it wasnt.

Example: {{(tile==0)? ' ': ((tile==1)? 'x' : 'o')}}

Furthermore i would like to force a new row if x%3 == 0
Im thinking of something like (but it isnt working):

<ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col>
        <ion-col *ngFor="let field1 of gs.fields; let x = index; trackBy: trackByFn">
          <ion-row ng-if "x % 3 == 0">

            <ion-col *ngFor="let field2 of field1; let y = index; trackBy: trackByFn">
              <ion-row>
                <ion-col class="ctr fc tile" *ngFor="let tile of field2; let z = index; trackBy: trackByFn" (click)="playerClick(x,y,z)">
                  {{(tile==0)? ' ': ((tile==1)? 'x' : 'o')}}
                </ion-col>
              </ion-row>
            </ion-col>
          </ion-row ng-if "x % 3 == 0">
        </ion-col>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

^ I put ion-row inside the first nGFor there

<ion-row ng-if "x % 3 == 0">

ROWS how it is

ROWS how it should be

Body:
i think you're confusing angular 1 with angular 2.

ng-style and ng-class are angular 1 syntax

in angular 2 and above the correct way to invoke these directives is:

[ngClass]="{'player1': tile==1, 'player2' : tile==2}"
[ngStyle]="{'font-size': fontSize+'px'}"

link to docs


问:
set selected item of drop downlist equal to a text box
How can I make my drop down list shows the value in my text box? The value is always one the items of drop down list, but how can I set the selected item of drop down list equals to the value of my textbox, after click?</p>

```<code> $('<input  name="Product Name" data-type="string" \>')
     .appendTo(container)
     .kendoDropDownList({
         dataSource: mydata,
         dataTextField: "Text",
  });
</code>```

答:
Try something like this (it's just an example of the way how to set the value)

```<code>$("#Instrument").kendoDropDownList({
  dataTextField: "symbol",
  dataValueField: "symbol",
  dataSource: data,
  index: 0
});

var dropdownlist = $("#YourId").data("kendoDropDownList");
dropdownlist.select(function (dataItem) {
    return dataItem.symbol === "Your value from input or whatever";
});
</code>```

PS: in "dataItem.symbol" symbol is your dataTextField: "symbol"

Body:
How can I make my drop down list shows the value in my text box? The value is always one the items of drop down list, but how can I set the selected item of drop down list equals to the value of my textbox, after click?

 $('<input  name="Product Name" data-type="string" \>')
     .appendTo(container)
     .kendoDropDownList({
         dataSource: mydata,
         dataTextField: "Text",
  });

Body:
Try something like this (it's just an example of the way how to set the value)

$("#Instrument").kendoDropDownList({
  dataTextField: "symbol",
  dataValueField: "symbol",
  dataSource: data,
  index: 0
});

var dropdownlist = $("#YourId").data("kendoDropDownList");
dropdownlist.select(function (dataItem) {
    return dataItem.symbol === "Your value from input or whatever";
});

PS: in "dataItem.symbol" symbol is your dataTextField: "symbol"


答:
If your app receives a POST, then 99.99% of the time it will come from an HTML form. The FormsCollection gathers all the values in the form for you.

In ASP.NET MVC you are almost always better off using strongly typed objects though. The DefaultModelBinder will create them for you most of the time, and you can implement IModelBinder if needed if the default one doesn't do what you need.

ContentLicense: CC BY-SA 2.5

Title: What is FormCollection argument for? Is it a dummy argument?


问:
Skype link in Email Signature does not work on gmail client
I have an email signature in which all the links work fine in every mail client except the skype one:

```<code><span>Skype:</span> <span><a href="skype:jared.rake?add">Jared.Rake</a></span>
</code>```

The link works as intended (launches the skype client) on all mail clients except gmail. Any idea why this is so?

I have the skype client installed on my system.

When you inspect the span tag(the one that contains the name, I can see the link () tag, but I cannot see the href attribute.

Any help would be appreciated.

答: Additionally, if you want to rebrand your skype link you can use a subdomain that redirects to your is.gd link to keep your links branded. I created a post about this here: http://meerkat.link/skype-in-gmail-sig-using-isgd</p>

Body:
I have an email signature in which all the links work fine in every mail client except the skype one:

Skype: Jared.Rake

The link works as intended (launches the skype client) on all mail clients except gmail. Any idea why this is so?

I have the skype client installed on my system.

When you inspect the span tag(the one that contains the name, I can see the link () tag, but I cannot see the href attribute.

Any help would be appreciated.


问:
Gradle dependencies: how to remove java classes from jar in repository?
Grade: how to exclude some java classes from a jar in public repository?

For example, a foo.jar in repository depends on bar1.jar, bar2.jar

```<code>foo.jar
     bar1.jar
     bar2.jar
</code>```

remove "javax/**" from foo.jar, add it into runtimeOnly configuration

```<code>dependencies {
    runtimeOnly foo-changed.jar, bar1.jar, bar2.jar
}
</code>```

Tried

```<code>configurations {
     changeFoo
}

dependencies {
     changeFoo "group:foo:1.0"  // contains foo.jar, bar1.jar, bar2.jar
}

task changeFoo(type: Jar) {
    def jarFile = configurations.changeFoo.singleFile   // error: more than one file

    from zipTree(jarFile) {
        exclude 'javax/**'
    }

    destinationDir project.libsDir
    archiveName "foo-changed.jar"
}
</code>```

How to get the single file (foo.jar)?
How to replace the foo.jar in the configurations.changeFoo with foo-changed.jar?

```<code>dependencies {
    runtimeOnly.extendsFrom changeFoo
}
</code>```

答:
Try something like this.</p>

```<code>configurations.changeFoo.asFileTree.each {
    from(zipTree(it))
    exclude ''
}
destinationDir project.libsDir
archiveName "foo-changed.jar"
</code>```

Body:
Grade: how to exclude some java classes from a jar in public repository?

For example, a foo.jar in repository depends on bar1.jar, bar2.jar

foo.jar
     bar1.jar
     bar2.jar

remove "javax/**" from foo.jar, add it into runtimeOnly configuration

dependencies {
    runtimeOnly foo-changed.jar, bar1.jar, bar2.jar
}

Tried

configurations {
     changeFoo
}

dependencies {
     changeFoo "group:foo:1.0"  // contains foo.jar, bar1.jar, bar2.jar
}

task changeFoo(type: Jar) {
    def jarFile = configurations.changeFoo.singleFile   // error: more than one file

    from zipTree(jarFile) {
        exclude 'javax/**'
    }

    destinationDir project.libsDir
    archiveName "foo-changed.jar"
}

How to get the single file (foo.jar)?
How to replace the foo.jar in the configurations.changeFoo with foo-changed.jar?

dependencies {
    runtimeOnly.extendsFrom changeFoo
}

Body:
Try something like this.

configurations.changeFoo.asFileTree.each {
    from(zipTree(it))
    exclude ''
}
destinationDir project.libsDir
archiveName "foo-changed.jar"


问:
"main" org.apache.spark.SparkException: Task not serializable
I'm trying to run the following simple Spark code:

```<code>public static void main(final String[] args)throws Exception {

    ClassLoader.getSystemClassLoader().getClass().getName();
    Thread.currentThread().getContextClassLoader().getClass().getName();
    GraphApiApplication.class.getClassLoader();

    /*if (args.length < 1) {
        System.err.println("try again");
        System.exit(1);
    }*/

    GraphApiApplication main = new GraphApiApplication();
    main.run();
}

private void run(){
    SparkSession spark = SparkSession
            .builder()
            .master("spark://192.168.xx.xx:7077")
            .config("spark.mongodb.input.uri", "mongodb://192.168.xx.xx:27017/database.test_spark")
            .config("spark.database.output.uri", "mongodb://192.168.xx.xx:27017/database.test_spark")
            .config("spark.driver.allowMultipleContexts", "true")
            .appName("SparkTest")
            .getOrCreate();

    JavaSparkContext jsc = new JavaSparkContext(spark.sparkContext());

    // Create a custom WriteConfig
    Map<String, String> writeOverrides = new HashMap<String, String>();
    writeOverrides.put("collection", "spark");
    writeOverrides.put("writeConcern.w", "majority");
    WriteConfig writeConfig = WriteConfig.create(jsc).withOptions(writeOverrides);

    // Create a RDD of 10 documents
    JavaRDD<Document> sparkDocuments = jsc.parallelize(asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).map
        (new Function<Integer, Document>() {
            public Document call(final Integer i) throws Exception {
                return Document.parse("{spark: " + i + "}");
            }
        });

    System.out.println("collection : "+writeOverrides);
    MongoSpark.save(sparkDocuments, writeConfig);
    spark.stop();
}
</code>```

Log Exception here :

```<code>Exception in thread "main" org.apache.spark.SparkException: Task not serializable
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:298)
    at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:288)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:108)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2094)
    at org.apache.spark.rdd.RDD$$anonfun$map$1.apply(RDD.scala:370)
    at org.apache.spark.rdd.RDD$$anonfun$map$1.apply(RDD.scala:369)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
    at org.apache.spark.rdd.RDD.map(RDD.scala:369)
    at org.apache.spark.api.java.JavaRDDLike$class.map(JavaRDDLike.scala:93)
    at org.apache.spark.api.java.AbstractJavaRDDLike.map(JavaRDDLike.scala:45)
    at com.bdg.ebdesk.graph_api.GraphApiApplication.run(GraphApiApplication.java:60)
    at com.bdg.ebdesk.graph_api.GraphApiApplication.main(GraphApiApplication.java:37)
Caused by: java.io.NotSerializableException: com.bdg.ebdesk.graph_api.GraphApiApplication
Serialization stack:
    - object not serializable (class: com.bdg.ebdesk.graph_api.GraphApiApplication, value: com.bdg.ebdesk.graph_api.GraphApiApplication@7e0aadd0)
    - field (class: com.bdg.ebdesk.graph_api.GraphApiApplication$1, name: this$0, type: class com.bdg.ebdesk.graph_api.GraphApiApplication)
    - object (class com.bdg.ebdesk.graph_api.GraphApiApplication$1, com.bdg.ebdesk.graph_api.GraphApiApplication$1@62d363ab)
    - field (class: org.apache.spark.api.java.JavaPairRDD$$anonfun$toScalaFunction$1, name: fun$1, type: interface org.apache.spark.api.java.function.Function)
    - object (class org.apache.spark.api.java.JavaPairRDD$$anonfun$toScalaFunction$1, <function1>)
    at org.apache.spark.serializer.SerializationDebugger$.improveException(SerializationDebugger.scala:40)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:46)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:100)
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:295)
    ... 13more
</code>```

Here 'jsc' is the JavaSparkContext object I'm using. As far as I know, JavaSparkContext is not a Serializable object and one should not use it inside any functions which will be sent to the Spark workers.

Now, what I'm not able to understand is, how the instance of JavaSparkContext is being sent to the workers? What should I change in my code to avoid such scenario?

答:
When you are writing anonymous inner class, named inner class or lambda, Java creates reference to the outer class in  the inner class.

So even if the inner class is serializable, the exception can occur, the outer class must be also serializable.

Add implements Serializable to your class GraphApiApplication, because this if the outer class for anonymous inner class that is written as argument in map function

Body:
I'm trying to run the following simple Spark code:

public static void main(final String[] args)throws Exception {

    ClassLoader.getSystemClassLoader().getClass().getName();
    Thread.currentThread().getContextClassLoader().getClass().getName();
    GraphApiApplication.class.getClassLoader();

    /*if (args.length < 1) {
        System.err.println("try again");
        System.exit(1);
    }*/

    GraphApiApplication main = new GraphApiApplication();
    main.run();
}

private void run(){
    SparkSession spark = SparkSession
            .builder()
            .master("spark://192.168.xx.xx:7077")
            .config("spark.mongodb.input.uri", "mongodb://192.168.xx.xx:27017/database.test_spark")
            .config("spark.database.output.uri", "mongodb://192.168.xx.xx:27017/database.test_spark")
            .config("spark.driver.allowMultipleContexts", "true")
            .appName("SparkTest")
            .getOrCreate();

    JavaSparkContext jsc = new JavaSparkContext(spark.sparkContext());

    // Create a custom WriteConfig
    Map<String, String> writeOverrides = new HashMap<String, String>();
    writeOverrides.put("collection", "spark");
    writeOverrides.put("writeConcern.w", "majority");
    WriteConfig writeConfig = WriteConfig.create(jsc).withOptions(writeOverrides);

    // Create a RDD of 10 documents
    JavaRDD<Document> sparkDocuments = jsc.parallelize(asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).map
        (new Function<Integer, Document>() {
            public Document call(final Integer i) throws Exception {
                return Document.parse("{spark: " + i + "}");
            }
        });

    System.out.println("collection : "+writeOverrides);
    MongoSpark.save(sparkDocuments, writeConfig);
    spark.stop();
}

Log Exception here :

Exception in thread "main" org.apache.spark.SparkException: Task not serializable
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:298)
    at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:288)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:108)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2094)
    at org.apache.spark.rdd.RDD$$anonfun$map$1.apply(RDD.scala:370)
    at org.apache.spark.rdd.RDD$$anonfun$map$1.apply(RDD.scala:369)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
    at org.apache.spark.rdd.RDD.map(RDD.scala:369)
    at org.apache.spark.api.java.JavaRDDLike$class.map(JavaRDDLike.scala:93)
    at org.apache.spark.api.java.AbstractJavaRDDLike.map(JavaRDDLike.scala:45)
    at com.bdg.ebdesk.graph_api.GraphApiApplication.run(GraphApiApplication.java:60)
    at com.bdg.ebdesk.graph_api.GraphApiApplication.main(GraphApiApplication.java:37)
Caused by: java.io.NotSerializableException: com.bdg.ebdesk.graph_api.GraphApiApplication
Serialization stack:
    - object not serializable (class: com.bdg.ebdesk.graph_api.GraphApiApplication, value: com.bdg.ebdesk.graph_api.GraphApiApplication@7e0aadd0)
    - field (class: com.bdg.ebdesk.graph_api.GraphApiApplication$1, name: this$0, type: class com.bdg.ebdesk.graph_api.GraphApiApplication)
    - object (class com.bdg.ebdesk.graph_api.GraphApiApplication$1, com.bdg.ebdesk.graph_api.GraphApiApplication$1@62d363ab)
    - field (class: org.apache.spark.api.java.JavaPairRDD$$anonfun$toScalaFunction$1, name: fun$1, type: interface org.apache.spark.api.java.function.Function)
    - object (class org.apache.spark.api.java.JavaPairRDD$$anonfun$toScalaFunction$1, <function1>)
    at org.apache.spark.serializer.SerializationDebugger$.improveException(SerializationDebugger.scala:40)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:46)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:100)
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:295)
    ... 13more

Here 'jsc' is the JavaSparkContext object I'm using. As far as I know, JavaSparkContext is not a Serializable object and one should not use it inside any functions which will be sent to the Spark workers.

Now, what I'm not able to understand is, how the instance of JavaSparkContext is being sent to the workers? What should I change in my code to avoid such scenario?


问:
Image is failed to upload in Firebase storage
Can you please help me, I am trying to upload an image in FirebaseStorage.
But it fails.

My Button click Method

```<code>public void uploadImage(View view){
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent,GALLERY_INTENT);
}
</code>```

And here is onActivityResult()

```<code>   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    progressDialog.setMessage("Uploading");
    progressDialog.show();
    if(requestCode ==GALLERY_INTENT){
        final Uri uri = data.getData();
        StorageReference filepath = storageReference.child("Photos").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Toast.makeText(getApplicationContext(),"Uploaded Successfully",Toast.LENGTH_LONG).show();
               // profileImage.setImageURI(uri);
                progressDialog.dismiss();
            }
        });
    }
}
</code>```

What's wrong with this code?

答:
Try this</p>

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.e("resultCode: ", resultCode + " RequestCode: " + requestCode);
    if (resultCode == getActivity().RESULT_OK) {
        sendImageToFireBase(data.getData());
    }
}

private void saveImageToFireBase(Uri pathUri) {
    StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Photos");
    StorageReference photoRef = storageReference.child(pathUri.getLastPathSegment());
    // Upload file to Firebase Storage
    photoRef.putFile(pathUri).addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // When the image has successfully uploaded, we get its download URL
            Uri downloadUrl = taskSnapshot.getDownloadUrl();
            // Set the download URL to the message box, so that the user can send it to the database
        }
    });
}
</code>```

Body:
Can you please help me, I am trying to upload an image in FirebaseStorage.
But it fails.

My Button click Method

public void uploadImage(View view){
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent,GALLERY_INTENT);
}

And here is onActivityResult()

   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    progressDialog.setMessage("Uploading");
    progressDialog.show();
    if(requestCode ==GALLERY_INTENT){
        final Uri uri = data.getData();
        StorageReference filepath = storageReference.child("Photos").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Toast.makeText(getApplicationContext(),"Uploaded Successfully",Toast.LENGTH_LONG).show();
               // profileImage.setImageURI(uri);
                progressDialog.dismiss();
            }
        });
    }
}

What's wrong with this code?

Body:
Try this

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.e("resultCode: ", resultCode + " RequestCode: " + requestCode);
    if (resultCode == getActivity().RESULT_OK) {
        sendImageToFireBase(data.getData());
    }
}

private void saveImageToFireBase(Uri pathUri) {
    StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Photos");
    StorageReference photoRef = storageReference.child(pathUri.getLastPathSegment());
    // Upload file to Firebase Storage
    photoRef.putFile(pathUri).addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // When the image has successfully uploaded, we get its download URL
            Uri downloadUrl = taskSnapshot.getDownloadUrl();
            // Set the download URL to the message box, so that the user can send it to the database
        }
    });
}


答:
The FormCollection is how ASP.NET provides you access to the values that were just posted to your page.

You could also use a strongly typed argument and then ASP.NET MVC would use the FormCollection internally to create your strongly typed object.


问:
Convert this String to hours and minutes c#
Input value is only like this in string value and nothing else:   P0DT3H40M0S
This indicates travel time and needs to be converted to hours and minutes.
D signifies Day, T is Time (right part signifies Time, above sample was:  3 Hours And 40 Minutes and 0 Seconds. H-hours, M-Minutes, S-Seconds)
If there's a value in D, eg.  P1DT3H40M0S  - this already signifies 1 Day and 3 Hours and 40 minutes and 0 Seconds, so output should be 27 Hours and 40 minutes. How do i get the values for Days, Hours and minutes using Regex? or can i use substring? my problem is if there were 2 digit Days and Hours, substring won't work.   i need to get the numbers leftside the D, H and M.

答:
You can use TimeSpan.ParseExact to parse this string into a TimeSpan

```<code>var pattern=@"\Pd\D\Th\Hm\Ms\S";
var ts = TimeSpan.ParseExact("P01DT3H40M0S",pattern,CultureInfo.InvariantCulture);
</code>```

You can use the TimeSpan object in calculations. It supports addition, subtraction and comparison.

You can extract the total duration in hours using TotalHours. In this case, this will return 27.6666666. You can get the whole hours just by casting to int, (int)ts.TotalHours will return 27.

Copying from one of Jon Skeet's answers you can format the string as hours/minutes by using the truncated TotalHours and the Minutes, Seconds component:

```<code>String.Format("{0}:{1}:{2}",(int)ts.TotalHours,ts.Minutes,ts.Seconds)
</code>```

This will return 27:40:0

Body:
You can use TimeSpan.ParseExact to parse this string into a TimeSpan

var pattern=@"\Pd\D\Th\Hm\Ms\S";
var ts = TimeSpan.ParseExact("P01DT3H40M0S",pattern,CultureInfo.InvariantCulture);

You can use the TimeSpan object in calculations. It supports addition, subtraction and comparison.

You can extract the total duration in hours using TotalHours. In this case, this will return 27.6666666. You can get the whole hours just by casting to int, (int)ts.TotalHours will return 27.

Copying from one of Jon Skeet's answers you can format the string as hours/minutes by using the truncated TotalHours and the Minutes, Seconds component:

String.Format("{0}:{1}:{2}",(int)ts.TotalHours,ts.Minutes,ts.Seconds)

This will return 27:40:0


问:
why is my time/date picker formatting adding minutes?
I have both a time picker and a date picker in my template. The values store to my database together as one numeric string, so I have to do a few steps to parse them from one another in the right formats when I interpolate them to my template in the required places on a different page. First I call a formatting function to separate the values and then I run it through an angular-moment pipe to convert the military time to standard 12 hour time.

I noticed that consistently when I pick a time, say 7:00 or 12:00 on the time picker, it will interpolate to my template as 7:08 or 12:08. Why is it adding minutes?

THIS IS HOW I SAVE THE DATE AND TIME TO THE DATABASE

```<code>constructor(//controllers n stuff) {

//empty event object

      this.event = {
        hostName : "",
        hostId: "",
        hostPhoto : "",
        coverCharge: 0,
        drinkMin: false,
        reimburse: false,
        venue : "",
        guests : 0,
        date : "",
        time : "",
        city : "",
        eventTime : "",
        createdTime: "",
        volunteers : 0

      }
}//close constructor

addEvent(){

    let authData = OnymosAccess.getAuth(); //GET DATABASE AUTH
            this.event.hostName = authData.userName;
            this.event.hostId = authData.userId;
            this.event.hostPhoto = authData.userPhoto();
          **this.event.eventTime = new Date(this.event.date + " " + this.event.time).getTime();**
            this.event.createdTime = Date.now();

            let that = this;

                OnymosUtil.addData( //SEND TO DATABASE

        '/events/' + this.event.city + '/' + this.event.createdTime,
                        this.event,

        function optionalSuccessCallback (statusMessage) {
                            console.log(statusMessage);

                            that.saveStatus = "successfully saved";
                         },

            function optionalFailureCallback (error) {

                            that.saveStatus = "failed saving" + error;
                        });
}//end addEvent
</code>```

HTML TEMPLATE

```<code><ion-row>
                <ion-col>
                    <ion-icon name="calendar"></ion-icon>
                    <BR>
                    **{{getFormattedTime(event.eventTime, 'MM-dd-yyyy')}}**
                </ion-col>
                <ion-col>
                    <ion-icon name="clock"></ion-icon>
                    <BR>
                    **{{ getFormattedTime(event.eventTime,'HH:MM' ) | amParse:'HH:mm' | amDateFormat:'hh:mm A' }}**

                </ion-col>
</code>```

THE GET FORMATTED TIME FUNCTION I RUN THE TIME THROUGH BEFORE I USE MOMENT.

```<code>getFormattedTime (time, format) {
        var t = new Date(time);
        var tf = function (i) { return (i < 10 ? '0' : '') + i };
        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
            switch (a) {
                case 'yyyy':
                    return tf(t.getFullYear());

                case 'MM':
                    return tf(t.getMonth() + 1);

                case 'mm':
                    return tf(t.getMinutes());

                case 'dd':
                    return tf(t.getDate());

                case 'HH':
                    return tf(t.getHours());

                case 'ss':
                    return tf(t.getSeconds());

            }
        })
    } // end of getFormattedTime
</code>```

答:
The problem with your code is that you are using uppercase MM that maps to t.getMonth() instead of lowercase mm (minutes).

Anyway, since you are using momentjs, I suggest to change your getFormattedTime using moment parsing (moment(Number) to parse milliseconds) and format().

Note that, with my code, you have to use moment tokens (so uppercase YYYY for year and uppercase DD for day of month)

Here a live example:

function getFormattedTime(time, format) {
  return moment(time).format(format);
}

console.log( getFormattedTime(1499200000000, 'MM-DD-YYYY') );
console.log( getFormattedTime(1499200000000, 'HH:mm') );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

Body:
I have both a time picker and a date picker in my template. The values store to my database together as one numeric string, so I have to do a few steps to parse them from one another in the right formats when I interpolate them to my template in the required places on a different page. First I call a formatting function to separate the values and then I run it through an angular-moment pipe to convert the military time to standard 12 hour time.

I noticed that consistently when I pick a time, say 7:00 or 12:00 on the time picker, it will interpolate to my template as 7:08 or 12:08. Why is it adding minutes?

THIS IS HOW I SAVE THE DATE AND TIME TO THE DATABASE

constructor(//controllers n stuff) {

//empty event object

      this.event = {
        hostName : "",
        hostId: "",
        hostPhoto : "",
        coverCharge: 0,
        drinkMin: false,
        reimburse: false,
        venue : "",
        guests : 0,
        date : "",
        time : "",
        city : "",
        eventTime : "",
        createdTime: "",
        volunteers : 0

      }
}//close constructor

addEvent(){

    let authData = OnymosAccess.getAuth(); //GET DATABASE AUTH
            this.event.hostName = authData.userName;
            this.event.hostId = authData.userId;
            this.event.hostPhoto = authData.userPhoto();
          **this.event.eventTime = new Date(this.event.date + " " + this.event.time).getTime();**
            this.event.createdTime = Date.now();

            let that = this;

                OnymosUtil.addData( //SEND TO DATABASE

        '/events/' + this.event.city + '/' + this.event.createdTime,
                        this.event,

        function optionalSuccessCallback (statusMessage) {
                            console.log(statusMessage);

                            that.saveStatus = "successfully saved";
                         },

            function optionalFailureCallback (error) {

                            that.saveStatus = "failed saving" + error;
                        });
}//end addEvent

HTML TEMPLATE

<ion-row>
                <ion-col>
                    <ion-icon name="calendar"></ion-icon>

                    **{{getFormattedTime(event.eventTime, 'MM-dd-yyyy')}}**
                </ion-col>
                <ion-col>
                    <ion-icon name="clock"></ion-icon>

                    **{{ getFormattedTime(event.eventTime,'HH:MM' ) | amParse:'HH:mm' | amDateFormat:'hh:mm A' }}**

                </ion-col>

THE GET FORMATTED TIME FUNCTION I RUN THE TIME THROUGH BEFORE I USE MOMENT.

getFormattedTime (time, format) {
        var t = new Date(time);
        var tf = function (i) { return (i < 10 ? '0' : '') + i };
        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
            switch (a) {
                case 'yyyy':
                    return tf(t.getFullYear());

                case 'MM':
                    return tf(t.getMonth() + 1);

                case 'mm':
                    return tf(t.getMinutes());

                case 'dd':
                    return tf(t.getDate());

                case 'HH':
                    return tf(t.getHours());

                case 'ss':
                    return tf(t.getSeconds());

            }
        })
    } // end of getFormattedTime

Body:
The problem with your code is that you are using uppercase MM that maps to t.getMonth() instead of lowercase mm (minutes).

Anyway, since you are using momentjs, I suggest to change your getFormattedTime using moment parsing (moment(Number) to parse milliseconds) and format().

Note that, with my code, you have to use moment tokens (so uppercase YYYY for year and uppercase DD for day of month)

Here a live example:

function getFormattedTime(time, format) {
  return moment(time).format(format);
}

console.log( getFormattedTime(1499200000000, 'MM-DD-YYYY') );
console.log( getFormattedTime(1499200000000, 'HH:mm') );

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


问:
Create an Array from existing array with additional element added
I have a method that takes vararg Array of strings

```<code>void count(long delta, String... tags);
</code>```

I have a predefined array of tags for the most cases

```<code>String[] tags = { "foo_tag:Foo",
                  "bar_tag:Bar",
                  "baz_tag:Baz"
                };
</code>```

and only one tag to be added to predefined tags in each call "project_id:12345"

So the call of count should look like this:

```<code>count(delta, "foo_tag:Foo", "bar_tag:Bar", "baz_tag:Baz", "project_id:12345");
</code>```

How can I simply create a new array containing my existing one plus additional element just in place of calling the method?

Something like this hypothetical Arrays.append method:

```<code>count(delta, Arrays.append(tags, "project_id:12345"));
</code>```

This is storing statistics operation, not a business logic, so I want this operation to be as fast as possible.

Currently, I have helper method appendTag, but it doesn't look elegant as for me

```<code>private String[] appendTag(String[] tags, String s)
{
    String[] result = new String[tags.length + 1];
    System.arraycopy(tags, 0, result, 0, tags.length);
    result[result.length-1] = s;
    return result;
}
</code>```

答:
There is no easy way to expand an array by one element and add something new.  But if you were working with a list instead, you could easily add a new element and then convert it to an array when calling the method:

```<code>String[] tags = { "foo_tag:Foo",
                  "bar_tag:Bar",
                  "baz_tag:Baz"
                };
List<String> tagList = new ArrayList<String>(Arrays.asList(tags));
tagList.add("project_id:12345");

count(delta, tagList.toArray(new String[0]));
</code>```

If you think you will have a long term need for this, then perhaps consider changing the implementation of count() to use a list instead of an array.  You could also overload this method and expose a version which accepts list instead of array.

Body:
I have a method that takes vararg Array of strings

void count(long delta, String... tags);

I have a predefined array of tags for the most cases

String[] tags = { "foo_tag:Foo",
                  "bar_tag:Bar",
                  "baz_tag:Baz"
                };

and only one tag to be added to predefined tags in each call "project_id:12345"

So the call of count should look like this:

count(delta, "foo_tag:Foo", "bar_tag:Bar", "baz_tag:Baz", "project_id:12345");

How can I simply create a new array containing my existing one plus additional element just in place of calling the method?

Something like this hypothetical Arrays.append method:

count(delta, Arrays.append(tags, "project_id:12345"));

This is storing statistics operation, not a business logic, so I want this operation to be as fast as possible.

Currently, I have helper method appendTag, but it doesn't look elegant as for me

private String[] appendTag(String[] tags, String s)
{
    String[] result = new String[tags.length + 1];
    System.arraycopy(tags, 0, result, 0, tags.length);
    result[result.length-1] = s;
    return result;
}

Body:
There is no easy way to expand an array by one element and add something new.  But if you were working with a list instead, you could easily add a new element and then convert it to an array when calling the method:

String[] tags = { "foo_tag:Foo",
                  "bar_tag:Bar",
                  "baz_tag:Baz"
                };
List<String> tagList = new ArrayList<String>(Arrays.asList(tags));
tagList.add("project_id:12345");

count(delta, tagList.toArray(new String[0]));

If you think you will have a long term need for this, then perhaps consider changing the implementation of count() to use a list instead of an array.  You could also overload this method and expose a version which accepts list instead of array.


问:
.slice() doesn't work with foreach loop
I have a problem with button "load more" for elements in the foreach loop. Normally without foreach loop .slice() is working fine. Now .slice(0,4) is showing only first element. Is there any way to do this with the loop?
My code:

```<code>$info=$wpdb->get_results('SELECT user_login FROM wp_users WHERE company_district="London"');
 foreach ($info as $info_res) {
        $id             = $info_res->id;
        $login      = $info_res->user_login;
        echo '<div id="comment" style="display:none;"><p>'.$login.'</p></div>';

    }

    ?>
</code>```

And Script:

```<code><a href="#" id="loadMore">Load More</a>

<script>
$(function () {
    $("#comment").slice(0, 4).show();
    $("#loadMore").on('click', function (e) {
        e.preventDefault();
        $("#comment:hidden").slice(0, 4).slideDown();
        if ($("#comment:hidden").length == 0) {
            $("#load").fadeOut('fast');
        }
        $('html,body').animate({
            scrollTop: $(this).offset().top
        }, 1500);
    });
});
</script>
</code>```

I want to show first 4 elements, then after click show more or all.

答:
Moved solution from question to answer:

Problem solved. Thanks. ID must be unique. I used class instead of ID.

Title: .slice() doesn't work with foreach loop

Body:
I have a problem with button "load more" for elements in the foreach loop. Normally without foreach loop .slice() is working fine. Now .slice(0,4) is showing only first element. Is there any way to do this with the loop?
My code:

$info=$wpdb->get_results('SELECT user_login FROM wp_users WHERE company_district="London"');
 foreach ($info as $info_res) {
        $id             = $info_res->id;
        $login      = $info_res->user_login;
        echo '

'.$login.'

';

    }

    ?>

And Script:

Load More

I want to show first 4 elements, then after click show more or all.


问:
How to invoke a function within document.ready in Angular 4
When I try to invoke a function outside document ready is works but doesn't works inside.

```<code>ngOnInit() {
      this.addItems(0, 2);
      $(document).ready(() => {
         if($('html').hasClass('fp-enabled')){
                $.fn.fullpage.destroy('all');
            }
        $('#fullpage').fullpage({
            onLeave: (index, nextIndex, direction) => {
                this.no_of_post = 5;
                if(direction == 'down' && index+1 >= this.no_of_post){
                    const start = this.no_of_post;
                    this.no_of_post += 1;
                    this.addItems(start, index+2);
                    console.log(index+1);
                }
            }
        });
      });
  }

addItems(startIndex, endIndex) {
    for (let i = startIndex; i < endIndex; ++i) {
        this.newService.fetchData().subscribe(data=>{
           this.single_post = data[i];
           this.posts.push(this.single_post);
        });
    }
  }
</code>```

The above code works but when I move the this.addItems(0, 2); within $(document).ready(() => { it doesn't work.

答:
Try this </p>

```<code>constructor(
    private zone: NgZone
) {}

ngOnInit() {
    this.zone.run(() => {
        // Your code here, stub for the sake of the example
        document.ready = () => {
            console.log('Code ran when document is ready, and stays in the scope of Angular.');
        };
    });
}
</code>```

Body:
When I try to invoke a function outside document ready is works but doesn't works inside.

ngOnInit() {
      this.addItems(0, 2);
      $(document).ready(() => {
         if($('html').hasClass('fp-enabled')){
                $.fn.fullpage.destroy('all');
            }
        $('#fullpage').fullpage({
            onLeave: (index, nextIndex, direction) => {
                this.no_of_post = 5;
                if(direction == 'down' && index+1 >= this.no_of_post){
                    const start = this.no_of_post;
                    this.no_of_post += 1;
                    this.addItems(start, index+2);
                    console.log(index+1);
                }
            }
        });
      });
  }

addItems(startIndex, endIndex) {
    for (let i = startIndex; i < endIndex; ++i) {
        this.newService.fetchData().subscribe(data=>{
           this.single_post = data[i];
           this.posts.push(this.single_post);
        });
    }
  }

The above code works but when I move the this.addItems(0, 2); within $(document).ready(() => { it doesn't work.

Body:
Try this

constructor(
    private zone: NgZone
) {}

ngOnInit() {
    this.zone.run(() => {
        // Your code here, stub for the sake of the example
        document.ready = () => {
            console.log('Code ran when document is ready, and stays in the scope of Angular.');
        };
    });
}


问:
Java error: Only a type can be imported. XYZ resolves to a package
I get the error: "Only a type can be imported. XYZ resolves to a package."

Someone has explained the cause here but I am not sure what I supposed to do to fix this. FYI: I am using Eclipse. I have added the code that does the importing below. The java.util.* import works fine.

```<code> <%@ page import="java.util.*"%>
 <%@ page import="org.eresearch.knowledgeportal.model.Category"%>
 <%@ page import="org.eresearch.knowledgeportal.dao.CategoryDao"%>

 <%
  CategoryDao catDao = new CategoryDao();
  ArrayList<Category> catList = catDao.selectCategory();

 //
 %>
</code>```

Edit: the actual error is below:

```<code> org.apache.jasper.JasperException: Unable to compile class for JSP:

 An error occurred at line: 7 in the generated java file
 Only a type can be imported. org.eresearch.knowledgeportal.model.Category resolves to a package
</code>```

答:
This typically happens when mixing (in the same jsp page) static jsp import:

```<code><%@include file="...
</code>```

with dynamic jsp import:

```<code><jsp:include page="...
</code>```

and your type has been already imported by the "static imported" jsp. When the same type needs to be used (and then imported) by the "dynamically imported" jsp -> this generate the Exception: "Only a type can be imported..."

Body:
I get the error: "Only a type can be imported. XYZ resolves to a package."

Someone has explained the cause here but I am not sure what I supposed to do to fix this. FYI: I am using Eclipse. I have added the code that does the importing below. The java.util.* import works fine.

 <%@ page import="java.util.*"%>
 <%@ page import="org.eresearch.knowledgeportal.model.Category"%>
 <%@ page import="org.eresearch.knowledgeportal.dao.CategoryDao"%>

 <%
  CategoryDao catDao = new CategoryDao();
  ArrayList<Category> catList = catDao.selectCategory();

 //
 %>

Edit: the actual error is below:

 org.apache.jasper.JasperException: Unable to compile class for JSP:

 An error occurred at line: 7 in the generated java file
 Only a type can be imported. org.eresearch.knowledgeportal.model.Category resolves to a package

Body:
This typically happens when mixing (in the same jsp page) static jsp import:

<%@include file="...

with dynamic jsp import:

<jsp:include page="...

and your type has been already imported by the "static imported" jsp. When the same type needs to be used (and then imported) by the "dynamically imported" jsp -> this generate the Exception: "Only a type can be imported..."


问:
invalid conversion from 'DWORD (*)(void*)' to 'DWORD (*)(void*)'
invalid conversion from 'DWORD (*)(void*)' to 'DWORD (*)(void*)' .
cake==lie
1==0

I have no idea what this means ... I get it in this code

```<code>HANDLE CPlugin::CreateWinampThread()    ||
{                                  __VVVVVVVV__
    hWinampThreadHandle = (HANDLE)CreateThread(NULL, 0, StartWinampThread, (void*)this, 0, &dwWinampThreadID);
    if (!hWinampThreadHandle)
        return 0;

     CloseHandle(hWinampThreadHandle);
     return hWinampThreadHandle;
}

.

DWORD  WINAPI CPlugin::StartWinampThread(void* lpParam)[...]
</code>```

答: StartWinampThread must be static if it is member function.</p>

Body:
invalid conversion from 'DWORD (*)(void*)' to 'DWORD (*)(void*)' .
cake==lie
1==0

I have no idea what this means ... I get it in this code

HANDLE CPlugin::CreateWinampThread()    ||
{                                  __VVVVVVVV__
    hWinampThreadHandle = (HANDLE)CreateThread(NULL, 0, StartWinampThread, (void*)this, 0, &dwWinampThreadID);
    if (!hWinampThreadHandle)
        return 0;

     CloseHandle(hWinampThreadHandle);
     return hWinampThreadHandle;
}

.

DWORD  WINAPI CPlugin::StartWinampThread(void* lpParam)[...]


问:
Websocket (spring) ssl connection (empty chain)
Good day! I have a simple chat application with websocket (STOMP).
I have configured ssl connection with mutal auth.

Server side:

```<code>server.port=8443
server.ssl.key-store=path/to/server.jks
server.ssl.trust-store=path/to/trusted.jks
server.ssl.key-store-password=22222222
server.ssl.trust-store-password=22222222
server.ssl.client-auth=need
</code>```

client :

```<code>System.setProperty("javax.net.ssl.keyStore","path/to/client.jks");
System.setProperty("javax.net.ssl.keyStorePassword","22222222");
System.setProperty("javax.net.ssl.trustStore","path/to/trusted.jks");
System.setProperty("javax.net.ssl.trustStorePassword","22222222");
</code>```

server trusted.jks and client trusted.jks are the same.

so when I try to connect with

```<code>-Djavax.net.debug=ssl
</code>```

I get lots of output and some strange situation - I can see two(?) key-agreements. The first one goes ok -

```<code>  trustStore is: /path/to/trusted.jks

adding as trusted cert:
  Subject: EMAILADDRESS=ca@ca.com, CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=RU
  Issuer:  EMAILADDRESS=ca@ca.com, CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=RU
  Algorithm: RSA; Serial number: 0x9952f188496b2545
  Valid from Wed Jun 28 15:39:04 MSK 2017 until Sat Jun 26 15:39:04 MSK 2027
</code>```

So my CA cert is added as trusted. Then

```<code>*** ClientHello, TLSv1.2
//ok
*** ServerHello, TLSv1.2
//ok
*** Certificate chain
//my localhost server cert
***
Found trusted certificate:

 Version: V3
 Subject: EMAILADDRESS=ca@ca.com, CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=RU
 Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11
</code>```

So my client found trusted certificate for this server certificate.

```<code>*** ECDH ServerKeyExchange
//ok
*** CertificateRequest
Cert Types: RSA, DSS, ECDSA
Supported Signature Algorithms: SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA, SHA256withECDSA, SHA256withRSA, SHA256withDSA, SHA224withECDSA, SHA224withRSA, SHA224withDSA, SHA1withECDSA, SHA1withRSA, SHA1withDSA
Cert Authorities:
</code>```

```<code>*** ServerHelloDone
</code>```

And I can find my CHAIN -

```<code>*** Certificate chain
chain [0] = [
[
  Version: V3
  Subject: EMAILADDRESS=client3@mail.ru, CN=client3, OU=client3, O=client3, L=client3, ST=client3, C=RU
  Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11

chain [1] = [
[
  Version: V3
  Subject: EMAILADDRESS=ca@ca.com, CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=RU
  Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11
*** ECDHClientKeyExchange
*** CertificateVerify
*** Finished
</code>```

As far as I know - this is ok.
Then I can see:

```<code>DEBUG org.springframework.web.client.RestTemplate - GET request for "https://localhost:8443/chat/info" resulted in 200 (null)
DEBUG org.springframework.web.socket.sockjs.client.WebSocketTransport - Starting WebSocket session on wss://localhost:8443/chat/437/f6158d1ee84b4c53ba55a6810b2f92a8/websocket
DEBUG org.springframework.web.socket.client.standard.StandardWebSocketClient -
Connecting to wss://localhost:8443/chat/437/f6158d1ee84b4c53ba55a6810b2f92a8/websocket
</code>```

Again adding trust store certificate and so on, all is the same, but

```<code>*** CertificateRequest
Cert Types: RSA, DSS, ECDSA
Supported Signature Algorithms: SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA, SHA256withECDSA, SHA256withRSA, SHA256withDSA, SHA224withECDSA, SHA224withRSA, SHA224withDSA, SHA1withECDSA, SHA1withRSA, SHA1withDSA
Cert Authorities:
<EMAILADDRESS=ca@ca.com, CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=RU>
*** ServerHelloDone
Warning: no suitable certificate found - continuing without client authentication
*** Certificate chain
<Empty>
***
</code>```

So the server says to me

```<code>ttps-jsse-nio-8443-exec-9, fatal error: 42: null cert chain
javax.net.ssl.SSLHandshakeException: null cert chain
</code>```

Any thoughts about problem? If it is needed I can post my keystores and client implementation here.
Thank you for help!

UPDATE with curl output

```<code> env -i curl -E ./chain.pem --key ./client.key --cacert ca.crt --verbose --user test:test  https://localhost:8443/

*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8443 (#0)
* found 1 certificates in ca.crt
* found 704 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ECDHE_RSA_AES_128_GCM_SHA256
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: localhost (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject:

C=RU,ST=localhost,
L=localhost,O=localhost,OU=localhost,
CN=localhost,EMAIL=localhost@mail.com
*    start date: Wed, 28 Jun 2017 13:07:14 GMT
*    expire date: Thu, 28 Jun 2018 13:07:14 GMT
*    issuer: C=RU,ST=ca,L=ca,O=ca,OU=ca,CN=ca,EMAIL=ca@ca.com
*    compression: NULL
* ALPN, server did not agree to a protocol
* Server auth using Basic with user 'kitcpp'
> GET / HTTP/1.1
> Host: localhost:8443
> Authorization: Basic a2l0Y3BwOmtpdGNwcA==
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 200
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< Strict-Transport-Security: max-age=31536000 ; includeSubDomains
< X-Frame-Options: DENY
< Set-Cookie: JSESSIONID=67BACDE78AF68627516075B29C987C86; Path=/; Secure; HttpOnly
< Last-Modified: Wed, 28 Jun 2017 16:29:53 GMT
 < Accept-Ranges: bytes
< Content-Type: text/html;charset=UTF-8
< Content-Language: en-US
< Content-Length: 6935
< Date: Fri, 30 Jun 2017 09:30:02 GMT
<
<!DOCTYPE html>
<html>
<head>
//and so on (my web chat page)
</code>```

答:
You are using Tomcat's WebSocket client. Its documentation describes how it should be configured to use SSL:

When using the WebSocket client to connect to secure server endpoints, the client SSL configuration is controlled by the userProperties of the provided javax.websocket.ClientEndpointConfig. The following user properties are supported:

org.apache.tomcat.websocket.SSL_CONTEXT

org.apache.tomcat.websocket.SSL_PROTOCOLS

org.apache.tomcat.websocket.SSL_TRUSTSTORE

org.apache.tomcat.websocket.SSL_TRUSTSTORE_PWD

…

If the org.apache.tomcat.websocket.SSL_CONTEXT property is set then the org.apache.tomcat.websocket.SSL_TRUSTSTORE and org.apache.tomcat.websocket.SSL_TRUSTSTORE_PWD properties will be ignored.

You're using Spring's WebSocket and it is creating the ClientEndpointConfig for you. To configure its user properties you set them on the StandardWebSocketClient and it will then use them when it creates the ClientEndpointConfig. For example, assuming that the default SSL context is sufficient:

```<code>StandardWebSocketClient simpleWebSocketClient =
        new StandardWebSocketClient();
Map<String, Object> userProperties = new HashMap<>();
userProperties.put("org.apache.tomcat.websocket.SSL_CONTEXT", SSLContext.getDefault());
simpleWebSocketClient.setUserProperties(userProperties);
</code>```

Body:
Good day! I have a simple chat application with websocket (STOMP).
I have configured ssl connection with mutal auth.

Server side:

server.port=8443
server.ssl.key-store=path/to/server.jks
server.ssl.trust-store=path/to/trusted.jks
server.ssl.key-store-password=22222222
server.ssl.trust-store-password=22222222
server.ssl.client-auth=need

client :

System.setProperty("javax.net.ssl.keyStore","path/to/client.jks");
System.setProperty("javax.net.ssl.keyStorePassword","22222222");
System.setProperty("javax.net.ssl.trustStore","path/to/trusted.jks");
System.setProperty("javax.net.ssl.trustStorePassword","22222222");

server trusted.jks and client trusted.jks are the same.

so when I try to connect with

-Djavax.net.debug=ssl

I get lots of output and some strange situation - I can see two(?) key-agreements. The first one goes ok -

  trustStore is: /path/to/trusted.jks

adding as trusted cert:
  Subject: EMAILADDRESS=ca@ca.com, CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=RU
  Issuer:  EMAILADDRESS=ca@ca.com, CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=RU
  Algorithm: RSA; Serial number: 0x9952f188496b2545
  Valid from Wed Jun 28 15:39:04 MSK 2017 until Sat Jun 26 15:39:04 MSK 2027

So my CA cert is added as trusted. Then

*** ClientHello, TLSv1.2
//ok
*** ServerHello, TLSv1.2
//ok
*** Certificate chain
//my localhost server cert
***
Found trusted certificate:

 Version: V3
 Subject: EMAILADDRESS=ca@ca.com, CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=RU
 Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11

So my client found trusted certificate for this server certificate.

*** ECDH ServerKeyExchange
//ok
*** CertificateRequest
Cert Types: RSA, DSS, ECDSA
Supported Signature Algorithms: SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA, SHA256withECDSA, SHA256withRSA, SHA256withDSA, SHA224withECDSA, SHA224withRSA, SHA224withDSA, SHA1withECDSA, SHA1withRSA, SHA1withDSA
Cert Authorities:

*** ServerHelloDone

And I can find my CHAIN -

*** Certificate chain
chain [0] = [
[
  Version: V3
  Subject: EMAILADDRESS=client3@mail.ru, CN=client3, OU=client3, O=client3, L=client3, ST=client3, C=RU
  Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11

chain [1] = [
[
  Version: V3
  Subject: EMAILADDRESS=ca@ca.com, CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=RU
  Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11
*** ECDHClientKeyExchange
*** CertificateVerify
*** Finished

As far as I know - this is ok.
Then I can see:

DEBUG org.springframework.web.client.RestTemplate - GET request for "https://localhost:8443/chat/info" resulted in 200 (null)
DEBUG org.springframework.web.socket.sockjs.client.WebSocketTransport - Starting WebSocket session on wss://localhost:8443/chat/437/f6158d1ee84b4c53ba55a6810b2f92a8/websocket
DEBUG org.springframework.web.socket.client.standard.StandardWebSocketClient -
Connecting to wss://localhost:8443/chat/437/f6158d1ee84b4c53ba55a6810b2f92a8/websocket

Again adding trust store certificate and so on, all is the same, but

*** CertificateRequest
Cert Types: RSA, DSS, ECDSA
Supported Signature Algorithms: SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA, SHA256withECDSA, SHA256withRSA, SHA256withDSA, SHA224withECDSA, SHA224withRSA, SHA224withDSA, SHA1withECDSA, SHA1withRSA, SHA1withDSA
Cert Authorities:
<EMAILADDRESS=ca@ca.com, CN=ca, OU=ca, O=ca, L=ca, ST=ca, C=RU>
*** ServerHelloDone
Warning: no suitable certificate found - continuing without client authentication
*** Certificate chain
<Empty>
***

So the server says to me

ttps-jsse-nio-8443-exec-9, fatal error: 42: null cert chain
javax.net.ssl.SSLHandshakeException: null cert chain

Any thoughts about problem? If it is needed I can post my keystores and client implementation here.
Thank you for help!

UPDATE with curl output

 env -i curl -E ./chain.pem --key ./client.key --cacert ca.crt --verbose --user test:test  https://localhost:8443/

*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8443 (#0)
* found 1 certificates in ca.crt
* found 704 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ECDHE_RSA_AES_128_GCM_SHA256
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: localhost (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject:

C=RU,ST=localhost,
L=localhost,O=localhost,OU=localhost,
CN=localhost,EMAIL=localhost@mail.com
*    start date: Wed, 28 Jun 2017 13:07:14 GMT
*    expire date: Thu, 28 Jun 2018 13:07:14 GMT
*    issuer: C=RU,ST=ca,L=ca,O=ca,OU=ca,CN=ca,EMAIL=ca@ca.com
*    compression: NULL
* ALPN, server did not agree to a protocol
* Server auth using Basic with user 'kitcpp'
> GET / HTTP/1.1
> Host: localhost:8443
> Authorization: Basic a2l0Y3BwOmtpdGNwcA==
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 200
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< Strict-Transport-Security: max-age=31536000 ; includeSubDomains
< X-Frame-Options: DENY
< Set-Cookie: JSESSIONID=67BACDE78AF68627516075B29C987C86; Path=/; Secure; HttpOnly
< Last-Modified: Wed, 28 Jun 2017 16:29:53 GMT
 < Accept-Ranges: bytes
< Content-Type: text/html;charset=UTF-8
< Content-Language: en-US
< Content-Length: 6935
< Date: Fri, 30 Jun 2017 09:30:02 GMT
<
<!DOCTYPE html>

//and so on (my web chat page)

Body:
You are using Tomcat's WebSocket client. Its documentation describes how it should be configured to use SSL:

When using the WebSocket client to connect to secure server endpoints, the client SSL configuration is controlled by the userProperties of the provided javax.websocket.ClientEndpointConfig. The following user properties are supported:

org.apache.tomcat.websocket.SSL_CONTEXT

org.apache.tomcat.websocket.SSL_PROTOCOLS

org.apache.tomcat.websocket.SSL_TRUSTSTORE

org.apache.tomcat.websocket.SSL_TRUSTSTORE_PWD

…

If the org.apache.tomcat.websocket.SSL_CONTEXT property is set then the org.apache.tomcat.websocket.SSL_TRUSTSTORE and org.apache.tomcat.websocket.SSL_TRUSTSTORE_PWD properties will be ignored.

You're using Spring's WebSocket and it is creating the ClientEndpointConfig for you. To configure its user properties you set them on the StandardWebSocketClient and it will then use them when it creates the ClientEndpointConfig. For example, assuming that the default SSL context is sufficient:

StandardWebSocketClient simpleWebSocketClient =
        new StandardWebSocketClient();
Map<String, Object> userProperties = new HashMap<>();
userProperties.put("org.apache.tomcat.websocket.SSL_CONTEXT", SSLContext.getDefault());
simpleWebSocketClient.setUserProperties(userProperties);


问:
Create a .csv file with values from a Python list
I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this

```<code>[u'value 1', u'value 2', ...]
</code>```

If I iterate through the values in the list i.e. for v in mylist: print v they appear to be plain text.

And I can put a , between each with print ','.join(mylist)

And I can output to a file, i.e.

```<code>myfile = open(...)
print >>myfile, ','.join(mylist)
</code>```

But I want to output to a CSV and have delimiters around the values in the list e.g.

```<code>"value 1", "value 2", ...
</code>```

I can't find an easy way to include the delimiters in the formatting, e.g. I have tried through the join statement. How can I do this?

答:
For another approach, you can use DataFrame in pandas:
And it can easily dump the data to csv just like the code below:</p>

```<code>import pandas
df = pandas.DataFrame(data={"col1": list_1, "col2": list_2})
df.to_csv("./file.csv", sep=',',index=False)
</code>```

Body:
I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this

[u'value 1', u'value 2', ...]

If I iterate through the values in the list i.e. for v in mylist: print v they appear to be plain text.

And I can put a , between each with print ','.join(mylist)

And I can output to a file, i.e.

myfile = open(...)
print >>myfile, ','.join(mylist)

But I want to output to a CSV and have delimiters around the values in the list e.g.

"value 1", "value 2", ...

I can't find an easy way to include the delimiters in the formatting, e.g. I have tried through the join statement. How can I do this?

Body:
For another approach, you can use DataFrame in pandas:
And it can easily dump the data to csv just like the code below:

import pandas
df = pandas.DataFrame(data={"col1": list_1, "col2": list_2})
df.to_csv("./file.csv", sep=',',index=False)


问:
Coordinates in WPF Canvas
when defining coordinates for canvas shapes in XAML files, is it possible to do something like this:

```<code><Canvas x:Name="myCanvas"
        DockPanel.Dock="Bottom"
        VerticalAlignment="Stretch">

    <Canvas.Background>
        <SolidColorBrush Color="White" Opacity="100" />
    </Canvas.Background>

    <Ellipse x:Name="ell1"
                Width="30"
                Height="30"
                Stroke="Black"
                StrokeThickness="1"
                Fill="Red"
                Canvas.Left="100"
                Canvas.Top="50" />

    <Ellipse x:Name="ell2"
                Width="30"
                Height="30"
                Stroke="Black"
                StrokeThickness="1"
                Fill="Red"
                Canvas.Right="100"
                Canvas.Top="50" />

    <Line Stroke="Black"
            StrokeThickness="1"
            X1="ell1.Canvas.Right"                              *** look here ***
            Y1="ell1.Canvas.Top + ell1.Height/2"                *** look here ***
            X2="ell2.Canvas.Left"                               *** look here ***
            Y2="ell2.Canvas.Top + ell2.Height/2" />             *** look here ***

</Canvas>
</code>```

Or the only way of doing it is through C#?

Thanks,
Massimo

答:
This should generate the desired result without too much hassle. You may have to adjust the Margin of the Grid.

```<code><Grid DockPanel.Dock="Bottom" Margin="100,50">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>

    <Ellipse Grid.Column="0" Width="30" Height="30"
             Stroke="Black" StrokeThickness="1" Fill="Red"/>

    <Ellipse Grid.Column="2" Width="30" Height="30"
             Stroke="Black" StrokeThickness="1" Fill="Red"/>

    <Rectangle Grid.Column="1" Fill="Black" Height="1"/>
</Grid>
</code>```

This is even simpler:

```<code><DockPanel DockPanel.Dock="Bottom" Margin="100,50">

    <Ellipse DockPanel.Dock="Left" Width="30" Height="30"
             Stroke="Black" StrokeThickness="1" Fill="Red"/>

    <Ellipse DockPanel.Dock="Right" Grid.Column="2" Width="30" Height="30"
             Stroke="Black" StrokeThickness="1" Fill="Red"/>

    <Rectangle Fill="Black" Height="1"/>
</DockPanel>
</code>```

Title: Coordinates in WPF Canvas

Body:
when defining coordinates for canvas shapes in XAML files, is it possible to do something like this:

<Canvas x:Name="myCanvas"
        DockPanel.Dock="Bottom"
        VerticalAlignment="Stretch">

    <Canvas.Background>
        <SolidColorBrush Color="White" Opacity="100" />
    </Canvas.Background>

    <Ellipse x:Name="ell1"
                Width="30"
                Height="30"
                Stroke="Black"
                StrokeThickness="1"
                Fill="Red"
                Canvas.Left="100"
                Canvas.Top="50" />

    <Ellipse x:Name="ell2"
                Width="30"
                Height="30"
                Stroke="Black"
                StrokeThickness="1"
                Fill="Red"
                Canvas.Right="100"
                Canvas.Top="50" />

    <Line Stroke="Black"
            StrokeThickness="1"
            X1="ell1.Canvas.Right"                              *** look here ***
            Y1="ell1.Canvas.Top + ell1.Height/2"                *** look here ***
            X2="ell2.Canvas.Left"                               *** look here ***
            Y2="ell2.Canvas.Top + ell2.Height/2" />             *** look here ***

</Canvas>

Or the only way of doing it is through C#?

Thanks,
Massimo

Body:
This should generate the desired result without too much hassle. You may have to adjust the Margin of the Grid.

<Grid DockPanel.Dock="Bottom" Margin="100,50">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>

    <Ellipse Grid.Column="0" Width="30" Height="30"
             Stroke="Black" StrokeThickness="1" Fill="Red"/>

    <Ellipse Grid.Column="2" Width="30" Height="30"
             Stroke="Black" StrokeThickness="1" Fill="Red"/>

    <Rectangle Grid.Column="1" Fill="Black" Height="1"/>
</Grid>

This is even simpler:

<DockPanel DockPanel.Dock="Bottom" Margin="100,50">

    <Ellipse DockPanel.Dock="Left" Width="30" Height="30"
             Stroke="Black" StrokeThickness="1" Fill="Red"/>

    <Ellipse DockPanel.Dock="Right" Grid.Column="2" Width="30" Height="30"
             Stroke="Black" StrokeThickness="1" Fill="Red"/>

    <Rectangle Fill="Black" Height="1"/>
</DockPanel>


问:
pymssql windows authentication
The pymssql module used to support windows authentication. Now it seems it does not. Though in some places it still shows that it should work. I have been unable to find a definitive answer to this problem, nor a solution. Most relevant link:

https://groups.google.com/forum/#!topic/pymssql/QDMLTGBNeU0

pymssql 1.0 supported it because it made use of and depended on the
  MS-provided DLL which was part of the SQL Server client stack. This
  stack was in charge of handling all of the NTLM negotiation and such.
  This meant, among other things that it was a Windows-only solution.

I can simulate many sorts of network environments so I have tried many different setups. I am trying to be able to use this script to connect to a remote MSSQL server using windows authentication. And this is the problem.

According to my research, including the links above, there are two ways to use windows authentication with the pymssql module that are supposed to work.

First Method: Using the current users credentials:

```<code>pymssql.connect(server='server')
# credentials come from active windows session
# some research shows that a "trusted=True" keyword should be provided.
</code>```

Second Method: Using a given users credentials:

```<code>pymssql.connect(server='server', user=r'domain\user', password='pass')
# credentials are given in code and somehow converted to a
# windows authentication in the background
# some research shows that a "trusted=True" keyword should be provided.
</code>```

The same goes for using the _mssql module.

NOTES:

Python version: 2.7.8

Version of pymssql I am using: 2.1.1

Version of pymssql that used to support windows authentication: 1.x

I have tested with (All 64 bit):

windows 7 professional

windows 7 home premium

windows server 2012

windows server 2012R2

Other questions on the topic:

pymssql: How to use windows authentication when running on a non-windows box

Unable to connect using pymssql with windows authentication

https://stackoverflow.com/questions/27692366/mssql-python-windows-authentication

答:
Seems it work now.
Python 3.6,
Windows 10.</p>

```<code>conn = pymssql.connect(server='(local)', database='DbName')
</code>```

Title: pymssql windows authentication

Body:
The pymssql module used to support windows authentication. Now it seems it does not. Though in some places it still shows that it should work. I have been unable to find a definitive answer to this problem, nor a solution. Most relevant link:

https://groups.google.com/forum/#!topic/pymssql/QDMLTGBNeU0

pymssql 1.0 supported it because it made use of and depended on the
  MS-provided DLL which was part of the SQL Server client stack. This
  stack was in charge of handling all of the NTLM negotiation and such.
  This meant, among other things that it was a Windows-only solution.

I can simulate many sorts of network environments so I have tried many different setups. I am trying to be able to use this script to connect to a remote MSSQL server using windows authentication. And this is the problem.

According to my research, including the links above, there are two ways to use windows authentication with the pymssql module that are supposed to work.

First Method: Using the current users credentials:

pymssql.connect(server='server')
# credentials come from active windows session
# some research shows that a "trusted=True" keyword should be provided.

Second Method: Using a given users credentials:

pymssql.connect(server='server', user=r'domain\user', password='pass')
# credentials are given in code and somehow converted to a
# windows authentication in the background
# some research shows that a "trusted=True" keyword should be provided.

The same goes for using the _mssql module.

NOTES:

Python version: 2.7.8

Version of pymssql I am using: 2.1.1

Version of pymssql that used to support windows authentication: 1.x

I have tested with (All 64 bit):

windows 7 professional

windows 7 home premium

windows server 2012

windows server 2012R2

Other questions on the topic:

pymssql: How to use windows authentication when running on a non-windows box

Unable to connect using pymssql with windows authentication

https://stackoverflow.com/questions/27692366/mssql-python-windows-authentication

Body:
Seems it work now.
Python 3.6,
Windows 10.

conn = pymssql.connect(server='(local)', database='DbName')


问:
Prefix for testing methods in Unit: "test" vs "should"
It is a common practice to prefix the tests method names in JUnit with "test". But in the last few years, some people changed this to the prefix "should".

If I want to test the customer creation in a database, I would normally name the method "testCustomerCreation". However, some people would name "shouldCreateCustomer".

This is a lot of personal taste when I am the only person in the project or when everyone else in the project agrees with me. But when/where this is not the case, some divergences or inconsistent mixes starts to shows up.

I readed somewhere an article of a guy that named his methods like "testShouldCreateCustomer", and for this reason he decided to drop the "test" prefix. But in fact he wasn't prefixing with "test", he was using "testShould" and changed to "should". Obviously, this did not convinced me.

I am personally strongly inclined to stick to "test" prefix because the methods names normally starts with verbs in the infinitive form ("get", "set", "add", "remove", "clear", "send", "receive", "open", "close", "read", "write", "create", "list", "pop", "print", etc, so is "test"). So, prefixing a method name with "should" makes it sound really very strange for me, looks wrong.

So, what is the real good reason to use "should" instead of "test"? What are the great advantages and disadvantages?

答:
The 'Should' convention is aligned with the behaviour driven development style of testing.

I personally really prefer to write tests in this style, as it encourages you to write tests that read as specifications, and are more aligned with the behaviour of the class or system that you are testing.

Where possible, I sometimes go one step further and give the test class even more context using it's name:

```<code>class ANewlyCreatedAccount {
  shouldHaveAZeroBalance() {}
  shouldCalculateItsOwnInterest() {}
}
</code>```

By naming your classes and thinking about them in this specification style, this can give you a lot of guidance on which tests to write, and in which order you should write the tests and make them green.

Yes, 'should' vs 'test' is just a prefix and it's important to be consistent, but this question is also about the style and mindset of how you test your code and choose which tests to write.  BDD has a ton of value, so I suggest reading further and give this a try.

Body:
The 'Should' convention is aligned with the behaviour driven development style of testing.

I personally really prefer to write tests in this style, as it encourages you to write tests that read as specifications, and are more aligned with the behaviour of the class or system that you are testing.

Where possible, I sometimes go one step further and give the test class even more context using it's name:

class ANewlyCreatedAccount {
  shouldHaveAZeroBalance() {}
  shouldCalculateItsOwnInterest() {}
}

By naming your classes and thinking about them in this specification style, this can give you a lot of guidance on which tests to write, and in which order you should write the tests and make them green.

Yes, 'should' vs 'test' is just a prefix and it's important to be consistent, but this question is also about the style and mindset of how you test your code and choose which tests to write.  BDD has a ton of value, so I suggest reading further and give this a try.


问:
Drag
 between two
 JS (without jQuery)
I am trying to build two ul in JS and HTML and drag li between them. (task to it without using jQuery)  I pretty sure that I do something wrong in

```<code>function handleDrop(e)  OR I need to rewrite all.
</code>```

Hope for your help

this is a code that I have.

HTML

```<code><body>
<ul id="columns">
  <li class="column" draggable="true"><header>A</header></li>
  <li class="column" draggable="true"><header>B</header></li>
  <li class="column" draggable="true"><header>C</header></li>
  <li class="column" draggable="true"><header>D</header></li>
  <li class="column" draggable="true"><header>E</header></li>
</ul>

<ul id="columns_1">
  <li class="column" draggable="true"><header>Ad</header></li>
  <li class="column" draggable="true"><header>Bd</header></li>
  <li class="column" draggable="true"><header>Cd</header></li>
  <li class="column" draggable="true"><header>Dd</header></li>
  <li class="column" draggable="true"><header>Ed</header></li>
</ul>
</body>
</code>```

AND JS

```<code><script type="text/javascript">

var dragSrcEl = null;

function handleDragStart(e) {
  // Target (this) element is the source node.
  dragSrcEl = this;

  e.dataTransfer.effectAllowed = 'move';
  e.dataTransfer.setData('text/html', this.outerHTML);

  this.classList.add('dragElem');
}
function handleDragOver(e) {
  if (e.preventDefault) {
    e.preventDefault(); // Necessary. Allows us to drop.
  }
  this.classList.add('over');

  e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.

  return false;
}

function handleDragEnter(e) {
     console.log('handleDragEnter');
        e.preventDefault();

  // this / e.target is the current hover target.
}

function handleDragLeave(e) {
  this.classList.remove('over');  // this / e.target is previous target element.
}

function handleDrop(e) {
  // this/e.target is current target element.

  if (e.stopPropagation) {
    e.stopPropagation(); // Stops some browsers from redirecting.
  }

  // Don't do anything if dropping the same column we're dragging.
  if (dragSrcEl != this) {
    // Set the source column's HTML to the HTML of the column we dropped on.
    //alert(this.outerHTML);
    //dragSrcEl.innerHTML = this.innerHTML;
    //this.innerHTML = e.dataTransfer.getData('text/html');
    this.parentNode.removeChild(dragSrcEl);
    var dropHTML = e.dataTransfer.getData('text/html');
    this.insertAdjacentHTML('beforebegin',dropHTML);
    var dropElem = this.previousSibling;
    addDnDHandlers(dropElem);

  }
  this.classList.remove('over');
  return false;
}

function handleDragEnd(e) {
  // this/e.target is the source node.
  this.classList.remove('over');

  /*[].forEach.call(cols, function (col) {
    col.classList.remove('over');
  });*/
}

function addDnDHandlers(elem) {
  elem.addEventListener('dragstart', handleDragStart, false);
  elem.addEventListener('dragenter', handleDragEnter, false)
  elem.addEventListener('dragover', handleDragOver, false);
  elem.addEventListener('dragleave', handleDragLeave, false);
  elem.addEventListener('drop', handleDrop, false);
  elem.addEventListener('dragend', handleDragEnd, false);

}

var cols = document.querySelectorAll('#columns .column');
[].forEach.call(cols, addDnDHandlers);
cols

var cols_1 = document.querySelectorAll('#columns_1 .column');
[].forEach.call(cols, addDnDHandlers);

</script>
</code>```

答:
You should remove the dragged element from its parent. And not from the elemet that triggered the drop event. Below is the code. Have a look and let me know if this is what you wanted.

var dragSrcEl = null;

function handleDragStart(e) {
  // Target (this) element is the source node.
  dragSrcEl = this;

  e.dataTransfer.effectAllowed = 'move';
  e.dataTransfer.setData('text/html', this.outerHTML);

  this.classList.add('dragElem');
}
function handleDragOver(e) {
  if (e.preventDefault) {
    e.preventDefault(); // Necessary. Allows us to drop.
  }
  this.classList.add('over');

  e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.

  return false;
}

function handleDragEnter(e) {
     //console.log('handleDragEnter');
        e.preventDefault();

  // this / e.target is the current hover target.
}

function handleDragLeave(e) {
  this.classList.remove('over');  // this / e.target is previous target element.
}

function handleDrop(e) {
  // this/e.target is current target element.
  if (e.stopPropagation) {
    e.stopPropagation(); // Stops some browsers from redirecting.
  }

  // Don't do anything if dropping the same column we're dragging.
  if (dragSrcEl != this) {
    // Set the source column's HTML to the HTML of the column we dropped on.
    //alert(this.outerHTML);
    //dragSrcEl.innerHTML = this.innerHTML;
    //this.innerHTML = e.dataTransfer.getData('text/html');
    dragSrcEl.parentNode.removeChild(dragSrcEl);
    var dropHTML = e.dataTransfer.getData('text/html');
    this.insertAdjacentHTML('beforebegin',dropHTML);
    var dropElem = this.previousSibling;
    addDnDHandlers(dropElem);

  }
  this.classList.remove('over');
  return false;
}

function handleDragEnd(e) {
  // this/e.target is the source node.
  this.classList.remove('over');

  /*[].forEach.call(cols, function (col) {
    col.classList.remove('over');
  });*/
}

function addDnDHandlers(elem) {
  elem.addEventListener('dragstart', handleDragStart, false);
  elem.addEventListener('dragenter', handleDragEnter, false)
  elem.addEventListener('dragover', handleDragOver, false);
  elem.addEventListener('dragleave', handleDragLeave, false);
  elem.addEventListener('drop', handleDrop, false);
  elem.addEventListener('dragend', handleDragEnd, false);

}

var cols = document.querySelectorAll('#columns .column');
[].forEach.call(cols, addDnDHandlers);

var cols_1 = document.querySelectorAll('#columns_1 .column');
[].forEach.call(cols_1, addDnDHandlers);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<ul id="columns">
  <li class="column" draggable="true"><header>A</header></li>
  <li class="column" draggable="true"><header>B</header></li>
  <li class="column" draggable="true"><header>C</header></li>
  <li class="column" draggable="true"><header>D</header></li>
  <li class="column" draggable="true"><header>E</header></li>
</ul>

<ul id="columns_1">
  <li class="column" draggable="true"><header>Ad</header></li>
  <li class="column" draggable="true"><header>Bd</header></li>
  <li class="column" draggable="true"><header>Cd</header></li>
  <li class="column" draggable="true"><header>Dd</header></li>
  <li class="column" draggable="true"><header>Ed</header></li>
</ul>
</body></code>```

Hope this helps :)

Title: Drag <li> between two <ul> JS (without jQuery)

Body:
I am trying to build two ul in JS and HTML and drag li between them. (task to it without using jQuery)  I pretty sure that I do something wrong in

function handleDrop(e)  OR I need to rewrite all.

Hope for your help

this is a code that I have.

HTML

A

B

C

D

E

Ad

Bd

Cd

Dd

Ed

AND JS

Body:
You should remove the dragged element from its parent. And not from the elemet that triggered the drop event. Below is the code. Have a look and let me know if this is what you wanted.

var dragSrcEl = null;

function handleDragStart(e) {
  // Target (this) element is the source node.
  dragSrcEl = this;

  e.dataTransfer.effectAllowed = 'move';
  e.dataTransfer.setData('text/html', this.outerHTML);

  this.classList.add('dragElem');
}
function handleDragOver(e) {
  if (e.preventDefault) {
    e.preventDefault(); // Necessary. Allows us to drop.
  }
  this.classList.add('over');

  e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.

  return false;
}

function handleDragEnter(e) {
     //console.log('handleDragEnter');
        e.preventDefault();

  // this / e.target is the current hover target.
}

function handleDragLeave(e) {
  this.classList.remove('over');  // this / e.target is previous target element.
}

function handleDrop(e) {
  // this/e.target is current target element.
  if (e.stopPropagation) {
    e.stopPropagation(); // Stops some browsers from redirecting.
  }

  // Don't do anything if dropping the same column we're dragging.
  if (dragSrcEl != this) {
    // Set the source column's HTML to the HTML of the column we dropped on.
    //alert(this.outerHTML);
    //dragSrcEl.innerHTML = this.innerHTML;
    //this.innerHTML = e.dataTransfer.getData('text/html');
    dragSrcEl.parentNode.removeChild(dragSrcEl);
    var dropHTML = e.dataTransfer.getData('text/html');
    this.insertAdjacentHTML('beforebegin',dropHTML);
    var dropElem = this.previousSibling;
    addDnDHandlers(dropElem);

  }
  this.classList.remove('over');
  return false;
}

function handleDragEnd(e) {
  // this/e.target is the source node.
  this.classList.remove('over');

  /*[].forEach.call(cols, function (col) {
    col.classList.remove('over');
  });*/
}

function addDnDHandlers(elem) {
  elem.addEventListener('dragstart', handleDragStart, false);
  elem.addEventListener('dragenter', handleDragEnter, false)
  elem.addEventListener('dragover', handleDragOver, false);
  elem.addEventListener('dragleave', handleDragLeave, false);
  elem.addEventListener('drop', handleDrop, false);
  elem.addEventListener('dragend', handleDragEnd, false);

}

var cols = document.querySelectorAll('#columns .column');
[].forEach.call(cols, addDnDHandlers);

var cols_1 = document.querySelectorAll('#columns_1 .column');
[].forEach.call(cols_1, addDnDHandlers);

<body>
<ul id="columns">
  <li class="column" draggable="true"><header>A</header></li>
  <li class="column" draggable="true"><header>B</header></li>
  <li class="column" draggable="true"><header>C</header></li>
  <li class="column" draggable="true"><header>D</header></li>
  <li class="column" draggable="true"><header>E</header></li>
</ul>

<ul id="columns_1">
  <li class="column" draggable="true"><header>Ad</header></li>
  <li class="column" draggable="true"><header>Bd</header></li>
  <li class="column" draggable="true"><header>Cd</header></li>
  <li class="column" draggable="true"><header>Dd</header></li>
  <li class="column" draggable="true"><header>Ed</header></li>
</ul>
</body>

Hope this helps :)


问:
Passing variables (that have space) using JavaScript window pop-up
Pop-up script:

```<code><script>
function myFunction2(url,url2) {

window.open('googleapi.php?id='+url+'&id2='+url2, "_blank", "toolbar=no,scrollbars=no,resizable=no,top=70,left=50,width=1200,height=500");
}

</script>
</code>```

PHP code:

```<code>echo "<td style='color: red;font-weight: bold;'>" . '<a style="color:
red;font-weight: bold;" href= javascript:myFunction2("'."tom
peter".'","'.$row['Account_Number'].'")>'.'Abnormal'.'</a>' . "</td>";
</code>```

Error - it's only considering "tom" - myFunction2("tom

I need to obtain myFunction2("tom peter","11234") - Can someone please help me?

答:
Change php code as :</p>

```<code><?php
$acNumb = "11234";
echo "<td style='color: red;font-weight: bold;'><a style='color: red;font-weight: bold;' href= 'javascript:myFunction2(".'"tom peter"'.",".'"'.$acNumb.'"'.")'>Abnormal</a></td>";
?>
</code>```

Body:
Pop-up script:

PHP code:

echo "" . ''.'Abnormal'.'' . "	";

Error - it's only considering "tom" - myFunction2("tom

I need to obtain myFunction2("tom peter","11234") - Can someone please help me?

Body:
Change php code as :

<?php
$acNumb = "11234";
echo "<td style='color: red;font-weight: bold;'><a style='color: red;font-weight: bold;' href= 'javascript:myFunction2(".'"tom peter"'.",".'"'.$acNumb.'"'.")'>Abnormal</a></td>";
?>


问:
Javafx - Security concern while deploying App using Fxlauncher vs Java Web Start
I have created a Tornadofx application and was looking to deploy it in production. For this I was considering two options:

Fxlauncher

Java web start

Fxlauncher seemed pretty easy to use and deploy with only gradle configurations and commands.

But my main concern is whether it is secure enough?

For example, In Java web start, I was reading through the documentations and found this :

Signing JAR Files Used in Java Web Start
  Java Web Start enforces a security sandbox. By default it grants any application, including application clients, only minimal privileges. Because Java Web Start applications can be so easily downloaded, Java Web Start provides protection from potentially harmful programs that might be accessible over the network. If an application requires a higher privilege level than the sandbox permits, the code that needs privileges must be in a JAR file that was signed. When Java Web Start downloads such a signed JAR file, it displays information about the certificate that was used to sign the JAR, and it asks you whether you want to trust that signed code. If you agree, the code receives elevated permissions and runs. If you reject the signed code, Java Web Start does not start the downloaded application.

Basically, signing of jars is one of the key concerns while using Java web start and JNLP ; But with Fxlauncher, I was not able to find any such requirement or standard to do so.

So how does Fxlauncher handle such security issues?

Currently, using the fxlauncher, I am able to read/write files from/to my client's machine. Is this ok without jar signing ?

FYI, I haven't practically used Java web start, was just reading through Oracle guidelines.

Refrences:

Signing JAR Files Used in Java Web Start

Understanding Signing and Verification

答:
FXLauncher ultimately creates an installable native application using the javapackager utility. You could say that security concerns are moved up one level from the JVM to the OS, if you will. Hence, you should treat an application packaged with FXLauncher the same way you would treat any other native application.

The Gradle plugin currently doesn't expose the ability to sign your application bundle, but you could do that separately until the plugin catches up. Signing the application gives your end users confidence that you are who you say you are and improves the installation experience by replacing the security warning with a dialog that presents your identity instead.

Bottom line: When you install any native application you are basically at the mercy of the developer to some extent, and this is just as much true for FXLauncher packaged applications.