问:
Linux piping data containing backticks
I'm piping output from one command into a second:

```<code>mpc listall | mpc add
</code>```

mpc listall returns the following data (can output 1 or more lines):

```<code>Dare - 16 - I´ll Be Your King.mp3
</code>```

When piping it into the next command, it seems that my shell (Ash on BusyBox) converts the ´ into an asterisk, as I get the error

```<code>error adding Dare - 16 - I*ll Be Your King.mp3: No such directory
</code>```

Manually adding double quotes works! like this:

```<code>mpc add "Dare - 16 - I´ll Be Your King.mp3"
</code>```

So, I tried adding those by sed and awk, but in those cases the backtick gets converted to an asterisk again:

```<code>mpc listall | sed 's/^/"/;s/$/"/'
</code>```

returns:

```<code>"Dare - 16 - I*ll Be Your King.mp3"
</code>```

So, question is, is there a way to pass backticks, or actually any character, as is, into another command without conversions?

By the way, obviously, it's quite bad to have this character in the file name in the first place, but I want my code to be robust and able to handle anything thrown at it.

答:
Not a direct solution the problem, but a work-around (that's actually better, because it uses the API) in python using the python-mpd2 library:

```<code>myMpdClient = MPDClient()
myMpdClient.connect("localhost", 6600)  # connect to localhost:6600
myMpdClient.findadd('base','directory-name')
myMpdClient.close()
</code>```

I'll accept a working solution to the actual proposed problem, instead of this one, if someone posts a working solution.

Title: Linux piping data containing backticks

Body:
I'm piping output from one command into a second:

mpc listall | mpc add

mpc listall returns the following data (can output 1 or more lines):

Dare - 16 - I´ll Be Your King.mp3

When piping it into the next command, it seems that my shell (Ash on BusyBox) converts the ´ into an asterisk, as I get the error

error adding Dare - 16 - I*ll Be Your King.mp3: No such directory

Manually adding double quotes works! like this:

mpc add "Dare - 16 - I´ll Be Your King.mp3"

So, I tried adding those by sed and awk, but in those cases the backtick gets converted to an asterisk again:

mpc listall | sed 's/^/"/;s/$/"/'

returns:

"Dare - 16 - I*ll Be Your King.mp3"

So, question is, is there a way to pass backticks, or actually any character, as is, into another command without conversions?

By the way, obviously, it's quite bad to have this character in the file name in the first place, but I want my code to be robust and able to handle anything thrown at it.

Body:
Not a direct solution the problem, but a work-around (that's actually better, because it uses the API) in python using the python-mpd2 library:

myMpdClient = MPDClient()
myMpdClient.connect("localhost", 6600)  # connect to localhost:6600
myMpdClient.findadd('base','directory-name')
myMpdClient.close()

I'll accept a working solution to the actual proposed problem, instead of this one, if someone posts a working solution.


来源: stackexchange

问:
PHP creates super large image file
In my app users uploads multiple photos (e.g. 3000x2000 each, in JPG and PNG formats). My PHP program needs to layout those photos and combine them into 1 large photos.

For example, a user uploads 4 photos - p1.jpg, p2.jpg, p3.jpg, p4.jpg, and each is 3000x2000. I need to create a large image that places the 4 images in a 2x2 grid layout like this -

```<code>+-----+-----+  (overall witdh = 6000, overall height = 4000)
| p1  | p2  |
+-----+-----+
| p3  | p4  |
+-----+-----+
</code>```

I can make each image smaller (e.g. 50% of original) so that the overall size can be shrunk down, but if user uploads 8 images or 16 images, the overall size will become super large again.

The resulting image will consume very high memory in PHP, so my question is, what's the best way to create that large image with minimum memory consumption.

One idea I have is that we use a stream to handle large data files chunk by chunk. So I wonder if there is a solution/library allowing chunk-by-chunk image merging.

答:
I can suggest that instead of uploading one big image you can upload all the images independently but while displaying or while downloading you can write some script which will convert all uploaded images into your one big image layout.

If you have some specific position for the image then you can use canvas library called http://fabricjs.com/. By using this library you can customize your image and you can save all the image position in your database and later you can fetch images according to that position.

ContentLicense: CC BY-SA 3.0

Title: PHP creates super large image file

Body:
In my app users uploads multiple photos (e.g. 3000x2000 each, in JPG and PNG formats). My PHP program needs to layout those photos and combine them into 1 large photos.

For example, a user uploads 4 photos - p1.jpg, p2.jpg, p3.jpg, p4.jpg, and each is 3000x2000. I need to create a large image that places the 4 images in a 2x2 grid layout like this -

+-----+-----+  (overall witdh = 6000, overall height = 4000)
| p1  | p2  |
+-----+-----+
| p3  | p4  |
+-----+-----+

I can make each image smaller (e.g. 50% of original) so that the overall size can be shrunk down, but if user uploads 8 images or 16 images, the overall size will become super large again.

The resulting image will consume very high memory in PHP, so my question is, what's the best way to create that large image with minimum memory consumption.

One idea I have is that we use a stream to handle large data files chunk by chunk. So I wonder if there is a solution/library allowing chunk-by-chunk image merging.


问:
Provisioning Service Fabric behind Application Gateway
We are tying to achieve this.
From my understanding, we should place the outside interface of the SF loadbalancer on a private network and then connect to the App Gateway's LB internal interface using Azure Virtual Network Peering.

Is this doable, are there any issues with this?

答:
I think there is better support to abstract Service Fabric by using Azure API management instead of Application Gateway.

I presume your SF is on Azure then API management has built in support for Service fabric so you dont have to do end point resolution or get partition key etc


问:
ByteBuffer.PutDouble equivalent in C#
I have a double(float/Decimal) value and I want to get the same byte array as produced by Java ByteBuffer in C#.
However the byte array produced by using ByteBuffer.PutDouble in Java and BinaryWriter in C# is different. Can someone please explain the implementation detail difference between the two.

Java:

```<code>ByteBuffer bytes = ByteBuffer.allocate(8).putDouble(0,1.12346);
</code>```

bytes[] = {63, -15, -7, -83, -45, 115, -106, 54};

C#:

```<code>double value = 1.12346;
byte[] arr;
using (MemoryStream stream = new MemoryStream())
{
   using (BinaryWriter writer = new BinaryWriter(stream))
   {
      writer.Write(value);
      arr = stream.ToArray();
   }
}
</code>```

arr[] = {153, 211, 101, 49, 177, 249, 241, 63};

答:
ByteBuffer is big endian by default and bytes are signed.

In C#, it's little endian by default and bytes are unsigned.

You have the same data in the opposite order, from a serialization point of view, the sign of the bytes is not important except it is a little confusing.

In C# you can use the EndianBinaryWriter BinaryWriter Endian issue

Title: ByteBuffer.PutDouble equivalent in C#

Body:
I have a double(float/Decimal) value and I want to get the same byte array as produced by Java ByteBuffer in C#.
However the byte array produced by using ByteBuffer.PutDouble in Java and BinaryWriter in C# is different. Can someone please explain the implementation detail difference between the two.

Java:

ByteBuffer bytes = ByteBuffer.allocate(8).putDouble(0,1.12346);

bytes[] = {63, -15, -7, -83, -45, 115, -106, 54};

C#:

double value = 1.12346;
byte[] arr;
using (MemoryStream stream = new MemoryStream())
{
   using (BinaryWriter writer = new BinaryWriter(stream))
   {
      writer.Write(value);
      arr = stream.ToArray();
   }
}

arr[] = {153, 211, 101, 49, 177, 249, 241, 63};


问:
How can I authenticate a request using Laravel Passport having the access token in query string instead of in header?
Authentication works fine using 'middleware' => 'auth:api' on regular endpoints where the client sends the Authorization=Bearer <access_token>.

But now I'd like to handle plain image download requests, without Authorization header, having the access token in the query string like this: GET /picture/my_picture.png?access_token=1234.

I tried something like this in my middleware, but I can't seem to add headers to the Request:

```<code>if ($request->has('access_token')) {
    // something like $request->header->set('Authorization', 'Bearer ' . $request->get('access_token'));
}

if ($this->auth->guard($guard)->guest()) {
    // throw exception
}
</code>```

Can this be done? Maybe intercept or override something/somewhere else?

答:
I had similar issue
In your
App\Http\Kernal.php

register your middleware in
$middleware and
$routeMiddleware

```<code><?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\AddHeaderAccessToken::class,

        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
//            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'addAccessToken' => \App\Http\Middleware\AddHeaderAccessToken::class,
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

        'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
        'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class
    ];
}
</code>```

Middleware

```<code><?php

namespace App\Http\Middleware;

use Closure;

class AddHeaderAccessToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      if ($request->has('access_token')) {
         $request->headers->set('Authorization', 'Bearer ' . $request->get('access_token'));
        }
        return $next($request);
    }
}
</code>```

Body:
Authentication works fine using 'middleware' => 'auth:api' on regular endpoints where the client sends the Authorization=Bearer <access_token>.

But now I'd like to handle plain image download requests, without Authorization header, having the access token in the query string like this: GET /picture/my_picture.png?access_token=1234.

I tried something like this in my middleware, but I can't seem to add headers to the Request:

if ($request->has('access_token')) {
    // something like $request->header->set('Authorization', 'Bearer ' . $request->get('access_token'));
}

if ($this->auth->guard($guard)->guest()) {
    // throw exception
}

Can this be done? Maybe intercept or override something/somewhere else?

Body:
I had similar issue
In your
App\Http\Kernal.php

register your middleware in
$middleware and
$routeMiddleware

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\AddHeaderAccessToken::class,

        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
//            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'addAccessToken' => \App\Http\Middleware\AddHeaderAccessToken::class,
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

        'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
        'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class
    ];
}

Middleware

<?php

namespace App\Http\Middleware;

use Closure;

class AddHeaderAccessToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      if ($request->has('access_token')) {
         $request->headers->set('Authorization', 'Bearer ' . $request->get('access_token'));
        }
        return $next($request);
    }
}


问:
How can i run artisan commands in cpanel
How can i run these artisan commands in my application that is hosted in the net? Is there like a cmd in my cpanel where i can do these commands? Thanks in advance.

php artisan clear:cache

php artisan view:clear

答:
Try this. You can clear all of laravel application cache hosted in shared hosting server that can not access ssh shell by the following code:

```<code>Route::get('/cleareverything', function () {
    $clearcache = Artisan::call('cache:clear');
    echo "Cache cleared<br>";

    $clearview = Artisan::call('view:clear');
    echo "View cleared<br>";

    $clearconfig = Artisan::call('config:cache');
    echo "Config cleared<br>";

    $cleardebugbar = Artisan::call('debugbar:clear');
    echo "Debug Bar cleared<br>";
});
</code>```

Now run yourdoamin.com/cleareverything

This code does not throw any error. I already used this code.

Ref : https://laravel.com/docs/5.2/artisan#calling-commands-via-code

Body:
Try this. You can clear all of laravel application cache hosted in shared hosting server that can not access ssh shell by the following code:

Route::get('/cleareverything', function () {
    $clearcache = Artisan::call('cache:clear');
    echo "Cache cleared<br>";

    $clearview = Artisan::call('view:clear');
    echo "View cleared<br>";

    $clearconfig = Artisan::call('config:cache');
    echo "Config cleared<br>";

    $cleardebugbar = Artisan::call('debugbar:clear');
    echo "Debug Bar cleared<br>";
});

Now run yourdoamin.com/cleareverything

This code does not throw any error. I already used this code.

Ref : https://laravel.com/docs/5.2/artisan#calling-commands-via-code


问:
Trying to use Javascript to populate a hidden input
I have this code:

```<code> while($row = mysql_fetch_array($res)) {
        $name = $row['advertiser'];
        $id = $row['id'];
        if($row['id'] % 4 == 1 || $row['id'] == 1)
        {
            echo "<tr>";
        }
        if($row['availability'] == 0)
        {
            $td = "<td id='green'>";
        }
        if($row['availability'] == 1)
        {
            $td = "<td id='grey'>";
        }
        if($row['price'] == 0)
        {
            mysql_query("UPDATE booklet SET availability = 0 WHERE id = '$id'");
        }
        echo $td . $row['id'] . "<br/><p style='font-size: 6pt;'>" . $name[0] . "<p><img src=" . $row['image'] . "></td>";

        if($row['id'] % 4 == 0)
        {
            echo "</tr>";
        }
}
</code>```

It creates a table. What I want to do is this: if you click on a td, I want to pass the value of that td, for example - the number one (1), if you clicked on the first td - I want to pass this value over to a hidden input so I may later use it elsewhere.

The table looks fine. I know what to do when I have the value in a hidden input. I just need to be able to have the table, when I click on a td, to pass the value over. Or to do anything. onClick doesn't work. Even the absolute simplest isolated JQuery statements don't even come close to parsing. The most complex Javascript that actually has worked on this page is a document.write(). Everything else stumps any known browser.

So, using absolutely any methods, is it a possibility, within the realm of current technology, to have code that does what I want?

Again, I need to have a table cell, when clicked on, pass a variable to a hidden input. I've tried everything.

答:
```<code><td onclick="document.forms[0]['nameofhiddenfield'].value = this.id"> ... </td>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this code:

 while($row = mysql_fetch_array($res)) {
        $name = $row['advertiser'];
        $id = $row['id'];
        if($row['id'] % 4 == 1 || $row['id'] == 1)
        {
            echo "
";
        }
        if($row['availability'] == 0)
        {
            $td = "";
        }
        if($row['availability'] == 1)
        {
            $td = "";
        }
        if($row['price'] == 0)
        {
            mysql_query("UPDATE booklet SET availability = 0 WHERE id = '$id'");
        }
        echo $td . $row['id'] . "

" . $name[0] . "
	";

        if($row['id'] % 4 == 0)
        {
            echo "
";
        }
}

It creates a table. What I want to do is this: if you click on a td, I want to pass the value of that td, for example - the number one (1), if you clicked on the first td - I want to pass this value over to a hidden input so I may later use it elsewhere.

The table looks fine. I know what to do when I have the value in a hidden input. I just need to be able to have the table, when I click on a td, to pass the value over. Or to do anything. onClick doesn't work. Even the absolute simplest isolated JQuery statements don't even come close to parsing. The most complex Javascript that actually has worked on this page is a document.write(). Everything else stumps any known browser.

So, using absolutely any methods, is it a possibility, within the realm of current technology, to have code that does what I want?

Again, I need to have a table cell, when clicked on, pass a variable to a hidden input. I've tried everything.


问:
How to implement ssl in tomcat using CRT and PEM file (SSL_ERROR_NO_CYPHER_OVERLAP)
I received ssl files from vendor - 2 crt files and one pem file. Can some one give steps how to implement ssl using these files in Tomcat 7 ?

I implemented below steps to store ssl files into keystore

```<code>keytool -import -alias root -keystore tomcat.jks -trustcacerts -file tomcat.pem
keytool -import -alias comodo1 -keystore tomcat.jks -trustcacerts -file root.crt
keytool -import -alias comodo2 -keystore tomcat.jks -trustcacerts -file int.crt
</code>```

configured below lines in Tomcat

```<code><Connector port="443" protocol="HTTP/1.1"
SSLEnabled="true"
scheme="https" secure="true" clientAuth="false"
sslProtocol="TLS" keystoreFile="/opt/tomcat.jks"
keystorePass="password"/>
</code>```

also try to replace above protocol with org.apache.coyote.http11.Http11NioProtocol but still it didn't work on browser i got below error message. can some one help me on this.

```<code>An error occurred during a connection to XXXX:8443. Cannot communicate securely with peer: no common encryption algorithm(s). Error code: SSL_ERROR_NO_CYPHER_OVERLAP
</code>```

答:
Please run the below command and confirm if there is a privatekeyEntry in the keystore.

keytool -list -v -keystore < Keystore File Path>

If this entry is not available, then the keystore file can not be used for SSL Encryption.

Body:
I received ssl files from vendor - 2 crt files and one pem file. Can some one give steps how to implement ssl using these files in Tomcat 7 ?

I implemented below steps to store ssl files into keystore

keytool -import -alias root -keystore tomcat.jks -trustcacerts -file tomcat.pem
keytool -import -alias comodo1 -keystore tomcat.jks -trustcacerts -file root.crt
keytool -import -alias comodo2 -keystore tomcat.jks -trustcacerts -file int.crt

configured below lines in Tomcat

<Connector port="443" protocol="HTTP/1.1"
SSLEnabled="true"
scheme="https" secure="true" clientAuth="false"
sslProtocol="TLS" keystoreFile="/opt/tomcat.jks"
keystorePass="password"/>

also try to replace above protocol with org.apache.coyote.http11.Http11NioProtocol but still it didn't work on browser i got below error message. can some one help me on this.

An error occurred during a connection to XXXX:8443. Cannot communicate securely with peer: no common encryption algorithm(s). Error code: SSL_ERROR_NO_CYPHER_OVERLAP


问:
How Windows SVN limits file upload size
My environment: Windows visualsvn
How to limit the size of a user to upload a file. I hope you can get your help.</p>

答:
VisualSVN Server does not limit the size of a commit. Make sure that you run an up to date server and client version and that an antivirus or proxy does not make the client drop the connection.

Note that you can always contact support@visualsvn.com for assistance.

Title: How Windows SVN limits file upload size


问:
How to conditionally skip a test in python
I would like to skip some test functions when a condition is met, for example:

```<code>@skip_unless(condition)
def test_method(self):
    ...
</code>```

Here I expect the test method to be reported as skipped if condition evaluated to true. I was able to do this with some effort with nose, but I would like to see if it is possible in nose2.

Related question describes a method for skipping all tests in nose2.

答:
Generic Solution:

You can use unittest skip conditions which will work with nosetests, nose2 and pytest. There are two options:

```<code>class TestTheTest(unittest.TestCase):
    @unittest.skipIf(condition, reason)
    def test_that_runs_when_condition_false(self):
        assert 1 == 1

    @unittest.skipUnless(condition, reason)
    def test_that_runs_when_condition_true(self):
        assert 1 == 1
</code>```

Pytest

Using pytest framework:

```<code>@pytest.mark.skipif(condition, reason)
def test_that_runs_when_condition_false():
    assert 1 == 1
</code>```

Body:
I would like to skip some test functions when a condition is met, for example:

@skip_unless(condition)
def test_method(self):
    ...

Here I expect the test method to be reported as skipped if condition evaluated to true. I was able to do this with some effort with nose, but I would like to see if it is possible in nose2.

Related question describes a method for skipping all tests in nose2.

Body:
Generic Solution:

You can use unittest skip conditions which will work with nosetests, nose2 and pytest. There are two options:

class TestTheTest(unittest.TestCase):
    @unittest.skipIf(condition, reason)
    def test_that_runs_when_condition_false(self):
        assert 1 == 1

    @unittest.skipUnless(condition, reason)
    def test_that_runs_when_condition_true(self):
        assert 1 == 1

Pytest

Using pytest framework:

@pytest.mark.skipif(condition, reason)
def test_that_runs_when_condition_false():
    assert 1 == 1


问:
How to extract specific substring from an expression in java
I have the following text:

```<code>Units Currently On Bed List
[total beds=0]
Number Of Beds Unit Interval Select All
</code>```

The number after '=' is dynamic and subject to change. How can I extract the number in java using regex?

答:
If you mean "number after = is dynamic and subject to change.", then for your example data you could for example capture the number in a group:

\[.+?=(\d+)\]

Match a \[

Match any character one or more times non greedy .+?

Match an equal sign =

Capture 1 or more digits (\d+)

Match a \]

Body:
I have the following text:

Units Currently On Bed List
[total beds=0]
Number Of Beds Unit Interval Select All

The number after '=' is dynamic and subject to change. How can I extract the number in java using regex?


问:
How can i make my program run faster: Is using threads a solution?
I've written a program building a huge search tree. Because my tree is too huge i expected that my program will use over 40 % of cpu. instead of this my program uses not over 10 % of cpu even it runs with high priority.

If threads will use more cpu while running parallel, let me please know it; i can divide my program in threads, i need really reduce the search time.

Thanks !

答:
Probably you don't have a CPU with 10 cores, so your program doesn't use all the CPU that it can and you have a different problem, like I/O access or something like that.

In this case use more thread is not the solution.

The tree search can be divided on threads easily (searching in the children by different threads for example), but as you are not using all the main thread capacity you don't obtain an better performance using more threads.

The CPU is not your program limiter


问:
JS: Sum of span values in For loop
I have the following values within span tags:

```<code><div id="aantallen">
 <span>3</span>
 <span>2</span>
</div>
</code>```

In JS I want to get the sum of these values. So I made the following For Loop:

```<code>var div = document.getElementById("aantallen");
var spans = div.getElementsByTagName("span");
for(i=0;i<spans.length;i++)
{
    var totaalPersonen = totaalPersonen + i;
    alert(totaalPersonen);
}
</code>```

However, the 3 and 2 are text, so I get Nan in the alerts. My question: how can in convert the 3 and 2 into strings so that I can make a sum of these values?

I tried with String(i) but couldn't get it to work.

答:
You need to convert the content of the DOM element to a Number.
Then, you can use reduce in order to calculate the sum.

const spans = document.querySelectorAll('#aantallen span');

const result = Array.from(spans).reduce((sum, spanElm) => sum + Number(spanElm.textContent), 0)

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="aantallen">
  <span>3</span>
  <span>2</span>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: JS: Sum of span values in For loop

Body:
I have the following values within span tags:

 3
 2

In JS I want to get the sum of these values. So I made the following For Loop:

var div = document.getElementById("aantallen");
var spans = div.getElementsByTagName("span");
for(i=0;i<spans.length;i++)
{
    var totaalPersonen = totaalPersonen + i;
    alert(totaalPersonen);
}

However, the 3 and 2 are text, so I get Nan in the alerts. My question: how can in convert the 3 and 2 into strings so that I can make a sum of these values?

I tried with String(i) but couldn't get it to work.

Body:
You need to convert the content of the DOM element to a Number.
Then, you can use reduce in order to calculate the sum.

const spans = document.querySelectorAll('#aantallen span');

const result = Array.from(spans).reduce((sum, spanElm) => sum + Number(spanElm.textContent), 0)

console.log(result);

<div id="aantallen">
  <span>3</span>
  <span>2</span>
</div>


问:
Apply CountVectorizer to column with list of words in rows in Python
I made a preprocessing part for text analysis and after removing stopwords and stemming like this:

```<code>test[col] = test[col].apply(
    lambda x: [ps.stem(item) for item in re.findall(r"[\w']+", x) if ps.stem(item) not in stop_words])

train[col] = train[col].apply(
    lambda x: [ps.stem(item) for item in re.findall(r"[\w']+", x) if ps.stem(item) not in stop_words])
</code>```

I've got a column with list of "cleaned words". Here are 3 rows in a column:

```<code>['size']
['pcs', 'new', 'x', 'kraft', 'bubble', 'mailers', 'lined', 'bubble', 'wrap', 'protection', 'self', 'sealing', 'peelandseal', 'adhesive', 'keeps', 'contents', 'secure', 'tamper', 'proof', 'durable', 'lightweight', 'kraft', 'material', 'helps', 'save', 'postage', 'approved', 'ups', 'fedex', 'usps']
['brand', 'new', 'coach', 'bag', 'bought', 'rm', 'coach', 'outlet']
</code>```

I now want to apply CountVectorizer to this column:

```<code>from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features=1500, analyzer='word', lowercase=False) # will leave only 1500 words
X_train = cv.fit_transform(train[col])
</code>```

But I got an Error:

```<code>TypeError: expected string or bytes-like object
</code>```

It would be a bit strange to create string from list and than separate by CountVectorizer again.

答:
When you use fit_transform, the params passed in have to be an iterable of strings or bytes-like objects. Looks like you should be applying that over your column instead.

```<code>X_train = train[col].apply(lambda x: cv.fit_transform(x))
</code>```

You can read the docs for fit_transform here.

Body:
I made a preprocessing part for text analysis and after removing stopwords and stemming like this:

test[col] = test[col].apply(
    lambda x: [ps.stem(item) for item in re.findall(r"[\w']+", x) if ps.stem(item) not in stop_words])

train[col] = train[col].apply(
    lambda x: [ps.stem(item) for item in re.findall(r"[\w']+", x) if ps.stem(item) not in stop_words])

I've got a column with list of "cleaned words". Here are 3 rows in a column:

['size']
['pcs', 'new', 'x', 'kraft', 'bubble', 'mailers', 'lined', 'bubble', 'wrap', 'protection', 'self', 'sealing', 'peelandseal', 'adhesive', 'keeps', 'contents', 'secure', 'tamper', 'proof', 'durable', 'lightweight', 'kraft', 'material', 'helps', 'save', 'postage', 'approved', 'ups', 'fedex', 'usps']
['brand', 'new', 'coach', 'bag', 'bought', 'rm', 'coach', 'outlet']

I now want to apply CountVectorizer to this column:

from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features=1500, analyzer='word', lowercase=False) # will leave only 1500 words
X_train = cv.fit_transform(train[col])

But I got an Error:

TypeError: expected string or bytes-like object

It would be a bit strange to create string from list and than separate by CountVectorizer again.

Body:
When you use fit_transform, the params passed in have to be an iterable of strings or bytes-like objects. Looks like you should be applying that over your column instead.

X_train = train[col].apply(lambda x: cv.fit_transform(x))

You can read the docs for fit_transform here.


问:
How to set 4 RelativeLayout Horizontally and Adjust automatically according to screen size

Please Refer to screen shot.
Now my Problem is
i have make a xml design that is like in screenshot.
i have 4 relative layout contains imageview and textview.
now i want to set these 4 relative layout horizontally with equal space from right,left,start,end.
In my layout when it go on big screen the start and end showing extra space,i know i have set it like that.
But Is there any solution to set these RLs automatic adjust there size according to screen size.

```<code> <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/one"
    android:id="@+id/RL_MainCat"
    android:background="@color/white"
    android:layout_marginTop="10dp">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true">
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/RL_UploadPres"
    android:layout_marginLeft="10dp"
    >
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/upload_pres_icon"
    android:id="@+id/icon_uploadpres"
    android:layout_centerHorizontal="true"
    />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload\nPrescription"
        android:textAlignment="center"
        android:textColor="#1f222d"
        android:textSize="11sp"
        android:layout_below="@+id/icon_uploadpres"
        android:layout_marginTop="10dp"
        />
</RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/RL_UploadPres"
        android:id="@+id/RL_FindPharmacy"
        android:layout_marginLeft="20dp">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/find_pharma_icon"
            android:id="@+id/icon_findphar"
            android:layout_centerHorizontal="true"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" Find \n  Pharmacy  "
            android:textAlignment="center"
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:layout_below="@+id/icon_findphar"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/RL_FindPharmacy"
        android:id="@+id/RL_BuyOTC"
        android:layout_marginLeft="20dp"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/otc_icon"
            android:id="@+id/icon_findotc"
            android:layout_centerHorizontal="true"

            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  Buy \n      OTC     "
            android:textAlignment="center"
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:layout_below="@+id/icon_findotc"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"/>

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/RL_BuyMedicine"
        android:layout_toRightOf="@+id/RL_BuyOTC"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/medicine_icon"
            android:id="@+id/icon_findmedi"
            android:layout_centerHorizontal="true"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  Buy \n Medicines  "
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:textAlignment="center"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            android:layout_below="@+id/icon_findmedi"
            />

    </RelativeLayout>
</RelativeLayout>
</code>```

答:
Try this:</p>

```<code><RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/one"
android:id="@+id/RL_MainCat"
android:background="@color/white"
android:layout_marginTop="10dp">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true">
<RelativeLayout
android:layout_weight="0.25"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/RL_UploadPres"
android:layout_marginLeft="10dp"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/upload_pres_icon"
android:id="@+id/icon_uploadpres"
android:layout_centerHorizontal="true"
/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Upload\nPrescription"
    android:textAlignment="center"
    android:textColor="#1f222d"
    android:textSize="11sp"
    android:layout_below="@+id/icon_uploadpres"
    android:layout_marginTop="10dp"
    />
</RelativeLayout>

<RelativeLayout
    android:layout_weight="0.25"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/RL_UploadPres"
    android:id="@+id/RL_FindPharmacy"
    android:layout_marginLeft="20dp">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/find_pharma_icon"
        android:id="@+id/icon_findphar"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" Find \n  Pharmacy  "
        android:textAlignment="center"
        android:textColor="#1f222d"
        android:textSize="11sp"
        android:layout_below="@+id/icon_findphar"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        />
</RelativeLayout>

<RelativeLayout
    android:layout_weight="0.25"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/RL_FindPharmacy"
    android:id="@+id/RL_BuyOTC"
    android:layout_marginLeft="20dp"
    >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/otc_icon"
        android:id="@+id/icon_findotc"
        android:layout_centerHorizontal="true"

        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="  Buy \n      OTC     "
        android:textAlignment="center"
        android:textColor="#1f222d"
        android:textSize="11sp"
        android:layout_below="@+id/icon_findotc"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

<RelativeLayout
    android:layout_weight="0.25"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:id="@+id/RL_BuyMedicine"
    android:layout_toRightOf="@+id/RL_BuyOTC"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="10dp"
    >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/medicine_icon"
        android:id="@+id/icon_findmedi"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="  Buy \n Medicines  "
        android:textColor="#1f222d"
        android:textSize="11sp"
        android:textAlignment="center"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/icon_findmedi"
        />
</LinearLayout>
</RelativeLayout>
</code>```

Body:
Please Refer to screen shot.
Now my Problem is
i have make a xml design that is like in screenshot.
i have 4 relative layout contains imageview and textview.
now i want to set these 4 relative layout horizontally with equal space from right,left,start,end.
In my layout when it go on big screen the start and end showing extra space,i know i have set it like that.
But Is there any solution to set these RLs automatic adjust there size according to screen size.

 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/one"
    android:id="@+id/RL_MainCat"
    android:background="@color/white"
    android:layout_marginTop="10dp">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true">
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/RL_UploadPres"
    android:layout_marginLeft="10dp"
    >
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/upload_pres_icon"
    android:id="@+id/icon_uploadpres"
    android:layout_centerHorizontal="true"
    />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload\nPrescription"
        android:textAlignment="center"
        android:textColor="#1f222d"
        android:textSize="11sp"
        android:layout_below="@+id/icon_uploadpres"
        android:layout_marginTop="10dp"
        />
</RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/RL_UploadPres"
        android:id="@+id/RL_FindPharmacy"
        android:layout_marginLeft="20dp">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/find_pharma_icon"
            android:id="@+id/icon_findphar"
            android:layout_centerHorizontal="true"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" Find \n  Pharmacy  "
            android:textAlignment="center"
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:layout_below="@+id/icon_findphar"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/RL_FindPharmacy"
        android:id="@+id/RL_BuyOTC"
        android:layout_marginLeft="20dp"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/otc_icon"
            android:id="@+id/icon_findotc"
            android:layout_centerHorizontal="true"

            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  Buy \n      OTC     "
            android:textAlignment="center"
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:layout_below="@+id/icon_findotc"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"/>

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/RL_BuyMedicine"
        android:layout_toRightOf="@+id/RL_BuyOTC"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/medicine_icon"
            android:id="@+id/icon_findmedi"
            android:layout_centerHorizontal="true"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  Buy \n Medicines  "
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:textAlignment="center"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            android:layout_below="@+id/icon_findmedi"
            />

    </RelativeLayout>
</RelativeLayout>

Body:
Try this:

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/one"
android:id="@+id/RL_MainCat"
android:background="@color/white"
android:layout_marginTop="10dp">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true">
<RelativeLayout
android:layout_weight="0.25"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/RL_UploadPres"
android:layout_marginLeft="10dp"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/upload_pres_icon"
android:id="@+id/icon_uploadpres"
android:layout_centerHorizontal="true"
/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Upload\nPrescription"
    android:textAlignment="center"
    android:textColor="#1f222d"
    android:textSize="11sp"
    android:layout_below="@+id/icon_uploadpres"
    android:layout_marginTop="10dp"
    />
</RelativeLayout>

<RelativeLayout
    android:layout_weight="0.25"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/RL_UploadPres"
    android:id="@+id/RL_FindPharmacy"
    android:layout_marginLeft="20dp">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/find_pharma_icon"
        android:id="@+id/icon_findphar"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" Find \n  Pharmacy  "
        android:textAlignment="center"
        android:textColor="#1f222d"
        android:textSize="11sp"
        android:layout_below="@+id/icon_findphar"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        />
</RelativeLayout>

<RelativeLayout
    android:layout_weight="0.25"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/RL_FindPharmacy"
    android:id="@+id/RL_BuyOTC"
    android:layout_marginLeft="20dp"
    >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/otc_icon"
        android:id="@+id/icon_findotc"
        android:layout_centerHorizontal="true"

        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="  Buy \n      OTC     "
        android:textAlignment="center"
        android:textColor="#1f222d"
        android:textSize="11sp"
        android:layout_below="@+id/icon_findotc"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

<RelativeLayout
    android:layout_weight="0.25"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:id="@+id/RL_BuyMedicine"
    android:layout_toRightOf="@+id/RL_BuyOTC"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="10dp"
    >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/medicine_icon"
        android:id="@+id/icon_findmedi"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="  Buy \n Medicines  "
        android:textColor="#1f222d"
        android:textSize="11sp"
        android:textAlignment="center"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/icon_findmedi"
        />
</LinearLayout>
</RelativeLayout>


问:
getting hold of "value" in k/v pair returned by query
Trying to figure out the right way to parse key-value pairs produced by a Cypher query:

```<code>@app.route('/about')
    def about():
        data = graph.run("MATCH (n) RETURN n.level")
        for record in data:
    return render_template("output.html",output=record)
</code>```

Please disregard the fact that I'm not combining the returned records into a list prior to populating the template. I do get one record as output, and am ok with that for now.

What I'm struggling with is - how do I handle the resulting k/v pair

(u'n.level': u'high')

I mean, if I'm just interested in the value 'high', is there a clean way to get hold of it?

Sorry if this sounds too basic. I do understand, there must be some parsing tools, but at this point, I just don't know where to look.

答:
Sorry, the solution is simple. Flask returns a py2neo.database.record object, which can be indexed just like a list, the only caveat being that the list has only one element (not two, as it might appear).
So, if variable record above equals to (u'n.level': u'high'), record[0] will be equal to 'high'.
And the 'u's can be just ignored altogether, as explained elsewhere on SO.

Body:
Trying to figure out the right way to parse key-value pairs produced by a Cypher query:

@app.route('/about')
    def about():
        data = graph.run("MATCH (n) RETURN n.level")
        for record in data:
    return render_template("output.html",output=record)

Please disregard the fact that I'm not combining the returned records into a list prior to populating the template. I do get one record as output, and am ok with that for now.

What I'm struggling with is - how do I handle the resulting k/v pair

(u'n.level': u'high')

I mean, if I'm just interested in the value 'high', is there a clean way to get hold of it?

Sorry if this sounds too basic. I do understand, there must be some parsing tools, but at this point, I just don't know where to look.


问:
Python function to find indexes of 1s in binary array and
I have an array which looks like this

```<code>[1, 0, 1 , 0 , 0, 1]
</code>```

And I want to get those indexes that have 1 in it.
So here I would get an array of [0, 2 , 5]
and then based on it I would create a new array that takes these numbers and exponantiate 2 with them
So the end array is

```<code>[2**0, 2**2, 2**5]
</code>```

Is there a way to write it as shortly as possible?

答:
you could use enumerate in a list comprehension:

```<code>a = [1, 0, 1 , 0 , 0, 1]
b = [2**idx for idx, v in enumerate(a) if v]
b
</code>```

output:

```<code>[1, 4, 32]
</code>```

Body:
I have an array which looks like this

[1, 0, 1 , 0 , 0, 1]

And I want to get those indexes that have 1 in it.
So here I would get an array of [0, 2 , 5]
and then based on it I would create a new array that takes these numbers and exponantiate 2 with them
So the end array is

[2**0, 2**2, 2**5]

Is there a way to write it as shortly as possible?

Body:
you could use enumerate in a list comprehension:

a = [1, 0, 1 , 0 , 0, 1]
b = [2**idx for idx, v in enumerate(a) if v]
b

output:

[1, 4, 32]


答: You could have a look into the Task Parallel Library to split your work up into several smaller tasks which can run at the same time.</p>

Title: How can i make my program run faster: Is using threads a solution?

Body:
I've written a program building a huge search tree. Because my tree is too huge i expected that my program will use over 40 % of cpu. instead of this my program uses not over 10 % of cpu even it runs with high priority.

If threads will use more cpu while running parallel, let me please know it; i can divide my program in threads, i need really reduce the search time.

Thanks !


答:
Not sute using regex but this is one way :</p>

```<code>int first = str.indexOf('=') +1;
int last = str.lastIndexOf(']');

String nbr = str.subString(first,last );
int number = Integer.parseInt(nbr);
</code>```

Title: How to extract specific substring from an expression in java

Body:
Not sute using regex but this is one way :

int first = str.indexOf('=') +1;
int last = str.lastIndexOf(']');

String nbr = str.subString(first,last );
int number = Integer.parseInt(nbr);


问:
How to add footer to Navigation Drawer in Android using design support library?
How can I add a footer to a NavigationView? In my case the NavigationView items are inflated by menu resource. Initially I tried to add a LinearLayout as a footer, but the NavigationView is not scrollable and the footer gets overlapped by the navigation menu items. I want to implement a Google Play rating segment as a footer exactly like this image:

navigation_drawer.xml:

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">

  <android.support.v7.widget.Toolbar
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:background="@color/colorPrimary"
      android:id="@+id/toolbar"
      android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
      app:title="@string/app_name" />

  <android.support.v4.widget.DrawerLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      android:layout_height="match_parent"
      android:layout_width="match_parent"
      android:id="@+id/drawerLayout">

    <FrameLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/containerView">
    </FrameLayout>

    <android.support.design.widget.NavigationView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/shitstuff"
        app:itemTextColor="@color/green"
        app:menu="@menu/drawermenu"
        app:headerLayout="@layout/drawer_header"
        android:layout_marginTop="-24dp">
    </android.support.design.widget.NavigationView>

  </android.support.v4.widget.DrawerLayout>

</LinearLayout>
</code>```

答:
```<code><android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:itemIconTint="@color/colorAccent"
    app:menu="@menu/activity_main_drawer">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:clickable="true"
        android:orientation="vertical">

        <TextView
            android:id="@+id/nav_footer_textview"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:gravity="center"
            android:text="Your Footer Text Here" />

    </LinearLayout>
</android.support.design.widget.NavigationView>
</code>```

And for performing click on it:

```<code>NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
TextView footerTV = (TextView) navigationView.findViewById(R.id.nav_footer_textview);
footerTV.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Toast.makeText(MainActivity.this, "Footer is clicked", Toast.LENGTH_SHORT).show();
    }
});
</code>```

Body:
How can I add a footer to a NavigationView? In my case the NavigationView items are inflated by menu resource. Initially I tried to add a LinearLayout as a footer, but the NavigationView is not scrollable and the footer gets overlapped by the navigation menu items. I want to implement a Google Play rating segment as a footer exactly like this image:

navigation_drawer.xml:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">

  <android.support.v7.widget.Toolbar
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:background="@color/colorPrimary"
      android:id="@+id/toolbar"
      android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
      app:title="@string/app_name" />

  <android.support.v4.widget.DrawerLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      android:layout_height="match_parent"
      android:layout_width="match_parent"
      android:id="@+id/drawerLayout">

    <FrameLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/containerView">
    </FrameLayout>

    <android.support.design.widget.NavigationView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/shitstuff"
        app:itemTextColor="@color/green"
        app:menu="@menu/drawermenu"
        app:headerLayout="@layout/drawer_header"
        android:layout_marginTop="-24dp">
    </android.support.design.widget.NavigationView>

  </android.support.v4.widget.DrawerLayout>

</LinearLayout>

Body:
<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:itemIconTint="@color/colorAccent"
    app:menu="@menu/activity_main_drawer">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:clickable="true"
        android:orientation="vertical">

        <TextView
            android:id="@+id/nav_footer_textview"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:gravity="center"
            android:text="Your Footer Text Here" />

    </LinearLayout>
</android.support.design.widget.NavigationView>

And for performing click on it:

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
TextView footerTV = (TextView) navigationView.findViewById(R.id.nav_footer_textview);
footerTV.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Toast.makeText(MainActivity.this, "Footer is clicked", Toast.LENGTH_SHORT).show();
    }
});


问:
SQL - how to update a column with each row value incremented by 1?
For the selected rows in a column, how to update each row sequentially from the beginning to the end, with each row value incremented by 1 (or certain number). I know this can be done in excel in few seconds but I could figure out how to achieve in SQL server. For instance:

customer id is NULL now
update customer id with every row incremented by 1 (i.e. first row = 1, second row = 2, .....nth row = n)

```<code>ship-to party   customer id
0002018092      NULL
0002008127      NULL
0002000129      NULL
0002031592      NULL
0002034232      NULL
</code>```

desired output

```<code>ship-to party   customer id
0002018092      1
0002008127      2
0002000129      3
0002031592      4
0002034232      5
</code>```

Also, for the selected rows in a column, how to update each row with the row number? I know there is a row_number() function but didn't succeed in producing the desired result. for instance

column A is NULL now
update Column A with every row incremented by 1 (i.e. first row = row number 1, second row = row number 2, .....nth row = row number n)

Any demonstration would be very helpful.thkans

答:
example : suppose I want to add a value to each value in column SomeIntField in table tblUser

there are 2 ways of doing this easy

first: this just adds value 1 to each column SomeIntField

```<code>update tblUser set SomeIntField = SomeIntField + 1
</code>```

second : this adds an incrementing value, the first row gets +1, second gets +2, and so on...

```<code>declare @number int = 0

update tblUser
set    @number = @number + 1,
       SomeIntField = isnull(SomeIntField, 0) + @Number
</code>```

EDIT: based on your last comment this might be what you want

```<code>declare @table table (shiptoparty varchar(50), customer_id int)

insert into @Table (shiptoparty, customer_id)
values ('0002018092', NULL), ('0002008127', NULL), ('0002000129', NULL), ('0002031592', NULL), ('0002034232', NULL)

declare @number int = 0

update @table
set    @number = @number + 1,
       customer_id = isnull(customer_id, 0) + @Number

select * from @table
</code>```

The result of this is :

```<code>shiptoparty | customer_id
----------- | -----------
0002018092  | 1
0002008127  | 2
0002000129  | 3
0002031592  | 4
0002034232  | 5
</code>```

Body:
For the selected rows in a column, how to update each row sequentially from the beginning to the end, with each row value incremented by 1 (or certain number). I know this can be done in excel in few seconds but I could figure out how to achieve in SQL server. For instance:

customer id is NULL now
update customer id with every row incremented by 1 (i.e. first row = 1, second row = 2, .....nth row = n)

ship-to party   customer id
0002018092      NULL
0002008127      NULL
0002000129      NULL
0002031592      NULL
0002034232      NULL

desired output

ship-to party   customer id
0002018092      1
0002008127      2
0002000129      3
0002031592      4
0002034232      5

Also, for the selected rows in a column, how to update each row with the row number? I know there is a row_number() function but didn't succeed in producing the desired result. for instance

column A is NULL now
update Column A with every row incremented by 1 (i.e. first row = row number 1, second row = row number 2, .....nth row = row number n)

Any demonstration would be very helpful.thkans

Body:
example : suppose I want to add a value to each value in column SomeIntField in table tblUser

there are 2 ways of doing this easy

first: this just adds value 1 to each column SomeIntField

update tblUser set SomeIntField = SomeIntField + 1

second : this adds an incrementing value, the first row gets +1, second gets +2, and so on...

declare @number int = 0

update tblUser
set    @number = @number + 1,
       SomeIntField = isnull(SomeIntField, 0) + @Number

EDIT: based on your last comment this might be what you want

declare @table table (shiptoparty varchar(50), customer_id int)

insert into @Table (shiptoparty, customer_id)
values ('0002018092', NULL), ('0002008127', NULL), ('0002000129', NULL), ('0002031592', NULL), ('0002034232', NULL)

declare @number int = 0

update @table
set    @number = @number + 1,
       customer_id = isnull(customer_id, 0) + @Number

select * from @table

The result of this is :

shiptoparty | customer_id
----------- | -----------
0002018092  | 1
0002008127  | 2
0002000129  | 3
0002031592  | 4
0002034232  | 5


问:
repeating previous regex
I have a line (and a arbitrary number of them)
0    1   1   75     55

I can get it by doing

```<code>x = re.search("\d+\s+\d+\s+(\d+)\s+(\d+)\s+(\d+)", line)
    if x != None:
        print(x.group(1))
        print(x.group(2))
        print(x.group(3))
</code>```

But there must be a neater way to write this. I was looking at the docs for something to repeat the previous expression and found (exp){m times}.

So I try

```<code>x = re.search("(\d+\s+){5}", line)
</code>```

and then expect x.group(1) to be 0, 2 to be 1, 3 to be 1 and so on
but x.group(1) ouputs 55 (the last number). Im sort of confused. Thanks.

Also on a side note. Do you guys have any recommendations for online tutorials (or free to download books) on regex?

答:
```<code>import re

line = '0 1 2 75 55'

x = re.search('\\s+'.join(5*('(\\d+)',)), line)

if x:
    print '\n'.join(x.group(3,4,5))
</code>```

Bof

Or, with idea of Sven Marnach:

```<code>print '\n'.join(line.split()[2:5])
</code>```

Title: repeating previous regex

Body:
I have a line (and a arbitrary number of them)
0    1   1   75     55

I can get it by doing

x = re.search("\d+\s+\d+\s+(\d+)\s+(\d+)\s+(\d+)", line)
    if x != None:
        print(x.group(1))
        print(x.group(2))
        print(x.group(3))

But there must be a neater way to write this. I was looking at the docs for something to repeat the previous expression and found (exp){m times}.

So I try

x = re.search("(\d+\s+){5}", line)

and then expect x.group(1) to be 0, 2 to be 1, 3 to be 1 and so on
but x.group(1) ouputs 55 (the last number). Im sort of confused. Thanks.

Also on a side note. Do you guys have any recommendations for online tutorials (or free to download books) on regex?

Body:
import re

line = '0 1 2 75 55'

x = re.search('\\s+'.join(5*('(\\d+)',)), line)

if x:
    print '\n'.join(x.group(3,4,5))

Bof

Or, with idea of Sven Marnach:

print '\n'.join(line.split()[2:5])


问:
Sub-classing the argparse Argument Parser
I am trying to write a parser class derived from the Python argparse ArgumentParser class. The outlines of the following code work fine on the command line but generate an error I am struggling to understand in the context of my module.

The code (stripped down a little to remove the unimportant stuff) is as follows:

```<code>class SansParser(argparse.ArgumentParser):
"""Argument parser for preparing a SansModel fit or calculation

"""

def __init__(self):
    """Initialisation method for the parser class"""

    argparse.ArgumentParser.__init__(self)

    # Subparsers for the two commands 'calc' and 'fit'
    self.subparsers = self.add_subparsers()
    self.fit_parser = self.subparsers.add_parser('fit', help="Fit a dataset")
    self.fit_parser.add_argument('-d', '-data', '-dataset', type = str,
                                 dest = 'dataset',
                                 help = "The dataset to fit in SasXML format")
    self.fit_parser.set_defaults(func=fit)
    self.calc_parser = self.subparsers.add_parser('calc', prog='test')
    self.calc_parser.set_defaults(func=calculate)
</code>```

I can run the equivalent of this as a script and its fine. If I run it from either shell or import into python command line and try to instantiate the class I get:

```<code>$ python sansmodel.py
    Traceback (most recent call last):
    File "sansmodel.py", line 57, in <module>
      parser = SansParser()
    File "sansmodel.py", line 41, in __init__
      self.fit_parser = self.subparsers.add_parser('fit', help="Fit a dataset")
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py",
    line 1064, in add_parser
      parser = self._parser_class(**kwargs)
 TypeError: __init__() got an unexpected keyword argument 'prog'
</code>```

As far as I can tell the code in argparse itself at line 1064 explicitly creates the 'prog' keyword and this is the expected behaviour so I'm confused as to where it is unexpected. I'm guessing I've got something backwards with the scope somehow?

答:
I got the same error this afternoon, and found your question when looking for some solution.

If you have read the ArgumentParser's __init__(), you could see that it accepts a series of arguments, including right the 'prog':

```<code>class ArgumentParser(_AttributeHolder, _ActionsContainer):
"""SOME DOC STRING..."""

    def __init__(self,
             prog=None,
             usage=None,
             description=None,
             epilog=None,
             parents=[],
             formatter_class=HelpFormatter,
             prefix_chars='-',
             fromfile_prefix_chars=None,
             argument_default=None,
             conflict_handler='error',
             add_help=True,
             allow_abbrev=True):
        ...... # SOME IMPLEMENTATION
</code>```

I think the fact is: the custom parser class overridden the __init__() method, and accepts no argument. But other methods are not modified. This made the methods' behaviors conflict. When creating sub parser, add_parser() calls the parser's __init__() with arguments including 'prog'. To ArgumentParser, it's ok, but to the custom parser with overridden __init__(), obviously it will fail.

Of course @jcollado's suggestion works fine, but seems it also cancels the customization of sub parser's behavior.

My solution to this problem, a little ugly but also works well. When overriding the __init__() of ArgumentParser, just keep every argument and its default value. Like this:

```<code>class MyParser(argparse.ArgumentParser):
    def __init__(
        self,
        prog=None,
        usage=None,
        description=None,
        epilog=None,
        parents=[],
        formatter_class=argparse.HelpFormatter,
        prefix_chars='-',
        fromfile_prefix_chars=None,
        argument_default=None,
        conflict_handler='error',
        add_help=True,
        allow_abbrev=True
        # and your custom arguments here
        ):

        super(MyParser, self).__init__(prog=prog, usage=usage, description=description, epilog=epilog,
                                   parents=parents, formatter_class=formatter_class,
                                   prefix_chars=prefix_chars, fromfile_prefix_chars=fromfile_prefix_chars,
                                   argument_default=argument_default, conflict_handler=conflict_handler,
                                   add_help=add_help, allow_abbrev=allow_abbrev
                                   )
        # and your custom actions here
</code>```

Body:
I am trying to write a parser class derived from the Python argparse ArgumentParser class. The outlines of the following code work fine on the command line but generate an error I am struggling to understand in the context of my module.

The code (stripped down a little to remove the unimportant stuff) is as follows:

class SansParser(argparse.ArgumentParser):
"""Argument parser for preparing a SansModel fit or calculation

"""

def __init__(self):
    """Initialisation method for the parser class"""

    argparse.ArgumentParser.__init__(self)

    # Subparsers for the two commands 'calc' and 'fit'
    self.subparsers = self.add_subparsers()
    self.fit_parser = self.subparsers.add_parser('fit', help="Fit a dataset")
    self.fit_parser.add_argument('-d', '-data', '-dataset', type = str,
                                 dest = 'dataset',
                                 help = "The dataset to fit in SasXML format")
    self.fit_parser.set_defaults(func=fit)
    self.calc_parser = self.subparsers.add_parser('calc', prog='test')
    self.calc_parser.set_defaults(func=calculate)

I can run the equivalent of this as a script and its fine. If I run it from either shell or import into python command line and try to instantiate the class I get:

$ python sansmodel.py
    Traceback (most recent call last):
    File "sansmodel.py", line 57, in <module>
      parser = SansParser()
    File "sansmodel.py", line 41, in __init__
      self.fit_parser = self.subparsers.add_parser('fit', help="Fit a dataset")
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py",
    line 1064, in add_parser
      parser = self._parser_class(**kwargs)
 TypeError: __init__() got an unexpected keyword argument 'prog'

As far as I can tell the code in argparse itself at line 1064 explicitly creates the 'prog' keyword and this is the expected behaviour so I'm confused as to where it is unexpected. I'm guessing I've got something backwards with the scope somehow?

Body:
I got the same error this afternoon, and found your question when looking for some solution.

If you have read the ArgumentParser's __init__(), you could see that it accepts a series of arguments, including right the 'prog':

class ArgumentParser(_AttributeHolder, _ActionsContainer):
"""SOME DOC STRING..."""

    def __init__(self,
             prog=None,
             usage=None,
             description=None,
             epilog=None,
             parents=[],
             formatter_class=HelpFormatter,
             prefix_chars='-',
             fromfile_prefix_chars=None,
             argument_default=None,
             conflict_handler='error',
             add_help=True,
             allow_abbrev=True):
        ...... # SOME IMPLEMENTATION

I think the fact is: the custom parser class overridden the __init__() method, and accepts no argument. But other methods are not modified. This made the methods' behaviors conflict. When creating sub parser, add_parser() calls the parser's __init__() with arguments including 'prog'. To ArgumentParser, it's ok, but to the custom parser with overridden __init__(), obviously it will fail.

Of course @jcollado's suggestion works fine, but seems it also cancels the customization of sub parser's behavior.

My solution to this problem, a little ugly but also works well. When overriding the __init__() of ArgumentParser, just keep every argument and its default value. Like this:

class MyParser(argparse.ArgumentParser):
    def __init__(
        self,
        prog=None,
        usage=None,
        description=None,
        epilog=None,
        parents=[],
        formatter_class=argparse.HelpFormatter,
        prefix_chars='-',
        fromfile_prefix_chars=None,
        argument_default=None,
        conflict_handler='error',
        add_help=True,
        allow_abbrev=True
        # and your custom arguments here
        ):

        super(MyParser, self).__init__(prog=prog, usage=usage, description=description, epilog=epilog,
                                   parents=parents, formatter_class=formatter_class,
                                   prefix_chars=prefix_chars, fromfile_prefix_chars=fromfile_prefix_chars,
                                   argument_default=argument_default, conflict_handler=conflict_handler,
                                   add_help=add_help, allow_abbrev=allow_abbrev
                                   )
        # and your custom actions here


问:
What syntax is causing an error "SyntaxError: missing ; after for-loop condition"?
```<code>$.getJSON("blogData.json", function(data) {

if((Object.keys(data).length) < 2){
    for(var i=0; i =Object.keys(data).length){
    $("#blogPosts").append("<h3>" + data[data.length-i].title + "</h3>");
    $("#blogPosts").append("<h4>" + data[data.length-i].desc + "</h4>");
    $("#blogPosts").append("<h4>" + data[data.length-i].author + "</h4>");
    $("#blogPosts").append("<p>" + data[data.length-i].post + "</p>");
    $("#blogPosts").append("<br>");
    }
}
else{
    for(var x=0; x = 2; x++; ){
    $("#blogPosts").append("<h3>" + data[data.length-i].title+ "</h3>");
    $("#blogPosts").append("<h4>" + data[data.length-i].desc + "</h4>");
    $("#blogPosts").append("<h4>" + data[data.length-i].author + "</h4>");
    $("#blogPosts").append("<p>" + data[data.length-i].post + "</p>");
    $("#blogPosts").append("<br>");

}
}

});
</code>```

<p>I am unable to work out why this is causing an issue in my website? I would like the JSON array to be displayed but only the 2 most recent records added to the array? Anybody able to advise on this issue?  </p>

答:
You need to increment i in the upper loop:

```<code>for(var i=0; i =Object.keys(data).length; i++){ // increment i
    $("#blogPosts").append("<h3>" + data[data.length-i].title + "</h3>");
    $("#blogPosts").append("<h4>" + data[data.length-i].desc + "</h4>");
    $("#blogPosts").append("<h4>" + data[data.length-i].author + "</h4>");
    $("#blogPosts").append("<p>" + data[data.length-i].post + "</p>");
    $("#blogPosts").append("<br>");
}
</code>```

You can find the documentation for JavaScript for loops at developer.mozilla.org

Body:
$.getJSON("blogData.json", function(data) {

if((Object.keys(data).length) < 2){
    for(var i=0; i =Object.keys(data).length){
    $("#blogPosts").append("
" + data[data.length-i].title + "
");
    $("#blogPosts").append("
" + data[data.length-i].desc + "
");
    $("#blogPosts").append("
" + data[data.length-i].author + "
");
    $("#blogPosts").append("
" + data[data.length-i].post + "
");
    $("#blogPosts").append("
");
    }
}
else{
    for(var x=0; x = 2; x++; ){
    $("#blogPosts").append("
" + data[data.length-i].title+ "
");
    $("#blogPosts").append("
" + data[data.length-i].desc + "
");
    $("#blogPosts").append("
" + data[data.length-i].author + "
");
    $("#blogPosts").append("
" + data[data.length-i].post + "
");
    $("#blogPosts").append("
");

}
}

});

I am unable to work out why this is causing an issue in my website? I would like the JSON array to be displayed but only the 2 most recent records added to the array? Anybody able to advise on this issue?

Body:
You need to increment i in the upper loop:

for(var i=0; i =Object.keys(data).length; i++){ // increment i
    $("#blogPosts").append("<h3>" + data[data.length-i].title + "</h3>");
    $("#blogPosts").append("<h4>" + data[data.length-i].desc + "</h4>");
    $("#blogPosts").append("<h4>" + data[data.length-i].author + "</h4>");
    $("#blogPosts").append("<p>" + data[data.length-i].post + "</p>");
    $("#blogPosts").append("<br>");
}

You can find the documentation for JavaScript for loops at developer.mozilla.org


问:
neo4j: extraction of random graphs
We have a big graph database made with Neo4j which has two type of relationships "E" and "I".

We would like to extract two graphs from it with a starting node called n0.
The first graph Gxi, based on the "I" relationship, must be obtained randomly.
The following request is wrong but this is the idea we want to implement. Here 10 neighbors are randomly chosen for each node of the last step

```<code>MATCH r1:(n0)-[:I]-(n1)
WITH random(n1) LIMIT 10
MATCH r2:(n1)-[:I]-(n2)
WITH random(n2) LIMIT 10*10
MATCH r3:(n2)-[:I]-(n3)
WITH random(n3) LIMIT 10*10*10
MATCH r4:(n4)-[:I]-(n4)
WITH random(n4) LIMIT 10*10*10*10
RETURN r1+r2+r3+r4
</code>```

Then we would like to create the second graph Gxe based on the relationships "E" and the nodes of Gxi.

Thank you for your help.

答:
APOC Procedures may be able to help here. There are collection functions that can be used to choose random items from a collection, and you can get slices of the collection rather than having to use LIMIT.

The trickier part will actually be collecting the subpaths along the way.

```<code>// assume already matched to start node n
MATCH r = (n)-[:I]-()
WITH apoc.coll.randomItems(collect(r), 10) as r1
UNWIND r1 as r
WITH r1, last(nodes(r)) as n

MATCH r = (n)-[:I]-()
WITH r1, apoc.coll.randomItems(collect(r), 10) as r2
UNWIND r2 as r
WITH r1, r2, last(nodes(r)) as n

MATCH r = (n)-[:I]-()
WITH r1, r2, apoc.coll.randomItems(collect(r), 10) as r3
UNWIND r3 as r
WITH r1, r2, r3, last(nodes(r)) as n

MATCH r = (n)-[:I]-()
WITH r1, r2, r3, apoc.coll.randomItems(collect(r), 10) as r4
RETURN r1 + r2 + r3 + r4
</code>```

Title: neo4j: extraction of random graphs

Body:
We have a big graph database made with Neo4j which has two type of relationships "E" and "I".

We would like to extract two graphs from it with a starting node called n0.
The first graph Gxi, based on the "I" relationship, must be obtained randomly.
The following request is wrong but this is the idea we want to implement. Here 10 neighbors are randomly chosen for each node of the last step

MATCH r1:(n0)-[:I]-(n1)
WITH random(n1) LIMIT 10
MATCH r2:(n1)-[:I]-(n2)
WITH random(n2) LIMIT 10*10
MATCH r3:(n2)-[:I]-(n3)
WITH random(n3) LIMIT 10*10*10
MATCH r4:(n4)-[:I]-(n4)
WITH random(n4) LIMIT 10*10*10*10
RETURN r1+r2+r3+r4

Then we would like to create the second graph Gxe based on the relationships "E" and the nodes of Gxi.

Thank you for your help.

Body:
APOC Procedures may be able to help here. There are collection functions that can be used to choose random items from a collection, and you can get slices of the collection rather than having to use LIMIT.

The trickier part will actually be collecting the subpaths along the way.

// assume already matched to start node n
MATCH r = (n)-[:I]-()
WITH apoc.coll.randomItems(collect(r), 10) as r1
UNWIND r1 as r
WITH r1, last(nodes(r)) as n

MATCH r = (n)-[:I]-()
WITH r1, apoc.coll.randomItems(collect(r), 10) as r2
UNWIND r2 as r
WITH r1, r2, last(nodes(r)) as n

MATCH r = (n)-[:I]-()
WITH r1, r2, apoc.coll.randomItems(collect(r), 10) as r3
UNWIND r3 as r
WITH r1, r2, r3, last(nodes(r)) as n

MATCH r = (n)-[:I]-()
WITH r1, r2, r3, apoc.coll.randomItems(collect(r), 10) as r4
RETURN r1 + r2 + r3 + r4


Title: Python function to find indexes of 1s in binary array and

Body:
Here's one compact way -

2**np.where(a)[0]

Sample run -

In [83]: a = np.array([1, 0, 1 , 0 , 0, 1])

In [84]: 2**np.where(a)[0]
Out[84]: array([ 1,  4, 32])


问:
sprite animation using cocos2d working on simulator but not on device
i've got a 2 frame sprite animation running along a bezier path using ccbezierto. this works perfectly fine on the simulator, no warning no errors. but strange thing is on my iphone 3GS device, the animation and the ccbezierto action does not show up on screen, the sprite disappears for the duration of the supposed animation and pops back at the designated position.

so anyone got experience with this kind of thing? or is it a bug?

答: Check the case on the spelling of your sprite sheet -- the simulator will check for up and downcase versions of the same resource, the iPhone won't. </p>


问:
JAXRS - Query Params are empty strings
I am trying to create a simple rest service that reads the query params in a url.

```<code>public Response getBalanceSnapshot(
    @DefaultValue("abc") @QueryParam("typeofid") String t,
    @DefaultValue("def") @QueryParam("id") String i) {

    //    public Response getBalanceSnapshot(@Context UriInfo uriInfo) {
    //    String t = uriInfo.getQueryParameters().getFirst("parameter1");
    //    String i = uriInfo.getQueryParameters().getFirst("parameter1");

    if (i == null) {
        throw new WebApplicationException(
                Response.status(HttpURLConnection.HTTP_BAD_REQUEST)
                        .entity("name parameter is mandatory")
                        .build());
    }

    if (t.length() == 0) {
        return Response.status(200).entity("empty string").build();
    }

    return Response.status(200)
            .entity("query params are " + t + " and " + i)
           .build();
}
</code>```

If request is -
http://localhost:8080/sampleresource/firstendpoint?typeofid=acc_id&id=1234

Then expected response is query params are acc_id and 1234.
Actual response is . query params are

The strings are not null. But both lengths are 0.

I have also tried using the URI info to get the params. But that gives a different error.

答:
Let's test some other features of Java.

```<code>public class Test {
    public static void main(final String... args) {
        final String s = null;
        System.out.println("aaa" + s + "bbb");
    }
}
</code>```

The program prints

```<code>aaanullbbb
</code>```

not

```<code>aaabbb
</code>```

When you see

```<code>query params are  and
</code>```

not

```<code>query params are acc_id and 1234
</code>```

That means the t ant the i is actually "", not null.

Are you sure you're requesting to the right method?

Title: JAXRS - Query Params are empty strings

Body:
I am trying to create a simple rest service that reads the query params in a url.

public Response getBalanceSnapshot(
    @DefaultValue("abc") @QueryParam("typeofid") String t,
    @DefaultValue("def") @QueryParam("id") String i) {

    //    public Response getBalanceSnapshot(@Context UriInfo uriInfo) {
    //    String t = uriInfo.getQueryParameters().getFirst("parameter1");
    //    String i = uriInfo.getQueryParameters().getFirst("parameter1");

    if (i == null) {
        throw new WebApplicationException(
                Response.status(HttpURLConnection.HTTP_BAD_REQUEST)
                        .entity("name parameter is mandatory")
                        .build());
    }

    if (t.length() == 0) {
        return Response.status(200).entity("empty string").build();
    }

    return Response.status(200)
            .entity("query params are " + t + " and " + i)
           .build();
}

If request is -
http://localhost:8080/sampleresource/firstendpoint?typeofid=acc_id&id=1234

Then expected response is query params are acc_id and 1234.
Actual response is . query params are

The strings are not null. But both lengths are 0.

I have also tried using the URI info to get the params. But that gives a different error.

Body:
Let's test some other features of Java.

public class Test {
    public static void main(final String... args) {
        final String s = null;
        System.out.println("aaa" + s + "bbb");
    }
}

The program prints

aaanullbbb

not

aaabbb

When you see

query params are  and

not

query params are acc_id and 1234

That means the t ant the i is actually "", not null.

Are you sure you're requesting to the right method?


问:
Does anyone know of a reg expression for uk date format
Hi does any one know a reg ex for a uk date format e.g. dd/mm/yyyy.

The dd or mm can be 1 character e.g. 1/1/2010 but the year must always be 4 characters.

Thanks in advance

答:
There are two things you want to do, which in my view are best considered separately

1) You want to make sure that the date is a real, actual date.
For example the 2019-02-29 isn't a real date whereas 2020-02-29 is a real date because 2020 is a leap year

2) You want to check that the date is in the correct format (so dd/mm/yyyy)

The second point can be done easily enough with a simple RegEx, plenty of examples of that.

To complicate matters, if you ask Firefox if 2019-02-29 is a real date, it'll return NaN, which is what you'd expect.

Chrome, on the other hand will say it is a real date and give you back the 1st of March 2019 - which will validate

Chrome, will also accept a single digit number as a proper date too for some strange reason, feed it "2" and it'll give you full date from 2001 back - which will validate

So first step is to create a function which attempts to decipher a date (no matter the format) and works cross-browser to return a boolean indicating if the date is valid or not

```<code>function validatableDate(value)
{
    Date.prototype.isValid = function()
    {   // An invalid date object returns NaN for getTime() and NaN is the only
        // object not strictly equal to itself.
        return this.getTime() === this.getTime();
    };
    minTwoDigits = function(n)
    {   //pads any digit less than 10 with a leading 0
        return (parseInt(n) < 10 ? '0' : '') + parseInt(n);
    }
    var valid_date = false;
    var iso_array = null;
    // check if there are date dividers (gets around chrome allowing single digit numbers)
    if ((value.indexOf('/') != -1) || (value.indexOf('-') != -1)) { //if we're dealing with - dividers we'll do some pre-processing and swap them out for /
        if (value.indexOf('-') != -1) {
            dash_parts = value.split('-');
            value = dash_parts.join("/");
            //if we have a leading year, we'll put it at the end and work things out from there
            if (dash_parts[0].length > 2) {
                value = dash_parts[1] + '/' + dash_parts[2] + '/' + dash_parts[0];
            }
        }

        parts = value.split('/');
        if (parts[0] > 12) { //convert to ISO from UK dd/mm/yyyy format
            iso_array = [parts[2], minTwoDigits(parts[1]), minTwoDigits(parts[0])]
        } else if (parts[1] > 12) { //convert to ISO from American mm/dd/yyyy format
            iso_array = [parts[2], minTwoDigits(parts[0]), minTwoDigits(parts[1])]
        } else //if a date is valid in either UK or US (e.g. 12/12/2017 , 10/10/2017) then we don't particularly care what format it is in - it's valid regardless
        {
            iso_array = [parts[2], minTwoDigits(parts[0]), minTwoDigits(parts[1])]
        }

        if (Array.isArray(iso_array)) {
            value = iso_array.join("-");
            var d = new Date(value + 'T00:00:01Z');
            if (d.isValid()) //test if it is a valid date (there are issues with this in Chrome with Feb)
            {
                valid_date = true;
            }
            //if the month is Feb we need to do another step to cope with Chrome peculiarities
            if (parseInt(iso_array[1]) == 2) {
                month_info = new Date(iso_array[0], iso_array[1], 0);
                //if the day inputed is larger than the last day of the February in that year
                if (iso_array[2] > month_info.getDate()) {
                    valid_date = false;
                }
            }
        }
    }
    return valid_date;
}
</code>```

That can be compressed down to

```<code>function validatableDate(t) {
    Date.prototype.isValid = function () {
        return this.getTime() === this.getTime()
    }, minTwoDigits = function (t) {
        return (parseInt(t) < 10 ? "0" : "") + parseInt(t)
    };
    var a = !1,
        i = null;
    return -1 == t.indexOf("/") && -1 == t.indexOf("-") || (-1 != t.indexOf("-") && (dash_parts = t.split("-"), t = dash_parts.join("/"), dash_parts[0].length > 2 && (t = dash_parts[1] + "/" + dash_parts[2] + "/" + dash_parts[0])), parts = t.split("/"), i = parts[0] > 12 ? [parts[2], minTwoDigits(parts[1]), minTwoDigits(parts[0])] : (parts[1], [parts[2], minTwoDigits(parts[0]), minTwoDigits(parts[1])]), Array.isArray(i) && (t = i.join("-"), new Date(t + "T00:00:01Z").isValid() && (a = !0), 2 == parseInt(i[1]) && (month_info = new Date(i[0], i[1], 0), i[2] > month_info.getDate() && (a = !1)))), a
}
</code>```

That gets you a cross-browser test as to whether the date can be validated or not and it'll read & decipher dates in formats

yyyy-mm-dd

dd-mm-yyyy

mm-dd-yyyy

dd/mm/yyyy

mm/dd/yyyy

Once you've validated the date is a real, proper one you can then test the format with a regex. So for UK dd/mm/yy

```<code>function dateUK(value) {
    valid_uk_date=false;
    valid_date=validatableDate(value);
    if(valid_date && value.match(/^(0?[1-9]|[12][0-9]|3[01])[\/](0?[1-9]|1[012])[\/]\d{4}$/))
    {   valid_uk_date=true;
    }
    return  valid_uk_date;
}
</code>```

You then know that the date is a real one and that it's in the correct format.

For yyyy-mm-dd format, you'd do:

```<code>function dateISO(value) {
    valid_iso_date=false;
    valid_date=validatableDate(value);
    if(valid_date && value.match(/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/))
    {   valid_iso_date=true;
    }
    return  valid_iso_date;
}
</code>```

It depends how thorough you want to be of course, for a rough check of format sanity a RegEx may be enough for your purposes. If however you want to test if the date is a real one AND if the format is valid then this will hopefully help point you along the way

Thanks

Body:
There are two things you want to do, which in my view are best considered separately

1) You want to make sure that the date is a real, actual date.
For example the 2019-02-29 isn't a real date whereas 2020-02-29 is a real date because 2020 is a leap year

2) You want to check that the date is in the correct format (so dd/mm/yyyy)

The second point can be done easily enough with a simple RegEx, plenty of examples of that.

To complicate matters, if you ask Firefox if 2019-02-29 is a real date, it'll return NaN, which is what you'd expect.

Chrome, on the other hand will say it is a real date and give you back the 1st of March 2019 - which will validate

Chrome, will also accept a single digit number as a proper date too for some strange reason, feed it "2" and it'll give you full date from 2001 back - which will validate

So first step is to create a function which attempts to decipher a date (no matter the format) and works cross-browser to return a boolean indicating if the date is valid or not

function validatableDate(value)
{
    Date.prototype.isValid = function()
    {   // An invalid date object returns NaN for getTime() and NaN is the only
        // object not strictly equal to itself.
        return this.getTime() === this.getTime();
    };
    minTwoDigits = function(n)
    {   //pads any digit less than 10 with a leading 0
        return (parseInt(n) < 10 ? '0' : '') + parseInt(n);
    }
    var valid_date = false;
    var iso_array = null;
    // check if there are date dividers (gets around chrome allowing single digit numbers)
    if ((value.indexOf('/') != -1) || (value.indexOf('-') != -1)) { //if we're dealing with - dividers we'll do some pre-processing and swap them out for /
        if (value.indexOf('-') != -1) {
            dash_parts = value.split('-');
            value = dash_parts.join("/");
            //if we have a leading year, we'll put it at the end and work things out from there
            if (dash_parts[0].length > 2) {
                value = dash_parts[1] + '/' + dash_parts[2] + '/' + dash_parts[0];
            }
        }

        parts = value.split('/');
        if (parts[0] > 12) { //convert to ISO from UK dd/mm/yyyy format
            iso_array = [parts[2], minTwoDigits(parts[1]), minTwoDigits(parts[0])]
        } else if (parts[1] > 12) { //convert to ISO from American mm/dd/yyyy format
            iso_array = [parts[2], minTwoDigits(parts[0]), minTwoDigits(parts[1])]
        } else //if a date is valid in either UK or US (e.g. 12/12/2017 , 10/10/2017) then we don't particularly care what format it is in - it's valid regardless
        {
            iso_array = [parts[2], minTwoDigits(parts[0]), minTwoDigits(parts[1])]
        }

        if (Array.isArray(iso_array)) {
            value = iso_array.join("-");
            var d = new Date(value + 'T00:00:01Z');
            if (d.isValid()) //test if it is a valid date (there are issues with this in Chrome with Feb)
            {
                valid_date = true;
            }
            //if the month is Feb we need to do another step to cope with Chrome peculiarities
            if (parseInt(iso_array[1]) == 2) {
                month_info = new Date(iso_array[0], iso_array[1], 0);
                //if the day inputed is larger than the last day of the February in that year
                if (iso_array[2] > month_info.getDate()) {
                    valid_date = false;
                }
            }
        }
    }
    return valid_date;
}

That can be compressed down to

function validatableDate(t) {
    Date.prototype.isValid = function () {
        return this.getTime() === this.getTime()
    }, minTwoDigits = function (t) {
        return (parseInt(t) < 10 ? "0" : "") + parseInt(t)
    };
    var a = !1,
        i = null;
    return -1 == t.indexOf("/") && -1 == t.indexOf("-") || (-1 != t.indexOf("-") && (dash_parts = t.split("-"), t = dash_parts.join("/"), dash_parts[0].length > 2 && (t = dash_parts[1] + "/" + dash_parts[2] + "/" + dash_parts[0])), parts = t.split("/"), i = parts[0] > 12 ? [parts[2], minTwoDigits(parts[1]), minTwoDigits(parts[0])] : (parts[1], [parts[2], minTwoDigits(parts[0]), minTwoDigits(parts[1])]), Array.isArray(i) && (t = i.join("-"), new Date(t + "T00:00:01Z").isValid() && (a = !0), 2 == parseInt(i[1]) && (month_info = new Date(i[0], i[1], 0), i[2] > month_info.getDate() && (a = !1)))), a
}

That gets you a cross-browser test as to whether the date can be validated or not and it'll read & decipher dates in formats

yyyy-mm-dd

dd-mm-yyyy

mm-dd-yyyy

dd/mm/yyyy

mm/dd/yyyy

Once you've validated the date is a real, proper one you can then test the format with a regex. So for UK dd/mm/yy

function dateUK(value) {
    valid_uk_date=false;
    valid_date=validatableDate(value);
    if(valid_date && value.match(/^(0?[1-9]|[12][0-9]|3[01])[\/](0?[1-9]|1[012])[\/]\d{4}$/))
    {   valid_uk_date=true;
    }
    return  valid_uk_date;
}

You then know that the date is a real one and that it's in the correct format.

For yyyy-mm-dd format, you'd do:

function dateISO(value) {
    valid_iso_date=false;
    valid_date=validatableDate(value);
    if(valid_date && value.match(/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/))
    {   valid_iso_date=true;
    }
    return  valid_iso_date;
}

It depends how thorough you want to be of course, for a rough check of format sanity a RegEx may be enough for your purposes. If however you want to test if the date is a real one AND if the format is valid then this will hopefully help point you along the way

Thanks