问:
How to permanently disable region-folding in Visual Studio 2008
Anyone know how to turn off code folding in visual studio 2008? Some of my colleagues love it, but I personally always want to see all the code, and never want code folded out of sight. I'd like a setting that means my copy of Visual Studio never folds <code>#regions</code>or function bodies. </p>

答:
The accepted answer turns off ALL code folding.  If you want to disable #region folding but  collapse comments, loops, methods, etc I wrote a plugin that does this for you.

Make #regions suck less (for free):

http://visualstudiogallery.msdn.microsoft.com/0ca60d35-1e02-43b7-bf59-ac7deb9afbca

Auto Expand regions when a file is opened

Optionally prevent regions from being collapsed (but still be able to collapse other code)

Give the #region / #end region lines a smaller, lighter background so they are less noticeable (also an option)

Works in C# and VB (but only in VS 2010/2012, not supported for 2008)

OwnerDisplayName: Steve Cooper

Body: Anyone know how to turn off code folding in visual studio 2008? Some of my colleagues love it, but I personally always want to see all the code, and never want code folded out of sight. I'd like a setting that means my copy of Visual Studio never folds #regionsor function bodies.


来源: stackexchange

问:
Concatenate a list until a certain character
I have this list:

```<code>Jokes =   ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']
</code>```

I would want to concatenate the list as follow:

```<code>Jokes = ['First joke \n Still first', 'Second joke \n Still second joke \n Still 2nd joke']
</code>```

Is this somehow possible?

Thank you,

答:
What criteria are you using to determine when to split. Are you using the ''? Are you expecting exactly the phrase "first joke" "second joke"? You don't tell us your criteria, so we are guessing. Suppose it is the ''. </p>

```<code>Jokes = ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']
idx   = Jokes.index('')
Jokes = ['\n'.join(Jokes[:idx]),'\n'.join(Jokes[idx+1:])]
print(Jokes)
</code>```

<p>If you have a longer list or more than one '', then this answer obviously changes. But I have no details, so I don't know. </p>

ContentLicense: CC BY-SA 4.0

Body:
I have this list:

Jokes =   ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']

I would want to concatenate the list as follow:

Jokes = ['First joke \n Still first', 'Second joke \n Still second joke \n Still 2nd joke']

Is this somehow possible?

Thank you,

Body:
What criteria are you using to determine when to split. Are you using the ''? Are you expecting exactly the phrase "first joke" "second joke"? You don't tell us your criteria, so we are guessing. Suppose it is the ''.

Jokes = ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']
idx   = Jokes.index('')
Jokes = ['\n'.join(Jokes[:idx]),'\n'.join(Jokes[idx+1:])]
print(Jokes)

If you have a longer list or more than one '', then this answer obviously changes. But I have no details, so I don't know.


问:
Image not uploading to server using react-native-image-crop-picker
I am using react-native-image-crop-picker I can select the image from gallery but when trying to upload to server via form-data, but the image is not uploading to server, its showing blank on server.Can anyone suggest me how to upload multiple image to server using react-native-image-crop-picker?It would be so appreciable.Thanks.</p>

答:
Assuming that your back-end server accepts file as a parameter for images and you are trying to upload multiple images to the server and on server, miltiple images handling is implemented and you are using axios for API handling, you can do something like:

```<code>const images = await ImageCropPicker.openPicker({
    mediaType: 'photo',
    compressImageQuality: 0.4
});

const data = new FormData();
images.forEach((image, index) => {
    data.append(`file[${index}]`, {
        uri: Platform.OS === 'ios' ? `file:///${image.path}` : image.path,
        type: 'image/jpeg',
        name: 'image.jpg'
    });
});

axios({
    url: 'imageUploadUrl',
    method: 'POST',
    data,
    headers: { 'Content-Type': 'multipart/form-data' }
}).then((response) => {
    console.log('image upload response: ', response)
}).catch((error) => {
    console.log('image upload error: ', error)
});
</code>```

Please do not forget to replace the imageUploadUrl with your server API url.

Body:
Assuming that your back-end server accepts file as a parameter for images and you are trying to upload multiple images to the server and on server, miltiple images handling is implemented and you are using axios for API handling, you can do something like:

const images = await ImageCropPicker.openPicker({
    mediaType: 'photo',
    compressImageQuality: 0.4
});

const data = new FormData();
images.forEach((image, index) => {
    data.append(`file[${index}]`, {
        uri: Platform.OS === 'ios' ? `file:///${image.path}` : image.path,
        type: 'image/jpeg',
        name: 'image.jpg'
    });
});

axios({
    url: 'imageUploadUrl',
    method: 'POST',
    data,
    headers: { 'Content-Type': 'multipart/form-data' }
}).then((response) => {
    console.log('image upload response: ', response)
}).catch((error) => {
    console.log('image upload error: ', error)
});

Please do not forget to replace the imageUploadUrl with your server API url.


问:
How to Make columns in row
Hi i want to know that how can we create column in a row with html and css.
Like this in the picture.1</p>

答:
You could use Flex Box to have a single row of items and use the boxes to space appropriately, this will also provide scaling for different screen sizes.

Here is a link to a great explaination of what Flex Box can do: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

If that's not what you're looking for, there's always making a table.

Title: How to Make columns in row


问:
Retry a command only once : when a command fails (in bash)
```<code> for ( i=3; i<5; i++)

 do

   execute some command 1

   if command 2 is successful then do not run the command 1 (the for loop should continue)

   if command 2 is not successful then run command 1 only once (like retry command 1 only once, after this the for loop should continue)

done
</code>```

This is to note that command 2 is dependent on command 1 and command 2 can only be executed after command 1

for example:

```<code> for ( i=3; i<5; i++)
 do
    echo "i" >> mytext.txt   ---> command 1
    if "check the content of mytext.txt file to see if the value of i is  actually added" ---> command 2
    if it is not added then execute echo "i" >> mytext.txt (command 1) again and only once.
    if i value is added to the file .. then exit and continue the loop
  done
</code>```

Since the "command 1" is quite big and not just an example echo statement here.I do not want to add "command 1" twice .. once outside and once inside the if condition. I want this logic in an optimized way with no redundancy of code.

答:
you can declare functions like</p>

```<code>function command
{
  your_command -f params

}

for ( i=3; i<5; i++)

 do
   if command ; then
      echo "success"
   else
      echo "retry"
      command
    fi

done

</code>```

Body:
 for ( i=3; i<5; i++)

 do

   execute some command 1

   if command 2 is successful then do not run the command 1 (the for loop should continue)

   if command 2 is not successful then run command 1 only once (like retry command 1 only once, after this the for loop should continue)

done

This is to note that command 2 is dependent on command 1 and command 2 can only be executed after command 1

for example:

 for ( i=3; i<5; i++)
 do
    echo "i" >> mytext.txt   ---> command 1
    if "check the content of mytext.txt file to see if the value of i is  actually added" ---> command 2
    if it is not added then execute echo "i" >> mytext.txt (command 1) again and only once.
    if i value is added to the file .. then exit and continue the loop
  done

Since the "command 1" is quite big and not just an example echo statement here.I do not want to add "command 1" twice .. once outside and once inside the if condition. I want this logic in an optimized way with no redundancy of code.

Body:
you can declare functions like

function command
{
  your_command -f params

}

for ( i=3; i<5; i++)

 do
   if command ; then
      echo "success"
   else
      echo "retry"
      command
    fi

done


问:
Rebuilding original signal from frequencies, amplitude, and phase obtained after doing an fft
Rebuilding original signal from frequencies, amplitude, and phase obtained after doing an fft.

Greetings

I'm trying to rebuild a signal from the frequency, amplitude, and phase obtained after I do an fft of a signal, but when I try and combine the fft data (frequency, amplitude, and phase) back to see if I get a similar signal, the pattern is a little off.  I think it has
to do with my formula which may be a little incorrect.

The formula I'm using to combine the data is:

```<code>amplitude*sin(2*pi*time*frequency+phase)+amplitude*cos(2*pi*time*frequency+phase);
</code>```

Please note:
At the moment I don't want to use IFFT due to the fact that I will be editing the amplitude and frequencies before the calculations are done

An image of the plot is below.  The top one is the original signal and the bottom one is the signal created with the equation.  If you want to know I'm using matlab but I think the problem is with the equation.

tia

答:
The IFFT is an efficient implementation of the following transformation:

```<code>       N-1
x[n] = SUM X[k] exp(j*2*pi*n*k/N)
       k=0
</code>```

where X[k] are your FFT results (complex amplitudes), and x[n] are your time-domain samples.  For real-only inputs, this can be rewritten in terms of cos and sin (or in terms of cos with a phase term), but it's usually easier just to stick with the complex representation.

[This can be heavily vectorised, but I'll leave that up to you!]

ContentLicense: CC BY-SA 3.0

Body:
Rebuilding original signal from frequencies, amplitude, and phase obtained after doing an fft.

Greetings

I'm trying to rebuild a signal from the frequency, amplitude, and phase obtained after I do an fft of a signal, but when I try and combine the fft data (frequency, amplitude, and phase) back to see if I get a similar signal, the pattern is a little off.  I think it has
to do with my formula which may be a little incorrect.

The formula I'm using to combine the data is:

amplitude*sin(2*pi*time*frequency+phase)+amplitude*cos(2*pi*time*frequency+phase);

Please note:
At the moment I don't want to use IFFT due to the fact that I will be editing the amplitude and frequencies before the calculations are done

An image of the plot is below.  The top one is the original signal and the bottom one is the signal created with the equation.  If you want to know I'm using matlab but I think the problem is with the equation.

tia

Body:
The IFFT is an efficient implementation of the following transformation:

       N-1
x[n] = SUM X[k] exp(j*2*pi*n*k/N)
       k=0

where X[k] are your FFT results (complex amplitudes), and x[n] are your time-domain samples.  For real-only inputs, this can be rewritten in terms of cos and sin (or in terms of cos with a phase term), but it's usually easier just to stick with the complex representation.

[This can be heavily vectorised, but I'll leave that up to you!]


问:
Generate HMAC SHA256 hash using key in C++
I am looking for some function or a way that would return HMAC SHA256 hash in C++ using secret key. I have seen documentation of Crypto++ and OpenSSL but it does not accept an extra parameter of secret key for computation. Can someone help me by providing some info, code snippets or links.</p>

答:
Following is a sample of function to generate SHA256-HMAC using Crypto++

#include <string>
#include <string_view>

#include <cryptopp/filters.h>
using CryptoPP::StringSink;
using CryptoPP::StringSource;
using CryptoPP::HashFilter;

#include <cryptopp/hmac.h>
using CryptoPP::HMAC;

#include <cryptopp/sha.h>
using CryptoPP::SHA256;

std::string CalcHmacSHA256(std::string_view decodedSecretKey, std::string_view request)
{
    // Calculate HMAC
    HMAC<SHA256> hmac(reinterpret_cast<CryptoPP::byte const*>(decodedSecretKey.data()), decodedSecretKey.size());

    std::string calculated_hmac;
    auto sink = std::make_unique<StringSink>(calculated_hmac);

    auto filter = std::make_unique<HashFilter>(hmac, sink.get());
    sink.release();

    StringSource(reinterpret_cast<CryptoPP::byte const*>(request.data()), request.size(), true, filter.get()); // StringSource
    filter.release();

    return calculated_hmac;
}

#include <iostream>

int main() {
    std::cout << CalcHmacSHA256("key", "data");
}
```

The source is CME iLink2 specification

Body:
Following is a sample of function to generate SHA256-HMAC using Crypto++

#include <string>
#include <string_view>

#include <cryptopp/filters.h>
using CryptoPP::StringSink;
using CryptoPP::StringSource;
using CryptoPP::HashFilter;

#include <cryptopp/hmac.h>
using CryptoPP::HMAC;

#include <cryptopp/sha.h>
using CryptoPP::SHA256;

std::string CalcHmacSHA256(std::string_view decodedSecretKey, std::string_view request)
{
    // Calculate HMAC
    HMAC<SHA256> hmac(reinterpret_cast<CryptoPP::byte const*>(decodedSecretKey.data()), decodedSecretKey.size());

    std::string calculated_hmac;
    auto sink = std::make_unique<StringSink>(calculated_hmac);

    auto filter = std::make_unique<HashFilter>(hmac, sink.get());
    sink.release();

    StringSource(reinterpret_cast<CryptoPP::byte const*>(request.data()), request.size(), true, filter.get()); // StringSource
    filter.release();

    return calculated_hmac;
}

#include <iostream>

int main() {
    std::cout << CalcHmacSHA256("key", "data");
}

The source is CME iLink2 specification


问:
Angular Reactive validate even if radio button is not selected
My form validates even if my radio button is not selected. I set initially to null and dont select any radio button but still form is valid

this.myForm = this.fb.group({
  enter: [null, [Validators.required]]
});

this.myForm.valueChanges.subscribe(i => {
  // i get form as valid
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form [formGroup]="myForm">
  <div role="group" aria-labelledby="aria-group-legend" class="left-pad-25">
    <input formControlName="enter" type="radio" [value]="true" tabindex="0"
      (change)="enterChange(true)" kendoRadioButton />
    <label for="rd1"> Yes </label>
    <input formControlName="enter" type="radio" [value]="false" tabindex="0"
      (change)="enterChange(false)" kendoRadioButton />
    <label for="rd2"> No </label>
    <span class="error-text" *ngIf="myForm.get('enter').errors
      && myForm.get('enter').touched || myForm.get('enter').dirty">
    <span class="checkbox-message"
      *ngIf="myForm.get('enter').hasError('required')">Please
      select one of these options.</span>
    </span>
  </div>
</form></code>```

答: for this case you need Validators.requiredTrue

Body:
My form validates even if my radio button is not selected. I set initially to null and dont select any radio button but still form is valid

this.myForm = this.fb.group({
  enter: [null, [Validators.required]]
});

this.myForm.valueChanges.subscribe(i => {
  // i get form as valid
});

<form [formGroup]="myForm">

    <input formControlName="enter" type="radio" [value]="true" tabindex="0"
      (change)="enterChange(true)" kendoRadioButton />
     Yes
    <input formControlName="enter" type="radio" [value]="false" tabindex="0"
      (change)="enterChange(false)" kendoRadioButton />
     No

    Please
      select one of these options.

</form>


问:
Need help with file IO in C
I'm converting the following code from C# to C, and I don't think I'm doing this correctly.

Entry3D and entry_3d are just structs that contain int lookup, length, extra in both cases.
Here's the C# snippet (and it works perfectly fine):

```<code>    BinaryReader reader = new BinaryReader(File.Open("artidx.mul", FileMode.Open));
    BinaryReader art = new BinaryReader(File.Open("art.mul", FileMode.Open));
    int count = (int)(reader.BaseStream.Length / 12);
    int length = 0x10000;
    Entry3D[] index = new Entry3D[length];
    Console.WriteLine("Loading indexes {0}", count);
    for (int i = 0; i < count && i < length; i++)
    {
        index[i].lookup = reader.ReadInt32();
        index[i].length = reader.ReadInt32();
        index[i].extra = reader.ReadInt32();
    }
    for (int i = count; i < length; ++i)
    {
        index[i].lookup = -1;
        index[i].length = -1;
        index[i].extra = -1;
    }
</code>```

Here's the part in C that I'm having trouble with.

```<code>/* Init everything else */
printf( "Init maps & gfx" );
mapFile = fopen( "sd:/map0.mul",   "rb" ),
 artIdx = fopen( "sd:/artidx.mul", "rb" ),
    art = fopen( "sd:/art.mul",    "rb" );

if ( mapFile == NULL || artIdx == NULL || art == NULL )
{
  printf( "D'oh, file loading failed: [%d][%d][%d]", mapFile == NULL, artIdx == NULL, art == NULL  );
  return(1);
}

/* Find artidx count and set length */
printf( "Init art index" );
fseek( artIdx, 0, SEEK_END );
int count = (ftell(artIdx) / 12), length = 0x10000; // 0x10000 entries availible
entry_3d entries[length];
fseek( artIdx, 0, SEEK_SET );

printf( "Reading art-idx, count=%d", count );
int i;
for( i = 0; i < count && i < length; i++ )
{
  //printf( "loc: %u i: %u", ftell( artIdx ), i );
  //fread( &entries[i], 12, 1, artIdx );
  fread( &(entries[i].lookup), 4, 1, artIdx ); // read 12 bytes total
  fread( &(entries[i].length), 4, 1, artIdx );
  fread( &(entries[i].extra), 4, 1, artIdx );
}

printf( "Setting aidx remainders" );
for ( i = count; i < length; i++ )
{
  entries[i].lookup = -1;
  entries[i].length = -1;
  entries[i].extra = -1;
}
</code>```

It's a bit impossible for me to debug the C part, but I can tell that it "dies" somewhere in the first for-loop. I'm guessing that it's possibly reading past the end of the stream (even though it shouldn't)?

答:
I don't see much wrong here. The code will work correctly on a linux/windows box.

Error handling could be improved.

It will not fail gracefully when the artidx file is not a multiple of 12 bytes.

I suppose this code could quite easily run out of memory on the Wii console. Try allocating the entry_3d array dynamically (using calloc/malloc). Also, try reducing the length to see whether you are running out of memory. It is not impossible that the libc implementation on the Wii doesn't warn you when stack will overlap heap; embedded systems sometimes assume the programmers know all the intricacies and limits of the device (The Wii with it's many processing chips is a very fine example of that in many respects, so I'd really consider this).

I'm pretty sure you know how to find the forums where the homebrew devs lurk. They might be able to shed some light here.

Title: Need help with file IO in C

Body:
I'm converting the following code from C# to C, and I don't think I'm doing this correctly.

Entry3D and entry_3d are just structs that contain int lookup, length, extra in both cases.
Here's the C# snippet (and it works perfectly fine):

    BinaryReader reader = new BinaryReader(File.Open("artidx.mul", FileMode.Open));
    BinaryReader art = new BinaryReader(File.Open("art.mul", FileMode.Open));
    int count = (int)(reader.BaseStream.Length / 12);
    int length = 0x10000;
    Entry3D[] index = new Entry3D[length];
    Console.WriteLine("Loading indexes {0}", count);
    for (int i = 0; i < count && i < length; i++)
    {
        index[i].lookup = reader.ReadInt32();
        index[i].length = reader.ReadInt32();
        index[i].extra = reader.ReadInt32();
    }
    for (int i = count; i < length; ++i)
    {
        index[i].lookup = -1;
        index[i].length = -1;
        index[i].extra = -1;
    }

Here's the part in C that I'm having trouble with.

/* Init everything else */
printf( "Init maps & gfx" );
mapFile = fopen( "sd:/map0.mul",   "rb" ),
 artIdx = fopen( "sd:/artidx.mul", "rb" ),
    art = fopen( "sd:/art.mul",    "rb" );

if ( mapFile == NULL || artIdx == NULL || art == NULL )
{
  printf( "D'oh, file loading failed: [%d][%d][%d]", mapFile == NULL, artIdx == NULL, art == NULL  );
  return(1);
}

/* Find artidx count and set length */
printf( "Init art index" );
fseek( artIdx, 0, SEEK_END );
int count = (ftell(artIdx) / 12), length = 0x10000; // 0x10000 entries availible
entry_3d entries[length];
fseek( artIdx, 0, SEEK_SET );

printf( "Reading art-idx, count=%d", count );
int i;
for( i = 0; i < count && i < length; i++ )
{
  //printf( "loc: %u i: %u", ftell( artIdx ), i );
  //fread( &entries[i], 12, 1, artIdx );
  fread( &(entries[i].lookup), 4, 1, artIdx ); // read 12 bytes total
  fread( &(entries[i].length), 4, 1, artIdx );
  fread( &(entries[i].extra), 4, 1, artIdx );
}

printf( "Setting aidx remainders" );
for ( i = count; i < length; i++ )
{
  entries[i].lookup = -1;
  entries[i].length = -1;
  entries[i].extra = -1;
}

It's a bit impossible for me to debug the C part, but I can tell that it "dies" somewhere in the first for-loop. I'm guessing that it's possibly reading past the end of the stream (even though it shouldn't)?


问:
Override Bootstrap CSS with custom CSS
I have a small problem overriding some of Bootstrap's CSS style.

The standard definition of a bootstrap table has the following code:

```<code>.table {
width: 100%;
max-width: 100%;
margin-bottom: 20px;
}
</code>```

I would like to set margin-bottom to 0px, using my own css code, but I'm having some problems overriding it.

This is my code:

```<code>table .table.table-responsive .table-middle {
margin-bottom: 0px;
}
</code>```

How to fix it?

Thanks in advance! :)

答:
Try Using !important after the css text. I have shown a example below
padding-bottom: 4.5rem !important;</p>

Title: Override Bootstrap CSS with custom CSS

Body:
I have a small problem overriding some of Bootstrap's CSS style.

The standard definition of a bootstrap table has the following code:

.table {
width: 100%;
max-width: 100%;
margin-bottom: 20px;
}

I would like to set margin-bottom to 0px, using my own css code, but I'm having some problems overriding it.

This is my code:

table .table.table-responsive .table-middle {
margin-bottom: 0px;
}

How to fix it?

Thanks in advance! :)


问:
Perl file transfer to remote server using Net::OpenSSH
I have a script which establishes connection to remote server using Perl module Net::OpenSSH and transfers files from local server to remote machine. This works perfectly fine.

```<code>...
my $ssh = ConnectToServer( $host, $user, $password );

my $remote_dir = "/home/shared/some/path/"

if ( $ssh->system('mkdir', '-p', $remote_dir) ) {
    print "Directory $remote_dir created!\n";
} else {
   print "Can't create $remote_dir on $host : ".$ssh->error."\n";
}

$ssh->scp_put({glob => 1}, "/home/shared/Test_Vinod/LOG/*.zip", $remote_dir)
        or die "scp failed: " . $ssh->error;

undef $ssh;

sub ConnectToServer {
    my ( $host, $user, $passwd ) = @_;
    my $ssh = Net::OpenSSH->new($host,
                                user => $user,
                                password => $passwd,
                                master_opts => [-o => "StrictHostKeyChecking=no"]
    );
    $ssh->error and die "Couldn't establish SSH connection: ". $ssh->error;

    return $ssh;
}
</code>```

But whenever I execute this script I get message:

```<code>Directory /home/shared/some/path/ created!
</code>```

My understanding on line if ($ssh->system('mkdir', '-p', $remote_dir)) { is:

If $remote_dir doesn't exists create it recursively on remote machine.

But how the value of $ssh->system('mkdir', '-p', $remote_dir) becomes 1 even when directory already exists.

Maybe I am confused with -p flag. Experts comments expected. Thanks.

答:
The -p flag doesn't care that the directory already exists. As long as it exists at the end, it exits successfully.

```<code>$ mkdir -p test/a/b/c
$ echo $?
0

$ mkdir -p test/a/b/c
$ echo $?
0
</code>```

The man page for mkdir on macOS notes this behavior:

```<code>-p      Create intermediate directories as required.  If this
option is not specified, the full path prefix of each operand must
already exist. On the other hand, with this option specified, no
error will be reported if a directory given as an operand already
exists.  Intermediate directories are created with permission bits
of rwxrwxrwx (0777) as modified by the current umask, plus write
and search permission for the owner.
</code>```

Net::Openssl::system returns true if the remote command exited successfully (exit 0, as you see above), so it will always return true if the directory exists at the end of the mkdir call.

This is a nice idempotent feature. You can run that mkdir -p as often as you like without worrying about the directories existing. You want that directory tree to exist and as long as it does, mkdir exits successfully.

Body:
I have a script which establishes connection to remote server using Perl module Net::OpenSSH and transfers files from local server to remote machine. This works perfectly fine.

...
my $ssh = ConnectToServer( $host, $user, $password );

my $remote_dir = "/home/shared/some/path/"

if ( $ssh->system('mkdir', '-p', $remote_dir) ) {
    print "Directory $remote_dir created!\n";
} else {
   print "Can't create $remote_dir on $host : ".$ssh->error."\n";
}

$ssh->scp_put({glob => 1}, "/home/shared/Test_Vinod/LOG/*.zip", $remote_dir)
        or die "scp failed: " . $ssh->error;

undef $ssh;

sub ConnectToServer {
    my ( $host, $user, $passwd ) = @_;
    my $ssh = Net::OpenSSH->new($host,
                                user => $user,
                                password => $passwd,
                                master_opts => [-o => "StrictHostKeyChecking=no"]
    );
    $ssh->error and die "Couldn't establish SSH connection: ". $ssh->error;

    return $ssh;
}

But whenever I execute this script I get message:

Directory /home/shared/some/path/ created!

My understanding on line if ($ssh->system('mkdir', '-p', $remote_dir)) { is:

If $remote_dir doesn't exists create it recursively on remote machine.

But how the value of $ssh->system('mkdir', '-p', $remote_dir) becomes 1 even when directory already exists.

Maybe I am confused with -p flag. Experts comments expected. Thanks.

Body:
The -p flag doesn't care that the directory already exists. As long as it exists at the end, it exits successfully.

$ mkdir -p test/a/b/c
$ echo $?
0

$ mkdir -p test/a/b/c
$ echo $?
0

The man page for mkdir on macOS notes this behavior:

-p      Create intermediate directories as required.  If this
option is not specified, the full path prefix of each operand must
already exist. On the other hand, with this option specified, no
error will be reported if a directory given as an operand already
exists.  Intermediate directories are created with permission bits
of rwxrwxrwx (0777) as modified by the current umask, plus write
and search permission for the owner.

Net::Openssl::system returns true if the remote command exited successfully (exit 0, as you see above), so it will always return true if the directory exists at the end of the mkdir call.

This is a nice idempotent feature. You can run that mkdir -p as often as you like without worrying about the directories existing. You want that directory tree to exist and as long as it does, mkdir exits successfully.


问:
NGINX headers not working with GAE app.yaml
I'm trying to set some Nginx headers, running on Google App Engine B4.

This is the piece of code that I've placed in my app.yaml file:

```<code>runtime_config:
  nginx_conf_http_include: nginx-http.conf
</code>```

An this is the content of the nginx-http.conf file:

```<code># Security headers
server_tokens off;
add_header X-Frame-Options SAMEORIGIN always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Content-Security-Policy "default-src 'self';" always;
add_header Referrer-Policy no-referrer;
add_header Feature-Policy "geolocation none;midi none;notifications none;push none;sync-xhr none;microphone none;camera none;magnetometer none;gyroscope none;speaker self;vibrate none;fullscreen self;payment none;";
</code>```

None of these headers are available after deployment.

Please help guys!

答:
The nginx_conf_http_include configuration item is only available for Flex environments and PHP language, that's why it doesn't work.
The best way to approach would be to set the headers by using the Handlers element, more specifically the http_headers, for example:

```<code>handlers:
- url: /images
  static_dir: static/images
  http_headers:
    X-Foo-Header: foo
    X-Bar-Header: bar value
  # ...
</code>```

Body:
I'm trying to set some Nginx headers, running on Google App Engine B4.

This is the piece of code that I've placed in my app.yaml file:

runtime_config:
  nginx_conf_http_include: nginx-http.conf

An this is the content of the nginx-http.conf file:

# Security headers
server_tokens off;
add_header X-Frame-Options SAMEORIGIN always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Content-Security-Policy "default-src 'self';" always;
add_header Referrer-Policy no-referrer;
add_header Feature-Policy "geolocation none;midi none;notifications none;push none;sync-xhr none;microphone none;camera none;magnetometer none;gyroscope none;speaker self;vibrate none;fullscreen self;payment none;";

None of these headers are available after deployment.

Please help guys!

Body:
The nginx_conf_http_include configuration item is only available for Flex environments and PHP language, that's why it doesn't work.
The best way to approach would be to set the headers by using the Handlers element, more specifically the http_headers, for example:

handlers:
- url: /images
  static_dir: static/images
  http_headers:
    X-Foo-Header: foo
    X-Bar-Header: bar value
  # ...


问:
Is it possible to read php code from other sites?
Just a curious question. I was wondering is it possible to read a sites php/server side codes? Is there any software/method that can be used to do so? Sometimes for educational purposes, i really want to see how people form the backend infrastructure of their sites. </p>

答: It is not possible to tell that people are even using php at all in their back end unless the site provider allows you to know that.</p>


问:
Automatically click the default button in the windows based dialog box using python
I am working on a project to handle windows based dialog box. When I click on a web link, it opens up a dialog box with the 'save file' and 'cancel' buttons. How can I click the save file button using python? It's an executable file(.exe).

I tried using webdriver.FirefoxProfile() set preferences but no luck so far.

```<code>from selenium import webdriver
profile = webdriver.FirefoxProfile()

profile.set_preference('browser.download.folderList', 0)
profile.set_preference('browser.download.manager.showWhenStarting',False)
profile.set_preference('browser.download.dir', 'C:\Desktop\Python')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk','exe/application')

browser = webdriver.Firefox(profile)
browser.get('https://youtube-dl.org/')

browser.find_element_by_link_text('youtube-dl.exe').click()
</code>```

答:
Click on F12 and fin xpath:

Or simple use: xpather

```<code>import scrapy
from selenium import webdriver

class ProductSpider(scrapy.Spider):
    name = "youtube-dl.exe"
    allowed_domains = ['youtube-dl.org']
    start_urls = ['https://youtube-dl.org/']

    def __init__(self):
        self.driver = webdriver.Firefox()

    def parse(self, response):
        self.driver.get(response.url)

        while True:
            next = self.driver.find_element_by_xpath('//td[@class="pagn-next"]/a')

            try:
                next.click()

                # get the data and write it to scrapy items
            except:
                break

        self.driver.close()
</code>```

Body:
I am working on a project to handle windows based dialog box. When I click on a web link, it opens up a dialog box with the 'save file' and 'cancel' buttons. How can I click the save file button using python? It's an executable file(.exe).

I tried using webdriver.FirefoxProfile() set preferences but no luck so far.

from selenium import webdriver
profile = webdriver.FirefoxProfile()

profile.set_preference('browser.download.folderList', 0)
profile.set_preference('browser.download.manager.showWhenStarting',False)
profile.set_preference('browser.download.dir', 'C:\Desktop\Python')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk','exe/application')

browser = webdriver.Firefox(profile)
browser.get('https://youtube-dl.org/')

browser.find_element_by_link_text('youtube-dl.exe').click()

Body:
Click on F12 and fin xpath:

Or simple use: xpather

import scrapy
from selenium import webdriver

class ProductSpider(scrapy.Spider):
    name = "youtube-dl.exe"
    allowed_domains = ['youtube-dl.org']
    start_urls = ['https://youtube-dl.org/']

    def __init__(self):
        self.driver = webdriver.Firefox()

    def parse(self, response):
        self.driver.get(response.url)

        while True:
            next = self.driver.find_element_by_xpath('//td[@class="pagn-next"]/a')

            try:
                next.click()

                # get the data and write it to scrapy items
            except:
                break

        self.driver.close()


答: You can try using one row like container, inside create 4 div's and add display flex and justify-content. </p>

Title: How to Make columns in row

Body:
Hi i want to know that how can we create column in a row with html and css.
Like this in the picture.1


问:
Why does getRootInActiveWindow() return null when trying to get the SMS window
I'm developing an application which reads the text on the screen to the user. When a user enters an SMS conversation, I want to read the messages sequentially from top to bottom.

To query the window which holds all of the UI elements (ie TextViews, EditTexts, etc.) of the SMS conversation, I am using getRootInActiveWindow() inside the onAccessibilityEvent(AccessibilityEvent event) method of my accessibility service. However, every time an AccessibilityEvent from the SMS window (package name: com.google.android.apps.messaging) is fired, getRootInActiveWindow() returns null.

Why does that occur and how can I get over this problem?

Thank you for the time taken!

答:
Set canRetrieveWindowContent in SERVICE_META_DATA to true.

Service Meta Data for Accessibility Service


问:
Using scaler in Sklearn PIpeline and Cross validation
I previously saw a post with code like this:

```<code>scalar = StandardScaler()
clf = svm.LinearSVC()

pipeline = Pipeline([('transformer', scalar), ('estimator', clf)])

cv = KFold(n_splits=4)
scores = cross_val_score(pipeline, X, y, cv = cv)
</code>```

My understanding is that: when we apply scaler, we should use 3 out of the 4 folds to calculate mean and standard deviation, then we apply the mean and standard deviation to all 4 folds.

In the above code, how can I know that Sklearn is following the same strategy? On the other hand, if sklearn is not following the same strategy, which means sklearn would calculate the mean/std from all 4 folds. Would that mean I should not use the above codes?

I do like the above codes because it saves tons of time.

答:
Yes, this is done properly; this is one of the reasons for using pipelines: all the preprocessing is fitted only on training folds.

Some references.

Section 6.1.1 of the User Guide:

Safety

  Pipelines help avoid leaking statistics from your test data into the trained model in cross-validation, by ensuring that the same samples are used to train the transformers and predictors.

The note at the end of section 3.1.1 of the User Guide:

Data transformation with held out data

  Just as it is important to test a predictor on data held-out from training, preprocessing (such as standardization, feature selection, etc.) and similar data transformations similarly should be learnt from a training set and applied to held-out data for prediction:

  ...code sample...

  A Pipeline makes it easier to compose estimators, providing this behavior under cross-validation:

  ...

Finally, you can look into the source for cross_val_score.  It calls cross_validate, which clones and fits the estimator (in this case, the entire pipeline) on each training split.  GitHub link.

Body:
I previously saw a post with code like this:

scalar = StandardScaler()
clf = svm.LinearSVC()

pipeline = Pipeline([('transformer', scalar), ('estimator', clf)])

cv = KFold(n_splits=4)
scores = cross_val_score(pipeline, X, y, cv = cv)

My understanding is that: when we apply scaler, we should use 3 out of the 4 folds to calculate mean and standard deviation, then we apply the mean and standard deviation to all 4 folds.

In the above code, how can I know that Sklearn is following the same strategy? On the other hand, if sklearn is not following the same strategy, which means sklearn would calculate the mean/std from all 4 folds. Would that mean I should not use the above codes?

I do like the above codes because it saves tons of time.


问:
filtering out values in a multi-dimensional array in php
I have a situation where I have two arrays and I use one array(A) to determine which elements of the second array(B) I need to use. Since I will be combing B multiple times and each time I will not need the previously used elements I have written a function that I call sift_array.

```<code>function sift_array(&$array, $key, $value){
   foreach($array as $element){
      if($element[$key] == $value){$temp[] = $element;}
      else{$temp2[] = $element;}
   }
   $array = $temp2;
   return $temp;
}</code>```

I am curious if there is a faster way to perform this function.

Here is an example of how I use this function.

In my web app users can set up a 'bot' to perform an action so many times while they are away/logged off. I have a program that will run periodically to operate the bots. The bots can not run the same action if it was the last bot to do so.

The bots array has 3 key elements     : account_id, action_id, job_id
The job array has 1 key element      : job_id.

I pass in the bots array then for the $key I pass 'job_id' and for the $value I pass the job id I am working with, say job 1.

```<code>$runTheseBots = sift_array($bots, 'job_id', 1);
executeBots($runTheseBots);</code>```

This will have a faster execution time because all the bots that deal with job 1 are already handled.

```<code>$runTheseBots = sift_array($bots, 'job_id', 2);
executeBots($runTheseBots);</code>```

答:
A better option would be something called a "Bucket sort".

This is the quickest option for sorting, if there is a relatively small number of 'buckets'.

In this case, each job_id is a 'bucket'.

You only want to be sifting the array once. For each element, you place it in an appropriate bucket, depending on the job_id, (one bucket per job_id).

That way the array is only sorted once, and accessing all elements for each job consumes zero extra processing.

If optimising is absolutely critical, you could have two or more sort functions. Selection of the sort algorithm is done at run time based on the number of buckets and elements that need to be dealt with.

Body:
I have a situation where I have two arrays and I use one array(A) to determine which elements of the second array(B) I need to use. Since I will be combing B multiple times and each time I will not need the previously used elements I have written a function that I call sift_array.

function sift_array(&$array, $key, $value){
   foreach($array as $element){
      if($element[$key] == $value){$temp[] = $element;}
      else{$temp2[] = $element;}
   }
   $array = $temp2;
   return $temp;
}

I am curious if there is a faster way to perform this function.

Here is an example of how I use this function.

In my web app users can set up a 'bot' to perform an action so many times while they are away/logged off. I have a program that will run periodically to operate the bots. The bots can not run the same action if it was the last bot to do so.

The bots array has 3 key elements     : account_id, action_id, job_id
The job array has 1 key element      : job_id.

I pass in the bots array then for the $key I pass 'job_id' and for the $value I pass the job id I am working with, say job 1.

$runTheseBots = sift_array($bots, 'job_id', 1);
executeBots($runTheseBots);

This will have a faster execution time because all the bots that deal with job 1 are already handled.

$runTheseBots = sift_array($bots, 'job_id', 2);
executeBots($runTheseBots);


问:
why does tensorboard give this error: InvalidArgumentError: Nan in summary histogram for
I built the model to classification using 1D convolution layers using tf.Keras .this works well if I remove the tensorboard.As I'm a beginner,I can't figure it out what the problem is.
Please help

```<code>%reload_ext tensorboard
import tensorflow as tf

from tensorflow.keras.layers import Dense, Activation,Conv1D,MaxPool1D,GlobalAveragePooling1D,Dropout,Flatten,concatenate,Input
from tensorflow.keras.models import Model

inp = Input(shape=(1000,21))
a = Conv1D(filters=250,padding='valid', kernel_size=(8),strides=1)(inp)
a=MaxPool1D(1000-8+1,strides=1,padding='valid')(a)
a=Flatten()(a)
b = Conv1D(filters=250,padding='valid', kernel_size=(12))(inp)
b=MaxPool1D(1000-12+1,strides=1,padding='valid')(b)
b=Flatten()(b)
c = Conv1D(filters=250,padding='valid', kernel_size=(16))(inp)
c=MaxPool1D(1000-16+1,strides=1,padding='valid')(c)
c=Flatten()(c)
d = Conv1D(filters=250,padding='valid', kernel_size=(20))(inp)
d=MaxPool1D(1000-20+1,strides=1,padding='valid')(d)
d=Flatten()(d)
e = Conv1D(filters=250,padding='valid', kernel_size=(24))(inp)
e=MaxPool1D(1000-24+1,strides=1,padding='valid')(e)
e=Flatten()(e)
f = Conv1D(filters=250,padding='valid', kernel_size=(28))(inp)
f=MaxPool1D(1000-28+1,strides=1,padding='valid')(f)
f=Flatten()(f)
g = Conv1D(filters=250,padding='valid', kernel_size=(32))(inp)
g=MaxPool1D(1000-32+1,strides=1,padding='valid')(g)
g=Flatten()(g)
h= Conv1D(filters=250,padding='valid', kernel_size=(36))(inp)
h=MaxPool1D(1000-36+1,strides=1,padding='valid')(h)
h=Flatten()(h)
model=concatenate([a,b,c,d,e,f,g,h],1)
model = Dropout(0.3)(model)
#model = Dense(2000,activation='relu')(model)
model = Dense(2892,activation='sigmoid')(model)
model = Model(inp, model)
print(model.summary())
</code>```

and use the sequence class batch generator to input batches

```<code>class MyGenerator(tf.keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, ids, train_dir):
        'Initialization'
        self.ids = ids
        self.train_dir = train_dir

    def __len__(self):
        'Denotes the number of batches per epoch'
        batch_size=100
        numofBatchs=math.ceil(len(self.train_dir) / batch_size)
        return numofBatchs

    def __getitem__(self, index):

      test_resL=[]
      test_resD=[]
      start_posT = index * 100
      end_posT = min(start_posT + 100, len(self.train_dir))
      test_resL=self.ids[start_posT:end_posT]
      test_resD=self.train_dir[start_posT:end_posT]
      #iTest += 1

      isize=len(test_resL)

      dataTest = np.zeros( (isize,1000,21), dtype=np.float32 )
      labelsTest = np.zeros( (isize,2892), dtype=np.uint8 )
      #rawTest = []

      for i , idy in enumerate(test_resL):
          label=idy
          #print(label)
          encoding_label_np(label, labelsTest[i] )
      for i , idx in enumerate(test_resD):
          seq=idx
          encoding_seq_np(seq, dataTest[i] )
      #dataShped=np.reshape(dataTest,(-1, 1, 1000, 21))
      # print(dataTest[0:2])
      # print(labelsTest[0:2])
      return dataTest,labelsTest
</code>```

after adding tensor board it runs 1st epoch only.

```<code>poch 1/20
10431/10431 [==============================] - ETA: 0s - loss: 2.7652 - accuracy: 0.3496
---------------------------------------------------------------------------
_FallbackException                        Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_summary_ops.py in write_histogram_summary(writer, step, tag, values, name)
    463         _ctx._context_handle, tld.device_name, "WriteHistogramSummary", name,
--> 464         tld.op_callbacks, writer, step, tag, values)
    465       return _result

_FallbackException: This function does not handle the case of the path where all inputs are not already EagerTensors.

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
13 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     58     ctx.ensure_initialized()
     59     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 60                                         inputs, attrs, num_outputs)
     61   except core._NotOkStatusException as e:
     62     if name is not None:

InvalidArgumentError: Nan in summary histogram for: conv1d_16/kernel_0 [Op:WriteHistogramSummary]
</code>```

答:
Providing the solution here (Answer Section), even though it is present in the comment section for the benefit of the community.

```<code>InvalidArgumentError: Nan in summary histogram for: conv1d_16/kernel_0 [Op:WriteHistogramSummary]
</code>```

This issue was resolved after modifying activation function from sigmoid to softmax in  the dense layer of Model.

Final Model Structure is as below

```<code>import tensorflow as tf

from tensorflow.keras.layers import Dense, Activation,Conv1D,MaxPool1D,GlobalAveragePooling1D,Dropout,Flatten,concatenate,Input
from tensorflow.keras.models import Model

inp = Input(shape=(1000,21))
a = Conv1D(filters=250,padding='valid', kernel_size=(8),strides=1)(inp)
a=MaxPool1D(1000-8+1,strides=1,padding='valid')(a)
a=Flatten()(a)
b = Conv1D(filters=250,padding='valid', kernel_size=(12))(inp)
b=MaxPool1D(1000-12+1,strides=1,padding='valid')(b)
b=Flatten()(b)
c = Conv1D(filters=250,padding='valid', kernel_size=(16))(inp)
c=MaxPool1D(1000-16+1,strides=1,padding='valid')(c)
c=Flatten()(c)
d = Conv1D(filters=250,padding='valid', kernel_size=(20))(inp)
d=MaxPool1D(1000-20+1,strides=1,padding='valid')(d)
d=Flatten()(d)
e = Conv1D(filters=250,padding='valid', kernel_size=(24))(inp)
e=MaxPool1D(1000-24+1,strides=1,padding='valid')(e)
e=Flatten()(e)
f = Conv1D(filters=250,padding='valid', kernel_size=(28))(inp)
f=MaxPool1D(1000-28+1,strides=1,padding='valid')(f)
f=Flatten()(f)
g = Conv1D(filters=250,padding='valid', kernel_size=(32))(inp)
g=MaxPool1D(1000-32+1,strides=1,padding='valid')(g)
g=Flatten()(g)
h= Conv1D(filters=250,padding='valid', kernel_size=(36))(inp)
h=MaxPool1D(1000-36+1,strides=1,padding='valid')(h)
h=Flatten()(h)
model=concatenate([a,b,c,d,e,f,g,h],1)
model = Dropout(0.3)(model)
#model = Dense(2000,activation='relu')(model)
model = Dense(2892,activation='softmax')(model)
model = Model(inp, model)
print(model.summary())
</code>```

Output:

```<code>Model: "model"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_1 (InputLayer)            [(None, 1000, 21)]   0
__________________________________________________________________________________________________
conv1d (Conv1D)                 (None, 993, 250)     42250       input_1[0][0]
__________________________________________________________________________________________________
conv1d_1 (Conv1D)               (None, 989, 250)     63250       input_1[0][0]
__________________________________________________________________________________________________
conv1d_2 (Conv1D)               (None, 985, 250)     84250       input_1[0][0]
__________________________________________________________________________________________________
conv1d_3 (Conv1D)               (None, 981, 250)     105250      input_1[0][0]
__________________________________________________________________________________________________
conv1d_4 (Conv1D)               (None, 977, 250)     126250      input_1[0][0]
__________________________________________________________________________________________________
conv1d_5 (Conv1D)               (None, 973, 250)     147250      input_1[0][0]
__________________________________________________________________________________________________
conv1d_6 (Conv1D)               (None, 969, 250)     168250      input_1[0][0]
__________________________________________________________________________________________________
conv1d_7 (Conv1D)               (None, 965, 250)     189250      input_1[0][0]
__________________________________________________________________________________________________
max_pooling1d (MaxPooling1D)    (None, 1, 250)       0           conv1d[0][0]
__________________________________________________________________________________________________
max_pooling1d_1 (MaxPooling1D)  (None, 1, 250)       0           conv1d_1[0][0]
__________________________________________________________________________________________________
max_pooling1d_2 (MaxPooling1D)  (None, 1, 250)       0           conv1d_2[0][0]
__________________________________________________________________________________________________
max_pooling1d_3 (MaxPooling1D)  (None, 1, 250)       0           conv1d_3[0][0]
__________________________________________________________________________________________________
max_pooling1d_4 (MaxPooling1D)  (None, 1, 250)       0           conv1d_4[0][0]
__________________________________________________________________________________________________
max_pooling1d_5 (MaxPooling1D)  (None, 1, 250)       0           conv1d_5[0][0]
__________________________________________________________________________________________________
max_pooling1d_6 (MaxPooling1D)  (None, 1, 250)       0           conv1d_6[0][0]
__________________________________________________________________________________________________
max_pooling1d_7 (MaxPooling1D)  (None, 1, 250)       0           conv1d_7[0][0]
__________________________________________________________________________________________________
flatten (Flatten)               (None, 250)          0           max_pooling1d[0][0]
__________________________________________________________________________________________________
flatten_1 (Flatten)             (None, 250)          0           max_pooling1d_1[0][0]
__________________________________________________________________________________________________
flatten_2 (Flatten)             (None, 250)          0           max_pooling1d_2[0][0]
__________________________________________________________________________________________________
flatten_3 (Flatten)             (None, 250)          0           max_pooling1d_3[0][0]
__________________________________________________________________________________________________
flatten_4 (Flatten)             (None, 250)          0           max_pooling1d_4[0][0]
__________________________________________________________________________________________________
flatten_5 (Flatten)             (None, 250)          0           max_pooling1d_5[0][0]
__________________________________________________________________________________________________
flatten_6 (Flatten)             (None, 250)          0           max_pooling1d_6[0][0]
__________________________________________________________________________________________________
flatten_7 (Flatten)             (None, 250)          0           max_pooling1d_7[0][0]
__________________________________________________________________________________________________
concatenate (Concatenate)       (None, 2000)         0           flatten[0][0]
                                                                 flatten_1[0][0]
                                                                 flatten_2[0][0]
                                                                 flatten_3[0][0]
                                                                 flatten_4[0][0]
                                                                 flatten_5[0][0]
                                                                 flatten_6[0][0]
                                                                 flatten_7[0][0]
__________________________________________________________________________________________________
dropout (Dropout)               (None, 2000)         0           concatenate[0][0]
__________________________________________________________________________________________________
dense (Dense)                   (None, 2892)         5786892     dropout[0][0]
==================================================================================================
Total params: 6,712,892
Trainable params: 6,712,892
Non-trainable params: 0
______________________________________
</code>```

Body:
I built the model to classification using 1D convolution layers using tf.Keras .this works well if I remove the tensorboard.As I'm a beginner,I can't figure it out what the problem is.
Please help

%reload_ext tensorboard
import tensorflow as tf

from tensorflow.keras.layers import Dense, Activation,Conv1D,MaxPool1D,GlobalAveragePooling1D,Dropout,Flatten,concatenate,Input
from tensorflow.keras.models import Model

inp = Input(shape=(1000,21))
a = Conv1D(filters=250,padding='valid', kernel_size=(8),strides=1)(inp)
a=MaxPool1D(1000-8+1,strides=1,padding='valid')(a)
a=Flatten()(a)
b = Conv1D(filters=250,padding='valid', kernel_size=(12))(inp)
b=MaxPool1D(1000-12+1,strides=1,padding='valid')(b)
b=Flatten()(b)
c = Conv1D(filters=250,padding='valid', kernel_size=(16))(inp)
c=MaxPool1D(1000-16+1,strides=1,padding='valid')(c)
c=Flatten()(c)
d = Conv1D(filters=250,padding='valid', kernel_size=(20))(inp)
d=MaxPool1D(1000-20+1,strides=1,padding='valid')(d)
d=Flatten()(d)
e = Conv1D(filters=250,padding='valid', kernel_size=(24))(inp)
e=MaxPool1D(1000-24+1,strides=1,padding='valid')(e)
e=Flatten()(e)
f = Conv1D(filters=250,padding='valid', kernel_size=(28))(inp)
f=MaxPool1D(1000-28+1,strides=1,padding='valid')(f)
f=Flatten()(f)
g = Conv1D(filters=250,padding='valid', kernel_size=(32))(inp)
g=MaxPool1D(1000-32+1,strides=1,padding='valid')(g)
g=Flatten()(g)
h= Conv1D(filters=250,padding='valid', kernel_size=(36))(inp)
h=MaxPool1D(1000-36+1,strides=1,padding='valid')(h)
h=Flatten()(h)
model=concatenate([a,b,c,d,e,f,g,h],1)
model = Dropout(0.3)(model)
#model = Dense(2000,activation='relu')(model)
model = Dense(2892,activation='sigmoid')(model)
model = Model(inp, model)
print(model.summary())

and use the sequence class batch generator to input batches

class MyGenerator(tf.keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, ids, train_dir):
        'Initialization'
        self.ids = ids
        self.train_dir = train_dir

    def __len__(self):
        'Denotes the number of batches per epoch'
        batch_size=100
        numofBatchs=math.ceil(len(self.train_dir) / batch_size)
        return numofBatchs

    def __getitem__(self, index):

      test_resL=[]
      test_resD=[]
      start_posT = index * 100
      end_posT = min(start_posT + 100, len(self.train_dir))
      test_resL=self.ids[start_posT:end_posT]
      test_resD=self.train_dir[start_posT:end_posT]
      #iTest += 1

      isize=len(test_resL)

      dataTest = np.zeros( (isize,1000,21), dtype=np.float32 )
      labelsTest = np.zeros( (isize,2892), dtype=np.uint8 )
      #rawTest = []

      for i , idy in enumerate(test_resL):
          label=idy
          #print(label)
          encoding_label_np(label, labelsTest[i] )
      for i , idx in enumerate(test_resD):
          seq=idx
          encoding_seq_np(seq, dataTest[i] )
      #dataShped=np.reshape(dataTest,(-1, 1, 1000, 21))
      # print(dataTest[0:2])
      # print(labelsTest[0:2])
      return dataTest,labelsTest

after adding tensor board it runs 1st epoch only.

poch 1/20
10431/10431 [==============================] - ETA: 0s - loss: 2.7652 - accuracy: 0.3496
---------------------------------------------------------------------------
_FallbackException                        Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_summary_ops.py in write_histogram_summary(writer, step, tag, values, name)
    463         _ctx._context_handle, tld.device_name, "WriteHistogramSummary", name,
--> 464         tld.op_callbacks, writer, step, tag, values)
    465       return _result

_FallbackException: This function does not handle the case of the path where all inputs are not already EagerTensors.

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
13 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     58     ctx.ensure_initialized()
     59     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 60                                         inputs, attrs, num_outputs)
     61   except core._NotOkStatusException as e:
     62     if name is not None:

InvalidArgumentError: Nan in summary histogram for: conv1d_16/kernel_0 [Op:WriteHistogramSummary]

Body:
Providing the solution here (Answer Section), even though it is present in the comment section for the benefit of the community.

InvalidArgumentError: Nan in summary histogram for: conv1d_16/kernel_0 [Op:WriteHistogramSummary]

This issue was resolved after modifying activation function from sigmoid to softmax in  the dense layer of Model.

Final Model Structure is as below

import tensorflow as tf

from tensorflow.keras.layers import Dense, Activation,Conv1D,MaxPool1D,GlobalAveragePooling1D,Dropout,Flatten,concatenate,Input
from tensorflow.keras.models import Model

inp = Input(shape=(1000,21))
a = Conv1D(filters=250,padding='valid', kernel_size=(8),strides=1)(inp)
a=MaxPool1D(1000-8+1,strides=1,padding='valid')(a)
a=Flatten()(a)
b = Conv1D(filters=250,padding='valid', kernel_size=(12))(inp)
b=MaxPool1D(1000-12+1,strides=1,padding='valid')(b)
b=Flatten()(b)
c = Conv1D(filters=250,padding='valid', kernel_size=(16))(inp)
c=MaxPool1D(1000-16+1,strides=1,padding='valid')(c)
c=Flatten()(c)
d = Conv1D(filters=250,padding='valid', kernel_size=(20))(inp)
d=MaxPool1D(1000-20+1,strides=1,padding='valid')(d)
d=Flatten()(d)
e = Conv1D(filters=250,padding='valid', kernel_size=(24))(inp)
e=MaxPool1D(1000-24+1,strides=1,padding='valid')(e)
e=Flatten()(e)
f = Conv1D(filters=250,padding='valid', kernel_size=(28))(inp)
f=MaxPool1D(1000-28+1,strides=1,padding='valid')(f)
f=Flatten()(f)
g = Conv1D(filters=250,padding='valid', kernel_size=(32))(inp)
g=MaxPool1D(1000-32+1,strides=1,padding='valid')(g)
g=Flatten()(g)
h= Conv1D(filters=250,padding='valid', kernel_size=(36))(inp)
h=MaxPool1D(1000-36+1,strides=1,padding='valid')(h)
h=Flatten()(h)
model=concatenate([a,b,c,d,e,f,g,h],1)
model = Dropout(0.3)(model)
#model = Dense(2000,activation='relu')(model)
model = Dense(2892,activation='softmax')(model)
model = Model(inp, model)
print(model.summary())

Output:

Model: "model"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_1 (InputLayer)            [(None, 1000, 21)]   0
__________________________________________________________________________________________________
conv1d (Conv1D)                 (None, 993, 250)     42250       input_1[0][0]
__________________________________________________________________________________________________
conv1d_1 (Conv1D)               (None, 989, 250)     63250       input_1[0][0]
__________________________________________________________________________________________________
conv1d_2 (Conv1D)               (None, 985, 250)     84250       input_1[0][0]
__________________________________________________________________________________________________
conv1d_3 (Conv1D)               (None, 981, 250)     105250      input_1[0][0]
__________________________________________________________________________________________________
conv1d_4 (Conv1D)               (None, 977, 250)     126250      input_1[0][0]
__________________________________________________________________________________________________
conv1d_5 (Conv1D)               (None, 973, 250)     147250      input_1[0][0]
__________________________________________________________________________________________________
conv1d_6 (Conv1D)               (None, 969, 250)     168250      input_1[0][0]
__________________________________________________________________________________________________
conv1d_7 (Conv1D)               (None, 965, 250)     189250      input_1[0][0]
__________________________________________________________________________________________________
max_pooling1d (MaxPooling1D)    (None, 1, 250)       0           conv1d[0][0]
__________________________________________________________________________________________________
max_pooling1d_1 (MaxPooling1D)  (None, 1, 250)       0           conv1d_1[0][0]
__________________________________________________________________________________________________
max_pooling1d_2 (MaxPooling1D)  (None, 1, 250)       0           conv1d_2[0][0]
__________________________________________________________________________________________________
max_pooling1d_3 (MaxPooling1D)  (None, 1, 250)       0           conv1d_3[0][0]
__________________________________________________________________________________________________
max_pooling1d_4 (MaxPooling1D)  (None, 1, 250)       0           conv1d_4[0][0]
__________________________________________________________________________________________________
max_pooling1d_5 (MaxPooling1D)  (None, 1, 250)       0           conv1d_5[0][0]
__________________________________________________________________________________________________
max_pooling1d_6 (MaxPooling1D)  (None, 1, 250)       0           conv1d_6[0][0]
__________________________________________________________________________________________________
max_pooling1d_7 (MaxPooling1D)  (None, 1, 250)       0           conv1d_7[0][0]
__________________________________________________________________________________________________
flatten (Flatten)               (None, 250)          0           max_pooling1d[0][0]
__________________________________________________________________________________________________
flatten_1 (Flatten)             (None, 250)          0           max_pooling1d_1[0][0]
__________________________________________________________________________________________________
flatten_2 (Flatten)             (None, 250)          0           max_pooling1d_2[0][0]
__________________________________________________________________________________________________
flatten_3 (Flatten)             (None, 250)          0           max_pooling1d_3[0][0]
__________________________________________________________________________________________________
flatten_4 (Flatten)             (None, 250)          0           max_pooling1d_4[0][0]
__________________________________________________________________________________________________
flatten_5 (Flatten)             (None, 250)          0           max_pooling1d_5[0][0]
__________________________________________________________________________________________________
flatten_6 (Flatten)             (None, 250)          0           max_pooling1d_6[0][0]
__________________________________________________________________________________________________
flatten_7 (Flatten)             (None, 250)          0           max_pooling1d_7[0][0]
__________________________________________________________________________________________________
concatenate (Concatenate)       (None, 2000)         0           flatten[0][0]
                                                                 flatten_1[0][0]
                                                                 flatten_2[0][0]
                                                                 flatten_3[0][0]
                                                                 flatten_4[0][0]
                                                                 flatten_5[0][0]
                                                                 flatten_6[0][0]
                                                                 flatten_7[0][0]
__________________________________________________________________________________________________
dropout (Dropout)               (None, 2000)         0           concatenate[0][0]
__________________________________________________________________________________________________
dense (Dense)                   (None, 2892)         5786892     dropout[0][0]
==================================================================================================
Total params: 6,712,892
Trainable params: 6,712,892
Non-trainable params: 0
______________________________________


问:
Why am I getting an error when trying to compare to dictionary values?
I'm supposed to:

Write a function, precipiation(d, a, b) that takes parameters:

d: Dictionary mapping a season to an amount of precipitation for that season.
a: One season
b: Another season

Your function should return True if the rainfall in season a was greater than it was in season b, and False otherwise. If the rainfall was equal, return False.

Your function should handle the following errors the following ways:

If either a or b is not a valid season in the dictionary, you should return an error message (as a string) formatted exactly as:
"Error: Key is not in Dictionary."

If the values for the rainfall in each season are not valid for comparison, that is, one of them is not a number, return an error message (as a string) formatted exactly as:
"Error: Invalid data types in Dictionary?"

You may assume that no test case will produce both types of errors (so you do not need to decide whether or not to return a Key Error or Invalid Type error when you encounter both). However, you should not make any assumptions about the seasons that exist--sometimes there may be a 'potato' season.

I wrote a function that is mostly correct

```<code>def precipitation(d, a, b):

    try:
        if d[a] > d[b]:
            return True
        else:
            return False

    except:
        if a not in d or b not in d:
            return ("Error: Key is not in Dictionary.")

        if d[a] not in (int) or d[b] not in (int):
            return ("Error: Invalid data types in Dictionary?")
</code>```

When I run this function with test case

```<code>precipitation({"Spring": 'cats', "Summer": 313, "Fall": 1457, "Winter": 354}, "Summer", "Spring") == 'Error: Invalid data types in Dictionary?'
</code>```

I get an error
 argument of type 'type' is not iterable

How can I fix this and what is causing the problem

答:
use this as this is exact way of error handling

```<code>if ValueError:
    return ("Error: Invalid data types in Dictionary?")
</code>```

instead of

```<code>if if d[a] not in (int) or d[b] not in (int):
    return ("Error: Invalid data types in Dictionary?")
</code>```

Body:
I'm supposed to:

Write a function, precipiation(d, a, b) that takes parameters:

d: Dictionary mapping a season to an amount of precipitation for that season.
a: One season
b: Another season

Your function should return True if the rainfall in season a was greater than it was in season b, and False otherwise. If the rainfall was equal, return False.

Your function should handle the following errors the following ways:

If either a or b is not a valid season in the dictionary, you should return an error message (as a string) formatted exactly as:
"Error: Key is not in Dictionary."

If the values for the rainfall in each season are not valid for comparison, that is, one of them is not a number, return an error message (as a string) formatted exactly as:
"Error: Invalid data types in Dictionary?"

You may assume that no test case will produce both types of errors (so you do not need to decide whether or not to return a Key Error or Invalid Type error when you encounter both). However, you should not make any assumptions about the seasons that exist--sometimes there may be a 'potato' season.

I wrote a function that is mostly correct

def precipitation(d, a, b):

    try:
        if d[a] > d[b]:
            return True
        else:
            return False

    except:
        if a not in d or b not in d:
            return ("Error: Key is not in Dictionary.")

        if d[a] not in (int) or d[b] not in (int):
            return ("Error: Invalid data types in Dictionary?")

When I run this function with test case

precipitation({"Spring": 'cats', "Summer": 313, "Fall": 1457, "Winter": 354}, "Summer", "Spring") == 'Error: Invalid data types in Dictionary?'

I get an error
 argument of type 'type' is not iterable

How can I fix this and what is causing the problem

Body:
use this as this is exact way of error handling

if ValueError:
    return ("Error: Invalid data types in Dictionary?")

instead of

if if d[a] not in (int) or d[b] not in (int):
    return ("Error: Invalid data types in Dictionary?")


问:
How to stop NSTimer
Hey so i am just making an example application and i am having a little trouble, So i have a table view and then i have a few rows and when a user clicks a row it takes them to a new view. On this view i have a button to play music. I am using a timer to make a slider bar increase based on music duration and remaining time.

Now my problem is, what do i have to put so that when i go back to the table view via the top left button, that the NSTimer stops?

this is what i have so far, i cannot get a repeat: YES timer to stop.

```<code>#import "SecondViewController.h"

@implementation SecondViewController
@synthesize lbl1;
@synthesize timer;

-(IBAction) slide {
 myMusic.currentTime = slider.value;
}

-(IBAction)play
{
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
 slider.maximumValue = [myMusic duration];
 myMusic.volume = 0.2;
 [myMusic prepareToPlay];
 [myMusic play];
}

-(IBAction)pause
{
 [myMusic pause];
}

-(IBAction)stop
{
 slider.value = 0;
 myMusic.currentTime = 0;
 [myMusic stop];
}

- (void)updateTime{
  slider.value = myMusic.currentTime;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

  //This plays music, we must give it a path to find the file and then u can change it.
 NSString * pathToMusicFile = [[NSBundle mainBundle] pathForResource:@"Katy" ofType:@"mp3"];
     myMusic = [[ AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathToMusicFile] error:NULL];
     myMusic.delegate = self;
     myMusic.numberOfLoops = -1;

 slider.value = 0;
 //[myMusic play];

    [super viewDidLoad];
}

- (void)viewDidUnload {

 [timer invalidate];
 timer = nil;
 //myMusic.currentTime = 0;
 [myMusic stop];
 [super viewDidUnload];

 // Release any retained subviews of the main view.
 // e.g. self.myOutlet = nil;
}

-(IBAction) TxtChange;{

 lbl1.text = @" test2! I CHNAGED TEXT FROM ANOTHER XIB";
}

- (void)dealloc {
 [timer invalidate];
 timer = nil;
 [myMusic release];
    [super dealloc];
}

@end
</code>```

答:
As iCoder says it has to be invalidated in viewWillDisappear.

I added the following just to make sure. it works for me. Hope it helps (and adds to icoders answer do not intent to copy)

```<code>- (void) startTimer
{
[self stopTimer];
timer = [NSTimer scheduledTimerWithTimeInterval: 5.0
                                                     target: self
                                                   selector:@selector(onTick)
                                                   userInfo: nil repeats:YES];

}

- (void) stopTimer
{
    if (timer) {
        [timer invalidate];
        timer = nil;
    }

}
</code>```

Title: How to stop NSTimer

Body:
Hey so i am just making an example application and i am having a little trouble, So i have a table view and then i have a few rows and when a user clicks a row it takes them to a new view. On this view i have a button to play music. I am using a timer to make a slider bar increase based on music duration and remaining time.

Now my problem is, what do i have to put so that when i go back to the table view via the top left button, that the NSTimer stops?

this is what i have so far, i cannot get a repeat: YES timer to stop.

#import "SecondViewController.h"

@implementation SecondViewController
@synthesize lbl1;
@synthesize timer;

-(IBAction) slide {
 myMusic.currentTime = slider.value;
}

-(IBAction)play
{
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
 slider.maximumValue = [myMusic duration];
 myMusic.volume = 0.2;
 [myMusic prepareToPlay];
 [myMusic play];
}

-(IBAction)pause
{
 [myMusic pause];
}

-(IBAction)stop
{
 slider.value = 0;
 myMusic.currentTime = 0;
 [myMusic stop];
}

- (void)updateTime{
  slider.value = myMusic.currentTime;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

  //This plays music, we must give it a path to find the file and then u can change it.
 NSString * pathToMusicFile = [[NSBundle mainBundle] pathForResource:@"Katy" ofType:@"mp3"];
     myMusic = [[ AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathToMusicFile] error:NULL];
     myMusic.delegate = self;
     myMusic.numberOfLoops = -1;

 slider.value = 0;
 //[myMusic play];

    [super viewDidLoad];
}

- (void)viewDidUnload {

 [timer invalidate];
 timer = nil;
 //myMusic.currentTime = 0;
 [myMusic stop];
 [super viewDidUnload];

 // Release any retained subviews of the main view.
 // e.g. self.myOutlet = nil;
}

-(IBAction) TxtChange;{

 lbl1.text = @" test2! I CHNAGED TEXT FROM ANOTHER XIB";
}

- (void)dealloc {
 [timer invalidate];
 timer = nil;
 [myMusic release];
    [super dealloc];
}

@end

Body:
As iCoder says it has to be invalidated in viewWillDisappear.

I added the following just to make sure. it works for me. Hope it helps (and adds to icoders answer do not intent to copy)

- (void) startTimer
{
[self stopTimer];
timer = [NSTimer scheduledTimerWithTimeInterval: 5.0
                                                     target: self
                                                   selector:@selector(onTick)
                                                   userInfo: nil repeats:YES];

}

- (void) stopTimer
{
    if (timer) {
        [timer invalidate];
        timer = nil;
    }

}


问:
Powershell How to extract hashtable value from nested hashtable
I've made an API  request to the ManageEngine tech support database which returns a JSON response which  is returned as a custom object of three hash tables: $result.response_status, $result.list_info, and $result.requests The third of these contains the data I'm looking for.

$results.requests.id  an integer

$results.requests.subject a string

$results.requester a hashtable.

The requester hash table is @requester{name= 'Martin Zimmerman'; email='mzimmer@company.com'}

What I'd like to be able to do is:

```<code>$results.requests | select id, subject, requester.name
</code>```

to get a single line displaying the id, subject and requester's name

```<code>id   subject         name
--   --------------  --------------
3329 Can't open file Martin Zimmerman
</code>```

However, I cannot figure out the nomenclature to extract the value of the name key in the requester hash table.

答:
I think this is what you want. You need to build a Calculated Property (Example 10).

$results.requests | Select-Object id,subject,@{l='name';e={$_.requester['name']}}
```

<p>This approach allows you to call the name key from the hashtable.</p>

<h3>EDIT</h3>

<p>If your <code>requester</code> item is a PSCustomObject, then try this.</p>

<pre class="lang-bsh prettyprint-override"><code>$results.requests | Select-Object id,subject,@{l='name';e={$_.requester.name}}
</code>```

Test with similar object structure.

$results = New-Object psobject
$requests = New-Object psobject
$requests | Add-Member -MemberType NoteProperty -Name id -Value 2
$requests | Add-Member -MemberType NoteProperty -Name subject -Value "lol"
$hash = @{}
$hash.Add("email","mzimmerman@company.com")
$hash.Add("name","Martin Zimmerman")
$requests | Add-Member -MemberType NoteProperty -Name requester -Value $hash
$results | Add-Member -MemberType NoteProperty -Name requests -Value $requests
$results.requests | select id,subject,@{l='name';e={$_.requester['name']}}

id subject name
-- ------- ----
 2 lol     Martin Zimmerman
```

Body:
I've made an API  request to the ManageEngine tech support database which returns a JSON response which  is returned as a custom object of three hash tables: $result.response_status, $result.list_info, and $result.requests The third of these contains the data I'm looking for.

$results.requests.id  an integer

$results.requests.subject a string

$results.requester a hashtable.

The requester hash table is @requester{name= 'Martin Zimmerman'; email='mzimmer@company.com'}

What I'd like to be able to do is:

$results.requests | select id, subject, requester.name

to get a single line displaying the id, subject and requester's name

id   subject         name
--   --------------  --------------
3329 Can't open file Martin Zimmerman

However, I cannot figure out the nomenclature to extract the value of the name key in the requester hash table.

Body:
I think this is what you want. You need to build a Calculated Property (Example 10).

$results.requests | Select-Object id,subject,@{l='name';e={$_.requester['name']}}

This approach allows you to call the name key from the hashtable.

EDIT

If your requester item is a PSCustomObject, then try this.

$results.requests | Select-Object id,subject,@{l='name';e={$_.requester.name}}

Test with similar object structure.

$results = New-Object psobject
$requests = New-Object psobject
$requests | Add-Member -MemberType NoteProperty -Name id -Value 2
$requests | Add-Member -MemberType NoteProperty -Name subject -Value "lol"
$hash = @{}
$hash.Add("email","mzimmerman@company.com")
$hash.Add("name","Martin Zimmerman")
$requests | Add-Member -MemberType NoteProperty -Name requester -Value $hash
$results | Add-Member -MemberType NoteProperty -Name requests -Value $requests
$results.requests | select id,subject,@{l='name';e={$_.requester['name']}}

id subject name
-- ------- ----
 2 lol     Martin Zimmerman


问:
How to sort output from SQL statements combined with union
I have statements

```<code>SELECT a FROM X UNION
SELECT b FROM Y UNION
SELECT c FROM Z;
</code>```

I want the outbut to be orderd so that first come rows from a, then b and finaly c. I have tried to use GROUP BY and ORDER BY but I keep getting errors and fail to see the logic, how it should work.

答:
You can do:</p>

```<code>select a
from (
  SELECT a, 1 as display_order FROM X
  UNION ALL
  SELECT b, 2 FROM Y
  UNION ALL
  SELECT c, 3 FROM Z
) w
order by display_order
</code>```

Body:
I have statements

SELECT a FROM X UNION
SELECT b FROM Y UNION
SELECT c FROM Z;

I want the outbut to be orderd so that first come rows from a, then b and finaly c. I have tried to use GROUP BY and ORDER BY but I keep getting errors and fail to see the logic, how it should work.

Body:
You can do:

select a
from (
  SELECT a, 1 as display_order FROM X
  UNION ALL
  SELECT b, 2 FROM Y
  UNION ALL
  SELECT c, 3 FROM Z
) w
order by display_order


问:
Adding some content to a <text> tag through JS
Bit stuck on getting this to work.

Had issues with the backend changing a string from x to x*. Please take the Asterix literally.

I am trying to get around this by using 'contains()' JQuery to detect the text, and apply a class to it.

```<code><text fill="#FF8201" style="font-size: 13.2px;" x="0" y="327.58888888888885" fill-opacity="1">JIMMY</text>
</code>```

Javascript:

```<code> $(document).ready(function(){
 $("text:contains(JIMMY)").addClass('an');
 });
</code>```

CSS:

```<code>text.an::after {
content: '*';
}
</code>```

But it's not working. Not sure why...

答:
In one of the comments above, there is a JSFiddle that is linked. When viewing that, I see no problem, as the * is visible. The only thing I noticed was that you were using JQuery, so my only thought on this is if you haven't liked your JQuery or CSS properly. As you may know, you can link to JQuery by using a CDN:

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

Or you can download the JQuery files and attach it from a local file:

```<code><script src="/jquery/3.5.1/jquery.min.js"></script>
</code>```

Or it could be a problem in linking the CSS file (which contains the class styles):

```<code><link rel="stylesheet" href="/CSS/style.css" type="text/css" />
</code>```

Other than that, I have no idea.

Body:
Bit stuck on getting this to work.

Had issues with the backend changing a string from x to x*. Please take the Asterix literally.

I am trying to get around this by using 'contains()' JQuery to detect the text, and apply a class to it.

<text fill="#FF8201" style="font-size: 13.2px;" x="0" y="327.58888888888885" fill-opacity="1">JIMMY</text>

Javascript:

 $(document).ready(function(){
 $("text:contains(JIMMY)").addClass('an');
 });

CSS:

text.an::after {
content: '*';
}

But it's not working. Not sure why...

Body:
In one of the comments above, there is a JSFiddle that is linked. When viewing that, I see no problem, as the * is visible. The only thing I noticed was that you were using JQuery, so my only thought on this is if you haven't liked your JQuery or CSS properly. As you may know, you can link to JQuery by using a CDN:

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

Or you can download the JQuery files and attach it from a local file:

<script src="/jquery/3.5.1/jquery.min.js"></script>

Or it could be a problem in linking the CSS file (which contains the class styles):

<link rel="stylesheet" href="/CSS/style.css" type="text/css" />

Other than that, I have no idea.


问:
Nginx locations - case insensitive with spaces
My question is about nginx "location" configuration blocks:

If I want to make a location with a space character (well, %20) in the URL I can do it like so:

```<code>location ^~ "/Style Library/" {
}
</code>```

If I want to make a case-insensitive location, I can do it like so:

```<code>location ~* ^/StyleLibrary/ {
}
</code>```

However, I can't find a way of getting case-insensitive locations with space characters working.  None of these appear to work:

```<code>location ~* "^/Style Library/" {
}

location ~* ^/Style[^_]Library/ {
}

location ~* ^/Style\sLibrary/ {
}

location ~* ^/Style.Library/ {
}
</code>```

Can anyone help?

答:
Do you have other regex locations that may be handling the request earlier in the server block?  I just ran a test locally and was able to make the following location work:

```<code>location ~* "^/Style Library/" {
  rewrite ^ /dump.php;
}
</code>```

where /dump.php is just a simple script that does a var_export($_SERVER);

I tested this with

```<code>curl -i "dev/StYlE LiBrArY/"
</code>```

I'd guess that some other location is handling the request instead of that regex location.

Body:
My question is about nginx "location" configuration blocks:

If I want to make a location with a space character (well, %20) in the URL I can do it like so:

location ^~ "/Style Library/" {
}

If I want to make a case-insensitive location, I can do it like so:

location ~* ^/StyleLibrary/ {
}

However, I can't find a way of getting case-insensitive locations with space characters working.  None of these appear to work:

location ~* "^/Style Library/" {
}

location ~* ^/Style[^_]Library/ {
}

location ~* ^/Style\sLibrary/ {
}

location ~* ^/Style.Library/ {
}

Can anyone help?

Body:
Do you have other regex locations that may be handling the request earlier in the server block?  I just ran a test locally and was able to make the following location work:

location ~* "^/Style Library/" {
  rewrite ^ /dump.php;
}

where /dump.php is just a simple script that does a var_export($_SERVER);

I tested this with

curl -i "dev/StYlE LiBrArY/"

I'd guess that some other location is handling the request instead of that regex location.


问:
Adding Missing Dates in MongoDB Aggregation
In this problem, I want to get the user subscription for the following time range

Today

This Week

This Month

This Year

For this time range, i want to display the $group of all possible dates.

```<code>[
  { Dates: '2020-05-21', Count: 3, AverageIncome: 30 },
  { Dates: '2020-05-22', Count: 10, AverageIncome: 30 },
  { Dates: '2020-05-24', Count: 1, AverageIncome: 37 },
  { Dates: '2020-05-25', Count: 1, AverageIncome: 30 },
  { Dates: '2020-05-26', Count: 2, AverageIncome: 65 }
]
</code>```

I want to add the missing dates as well with accumulator data set to 0. For example, it should be

```<code>[
  { Dates: '2020-05-21', Count: 3, AverageIncome: 30 },
  { Dates: '2020-05-22', Count: 10, AverageIncome: 30 },
  { Dates: '2020-05-23', Count: 0, AverageIncome: 0 },
  { Dates: '2020-05-24', Count: 1, AverageIncome: 37 },
  { Dates: '2020-05-25', Count: 1, AverageIncome: 30 },
  { Dates: '2020-05-26', Count: 2, AverageIncome: 65 },
  { Dates: '2020-05-27', Count: 0, AverageIncome: 0 },
  { Dates: '2020-05-28', Count: 2, AverageIncome: 0 },
]
</code>```

PS: At this time the UTC time would be 28th may 11:45 pm

The aggregation pipeline stages i am using

const $agg = await Subscription.aggregate([
    {
      $match: {
        createdOn: {
          $gte: moment(req.query.from).toDate(),
          $lte: moment(req.query.to).toDate()
        },
        isCancelled: false
      }
    },

    {
      $group: {
        _id: {
          $dateToString: {
            format: "%Y-%m-%d",
            date: "$createdOn"
          }
        },
        count: { $sum: 1 },
        avgAmount: { $avg: "$amountPaid" }
      }
    },
    {
      $project: {
        _id: false,
        sortKey: {
          $dateFromString: {
            dateString: "$_id"
          }
        },
        Dates: "$_id",
        Count: "$count",
        AverageIncome: "$avgAmount"
      }
    },
    {
      $sort: {
        sortKey: 1
      }
    },
    {
      $project: {
        sortKey: false
      }
    }
  ]);
```

答:
I had faced the similar issue some time back, and here is the approach that I followed:</p>

```<code>function fillEmptyDates($agg, $defaultData, from, to) {
  const $aggObj = {}; //Taking this as an object for easy checking

  $agg.map((agg) => {
    $aggObj[agg.Date] = agg; //Making an object from array entries with Date as key
  });

  const $loopDate = moment(from);
  const $endDate = moment(to);

  //Starting from from date to to date, checking if any date does not have entry in $aggObje
  while ($endDate.isSameOrAfter($loopDate)) {
    let $aggDate = $loopDate.format("YYYY-MM-DD");

    if (!$aggObj.hasOwnProperty($aggDate)) {
      //If any date does not have entry, creating a new entry from default aggregates and giving it the date as current date
      $aggObj[$aggDate] = {
        ...$defaultData,
        Date: $aggDate
      };
    }
    $loopDate.add(1, "day"); //Incrementing aggregate date
  }

  //Converting back to array and sorting by date
  return Object.values($aggObj).sort((a, b) =>
    moment(a.Date).isBefore(moment(b.Date)) ? -1 : 1
  );
};

//You can call this function like so
$agg = fillEmptyDates(
            $agg,
            { Count: 0, AverageIncome: 0 },
            req.query.from,
            req.query.to,
        )
</code>```

Body:
In this problem, I want to get the user subscription for the following time range

Today

This Week

This Month

This Year

For this time range, i want to display the $group of all possible dates.

[
  { Dates: '2020-05-21', Count: 3, AverageIncome: 30 },
  { Dates: '2020-05-22', Count: 10, AverageIncome: 30 },
  { Dates: '2020-05-24', Count: 1, AverageIncome: 37 },
  { Dates: '2020-05-25', Count: 1, AverageIncome: 30 },
  { Dates: '2020-05-26', Count: 2, AverageIncome: 65 }
]

I want to add the missing dates as well with accumulator data set to 0. For example, it should be

[
  { Dates: '2020-05-21', Count: 3, AverageIncome: 30 },
  { Dates: '2020-05-22', Count: 10, AverageIncome: 30 },
  { Dates: '2020-05-23', Count: 0, AverageIncome: 0 },
  { Dates: '2020-05-24', Count: 1, AverageIncome: 37 },
  { Dates: '2020-05-25', Count: 1, AverageIncome: 30 },
  { Dates: '2020-05-26', Count: 2, AverageIncome: 65 },
  { Dates: '2020-05-27', Count: 0, AverageIncome: 0 },
  { Dates: '2020-05-28', Count: 2, AverageIncome: 0 },
]

PS: At this time the UTC time would be 28th may 11:45 pm

The aggregation pipeline stages i am using

const $agg = await Subscription.aggregate([
    {
      $match: {
        createdOn: {
          $gte: moment(req.query.from).toDate(),
          $lte: moment(req.query.to).toDate()
        },
        isCancelled: false
      }
    },

    {
      $group: {
        _id: {
          $dateToString: {
            format: "%Y-%m-%d",
            date: "$createdOn"
          }
        },
        count: { $sum: 1 },
        avgAmount: { $avg: "$amountPaid" }
      }
    },
    {
      $project: {
        _id: false,
        sortKey: {
          $dateFromString: {
            dateString: "$_id"
          }
        },
        Dates: "$_id",
        Count: "$count",
        AverageIncome: "$avgAmount"
      }
    },
    {
      $sort: {
        sortKey: 1
      }
    },
    {
      $project: {
        sortKey: false
      }
    }
  ]);

Body:
I had faced the similar issue some time back, and here is the approach that I followed:

function fillEmptyDates($agg, $defaultData, from, to) {
  const $aggObj = {}; //Taking this as an object for easy checking

  $agg.map((agg) => {
    $aggObj[agg.Date] = agg; //Making an object from array entries with Date as key
  });

  const $loopDate = moment(from);
  const $endDate = moment(to);

  //Starting from from date to to date, checking if any date does not have entry in $aggObje
  while ($endDate.isSameOrAfter($loopDate)) {
    let $aggDate = $loopDate.format("YYYY-MM-DD");

    if (!$aggObj.hasOwnProperty($aggDate)) {
      //If any date does not have entry, creating a new entry from default aggregates and giving it the date as current date
      $aggObj[$aggDate] = {
        ...$defaultData,
        Date: $aggDate
      };
    }
    $loopDate.add(1, "day"); //Incrementing aggregate date
  }

  //Converting back to array and sorting by date
  return Object.values($aggObj).sort((a, b) =>
    moment(a.Date).isBefore(moment(b.Date)) ? -1 : 1
  );
};

//You can call this function like so
$agg = fillEmptyDates(
            $agg,
            { Count: 0, AverageIncome: 0 },
            req.query.from,
            req.query.to,
        )


问:
MySQL - get multiple rows in subquery
I have 2 tables:
 1. feeds
 2. photo_url

feed_id  description       photo_id  feed_id  url
  1         one               1         1       a
  2         two               2         1       b
  3         three             3         3       c
                              4         3       d
                              5         3       e

Each Feed can have multiple photos (as above)

I am trying to query feeds along with list of corresponding urls

```<code>SELECT f.feed_id, f.description,
(SELECT p.url as url FROM photo_url p WHERE p.feed_id = f.feed_id) as photo_url
FROM feed f
where f.feed_id = 1;
</code>```

Currently I am getting this error:
Error Code: 1241. Operand should contain 1 column(s)

Actually I am expecting an output as:

```<code>[ {
    "feed_id": 1,
    "description": "one",
    "photo_url":[{
             "url":"a"
            },
            {
             "url":"b"
            }]
   }]
</code>```

I tried with JOIN (LEFT, LEFT OUTER, INNER) but not getting desired results.
Is there any way to get result using nested query or should I loop a separate query for every row?

答:
You need to use GROUP_CONCAT:

```<code>SELECT f.feed_id, f.description, GROUP_CONCAT(p.url) as photo_url
FROM feed f
INNER JOIN photo_url as p ON p.feed_id = f.feed_id
WHERE f.feed_id = 1
GROUP BY f.feed_id;
</code>```

Or, without the WHERE f.feed_id = 1:

```<code>SELECT f.feed_id, f.description, GROUP_CONCAT(p.url) as photo_url
FROM feed f
INNER JOIN photo_url as p ON p.feed_id = f.feed_id
GROUP BY f.feed_id;
</code>```

Result is:

```<code>feed_id description photo_url
  1        one         a,b
  3       three        c,d,e
</code>```

Check this SQLfiddle

Title: MySQL - get multiple rows in subquery

Body:
I have 2 tables:
 1. feeds
 2. photo_url

feed_id  description       photo_id  feed_id  url
  1         one               1         1       a
  2         two               2         1       b
  3         three             3         3       c
                              4         3       d
                              5         3       e

Each Feed can have multiple photos (as above)

I am trying to query feeds along with list of corresponding urls

SELECT f.feed_id, f.description,
(SELECT p.url as url FROM photo_url p WHERE p.feed_id = f.feed_id) as photo_url
FROM feed f
where f.feed_id = 1;

Currently I am getting this error:
Error Code: 1241. Operand should contain 1 column(s)

Actually I am expecting an output as:

[ {
    "feed_id": 1,
    "description": "one",
    "photo_url":[{
             "url":"a"
            },
            {
             "url":"b"
            }]
   }]

I tried with JOIN (LEFT, LEFT OUTER, INNER) but not getting desired results.
Is there any way to get result using nested query or should I loop a separate query for every row?

Body:
You need to use GROUP_CONCAT:

SELECT f.feed_id, f.description, GROUP_CONCAT(p.url) as photo_url
FROM feed f
INNER JOIN photo_url as p ON p.feed_id = f.feed_id
WHERE f.feed_id = 1
GROUP BY f.feed_id;

Or, without the WHERE f.feed_id = 1:

SELECT f.feed_id, f.description, GROUP_CONCAT(p.url) as photo_url
FROM feed f
INNER JOIN photo_url as p ON p.feed_id = f.feed_id
GROUP BY f.feed_id;

Result is:

feed_id description photo_url
  1        one         a,b
  3       three        c,d,e

Check this SQLfiddle


答:
In addition to the correct answers already provided,

since you are using try and except, you can also specify the type of exception for each block as well:

def precipitation(d, a, b):
    try:
        return d[a] > d[b]
    except KeyError:
        return "Error: Key is not in Dictionary."
    except TypeError:
        return "Error: Invalid data types in Dictionary?"
```

Title: Why am I getting an error when trying to compare to dictionary values?


问:
Can I define synonyms for verbs in Luis bot framework?
In our company, we are building a chatbot using Microsoft Luis Bot Framework. For two of the intent's, I don't know how I should annotate the examples.

I have a product called ABC and I need two different intent's: Access ABC and Use ABC. That is, for each of these two intents, we have different answers.

Now, my questions is how can I define synonyms for verbs. Should I define verbs as entities?
Our utterances for the intent Access ABC would be like:

1) How can I access ABC?

2) How can I reach ABC?

Our utterance's for the intent Use ABC would be like:

3) How can I use ABC?

4) Is there any introduction to ABC?

5) I am new to ABC. Is there any usage guideline?

The problem that I see is that if I don't tag the verbs for the first intent, how can the system distinguish between 1 (or 2) and 4?

答:
This is a big problem. In your utterences 1 and 2 for example, all you are teaching a model is that the verb access all the verb reach have no importance. this is because you are telling the models look at those two sentences both works regardless of what is a verb. This mean it will create quite a lot of confusions with your sentence number three. Training this model is still very empirical. We use QBox (disclaimer, I work for them). Having a couple of verbs uterences for each use case might work but you are going to have to try it. But be careful at your training examples. Try to vary as much as you can the word that play less importance.
1- how can I access ABC
2- tell me how to reach ABC
3- I can't access ABC
4- I'm struggling to reach ABC

remember that you will need 10 to 15 examples minimum in order to reach a good level of performance. This depends of the number of intents you have in your model of course