问:
Session store not set on request in Laravel 5.3
My website got an error like this:

I also tried some solution like wrap Route in middleware web it it didn't works

Here is my Kernel.php

```<code><?php

namespace App\Http;

use App\Http\Middleware\Activated;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{

    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \anlutro\LaravelSettings\SaveMiddleware::class,
            \Barryvdh\Cors\HandleCors::class,
            Activated::class
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
(The rest of file)
    }
</code>```

How can i resolve that :((

答:
You'll need to use the web middleware if you need session state, CSRF protection, and more.

```<code>Route::group(['middleware' => ['web']], function () {
    // your routes here
});
</code>```

your kernel.php should look like this

```<code>protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Session\Middleware\StartSession::class,
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,

            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \anlutro\LaravelSettings\SaveMiddleware::class,
            \Barryvdh\Cors\HandleCors::class,
            Activated::class
        ],
</code>```

Body:
My website got an error like this:

I also tried some solution like wrap Route in middleware web it it didn't works

Here is my Kernel.php

<?php

namespace App\Http;

use App\Http\Middleware\Activated;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{

    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \anlutro\LaravelSettings\SaveMiddleware::class,
            \Barryvdh\Cors\HandleCors::class,
            Activated::class
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
(The rest of file)
    }

How can i resolve that :((

Body:
You'll need to use the web middleware if you need session state, CSRF protection, and more.

Route::group(['middleware' => ['web']], function () {
    // your routes here
});

your kernel.php should look like this

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Session\Middleware\StartSession::class,
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,

            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \anlutro\LaravelSettings\SaveMiddleware::class,
            \Barryvdh\Cors\HandleCors::class,
            Activated::class
        ],


来源: stackexchange

问:
Show Notice: "Undefined variable: arr on line 40" when data table is empty
I made a public function View() under a class Delivary(). But in line 40 I return $arr. Now it show Undefined variable: arr when my data table is empty.
Notice: Undefined variable: arr in C:\xampp\htdocs\online shop\dataAccessLayer\dalDelivary.php on line 40

My code is:

```<code>class Delivary {

public $place;
public $address;
public $amount;
public $date;
public $payment;
public $walletnumber;
public $user_id;

public function DB()
{
    $connection = mysqli_connect("localhost","root","","project");
    return $connection;
}

public function Insert()
{
    $sql = "INSERT INTO delivery (place, address, amount, `date`,payment, walletnumber, user_id) VALUES
    ('$this->place', '$this->address', '$this->amount', '$this->date', '$this->payment', '$this->walletnumber', '$this->user_id');";
    if(mysqli_query($this->DB(), $sql))
    {
        return true;
    }
        return false;
}

public function View()
{
    $sql = "SELECT delivery.delivery_id, service.area, delivery.address, delivery.amount, delivery.date, delivery.payment, delivery.walletnumber, delivery.user_id FROM delivery, service WHERE service.service_id = delivery.place";
    $result = mysqli_query($this->DB(),$sql);
    while($d = mysqli_fetch_row($result))
        {
            $arr[] = $d;
        }
        return $arr; //line 40
}
public function Delete()
    {
        $sql = "DELETE FROM delivery WHERE delivery_id = '".$this->delivery_id."'";
        if(mysqli_query($this->DB(), $sql))
        {
            return true;
        }
        return false;
    }}
</code>```

答:
You're accessing $arr like an array before it's been defined as one. To eliminate this notice (Which is more a warning than an error), simply define the array before you use it:

```<code>$arr = [];
while($d = mysqli_fetch_row($result))
{
     $arr[] = $d;
}
return $arr; //line 40
</code>```

Make sure you're checking for errors from the return of the mysqli_query function:

```<code>$conn = $this->DB();
$sql = "SELECT delivery.delivery_id, service.area, delivery.address, delivery.amount, delivery.date, delivery.payment, delivery.walletnumber, delivery.user_id FROM delivery, service WHERE service.service_id = delivery.place";
$result = mysqli_query($conn, $sql);
if ( !$result ) {
    echo "There was an error executing this query: ", mysqli_error($conn);
    exit;
}
$arr = [];
while($d = mysqli_fetch_row($result))
{
    $arr[] = $d;
}
return $arr;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I made a public function View() under a class Delivary(). But in line 40 I return $arr. Now it show Undefined variable: arr when my data table is empty.
Notice: Undefined variable: arr in C:\xampp\htdocs\online shop\dataAccessLayer\dalDelivary.php on line 40

My code is:

class Delivary {

public $place;
public $address;
public $amount;
public $date;
public $payment;
public $walletnumber;
public $user_id;

public function DB()
{
    $connection = mysqli_connect("localhost","root","","project");
    return $connection;
}

public function Insert()
{
    $sql = "INSERT INTO delivery (place, address, amount, `date`,payment, walletnumber, user_id) VALUES
    ('$this->place', '$this->address', '$this->amount', '$this->date', '$this->payment', '$this->walletnumber', '$this->user_id');";
    if(mysqli_query($this->DB(), $sql))
    {
        return true;
    }
        return false;
}

public function View()
{
    $sql = "SELECT delivery.delivery_id, service.area, delivery.address, delivery.amount, delivery.date, delivery.payment, delivery.walletnumber, delivery.user_id FROM delivery, service WHERE service.service_id = delivery.place";
    $result = mysqli_query($this->DB(),$sql);
    while($d = mysqli_fetch_row($result))
        {
            $arr[] = $d;
        }
        return $arr; //line 40
}
public function Delete()
    {
        $sql = "DELETE FROM delivery WHERE delivery_id = '".$this->delivery_id."'";
        if(mysqli_query($this->DB(), $sql))
        {
            return true;
        }
        return false;
    }}

Body:
You're accessing $arr like an array before it's been defined as one. To eliminate this notice (Which is more a warning than an error), simply define the array before you use it:

$arr = [];
while($d = mysqli_fetch_row($result))
{
     $arr[] = $d;
}
return $arr; //line 40

Make sure you're checking for errors from the return of the mysqli_query function:

$conn = $this->DB();
$sql = "SELECT delivery.delivery_id, service.area, delivery.address, delivery.amount, delivery.date, delivery.payment, delivery.walletnumber, delivery.user_id FROM delivery, service WHERE service.service_id = delivery.place";
$result = mysqli_query($conn, $sql);
if ( !$result ) {
    echo "There was an error executing this query: ", mysqli_error($conn);
    exit;
}
$arr = [];
while($d = mysqli_fetch_row($result))
{
    $arr[] = $d;
}
return $arr;


问:
Preventing keys of different hash values from landing in same bucket with unordered_set
This might be a silly question, but here goes :

I hashed a dictionary of words into an unordered_set based hash-table. My hash function was made intentionally "bad", in that all strings that contained the same set of letters would hash to the same value. I initially tried to over-ride the normal hash function behaviour, and use a "frequency histogram" of the letters in each word as a hash value (which I learnt was impossible :) ), but one of the threads suggested using a 26-bit bitmask to achieve the same. The hash function works fine and dandy thus far.

For example, in my scheme, CITIED and CITED hash to the same value, 1049144. My idea was that given a set of letters, I wanted to find all the words containing letters from that set.

I am guessing that I haven't quite understood the concept of hashing (or my code is plain wrong), as I can't quite explain the behaviour I encountered :

I decided to look for all words which consisted of letters from the string "LIVEN".
My output (with hash key) was as follows :

```<code>VENVILLE,4215328
LEVIN,4215328
ENLIVEN,4215328
CURTSEYED,37486648
</code>```

How on earth did CURTSEYED land up there? As can be seen, it has a different hash value from the remaining three words. Where does the fault lie with my understanding/implementation of the hash table?

Code that produced above output:

```<code>
    typedef std::unordered_set&lt std::string, my_string_hash_function, my_string_equality&gt Dict
    DictHash dict;
    DictHash::const_local_iterator c_l_itr;

    DictHash::size_type bs = dict.bucket (std::string ("LIVEN"));
    for (c_l_itr = dict.begin(bs); c_l_itr != dict.end(bs); c_l_itr++)
         std::cout ```

My hash function :

```<code>struct my_string_hash_function
{
    std::size_t operator()(const std::string& s) const
    {
        unsigned long hash = 0;
        std::string::const_iterator itr;

        for (itr = s.begin(); itr != s.end(); itr++)
     hash |= 2 << (*itr - int('A'));

      return hash;
    }
};
</code>```

Comparison function :

```struct my_string_equality
{
    bool operator()(const std::string& s1, const std::string& s2) const
    {
        if (s1.length() != s2.length())
     return false;

        unsigned int hash1 = 0, hash2 = 0;
        const char *str1, *str2;
        int i,len;

        len = s1.length();
        str1 = s1.c_str();
        str2 = s2.c_str();

        for (i = 0; i < len; i++)
        {
            hash1 |= 2 << (str1[i] - (int)'A');
            hash2 |= 2 << (str2[i] - (int)'A');
        }

        return hash1 == hash2;
   }
};
</code>```

答: I think you've also got a potential bug in the my_string_equality... don't you just want to use the regular std::string::operator==()?  AFAIK you should be doing a comparison of the actual object values, not a comparison of their hash (the container already knows the hash value, it could just call my_string_hash_function and compare the results if that was what it needed to do).

ContentLicense: CC BY-SA 2.5

Body:
This might be a silly question, but here goes :

I hashed a dictionary of words into an unordered_set based hash-table. My hash function was made intentionally "bad", in that all strings that contained the same set of letters would hash to the same value. I initially tried to over-ride the normal hash function behaviour, and use a "frequency histogram" of the letters in each word as a hash value (which I learnt was impossible :) ), but one of the threads suggested using a 26-bit bitmask to achieve the same. The hash function works fine and dandy thus far.

For example, in my scheme, CITIED and CITED hash to the same value, 1049144. My idea was that given a set of letters, I wanted to find all the words containing letters from that set.

I am guessing that I haven't quite understood the concept of hashing (or my code is plain wrong), as I can't quite explain the behaviour I encountered :

I decided to look for all words which consisted of letters from the string "LIVEN".
My output (with hash key) was as follows :

VENVILLE,4215328
LEVIN,4215328
ENLIVEN,4215328
CURTSEYED,37486648

How on earth did CURTSEYED land up there? As can be seen, it has a different hash value from the remaining three words. Where does the fault lie with my understanding/implementation of the hash table?

Code that produced above output:

    typedef std::unordered_set&lt std::string, my_string_hash_function, my_string_equality&gt Dict
    DictHash dict;
    DictHash::const_local_iterator c_l_itr;

    DictHash::size_type bs = dict.bucket (std::string ("LIVEN"));
    for (c_l_itr = dict.begin(bs); c_l_itr != dict.end(bs); c_l_itr++)
         std::cout

My hash function :

struct my_string_hash_function
{
    std::size_t operator()(const std::string& s) const
    {
        unsigned long hash = 0;
        std::string::const_iterator itr;

        for (itr = s.begin(); itr != s.end(); itr++)
     hash |= 2 << (*itr - int('A'));

      return hash;
    }
};

Comparison function :

struct my_string_equality
{
    bool operator()(const std::string& s1, const std::string& s2) const
    {
        if (s1.length() != s2.length())
     return false;

        unsigned int hash1 = 0, hash2 = 0;
        const char *str1, *str2;
        int i,len;

        len = s1.length();
        str1 = s1.c_str();
        str2 = s2.c_str();

        for (i = 0; i < len; i++)
        {
            hash1 |= 2 << (str1[i] - (int)'A');
            hash2 |= 2 << (str2[i] - (int)'A');
        }

        return hash1 == hash2;
   }
};


问:
"v.context.$implicit.categories[0] is undefined" error in Ionic 3
I am trying to access the category slug for a product in ionic using the WordPress rest API. This seems to work fine on one page as
{{productdetail?.categories[0].slug}}
 however this does not seems to work when i try implementing the same using for loop in angular on another page

```<code><div class="width50" *ngFor="let object of dataList">
    <img src="{{object.images[0].src}}" width="150"  (click)="navigateToPage(object.id)" />
    <h3 class="product-name uppercase" text-nowrap>{{object?.categories[0].slug}}</h3>
</div>
</code>```

it gives an error as v.context.$implicit.categories[0] is undefined however on same page the code for image source seems to work fine.

答:
According to the docs

The Angular safe navigation operator (?.) is a fluent and convenient
  way to guard against null and undefined values in property paths. Here
  it is, protecting against a view render failure if the currentHero is
  null.

This way if write

```<code>obj?.foo
</code>```

angular will transform it to the following expression.

```<code>obj == null ? null : obj.foo
</code>```

so if the obj is empty value then you won't see any of errors.

In your case you can use the expresion

```<code>object?.categories[0]?.slug
</code>```

that will be transformed to

```<code>object == null ? null : object.categories[0] == null ? null : object.categories[0].slug;
</code>```

Safe navigation operator is helpful if you don't know whether your object contains any value or not, or you load data asynchronously and your object is undefined at first time.

Body:
I am trying to access the category slug for a product in ionic using the WordPress rest API. This seems to work fine on one page as
{{productdetail?.categories[0].slug}}
 however this does not seems to work when i try implementing the same using for loop in angular on another page

{{object?.categories[0].slug}}

it gives an error as v.context.$implicit.categories[0] is undefined however on same page the code for image source seems to work fine.

Body:
According to the docs

The Angular safe navigation operator (?.) is a fluent and convenient
  way to guard against null and undefined values in property paths. Here
  it is, protecting against a view render failure if the currentHero is
  null.

This way if write

obj?.foo

angular will transform it to the following expression.

obj == null ? null : obj.foo

so if the obj is empty value then you won't see any of errors.

In your case you can use the expresion

object?.categories[0]?.slug

that will be transformed to

object == null ? null : object.categories[0] == null ? null : object.categories[0].slug;

Safe navigation operator is helpful if you don't know whether your object contains any value or not, or you load data asynchronously and your object is undefined at first time.


问:
Adding a new channel to an image
I am trying to add a 4th "channel" to an image. Specifically, I have a RGB image and would like append that image matrix with an edge detection layer as found by a Canny filter, which I will then use as an input for a neural network.

I have edge detection working, and I can even append the images, but for some reason, the data 'reverts' after looping. The changes that I make in the size of the image do not stick.

Code

I have three sets of 32x32x3 color images: X_train, X_valid, and X_test. For each one, I am normalizing the image and then appending the gradient. Appending appears to take affect while looping, but the changes do not exist after looping.

Code snippet

```<code>import cv2 as cv
example_record = 2

print('X_train is shape {}'.format(X_train.shape))
print('X_valid is shape {}'.format(X_valid.shape))
print('X_test is shape {}'.format(X_test.shape))

# Show before
plt.imshow(X_valid[example_record])
plt.title('Validation Input {} Before Normalization'.format(example_record))

# Normalize
canny_low = 50
canny_high = 100
for dataset in [X_train, X_valid, X_test]:
    for i, img in enumerate(dataset):
        cv.normalize(img, img, 0, 255, cv.NORM_MINMAX)
        edges = cv.Canny(img, canny_low, canny_high)
        edges = np.reshape(edges, (img.shape[0], img.shape[1], 1))
        img = np.concatenate((img, edges),axis=2)
        if i == 0:
            print('img shape after concatenation {}'.format(img.shape))

# Show after
plt.figure()
print('Updated image shape: {}'.format(X_valid[example_record].shape))
plt.imshow(X_valid[example_record])
plt.title('Validation Input {} After Normalization'.format(example_record))
</code>```

Output

```<code>X_train is shape (34799, 32, 32, 3)
X_valid is shape (4410, 32, 32, 3)
X_test is shape (12630, 32, 32, 3)
img shape after concatenation (32, 32, 4)
img shape after concatenation (32, 32, 4)
img shape after concatenation (32, 32, 4)
Updated image shape: (32, 32, 3)
</code>```

Other Attempts

If I replace img = np.concatenate((img, edges),axis=2) with dataset[i] = np.concatenate((img, edges),axis=2), I get the error:

```<code>     21         edges = cv.Canny(img, canny_low, canny_high)
     22         edges = np.reshape(edges, (img.shape[0], img.shape[1], 1))
---> 23         dataset[i] = np.concatenate((img, edges),axis=2)
     24         if i == 0:
     25             print('img shape after concatenation {}'.format(img.shape))

ValueError: could not broadcast input array from shape (32,32,4) into shape (32,32,3)
</code>```

答:
Ok, my previous answer was not detailed enough for someone's taste and it was down-voted. So, let me provide a "ready" solution:

```<code># Normalize
canny_low = 50
canny_high = 100
X = [X_train, X_valid, X_test]
X_new = [np.empty(x.shape[:-1] + (x.shape[-1] + 1,), dtype=x.dtype) for x in X]

for dataset, dsnew in zip(X, X_new):
    for i, img in enumerate(dataset):
        cv.normalize(img, img, 0, 255, cv.NORM_MINMAX)
        edges = np.expand_dims(cv.Canny(img, canny_low, canny_high), axis=2)
        dsnew[i, :, :, :] = np.concatenate((img, edges), axis=2)
</code>```

Alternatively, you could expand X_train, X_valid, and X_test before the loop starts and this may save some memory.

Title: Adding a new channel to an image

Body:
I am trying to add a 4th "channel" to an image. Specifically, I have a RGB image and would like append that image matrix with an edge detection layer as found by a Canny filter, which I will then use as an input for a neural network.

I have edge detection working, and I can even append the images, but for some reason, the data 'reverts' after looping. The changes that I make in the size of the image do not stick.

Code

I have three sets of 32x32x3 color images: X_train, X_valid, and X_test. For each one, I am normalizing the image and then appending the gradient. Appending appears to take affect while looping, but the changes do not exist after looping.

Code snippet

import cv2 as cv
example_record = 2

print('X_train is shape {}'.format(X_train.shape))
print('X_valid is shape {}'.format(X_valid.shape))
print('X_test is shape {}'.format(X_test.shape))

# Show before
plt.imshow(X_valid[example_record])
plt.title('Validation Input {} Before Normalization'.format(example_record))

# Normalize
canny_low = 50
canny_high = 100
for dataset in [X_train, X_valid, X_test]:
    for i, img in enumerate(dataset):
        cv.normalize(img, img, 0, 255, cv.NORM_MINMAX)
        edges = cv.Canny(img, canny_low, canny_high)
        edges = np.reshape(edges, (img.shape[0], img.shape[1], 1))
        img = np.concatenate((img, edges),axis=2)
        if i == 0:
            print('img shape after concatenation {}'.format(img.shape))

# Show after
plt.figure()
print('Updated image shape: {}'.format(X_valid[example_record].shape))
plt.imshow(X_valid[example_record])
plt.title('Validation Input {} After Normalization'.format(example_record))

Output

X_train is shape (34799, 32, 32, 3)
X_valid is shape (4410, 32, 32, 3)
X_test is shape (12630, 32, 32, 3)
img shape after concatenation (32, 32, 4)
img shape after concatenation (32, 32, 4)
img shape after concatenation (32, 32, 4)
Updated image shape: (32, 32, 3)

Other Attempts

If I replace img = np.concatenate((img, edges),axis=2) with dataset[i] = np.concatenate((img, edges),axis=2), I get the error:

     21         edges = cv.Canny(img, canny_low, canny_high)
     22         edges = np.reshape(edges, (img.shape[0], img.shape[1], 1))
---> 23         dataset[i] = np.concatenate((img, edges),axis=2)
     24         if i == 0:
     25             print('img shape after concatenation {}'.format(img.shape))

ValueError: could not broadcast input array from shape (32,32,4) into shape (32,32,3)

Body:
Ok, my previous answer was not detailed enough for someone's taste and it was down-voted. So, let me provide a "ready" solution:

# Normalize
canny_low = 50
canny_high = 100
X = [X_train, X_valid, X_test]
X_new = [np.empty(x.shape[:-1] + (x.shape[-1] + 1,), dtype=x.dtype) for x in X]

for dataset, dsnew in zip(X, X_new):
    for i, img in enumerate(dataset):
        cv.normalize(img, img, 0, 255, cv.NORM_MINMAX)
        edges = np.expand_dims(cv.Canny(img, canny_low, canny_high), axis=2)
        dsnew[i, :, :, :] = np.concatenate((img, edges), axis=2)

Alternatively, you could expand X_train, X_valid, and X_test before the loop starts and this may save some memory.


答:
Change

```<code>public function View()
{
    $sql = "SELECT delivery.delivery_id, service.area, delivery.address, delivery.amount, delivery.date, delivery.payment, delivery.walletnumber, delivery.user_id FROM delivery, service WHERE service.service_id = delivery.place";
    $result = mysqli_query($this->DB(),$sql);
    while($d = mysqli_fetch_row($result))
        {
            $arr[] = $d;
        }
        return $arr; //line 40
}
</code>```

TO

```<code>    public function View()
    {
        $arr = [];
        //Please correct the following SQL statement as per your requirement.
        $sql = "SELECT delivery.delivery_id, service.area, delivery.address, delivery.amount, delivery.date, delivery.payment, delivery.walletnumber, delivery.user_id FROM delivery, service WHERE service.service_id = delivery.place";
        $result = mysqli_query($this->DB(),$sql);
        while($d = mysqli_fetch_row($result))
            {
                $arr[] = $d;
            }
        return $arr; //line 40
    }
</code>```

And the error should go. Since you are directly pushing to $arr in the while loop, PHP is not able to find  $arr in case where your query returns 0 records. Since your query returns 0 records, it doesnt execute the code in while loop and hence PHP is not aware of $arr.

Title: Show Notice: "Undefined variable: arr on line 40" when data table is empty

Body:
Change

public function View()
{
    $sql = "SELECT delivery.delivery_id, service.area, delivery.address, delivery.amount, delivery.date, delivery.payment, delivery.walletnumber, delivery.user_id FROM delivery, service WHERE service.service_id = delivery.place";
    $result = mysqli_query($this->DB(),$sql);
    while($d = mysqli_fetch_row($result))
        {
            $arr[] = $d;
        }
        return $arr; //line 40
}

TO

    public function View()
    {
        $arr = [];
        //Please correct the following SQL statement as per your requirement.
        $sql = "SELECT delivery.delivery_id, service.area, delivery.address, delivery.amount, delivery.date, delivery.payment, delivery.walletnumber, delivery.user_id FROM delivery, service WHERE service.service_id = delivery.place";
        $result = mysqli_query($this->DB(),$sql);
        while($d = mysqli_fetch_row($result))
            {
                $arr[] = $d;
            }
        return $arr; //line 40
    }

And the error should go. Since you are directly pushing to $arr in the while loop, PHP is not able to find  $arr in case where your query returns 0 records. Since your query returns 0 records, it doesnt execute the code in while loop and hence PHP is not aware of $arr.


问:
What is a good method for decrypting a packet being sent from a client over a local network? (Possible wireshark?)
At the moment I am working on a C# project that processes packets being sent from the client using a PacketReader I created. I log the packet and data being sent from the client into a textbox, but how do i really understand what is being sent?

Here is an example of one of the packets:

```<code>Client->Server
06 00 FD FF 3A 1A                                   ....:.
</code>```

What I really don't understand is the data to the right of the hex.

答:
Your problem is probably "decoding", not "decrypting" the data.

The client sends a message to the server. You see it sends 06 00 FD FF 3A 1A.

It could mean anything and nothing.

E.g. the server and client could be programmed to encode "dolphin" as 06 and then 00 FD FF as padding / delimiter and 3A 1A as payload meaning thanks for all the fish.

Try sending various inputs from your client to your server, changing known parts of the message and see how your packets change.

Oh, and: Good luck!

PS: The ....:. is an ASCII representation of your hex values on the left. . usually indicates that there is no printable character for the ASCII character of the respective value.

Body:
At the moment I am working on a C# project that processes packets being sent from the client using a PacketReader I created. I log the packet and data being sent from the client into a textbox, but how do i really understand what is being sent?

Here is an example of one of the packets:

Client->Server
06 00 FD FF 3A 1A                                   ....:.

What I really don't understand is the data to the right of the hex.


问:
Standard_in error in bash script
I have two bash scripts that are almost identical.  One works and one doesn't and I can't figure out what's going on.  Here are the scripts:

This one works fine:

```<code>#!/bin/bash

CURDIR=$HOME/Documents/Development/road/Earthmoving
TOL=0.05

echo -e "\nRunning Unit Tests"
echo -e "------------------\n"

for infile in $CURDIR/utest/*.csv
do
    file=$(basename $infile .csv)
    echo -n " Test $file"
    value=`$CURDIR/Release/earthmove -f $infile`
    res=`cat $CURDIR/utest/$file.res`
    if [ "$(echo "$res+$TOL*$res >= $value && $res-$TOL*$res <= $value" | bc)" -eq 1 ]; then
    echo -e "\t\t PASSED."
    else
    echo -e "\t\t FAILED."
    fi;
done

echo ""
</code>```

But this one gives me all kinds of errors:

```<code>#!/bin/bash

CURDIR=$HOME/Documents/Development/road/Vertical
TOL=0.05

echo -e "\nRunning Unit Tests"
echo -e "------------------\n"

for infile in $CURDIR/utest/*.csv
do
    file=$(basename $infile .csv)
    echo -n " Test $file"
    value=`$CURDIR/Release/vertical -f $infile`
    res=`cat $CURDIR/utest/$file.res`
    if [ "$(echo "$res+$TOL*$res >= $value && $res-$TOL*$res <= $value" | bc)" -eq 1 ]; then
    echo -e "\t\t PASSED."
    else
    echo -e "\t\t FAILED."
    fi;
done

echo ""
</code>```

The two files are IDENTICAL besides the directory (Earthmoving vs Vertical) and the program name (earthmove vs vertical).  I know this because I created the second by copying and pasting the first.  Running the second script results in this:

```<code>Running Unit Tests
------------------

 Test flatroad(standard_in) 1: illegal character: S
(standard_in) 1: syntax error
(standard_in) 1: illegal character: :
(standard_in) 2: illegal character: S
(standard_in) 2: illegal character: :
(standard_in) 2: syntax error
(standard_in) 2: illegal character: N
(standard_in) 2: illegal character: :
(standard_in) 2: illegal character: I
(standard_in) 2: illegal character: :
(standard_in) 2: illegal character: :
(standard_in) 2: illegal character: O
(standard_in) 2: illegal character: :
(standard_in) 3: illegal character: P
(standard_in) 3: illegal character: :
(standard_in) 3: syntax error
(standard_in) 3: illegal character: M
(standard_in) 3: illegal character: :
(standard_in) 3: illegal character: H
(standard_in) 3: illegal character: :
(standard_in) 3: illegal character: :
(standard_in) 4: illegal character: P
(standard_in) 4: illegal character: :
(standard_in) 4: syntax error
(standard_in) 4: illegal character: M
(standard_in) 4: illegal character: :
(standard_in) 4: illegal character: H
(standard_in) 4: illegal character: :
(standard_in) 4: illegal character: :
(standard_in) 5: syntax error
(standard_in) 5: illegal character: :
(standard_in) 6: illegal character: P
(standard_in) 6: illegal character: :
(standard_in) 6: illegal character: M
(standard_in) 6: syntax error
(standard_in) 6: illegal character: :
(standard_in) 7: syntax error
(standard_in) 7: illegal character: :
(standard_in) 8: illegal character: P
(standard_in) 8: illegal character: :
(standard_in) 8: syntax error
(standard_in) 8: illegal character: M
(standard_in) 8: illegal character: :
(standard_in) 15: syntax error
(standard_in) 16: syntax error
(standard_in) 16: illegal character: M
(standard_in) 16: illegal character: I
(standard_in) 16: illegal character: P
(standard_in) 17: syntax error
(standard_in) 18: illegal character: T
(standard_in) 18: illegal character: S
(standard_in) 18: illegal character: T
(standard_in) 18: syntax error
(standard_in) 19: illegal character: T
(standard_in) 19: illegal character: S
(standard_in) 19: illegal character: T
(standard_in) 19: syntax error
(standard_in) 20: illegal character: T
(standard_in) 20: illegal character: S
(standard_in) 20: illegal character: T
(standard_in) 20: syntax error
(standard_in) 21: illegal character: T
.
.
.
(standard_in) 90: illegal character: I
(standard_in) 90: illegal character: O
(standard_in) 90: syntax error
(standard_in) 90: illegal character: P
(standard_in) 90: illegal character: I
(standard_in) 90: illegal character: I
(standard_in) 90: illegal character: T
(standard_in) 91: syntax error
(standard_in) 91: syntax error
(standard_in) 91: syntax error
(standard_in) 91: syntax error
(standard_in) 93: illegal character: S
(standard_in) 93: syntax error
(standard_in) 94: illegal character: O
(standard_in) 94: syntax error
(standard_in) 95: syntax error
(standard_in) 96: illegal character: U
(standard_in) 96: syntax error
(standard_in) 96: illegal character: '
(standard_in) 96: illegal character: O
(standard_in) 96: illegal character: '
                 FAILED.
</code>```

There are plenty more lines where the "..." is, but they're basically just a variation on the same idea.

答:
(standard_in) 1: syntax error

This error will be solved by using perl instead of bc command,

$(perl -e "print $b+$c")

Title: Standard_in error in bash script

Body:
I have two bash scripts that are almost identical.  One works and one doesn't and I can't figure out what's going on.  Here are the scripts:

This one works fine:

#!/bin/bash

CURDIR=$HOME/Documents/Development/road/Earthmoving
TOL=0.05

echo -e "\nRunning Unit Tests"
echo -e "------------------\n"

for infile in $CURDIR/utest/*.csv
do
    file=$(basename $infile .csv)
    echo -n " Test $file"
    value=`$CURDIR/Release/earthmove -f $infile`
    res=`cat $CURDIR/utest/$file.res`
    if [ "$(echo "$res+$TOL*$res >= $value && $res-$TOL*$res <= $value" | bc)" -eq 1 ]; then
    echo -e "\t\t PASSED."
    else
    echo -e "\t\t FAILED."
    fi;
done

echo ""

But this one gives me all kinds of errors:

#!/bin/bash

CURDIR=$HOME/Documents/Development/road/Vertical
TOL=0.05

echo -e "\nRunning Unit Tests"
echo -e "------------------\n"

for infile in $CURDIR/utest/*.csv
do
    file=$(basename $infile .csv)
    echo -n " Test $file"
    value=`$CURDIR/Release/vertical -f $infile`
    res=`cat $CURDIR/utest/$file.res`
    if [ "$(echo "$res+$TOL*$res >= $value && $res-$TOL*$res <= $value" | bc)" -eq 1 ]; then
    echo -e "\t\t PASSED."
    else
    echo -e "\t\t FAILED."
    fi;
done

echo ""

The two files are IDENTICAL besides the directory (Earthmoving vs Vertical) and the program name (earthmove vs vertical).  I know this because I created the second by copying and pasting the first.  Running the second script results in this:

Running Unit Tests
------------------

 Test flatroad(standard_in) 1: illegal character: S
(standard_in) 1: syntax error
(standard_in) 1: illegal character: :
(standard_in) 2: illegal character: S
(standard_in) 2: illegal character: :
(standard_in) 2: syntax error
(standard_in) 2: illegal character: N
(standard_in) 2: illegal character: :
(standard_in) 2: illegal character: I
(standard_in) 2: illegal character: :
(standard_in) 2: illegal character: :
(standard_in) 2: illegal character: O
(standard_in) 2: illegal character: :
(standard_in) 3: illegal character: P
(standard_in) 3: illegal character: :
(standard_in) 3: syntax error
(standard_in) 3: illegal character: M
(standard_in) 3: illegal character: :
(standard_in) 3: illegal character: H
(standard_in) 3: illegal character: :
(standard_in) 3: illegal character: :
(standard_in) 4: illegal character: P
(standard_in) 4: illegal character: :
(standard_in) 4: syntax error
(standard_in) 4: illegal character: M
(standard_in) 4: illegal character: :
(standard_in) 4: illegal character: H
(standard_in) 4: illegal character: :
(standard_in) 4: illegal character: :
(standard_in) 5: syntax error
(standard_in) 5: illegal character: :
(standard_in) 6: illegal character: P
(standard_in) 6: illegal character: :
(standard_in) 6: illegal character: M
(standard_in) 6: syntax error
(standard_in) 6: illegal character: :
(standard_in) 7: syntax error
(standard_in) 7: illegal character: :
(standard_in) 8: illegal character: P
(standard_in) 8: illegal character: :
(standard_in) 8: syntax error
(standard_in) 8: illegal character: M
(standard_in) 8: illegal character: :
(standard_in) 15: syntax error
(standard_in) 16: syntax error
(standard_in) 16: illegal character: M
(standard_in) 16: illegal character: I
(standard_in) 16: illegal character: P
(standard_in) 17: syntax error
(standard_in) 18: illegal character: T
(standard_in) 18: illegal character: S
(standard_in) 18: illegal character: T
(standard_in) 18: syntax error
(standard_in) 19: illegal character: T
(standard_in) 19: illegal character: S
(standard_in) 19: illegal character: T
(standard_in) 19: syntax error
(standard_in) 20: illegal character: T
(standard_in) 20: illegal character: S
(standard_in) 20: illegal character: T
(standard_in) 20: syntax error
(standard_in) 21: illegal character: T
.
.
.
(standard_in) 90: illegal character: I
(standard_in) 90: illegal character: O
(standard_in) 90: syntax error
(standard_in) 90: illegal character: P
(standard_in) 90: illegal character: I
(standard_in) 90: illegal character: I
(standard_in) 90: illegal character: T
(standard_in) 91: syntax error
(standard_in) 91: syntax error
(standard_in) 91: syntax error
(standard_in) 91: syntax error
(standard_in) 93: illegal character: S
(standard_in) 93: syntax error
(standard_in) 94: illegal character: O
(standard_in) 94: syntax error
(standard_in) 95: syntax error
(standard_in) 96: illegal character: U
(standard_in) 96: syntax error
(standard_in) 96: illegal character: '
(standard_in) 96: illegal character: O
(standard_in) 96: illegal character: '
                 FAILED.

There are plenty more lines where the "..." is, but they're basically just a variation on the same idea.


问:
Allow Win32_LogicalDisk for regular users
I am trying to set permissions for regular (non admin) users (group DOMAIN\Domain users) for getting general information about system and disk remotely through WMI.

I set permissions for that in "Computer Management" / "Services and Applications" / "WMI Control". I set "Execution Methods", "Enable Account", "Remote Enable" on REMOTE_COMPUTER_NAME.
Moreover I added "Domain users" group to the local "Distrubuted COM Users".

Then I run PowerShell request on LOCAL_COMPUTER_NAME which returns correct response:

```<code>Get-WMIObject Win32_OperatingSystem -ComputerName REMOTE_COMPUTER_NAME
</code>```

Then I run another PowerShell request which returns error:

```<code>Get-WMIObject Win32_LogicalDisk -ComputerName REMOTE_COMPUTER_NAME

Get-WMIObject : Provider failure
</code>```

This error equal to the code: 0x80041004

But if I run this request from administrator account then run request from a regular user account I get correct response.

I tried to set all checkboxes on root WMI permissions (with inheritance), but it did not help. I understand that I have to set some additional permissions, but which permissions? Google did not help me.

答: You'll not believe but reboot of computer helped!</p>

Body:
I am trying to set permissions for regular (non admin) users (group DOMAIN\Domain users) for getting general information about system and disk remotely through WMI.

I set permissions for that in "Computer Management" / "Services and Applications" / "WMI Control". I set "Execution Methods", "Enable Account", "Remote Enable" on REMOTE_COMPUTER_NAME.
Moreover I added "Domain users" group to the local "Distrubuted COM Users".

Then I run PowerShell request on LOCAL_COMPUTER_NAME which returns correct response:

Get-WMIObject Win32_OperatingSystem -ComputerName REMOTE_COMPUTER_NAME

Then I run another PowerShell request which returns error:

Get-WMIObject Win32_LogicalDisk -ComputerName REMOTE_COMPUTER_NAME

Get-WMIObject : Provider failure

This error equal to the code: 0x80041004

But if I run this request from administrator account then run request from a regular user account I get correct response.

I tried to set all checkboxes on root WMI permissions (with inheritance), but it did not help. I understand that I have to set some additional permissions, but which permissions? Google did not help me.


问:
Find the count of each category in a dataframe for uniques value of third column
I have dataframe df1:

```<code>A|A2|A3
-+--+--
a|ut|x
a|tv|y
a|ut|x
a|pq|y
a|ut|y
b|st|x
b|qp|x
b|nt|y
c|st|x
c|st|x
c|st|y
c|st|z
</code>```

I want to know the frequency of A2 with unique A3 for each A, i.e. I want following output:

```<code>A|A2|freq
-+--+----
a|ut|2
a|tv|1
a|pq|1
b|st|1
b|qp|1
b|nt|1
c|st|3
</code>```

I tried

```<code>count(df1, A, A2, A3)
</code>```

but get the error

Error in count(df1, A, A2, A3)  :  unused argument A3

ContentLicense: CC BY-SA 4.0

Body:
I have dataframe df1:

A|A2|A3
-+--+--
a|ut|x
a|tv|y
a|ut|x
a|pq|y
a|ut|y
b|st|x
b|qp|x
b|nt|y
c|st|x
c|st|x
c|st|y
c|st|z

I want to know the frequency of A2 with unique A3 for each A, i.e. I want following output:

A|A2|freq
-+--+----
a|ut|2
a|tv|1
a|pq|1
b|st|1
b|qp|1
b|nt|1
c|st|3

I tried

count(df1, A, A2, A3)

but get the error

Error in count(df1, A, A2, A3)  :  unused argument A3

Body:
Here is an option with data.table

library(data.table)
setDT(df1)[, .(freq = uniqueN(A3)), .(A, A2)]
#   A A2 freq
#1: a ut    2
#2: a tv    1
#3: a pq    1
#4: b st    1
#5: b qp    1
#6: b nt    1
#7: c st    3

data

df1 <- structure(list(A = c("a", "a", "a", "a", "a", "b", "b", "b",
"c", "c", "c", "c"), A2 = c("ut", "tv", "ut", "pq", "ut", "st",
 "qp", "nt", "st", "st", "st", "st"), A3 = c("x", "y", "x", "y",
"y", "x", "x", "y", "x", "x", "y", "z")), .Names = c("A", "A2",
"A3"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-12L))


答:
Hi you need to create a Middleware

```<code>php artisan make:middleware AnyNameYouWant
</code>```

it will create a nice boilerplate for you.

```<code>public function handle($request, Closure $next)
{
   // Your Logic
}

  return redirect('whereever you want to redirect');
}
</code>```

Then include it in your middleware

```<code>   'web' => [
        \App\Http\Middleware\EncryptCookies::class,

      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \anlutro\LaravelSettings\SaveMiddleware::class,
        \Barryvdh\Cors\HandleCors::class,
        \App\Http\Middleware\YourMiddleware::class
    ],
</code>```

I hope this helps

Title: Session store not set on request in Laravel 5.3

Body:
Hi you need to create a Middleware

php artisan make:middleware AnyNameYouWant

it will create a nice boilerplate for you.

public function handle($request, Closure $next)
{
   // Your Logic
}

  return redirect('whereever you want to redirect');
}

Then include it in your middleware

   'web' => [
        \App\Http\Middleware\EncryptCookies::class,

      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \anlutro\LaravelSettings\SaveMiddleware::class,
        \Barryvdh\Cors\HandleCors::class,
        \App\Http\Middleware\YourMiddleware::class
    ],

I hope this helps


问:
JavaFX clearing all nodes from anchorpane and adding new nodes during runtime
I'm having trouble adding nodes back into an AnchorPane during runtime.

What i'm trying to do is when a user clicks a button, the current nodes are stored in a ObservableList<Node> and then the AnchorPane is cleared. After this I need to add new nodes there. Then when the user is done, they click another button and my saved ObservableList is supposed to be added back to the AnchorPane.

Basically I'm trying to display a customer info form when user clicks on "Customer" button, then display the nodes that were there to start with.

Is there a different way to do this? Without displaying it in another window?
I used .addAll() but that isn't working.

Thanks.

```<code>private ObservableList<Node> middlePaneContent;
@FXML
private AnchorPane middlePane;
@FXML
private void setMiddlePane(){
    middlePaneContent = middlePane.getChildren();
    //middlePane.setVisible(false);
    middlePane.getChildren().clear();
}
@FXML
private void setInspectionToMiddlePane(){
    //middlePane.getChildren().addAll(middlePaneContent);
    middlePane.setVisible(true);
}
</code>```

答:
You're simply storing a reference to middlePane's child list in middlePaneContent. Both point to the same list. Clearing one of them will clear the "other".

Use another List to store the data:

```<code>private List<Node> middlePaneContent = new ArrayList<>();

@FXML
private AnchorPane middlePane;

@FXML
private void setMiddlePane(){
    // copy content to another list
    middlePaneContent.clear();
    middlePaneContent.addAll(middlePane.getChildren());

    //middlePane.setVisible(false);

    // clear child list
    middlePane.getChildren().clear();
}
</code>```

Body:
I'm having trouble adding nodes back into an AnchorPane during runtime.

What i'm trying to do is when a user clicks a button, the current nodes are stored in a ObservableList<Node> and then the AnchorPane is cleared. After this I need to add new nodes there. Then when the user is done, they click another button and my saved ObservableList is supposed to be added back to the AnchorPane.

Basically I'm trying to display a customer info form when user clicks on "Customer" button, then display the nodes that were there to start with.

Is there a different way to do this? Without displaying it in another window?
I used .addAll() but that isn't working.

Thanks.

private ObservableList<Node> middlePaneContent;
@FXML
private AnchorPane middlePane;
@FXML
private void setMiddlePane(){
    middlePaneContent = middlePane.getChildren();
    //middlePane.setVisible(false);
    middlePane.getChildren().clear();
}
@FXML
private void setInspectionToMiddlePane(){
    //middlePane.getChildren().addAll(middlePaneContent);
    middlePane.setVisible(true);
}

Body:
You're simply storing a reference to middlePane's child list in middlePaneContent. Both point to the same list. Clearing one of them will clear the "other".

Use another List to store the data:

private List<Node> middlePaneContent = new ArrayList<>();

@FXML
private AnchorPane middlePane;

@FXML
private void setMiddlePane(){
    // copy content to another list
    middlePaneContent.clear();
    middlePaneContent.addAll(middlePane.getChildren());

    //middlePane.setVisible(false);

    // clear child list
    middlePane.getChildren().clear();
}


问:
add new data to native storage
I am using ionic native storage, and saving few objects in it, I need to add new data to the existing storage

```<code>carCleanForm(form){
        console.log(form.value);
        this.nativeStorage.setItem("carClean", form.value);
    }
</code>```

so here every time when I invoke the form a new set of data will be added on clicking "carclean" button.

Could someone help me to add new data and as well as I need the old data, so on accessing the storage I should have the old object and new object listed

答:
Just store it in two object prevCarClean and carClean

```<code>carCleanForm(form){
  this.nativeStorage.getItem('carClean') .then(
    data => {
      let dataArray = data;
      dataArray.push(form.value);
      this.nativeStorage.setItem("carClean", dataArray);
    },
    error => console.error(error)
  );
}
</code>```

Title: add new data to native storage

Body:
I am using ionic native storage, and saving few objects in it, I need to add new data to the existing storage

carCleanForm(form){
        console.log(form.value);
        this.nativeStorage.setItem("carClean", form.value);
    }

so here every time when I invoke the form a new set of data will be added on clicking "carclean" button.

Could someone help me to add new data and as well as I need the old data, so on accessing the storage I should have the old object and new object listed

Body:
Just store it in two object prevCarClean and carClean

carCleanForm(form){
  this.nativeStorage.getItem('carClean') .then(
    data => {
      let dataArray = data;
      dataArray.push(form.value);
      this.nativeStorage.setItem("carClean", dataArray);
    },
    error => console.error(error)
  );
}


问:
Convert a list of dictionaries with similar/duplicate keys into a single dictionary (values would be list) using reduce method
This question is similar to the post "Python - Convert list of single key dictionaries into a single dictionary", where the assumption is that we guarantee different keys in the list of dictionaries. My question here is, what if we have similar keys and how we can utilize the reduce function.

For example, we have:

lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]

And we want to be:

```<code>dict = {'1': ['A', 'B'], '2': ['C', 'D'], '3': ['E']}
</code>```

In addition, the post How to merge multiple dicts with same key? is similar, except that here we would like to utilize the reduce method.

答:
You can use the setdefault() attribute of dictionary objects:

```<code>>>> def combine(dictionaries):
    combined_dict = {}
    for dictionary in dictionaries:
        for key, value in dictionary.items():
            combined_dict.setdefault(key, []).append(value)
    return combined_dict

>>>
>>> lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]
>>> combine(lst)
{'1': ['A', 'B'], '2': ['C', 'D'], '3': ['E']}
>>>
</code>```

This basically works by first checking if the key already exists in the new dictionary. If it does, we just append the current value to the same key. If not, we create a new key and append that current value to that.

Body:
This question is similar to the post "Python - Convert list of single key dictionaries into a single dictionary", where the assumption is that we guarantee different keys in the list of dictionaries. My question here is, what if we have similar keys and how we can utilize the reduce function.

For example, we have:

lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]

And we want to be:

dict = {'1': ['A', 'B'], '2': ['C', 'D'], '3': ['E']}

In addition, the post How to merge multiple dicts with same key? is similar, except that here we would like to utilize the reduce method.

Body:
You can use the setdefault() attribute of dictionary objects:

>>> def combine(dictionaries):
    combined_dict = {}
    for dictionary in dictionaries:
        for key, value in dictionary.items():
            combined_dict.setdefault(key, []).append(value)
    return combined_dict

>>>
>>> lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]
>>> combine(lst)
{'1': ['A', 'B'], '2': ['C', 'D'], '3': ['E']}
>>>

This basically works by first checking if the key already exists in the new dictionary. If it does, we just append the current value to the same key. If not, we create a new key and append that current value to that.


问:
The Download file for IOS debug build from codenameone is zip not IPA
I am successfully using codenameone netbeans.
 After successfully compiling my app for send iOS debug build to codenameone and successfully completed, the downloaded file for MyApplication.IPA is zip not IPA.
So please help for this, for how to download the file as IPA not a zip file?
Any suggestion?

Thanks a lot.

答:
We don't build zips in iOS targets. IPA files are technically zips in much the same way as JAR files are zips. But you shouldn't extract them or anything like that.

I'm guessing your browser detects the file format is a zip and is being stupid about it. I suggest trying a different browser.


问:
PHP sessions that have already been started
In my PHP code, if a session has already started, and I try to start a new one, I get the following Notice:

Notice: A session had already been started - ignoring session_start()

How can I avoid this?

答:
I encountered this issue while trying to fix $_SESSION's blocking behavior.

http://konrness.com/php5/how-to-prevent-blocking-php-requests/

The session file remains locked until the script completes or the
  session is manually closed.

So, by default, a page should open a session in read-only mode. But once it's open in read-only, it has to be closed-and-reopened in to get it into write mode.

```<code>const SESSION_DEFAULT_COOKIE_LIFETIME = 86400;

/**
 * Open _SESSION read-only
 */
function OpenSessionReadOnly() {
    session_start([
                      'cookie_lifetime' => SESSION_DEFAULT_COOKIE_LIFETIME,
                      'read_and_close'  => true,    // READ ACCESS FAST
                  ]);
    // $_SESSION is now defined. Call WriteSessionValues() to write out values
}

/**
 * _SESSION is read-only by default. Call this function to save a new value
 * call this function like `WriteSessionValues(["username"=>$login_user]);`
 * to set $_SESSION["username"]
 *
 * @param array $values_assoc_array
 */
function WriteSessionValues($values_assoc_array) {
    // this is required to close the read-only session and
    // not get a warning on the next line.
    session_abort();

    // now open the session with write access
    session_start([ 'cookie_lifetime' => SESSION_DEFAULT_COOKIE_LIFETIME ]);

    foreach ($values_assoc_array as $key => $value) {
        $_SESSION[ $key ] = $value;
    }
    session_write_close();  // Write session data and end session

    OpenSessionReadOnly(); // now reopen the session in read-only mode.
}

OpenSessionReadOnly();  // start the session for this page
</code>```

Then when you go to write some value:

```<code>WriteSessionValues(["username"=>$login_user]);
</code>```

The function takes an array of key=>value pairs to make it even more efficient.

Body:
I encountered this issue while trying to fix $_SESSION's blocking behavior.

http://konrness.com/php5/how-to-prevent-blocking-php-requests/

The session file remains locked until the script completes or the
  session is manually closed.

So, by default, a page should open a session in read-only mode. But once it's open in read-only, it has to be closed-and-reopened in to get it into write mode.

const SESSION_DEFAULT_COOKIE_LIFETIME = 86400;

/**
 * Open _SESSION read-only
 */
function OpenSessionReadOnly() {
    session_start([
                      'cookie_lifetime' => SESSION_DEFAULT_COOKIE_LIFETIME,
                      'read_and_close'  => true,    // READ ACCESS FAST
                  ]);
    // $_SESSION is now defined. Call WriteSessionValues() to write out values
}

/**
 * _SESSION is read-only by default. Call this function to save a new value
 * call this function like `WriteSessionValues(["username"=>$login_user]);`
 * to set $_SESSION["username"]
 *
 * @param array $values_assoc_array
 */
function WriteSessionValues($values_assoc_array) {
    // this is required to close the read-only session and
    // not get a warning on the next line.
    session_abort();

    // now open the session with write access
    session_start([ 'cookie_lifetime' => SESSION_DEFAULT_COOKIE_LIFETIME ]);

    foreach ($values_assoc_array as $key => $value) {
        $_SESSION[ $key ] = $value;
    }
    session_write_close();  // Write session data and end session

    OpenSessionReadOnly(); // now reopen the session in read-only mode.
}

OpenSessionReadOnly();  // start the session for this page

Then when you go to write some value:

WriteSessionValues(["username"=>$login_user]);

The function takes an array of key=>value pairs to make it even more efficient.


问:
Type Hints Convention for Instance Variables Python
I'm unsure of the Python convention for type hinting instance variables - I've been doing them within the __init__ constructor arguments like seen here:

```<code>class LoggedVar(Generic[T]):
    def __init__(self, value: T, name: str, logger: Logger) -> None:
        self.name = name
        self.logger = logger
        self.value = value`
</code>```

But I also see the PEP conventions of annotating instance variables as such (snippet below) and then also doing type hinting within the __init__ arguments:

```<code>class BasicStarship:
    captain: str = 'Picard'               # instance variable with default
    damage: int                           # instance variable without default
    stats: ClassVar[Dict[str, int]] = {}  # class variable`

    def __init__(self, damage: int, captain: str = None):
        self.damage = damage
        if captain:
            self.captain = captain  # Else keep the default
</code>```

Lastly, later on in the PEP 526 article they say one can do the following for convenience and convention:

```<code>class Box(Generic[T]):
    def __init__(self, content):
        self.content: T = content
</code>```

(Both of the above code snippets are from here.)

So — is one of these conventions better/more widely accepted than the others that I should try to stick to (better readability etc..)?

答:
I would recommend using the first version, where you assign types to your __init__ method's parameters, for most circumstances.

That particular method has the least amount of redundancy while still allowing type checkers to verify that you're calling that __init__ method correctly elsewhere in your code.

I would recommend using either the second or third version, where you explicitly annotate your fields (inside or outside __init__) when your __init__ method has grown complex enough to the point where one or more of the following apply:

It's no longer so straightforward what exactly your fields are to begin with

There's no longer a one-to-one mapping between your parameters and your fields

You have complex initialization logic that obscures how your fields are being assigned.

However, it was unclear to me whether the second or third version was preferred -- I personally prefer the third version because it's more conceptually cleaner and doesn't seem to mix the notion of instance vs class attributes, but I can't deny the second version looks cleaner.

I asked about it on the 'typing' gitter channel, and got the following response from Guido (who, on the off-chance you didn't know, made Python and is currently working on mypy and typing related stuff):

There seem to be strong opinions either way. I do indeed prefer putting attribute annotations in the class body rather than sprinkling them throughout __init__ and other methods. I also think that with PEP 526 this will be the future (also with things like class-based NamedTuple declarations and possibly https://github.com/ericvsmith/dataclasses).

(link to quote)

So, it seems like the second version is recommended over the third, and that defining classes in that manner will become more deeply integrated into the Python language itself at some point in the future!

Edit: PEP 557, data classes was recently accepted and appears to be on-track (?) to be included with Python 3.7.

Body:
I'm unsure of the Python convention for type hinting instance variables - I've been doing them within the __init__ constructor arguments like seen here:

class LoggedVar(Generic[T]):
    def __init__(self, value: T, name: str, logger: Logger) -> None:
        self.name = name
        self.logger = logger
        self.value = value`

But I also see the PEP conventions of annotating instance variables as such (snippet below) and then also doing type hinting within the __init__ arguments:

class BasicStarship:
    captain: str = 'Picard'               # instance variable with default
    damage: int                           # instance variable without default
    stats: ClassVar[Dict[str, int]] = {}  # class variable`

    def __init__(self, damage: int, captain: str = None):
        self.damage = damage
        if captain:
            self.captain = captain  # Else keep the default

Lastly, later on in the PEP 526 article they say one can do the following for convenience and convention:

class Box(Generic[T]):
    def __init__(self, content):
        self.content: T = content

(Both of the above code snippets are from here.)

So — is one of these conventions better/more widely accepted than the others that I should try to stick to (better readability etc..)?


问:
SELECT PHP and MySQL not working
I have this code for the select and printing values.
mysql_numn_rows returns null :/</p>

```<code><?php
mysql_connect('localhost','root','');
mysql_select_db("db2517");

$username = "Cristoforo";
$query = mysql_query("SELECT * users WHERE username='$username' ");

$numberOfRows = mysql_num_rows($query);
echo "num: $numberOfRows";

?>
</code>```

答:
Better use mysqli or pdo instead of mysql.here you missed from in your query so your Query should be

```<code>$query = mysql_query("SELECT * from users WHERE username='$username' ");
</code>```

Title: SELECT PHP and MySQL not working

Body:
I have this code for the select and printing values.
mysql_numn_rows returns null :/

<?php
mysql_connect('localhost','root','');
mysql_select_db("db2517");

$username = "Cristoforo";
$query = mysql_query("SELECT * users WHERE username='$username' ");

$numberOfRows = mysql_num_rows($query);
echo "num: $numberOfRows";

?>

Body:
Better use mysqli or pdo instead of mysql.here you missed from in your query so your Query should be

$query = mysql_query("SELECT * from users WHERE username='$username' ");


问:
How to replace values in specific lines and on determined conditions
I'm in trouble: I have a dataset with 128597 lines and 10 columns.
I need to change the values from column 10 between line 10276 until 128597.

And this change have to respect some conditions, like:
If the value is between 11 and 33, the value will become 1
If the value is between 34 and 56, the value will become 5
And go on...

I tried the code below, but didn't work:

m(10276:128597,10) > 11 & m(10276:128597,10)< 33=1;

Can anyone help me please!!! :)

答:
If your bins are consecutive, i.e. there are no gaps between the categories, you can use discretize. Like this you can change all values at once and don't have to use an insane number of logical operators if you have a lot if bins.

```<code>% edges of the bins. As an example there are currently 3 bins ranging from
% 11 to 34, 34 to 57, 57 to 77. The upper values are included in the next bin, i.e. bin 2 goes from 34.0 to 56.999999
edges = [11 34 57 77];
% Example values you want to give to the bins. Length has to be one shorter than edges
replacementvalues = [1 5 9];

% subset of the data you want to change
subset = m(10276:128597,:);
% bin the subset into categories
binnumber = discretize(subset,edges);
% replace the values in subset that are inside those bins
subset(~isnan(binnumber)) = replacementvalues(binnumber(~isnan(binnumber)));
% replace the values in the original matrix with the updated subset
m(10276:128597,:) = subset;
</code>```

If there are gaps between the bins, the code can be expanded by making a second set of "do not change" bins.

Body:
If your bins are consecutive, i.e. there are no gaps between the categories, you can use discretize. Like this you can change all values at once and don't have to use an insane number of logical operators if you have a lot if bins.

% edges of the bins. As an example there are currently 3 bins ranging from
% 11 to 34, 34 to 57, 57 to 77. The upper values are included in the next bin, i.e. bin 2 goes from 34.0 to 56.999999
edges = [11 34 57 77];
% Example values you want to give to the bins. Length has to be one shorter than edges
replacementvalues = [1 5 9];

% subset of the data you want to change
subset = m(10276:128597,:);
% bin the subset into categories
binnumber = discretize(subset,edges);
% replace the values in subset that are inside those bins
subset(~isnan(binnumber)) = replacementvalues(binnumber(~isnan(binnumber)));
% replace the values in the original matrix with the updated subset
m(10276:128597,:) = subset;

If there are gaps between the bins, the code can be expanded by making a second set of "do not change" bins.


问:
SpanMultiTermQueryWrapper in Lucene.NET?
Does anyone know if the SpanMultiTermQueryWrapper class is available in the Lucene.NET port? I can't find it anywhere, and it sure would be handy. I'm still using version 2.9...maybe it's available in a later version? Thanks!</p>

答:
SpanMultiTermQueryWrapper is available on Lucene.Net 4.8.0-beta00004.

If you need support in earlier versions of Lucene.Net, you can probably just grab the source code from the above link and any dependencies and drop them into a library for your applications.


问:
How to read memory values using VBScript?
I want to use VBScript to read values directly out of memory of another running application.

I can't seem to find information on using ReadProcessMemory() in VBScript.

I intend to use this in Quick Test Pro to do screen scraping of an application that needs testing.
This application does not use any standard controls and using QTP's OCR abilities does not provide us with reliable results.

We currently have code written in AutoIT that reads values of this application directly from memory and converts it to ASCII.  But we want to remove the reliance on that and using VBScript from within QTP would be ideal.

So can anyone tell me how I can read values from an executable in memory using VBScript?

答:
You can't do this in VBScript directly. As Josh Einstein's comment above mentions, it's impossible to call native Windows API functions directly from VBScript. There are two major reasons why this is the case. First, it would pose obvious security risks for code written in such a scripting language to be able to call native code directly. And second, VBScript only has one data type (Variant), which is not going to work properly with the return values of most of the Windows API functions.

Instead, you'll have to wrap the native API functions that you need in an ActiveX DLL (COM automation object), and then call functions from that library from your VBScript. The wrapper DLL would be designed specifically for VBScript-interoperability and would take care of any necessary data-type conversions, exposing only Variant types and containing all of the necessary (or potentially necessary!) error handling routines. Using VB 6 is the quickest and easiest way to do this and doesn't even require you to learn a new language, but you can also do this from C++, if you're comfortable there.


问:
Wordpress menu deletes when trying to add a hook
I'm trying to customize the default Wordpress menus. Added this to my functions.php file and it makes my menus disappear. What is wrong?

```<code>function custom_novice_menu($args) {
    $defaults = array(
        'container' => 'div'
    );
}

add_action('wp_nav_menu', 'custom_novice_menu');
</code>```

Here is some documentation on wp_nav_menu()

答: wp_nav_menu is not an action, It is a filter, So you will need to write apply_filters for it and return $nav_menu from the callback function.</p>

Body:
I'm trying to customize the default Wordpress menus. Added this to my functions.php file and it makes my menus disappear. What is wrong?

function custom_novice_menu($args) {
    $defaults = array(
        'container' => 'div'
    );
}

add_action('wp_nav_menu', 'custom_novice_menu');

Here is some documentation on wp_nav_menu()


问:
HTML2pdf Css not supporting
I have used a html2pdf file for generating pdf.But it does not support css at all. Please let me know what is the issue.

1) Downloaded file from
https://sourceforge.net/projects/html2fpdf/?source=typ_redirect

2) placed in a folder and used below code to generate pdf (working fine)

```<code>require("html2fpdf.php");
$buffer = "<div>
<h1>Hello Friends</h1><br>
<p>This is a sample code</p>
</div>";
$pdf = new HTML2FPDF('P', 'mm', 'Legal');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('my.pdf', 'D');
</code>```

but when i used css in this then generated pdf is not opened

```<code>require("html2fpdf.php");
$buffer = "<div style='width:950px;'>
<h1>Hello Friends</h1><br>
<p style='font-size:10'>This is a sample code</p>
</div>";
$pdf = new HTML2FPDF('P', 'mm', 'Legal');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('my.pdf', 'D');
</code>```

My php version is PHP Version 5.3.8.

I am bowed  to use HTML2PDF. So please answer if you know(I have used same with TCPDF and thats working fine but i need to implement same in HTML2PDF)

答:
I did two tests and CSS is working well except for the size of the div.

PHP Version : 5.6.30

Test 1

```<code><?php
require("html2fpdf.php");
$buffer = "
<h1>Hello Friends</h1><br>
<span style='font-weight: bold; font-size: 18pt; color: #FF0000; font-family: Times'>Hello there! I am red!<br></span>
<br>
<p style='font-size:10'>This is a sample code</p>
<p style='font-size:10px; color:blue;'>This is a sample code</p>
<span style='font-size:10px; color:blue;'>This is a sample code</p>
<span style='font-weight: italic; font-size: 10pt; color: #00FF00;'>I am a pdf ! Please accept my answer!</span>
";
$pdf = new HTML2FPDF('P', 'mm', 'Legal');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('my.pdf', 'D');

 ?>
</code>```

Result

Test 2

```<code><?php
require("html2fpdf.php");
$buffer = "<div style='width:950px;'>
<h1>Hello Friends</h1><br>
<span style='font-weight: bold; font-size: 18pt; color: #FF0000; font-family: Times'>Hello there! I am red!<br></span>
<br>
<p style='font-size:10'>This is a sample code</p>
<p style='font-size:10px; color:blue;'>This is a sample code</p>
<span style='font-size:10px; color:blue;'>This is a sample code</p>
<span style='font-weight: italic; font-size: 10pt; color: #00FF00;'>I am a pdf ! Please accept my answer!</span></div>
";
$pdf = new HTML2FPDF('P', 'mm', 'Legal');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('my.pdf', 'D');

 ?>
</code>```

Result

Title: HTML2pdf Css not supporting

Body:
I have used a html2pdf file for generating pdf.But it does not support css at all. Please let me know what is the issue.

1) Downloaded file from
https://sourceforge.net/projects/html2fpdf/?source=typ_redirect

2) placed in a folder and used below code to generate pdf (working fine)

require("html2fpdf.php");
$buffer = "

Hello Friends

This is a sample code

";
$pdf = new HTML2FPDF('P', 'mm', 'Legal');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('my.pdf', 'D');

but when i used css in this then generated pdf is not opened

require("html2fpdf.php");
$buffer = "

Hello Friends

This is a sample code

";
$pdf = new HTML2FPDF('P', 'mm', 'Legal');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('my.pdf', 'D');

My php version is PHP Version 5.3.8.

I am bowed  to use HTML2PDF. So please answer if you know(I have used same with TCPDF and thats working fine but i need to implement same in HTML2PDF)

Body:
I did two tests and CSS is working well except for the size of the div.

PHP Version : 5.6.30

Test 1

<?php
require("html2fpdf.php");
$buffer = "
<h1>Hello Friends</h1><br>
<span style='font-weight: bold; font-size: 18pt; color: #FF0000; font-family: Times'>Hello there! I am red!<br></span>
<br>
<p style='font-size:10'>This is a sample code</p>
<p style='font-size:10px; color:blue;'>This is a sample code</p>
<span style='font-size:10px; color:blue;'>This is a sample code</p>
<span style='font-weight: italic; font-size: 10pt; color: #00FF00;'>I am a pdf ! Please accept my answer!</span>
";
$pdf = new HTML2FPDF('P', 'mm', 'Legal');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('my.pdf', 'D');

 ?>

Result

Test 2

<?php
require("html2fpdf.php");
$buffer = "<div style='width:950px;'>
<h1>Hello Friends</h1><br>
<span style='font-weight: bold; font-size: 18pt; color: #FF0000; font-family: Times'>Hello there! I am red!<br></span>
<br>
<p style='font-size:10'>This is a sample code</p>
<p style='font-size:10px; color:blue;'>This is a sample code</p>
<span style='font-size:10px; color:blue;'>This is a sample code</p>
<span style='font-weight: italic; font-size: 10pt; color: #00FF00;'>I am a pdf ! Please accept my answer!</span></div>
";
$pdf = new HTML2FPDF('P', 'mm', 'Legal');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('my.pdf', 'D');

 ?>

Result


问:
Angular 1.5 filter with ng-repeat not working by track by id
so I tried so many different ways to get this done. Followed so many StackOverflow and could not get this to work. All I am trying to do is to filter some list items based on the value of a boolean property. Below is the picture of my object data. The closest example I am following is this question Filtering an Angular 1.2 ng-repeat with "track by" by a boolean property. Still not working. does it have anything to do with an object literal and this type of filtering with property only works with array? I am new to javascript so not sure. Also using angular material, virtual repeat container and other material based things are not affecting the result, I can display the whole data, just the filtered by this specific property not working

      loadAssets = () => {

        var self = this;
        self.infiniteAssets = {
            numLoaded_: 0,
            toLoad_: 0,
            items: [],
            pageNum:1,
            virtualIndex:0,

            getItemAtIndex: function (index) {
                this.virtualIndex=index;

                if (index > this.numLoaded_) {
                    this.fetchMoreItems_(index);
                    return null;
                }
                return this.items[index];
            },

            // Required.
            getLength: function () {
                if (this.virtualIndex > this.numLoaded_) {
                    return this.numLoaded_ ;
                }else{
                    return this.numLoaded_ + 5 ;
                }
            },

            fetchMoreItems_ : function (index) {
                if (this.toLoad_ < index) {
                    self.loading = true;
                    this.toLoad_ += 20;
                    self.siAsset.getAssets(this.pageNum++,20)
                        .then(angular.bind(this, function (assets) {
                            //this.objLength = assets.length;
                            if(! assets.statusCode){
                                this.items = this.items.concat(assets);
                                this.toLoad_ = this.items.length;
                                this.numLoaded_ = this.toLoad_;
                            }
                            self.loading = false;
                        }))
                }
            }
        };
        console.log('++++++++++',self.infiniteAssets)```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <md-virtual-repeat-container id="vertical-container" ng-show="$ctrl.infiniteAssets.getLength() > 0 && $ctrl.switch">

          <md-list>
            <md-list-item  class="list-page" md-on-demand md-virtual-repeat="asset in $ctrl.infiniteAssets | filter: {disabled: true } track by asset.id" ng-click="$ctrl.loadDetail(asset)">
              <span class="search-status" style="border-left-color:{{asset.statusColor}};"></span>
              <p >{{asset.name}} </p>
              <label hide-xs ng-if="asset.disabled" class="ng-animate-disabled">
                <md-chips >
                  <md-chip >{{'LABELS.DISABLED' | translate}}</md-chip>
                </md-chips>
              </label>
              <label ><i>{{asset.status || 'UNKNOWN'}}</i></label>
                 <md-button  aria-label="Delete Asset" class="md-icon-button md-warn" layout-padding ng-click="$ctrl.deleteAsset(asset)">
                       <md-icon md-svg-icon="delete" class="modelTrashIcon"></md-icon>
                  </md-button>
              <md-divider></md-divider>
            </md-list-item>
          </md-list>
        </md-virtual-repeat-container></code>```

答:
Are you certain md-virtual-repeat works with filters? AngularJS Materials virtual repeat is a custom implementation of ng-repeat, so you can't expect it to work exactly as the original. Here's from the documentation.

Virtual repeat is a limited substitute for ng-repeat that renders only
  enough DOM nodes to fill the container and recycling them as the user
  scrolls.

Arrays, but not objects are supported for iteration. Track by, as
  alias, and (key, value) syntax are not supported.

I would move the filtering inside your controller instead and just make sure the filter is reapplied whenever the collection changes.

Body:
so I tried so many different ways to get this done. Followed so many StackOverflow and could not get this to work. All I am trying to do is to filter some list items based on the value of a boolean property. Below is the picture of my object data. The closest example I am following is this question Filtering an Angular 1.2 ng-repeat with "track by" by a boolean property. Still not working. does it have anything to do with an object literal and this type of filtering with property only works with array? I am new to javascript so not sure. Also using angular material, virtual repeat container and other material based things are not affecting the result, I can display the whole data, just the filtered by this specific property not working

      loadAssets = () => {

        var self = this;
        self.infiniteAssets = {
            numLoaded_: 0,
            toLoad_: 0,
            items: [],
            pageNum:1,
            virtualIndex:0,

            getItemAtIndex: function (index) {
                this.virtualIndex=index;

                if (index > this.numLoaded_) {
                    this.fetchMoreItems_(index);
                    return null;
                }
                return this.items[index];
            },

            // Required.
            getLength: function () {
                if (this.virtualIndex > this.numLoaded_) {
                    return this.numLoaded_ ;
                }else{
                    return this.numLoaded_ + 5 ;
                }
            },

            fetchMoreItems_ : function (index) {
                if (this.toLoad_ < index) {
                    self.loading = true;
                    this.toLoad_ += 20;
                    self.siAsset.getAssets(this.pageNum++,20)
                        .then(angular.bind(this, function (assets) {
                            //this.objLength = assets.length;
                            if(! assets.statusCode){
                                this.items = this.items.concat(assets);
                                this.toLoad_ = this.items.length;
                                this.numLoaded_ = this.toLoad_;
                            }
                            self.loading = false;
                        }))
                }
            }
        };
        console.log('++++++++++',self.infiniteAssets)

    <md-virtual-repeat-container id="vertical-container" ng-show="$ctrl.infiniteAssets.getLength() > 0 && $ctrl.switch">

          <md-list>
            <md-list-item  class="list-page" md-on-demand md-virtual-repeat="asset in $ctrl.infiniteAssets | filter: {disabled: true } track by asset.id" ng-click="$ctrl.loadDetail(asset)">

{{asset.name}}

                <md-chips >
                  <md-chip >{{'LABELS.DISABLED' | translate}}</md-chip>
                </md-chips>

              {{asset.status || 'UNKNOWN'}}
                 <md-button  aria-label="Delete Asset" class="md-icon-button md-warn" layout-padding ng-click="$ctrl.deleteAsset(asset)">
                       <md-icon md-svg-icon="delete" class="modelTrashIcon"></md-icon>
                  </md-button>
              <md-divider></md-divider>
            </md-list-item>
          </md-list>
        </md-virtual-repeat-container>


问:
How reconnect clients sockets to my server if my server restarts
I'm trying to make a client-server connection using sockets.

It basically works pretty well; only one problem is when I close and re-open my server on server computer the clients won't reconnect

This is my client code :

```<code>Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Public Class Form1
        Public Delegate Sub MessageReceivedEventHandler(ByVal sender As Object, ByVal e As MessageReceivedEventArgs)
        Public Delegate Sub ClientConnectedEventHandler(ByVal sender As Object, ByVal e As ClientConnectedEventArgs)
        Public Event MessageReceived As MessageReceivedEventHandler
        Public Event ClientConnected As ClientConnectedEventHandler
        Public Buffer As Byte()
        Public Shared Client As TcpClient
        Dim Port As Integer = 5050
    Dim host As String = "computer name"
    Dim KEY As String = "mykey"

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim T As New Thread(AddressOf run)
        T.Start()
    End Sub

    Private Sub run()
        ' Connect to the server'
        Client = New TcpClient(host, Port)
        Dim T As New Thread(AddressOf Receiver, 10)
        T.Start()
    End Sub

    Public Shared Function StringToByte(ByVal STR As String) As Byte()
        Return System.Text.Encoding.Default.GetBytes(STR)
    End Function
    Public Shared Function ByteToString(ByVal BYS As Byte()) As String
        Return System.Text.Encoding.Default.GetString(BYS)
    End Function
    Public Sub Data(ByVal Sender As Object, ByVal Data As MessageReceivedEventArgs) Handles Me.MessageReceived
        Dim info As Byte() = Data.Message
        Dim Client As Socket = Data.clientSocket
        Dim ID As String = Data.Sender
        Dim Arr As String() = Split(System.Text.Encoding.Default.GetString(info), "mykey")
        Try
            Select Case Arr(0)

                Case "MSG"
                MsgBox(Arr(1))
                           End Select
        Catch ex As Exception
            MsgBox("Error Detected in Data Client :" & ex.Message)
        End Try
    End Sub

    Sub Receiver()
        Dim M As New MemoryStream
        Try
                If Client.Available > 0 Then
                    ReDim Buffer(Client.Available - 1)
                    Client.Client.Receive(Buffer, 0, Buffer.Length, SocketFlags.None)
                    M.Write(Buffer, 0, Buffer.Length)
                    If System.Text.Encoding.Default.GetString(M.ToArray).Contains("EOF") Then
                        Dim Data As Byte() = (M.ToArray).Remove(ConfigTcp.ENDOFPACKET)
                        Dim Msg As New MessageReceivedEventArgs
                        Msg.Message = Data
                        Msg.clientSocket = Client.Client
                        Msg.Sender = Client.Client.Handle.ToString()
                        RaiseEvent MessageReceived(Me, Msg)
                        M.Dispose()
                        M = New MemoryStream
                    End If
                End If
                Thread.Sleep(1)
        Catch ex As Exception
            MsgBox("Error Detected :" & ex.Message)
        End Try
    End Sub
    Public Shared Sub Send(ByVal sock As Socket, ByVal s As String)
            Send(sock, System.Text.Encoding.UTF8.GetBytes(s))
        End Sub
        Private Shared Sub Send(ByVal sock As Socket, ByVal b As Byte())
            Try
                Dim Memory As MemoryStream = New MemoryStream
                Dim CB As Byte() = b
                Memory.Write(CB, 0, CB.Length)
                Memory.Write(ConfigTcp.ENDOFPACKET, 0, ConfigTcp.ENDOFPACKET.Length)
                sock.Send(Memory.ToArray, 0, Memory.Length, SocketFlags.None)
                Memory.Dispose()
            Catch x As Exception
            End Try
        End Sub
    End Class
    Public Class MessageReceivedEventArgs
        Inherits EventArgs
        Public Sender As String
        Public clientSocket As Socket
        Public Message As Byte()
    End Class
    Public Class ClientConnectedEventArgs
        Inherits EventArgs
        Public clientID As String
        Public clientSocket As Socket
    End Class
</code>```

答:
Your client needs to handle disconnects and reconnect if needed.

To accomplish this, you can catch a SocketException and see why the socket was closed.

Depending on the exception you can run a method to have your client reconnect.

```<code>Public Sub DoReconnect()
    Dim SecondsToWait as Integer=1
    Do
        Try
            Client = New TcpClient(host, Port)
            Exit Do
        Catch SockEx as SocketException
            'TODO: decide whether to attempt reconnection or exit
        Catch Ex as Exception
            'TODO: Most likely should terminate the program here
            Console.WriteLine(Ex.ToString())
            Exit Do
        End Try
        System.Threading.Thread.Sleep(SecondsToWait*1000)
        SecondsToWait <<=1 ' Exponential Back Off Time
    Loop
End Sub
</code>```

Body:
I'm trying to make a client-server connection using sockets.

It basically works pretty well; only one problem is when I close and re-open my server on server computer the clients won't reconnect

This is my client code :

Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Public Class Form1
        Public Delegate Sub MessageReceivedEventHandler(ByVal sender As Object, ByVal e As MessageReceivedEventArgs)
        Public Delegate Sub ClientConnectedEventHandler(ByVal sender As Object, ByVal e As ClientConnectedEventArgs)
        Public Event MessageReceived As MessageReceivedEventHandler
        Public Event ClientConnected As ClientConnectedEventHandler
        Public Buffer As Byte()
        Public Shared Client As TcpClient
        Dim Port As Integer = 5050
    Dim host As String = "computer name"
    Dim KEY As String = "mykey"

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim T As New Thread(AddressOf run)
        T.Start()
    End Sub

    Private Sub run()
        ' Connect to the server'
        Client = New TcpClient(host, Port)
        Dim T As New Thread(AddressOf Receiver, 10)
        T.Start()
    End Sub

    Public Shared Function StringToByte(ByVal STR As String) As Byte()
        Return System.Text.Encoding.Default.GetBytes(STR)
    End Function
    Public Shared Function ByteToString(ByVal BYS As Byte()) As String
        Return System.Text.Encoding.Default.GetString(BYS)
    End Function
    Public Sub Data(ByVal Sender As Object, ByVal Data As MessageReceivedEventArgs) Handles Me.MessageReceived
        Dim info As Byte() = Data.Message
        Dim Client As Socket = Data.clientSocket
        Dim ID As String = Data.Sender
        Dim Arr As String() = Split(System.Text.Encoding.Default.GetString(info), "mykey")
        Try
            Select Case Arr(0)

                Case "MSG"
                MsgBox(Arr(1))
                           End Select
        Catch ex As Exception
            MsgBox("Error Detected in Data Client :" & ex.Message)
        End Try
    End Sub

    Sub Receiver()
        Dim M As New MemoryStream
        Try
                If Client.Available > 0 Then
                    ReDim Buffer(Client.Available - 1)
                    Client.Client.Receive(Buffer, 0, Buffer.Length, SocketFlags.None)
                    M.Write(Buffer, 0, Buffer.Length)
                    If System.Text.Encoding.Default.GetString(M.ToArray).Contains("EOF") Then
                        Dim Data As Byte() = (M.ToArray).Remove(ConfigTcp.ENDOFPACKET)
                        Dim Msg As New MessageReceivedEventArgs
                        Msg.Message = Data
                        Msg.clientSocket = Client.Client
                        Msg.Sender = Client.Client.Handle.ToString()
                        RaiseEvent MessageReceived(Me, Msg)
                        M.Dispose()
                        M = New MemoryStream
                    End If
                End If
                Thread.Sleep(1)
        Catch ex As Exception
            MsgBox("Error Detected :" & ex.Message)
        End Try
    End Sub
    Public Shared Sub Send(ByVal sock As Socket, ByVal s As String)
            Send(sock, System.Text.Encoding.UTF8.GetBytes(s))
        End Sub
        Private Shared Sub Send(ByVal sock As Socket, ByVal b As Byte())
            Try
                Dim Memory As MemoryStream = New MemoryStream
                Dim CB As Byte() = b
                Memory.Write(CB, 0, CB.Length)
                Memory.Write(ConfigTcp.ENDOFPACKET, 0, ConfigTcp.ENDOFPACKET.Length)
                sock.Send(Memory.ToArray, 0, Memory.Length, SocketFlags.None)
                Memory.Dispose()
            Catch x As Exception
            End Try
        End Sub
    End Class
    Public Class MessageReceivedEventArgs
        Inherits EventArgs
        Public Sender As String
        Public clientSocket As Socket
        Public Message As Byte()
    End Class
    Public Class ClientConnectedEventArgs
        Inherits EventArgs
        Public clientID As String
        Public clientSocket As Socket
    End Class

Body:
Your client needs to handle disconnects and reconnect if needed.

To accomplish this, you can catch a SocketException and see why the socket was closed.

Depending on the exception you can run a method to have your client reconnect.

Public Sub DoReconnect()
    Dim SecondsToWait as Integer=1
    Do
        Try
            Client = New TcpClient(host, Port)
            Exit Do
        Catch SockEx as SocketException
            'TODO: decide whether to attempt reconnection or exit
        Catch Ex as Exception
            'TODO: Most likely should terminate the program here
            Console.WriteLine(Ex.ToString())
            Exit Do
        End Try
        System.Threading.Thread.Sleep(SecondsToWait*1000)
        SecondsToWait <<=1 ' Exponential Back Off Time
    Loop
End Sub


问:
Dictionary compare between two objects
Assuming I have these objects

```<code>    var address = new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243");
    var person = new Person("Jane", "Smith", address);
</code>```

I want to check the equality of those object by using dictionary, so it's smiliar like this

```<code>    var dictionary = new Dictionary<object>{ [address] = address, [person] = person};
    Assert.IsTrue(dictionary.ContainsKey(new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243")));
    Assert.IsTrue(dictionary.ContainsKey(new Person("Jane", "Smith", address)));
</code>```

However, it's always return as False. what I'm missing here?

EDIT

Add custom dictionary

```<code>public class Dictionary<T> : Dictionary<T, T> where T : class, new()
{
}
</code>```

Add Classes

```<code>public abstract class BaseModel
{
    public string Id { get; set; }

    public BaseModel()
    {
    }
}

public class Address : BaseModel
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostalCode { get; set; }

    public Address() { }

    public override bool Equals(object value)
    {
        if (value == null)
            return false;

        Address mod = value as Address;

        return (mod != null)
            && (Street == mod.Street)
            && (City == mod.City)
            && (PostalCode == mod.PostalCode)
            && (State == mod.State);
    }

    public override int GetHashCode(){
        return base.GetHashCode();
    }

    public Address(string street, string city, string state, string postalCode) {
        this.Street = street;
        this.City = city;
        this.State = state;
        this.PostalCode = postalCode;
    }
}

public class Person : BaseModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public Person() { }

    public Person(string firstName, string lastName, Address address)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Address = address;
    }

    public override bool Equals(object value)
    {
        if (value == null)
            return false;

        Person mod = value as Person;

        return (mod != null)
            && (FirstName == mod.FirstName)
            && (LastName == mod.LastName)
            && (Address.Equals(mod.Address));
    }

    public override int GetHashCode(){
        return base.GetHashCode();
    }
}
</code>```

答:
Because you create new references of Address and Person, it wouldn't match the key, The following Assert statements would work:

```<code> var dictionary = new Dictionary<object, object> { [address] = address, [person] = person };
 Assert.IsTrue(dictionary.ContainsKey(address));
 Assert.IsTrue(dictionary.ContainsKey(person));
</code>```

UPDATE

If new references need to be created, make use of EqualityComparer argument for the dictionary:

```<code>public class CustomEqualityComparer : IEqualityComparer<object>
{
    public new bool Equals(object x, object y)
    {
        if (x is Address && y is Address)
        {
            var xAddress = x as Address;
            var yAddress = y as Address;
            return xAddress.Line1 == yAddress.Line1 &&
               xAddress.Line2 == yAddress.Line2 &&
               xAddress.Line3 == yAddress.Line3 &&
               xAddress.Line4 == yAddress.Line4;
        }

        if (x is Person && y is Person)
        {
            var xPerson = x as Person;
            var yPerson = y as Person;
            return xPerson.FirstName == yPerson.FirstName &&
               xPerson.LastName == yPerson.LastName;
        }

        return false;
    }

    public int GetHashCode(object obj)
    {
        if (obj is Address)
        {
            var address = obj as Address;
            return  address.Line1.GetHashCode() ^
                    address.Line2.GetHashCode() ^
                    address.Line3.GetHashCode() ^
                    address.Line4.GetHashCode();
        }

        if (obj is Person)
        {
            var person = obj as Person;
            return person.FirstName.GetHashCode() ^
                   person.LastName.GetHashCode();
        }

        return obj.GetHashCode();
    }
}
</code>```

And then in your test:

```<code>var dictionary = new Dictionary<object, object>(new CustomEqualityComparer())
        { [address] = address, [person] = person };
        Assert.IsTrue(dictionary.ContainsKey(new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243")));
        Assert.IsTrue(dictionary.ContainsKey(person));
</code>```

It is recommended to use the generic type instead of using the object in dictionary; Consider changing your key from object to a type.

Title: Dictionary compare between two objects

Body:
Assuming I have these objects

    var address = new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243");
    var person = new Person("Jane", "Smith", address);

I want to check the equality of those object by using dictionary, so it's smiliar like this

    var dictionary = new Dictionary<object>{ [address] = address, [person] = person};
    Assert.IsTrue(dictionary.ContainsKey(new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243")));
    Assert.IsTrue(dictionary.ContainsKey(new Person("Jane", "Smith", address)));

However, it's always return as False. what I'm missing here?

EDIT

Add custom dictionary

public class Dictionary<T> : Dictionary<T, T> where T : class, new()
{
}

Add Classes

public abstract class BaseModel
{
    public string Id { get; set; }

    public BaseModel()
    {
    }
}

public class Address : BaseModel
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostalCode { get; set; }

    public Address() { }

    public override bool Equals(object value)
    {
        if (value == null)
            return false;

        Address mod = value as Address;

        return (mod != null)
            && (Street == mod.Street)
            && (City == mod.City)
            && (PostalCode == mod.PostalCode)
            && (State == mod.State);
    }

    public override int GetHashCode(){
        return base.GetHashCode();
    }

    public Address(string street, string city, string state, string postalCode) {
        this.Street = street;
        this.City = city;
        this.State = state;
        this.PostalCode = postalCode;
    }
}

public class Person : BaseModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public Person() { }

    public Person(string firstName, string lastName, Address address)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Address = address;
    }

    public override bool Equals(object value)
    {
        if (value == null)
            return false;

        Person mod = value as Person;

        return (mod != null)
            && (FirstName == mod.FirstName)
            && (LastName == mod.LastName)
            && (Address.Equals(mod.Address));
    }

    public override int GetHashCode(){
        return base.GetHashCode();
    }
}

Body:
Because you create new references of Address and Person, it wouldn't match the key, The following Assert statements would work:

 var dictionary = new Dictionary<object, object> { [address] = address, [person] = person };
 Assert.IsTrue(dictionary.ContainsKey(address));
 Assert.IsTrue(dictionary.ContainsKey(person));

UPDATE

If new references need to be created, make use of EqualityComparer argument for the dictionary:

public class CustomEqualityComparer : IEqualityComparer<object>
{
    public new bool Equals(object x, object y)
    {
        if (x is Address && y is Address)
        {
            var xAddress = x as Address;
            var yAddress = y as Address;
            return xAddress.Line1 == yAddress.Line1 &&
               xAddress.Line2 == yAddress.Line2 &&
               xAddress.Line3 == yAddress.Line3 &&
               xAddress.Line4 == yAddress.Line4;
        }

        if (x is Person && y is Person)
        {
            var xPerson = x as Person;
            var yPerson = y as Person;
            return xPerson.FirstName == yPerson.FirstName &&
               xPerson.LastName == yPerson.LastName;
        }

        return false;
    }

    public int GetHashCode(object obj)
    {
        if (obj is Address)
        {
            var address = obj as Address;
            return  address.Line1.GetHashCode() ^
                    address.Line2.GetHashCode() ^
                    address.Line3.GetHashCode() ^
                    address.Line4.GetHashCode();
        }

        if (obj is Person)
        {
            var person = obj as Person;
            return person.FirstName.GetHashCode() ^
                   person.LastName.GetHashCode();
        }

        return obj.GetHashCode();
    }
}

And then in your test:

var dictionary = new Dictionary<object, object>(new CustomEqualityComparer())
        { [address] = address, [person] = person };
        Assert.IsTrue(dictionary.ContainsKey(new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243")));
        Assert.IsTrue(dictionary.ContainsKey(person));

It is recommended to use the generic type instead of using the object in dictionary; Consider changing your key from object to a type.