问:
Break s into next line starting from the left (rtl language)
I have some spans. They form a sentence:

```<code><span dir="rtl"> word4 </span>
<span dir="rtl"> word3 </span>
<span dir="rtl"> word2 </span>
<span dir="rtl"> word1 </span>
</code>```

It's written in a language which goes from right to left. So the last span contains the very first word. Now everything is displayed correctly as long as the sentence is displayed in one single line.

HOWEVER: When the sentence breaks, it will break the usual way, which means that what is the first word of the sentence, is now in the next line.

How can I make my spans break down on the left, so that the first span moves down into the next line first?

答:
Using flex:

```<code><div class="container">
  <span> word1 </span>
  <span> word2 </span>
  <span> word3 </span>
  <span> word4 </span>
</div>
</code>```

and the css style is like this:

```<code>.container {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-direction: row-reverse;
    -ms-flex-direction: row-reverse;
    flex-direction: row-reverse;
    -webkit-flex-wrap: wrap;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    }
</code>```

it should be noted that the above css makes all Spans align to right. if you want to align the Spans to the left, add this statements to the ".container" css class:

```<code>-webkit-justify-content: flex-end;
-ms-flex-pack: end;
justify-content: flex-end;
</code>```

Turning this into a stack snippet, with a width that will force wrapping and a background to see the container gives this:

.container {
            display: -ms-flexbox;
            display: -webkit-flex;
            display: flex;
            -webkit-flex-direction: row-reverse;
            -ms-flex-direction: row-reverse;
            flex-direction: row-reverse;
            -webkit-flex-wrap: wrap;
            -ms-flex-wrap: wrap;
            flex-wrap: wrap;
            }
.a-block-to-force-warping{
            max-width: 10em;
            background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a-block-to-force-warping">
<div class="container">
    <span> word1 </span>
    <span> word2 </span>
    <span> word3 </span>
    <span> word4 </span>
</div>
</div></code>```

Title: Break <span>s into next line starting from the left (rtl language)

Body:
I have some spans. They form a sentence:

 word4
 word3
 word2
 word1

It's written in a language which goes from right to left. So the last span contains the very first word. Now everything is displayed correctly as long as the sentence is displayed in one single line.

HOWEVER: When the sentence breaks, it will break the usual way, which means that what is the first word of the sentence, is now in the next line.

How can I make my spans break down on the left, so that the first span moves down into the next line first?

Body:
Using flex:

<div class="container">
  <span> word1 </span>
  <span> word2 </span>
  <span> word3 </span>
  <span> word4 </span>
</div>

and the css style is like this:

.container {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-direction: row-reverse;
    -ms-flex-direction: row-reverse;
    flex-direction: row-reverse;
    -webkit-flex-wrap: wrap;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    }

it should be noted that the above css makes all Spans align to right. if you want to align the Spans to the left, add this statements to the ".container" css class:

-webkit-justify-content: flex-end;
-ms-flex-pack: end;
justify-content: flex-end;

Turning this into a stack snippet, with a width that will force wrapping and a background to see the container gives this:

.container {
            display: -ms-flexbox;
            display: -webkit-flex;
            display: flex;
            -webkit-flex-direction: row-reverse;
            -ms-flex-direction: row-reverse;
            flex-direction: row-reverse;
            -webkit-flex-wrap: wrap;
            -ms-flex-wrap: wrap;
            flex-wrap: wrap;
            }
.a-block-to-force-warping{
            max-width: 10em;
            background-color: red;
}

<div class="a-block-to-force-warping">
<div class="container">
    <span> word1 </span>
    <span> word2 </span>
    <span> word3 </span>
    <span> word4 </span>
</div>
</div>


来源: stackexchange

问:
Ant do not delete file with no name like .gitignore .git
I want to use git to delete a folder,the folder contains some file with no name and only have extension,such as .gitignore,.log

I did it as below,and I also tried many other ways,but still can not delete them,can anyone help me?Thanks in advance!

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="test" default="clean">
  <target name="clean">
     <delete>
       <fileset dir="E:\test\tmt"/>
     </delete>
  <echo message="Finished delete file"/>
  </target>
</project>
</code>```

答: It is deprecated so I would go with Chad's answer, but ant delete also has an excludes property which takes in a comma-separated list of patterns (or direct file names).  Just FYI.

ContentLicense: CC BY-SA 3.0

Body:
I want to use git to delete a folder,the folder contains some file with no name and only have extension,such as .gitignore,.log

I did it as below,and I also tried many other ways,but still can not delete them,can anyone help me?Thanks in advance!

<?xml version="1.0" encoding="UTF-8"?>
<project name="test" default="clean">
  <target name="clean">
     <delete>
       <fileset dir="E:\test\tmt"/>
     </delete>
  <echo message="Finished delete file"/>
  </target>
</project>


问:
Python: PIP install path, what is the correct location for this and other addons?
I have recently had a few problems with my Python installation and as a result I have just reinstalled python and am trying to get all my addons working correctly as well. I’m going to look at virtualenv after to see if I can prevent this from happening again.

When I type which python into terminal I now get

```<code>/Library/Frameworks/Python.framework/Versions/2.7/bin/python
</code>```

I understand this to be the correct location and now want to get all the rest of my addons installed correctly as well.

However after installing pip via sudo easy_install pip and type which pip i get

```<code>/usr/local/bin/pip
</code>```

Is this correct? I would have thought it should reflect the below

```<code>/Library/Python/2.7/site-packages/
</code>```

There is a folder in here called pip-1.4-py2.7.egg which was not there prior to instillation but the above path does not give me any confidence.

Where should pip and my other addons such as Distribute, Flask and Boto be installed if I want to set this up correctly?

Mac OSX 10.7, Python 2.7

答: Also, when you uninstall the package, the first item listed is the directory to the executable.</p>

Body:
I have recently had a few problems with my Python installation and as a result I have just reinstalled python and am trying to get all my addons working correctly as well. I’m going to look at virtualenv after to see if I can prevent this from happening again.

When I type which python into terminal I now get

/Library/Frameworks/Python.framework/Versions/2.7/bin/python

I understand this to be the correct location and now want to get all the rest of my addons installed correctly as well.

However after installing pip via sudo easy_install pip and type which pip i get

/usr/local/bin/pip

Is this correct? I would have thought it should reflect the below

/Library/Python/2.7/site-packages/

There is a folder in here called pip-1.4-py2.7.egg which was not there prior to instillation but the above path does not give me any confidence.

Where should pip and my other addons such as Distribute, Flask and Boto be installed if I want to set this up correctly?

Mac OSX 10.7, Python 2.7


问:
Change styling of If Statements in Emacs?
My company has recently added some new code styling rules, and I would was wondering if there is an easy way via emacs to change a couple things w/ a regex replace.

if statements now have to look like the following:

```<code>if (expression) {
</code>```

where I have many that look like so:

```<code>if(expression){
</code>```

lacking the spaces. Is there an easy way to fix this?

答:
Just my two cents, but if I was going to do this with emacs, I'd probably avoid regular expressions and approach it in two parts.  First I'd do the search to  replace if( with if ( by doing a Meta-% "if("  "if ("  The quote marks are just for delineation, they don't belong in the entered text.  Then either answer each individual replacement query, or give it a "!" to tell it to do all replacements.  Repeat the process for the closing ){ to ) {.

Off the top of my head, I'd expect the first substituion to work without issue.  The second one will also get "){" combinations in loops, but if your new standard demands a space for if statements, I'd expect it to do so for loops as well, so that seems like it should be a good thing.

ContentLicense: CC BY-SA 2.5

Body:
My company has recently added some new code styling rules, and I would was wondering if there is an easy way via emacs to change a couple things w/ a regex replace.

if statements now have to look like the following:

if (expression) {

where I have many that look like so:

if(expression){

lacking the spaces. Is there an easy way to fix this?


问:
IOS phone launch screen mystery image
When my app launches, the storyboard launch screen shows my image as expected but is partially covered by a gray box. Can someone give me an idea where the image box is coming from?

The only thing on the launch screen is an image that is centered on the page.

Here is screen shot:

答: Did you check if the launch images are corrupted? </p>

Title: IOS phone launch screen mystery image


问:
GOPATH error in windows "GOPATH entry is relative; must be absolute path: "
I am new to GO and getting an error when initializing GOPATH in windows.
In my project folder is

C:\Users\kamin\Documents\pm-manager

and i am try to set path in environment variable (GOPATH)but it is getting an error
go: GOPATH entry is relative; must be absolute path: ":/cygdrive/c/Users/kamin/Documents/pm-manager\r\r".
Run 'go help gopath' for usage.

答:
you can put this case uses cygwin this go path

export GOPATH='c:\folder\folder\folder\'

for cygwin is necessary in string 'c:\path'

normaly you try use /cygdrive/.../...

but for GO is not possible ( need c:\ or other drive )


问:
kafka streaming behaviour for more than one partition
I am consuming from Kafka topic. This topic has 3 partitions.
I am using foreachRDD to process each batch RDD (using processData method to process each RDD, and ultimately create a DataSet from that).

Now, you can see that i have count variable , and i am incrementing this count variable in "processData" method to check how many actual records i have processed. (i understand , each RDD is collection of kafka topic records , and the number depends on batch interval size)

Now , the output is something like this :

1 1 1 2 3 2 4 3 5 ....

This makes me think that its because i might have 3 consumers( as i have 3 partitions), and each of these will call "foreachRDD" method separately, so the same count is being printed more than once, as each consumer might have cached its copy of count.

But the final output DataSet that i get has all the records.

So , does Spark internally union all the data? How does it makes out what to union?
I am trying to understand the behaviour , so that i can form my logic

int count = 0;

```<code>messages.foreachRDD(new VoidFunction<JavaRDD<ConsumerRecord<K, String>>>() {
            public void call(JavaRDD<ConsumerRecord<K, V>> rdd) {
                System.out.println("NUmber of elements in RDD : "+ rdd.count());

                List<Row> rows = rdd.map(record -> processData(record))
                        .reduce((rows1, rows2) -> {
                            rows1.addAll(rows2);
                            return rows1;
                        });

                StructType schema = DataTypes.createStructType(fields);
                Dataset ds = ss.createDataFrame(rows, schema);
                ds.createOrReplaceTempView("trades");
                ds.show();
            }
        });
</code>```

答:
The assumptions are not completely accurate.
foreachRDD is one of the so-called output operations in Spark Streaming. The function of output operations is to schedule the provided closure at the interval dictated by the batch interval. The code in that closure executes once each batch interval on the spark driver. Not distributed in the cluster.

In particular, foreachRDD is a general purpose output operation that provides access to the underlying RDD within the DStream. Operations applied on that RDD will execute on the Spark cluster.

So, coming back to the code of the original question, code in the foreachRDD closure such as System.out.println("NUmber of elements in RDD : "+ rdd.count()); executes on the driver. That's also the reason why we can see the output in the console. Note that the rdd.count() in this print will trigger a count of the RDD on the cluster, so count is a distributed operation that returns a value to the driver, then -on the driver- the print operation takes place.

Now comes a transformation of the RDD:

```<code>rdd.map(record -> processData(record))
</code>```

As we mentioned, operations applied to the RDD will execute on the cluster. And that execution will take place following the Spark execution model; that is, transformations are assembled into stages and applied to each partition of the underlying dataset. Given that we are dealing with 3 kafka topics, we will have 3 corresponding partitions in Spark. Hence, processData will be applied once to each partition.

So, does Spark internally union all the data? How does it make out what to union?

The same way we have output operations for Spark Streaming, we have actions for Spark. Actions will potentially apply an operation to the data and bring the results to the driver. The most simple operation is collect which brings the complete dataset to the driver, with the risk that it might not fit in memory. Other common action, count summarizes the number of records in the dataset and returns a single number to the driver.

In the code above, we are using reduce, which is also an action that applies the provided function and brings the resulting data to the driver. It's the use of that action that is "internally union all the data" as expressed in the question. In the reduce expression, we are actually collecting all the data that was distributed into a single local collection. It would be equivalent to do:  rdd.map(record -> processData(record)).collect()

If the intention is to create a Dataset, we should avoid "moving" all the data to the driver first.

A better approach would be:

```<code>val rows = rdd.map(record -> processData(record))
val df = ss.createDataFrame(rows, schema);
...
</code>```

In this case, the data of all partitions will remain local to the executor where they are located.

Note that moving data to the driver should be avoided. It is slow and in cases of large datasets will probably crash the job as the driver cannot typically hold all data available in a cluster.

Body:
I am consuming from Kafka topic. This topic has 3 partitions.
I am using foreachRDD to process each batch RDD (using processData method to process each RDD, and ultimately create a DataSet from that).

Now, you can see that i have count variable , and i am incrementing this count variable in "processData" method to check how many actual records i have processed. (i understand , each RDD is collection of kafka topic records , and the number depends on batch interval size)

Now , the output is something like this :

1 1 1 2 3 2 4 3 5 ....

This makes me think that its because i might have 3 consumers( as i have 3 partitions), and each of these will call "foreachRDD" method separately, so the same count is being printed more than once, as each consumer might have cached its copy of count.

But the final output DataSet that i get has all the records.

So , does Spark internally union all the data? How does it makes out what to union?
I am trying to understand the behaviour , so that i can form my logic

int count = 0;

messages.foreachRDD(new VoidFunction<JavaRDD<ConsumerRecord<K, String>>>() {
            public void call(JavaRDD<ConsumerRecord<K, V>> rdd) {
                System.out.println("NUmber of elements in RDD : "+ rdd.count());

                List<Row> rows = rdd.map(record -> processData(record))
                        .reduce((rows1, rows2) -> {
                            rows1.addAll(rows2);
                            return rows1;
                        });

                StructType schema = DataTypes.createStructType(fields);
                Dataset ds = ss.createDataFrame(rows, schema);
                ds.createOrReplaceTempView("trades");
                ds.show();
            }
        });

Body:
The assumptions are not completely accurate.
foreachRDD is one of the so-called output operations in Spark Streaming. The function of output operations is to schedule the provided closure at the interval dictated by the batch interval. The code in that closure executes once each batch interval on the spark driver. Not distributed in the cluster.

In particular, foreachRDD is a general purpose output operation that provides access to the underlying RDD within the DStream. Operations applied on that RDD will execute on the Spark cluster.

So, coming back to the code of the original question, code in the foreachRDD closure such as System.out.println("NUmber of elements in RDD : "+ rdd.count()); executes on the driver. That's also the reason why we can see the output in the console. Note that the rdd.count() in this print will trigger a count of the RDD on the cluster, so count is a distributed operation that returns a value to the driver, then -on the driver- the print operation takes place.

Now comes a transformation of the RDD:

rdd.map(record -> processData(record))

As we mentioned, operations applied to the RDD will execute on the cluster. And that execution will take place following the Spark execution model; that is, transformations are assembled into stages and applied to each partition of the underlying dataset. Given that we are dealing with 3 kafka topics, we will have 3 corresponding partitions in Spark. Hence, processData will be applied once to each partition.

So, does Spark internally union all the data? How does it make out what to union?

The same way we have output operations for Spark Streaming, we have actions for Spark. Actions will potentially apply an operation to the data and bring the results to the driver. The most simple operation is collect which brings the complete dataset to the driver, with the risk that it might not fit in memory. Other common action, count summarizes the number of records in the dataset and returns a single number to the driver.

In the code above, we are using reduce, which is also an action that applies the provided function and brings the resulting data to the driver. It's the use of that action that is "internally union all the data" as expressed in the question. In the reduce expression, we are actually collecting all the data that was distributed into a single local collection. It would be equivalent to do:  rdd.map(record -> processData(record)).collect()

If the intention is to create a Dataset, we should avoid "moving" all the data to the driver first.

A better approach would be:

val rows = rdd.map(record -> processData(record))
val df = ss.createDataFrame(rows, schema);
...

In this case, the data of all partitions will remain local to the executor where they are located.

Note that moving data to the driver should be avoided. It is slow and in cases of large datasets will probably crash the job as the driver cannot typically hold all data available in a cluster.


问:
Laravel custom redirection after validation errors
Can I ask what have I done wrong in my LoginRequest.php where I've set a condition to redirect to a custom login page if there is any sort of error in the login process? I have my codes as below:

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class LoginRequest extends Request
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
        'login_email'               =>  'required',
        'login_password'            =>  'required'
        ];
    }

    public function messages()
    {
        return [
            'login_email.required'          =>  'Email cannot be blank',
            'login_password.required'       =>  'Password cannot be blank'
        ];
    }

    public function redirect()
    {
        return redirect()->route('login');
    }
}
```

The code is supposed to redirect users who login from a nav bar login form to the main login page, if there are any errors, but it doesn't seem to redirect.

答:
If you are using the validate() method on the Controller

```<code>$this->validate($request, $rules);
</code>```

then you can overwrite the buildFailedValidationResponse from the ValidatesRequests trait present on the base Controller you extend.

Something along this line:

```<code>protected function buildFailedValidationResponse(Request $request, array $errors)
{
    if ($request->expectsJson()) {
        return new JsonResponse($errors, 422);
    }

    return redirect()->route('login');
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Can I ask what have I done wrong in my LoginRequest.php where I've set a condition to redirect to a custom login page if there is any sort of error in the login process? I have my codes as below:

<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class LoginRequest extends Request
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
        'login_email'               =>  'required',
        'login_password'            =>  'required'
        ];
    }

    public function messages()
    {
        return [
            'login_email.required'          =>  'Email cannot be blank',
            'login_password.required'       =>  'Password cannot be blank'
        ];
    }

    public function redirect()
    {
        return redirect()->route('login');
    }
}

The code is supposed to redirect users who login from a nav bar login form to the main login page, if there are any errors, but it doesn't seem to redirect.

Body:
If you are using the validate() method on the Controller

$this->validate($request, $rules);

then you can overwrite the buildFailedValidationResponse from the ValidatesRequests trait present on the base Controller you extend.

Something along this line:

protected function buildFailedValidationResponse(Request $request, array $errors)
{
    if ($request->expectsJson()) {
        return new JsonResponse($errors, 422);
    }

    return redirect()->route('login');
}


问:
Why do I get a ConcurrentModificationException?
Why do I get a ConcurrentModificationException at the specified location in my code? I cannot figure out what I am doing wrong... The removeMin() method is being used to locate the min in the list pq, remove it, and return its value

```<code>import java.util.Iterator;
import java.util.LinkedList;

public class test1 {

    static LinkedList<Integer> list = new LinkedList<Integer>();

    public static void main(String[] args) {
        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);

        System.out.println(removeMin());
    }

    public static Integer removeMin() {
        LinkedList<Integer> pq = new LinkedList<Integer>();
        Iterator<Integer> itPQ = pq.iterator();

        // Put contents of list into pq
        for (int i = 0; i < list.size(); i++) {
            pq.add(list.removeFirst());
        }

        int min = Integer.MAX_VALUE;
        int pos = 0;
        int remPos = 0;

        while (itPQ.hasNext()) {
            Integer element = itPQ.next(); // I get ConcurrentModificationException here
            if (element < min) {
                min = element;
                remPos = pos;
            }
            pos++;
        }

        pq.remove(remPos);
        return remPos;
    }

}
</code>```

答:
I ran your code, and it turns out that the offending line is here:

```<code>Iterator<Integer> itPQ = pq.iterator();
</code>```

This needs to come after your population of pq, so that the iterator does not have it's data updated asynchronously.

With this modification the code runs.

Now, it does not run correctly. The reason is as @Ishnark pointed out in his answer, that every time you are removing from the list, it gets smaller, and so not all of the list is being added to pq.

Body:
Why do I get a ConcurrentModificationException at the specified location in my code? I cannot figure out what I am doing wrong... The removeMin() method is being used to locate the min in the list pq, remove it, and return its value

import java.util.Iterator;
import java.util.LinkedList;

public class test1 {

    static LinkedList<Integer> list = new LinkedList<Integer>();

    public static void main(String[] args) {
        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);

        System.out.println(removeMin());
    }

    public static Integer removeMin() {
        LinkedList<Integer> pq = new LinkedList<Integer>();
        Iterator<Integer> itPQ = pq.iterator();

        // Put contents of list into pq
        for (int i = 0; i < list.size(); i++) {
            pq.add(list.removeFirst());
        }

        int min = Integer.MAX_VALUE;
        int pos = 0;
        int remPos = 0;

        while (itPQ.hasNext()) {
            Integer element = itPQ.next(); // I get ConcurrentModificationException here
            if (element < min) {
                min = element;
                remPos = pos;
            }
            pos++;
        }

        pq.remove(remPos);
        return remPos;
    }

}

Body:
I ran your code, and it turns out that the offending line is here:

Iterator<Integer> itPQ = pq.iterator();

This needs to come after your population of pq, so that the iterator does not have it's data updated asynchronously.

With this modification the code runs.

Now, it does not run correctly. The reason is as @Ishnark pointed out in his answer, that every time you are removing from the list, it gets smaller, and so not all of the list is being added to pq.


问:
Return a value of '1' a referenced cell is empty
In Excel, I need to return a value of 1 if a referenced cell is empty

I can do it if the value is zero but how do I do it if it is empty?

答:
Since required quite often it might as well be brief:

```<code>=1*(A1="")
</code>```

This will not return 1 if the cell appears empty but contains say a space or a formula of the kind =IF(B1=3,"Yes","") where B1 does not contain 3.

=A1="" will return either TRUE or FALSE but those in an equation are treated as 1 and 0 respectively so multiplying TRUE by 1 returns 1.

Much the same can be achieved with the double unary --:

```<code>=--(A1="")
</code>```

where when A1 is empty one minus negates TRUE into -1 and the other negates that to 1 (just + in place of -- however does not change TRUE to 1).

Body:
Since required quite often it might as well be brief:

=1*(A1="")

This will not return 1 if the cell appears empty but contains say a space or a formula of the kind =IF(B1=3,"Yes","") where B1 does not contain 3.

=A1="" will return either TRUE or FALSE but those in an equation are treated as 1 and 0 respectively so multiplying TRUE by 1 returns 1.

Much the same can be achieved with the double unary --:

=--(A1="")

where when A1 is empty one minus negates TRUE into -1 and the other negates that to 1 (just + in place of -- however does not change TRUE to 1).


问:
Bulk update/upsert in MongoDB?
Is it possible to do bulk update/upsert (not insert) in MongoDB?

If yes, please point me to any docs related to this?

Thanks

答:
You can use the command line program mongoimport it should be in your MongoDB bin dir ...

There are two options you'll want to look into to use upsert ...

--upsert                insert or
  update objects that already exist

  --upsertFields arg      comma-separated fields for the query
  part of the
                            upsert. You should make sure this is indexed

More info here: http://www.mongodb.org/display/DOCS/Import+Export+Tools

Or just do ...

```<code>$ mongoimport --help
</code>```

Title: Bulk update/upsert in MongoDB?

Body:
You can use the command line program mongoimport it should be in your MongoDB bin dir ...

There are two options you'll want to look into to use upsert ...

--upsert                insert or
  update objects that already exist

  --upsertFields arg      comma-separated fields for the query
  part of the
                            upsert. You should make sure this is indexed

More info here: http://www.mongodb.org/display/DOCS/Import+Export+Tools

Or just do ...

$ mongoimport --help


问:
Firebase retrieve data from a node based on info from another node in Swift
I'm currently working on an app for sports and I'm investigating if/how Firebase can handle the data and relationships I need.

The user logins into the app and goes to a Dashboard, which lists all the Pools he is participating in.

The current data structure for in Firebase is this:

```<code>  {
  Game:
     78765: {
          teamA: 'New York',
          teamB: 'Montreal',
          date:  '20170601',
          etc...
     },
     76421: {
          teamA: 'LA',
          teamB: 'Mexico',
          date:  '20170602',
          etc...
     }
  },
  {
  Pool:
     12345: {
          GameID: 78765,                      <- GameId from above
          PoolName: 'MyPool',
          Owner: 'LpWgezRkC6EWS0sjXEWxhFl2'   <- UserId
          etc...
     }
  },
  {
  PlayerInPool: {
      DUmwewIfzAbfWZN4NjS8mhX82   <- UserId
          12345: true             <- PoolId from above
      LpWgezRkC6EWS0sjXEWxhFl2
          12345: true
      etc...
      }
  }
</code>```

How would I go about pulling the pool information to display on the users Dashboard?

What needs to be displayed in each cell in the UICollectionView is the Pool info (PoolName and PoolOwner) with the Game information like the TeamA and TeamB names along with the Game date.

答:
It is possible to use firebase. I'm fairly new to programming and I caught on in no time. think JSON when you think of your structure and they encourage you to make it as flat as possible (as opposed to lots of nesting). Good Luck! Here is one idea of what your structure might look like.</p>

```<code>"GameTitle":{
        “PlayerInPool":{
             "PoolID":"12345",
            “UserID”:“email@address.com”,
            “Status”:“Active”
            }
        “Pool":{
             "PoolID":"12345",
            “PoolName”:“myPoolName”,
            “GameID”:“547324”
            }
        “Game":{
             "PlayerID1":"43623",
            “PlayerID2”:“23567”,
            “GameID”:“myGame”,
            “GameName”:“myGame12345”
            }
    }
</code>```

Body:
I'm currently working on an app for sports and I'm investigating if/how Firebase can handle the data and relationships I need.

The user logins into the app and goes to a Dashboard, which lists all the Pools he is participating in.

The current data structure for in Firebase is this:

  {
  Game:
     78765: {
          teamA: 'New York',
          teamB: 'Montreal',
          date:  '20170601',
          etc...
     },
     76421: {
          teamA: 'LA',
          teamB: 'Mexico',
          date:  '20170602',
          etc...
     }
  },
  {
  Pool:
     12345: {
          GameID: 78765,                      <- GameId from above
          PoolName: 'MyPool',
          Owner: 'LpWgezRkC6EWS0sjXEWxhFl2'   <- UserId
          etc...
     }
  },
  {
  PlayerInPool: {
      DUmwewIfzAbfWZN4NjS8mhX82   <- UserId
          12345: true             <- PoolId from above
      LpWgezRkC6EWS0sjXEWxhFl2
          12345: true
      etc...
      }
  }

How would I go about pulling the pool information to display on the users Dashboard?

What needs to be displayed in each cell in the UICollectionView is the Pool info (PoolName and PoolOwner) with the Game information like the TeamA and TeamB names along with the Game date.

Body:
It is possible to use firebase. I'm fairly new to programming and I caught on in no time. think JSON when you think of your structure and they encourage you to make it as flat as possible (as opposed to lots of nesting). Good Luck! Here is one idea of what your structure might look like.

"GameTitle":{
        “PlayerInPool":{
             "PoolID":"12345",
            “UserID”:“email@address.com”,
            “Status”:“Active”
            }
        “Pool":{
             "PoolID":"12345",
            “PoolName”:“myPoolName”,
            “GameID”:“547324”
            }
        “Game":{
             "PlayerID1":"43623",
            “PlayerID2”:“23567”,
            “GameID”:“myGame”,
            “GameName”:“myGame12345”
            }
    }


问:
Bad Python package organization installed a `tests` package to my path? (Anaconda)
Somehow (due to some bad advice) I believe have been bitten by using a shoddy organization of my project directory.

It currently looks like this (GOOD!):

```<code>\projectname
   setup.py
   LICENSE
   MANIFEST.in
   README.rst
   CHANGELOG.rst
   \src
      \projectname
         __init__.py
   \tests
      __init__.py
      test1.py
</code>```

However, it used to look like this (BAD!):

```<code>\package_name
   setup.py
   LICENSE
   MANIFEST.in
   README.rst
   CHANGELOG.rst
   \projectname <--- main package at top level
      __init__.py
   \tests
      test1.py
</code>```

Prior to fixing my shoddy setup, I was using an editable install of the project (python setup.py develop). I have subsequently removed (pip uninstall my_package) that install (and re-added) several times.

Despite removing it, I have now discovered that I seem to have a package called tests available for importing! And the package path is pointed to the directory of my project:

```<code>>>> import tests
>>> tests.__path__
_NamespacePath(['c:\\users\\username\\projects\\projectname\\tests'])
</code>```

I am guessing this happened as a result of installing my package using the initial broken package organization.

How can I remove this tests "package" from my path? I am using Anaconda 4.3 (latest version). pip uninstall tests was not successful.

NOTE: My project has also been published to pypi (project name: parmatter) and I did install it once from there as a test, but only after using the modified project organization structure, so I don't think this was the cause. If anyone wants to install it and see if it leads to the same problem, that may at least help me nail down the cause.

Project repo:  https://github.com/Ricyteach/parmatter

Source distribution: parmatter-0.0.5.tar.gz

EDIT

Result of python -m site below.

```<code>C:\>python -m site
sys.path = [
    'C:\\',
    'C:\\Users\\ricky\\Anaconda3\\python36.zip',
    'C:\\Users\\ricky\\Anaconda3\\DLLs',
    'C:\\Users\\ricky\\Anaconda3\\lib',
    'C:\\Users\\ricky\\Anaconda3',
    'C:\\Users\\ricky\\Anaconda3\\lib\\site-packages',
    'C:\\Users\\ricky\\Anaconda3\\lib\\site-packages\\Sphinx-1.5.6-py3.6.egg',
    'c:\\users\\ricky\\projects\\parmatter',
    'C:\\Users\\ricky\\Anaconda3\\lib\\site-packages\\win32',
    'C:\\Users\\ricky\\Anaconda3\\lib\\site-packages\\win32\\lib',
    'C:\\Users\\ricky\\Anaconda3\\lib\\site-packages\\Pythonwin',
    'C:\\Users\\ricky\\Anaconda3\\lib\\site-packages\\setuptools-27.2.0-py3.6.egg',
]
USER_BASE: 'C:\\Users\\ricky\\AppData\\Roaming\\Python' (doesn't exist)
USER_SITE: 'C:\\Users\\ricky\\AppData\\Roaming\\Python\\Python36\\site-packages' (doesn't exist)
ENABLE_USER_SITE: True
</code>```

It appears I need to remove the project directory from site... how do I do that? And how did it get there in the first place?

答:
The issue was caused by OP installing an old version of the project in development mode, using the system Python interpreter instead of in a venv (hint: don't do that).  That creates a line in easy-install.pth which makes project dir(s) available in sys.path.

Locate the easy-install.pth file in your site-packages directory, and remove any lines starting like this:

```<code>c:\\users\\username\\projects
</code>```

As for your project structure,
I recommend you remove __init__.py from the tests subdirectory.  It is not needed, and means you'll have to explicitly exclude tests if you're using find_packages() helper.

I installed your v0.0.5 distribution, and the problem does not remain in that version.  Your distribution is broken for Python 2, you should include python_requires='>=3' in the setup.py setup call so that appropriate metadata will be generated to prevent pip from attempting to install it on Python 2.

Body:
Somehow (due to some bad advice) I believe have been bitten by using a shoddy organization of my project directory.

It currently looks like this (GOOD!):

\projectname
   setup.py
   LICENSE
   MANIFEST.in
   README.rst
   CHANGELOG.rst
   \src
      \projectname
         __init__.py
   \tests
      __init__.py
      test1.py

However, it used to look like this (BAD!):

\package_name
   setup.py
   LICENSE
   MANIFEST.in
   README.rst
   CHANGELOG.rst
   \projectname <--- main package at top level
      __init__.py
   \tests
      test1.py

Prior to fixing my shoddy setup, I was using an editable install of the project (python setup.py develop). I have subsequently removed (pip uninstall my_package) that install (and re-added) several times.

Despite removing it, I have now discovered that I seem to have a package called tests available for importing! And the package path is pointed to the directory of my project:

>>> import tests
>>> tests.__path__
_NamespacePath(['c:\\users\\username\\projects\\projectname\\tests'])

I am guessing this happened as a result of installing my package using the initial broken package organization.

How can I remove this tests "package" from my path? I am using Anaconda 4.3 (latest version). pip uninstall tests was not successful.

NOTE: My project has also been published to pypi (project name: parmatter) and I did install it once from there as a test, but only after using the modified project organization structure, so I don't think this was the cause. If anyone wants to install it and see if it leads to the same problem, that may at least help me nail down the cause.

Project repo:  https://github.com/Ricyteach/parmatter

Source distribution: parmatter-0.0.5.tar.gz

EDIT

Result of python -m site below.

C:\>python -m site
sys.path = [
    'C:\\',
    'C:\\Users\\ricky\\Anaconda3\\python36.zip',
    'C:\\Users\\ricky\\Anaconda3\\DLLs',
    'C:\\Users\\ricky\\Anaconda3\\lib',
    'C:\\Users\\ricky\\Anaconda3',
    'C:\\Users\\ricky\\Anaconda3\\lib\\site-packages',
    'C:\\Users\\ricky\\Anaconda3\\lib\\site-packages\\Sphinx-1.5.6-py3.6.egg',
    'c:\\users\\ricky\\projects\\parmatter',
    'C:\\Users\\ricky\\Anaconda3\\lib\\site-packages\\win32',
    'C:\\Users\\ricky\\Anaconda3\\lib\\site-packages\\win32\\lib',
    'C:\\Users\\ricky\\Anaconda3\\lib\\site-packages\\Pythonwin',
    'C:\\Users\\ricky\\Anaconda3\\lib\\site-packages\\setuptools-27.2.0-py3.6.egg',
]
USER_BASE: 'C:\\Users\\ricky\\AppData\\Roaming\\Python' (doesn't exist)
USER_SITE: 'C:\\Users\\ricky\\AppData\\Roaming\\Python\\Python36\\site-packages' (doesn't exist)
ENABLE_USER_SITE: True

It appears I need to remove the project directory from site... how do I do that? And how did it get there in the first place?

Body:
The issue was caused by OP installing an old version of the project in development mode, using the system Python interpreter instead of in a venv (hint: don't do that).  That creates a line in easy-install.pth which makes project dir(s) available in sys.path.

Locate the easy-install.pth file in your site-packages directory, and remove any lines starting like this:

c:\\users\\username\\projects

As for your project structure,
I recommend you remove __init__.py from the tests subdirectory.  It is not needed, and means you'll have to explicitly exclude tests if you're using find_packages() helper.

I installed your v0.0.5 distribution, and the problem does not remain in that version.  Your distribution is broken for Python 2, you should include python_requires='>=3' in the setup.py setup call so that appropriate metadata will be generated to prevent pip from attempting to install it on Python 2.


答:
An Iterator should not be considered usable once the Collection from which it was obtained is modified.  (This restriction is relaxed for java.util.concurrent.* collection classes.)

You are first obtaining an Iterator for pq, then modifying pq.  Once you modify pq, the Iterator itPQ is no longer valid, so when you try to use it, you get a ConcurrentModificationException.

One solution is to move Iterator<Integer> itPQ = pq.iterator(); to right before the while loop.  A better approach is to do away with the explicit use of Iterator altogether:

```<code>for (Integer element : pq) {
</code>```

Technically, the for-each loop uses an Iterator internally, so either way, this loop would only be valid as long as you don’t try to modify pq inside the loop.

Title: Why do I get a ConcurrentModificationException?

Body:
An Iterator should not be considered usable once the Collection from which it was obtained is modified.  (This restriction is relaxed for java.util.concurrent.* collection classes.)

You are first obtaining an Iterator for pq, then modifying pq.  Once you modify pq, the Iterator itPQ is no longer valid, so when you try to use it, you get a ConcurrentModificationException.

One solution is to move Iterator<Integer> itPQ = pq.iterator(); to right before the while loop.  A better approach is to do away with the explicit use of Iterator altogether:

for (Integer element : pq) {

Technically, the for-each loop uses an Iterator internally, so either way, this loop would only be valid as long as you don’t try to modify pq inside the loop.


问:
lodash json group object costs
Please,
I have this JSON object and want to group values by type.

```<code>var costs = [
  { 'name': 'JON', 'flight':100, 'value': 12,  type: 'uns' },
  { 'name': 'JON', 'flight':100, 'value': 35,  type: 'sch' },
  { 'name': 'BILL', 'flight':200, 'value': 33,  type: 'uns' },
  { 'name': 'BILL', 'flight':200, 'value': 45,  type: 'sch' }
];
</code>```

I want something like this:

```<code>var costs = [
  { 'name': 'JON', 'flight':100, 'uns': 12,  'sch': 35 },
  { 'name': 'BILL', 'flight':200, 'uns': 33,  'sch': 45}
];
</code>```

I try use lodash but without sucess:

```<code>var compiled_costs = _.chain(costs)
                      .groupBy("flight")
                      .value();

{
"100":
    [    {"name":"JON","flight":100,"value":12,"type":"uns"},
         {"name":"JON","flight":100,"value":35,"type":"sch"}
    ],
"200":
    [
         {"name":"BILL","flight":200,"value":33,"type":"uns"},
         {"name":"BILL","flight":200,"value":45,"type":"sch"}
    ]
}
</code>```

答:
This is what Map was made for. Since you are merging the data you might want to consider keeping the hashMap for quicker lookup. Otherwise turning it into an array is trivial as I demonstrate.

function compiled_costs(costs) {
  var hash = new Map();
  for (let cost of costs) {
    if (hash.has(cost.name)) {
      var values = hash.get(cost.name),
        value = values.value,
        type = values.type;
      delete values.value;
      delete values.type;
      values.uns = value;
      values.sch = cost.value;
    } else hash.set(cost.name, cost)
  }
  return hash
}

var costs = [{
    'name': 'JON',
    'flight': 100,
    'value': 12,
    type: 'uns'
  },
  {
    'name': 'JON',
    'flight': 100,
    'value': 35,
    type: 'sch'
  },
  {
    'name': 'BILL',
    'flight': 200,
    'value': 33,
    type: 'uns'
  },
  {
    'name': 'BILL',
    'flight': 200,
    'value': 45,
    type: 'sch'
  }
];

var formated = [...compiled_costs(costs).values()];
//formated
console.log('formated',formated);
//hashed
var hashed = [...compiled_costs(costs)];
console.log('hashed',hashed);```

Title: lodash json group object costs

Body:
Please,
I have this JSON object and want to group values by type.

var costs = [
  { 'name': 'JON', 'flight':100, 'value': 12,  type: 'uns' },
  { 'name': 'JON', 'flight':100, 'value': 35,  type: 'sch' },
  { 'name': 'BILL', 'flight':200, 'value': 33,  type: 'uns' },
  { 'name': 'BILL', 'flight':200, 'value': 45,  type: 'sch' }
];

I want something like this:

var costs = [
  { 'name': 'JON', 'flight':100, 'uns': 12,  'sch': 35 },
  { 'name': 'BILL', 'flight':200, 'uns': 33,  'sch': 45}
];

I try use lodash but without sucess:

var compiled_costs = _.chain(costs)
                      .groupBy("flight")
                      .value();

{
"100":
    [    {"name":"JON","flight":100,"value":12,"type":"uns"},
         {"name":"JON","flight":100,"value":35,"type":"sch"}
    ],
"200":
    [
         {"name":"BILL","flight":200,"value":33,"type":"uns"},
         {"name":"BILL","flight":200,"value":45,"type":"sch"}
    ]
}


问:
React.js Trigger click event
I'm trying to trigger click event in react.js component.

I'm using rubix template especially  component.
But clicking menu item DropdownButton need to be close but not working.
So I tried to make it manually.

When I click anywhere else menuitem dropdown menu is collapsing.

So I want to trigger click event.

How can I do this?

Here is code snippet for DropdownButton component.

```<code><DropdownButton bsStyle='darkgreen45' title={id_str} class='apps_dropdown' key="test" id="sub_nav_btn">
        <SidebarNavItem eventKey="1" name='Application1' onClick={()=>this.handleClick()} href={::this.getPath('application1')} />
        <SidebarNavItem eventKey="2" name='Application2' href={::this.getPath('application2')} />
      </DropdownButton>
</code>```

Any help would be appreciate.

答: Are you looking for an outside click handler? Sounds like you want to fire an event when the user DOESN'T click the DropdownButton?</p>

Title: React.js Trigger click event

Body:
I'm trying to trigger click event in react.js component.

I'm using rubix template especially  component.
But clicking menu item DropdownButton need to be close but not working.
So I tried to make it manually.

When I click anywhere else menuitem dropdown menu is collapsing.

So I want to trigger click event.

How can I do this?

Here is code snippet for DropdownButton component.

<DropdownButton bsStyle='darkgreen45' title={id_str} class='apps_dropdown' key="test" id="sub_nav_btn">
        <SidebarNavItem eventKey="1" name='Application1' onClick={()=>this.handleClick()} href={::this.getPath('application1')} />
        <SidebarNavItem eventKey="2" name='Application2' href={::this.getPath('application2')} />
      </DropdownButton>

Any help would be appreciate.


问:
MySQL JOIN two tables
I'm sorry about the ambiguous title - I couldn't come up with an explanation for the behaviour I want without giving examples. Also, if this is a duplicate thread, please point me to the correct one and I'll delete it. I couldn't search for what I wanted because, as I said above, it's hard to explain...

Anyway, I want to select data from two tables. One holds a bunch of projects, whereas another holds multiple checklist items for each project. I have a very primitive LEFT JOIN query at the moment, which returns this (there is only one project, at the moment):

```
name                    description
Project file symlinks   One
Project file symlinks   Two
Project file symlinks   seven
Project file symlinks   ahahahahaha
Project file symlinks   many
Project file symlinks   ANOTHER ONE
```

What I'd like to happen is this, for each project in the projects table:

```
name                    description
Project file symlinks   One
                        Two
                        seven
                        ahahahahaha
                        many
                        ANOTHER ONE
```

Or null, it doesn't matter. Essentially, I want to only print the project name once, but print all it's corresponding checklist items.

Here is the query I currently have:

```
SELECT Projects.name, DevProgress.description
FROM DevProgress
LEFT JOIN Projects
ON Projects.id = DevProgress.projectID
```

Can anyone offer a MySQL JOIN query so that I can get the behaviour I want? Thanks for any help,

EDIT

Thanks very much to dcp for helping me out. I eventually came up with this LEFT JOIN query, posted as reference:

```
SELECT name, GROUP_CONCAT(description) AS checklist
FROM Projects LEFT JOIN DevProgress ON Projects.id = DevProgress.projectID
GROUP BY name;
```

And the output:

```
name                      checklist
Project file symlinks     One,Two,seven,ahahahahaha,many,ANOTHER ONE
Testing Project numer 1   NULL
```

James

答:
I don't know very much about mySQL, but it's doable in SQL Server, so it might be possible in mySQL also.

But my point is that even though it might be doable it would be pretty ugly, because SQL just isn't designed this way. In SQL each record of the result set is independent from the other ones. This has several advantages - for example you can apply an additional filter to the result set (if you decide you want only descriptions starting with "ahahaha"), you can reorder it (if you want to sort by description), you can internally parallelize the query and so on without losing information.

This is why some things in SQL are just a bit harder than in other languages, for example numbering your output, querying hierarchies, transposing the output or give special treatment to the first of a group of items.

So your best options might be to either live with the output and post-process it the way you want (which should be pretty trivial - just keep a variable with the last project name and replace the name with empty string if its the same as that last one) or use dcp's answer and flatten the group to a single result row.

Title: MySQL JOIN two tables

Body:
I'm sorry about the ambiguous title - I couldn't come up with an explanation for the behaviour I want without giving examples. Also, if this is a duplicate thread, please point me to the correct one and I'll delete it. I couldn't search for what I wanted because, as I said above, it's hard to explain...

Anyway, I want to select data from two tables. One holds a bunch of projects, whereas another holds multiple checklist items for each project. I have a very primitive LEFT JOIN query at the moment, which returns this (there is only one project, at the moment):

name                    description
Project file symlinks   One
Project file symlinks   Two
Project file symlinks   seven
Project file symlinks   ahahahahaha
Project file symlinks   many
Project file symlinks   ANOTHER ONE

What I'd like to happen is this, for each project in the projects table:

name                    description
Project file symlinks   One
                        Two
                        seven
                        ahahahahaha
                        many
                        ANOTHER ONE

Or null, it doesn't matter. Essentially, I want to only print the project name once, but print all it's corresponding checklist items.

Here is the query I currently have:

SELECT Projects.name, DevProgress.description
FROM DevProgress
LEFT JOIN Projects
ON Projects.id = DevProgress.projectID

Can anyone offer a MySQL JOIN query so that I can get the behaviour I want? Thanks for any help,

EDIT

Thanks very much to dcp for helping me out. I eventually came up with this LEFT JOIN query, posted as reference:

SELECT name, GROUP_CONCAT(description) AS checklist
FROM Projects LEFT JOIN DevProgress ON Projects.id = DevProgress.projectID
GROUP BY name;

And the output:

name                      checklist
Project file symlinks     One,Two,seven,ahahahahaha,many,ANOTHER ONE
Testing Project numer 1   NULL

James


问:
Custom slot types in amazon lex without enumeration values
I'm trying to build a bot to change userinfo stored in a database.

My first thought was to create two slot types like {toChange} and {newValue} where the user could say "Change my name to Peter Griffin" or "My new email is user@mail.com".

Turns out Lex can't handle these custom string inputs. I had to create a slot type for each value the user can have: {name} with AMAZON.Person, {address} with AMAZON.PostalAddress and so on and let Lambda handle the correct slots to elicit.

The problem is that Lex does not offer slot types for email or an bankingaccount number in IBAN format (nor any other format).

If I use a custom slot type with an empty enumeration list I can only enter text, not numbers. Furthermore blanks and special characterls like . and @ are not recognized and Lex asks for input again.

Is there any way to accomplish this? I thought of something like asking for the first part of the mail before the @, then to ask for the provider and lastly filling in the country code. But that is far far away from being userfriendly.

[EDIT]

During testing I found out there is no validation on Amazons side for AMAZON.PostalAddress as for now. I can literally type anything I want and it will be accepted, like lets say an email address or an account number :twinkle:

For the moment this approach works fine, but there is absolutely no guarantee it will stay this way in the future, so my question still is open.

PS: Like this I was able to follow my first approach with {toChange} and {newValue}, where the first is a custom slot type with enumation values und the latter is a AMAZON.PostalAddress slot.

答:
The way I did it was,

create a custom slot type like

```<code>{   "name": "emailAddressSlotType",
    "description": "see name",
    "enumerationValues": [
        { "value": "bobbySmith@yahoo.com" },
        { "value": "FreakyDonkeyLover@gmail.com" },
        { "value": "smithyBob@hotmail.com" }
    ]
}
</code>```

The enumeration values are just sample email addresses. You then need to validate it with something like a Lambda validationCodeHook.

see: this probably... i'm still working on mine

Body:
The way I did it was,

create a custom slot type like

{   "name": "emailAddressSlotType",
    "description": "see name",
    "enumerationValues": [
        { "value": "bobbySmith@yahoo.com" },
        { "value": "FreakyDonkeyLover@gmail.com" },
        { "value": "smithyBob@hotmail.com" }
    ]
}

The enumeration values are just sample email addresses. You then need to validate it with something like a Lambda validationCodeHook.

see: this probably... i'm still working on mine


问:
What does "fakesource" refer to in a python pdb debugging session?
I'm trying to drill into the internals of my Bokeh application to see how an AjaxDataSource works under the hood to gain some inspiration to generalize a remote source for my application through a custom extension of the necessary base classes.

I was able to step in a good amount of pdb earlier in the function but I hit a limit where the debugger landed on fakesource like shown below when drilling into the circle function. Here's the python source below...

```<code>def modify_doc1(doc):

    # get model data from Flask
    url    = "http://localhost:8080/sendModelData/"
    pdb.set_trace()
    source = AjaxDataSource( data             = dict( x=[] , y=[] ) ,
                             data_url         = url       ,
                             polling_interval = 5000      ,
                             mode             = 'replace' ,
                             method           = 'GET'     )
    # plot the model data
    plot = figure( )
    plot.circle( 'x' , 'y' , source=source , size=2 )
    doc.add_root(column(plot))

> C:\MyBokehApp\flask_embedjsonroute.py(43)modify_doc1()
-> plot.circle( 'x' , 'y' , source=source , size=2 )
(Pdb) s
--Call--
> C:\MyBokehApp\fakesource(2)circle()
(Pdb) n
> C:\MyBokehApp\fakesource(3)circle()
(Pdb) n
> C:\MyBokehApp\fakesource(4)circle()
(Pdb) n
> C:\MyBokehApp\fakesource(5)circle()
(Pdb) n
--Return--
</code>```

I'm curious what this is communicating exactly? I've seen fakepath in an html file input context but what does fakesource mean with python source and the debugger? Is this saying I'm hitting a binary implementation or assembly code or something?

答:
In this case, plot.circle is a function that has been generated at run-time by the bokeh library.  To generate this function, bokeh has created some source code on the fly and compiled it into a python function.

When compiling such source a filename can be given to indicate its origin.  This allows tools such as pdb to load that source in order to show it to you.  In this case, bokeh has set this filename to fakesource.

(The code responsible for this is bokeh.plotting.helpers if you wish to see it yourself)

Body:
I'm trying to drill into the internals of my Bokeh application to see how an AjaxDataSource works under the hood to gain some inspiration to generalize a remote source for my application through a custom extension of the necessary base classes.

I was able to step in a good amount of pdb earlier in the function but I hit a limit where the debugger landed on fakesource like shown below when drilling into the circle function. Here's the python source below...

def modify_doc1(doc):

    # get model data from Flask
    url    = "http://localhost:8080/sendModelData/"
    pdb.set_trace()
    source = AjaxDataSource( data             = dict( x=[] , y=[] ) ,
                             data_url         = url       ,
                             polling_interval = 5000      ,
                             mode             = 'replace' ,
                             method           = 'GET'     )
    # plot the model data
    plot = figure( )
    plot.circle( 'x' , 'y' , source=source , size=2 )
    doc.add_root(column(plot))

> C:\MyBokehApp\flask_embedjsonroute.py(43)modify_doc1()
-> plot.circle( 'x' , 'y' , source=source , size=2 )
(Pdb) s
--Call--
> C:\MyBokehApp\fakesource(2)circle()
(Pdb) n
> C:\MyBokehApp\fakesource(3)circle()
(Pdb) n
> C:\MyBokehApp\fakesource(4)circle()
(Pdb) n
> C:\MyBokehApp\fakesource(5)circle()
(Pdb) n
--Return--

I'm curious what this is communicating exactly? I've seen fakepath in an html file input context but what does fakesource mean with python source and the debugger? Is this saying I'm hitting a binary implementation or assembly code or something?


问:
unity3d c# typing to file fast
I want to save what I type to a text file. The code bellow works but when I type too fast, the file has no time to include all the character typed.
Would anyone have a suggestion on how to solve this?</p>

```<code>using System.IO;

string inp;

void Update ()
{
    if
    (
        Input.anyKeyDown
    )
    {

        inp=inp+(string)Input.inputString;

        string path="txt/txttst001.txt";

            File.WriteAllText
            (
                path,
                inp
            );
    }
}
</code>```

答:
Try using a StreamWriter instead:

```<code>using System.IO;

string inp;

void Update ()

{
    if
    (
        Input.anyKeyDown
    )
    {

    inp=inp+(string)Input.inputString;

    string path="txt/txttst001.txt";

using (System.IO.StreamWriter file = new System.IO.StreamWriter(path,true)){
        file.Write(inp);
    }
}
}
</code>```

For more information on StreamWriter you can check it here

Title: unity3d c# typing to file fast

Body:
I want to save what I type to a text file. The code bellow works but when I type too fast, the file has no time to include all the character typed.
Would anyone have a suggestion on how to solve this?

using System.IO;

string inp;

void Update ()
{
    if
    (
        Input.anyKeyDown
    )
    {

        inp=inp+(string)Input.inputString;

        string path="txt/txttst001.txt";

            File.WriteAllText
            (
                path,
                inp
            );
    }
}

Body:
Try using a StreamWriter instead:

using System.IO;

string inp;

void Update ()

{
    if
    (
        Input.anyKeyDown
    )
    {

    inp=inp+(string)Input.inputString;

    string path="txt/txttst001.txt";

using (System.IO.StreamWriter file = new System.IO.StreamWriter(path,true)){
        file.Write(inp);
    }
}
}

For more information on StreamWriter you can check it here


问:
Same difference in alternate rows per sub group
I have data frame where i need to find difference but for every alternate row the difference should stay same as the things to do are same like this:

but I have used this:

```<code>things <- data.frame( category = c("A","B","A","B","A","B","A","B","A","B"),
                      things2do = c("ball","ball","bat","bat","hockey","hockey","volley ball","volley ball","foos ball","foos ball"),
                      number = c(12,5,4,1,0,2,2,0,0,2))

    things %>%
      mutate(diff = number - lead(number,order_by=things2do))
</code>```

but it is not helpful,as I am getting this:

Can i get some help here?

答:
```<code>library(tidyverse)

things2 <- things %>%
  spread(category, number) %>%
  mutate(diff = B - A) %>%
  gather(category, number, A:B) %>%
  select(category, things2do, number, diff) %>%
  arrange(things2do)
</code>```

Body:
I have data frame where i need to find difference but for every alternate row the difference should stay same as the things to do are same like this:

but I have used this:

things <- data.frame( category = c("A","B","A","B","A","B","A","B","A","B"),
                      things2do = c("ball","ball","bat","bat","hockey","hockey","volley ball","volley ball","foos ball","foos ball"),
                      number = c(12,5,4,1,0,2,2,0,0,2))

    things %>%
      mutate(diff = number - lead(number,order_by=things2do))

but it is not helpful,as I am getting this:

Can i get some help here?


问:
Laravel API-Auth-Guard is not case-sensitive?
i'm prototyping an API with Laravel and noticed that the API-Token is not case-sensitive when using the standard Auth-Guard for API. So api_tokens like 'CVC' and 'cvc' are treated the same.

Is that an expected behaviour? Is that ideal in regard of security? Dont think so, even with a 60-byte-string, or what do you think? And is there a way to change that?

Thanks for your thoughts!
Carsten

答:
This shouldn't be the case. Laravel attempts to resolve the token in several ways first

```<code> * Get the token for the current request.
 *
 * @return string
 */
public function getTokenForRequest()
{
    $token = $this->request->query($this->inputKey);
    if (empty($token)) {
        $token = $this->request->input($this->inputKey);
    }
    if (empty($token)) {
        $token = $this->request->bearerToken();
    }
    if (empty($token)) {
        $token = $this->request->getPassword();
    }
    return $token;
}
</code>```

Where that method is invoked when attempting to resolve an instance of the user:

```<code>/**
 * Get the currently authenticated user.
 *
 * @return \Illuminate\Contracts\Auth\Authenticatable|null
 */
public function user()
{
    // If we've already retrieved the user for the current request we can just
    // return it back immediately. We do not want to fetch the user data on
    // every call to this method because that would be tremendously slow.
    if (! is_null($this->user)) {
        return $this->user;
    }
    $user = null;
    $token = $this->getTokenForRequest();
    if (! empty($token)) {
        $user = $this->provider->retrieveByCredentials(
            [$this->storageKey => $token]
        );
    }
    return $this->user = $user;
}
</code>```

And the provider in this case is the DatabaseUserProvider, which the method retrieveByCredentials performs a strict case-sensitive check using the Database Factories ->where() method, no like is used, you can see that here:

```<code>public function retrieveByCredentials(array $credentials)
{
    // First we will add each credential element to the query as a where clause.
    // Then we can execute the query and, if we found a user, return it in a
    // generic "user" object that will be utilized by the Guard instances.
    $query = $this->conn->table($this->table);
    foreach ($credentials as $key => $value) {
        if (! Str::contains($key, 'password')) {
            $query->where($key, $value);
        }
    }
    // Now we are ready to execute the query to see if we have an user matching
    // the given credentials. If not, we will just return nulls and indicate
    // that there are no matching users for these given credential arrays.
    $user = $query->first();
    return $this->getGenericUser($user);
}
</code>```

So no, your case is not typical, and likely there are other components in play here that we're not privy to.

Body:
This shouldn't be the case. Laravel attempts to resolve the token in several ways first

 * Get the token for the current request.
 *
 * @return string
 */
public function getTokenForRequest()
{
    $token = $this->request->query($this->inputKey);
    if (empty($token)) {
        $token = $this->request->input($this->inputKey);
    }
    if (empty($token)) {
        $token = $this->request->bearerToken();
    }
    if (empty($token)) {
        $token = $this->request->getPassword();
    }
    return $token;
}

Where that method is invoked when attempting to resolve an instance of the user:

/**
 * Get the currently authenticated user.
 *
 * @return \Illuminate\Contracts\Auth\Authenticatable|null
 */
public function user()
{
    // If we've already retrieved the user for the current request we can just
    // return it back immediately. We do not want to fetch the user data on
    // every call to this method because that would be tremendously slow.
    if (! is_null($this->user)) {
        return $this->user;
    }
    $user = null;
    $token = $this->getTokenForRequest();
    if (! empty($token)) {
        $user = $this->provider->retrieveByCredentials(
            [$this->storageKey => $token]
        );
    }
    return $this->user = $user;
}

And the provider in this case is the DatabaseUserProvider, which the method retrieveByCredentials performs a strict case-sensitive check using the Database Factories ->where() method, no like is used, you can see that here:

public function retrieveByCredentials(array $credentials)
{
    // First we will add each credential element to the query as a where clause.
    // Then we can execute the query and, if we found a user, return it in a
    // generic "user" object that will be utilized by the Guard instances.
    $query = $this->conn->table($this->table);
    foreach ($credentials as $key => $value) {
        if (! Str::contains($key, 'password')) {
            $query->where($key, $value);
        }
    }
    // Now we are ready to execute the query to see if we have an user matching
    // the given credentials. If not, we will just return nulls and indicate
    // that there are no matching users for these given credential arrays.
    $user = $query->first();
    return $this->getGenericUser($user);
}

So no, your case is not typical, and likely there are other components in play here that we're not privy to.


问:
map v.s. flatmap when promise is involved
I am studying

operator map v.s. flatmap

how to add promise into observable chain.

Then I constructed 4 different versions of var source as below.
version 1, 3 works as expected, while version 2, 4 fail oddly.

My code has also been added in => js bin

Could someone tell what is wrong with my code?

Thanks,
Xi

```<code>console.clear();
var p = new Promise((resolve, reject) => {
  setTimeout( () => {
    resolve('resolved!');
  } , 1000);
});

var source = Rx.Observable.interval(200).take(3)
.flatMap(x => Rx.Observable.timer(500).map(() => x))   //version 1, works OK
// .flatMap(x => Rx.Observable.timer(500).map((x) => x))  // version 2, not OK, returns => 0, 0, 0
// .map(x => p.then( s => console.log(s)));                  // version 3, works OK
// .flatMap(x => p.then( s => console.log(s)));                  // version 4, not OK, error occurs

source.subscribe(x => console.log(x.toString()));
</code>```

答:
```<code>.flatMap(x => Rx.Observable.timer(500).map((x) => x))
</code>```

returns "0", "0", "0" because timer emits 0 after 500 ms and map takes that value as input x and returns it with (x) => x. In the previous line, x was not redeclared in the map, so it came from flatMap.

```<code>.flatMap(x => p.then( s => console.log(s)));
</code>```

gives an error because a promise emits the return value of the then callback. That's console.log(s) which being a statement evaluates to undefined. So the flatMap gives an Observable of undefined, undefined, undefined. When the first reaches the subscribe it tries to do undefined.toString and errors out.

Body:
I am studying

operator map v.s. flatmap

how to add promise into observable chain.

Then I constructed 4 different versions of var source as below.
version 1, 3 works as expected, while version 2, 4 fail oddly.

My code has also been added in => js bin

Could someone tell what is wrong with my code?

Thanks,
Xi

console.clear();
var p = new Promise((resolve, reject) => {
  setTimeout( () => {
    resolve('resolved!');
  } , 1000);
});

var source = Rx.Observable.interval(200).take(3)
.flatMap(x => Rx.Observable.timer(500).map(() => x))   //version 1, works OK
// .flatMap(x => Rx.Observable.timer(500).map((x) => x))  // version 2, not OK, returns => 0, 0, 0
// .map(x => p.then( s => console.log(s)));                  // version 3, works OK
// .flatMap(x => p.then( s => console.log(s)));                  // version 4, not OK, error occurs

source.subscribe(x => console.log(x.toString()));

Body:
.flatMap(x => Rx.Observable.timer(500).map((x) => x))

returns "0", "0", "0" because timer emits 0 after 500 ms and map takes that value as input x and returns it with (x) => x. In the previous line, x was not redeclared in the map, so it came from flatMap.

.flatMap(x => p.then( s => console.log(s)));

gives an error because a promise emits the return value of the then callback. That's console.log(s) which being a statement evaluates to undefined. So the flatMap gives an Observable of undefined, undefined, undefined. When the first reaches the subscribe it tries to do undefined.toString and errors out.


问:
Kotlin has array.indexOf but I cannot figure out how to do array.indexOfBy { lambda }
Kotlin has array.indexOf(item) but I cannot figure out how to do array.indexOfBy { lambda }.  Does it not exist?  I can find an item, but I cannot get its index at the same time.

Am I missing a function in the stdlib?

I can create a function with a loop that chekcs the items and returns when it finds the target.  Like this:

```<code>fun <T : Any> indexOfBy(items: Array<T>, predicate: (T) -> Boolean): Int {
    for (i in items.indices) { // or (i in 0..items.size-1)
        if (predicate(items[i])) {
            return i
        }
    }
    return -1
}
</code>```

Then I tried to make it a little more functional using forEach:

```<code>fun <T : Any> indexOfBy(items: Array<T>, predicate: (T) -> Boolean): Int {
    (items.indices).forEach {
        if (predicate(items[it])) {
            return it
        }
    }
    return -1
}
</code>```

Or I can do something silly like this which isn't very performant:

```<code>val slowAndSilly = people.indexOf(people.find { it.name == "David" })
</code>```

And what looks best is maybe as extension functions:

```<code>fun <T: Any> Array<T>.indexOfBy(predicate: (T)->Boolean): Int =
        this.withIndex().find { predicate(it.value) }?.index ?: -1
fun <T: Any> Collection<T>.indexOfBy(predicate: (T)->Boolean): Int =
        this.withIndex().find { predicate(it.value) }?.index ?: -1
fun <T: Any> Sequence<T>.indexOfBy(predicate: (T)->Boolean): Int =
        this.withIndex().find { predicate(it.value) }?.index ?: -1
</code>```

Is there a more elegant and idiomatic way to accomplish this?!?  I also don't see a function like this for lists, collections nor sequences.

(this question is derived from the comment on another post)

答:
Alternatives that are handy in some cases:</p>

```<code>a.indices.first { a[it] == 2 } // throws NoSuchElementException if not found
a.indices.find { a[it] == 2 }  // null if not found
</code>```

Body:
Kotlin has array.indexOf(item) but I cannot figure out how to do array.indexOfBy { lambda }.  Does it not exist?  I can find an item, but I cannot get its index at the same time.

Am I missing a function in the stdlib?

I can create a function with a loop that chekcs the items and returns when it finds the target.  Like this:

fun <T : Any> indexOfBy(items: Array<T>, predicate: (T) -> Boolean): Int {
    for (i in items.indices) { // or (i in 0..items.size-1)
        if (predicate(items[i])) {
            return i
        }
    }
    return -1
}

Then I tried to make it a little more functional using forEach:

fun <T : Any> indexOfBy(items: Array<T>, predicate: (T) -> Boolean): Int {
    (items.indices).forEach {
        if (predicate(items[it])) {
            return it
        }
    }
    return -1
}

Or I can do something silly like this which isn't very performant:

val slowAndSilly = people.indexOf(people.find { it.name == "David" })

And what looks best is maybe as extension functions:

fun <T: Any> Array<T>.indexOfBy(predicate: (T)->Boolean): Int =
        this.withIndex().find { predicate(it.value) }?.index ?: -1
fun <T: Any> Collection<T>.indexOfBy(predicate: (T)->Boolean): Int =
        this.withIndex().find { predicate(it.value) }?.index ?: -1
fun <T: Any> Sequence<T>.indexOfBy(predicate: (T)->Boolean): Int =
        this.withIndex().find { predicate(it.value) }?.index ?: -1

Is there a more elegant and idiomatic way to accomplish this?!?  I also don't see a function like this for lists, collections nor sequences.

(this question is derived from the comment on another post)

Body:
Alternatives that are handy in some cases:

a.indices.first { a[it] == 2 } // throws NoSuchElementException if not found
a.indices.find { a[it] == 2 }  // null if not found


问:
Sending existing draft with node.js Gmail API
I'm attempting to use the users.drafts.send API to send a Gmail draft which already exists. Despite a lot of searching I haven't been able to find a lot of concrete information about what the request should actually look like. The requests I've tried are:

```<code>gmail.users.drafts.send( { 'userId': user, 'resource': { 'id': msg_id } }, callback );
</code>```

This results in a 'Not Found' error.

Based on some searching which seemed to imply that the draft resource needs to be in a sub-object called draft, I tried:

```<code>gmail.users.drafts.send( { 'userId': user, 'resource': { 'draft': { 'id': msg_id } } }, callback );
</code>```

That results in an "Invalid Draft" error. Which I suppose is a better error, but I still can't get it to actually send.

I've confirmed that the message ID and user ID strings are the correct ones, and there aren't any auth issues. (Other API calls are working fine.)

答:
After searched in all the internet I found a solution:

```<code>gmail.users.drafts.send({
    auth: access_token,
    userId: 'me',
    resource: {
      id: draft_id,
      message:{
        raw: base64encodedmessage
      }
    }
  }, callback);
</code>```

This works even If you want to send a draft with new body

Body:
I'm attempting to use the users.drafts.send API to send a Gmail draft which already exists. Despite a lot of searching I haven't been able to find a lot of concrete information about what the request should actually look like. The requests I've tried are:

gmail.users.drafts.send( { 'userId': user, 'resource': { 'id': msg_id } }, callback );

This results in a 'Not Found' error.

Based on some searching which seemed to imply that the draft resource needs to be in a sub-object called draft, I tried:

gmail.users.drafts.send( { 'userId': user, 'resource': { 'draft': { 'id': msg_id } } }, callback );

That results in an "Invalid Draft" error. Which I suppose is a better error, but I still can't get it to actually send.

I've confirmed that the message ID and user ID strings are the correct ones, and there aren't any auth issues. (Other API calls are working fine.)

Body:
After searched in all the internet I found a solution:

gmail.users.drafts.send({
    auth: access_token,
    userId: 'me',
    resource: {
      id: draft_id,
      message:{
        raw: base64encodedmessage
      }
    }
  }, callback);

This works even If you want to send a draft with new body


问:
.Net Core Command Line App | Process.Start() runs on some machines but not others

Background

I am writing a .NET Core Command Line Application as a CLI for my build system. This part of the build system involves generating a NuGet package from a class library. I am using ProcessStartInfo.cs and Process.cs to make a call to nuget.exe to issue the pack command (nuget.exe location is in the system PATH).

NOTE: I cannot use dotnet CLI for the packaging as the class library is not a .NET Core project, so please do not say "Why don't you just use dotnet pack.

Stack

C# .NET Core (My CLI)

C# .NET 4.5 (Class Library)

Thoughtworks GoCD (Build Server)

Windows Server 2016 (Build Server OS)

Windows 10 (Local Machine OS)

Problem

The issue I am facing is that on my personal machine, when I run my build system CLI, everything works perfectly fine; however, when my build server runs it, the process appears to attempt to start, but then exits without throwing an exception or returning any sort of exit code. Both accounts (Me on my local machine and the account the build server runs under) are local admin accounts.

Code

Cmd.cs (Executes process)

```<code>public static class Cmd
{
    public static int Execute(string filename, string arguments)
    {
        var startInfo = new ProcessStartInfo
        {
            CreateNoWindow = true,
            FileName = filename,
            Arguments = arguments,
        };

        using (var process = new Process { StartInfo = startInfo })
        {
            try
            {
                process.Start();
                process.WaitForExit(30000);
                return process.ExitCode;
            }

            catch (Exception exception)
            {
                if (!process.HasExited)
                {
                    process.Kill();
                }

                Console.WriteLine($"Cmd could not execute command {filename} {arguments}:\n{exception.Message}");
                return (int)ExitCode.Exception;
            }
        }
    }
}
</code>```

Package.cs (uses Cmd.cs)

```<code>// Some code before this

// The below three variables are generated/provided and are made up here for show
var version = "1.0.0";
var package = $"MyLib.{version}";
var projectPath = "C:\Some\Made\Up\Path";
///////////

// Real code
var tempPath = $"{Path.Combine(Path.GetTempPath(), "NugetPackages")}";
var packagePath = Path.Combine(tempPath, package);

if (!Directory.Exists(tempPath))
{
    try
    {
        Directory.CreateDirectory(tempPath);
    }

    catch (Exception exception)
    {
        Console.WriteLine($"Could not create directory in user temp file: {exception.Message}");
        return (int) ExitCode.FilePermission;
    }
}

var filename = "nuget.exe";
var arguments = $"pack -Version {version} -OutputDirectory {tempPath} -properties Configuration=Release {projectPath}";
var exitCode = Cmd.Execute(filename, arguments);

if (exitCode != 0)
{
    Console.WriteLine($"Process failed to execute and exited with exit code: {exitCode}");
    return exitCode;
}

Console.WriteLine($"{package} built successfully");

// Some code after this
</code>```

答:
I modified my code to display all window output and it appears that the same version of NuGet.exe behaves differently on Windows 10 Pro vs Windows Server 2016... not sure why, but on Windows 10 Pro I can use the -Version tag to replace the $version$ token in the .nuspec, but in Windows Server 2016, I cannot do this and have to use a different token (e.g. $package$) and use the -properties switch to replace $package$ with my version... lame sauce!

So, instead of:

```<code>nuget.exe pack -Version 1.0.0 -OutputDirectory C:\Somewhere -properties Configuration=Release MyLib
</code>```

I have to use

```<code>nuget.exe pack -OutputDirectory C:\Somwhere -properties "Configuration=Release;package=1.0.0" MyLib
</code>```

Body:
Background

I am writing a .NET Core Command Line Application as a CLI for my build system. This part of the build system involves generating a NuGet package from a class library. I am using ProcessStartInfo.cs and Process.cs to make a call to nuget.exe to issue the pack command (nuget.exe location is in the system PATH).

NOTE: I cannot use dotnet CLI for the packaging as the class library is not a .NET Core project, so please do not say "Why don't you just use dotnet pack.

Stack

C# .NET Core (My CLI)

C# .NET 4.5 (Class Library)

Thoughtworks GoCD (Build Server)

Windows Server 2016 (Build Server OS)

Windows 10 (Local Machine OS)

Problem

The issue I am facing is that on my personal machine, when I run my build system CLI, everything works perfectly fine; however, when my build server runs it, the process appears to attempt to start, but then exits without throwing an exception or returning any sort of exit code. Both accounts (Me on my local machine and the account the build server runs under) are local admin accounts.

Code

Cmd.cs (Executes process)

public static class Cmd
{
    public static int Execute(string filename, string arguments)
    {
        var startInfo = new ProcessStartInfo
        {
            CreateNoWindow = true,
            FileName = filename,
            Arguments = arguments,
        };

        using (var process = new Process { StartInfo = startInfo })
        {
            try
            {
                process.Start();
                process.WaitForExit(30000);
                return process.ExitCode;
            }

            catch (Exception exception)
            {
                if (!process.HasExited)
                {
                    process.Kill();
                }

                Console.WriteLine($"Cmd could not execute command {filename} {arguments}:\n{exception.Message}");
                return (int)ExitCode.Exception;
            }
        }
    }
}

Package.cs (uses Cmd.cs)

// Some code before this

// The below three variables are generated/provided and are made up here for show
var version = "1.0.0";
var package = $"MyLib.{version}";
var projectPath = "C:\Some\Made\Up\Path";
///////////

// Real code
var tempPath = $"{Path.Combine(Path.GetTempPath(), "NugetPackages")}";
var packagePath = Path.Combine(tempPath, package);

if (!Directory.Exists(tempPath))
{
    try
    {
        Directory.CreateDirectory(tempPath);
    }

    catch (Exception exception)
    {
        Console.WriteLine($"Could not create directory in user temp file: {exception.Message}");
        return (int) ExitCode.FilePermission;
    }
}

var filename = "nuget.exe";
var arguments = $"pack -Version {version} -OutputDirectory {tempPath} -properties Configuration=Release {projectPath}";
var exitCode = Cmd.Execute(filename, arguments);

if (exitCode != 0)
{
    Console.WriteLine($"Process failed to execute and exited with exit code: {exitCode}");
    return exitCode;
}

Console.WriteLine($"{package} built successfully");

// Some code after this

Body:
I modified my code to display all window output and it appears that the same version of NuGet.exe behaves differently on Windows 10 Pro vs Windows Server 2016... not sure why, but on Windows 10 Pro I can use the -Version tag to replace the $version$ token in the .nuspec, but in Windows Server 2016, I cannot do this and have to use a different token (e.g. $package$) and use the -properties switch to replace $package$ with my version... lame sauce!

So, instead of:

nuget.exe pack -Version 1.0.0 -OutputDirectory C:\Somewhere -properties Configuration=Release MyLib

I have to use

nuget.exe pack -OutputDirectory C:\Somwhere -properties "Configuration=Release;package=1.0.0" MyLib


问:
Devise, Cucumber and multiple IDs when logging in - registering
I'm having the following problem:

I have a login form on my entire site (see https://github.com/plataformatec/devise/wiki/How-To:-Display-a-custom-sign_in-form-anywhere-in-your-app):

```<code># application.html.haml
...
= form_tag new_user_session_path do
  = text_field_tag 'user[email]'
  = password_field_tag 'user[password]'
  %button Login
</code>```

I want to test with cucumber to fill out my registration form:

```<code># register#new.html.haml
= semantic_form_for resource, :url => registration_path(resource_name) do |f|
  = f.inputs do
    = f.input :email, :required => true
    = f.input :password, :required => true
    = f.input :password_confirmation, :required => true
    = commit_button("Registrierung absenden")
</code>```

But now there is a problem - there are two fields on my page with the same attribute-id: user_email

When I try to fill the registration form with

```<code># registration_steps.rb
When /^I fill in registration data$/ do |param|
  # this one selects the wrong form - loginform instead of registration form
  fill_in("user_email", :with => "blabla")
end
</code>```

the attribute-ids of the fields are the same and "fill_in" selects the wrong input...

How could I change the ids to work with devise? Seems too much complex for me..

Did I pointed out my problem correctly?

UPDATE

This is a part of my rendered registration site:

```<code><html>
....
<!-- you see that both forms contain fields with the same ids! -->
<!-- so when i test f.e. with fill_in("user_login", :with => "123")
     then the wrong form will be filled out! -->
<form accept-charset="UTF-8" action="/users/sign_in" method="post">
    <input id="user_login" name="user[login]" size="30" type="text" />
    <input id="user_password" name="user[password]" size="30" type="password" />
    <input type="submit" value="anmelden" name="commit">
</form>
...
<form accept-charset="UTF-8" action="/users/sign_in" method="post">
    <input id="user_login" name="user[login]" size="30" type="text" />
    <input id="user_password" name="user[password]" size="30" type="password" />
    <input type="submit" value="anmelden" name="commit">
</form>
...
</html>
</code>```

答:
Solved the problem with using with_scope("123")</p>

```<code>with_scope("#user_new_form") do
    fill_in("user_email", :with => "123")
end
</code>```

Body:
I'm having the following problem:

I have a login form on my entire site (see https://github.com/plataformatec/devise/wiki/How-To:-Display-a-custom-sign_in-form-anywhere-in-your-app):

# application.html.haml
...
= form_tag new_user_session_path do
  = text_field_tag 'user[email]'
  = password_field_tag 'user[password]'
  %button Login

I want to test with cucumber to fill out my registration form:

# register#new.html.haml
= semantic_form_for resource, :url => registration_path(resource_name) do |f|
  = f.inputs do
    = f.input :email, :required => true
    = f.input :password, :required => true
    = f.input :password_confirmation, :required => true
    = commit_button("Registrierung absenden")

But now there is a problem - there are two fields on my page with the same attribute-id: user_email

When I try to fill the registration form with

# registration_steps.rb
When /^I fill in registration data$/ do |param|
  # this one selects the wrong form - loginform instead of registration form
  fill_in("user_email", :with => "blabla")
end

the attribute-ids of the fields are the same and "fill_in" selects the wrong input...

How could I change the ids to work with devise? Seems too much complex for me..

Did I pointed out my problem correctly?

UPDATE

This is a part of my rendered registration site:

....

<form accept-charset="UTF-8" action="/users/sign_in" method="post">
    <input id="user_login" name="user[login]" size="30" type="text" />
    <input id="user_password" name="user[password]" size="30" type="password" />
    <input type="submit" value="anmelden" name="commit">
</form>
...
<form accept-charset="UTF-8" action="/users/sign_in" method="post">
    <input id="user_login" name="user[login]" size="30" type="text" />
    <input id="user_password" name="user[password]" size="30" type="password" />
    <input type="submit" value="anmelden" name="commit">
</form>
...

Body:
Solved the problem with using with_scope("123")

with_scope("#user_new_form") do
    fill_in("user_email", :with => "123")
end


问:
App bar like Google inbox web app
I am building a react web application. I am using material ui for it. I am looking to have an appbar like google inbox has (screenshot attached below). Currently I have Appbar imported from material ui module, but it just contains title , navigation icon. I want to have a search bar, profile photo etc in my app bar, just like google inbox. How can I customize it to get a design like that. Do I have to tweak with material ui's appbar (if yes then how exactly) or do I have to do something else?

答:
As second option, You can use alternate framework react-materialize as well, as it has what your requirement is exactly.</p>

```<code><Navbar brand='logo' right>
  <NavItem href='get-started.html'><Icon>search</Icon></NavItem>
  <NavItem href='get-started.html'><Icon>view_module</Icon></NavItem>
  <NavItem href='get-started.html'><Icon>refresh</Icon></NavItem>
  <NavItem href='get-started.html'><Icon>more_vert</Icon></NavItem>
</Navbar>
</code>```

Title: App bar like Google inbox web app

Body:
As second option, You can use alternate framework react-materialize as well, as it has what your requirement is exactly.

<Navbar brand='logo' right>
  <NavItem href='get-started.html'><Icon>search</Icon></NavItem>
  <NavItem href='get-started.html'><Icon>view_module</Icon></NavItem>
  <NavItem href='get-started.html'><Icon>refresh</Icon></NavItem>
  <NavItem href='get-started.html'><Icon>more_vert</Icon></NavItem>
</Navbar>


问:
non-static initialization of a flexible array member
I'm trying to populate a struct member with an array created at runtime and get the following error:

```<code>error: non-static initialization of a flexible array member
             .entries = entries
                        ^
</code>```

I have isolated the problem and reproduced it in simpler code to make it clearer:

```<code>#include <stdlib.h>

typedef struct entry {
    char *title;
    int id;
} Entry;

typedef struct collection {
    size_t size;
    Entry entries[];
} Collection;

// This function signature may not be changed
void populate(int n, Collection *result){

    Entry entries[n];

    for (int i = 0; i < n; ++i) {
        Entry entry = {
                .title = "Title",
                .id = i
        };

        entries[i] = entry;
    }

    Collection collection = {
            .size = n,
            .entries = entries
    };

    result = &collection;
}
</code>```

How can I fix this?

答:
Actually, initialising a struct with a flexible array member is not straight forward; You will have to allocate a collection item with enough space for the entries you'd like to copy in later. So you could write something like the following:

```<code>Collection *coll = malloc(sizeof(Collection)+n*sizeof(Entry));
coll->size = n;
memcpy (coll->entries, entries, n*sizeof(Entry));
</code>```

I see no other way than using such a "hand-written" malloc.

Note however, that if memory allocation is expected to be done in function populate, the signature of function populate cannot remain as is, because it would not allow to "return" or set a pointer to a newly allocated Collection-object. In this case, the signature would have to be changed either into void populate(int n, Collection **result) or into Collection *populate(int n).

Body:
I'm trying to populate a struct member with an array created at runtime and get the following error:

error: non-static initialization of a flexible array member
             .entries = entries
                        ^

I have isolated the problem and reproduced it in simpler code to make it clearer:

#include <stdlib.h>

typedef struct entry {
    char *title;
    int id;
} Entry;

typedef struct collection {
    size_t size;
    Entry entries[];
} Collection;

// This function signature may not be changed
void populate(int n, Collection *result){

    Entry entries[n];

    for (int i = 0; i < n; ++i) {
        Entry entry = {
                .title = "Title",
                .id = i
        };

        entries[i] = entry;
    }

    Collection collection = {
            .size = n,
            .entries = entries
    };

    result = &collection;
}

How can I fix this?

Body:
Actually, initialising a struct with a flexible array member is not straight forward; You will have to allocate a collection item with enough space for the entries you'd like to copy in later. So you could write something like the following:

Collection *coll = malloc(sizeof(Collection)+n*sizeof(Entry));
coll->size = n;
memcpy (coll->entries, entries, n*sizeof(Entry));

I see no other way than using such a "hand-written" malloc.

Note however, that if memory allocation is expected to be done in function populate, the signature of function populate cannot remain as is, because it would not allow to "return" or set a pointer to a newly allocated Collection-object. In this case, the signature would have to be changed either into void populate(int n, Collection **result) or into Collection *populate(int n).


问:
How to get Javascript variable value into CSS?
How can I have the time variable's contents displayed as the content property in my CSS?

JavaScript:

function clock(){
    var d = new Date();
    var hour = d.getHours();
    var min = d.getMinutes();
    var time = hour + ":" + min;
}
```

<p>CSS:</p>

<pre class="lang-css prettyprint-override"><code>.screen{
    position: absolute;
    height: 75%;
    width: 75%;
    background: #98E8EE;
    top: 11.5%;
    left: 12.5%;
}

.screen::after{
    color: #F9F5F4;
    font-size: 40px;
    content: ;
    font-family: Arial;
    margin-left: 36.5px;
    top: 20px;
    position: relative
}
</code>```

答: You can use jquery to add in the content to your element</p>

Body:
How can I have the time variable's contents displayed as the content property in my CSS?

JavaScript:

function clock(){
    var d = new Date();
    var hour = d.getHours();
    var min = d.getMinutes();
    var time = hour + ":" + min;
}

CSS:

.screen{
    position: absolute;
    height: 75%;
    width: 75%;
    background: #98E8EE;
    top: 11.5%;
    left: 12.5%;
}

.screen::after{
    color: #F9F5F4;
    font-size: 40px;
    content: ;
    font-family: Arial;
    margin-left: 36.5px;
    top: 20px;
    position: relative
}


问:
Count the number of number x that has digit sum equal the digit sum of x*m
I was trying to solve the following problem but I am stuck. I think it is an dynamic programming problem.
Could you please give some ideas?

Problem:

Given a positive number n (n<=18) and a positive number m (m<=100).
Call S(x) is sum of digits of x.
For example S(123)=6
Count the number of integer number x that has n digits and S(x)=S(x*m)

Example:

n= 1, m= 2 result= 2

n= 18, m=1  result = 1000000000000000000

Thanks in advance.

答:
This problem can be calculated directly.

From those documents: 1, 2, and 3 (thanks to @LouisRicci for finding them), we can state:

The Repeating Cycle of Sum of Digits of Multiples starts repeating at the last digit but one from the base-number (9 for base-10)

S(x) can be defined as: let a equal x mod 9, if a is zero, take 9 as result, else take a. You can play it in the ES6 snippet below:

IN.oninput= (_=> OUT.value= (IN.value % 9) || 9);
IN.oninput();```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Input x:<br>
<input id=IN value=123><br>

S(x):<br>
<input id=OUT disabled></code>```

Multiplication rule: S(x * y) = S(S(x) * S(y)).

S(x) and S(x*m) will always be true for x=0, this way there is no zero result.

With the above statements in mind, we should calc the Repeating Cycle of Sum of Digits of Multiples for S(m):

```<code>int m = 88;
int Sm = S(m); // 7

int true_n_times_in_nine = 0;
for (int i=1; i<=9; i++) {
    true_n_times_in_nine += i == S(i * Sm);
}
</code>```

The answer then:

```<code>result = ((pow(10, n) / 9) * true_n_times_in_nine);
</code>```

Plus one because of case zero:

```<code>result++;
</code>```

Here is an ES6 solution:

S= x=> (x % 9) || 9;
TrueIn9= (m, Sm=S(m))=> [1,2,3,4,5,6,7,8,9].filter(i=> i==S(i*Sm)).length;
F= (n,m)=> ~~(eval('1e'+n)/9) * TrueIn9(m) + 1;

N.oninput=
M.oninput=
f=(_=> OUT.value= F(N.value | 0, M.value | 0));
f();```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Input n: (number of digits)<br>
<input id=N value=1><br>

Input m: (multiplicative number)<br>
<input id=M value=2><br>

F(n,m):<br>
<input id=OUT disabled><br></code>```

Body:
This problem can be calculated directly.

From those documents: 1, 2, and 3 (thanks to @LouisRicci for finding them), we can state:

The Repeating Cycle of Sum of Digits of Multiples starts repeating at the last digit but one from the base-number (9 for base-10)

S(x) can be defined as: let a equal x mod 9, if a is zero, take 9 as result, else take a. You can play it in the ES6 snippet below:

IN.oninput= (_=> OUT.value= (IN.value % 9) || 9);
IN.oninput();

Input x:<br>
<input id=IN value=123><br>

S(x):<br>
<input id=OUT disabled>

Multiplication rule: S(x * y) = S(S(x) * S(y)).

S(x) and S(x*m) will always be true for x=0, this way there is no zero result.

With the above statements in mind, we should calc the Repeating Cycle of Sum of Digits of Multiples for S(m):

int m = 88;
int Sm = S(m); // 7

int true_n_times_in_nine = 0;
for (int i=1; i<=9; i++) {
    true_n_times_in_nine += i == S(i * Sm);
}

The answer then:

result = ((pow(10, n) / 9) * true_n_times_in_nine);

Plus one because of case zero:

result++;

Here is an ES6 solution:

S= x=> (x % 9) || 9;
TrueIn9= (m, Sm=S(m))=> [1,2,3,4,5,6,7,8,9].filter(i=> i==S(i*Sm)).length;
F= (n,m)=> ~~(eval('1e'+n)/9) * TrueIn9(m) + 1;

N.oninput=
M.oninput=
f=(_=> OUT.value= F(N.value | 0, M.value | 0));
f();

Input n: (number of digits)<br>
<input id=N value=1><br>

Input m: (multiplicative number)<br>
<input id=M value=2><br>

F(n,m):<br>
<input id=OUT disabled><br>