问:
get_included_files() for defined path
I am trying to get the names/path of the files that are included in a files with a given path . But the get_included_files() function works only for the files in which it is written.

```<code><?
    include_once('/folder1/folder2/xyz.php');
    $path = '/abcd.php';
    $includeFiles = get_included_files();
?>
</code>```

I have tried the above code and i am getting only the included files in this file only.
I want to get the name of the included files in abcd.php i.e for the defined path.

Please HELP !!

答:
How about something like this?</p>

```<code>array_filter(get_included_files(), function($item) {
    return strpos($item, '/path/to/files/') === 0;
});
</code>```

Title: get_included_files() for defined path

Body:
I am trying to get the names/path of the files that are included in a files with a given path . But the get_included_files() function works only for the files in which it is written.

<?
    include_once('/folder1/folder2/xyz.php');
    $path = '/abcd.php';
    $includeFiles = get_included_files();
?>

I have tried the above code and i am getting only the included files in this file only.
I want to get the name of the included files in abcd.php i.e for the defined path.

Please HELP !!

Body:
How about something like this?

array_filter(get_included_files(), function($item) {
    return strpos($item, '/path/to/files/') === 0;
});


来源: stackexchange

问:
how to search for a specific file in blob storage
I am kind of new to Blob storage and i need to access a specific file from blob storage.
i.e when i type in a specific folder it should list out all the blobs underneath it.

Can anyone help me with that

here's the code which i am trying to do.

```<code>if (AccountFileTransfer != null)
{
    BlobClientFileTransfer = AccountFileTransfer.CreateCloudBlobClient();
    ContainerFileTransfer = BlobClientFileTransfer.GetContainerReference(CONTAINER);

    CloudBlob blob = ContainerFileTransfer.GetBlobReference(txtFileSearch.Text);
    if (blob.Uri == null)
    {
        System.Windows.Forms.MessageBox.Show("Not a Valid blob search");
    }
    else
    {
        lvFileTransfer.Items.Add(blob.Uri);
    }
}
</code>```

答: Use Azure Search to index and search for files in Blob storage

ContentLicense: CC BY-SA 3.0

Body:
I am kind of new to Blob storage and i need to access a specific file from blob storage.
i.e when i type in a specific folder it should list out all the blobs underneath it.

Can anyone help me with that

here's the code which i am trying to do.

if (AccountFileTransfer != null)
{
    BlobClientFileTransfer = AccountFileTransfer.CreateCloudBlobClient();
    ContainerFileTransfer = BlobClientFileTransfer.GetContainerReference(CONTAINER);

    CloudBlob blob = ContainerFileTransfer.GetBlobReference(txtFileSearch.Text);
    if (blob.Uri == null)
    {
        System.Windows.Forms.MessageBox.Show("Not a Valid blob search");
    }
    else
    {
        lvFileTransfer.Items.Add(blob.Uri);
    }
}


问:
What Perl module to use?
How do I choose between two (or more) Perl modules, when each of them has the method(s) I need?</p>

答:
I'd check

if the API supports my use case.

If both APIs do, choose the module that is easier to work with.

If both APIs are equally easy to work with, choose the one with better documentation/support.

If both are equally well documented/supported, choose the that has less dependencies.

If both have the same amount of dependencies, take the smaller one.

If both are about equal, choose the one with more releases / more active development / more passes in the test matrix (courtesy of Eric Strom)

If both still are equal, roll a dice.

Your preferences may vary so you might want to reorder the list, depending on your preferences.

ContentLicense: CC BY-SA 2.5

Title: What Perl module to use?


问:
How to print or save the output values of each layer of neural network in Theano?
I need to examine the output values of each layer of the network in theano-python.

I suppose : net.layers[i].output should do the job.

However, it seems  net.layers[i].output is theano.tensor type.  How to print it or save it in some file format can be read by human ?

Thanks.

答:
You can use

```<code>net.layers[i].output.get_values()
</code>```

to convert the tensor values into the Numpy array.

And subsequently, you use the following to store those values:

```<code>numpy.savetxt
</code>```

Body:
You can use

net.layers[i].output.get_values()

to convert the tensor values into the Numpy array.

And subsequently, you use the following to store those values:

numpy.savetxt


问:
CAS username field value to be manually added to the existing user on import?
I installed the CAS module on a Drupal 8 site, and it is working fine. For new users, it auto-registers the user with cas_username, but I would like to import the cas_username manually for the existing Drupal 8 user.

I also tried importing users in CSV format(https://github.com/steveoliver/user_import); I have been able to add the $account(row[0],row[1]), but for the CAS username import, i don't know how to import it, and in which field is stored.

```<code>  'uid' => NULL,
  'name' => $username,
  'field_first_name' => row[0],
  'field_last_name' => $row[1],
  'pass' => $username,
  'mail' => $row[2],
  'status' => 1,
  'created' => REQUEST_TIME,
  'roles' => array_values($config['roles']),
</code>```

I tried Managing CAS username; the suggestion given is for Drupal 7, but the same method doesn't work for Drupal 8.

Kindly suggest me solution import the cas username in CSV.

答:
I find out the solution for the CAS_username import in CSV method. The method of db_insert in (authmap) table, which dynamically insert the CAS_username in respective field.

The authmap table is present in external authentication module.

```<code>db_insert('authmap')
->fields(array(
 'uid' => $uid,
 'provider' => 'cas',
 'authname' => $row[0],
 'data' => 'N;',
 ))
->execute();
</code>```

So this is the method, i dynamically update the CAS_username using CSV. If any suggestions or update in that. Kindly Prescribe it.

Body:
I installed the CAS module on a Drupal 8 site, and it is working fine. For new users, it auto-registers the user with cas_username, but I would like to import the cas_username manually for the existing Drupal 8 user.

I also tried importing users in CSV format(https://github.com/steveoliver/user_import); I have been able to add the $account(row[0],row[1]), but for the CAS username import, i don't know how to import it, and in which field is stored.

  'uid' => NULL,
  'name' => $username,
  'field_first_name' => row[0],
  'field_last_name' => $row[1],
  'pass' => $username,
  'mail' => $row[2],
  'status' => 1,
  'created' => REQUEST_TIME,
  'roles' => array_values($config['roles']),

I tried Managing CAS username; the suggestion given is for Drupal 7, but the same method doesn't work for Drupal 8.

Kindly suggest me solution import the cas username in CSV.

Body:
I find out the solution for the CAS_username import in CSV method. The method of db_insert in (authmap) table, which dynamically insert the CAS_username in respective field.

The authmap table is present in external authentication module.

db_insert('authmap')
->fields(array(
 'uid' => $uid,
 'provider' => 'cas',
 'authname' => $row[0],
 'data' => 'N;',
 ))
->execute();

So this is the method, i dynamically update the CAS_username using CSV. If any suggestions or update in that. Kindly Prescribe it.


问:
Perl: How to pass array element by reference to sub
I'm coming to Perl from a C/C++ background and am progressing very slowly, so please bear with me...

I've got an array of hashes and I want to pass one element of the array to a sub-routine (by reference) where that element will be modified.

```<code>use strict;
use warnings;

use Data::Dumper;

my @array;
my %hash;

$hash{'key1'} = 1;
$hash{'key2'} = 2;
$hash{'key3'} = 3;
$hash{'key4'} = 4;
push @array, {%hash};

$hash{'key1'} = 10;
$hash{'key2'} = 20;
$hash{'key3'} = 30;
$hash{'key4'} = 40;
push @array, {%hash};

# Expect:
#   @array[0] like 1,2,3,4
#   @array[1] like 10,20,30,40
print Dumper(@array);

doChange(\@array[1]); # <<==== THIS IS THE BIT WHERE I NEED ASSISTANCE TO PASS ARRAY ELEMENT BY REFERENCE, IF POSSIBLE

# Expect:
#   @array[0] like 1,2,3,4
#   @array[1] like 100,200,300,400 <<== VALUES HAVE CHANGED
print Dumper(@array);

sub doChange
{
    my %h = @_; # <<===  THIS IS NOT RIGHT EITHER!?

    $h{'key1'} = 100;
    $h{'key2'} = 200;
    $h{'key3'} = 300;
    $h{'key4'} = 400;
}
</code>```

答:
Well that was fun.</p>

```<code>use strict;
use warnings;

use Data::Dumper;

my @array;
my $hash;

$hash = {}; # initialise to a blank hash.
$hash->{'key1'} = 1;
$hash->{'key2'} = 2;
$hash->{'key3'} = 3;
$hash->{'key4'} = 4;
push @array, $hash;

$hash = {};  # initialise to a blank hash.
$hash->{'key1'} = 10;
$hash->{'key2'} = 20;
$hash->{'key3'} = 30;
$hash->{'key4'} = 40;
push @array, $hash;

# Expect:
#   @array[0] like 1,2,3,4
#   @array[1] like 10,20,30,40
print Dumper(\@array);   # Dumper takes a reference.

doChange($array[1]); # pass a pointer (reference) to the hash.

# Expect:
#   @array[0] like 1,2,3,4
#   @array[1] like 100,200,300,400 <<== VALUES HAVE CHANGED
print Dumper(\@array);

sub doChange
{
    my $h = shift; # Get the pointer to your hash.

    $h->{'key1'} = 100;  # mess with it.
    $h->{'key2'} = 200;
    $h->{'key3'} = 300;
    $h->{'key4'} = 400;
}
</code>```

Body:
I'm coming to Perl from a C/C++ background and am progressing very slowly, so please bear with me...

I've got an array of hashes and I want to pass one element of the array to a sub-routine (by reference) where that element will be modified.

use strict;
use warnings;

use Data::Dumper;

my @array;
my %hash;

$hash{'key1'} = 1;
$hash{'key2'} = 2;
$hash{'key3'} = 3;
$hash{'key4'} = 4;
push @array, {%hash};

$hash{'key1'} = 10;
$hash{'key2'} = 20;
$hash{'key3'} = 30;
$hash{'key4'} = 40;
push @array, {%hash};

# Expect:
#   @array[0] like 1,2,3,4
#   @array[1] like 10,20,30,40
print Dumper(@array);

doChange(\@array[1]); # <<==== THIS IS THE BIT WHERE I NEED ASSISTANCE TO PASS ARRAY ELEMENT BY REFERENCE, IF POSSIBLE

# Expect:
#   @array[0] like 1,2,3,4
#   @array[1] like 100,200,300,400 <<== VALUES HAVE CHANGED
print Dumper(@array);

sub doChange
{
    my %h = @_; # <<===  THIS IS NOT RIGHT EITHER!?

    $h{'key1'} = 100;
    $h{'key2'} = 200;
    $h{'key3'} = 300;
    $h{'key4'} = 400;
}

Body:
Well that was fun.

use strict;
use warnings;

use Data::Dumper;

my @array;
my $hash;

$hash = {}; # initialise to a blank hash.
$hash->{'key1'} = 1;
$hash->{'key2'} = 2;
$hash->{'key3'} = 3;
$hash->{'key4'} = 4;
push @array, $hash;

$hash = {};  # initialise to a blank hash.
$hash->{'key1'} = 10;
$hash->{'key2'} = 20;
$hash->{'key3'} = 30;
$hash->{'key4'} = 40;
push @array, $hash;

# Expect:
#   @array[0] like 1,2,3,4
#   @array[1] like 10,20,30,40
print Dumper(\@array);   # Dumper takes a reference.

doChange($array[1]); # pass a pointer (reference) to the hash.

# Expect:
#   @array[0] like 1,2,3,4
#   @array[1] like 100,200,300,400 <<== VALUES HAVE CHANGED
print Dumper(\@array);

sub doChange
{
    my $h = shift; # Get the pointer to your hash.

    $h->{'key1'} = 100;  # mess with it.
    $h->{'key2'} = 200;
    $h->{'key3'} = 300;
    $h->{'key4'} = 400;
}


问:
Unable to import 'Rx' to my Angular 2 application
I am pretty new at Angular2. I am trying to learn it using a dummy app.

I have recently gone through a tutorial on RxJS and got a basic hold on Observables (or atleast I assume so). Based on that, I have an idea of returning a list of users from my array in service as a stream. I intent to use interval for it and display a kind  of lazy loading effect on screen.

My intention is something like:

```<code>getUsers() {
        return Rx.Observable.from(this.users); //want to add interval too on this
    }
</code>```

However, I am stuck at importing 'Rx' in to my service. Using 'Rx' without import obviously gives me error. The rest imports for Observables and operator works fine.

I went to node_modules and found there is a rx and a rxjs module too. But somehow using any of these below commands, I can't get rid of my error on Rx.

```<code>import 'rxjs/Rx';
import  Rx from 'rxjs/Rx';
import { Rx} from 'rx/Rx';
import { Rx} from 'rx';
</code>```

I went through few links on SO those say Rx is no longer bundled with Angular. However, I am working with the latest angular official seed and I do see rx and rxjs packages. I have a 5.0.1 version mentioned in package.json. Am I assuming something wrong here ??

Please let me know How does one work with creating custom observables using Rx in Angular 2.

Note: I have no issues working Observable return by Http service, just want to create a Observable from scratch using Array

答:
The rxjs should be already as a dependency in your project. You can read how to properly import RxJS on its official readme page: https://github.com/ReactiveX/rxjs/#installation-and-usage

Most easily just use:

```<code>import {Observable} from 'rxjs';
</code>```

Note that this is different to using just import {Rx} from 'rxjs'; because this would look for an exported property called Rx in the rxjs/Rx.d.ts but no such property exists.

The rx package is the old RxJS 4 so you definitely don't want to use it with Angualr2.

Body:
I am pretty new at Angular2. I am trying to learn it using a dummy app.

I have recently gone through a tutorial on RxJS and got a basic hold on Observables (or atleast I assume so). Based on that, I have an idea of returning a list of users from my array in service as a stream. I intent to use interval for it and display a kind  of lazy loading effect on screen.

My intention is something like:

getUsers() {
        return Rx.Observable.from(this.users); //want to add interval too on this
    }

However, I am stuck at importing 'Rx' in to my service. Using 'Rx' without import obviously gives me error. The rest imports for Observables and operator works fine.

I went to node_modules and found there is a rx and a rxjs module too. But somehow using any of these below commands, I can't get rid of my error on Rx.

import 'rxjs/Rx';
import  Rx from 'rxjs/Rx';
import { Rx} from 'rx/Rx';
import { Rx} from 'rx';

I went through few links on SO those say Rx is no longer bundled with Angular. However, I am working with the latest angular official seed and I do see rx and rxjs packages. I have a 5.0.1 version mentioned in package.json. Am I assuming something wrong here ??

Please let me know How does one work with creating custom observables using Rx in Angular 2.

Note: I have no issues working Observable return by Http service, just want to create a Observable from scratch using Array

Body:
The rxjs should be already as a dependency in your project. You can read how to properly import RxJS on its official readme page: https://github.com/ReactiveX/rxjs/#installation-and-usage

Most easily just use:

import {Observable} from 'rxjs';

Note that this is different to using just import {Rx} from 'rxjs'; because this would look for an exported property called Rx in the rxjs/Rx.d.ts but no such property exists.

The rx package is the old RxJS 4 so you definitely don't want to use it with Angualr2.


问:
trimmingCharacters not work on iOS 10.3 Xcode8.3
Please help me, I use Xcode 8.3(swift 3.1), the function trimmingCharacters not work. My code as below:

```<code>    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if var searchStr = textField.text{
       let _searchStr = searchStr.trimmingCharacters(in: .whitespaces)
       print("After trimming:\(_searchStr)")
   }
}
</code>```

The input in textfield is 409 huỳnh and the print result is 409 huỳnh not as expected: 409huỳnh .

答:
You can use

```<code>let trimmedString = searchStr.stringByReplacingOccurrencesOfString(" ", withString: "")
</code>```

Hope this helps you !

Body:
Please help me, I use Xcode 8.3(swift 3.1), the function trimmingCharacters not work. My code as below:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if var searchStr = textField.text{
       let _searchStr = searchStr.trimmingCharacters(in: .whitespaces)
       print("After trimming:\(_searchStr)")
   }
}

The input in textfield is 409 huỳnh and the print result is 409 huỳnh not as expected: 409huỳnh .

Body:
You can use

let trimmedString = searchStr.stringByReplacingOccurrencesOfString(" ", withString: "")

Hope this helps you !


问:
PostgreSQL 9.6 won't connect on Ubuntu 16
I installed PostgreSQL 9.6 on my Ubuntu 16.04 system.  It seems like it's up and running, but when I try to make a connection it just fails.  When I run the status command I see that it's always saying exited for some reason.  I see lots of things in a google search but none seem to be helping.

I changed the first entry in the pg_hba.conf to be local all postgres trust

% ps augxw | grep postg

  postgres   769  0.0  0.3 303964 24384 ?        S    22:13   0:00 /usr/lib/postgresql/9.6/bin/postgres -D /var/lib/postgresql/9.6/main -c   config_file=/etc/postgresql/9.6/main/postgresql.conf

  postgres   772  0.0  0.0 303964  3956 ?        Ss   22:13   0:00 postgres: 9.6/main: checkpointer process

  postgres   773  0.0  0.0 303964  3956 ?        Ss   22:13   0:00 postgres: 9.6/main: writer process

  postgres   774  0.0  0.0 303964  3956 ?        Ss   22:13   0:00 postgres: 9.6/main: wal writer process

  postgres   775  0.0  0.0 304408  6572 ?        Ss   22:13   0:00 postgres: 9.6/main: autovacuum launcher process

  postgres   776  0.0  0.0 158964  3204 ?        Ss   22:13   0:00 postgres: 9.6/main: stats collector process

  ubuntu    1492  0.0  0.0  12944   936 pts/0    S+   22:14   0:00 grep postg

  %

  % sudo su - postgres

  $ psql -h localhost

  psql: could not connect to server: Connection refused

        Is the server running on host "localhost" (127.0.0.1) and accepting

        TCP/IP connections on port 5432?

  $ exit

  logout

  % systemctl status postgresql

  ● postgresql.service - PostgreSQL RDBMS

     Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)

     Active: active (exited) since Thu 2017-03-30 22:13:57 PDT; 1min 19s ago

    Process: 901 ExecStart=/bin/true (code=exited, status=0/SUCCESS)

   Main PID: 901 (code=exited, status=0/SUCCESS)

      Tasks: 0

     Memory: 0B

        CPU: 0

     CGroup: /system.slice/postgresql.service

Mar 30 22:13:57 ip-172-31-9-223 systemd[1]: Starting PostgreSQL RDBMS...

  Mar 30 22:13:57 ip-172-31-9-223 systemd[1]: Started PostgreSQL RDBMS.

答:
You are connecting using TCP/IP socket, but local refers to unix-domain socket.

The first field is the connection type: "local" is a Unix-domain socket, "host" is either a plain or SSL-encrypted TCP/IP socket, "hostssl" is an SSL-encrypted TCP/IP socket, and "hostnossl" is a plain TCP/IP socket.

I did install postgresql-9.6 from that repo and:

host   all             postgres         127.0.0.1/32            trust does what you want to do

postgres@lkaminski-ubuntu-desk:~$ psql works out of the box, no need to change config. It is using unix-domain socket that is already trusted. So you can just drop -h localhost and no need to edit configs.

$ sudo grep -e "^[^#]" /etc/postgresql/9.6/main/pg_hba.conf

```<code>local   all             postgres                                peer
host   all             postgres         127.0.0.1/32            trust
local   all             all                                     peer
host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5
</code>```

Body:
You are connecting using TCP/IP socket, but local refers to unix-domain socket.

The first field is the connection type: "local" is a Unix-domain socket, "host" is either a plain or SSL-encrypted TCP/IP socket, "hostssl" is an SSL-encrypted TCP/IP socket, and "hostnossl" is a plain TCP/IP socket.

I did install postgresql-9.6 from that repo and:

host   all             postgres         127.0.0.1/32            trust does what you want to do

postgres@lkaminski-ubuntu-desk:~$ psql works out of the box, no need to change config. It is using unix-domain socket that is already trusted. So you can just drop -h localhost and no need to edit configs.

$ sudo grep -e "^[^#]" /etc/postgresql/9.6/main/pg_hba.conf

local   all             postgres                                peer
host   all             postgres         127.0.0.1/32            trust
local   all             all                                     peer
host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5


问:
linq search for French characters
I'm usint EF and have a simple LINQ statement and want to search for words.
So there is Textbox search and submit button.

when searchtext contains "march" it finds eg. "des marchés", but If I search for "marché" it doesn't find. So it's the French character.

```<code>listAgendaItems = dc.agenda.Where(a =>
                        a.libelle_activite.Contains(searchText)
).ToList<agenda>();
</code>```

The database and the table Agenda have extended properties -> Collation  : French_CI_AS

So how can I makes sure I get the French words, too? like "é,  à"  etc

I also tried to search for "marche" but it doesn't find "marchés".

答:
Your collation French_CI_AS is "Case-Insensitive", "Accent-Sensitive". If you want a query for "marches" to match "marchés", you need French_CI_AI as your collation. In most languages, that's actually NOT what native speakers want, because the accents are semantically important, but that may depend on the circumstances or context.

If, in fact, your users do always want accent insensitive searches, you should set that collation property to AI instead of AS on the table (or the specific fields). Otherwise, if the need is rare, you can apply collation to a table in MS Sql on a per-query basis; keep in mind that if there is no index on that collation there may be a substantial performance cost. That may be nearly immaterial when you're doing a %wildcard% query, however, since you'll generally have a full table scan in that case anyway.

The last I checked, it wasn't possible to specify a collation in a Linq query directly, so if you are doing case insensitivity on an ad-hoc basis, you'd need to use direct-to-sql query through your data context.

Edited:
Based on your comment, it sounds like you are allowing HTML content to be stored in your database. You have numeric character references in your table, which SQL Server knows nothing about, since they're a feature of HTML, XML and SGML. You can only make this searchable if those characters are string literals in a suitable encoding.

NVARCHAR will store the content in Unicode, specifically UTF-16, and VARCHAR will use Windows-1252 with French collation.

If you are accepting this input via web forms, make sure the page encoding is appropriate. If you are only supporting modern browsers (essentially anything IE5+), UTF-8 is well supported, so you should consider using UTF-8 for all of your requests and responses.

Make sure in your web.config, you have something like this:

```<code><configuration>
   <system.web>
      <globalization
         requestEncoding="utf-8"
         responseEncoding="utf-8" />
   </system.web>
</configuration>
</code>```

If you already have data stored with those numeric character references in your database, you can unescape them by translating &#ddddd; into literal UTF-16 sequences, and store them again. Make sure you don't accidentally unescape semantically important NCRs like the greater-than, less-than or ampersand codepoints.

Title: linq search for French characters

Body:
I'm usint EF and have a simple LINQ statement and want to search for words.
So there is Textbox search and submit button.

when searchtext contains "march" it finds eg. "des marchés", but If I search for "marché" it doesn't find. So it's the French character.

listAgendaItems = dc.agenda.Where(a =>
                        a.libelle_activite.Contains(searchText)
).ToList<agenda>();

The database and the table Agenda have extended properties -> Collation  : French_CI_AS

So how can I makes sure I get the French words, too? like "é,  à"  etc

I also tried to search for "marche" but it doesn't find "marchés".

Body:
Your collation French_CI_AS is "Case-Insensitive", "Accent-Sensitive". If you want a query for "marches" to match "marchés", you need French_CI_AI as your collation. In most languages, that's actually NOT what native speakers want, because the accents are semantically important, but that may depend on the circumstances or context.

If, in fact, your users do always want accent insensitive searches, you should set that collation property to AI instead of AS on the table (or the specific fields). Otherwise, if the need is rare, you can apply collation to a table in MS Sql on a per-query basis; keep in mind that if there is no index on that collation there may be a substantial performance cost. That may be nearly immaterial when you're doing a %wildcard% query, however, since you'll generally have a full table scan in that case anyway.

The last I checked, it wasn't possible to specify a collation in a Linq query directly, so if you are doing case insensitivity on an ad-hoc basis, you'd need to use direct-to-sql query through your data context.

Edited:
Based on your comment, it sounds like you are allowing HTML content to be stored in your database. You have numeric character references in your table, which SQL Server knows nothing about, since they're a feature of HTML, XML and SGML. You can only make this searchable if those characters are string literals in a suitable encoding.

NVARCHAR will store the content in Unicode, specifically UTF-16, and VARCHAR will use Windows-1252 with French collation.

If you are accepting this input via web forms, make sure the page encoding is appropriate. If you are only supporting modern browsers (essentially anything IE5+), UTF-8 is well supported, so you should consider using UTF-8 for all of your requests and responses.

Make sure in your web.config, you have something like this:

<configuration>
   <system.web>
      <globalization
         requestEncoding="utf-8"
         responseEncoding="utf-8" />
   </system.web>
</configuration>

If you already have data stored with those numeric character references in your database, you can unescape them by translating &#ddddd; into literal UTF-16 sequences, and store them again. Make sure you don't accidentally unescape semantically important NCRs like the greater-than, less-than or ampersand codepoints.


问:
Paste special method of range class failed vba
```<code>Sub MakeTables()
    Dim wbTarget As Object

    Set wb = Workbooks.Open("C:\Users\A9900899\Desktop\Desmond\VBAProject\GenerateTablesFormulas.xlsx")
    Set wbTarget = Workbooks.Open("C:\Users\A9900899\Desktop\Desmond\VBAProject\USDReport.xlsx")

    With wb.Sheets("Sheet1").UsedRange
    .Copy

    ' Create the new sheet and name it at the end

        With wbTarget.Sheets("HK").Range("D82:X97")
        .PasteSpecial xlValues
        .PasteSpecial xlFormats
        End With
    End With

End Sub
</code>```

Can someone tell me what mistake I made here. It gives me the error that range class failed. Thank you

答:
if you want to keep the copied range size, then:

```<code>With wb.Sheets("Sheet1").UsedRange
    .Copy

    ' Create the new sheet and name it at the end

    With wbTarget.Sheets("HK").Range("D82") '.Resize(.Rows.Count, .Columns.Count) '<--| you can omit the 'Resize' part but it can be useful to make it clear (code can be read in years to come) you want to stick to copied range size
        .PasteSpecial xlValues
        .PasteSpecial xlFormats
    End With
End With
Application.CutCopyMode = False '<--| empty clipboard
</code>```

otherwise if you want to force the copied range size to the to-be-pasted one, then:

```<code>' Create the new sheet and name it at the end

With wbTarget.Sheets("HK").Range("D82:X97") '<--| reference range you want to paste values to and keep sizes of
    wb.Sheets("Sheet1").UsedRange.Resize(.Rows.Count, .Columns.Count).Copy '<--| copy the source sheet range with same sizes as referenced range

    .PasteSpecial xlValues
    .PasteSpecial xlFormats
End With
Application.CutCopyMode = False '<--| empty clipboard
</code>```

Body:
Sub MakeTables()
    Dim wbTarget As Object

    Set wb = Workbooks.Open("C:\Users\A9900899\Desktop\Desmond\VBAProject\GenerateTablesFormulas.xlsx")
    Set wbTarget = Workbooks.Open("C:\Users\A9900899\Desktop\Desmond\VBAProject\USDReport.xlsx")

    With wb.Sheets("Sheet1").UsedRange
    .Copy

    ' Create the new sheet and name it at the end

        With wbTarget.Sheets("HK").Range("D82:X97")
        .PasteSpecial xlValues
        .PasteSpecial xlFormats
        End With
    End With

End Sub

Can someone tell me what mistake I made here. It gives me the error that range class failed. Thank you

Body:
if you want to keep the copied range size, then:

With wb.Sheets("Sheet1").UsedRange
    .Copy

    ' Create the new sheet and name it at the end

    With wbTarget.Sheets("HK").Range("D82") '.Resize(.Rows.Count, .Columns.Count) '<--| you can omit the 'Resize' part but it can be useful to make it clear (code can be read in years to come) you want to stick to copied range size
        .PasteSpecial xlValues
        .PasteSpecial xlFormats
    End With
End With
Application.CutCopyMode = False '<--| empty clipboard

otherwise if you want to force the copied range size to the to-be-pasted one, then:

' Create the new sheet and name it at the end

With wbTarget.Sheets("HK").Range("D82:X97") '<--| reference range you want to paste values to and keep sizes of
    wb.Sheets("Sheet1").UsedRange.Resize(.Rows.Count, .Columns.Count).Copy '<--| copy the source sheet range with same sizes as referenced range

    .PasteSpecial xlValues
    .PasteSpecial xlFormats
End With
Application.CutCopyMode = False '<--| empty clipboard


问:
MySql Workbench installer requires Visual C++ 2015 Redistributable Package to be installed, but it already is installed
I've looked everywhere online, but it doesn't look like anyone has been able to resolve this issue.

When I download and try to install MySql Workbench, I get prompted to install Visual C++ Redistributable package (2015) to be installed. The wizard then takes me directly to this website in order to install it.

However, whenever I try to install either, it just tells me they're already installed.

After googling this for about an hour, I found some other people had this problem which apparently was resolved by following the instructions from this website. I downloaded instaedit and followed the instructions, but I continue to get the same error.

I've been at this for two days now and am going to go crazy. If someone can help me with this I'd be very grateful. I'm using Windows 10,

答:
First try to uninstall completely Visual C++ Redistributable package (2015) and install it again. If that does not help please try something else:

Open regedit and try to find key
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\14.0\VC\Runtimes\x64
or
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64
if you see that keys check value Installed=1 (DWORD)

If you found these keys and you got message about not installed c-runtime try to use processmonitor from sysinternals https://technet.microsoft.com/en-us/sysinternals/processmonitor and check if you have access to registry.

If you don't have these keys in your registry you can try to create it manually
 and see if that helps.

ContentLicense: CC BY-SA 4.0


问:
Adding a single character to add keys in Counter
If the type of a Counter object's keys is str, i.e.:

I could do this:

```<code>>>> vocab_counter = Counter("the lazy fox jumps over the brown dog".split())

>>> vocab_counter  = Counter({k+u"\uE000":v for k,v in vocab_counter.items()})
>>> vocab_counter
Counter({'brown\ue000': 1,
         'dog\ue000': 1,
         'fox\ue000': 1,
         'jumps\ue000': 1,
         'lazy\ue000': 1,
         'over\ue000': 1,
         'the\ue000': 2})
</code>```

What would be a quick and/or pythonic way to add a character to all keys?

Is the above method the only way to achieve the final counter with the character appended to all keys? Are there other way(s) to achieve the same goal?

答:
The better way would be adding that character before creating your counter object. You can do it using a generator expression within Counter:

```<code>In [15]: vocab_counter = Counter(w + u"\uE000" for w in "the lazy fox jumps over the brown dog".split())

In [16]: vocab_counter
Out[16]: Counter({'the\ue000': 2, 'fox\ue000': 1, 'dog\ue000': 1, 'jumps\ue000': 1, 'lazy\ue000': 1, 'over\ue000': 1, 'brown\ue000': 1})
</code>```

If it's not possible to modify the words before creating the Counter you can override the Counter object in order to add the special character during setting the values for keys.

Body:
If the type of a Counter object's keys is str, i.e.:

I could do this:

>>> vocab_counter = Counter("the lazy fox jumps over the brown dog".split())

>>> vocab_counter  = Counter({k+u"\uE000":v for k,v in vocab_counter.items()})
>>> vocab_counter
Counter({'brown\ue000': 1,
         'dog\ue000': 1,
         'fox\ue000': 1,
         'jumps\ue000': 1,
         'lazy\ue000': 1,
         'over\ue000': 1,
         'the\ue000': 2})

What would be a quick and/or pythonic way to add a character to all keys?

Is the above method the only way to achieve the final counter with the character appended to all keys? Are there other way(s) to achieve the same goal?

Body:
The better way would be adding that character before creating your counter object. You can do it using a generator expression within Counter:

In [15]: vocab_counter = Counter(w + u"\uE000" for w in "the lazy fox jumps over the brown dog".split())

In [16]: vocab_counter
Out[16]: Counter({'the\ue000': 2, 'fox\ue000': 1, 'dog\ue000': 1, 'jumps\ue000': 1, 'lazy\ue000': 1, 'over\ue000': 1, 'brown\ue000': 1})

If it's not possible to modify the words before creating the Counter you can override the Counter object in order to add the special character during setting the values for keys.


问:
Parent Div to Keep the Height of Tallest Child
I've been Googling potential solutions but as yet cannot find one that fits the brief.

```<code><div class="parent">
    <div class="child1">I'm 60px tall and visible; my parent is 100px tall</div>
    <div class="child2">I'm 80px tall and hidden until needed</div>
    <div class="child3">I'm 100px tall and hidden until needed</div>
</div>
</code>```

I need to have a number of child Divs with a parent Div.

Only one child will show at any time.

The parent Div must always remain the same height as the tallest child and never expand or
contract.

I'll use jQuery to change the css of the visible child but I'd prefer a CSS solution to the height if possible.

No IE8/9/10 to support.

Anyone got ideas?

答:
hide using opacity with 0 and 1 and the parent should be as tall as the tallest child.

See snippet below

$(function(){
  $(".c").fadeTo(0,0);
  $(".child1").fadeTo(0,1).addClass("visible");
  $(".btn").click(function(){
    $(".c").fadeTo(0,0);
    $(".visible").removeClass("visible").next().fadeTo(0,1).addClass("visible");
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent { position:relative; border:2px solid red; display:flex  }
.c { border:2px solid blue; }
.child1 { height:60px; }
.child2 { height:80px; }
.child3 { height:100px; }</code>```

I'm 60px tall and visible; my parent is 100px tall

I'm 80px tall and hidden until needed

I'm 100px tall and hidden until needed

<button class="btn">Show Next Child</button>

```

Body:
I've been Googling potential solutions but as yet cannot find one that fits the brief.

I'm 60px tall and visible; my parent is 100px tall

I'm 80px tall and hidden until needed

I'm 100px tall and hidden until needed

I need to have a number of child Divs with a parent Div.

Only one child will show at any time.

The parent Div must always remain the same height as the tallest child and never expand or
contract.

I'll use jQuery to change the css of the visible child but I'd prefer a CSS solution to the height if possible.

No IE8/9/10 to support.

Anyone got ideas?

Body:
hide using opacity with 0 and 1 and the parent should be as tall as the tallest child.

See snippet below

$(function(){
  $(".c").fadeTo(0,0);
  $(".child1").fadeTo(0,1).addClass("visible");
  $(".btn").click(function(){
    $(".c").fadeTo(0,0);
    $(".visible").removeClass("visible").next().fadeTo(0,1).addClass("visible");
  });

});

.parent { position:relative; border:2px solid red; display:flex  }
.c { border:2px solid blue; }
.child1 { height:60px; }
.child2 { height:80px; }
.child3 { height:100px; }

<div class="parent">
    <div class="c child1">I'm 60px tall and visible; my parent is 100px tall</div>
    <div class="c child2">I'm 80px tall and hidden until needed</div>
    <div class="c child3">I'm 100px tall and hidden until needed</div>
</div>

<button class="btn">Show Next Child</button>

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


答:
The only other optimised way I can think of is to use a subclass of Counter that appends the character when the key is inserted:

```<code>from collections import Counter

class CustomCounter(Counter):
    def __setitem__(self, key, value):
        if len(key) > 1 and not key.endswith(u"\uE000"):
            key += u"\uE000"
        super(CustomCounter, self).__setitem__(key, self.get(key, 0) + value)
</code>```

Demo:

```<code>>>> CustomCounter("the lazy fox jumps over the brown dog".split())
CustomCounter({u'the\ue000': 2, u'fox\ue000': 1, u'brown\ue000': 1, u'jumps\ue000': 1, u'dog\ue000': 1, u'over\ue000': 1, u'lazy\ue000': 1})
# With both args and kwargs
>>> CustomCounter("the lazy fox jumps over the brown dog".split(), **{'the': 1, 'fox': 3})
CustomCounter({u'fox\ue000': 4, u'the\ue000': 3, u'brown\ue000': 1, u'jumps\ue000': 1, u'dog\ue000': 1, u'over\ue000': 1, u'lazy\ue000': 1})
</code>```

Title: Adding a single character to add keys in Counter

Body:
The only other optimised way I can think of is to use a subclass of Counter that appends the character when the key is inserted:

from collections import Counter

class CustomCounter(Counter):
    def __setitem__(self, key, value):
        if len(key) > 1 and not key.endswith(u"\uE000"):
            key += u"\uE000"
        super(CustomCounter, self).__setitem__(key, self.get(key, 0) + value)

Demo:

>>> CustomCounter("the lazy fox jumps over the brown dog".split())
CustomCounter({u'the\ue000': 2, u'fox\ue000': 1, u'brown\ue000': 1, u'jumps\ue000': 1, u'dog\ue000': 1, u'over\ue000': 1, u'lazy\ue000': 1})
# With both args and kwargs
>>> CustomCounter("the lazy fox jumps over the brown dog".split(), **{'the': 1, 'fox': 3})
CustomCounter({u'fox\ue000': 4, u'the\ue000': 3, u'brown\ue000': 1, u'jumps\ue000': 1, u'dog\ue000': 1, u'over\ue000': 1, u'lazy\ue000': 1})


问:
Incrementing register in Assembler x86 doesn't go above value of 1
I'm pretty new to Assembler, I just need to complete my school task, but I have one little problem. The program should read two-digit numbers on input and count all the numbers that are greater than the first one. The problem is that register EDX (used for counting greater numbers) increments up to 1, but not above it. Can you suggest something not too complicated?

```<code>%include "asm_io.inc"
segment .data
char_prompt    db  "Insert numbers: ",0
comma           db  ", ",0
out_msg1       db  "Count of numbers greater than the first number(",0
out_msg2       db  "): ",0

segment .text
global _asm_main
_asm_main:
enter 0,0
pusha

mov     EAX, char_prompt
call    print_string

first_number:
call    read_char
cmp     EAX, 32
je      first_number
cmp     EAX, 10
je      after_input
cmp     EAX, 13
je      after_input
sub     EAX, 48     ; turn ASCII code into a digit
mov     EBX, 10
mul     EBX         ; multiply decimal point by 10
mov     EBX, EAX
call    read_char
sub     EAX, 48     ; turn ASCII code into a digit
add     EAX, EBX    ; add decimals and units together
mov     ECX, EAX
call    print_int
mov     EAX, comma
call    print_string
jmp     main_loop

main_loop:
call    read_char
cmp     EAX, 32
je      main_loop
cmp     EAX, 10
je      after_input
cmp     EAX, 13
je      after_input
sub     EAX, 48     ; turn ASCII code into a digit
mov     EBX, 10
mul     EBX         ; multiply decimal point by 10
mov     EBX, EAX
call    read_char
sub     EAX, 48     ; turn ASCII code into a digit
add     EAX, EBX    ; add decimals and units together
mov     EBX, EAX
call    print_int
mov     EAX, comma
call    print_string
mov     EAX, EBX
cmp     EAX, ECX    ; compare current number to first number
ja      increase
jmp     main_loop

increase:
inc     EDX         ; increase count of greater numbers <-- PROBLEM HERE
jmp     main_loop

after_input:
mov     EAX, out_msg1
call    print_string
mov     EAX, ECX
call    print_int
mov     EAX, out_msg2
call    print_string
mov     EAX, EDX
call    print_int
jmp     finish

finish:
popa                 ; terminate program
mov EAX, 0
mov EBX, 0
mov ECX, 0
mov EDX, 0
leave
ret
</code>```

The format of output is still pretty raw, I'm going to correct it once I solve that main issue.

I also tried

```<code>add EDX, 1
</code>```

instead of

```<code>inc EDX
</code>```

but it was the same result.

I would be really grateful if someone helped me.

答:
Hidden parameters

The problem is that some instructions in the x86 instruction set take hidden parameters.

mul sucks

In your case it's the MUL instruction.

mul ebx is a misnomer. It is really:

```<code>mul edx:eax, eax, ebx
    ^^^^^^^  ^^^  ^^^
      |||     |    +-------- Source 1
      |||     +------------- Source 2
      +++------------------- Destination
</code>```

That is mul ebx translates to: EDX:EAX = EAX * EBX.

So instead of 1 operand mul takes 3.

You can see this at:  http://www.felixcloutier.com/x86/MUL.html

The reason for this is that a multiply of two 32 bit operands can produce a 64-bit number. In order to facilitate this the processor stores the result in two registers. The lower 32 bits go into EAX and the higher 32 bits go into EDX.
In your case you are multiplying small numbers so EDX always ends up with zero, which neatly explains why EDX will never get above one.

-You keep on resetting it back to zero-.

The solution is to use another register for the counter, e.g. EDI.
But be careful, because EDI is also used as a hidden parameter in the string instructions.

If you're using those, then you'll need to either push edx before and pop edx after the mul instruction or use imul.

imul rules

This instruction allows you to specify explicit operands.

imul eax,ebx

This instruction will translate to the following pseudo code: eax = eax * ebx.

imul performs a s̲i̲gn̲e̲d̲ m̲u̲l̲t̲i̲pl̲y(!), which is probably fine for your use case, but something to be aware of. It will also throw away overflow bits, but you don't need to worry about that in your code.

Finally

If you're multiplying times a constant you can just do:

```<code>imul ebx,eax,10
</code>```

Condensing 3 instructions into 1, and avoiding clobbering edx.

About calling conventions

If any of those routines that you call modify any registers you'll also run into trouble. I'm assuming that your routines use pusha/popa throughout, but if any registers are clobbered by subroutines you'll need to compensate for that in your code.

If you call library functions, these will adhere to a calling convention which specify which registers are preserved by the called routine and which registers can be altered.

Body:
I'm pretty new to Assembler, I just need to complete my school task, but I have one little problem. The program should read two-digit numbers on input and count all the numbers that are greater than the first one. The problem is that register EDX (used for counting greater numbers) increments up to 1, but not above it. Can you suggest something not too complicated?

%include "asm_io.inc"
segment .data
char_prompt    db  "Insert numbers: ",0
comma           db  ", ",0
out_msg1       db  "Count of numbers greater than the first number(",0
out_msg2       db  "): ",0

segment .text
global _asm_main
_asm_main:
enter 0,0
pusha

mov     EAX, char_prompt
call    print_string

first_number:
call    read_char
cmp     EAX, 32
je      first_number
cmp     EAX, 10
je      after_input
cmp     EAX, 13
je      after_input
sub     EAX, 48     ; turn ASCII code into a digit
mov     EBX, 10
mul     EBX         ; multiply decimal point by 10
mov     EBX, EAX
call    read_char
sub     EAX, 48     ; turn ASCII code into a digit
add     EAX, EBX    ; add decimals and units together
mov     ECX, EAX
call    print_int
mov     EAX, comma
call    print_string
jmp     main_loop

main_loop:
call    read_char
cmp     EAX, 32
je      main_loop
cmp     EAX, 10
je      after_input
cmp     EAX, 13
je      after_input
sub     EAX, 48     ; turn ASCII code into a digit
mov     EBX, 10
mul     EBX         ; multiply decimal point by 10
mov     EBX, EAX
call    read_char
sub     EAX, 48     ; turn ASCII code into a digit
add     EAX, EBX    ; add decimals and units together
mov     EBX, EAX
call    print_int
mov     EAX, comma
call    print_string
mov     EAX, EBX
cmp     EAX, ECX    ; compare current number to first number
ja      increase
jmp     main_loop

increase:
inc     EDX         ; increase count of greater numbers <-- PROBLEM HERE
jmp     main_loop

after_input:
mov     EAX, out_msg1
call    print_string
mov     EAX, ECX
call    print_int
mov     EAX, out_msg2
call    print_string
mov     EAX, EDX
call    print_int
jmp     finish

finish:
popa                 ; terminate program
mov EAX, 0
mov EBX, 0
mov ECX, 0
mov EDX, 0
leave
ret

The format of output is still pretty raw, I'm going to correct it once I solve that main issue.

I also tried

add EDX, 1

instead of

inc EDX

but it was the same result.

I would be really grateful if someone helped me.

Body:
Hidden parameters

The problem is that some instructions in the x86 instruction set take hidden parameters.

mul sucks

In your case it's the MUL instruction.

mul ebx is a misnomer. It is really:

mul edx:eax, eax, ebx
    ^^^^^^^  ^^^  ^^^
      |||     |    +-------- Source 1
      |||     +------------- Source 2
      +++------------------- Destination

That is mul ebx translates to: EDX:EAX = EAX * EBX.

So instead of 1 operand mul takes 3.

You can see this at:  http://www.felixcloutier.com/x86/MUL.html

The reason for this is that a multiply of two 32 bit operands can produce a 64-bit number. In order to facilitate this the processor stores the result in two registers. The lower 32 bits go into EAX and the higher 32 bits go into EDX.
In your case you are multiplying small numbers so EDX always ends up with zero, which neatly explains why EDX will never get above one.

-You keep on resetting it back to zero-.

The solution is to use another register for the counter, e.g. EDI.
But be careful, because EDI is also used as a hidden parameter in the string instructions.

If you're using those, then you'll need to either push edx before and pop edx after the mul instruction or use imul.

imul rules

This instruction allows you to specify explicit operands.

imul eax,ebx

This instruction will translate to the following pseudo code: eax = eax * ebx.

imul performs a s̲i̲gn̲e̲d̲ m̲u̲l̲t̲i̲pl̲y(!), which is probably fine for your use case, but something to be aware of. It will also throw away overflow bits, but you don't need to worry about that in your code.

Finally

If you're multiplying times a constant you can just do:

imul ebx,eax,10

Condensing 3 instructions into 1, and avoiding clobbering edx.

About calling conventions

If any of those routines that you call modify any registers you'll also run into trouble. I'm assuming that your routines use pusha/popa throughout, but if any registers are clobbered by subroutines you'll need to compensate for that in your code.

If you call library functions, these will adhere to a calling convention which specify which registers are preserved by the called routine and which registers can be altered.


问:
C terminology: header vs. signature
the word header as far as I know is usually in reference to a header file while the word signature is in reference to the arguments and return type of the function. For example, in my experience this would be called a signature:

```<code>int ptInPoly(Point q, Point p[], int n)
</code>```

My professor is calling this a header in my assignments. I have found this confusing and would like to know if this different use terminology is common or something that only he does. Thanks

Here is some more context around the use of the term header:

"Your program must have a function with header: int ptInPoly(Point q, Point p[], int n) that determines if point q is in the polygon given in p"

答:
Header is never a correct term for this. The C11 standard explicitly defines that a header is that which is included in the form #include <foo.h>; here <foo.h> is a name of a header. Thus <stdio.h>, <stdlib.h> and such are headers. (They need not be actual files though, nor in C source code: C11 footnote 182):

182) A header is not necessarily a source file, nor are the < and > delimited sequences in header names necessarily valid source file names.

Signature, on the other hand, is somewhat better, if not very exact, as it is not the one used by the standard. The standard uses the term prototype for a declaration of a function signature that specifies the types of the parameters. (C11 6.2.1p2):

[...] A function prototype is a declaration of a function that declares the types of its parameters. [...]

Why a signature is somewhat vague is because in C a function need not have a prototype, but such a function could still considered having a partial signature, but is not a type signature in the strictest sense. Additionally, prototypeless declarations are considered obsolescent in C99 and C11 (C11 6.11.6, 6.11.7):

6.11.6 Function declarators

1 The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.

6.11.7 Function definitions

1 The use of function definitions with separate parameter identifier and declaration lists (not prototype-format parameter type and identifier declarators) is an obsolescent feature.

Thus the best wording would be

Your program must have a function with prototype int ptInPoly(Point q, Point p[], int n) that determines if point q is in the polygon given in p"

Title: C terminology: header vs. signature

Body:
the word header as far as I know is usually in reference to a header file while the word signature is in reference to the arguments and return type of the function. For example, in my experience this would be called a signature:

int ptInPoly(Point q, Point p[], int n)

My professor is calling this a header in my assignments. I have found this confusing and would like to know if this different use terminology is common or something that only he does. Thanks

Here is some more context around the use of the term header:

"Your program must have a function with header: int ptInPoly(Point q, Point p[], int n) that determines if point q is in the polygon given in p"


问:
Split and replace Java string
I am trying to read a text file, split the contents as explained below, and append the split comments in to a Java List.

The error is in the splitting part.

Existing String:

a1(X1, UniqueVar1), a2(X2, UniqueVar1), a3(UniqueVar1, UniqueVar2)
```

<p>Expected—to split them and append them to Java list:</p>

<pre class="lang-none prettyprint-override"><code>a1(X1, UniqueVar1)
a2(X2, UniqueVar1)
a3(UniqueVar1, UniqueVar2)
</code>```

Code:

```<code>subSplit = obj.split("\\), ");
for (String subObj: subSplit)
{
    System.out.println(subObj.trim());
}
</code>```

Result:

a1(X1, UniqueVar1
a2(X2, UniqueVar1
...
```

Please suggest how to correct this.

答:
Use a positive lookbehind in your regular expression:

```<code>String[] subSplit = obj.split("(?<=\\)), ");
</code>```

This expression matches a , preceded by a ), but because the lookbehind part (?<=\\)) is non-capturing (zero-width), it doesn't get discarded as being part of the split separator.

More information about lookaround assertions and non-capturing groups can be found in the javadoc of the Pattern class.

Title: Split and replace Java string

Body:
I am trying to read a text file, split the contents as explained below, and append the split comments in to a Java List.

The error is in the splitting part.

Existing String:

a1(X1, UniqueVar1), a2(X2, UniqueVar1), a3(UniqueVar1, UniqueVar2)

Expected—to split them and append them to Java list:

a1(X1, UniqueVar1)
a2(X2, UniqueVar1)
a3(UniqueVar1, UniqueVar2)

Code:

subSplit = obj.split("\\), ");
for (String subObj: subSplit)
{
    System.out.println(subObj.trim());
}

Result:

a1(X1, UniqueVar1
a2(X2, UniqueVar1
...

Please suggest how to correct this.

Body:
Use a positive lookbehind in your regular expression:

String[] subSplit = obj.split("(?<=\\)), ");

This expression matches a , preceded by a ), but because the lookbehind part (?<=\\)) is non-capturing (zero-width), it doesn't get discarded as being part of the split separator.

More information about lookaround assertions and non-capturing groups can be found in the javadoc of the Pattern class.


问:
drop shadow in libgdx
i'm working on a 2d android game and i would like to add a shadow/elevation to some of my in game elements.

This image shows exacly what effect do i want to achive. I know it can be easly achived using xml but i'm making my game using libgdx. I've searched quiete alot and i havn't found any built in way to do this. I cant use premade shadow graphics to put behind my elements becouse there are alot of diffrent element sizes. Would realy appriciate some help and hope my english didn't make it too hard to understand :)

答:
You can use a premade shadow graphic. Just use it as a ninepatch image. This is how I achieve exactly this effect.

More info here

Title: drop shadow in libgdx


问:
how to open excel on foreground in VBA using powerpoint
i am trying to open an excel file in a powerpoint presentation.
this is my code:

```<code>Sub diversestickersKoole()

Dim xlApp As Object
Dim xlWorkBook As Object

Set xlApp = CreateObject("Excel.Application")

xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("V:\Oliedocs\Koole\Stickers Scheepstanks Koole.xltm", True, False)

Set xlApp = Nothing
Set xlWorkBook = Nothing
End Sub
</code>```

the excel file is opening in the background. this must be in the foreground.

can someone help me?

答:
Adding the line xlWorkBook.Activate should be enough.

Your code should look like this:

```<code>Sub diversestickersKoole()

Dim xlApp As Object
Dim xlWorkBook As Object

Set xlApp = CreateObject("Excel.Application")

xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("V:\Oliedocs\Koole\Stickers   Scheepstanks Koole.xltm", True, False)

xlWorkBook.Activate

Set xlApp = Nothing

Set xlWorkBook = Nothing

End Function
</code>```

For references:

https://www.mrexcel.com/forum/excel-questions/670476-excel-visual-basic-applications-test-if-workbook-open-if-so-bring-front.html

Post #4

Body:
i am trying to open an excel file in a powerpoint presentation.
this is my code:

Sub diversestickersKoole()

Dim xlApp As Object
Dim xlWorkBook As Object

Set xlApp = CreateObject("Excel.Application")

xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("V:\Oliedocs\Koole\Stickers Scheepstanks Koole.xltm", True, False)

Set xlApp = Nothing
Set xlWorkBook = Nothing
End Sub

the excel file is opening in the background. this must be in the foreground.

can someone help me?

Body:
Adding the line xlWorkBook.Activate should be enough.

Your code should look like this:

Sub diversestickersKoole()

Dim xlApp As Object
Dim xlWorkBook As Object

Set xlApp = CreateObject("Excel.Application")

xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("V:\Oliedocs\Koole\Stickers   Scheepstanks Koole.xltm", True, False)

xlWorkBook.Activate

Set xlApp = Nothing

Set xlWorkBook = Nothing

End Function

For references:

https://www.mrexcel.com/forum/excel-questions/670476-excel-visual-basic-applications-test-if-workbook-open-if-so-bring-front.html

Post #4


问:
Changing value of a variable on OnClick Android
I have 2 buttons in my layout when user presses button 1 the value of 'number' should change to '2' and when the user presses button 2 the value of 'number' should change to '1'.But the value does not change.
Here is my code :

```<code>public class test extends AppCompatActivity{

public  int number ;

private Button btn1;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.testing);

    btn1=(Button)findViewById(R.id.btn1);
    btn2=(Button)findViewById(R.id.btn2);

    test();
}

void test()
{

  if(number<1) {
    number = 1;
    }

        Log.e("number value : ",String.valueOf(number));

    if(number==1)
    {

         btn1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
          number=2;

             Log.e("number value : ",String.valueOf(number));

         }

    });

    }

     if(number==2)
    {
     btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
             number=1;
             Log.e("number value : ",String.valueOf(number));

    }

    });

    }

    }
</code>```

Log.e outputs ``` E/number value :: 2``` when I press btn1 but when i press btn2 nothing happens and only btn1 works

答:
Try this</p>

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.testing);

    btn1=(Button)findViewById(R.id.btn1);
    btn2=(Button)findViewById(R.id.btn2);
    btn1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
          number=2;
             Log.e("number value : ",String.valueOf(number));
         }

    });
    btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
             number=1;
             Log.e("number value : ",String.valueOf(number));
    }

    });
}
</code>```

Body:
I have 2 buttons in my layout when user presses button 1 the value of 'number' should change to '2' and when the user presses button 2 the value of 'number' should change to '1'.But the value does not change.
Here is my code :

public class test extends AppCompatActivity{

public  int number ;

private Button btn1;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.testing);

    btn1=(Button)findViewById(R.id.btn1);
    btn2=(Button)findViewById(R.id.btn2);

    test();
}

void test()
{

  if(number<1) {
    number = 1;
    }

        Log.e("number value : ",String.valueOf(number));

    if(number==1)
    {

         btn1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
          number=2;

             Log.e("number value : ",String.valueOf(number));

         }

    });

    }

     if(number==2)
    {
     btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
             number=1;
             Log.e("number value : ",String.valueOf(number));

    }

    });

    }

    }

Log.e outputs
 E/number value :: 2
 when I press btn1 but when i press btn2 nothing happens and only btn1 works

Body:
Try this

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.testing);

    btn1=(Button)findViewById(R.id.btn1);
    btn2=(Button)findViewById(R.id.btn2);
    btn1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
          number=2;
             Log.e("number value : ",String.valueOf(number));
         }

    });
    btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
             number=1;
             Log.e("number value : ",String.valueOf(number));
    }

    });
}


问:
Removing link reference in browser
I am using the following code to toggle my mobile navigation

html

```<code><a href="#" class="toggle-nav"><p>toggle</p></a>
</code>```

I have a function which attaches the proper code/css and just need it to act as a button but not go anywhere (hence the '#').

However I want nothing to show up when it clicks/hover, since the browser usually indicates where the link is going, I don't want that (or anything else) to show

答:
You may style the link with pointer-events.

.toggle-nav {
  pointer-events: none
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>toggle</p></code>```

Title: Removing link reference in browser

Body:
I am using the following code to toggle my mobile navigation

html

toggle

I have a function which attaches the proper code/css and just need it to act as a button but not go anywhere (hence the '#').

However I want nothing to show up when it clicks/hover, since the browser usually indicates where the link is going, I don't want that (or anything else) to show

Body:
You may style the link with pointer-events.

.toggle-nav {
  pointer-events: none
}

<a href="#" class="toggle-nav"><p>toggle</p></a>


问:
Make Axios send cookies in its requests automatically
I am sending requests from the client to my Express.js server using Axios.

I set a cookie on the client and I want to read that cookie from all Axios requests without adding them manually to request by hand.

This is my clientside request example:

```<code>axios.get(`some api url`).then(response => ...
</code>```

I tried to access headers or cookies by using these properties in my Express.js server:

```<code>req.headers
req.cookies
</code>```

Neither of them contained any cookies. I am using cookie parser middleware:

```<code>app.use(cookieParser())
</code>```

How do I make Axios send cookies in requests automatically?

Edit:

I set cookie on the client like this:

```<code>import cookieClient from 'react-cookie'

...
let cookie = cookieClient.load('cookie-name')
if(cookie === undefined){
      axios.get('path/to/my/cookie/api').then(response => {
        if(response.status == 200){
          cookieClient.save('cookie-name', response.data, {path:'/'})
        }
      })
    }
...
</code>```

While it's also using Axios, it is not relevant to the question. I simply want to embed cookies into all my requests once a cookie is set.

答:
You can use withCredentials property.

XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request.

```<code>axios.get(BASE_URL + '/todos', { withCredentials: true });
</code>```

Also its possible to force credentials to every Axios requests

```<code>axios.defaults.withCredentials = true
</code>```

Or using credentials for some of the Axios requests as the following code

```<code>const instance = axios.create({
   withCredentials: true,
   baseURL: BASE_URL
})
instance.get('/todos')
</code>```

Body:
I am sending requests from the client to my Express.js server using Axios.

I set a cookie on the client and I want to read that cookie from all Axios requests without adding them manually to request by hand.

This is my clientside request example:

axios.get(`some api url`).then(response => ...

I tried to access headers or cookies by using these properties in my Express.js server:

req.headers
req.cookies

Neither of them contained any cookies. I am using cookie parser middleware:

app.use(cookieParser())

How do I make Axios send cookies in requests automatically?

Edit:

I set cookie on the client like this:

import cookieClient from 'react-cookie'

...
let cookie = cookieClient.load('cookie-name')
if(cookie === undefined){
      axios.get('path/to/my/cookie/api').then(response => {
        if(response.status == 200){
          cookieClient.save('cookie-name', response.data, {path:'/'})
        }
      })
    }
...

While it's also using Axios, it is not relevant to the question. I simply want to embed cookies into all my requests once a cookie is set.

Body:
You can use withCredentials property.

XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request.

axios.get(BASE_URL + '/todos', { withCredentials: true });

Also its possible to force credentials to every Axios requests

axios.defaults.withCredentials = true

Or using credentials for some of the Axios requests as the following code

const instance = axios.create({
   withCredentials: true,
   baseURL: BASE_URL
})
instance.get('/todos')


问:
javascript const keyword is not working
my.js

```<code>function deductions(){
    parseFloat($('#TaxDeduction').val());        // value 5
}

function earning() {
    const itdeduction = deductions();
    var basicsalary = parseFloat($('#BasicSalary').val());  //value 10000
    var da = parseFloat($('#DA').val());       // value 1000
    var totalearning = Math.round((basicsalary+da));   // value 11000
    var it_deduction = Math.round(((totalearning * itdeduction) / 100)); //value 550
    $('#TaxDeduction').html(it_deduction.toFixed(2));
    $('#TaxDeduction').val(it_deduction.toFixed(2)); //value 550 on first mouse over //value 60500 on second mouseover. but  i Need value 550 for n number of mouseover
}
</code>```

my.html

```<code>onmouseover="earning()"
</code>```

In this the onmouseover event my const keyword in javascript is not working. or else the on each time onmouseover TaxDeduction value gets increased.

答:
You are missing the return:

```<code> return parseFloat($('#TaxDeduction').val());
</code>```

Title: javascript const keyword is not working

Body:
my.js

function deductions(){
    parseFloat($('#TaxDeduction').val());        // value 5
}

function earning() {
    const itdeduction = deductions();
    var basicsalary = parseFloat($('#BasicSalary').val());  //value 10000
    var da = parseFloat($('#DA').val());       // value 1000
    var totalearning = Math.round((basicsalary+da));   // value 11000
    var it_deduction = Math.round(((totalearning * itdeduction) / 100)); //value 550
    $('#TaxDeduction').html(it_deduction.toFixed(2));
    $('#TaxDeduction').val(it_deduction.toFixed(2)); //value 550 on first mouse over //value 60500 on second mouseover. but  i Need value 550 for n number of mouseover
}

my.html

onmouseover="earning()"

In this the onmouseover event my const keyword in javascript is not working. or else the on each time onmouseover TaxDeduction value gets increased.

Body:
You are missing the return:

 return parseFloat($('#TaxDeduction').val());


答:
trimmingCharacters removes only leading and trailing white spaces.

try this

```<code>let _searchStr = searchStr.replacingOccurrences(" ", withString: "", options:.literal, range: nil)
</code>```

Title: trimmingCharacters not work on iOS 10.3 Xcode8.3

Body:
Please help me, I use Xcode 8.3(swift 3.1), the function trimmingCharacters not work. My code as below:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if var searchStr = textField.text{
       let _searchStr = searchStr.trimmingCharacters(in: .whitespaces)
       print("After trimming:\(_searchStr)")
   }
}

The input in textfield is 409 huỳnh and the print result is 409 huỳnh not as expected: 409huỳnh .

Body:
trimmingCharacters removes only leading and trailing white spaces.

try this

let _searchStr = searchStr.replacingOccurrences(" ", withString: "", options:.literal, range: nil)


问:
Android Realm ChangeListener not being triggered
I've got a Realm results change listener that isn't being triggered, here's the code:

```<code>final RealmResults<LogEntry> entries = realm.where(LogEntry.class).findAll();

entries.addChangeListener(new RealmChangeListener<RealmResults<LogEntry>>() {
            @Override
            public void onChange(RealmResults<LogEntry> results) {
                Log.v("Testing", "The size is: " + results.size());
            }
        });
</code>```

There is definitely new stuff being added, I have a log on the realm insertion printing out the new size of the table, yet for some reason the change listener does nothing? Am I missing something here, it seems identical to the docs.

答:
You need to keep a class reference to entries to prevent it from being GC'ed:

```<code>public MyClass {

  private RealmResults<LogEntry> entries;

  public void myMethod() {

    entries = realm.where(LogEntry.class).findAll();
    entries.addChangeListener(new RealmChangeListener<RealmResults<LogEntry>>() {
            @Override
            public void onChange(RealmResults<LogEntry> results) {
                Log.v("Testing", "The size is: " + results.size());
            }
        });
    }
}
</code>```

Body:
I've got a Realm results change listener that isn't being triggered, here's the code:

final RealmResults<LogEntry> entries = realm.where(LogEntry.class).findAll();

entries.addChangeListener(new RealmChangeListener<RealmResults<LogEntry>>() {
            @Override
            public void onChange(RealmResults<LogEntry> results) {
                Log.v("Testing", "The size is: " + results.size());
            }
        });

There is definitely new stuff being added, I have a log on the realm insertion printing out the new size of the table, yet for some reason the change listener does nothing? Am I missing something here, it seems identical to the docs.

Body:
You need to keep a class reference to entries to prevent it from being GC'ed:

public MyClass {

  private RealmResults<LogEntry> entries;

  public void myMethod() {

    entries = realm.where(LogEntry.class).findAll();
    entries.addChangeListener(new RealmChangeListener<RealmResults<LogEntry>>() {
            @Override
            public void onChange(RealmResults<LogEntry> results) {
                Log.v("Testing", "The size is: " + results.size());
            }
        });
    }
}


问:
webgl three.js - how to display a sprite ? Error: Uncaught TypeError: Cannot read property 'x' of undefined at SpritePlugin.render
I am a begginer with three.js.

I tried the code found here: Creating-a-scene

Then I tried to add a sprite with the code found here:
Sprite

But I couldn't make it work as I get the following error :

```<code>Uncaught TypeError: Cannot read property 'x' of undefined
    at SpritePlugin.render (three.js:6973)
    at WebGLRenderer.render (three.js:21007)
    at render (sprite.html:43)
</code>```

The html file is there:
http://www.planetarium2016.com/sprite.html

Where is my mistake ? Here is my code:

```<code><html>
    <head>
        <title>My first three.js app</title>
        <style>
            body { margin: 0; }
            canvas { width: 100%; height: 100% }
        </style>
    </head>
    <body>
        <script src="https://rawgithub.com/mrdoob/three.js/master/build/three.js"></script>
        <script>
            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
            var renderer = new THREE.WebGLRenderer();
            renderer.setSize( window.innerWidth, window.innerHeight );
            document.body.appendChild( renderer.domElement );
            // instantiate a loader
            var loader = new THREE.TextureLoader();
            //allow cross origin loading
                //loader.crossOrigin = '';
            // load a resource
            loader.load("https://codefisher.org/static/images/pastel-svg/256/bullet-star.png");
            var spriteMaterial = new THREE.SpriteMaterial( { map: loader, color: 0xffffff } );
            var sprite = new THREE.Sprite( spriteMaterial );
            sprite.scale.set(200, 200, 1);
            scene.add( sprite );
            camera.position.z = 2;
            var render = function () {
                requestAnimationFrame( render );
                renderer.render(scene, camera);
            };
            render();
        </script>
    </body>
</html>
</code>```

答:
I'd say the lines below would fix the error.

```<code>var spriteMap = loader.load("https://codefisher.org/static/images/pastel-svg/256/bullet-star.png");
var spriteMaterial = new THREE.SpriteMaterial( { map: spriteMap, color: 0xffffff } );
</code>```

And requestAnimationFrame is necessary. Let's just keep the render function as it used to be.

Body:
I am a begginer with three.js.

I tried the code found here: Creating-a-scene

Then I tried to add a sprite with the code found here:
Sprite

But I couldn't make it work as I get the following error :

Uncaught TypeError: Cannot read property 'x' of undefined
    at SpritePlugin.render (three.js:6973)
    at WebGLRenderer.render (three.js:21007)
    at render (sprite.html:43)

The html file is there:
http://www.planetarium2016.com/sprite.html

Where is my mistake ? Here is my code:

        <title>My first three.js app</title>

Body:
I'd say the lines below would fix the error.

var spriteMap = loader.load("https://codefisher.org/static/images/pastel-svg/256/bullet-star.png");
var spriteMaterial = new THREE.SpriteMaterial( { map: spriteMap, color: 0xffffff } );

And requestAnimationFrame is necessary. Let's just keep the render function as it used to be.


问:
How to debug the Angular error "Error while waiting for Protractor to sync with the page"?
```<code>**..\..\node_modules\gulp-angular-protractor\node_modules\gulp-protractor\node_modules\protractor\node_modules\selenium-webdriver\lib\goog\async\nexttick.js:41
  goog.global.setTimeout(function() { throw exception; }, 0);
                                      ^
Error while waiting for Protractor to sync with the page: "window.angular is undefined.  This could be either because this is a non-angular page or because your test involves client-side navigation, which can interfere with Protractor's bootstrapping.  See http://git.io/v4gXM for details"**
</code>```

What could be the possible error in the code?

答:
The reason would be the loading page, since you are trying to search in the Angular Page and the result page would be Angular too. But the page in between them for eg:  when you click some thing that would open another page, in between the opening you will get some loading screen or the loader icon etc. That may not be Angular. So you are getting synchronization issues.

Normally we will get there errors in loaders, frames or video contents in the Angular pages.

Try using browser.ignoreSynchronization = true; and once you page got Angular page got loaded make the browser.ignoreSynchronization = false;
So that the actual testcases for the Angular page will not fail.

Body:
**..\..\node_modules\gulp-angular-protractor\node_modules\gulp-protractor\node_modules\protractor\node_modules\selenium-webdriver\lib\goog\async\nexttick.js:41
  goog.global.setTimeout(function() { throw exception; }, 0);
                                      ^
Error while waiting for Protractor to sync with the page: "window.angular is undefined.  This could be either because this is a non-angular page or because your test involves client-side navigation, which can interfere with Protractor's bootstrapping.  See http://git.io/v4gXM for details"**

What could be the possible error in the code?


问:
ng-repeat shows terrible performance with large lists
I'm experiencing performance issues when using ng-repeat for long lists (thousands of records) that need to be shown within a table.

Here is the HTML I'm using:

```<code>    <table class="table table-hover">
        <thead>
            <tr>
                <th ng-repeat="One_Header in Data_List.Header track by $index">{{One_Header}}</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-model="Data_List" ng-repeat="One_Source in Data_List.Body track by $index" style="cursor:pointer">
                <td ng-repeat="One_Data_Field in One_Source track by $index">{{One_Data_Field}}</td>
            </tr>
        </tbody>
    </table>
</code>```

The received JSON (takes about 1 second to get it from the server) contains the data as follows:

```<code>"Data":{
         "Header":["Title_1","Title_2","Title_3"],
         "Body":[
                 ["Rec_1_Data_1","Rec_1_Data_2","Rec_1_Data_3"],
                 ["Rec_2_Data_1","Rec_2_Data_2","Rec_2_Data_3"],
                 ["Rec_3_Data_1","Rec_3_Data_2","Rec_3_Data_3"],
                 :
                 ["Rec_n_Data_1","Rec_n_Data_2","Rec_n_Data_3"]
                ]
}
</code>```

I also tried one-directional binding (i.e. {{::One_Data_Field}}) without any noticeable improvement.

As stated above, response arrives within a second and then it takes up to 10 seconds for the table to be built.

答:
you can try this sample pagination implementation:</p>

```<code>        var pageSize = 15;
        $scope.paginationLimit = function(pagesShown) {
            return pageSize * pagesShown.count;
        };

        $scope.hasMoreItemsToShow = function(list, pagesShown) {
           return pagesShown.count < (list.length / pageSize);
        };

        $scope.showMoreItems = function(pagesShown) {
            pagesShown.count = pagesShown.count + 1;
        };

       <tr ng-model="Data_List" ng-repeat="One_Source in Data_List.Body track by $index " style="cursor:pointer">
            <td ng-repeat="One_Data_Field in One_Source track by $index | limitTo: paginationLimit(pagesShown)">{{One_Data_Field}}</td>
        </tr>

        //sample row with show more button
        <tr class="showMore">
            <td></td>
            <td class="showBtn">
                <button type="button" class="btn btn-primary btn-lg" ng-init="pagesShown={'count': 1}" ng-click="showMoreItems(pagesShown)" ng-show="hasMoreItemsToShow(One_Source track, pagesShown)">Show More</button>
            </td>
            <td></td>
        </tr>
</code>```

Body:
I'm experiencing performance issues when using ng-repeat for long lists (thousands of records) that need to be shown within a table.

Here is the HTML I'm using:

                {{One_Header}}

                {{One_Data_Field}}

The received JSON (takes about 1 second to get it from the server) contains the data as follows:

"Data":{
         "Header":["Title_1","Title_2","Title_3"],
         "Body":[
                 ["Rec_1_Data_1","Rec_1_Data_2","Rec_1_Data_3"],
                 ["Rec_2_Data_1","Rec_2_Data_2","Rec_2_Data_3"],
                 ["Rec_3_Data_1","Rec_3_Data_2","Rec_3_Data_3"],
                 :
                 ["Rec_n_Data_1","Rec_n_Data_2","Rec_n_Data_3"]
                ]
}

I also tried one-directional binding (i.e. {{::One_Data_Field}}) without any noticeable improvement.

As stated above, response arrives within a second and then it takes up to 10 seconds for the table to be built.

Body:
you can try this sample pagination implementation:

        var pageSize = 15;
        $scope.paginationLimit = function(pagesShown) {
            return pageSize * pagesShown.count;
        };

        $scope.hasMoreItemsToShow = function(list, pagesShown) {
           return pagesShown.count < (list.length / pageSize);
        };

        $scope.showMoreItems = function(pagesShown) {
            pagesShown.count = pagesShown.count + 1;
        };

       <tr ng-model="Data_List" ng-repeat="One_Source in Data_List.Body track by $index " style="cursor:pointer">
            <td ng-repeat="One_Data_Field in One_Source track by $index | limitTo: paginationLimit(pagesShown)">{{One_Data_Field}}</td>
        </tr>

        //sample row with show more button
        <tr class="showMore">
            <td></td>
            <td class="showBtn">
                <button type="button" class="btn btn-primary btn-lg" ng-init="pagesShown={'count': 1}" ng-click="showMoreItems(pagesShown)" ng-show="hasMoreItemsToShow(One_Source track, pagesShown)">Show More</button>
            </td>
            <td></td>
        </tr>


问:
Error when converting dynamic offset and datetime
I have a dynamic parameter for offset and datetime.

And I have problem when converting the date.

```<code>Declare @STR NVARCHAR (MAX)
Declare @offset nvarchar = '+05:00'
Declare @paramrequest date = '2017-03-30'

SET @STR = 'select .... where '
+ CONVERT(DATE, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, + 'REQUESTDATETIME'), @offset )) + ' >=' + CAST(@paramrequest AS DATE);

EXECUTE (@STR)
</code>```

When I run the script, it gets me this error. How to get fix this error?

Conversion failed when converting date and/or time from character string.

答:
You need to build your string correctly. use CONCAT like this:

```<code>SET @STR = CONCAT('select .... where ',
  'CONVERT(DATE, SWITCHOFFSET(CONVERT(DATETIMEOFFSET,',
  'REQUESTDATETIME),''',
  @offset,''' )) >= ''',
 CAST(@paramrequest AS DATE), '''')
</code>```

Body:
I have a dynamic parameter for offset and datetime.

And I have problem when converting the date.

Declare @STR NVARCHAR (MAX)
Declare @offset nvarchar = '+05:00'
Declare @paramrequest date = '2017-03-30'

SET @STR = 'select .... where '
+ CONVERT(DATE, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, + 'REQUESTDATETIME'), @offset )) + ' >=' + CAST(@paramrequest AS DATE);

EXECUTE (@STR)

When I run the script, it gets me this error. How to get fix this error?

Conversion failed when converting date and/or time from character string.

Body:
You need to build your string correctly. use CONCAT like this:

SET @STR = CONCAT('select .... where ',
  'CONVERT(DATE, SWITCHOFFSET(CONVERT(DATETIMEOFFSET,',
  'REQUESTDATETIME),''',
  @offset,''' )) >= ''',
 CAST(@paramrequest AS DATE), '''')


问:
Anyone using JRuby-Rack with Rails 3?
Is anyone else out there running Rails 3 and JRuby-Rack, or Jetty and Rails 3?  Any trick to it?  I'm going insane with some debugging, and at this point I just want to know that it's possible.</p>

答: i am using jetty-rails + rails3 for a couple of projects. jetty-rails need to be fixed , require "activesupport" need to be changed to require "active_support" (for activesupport 3.0.3) and you have also do 'require "active_support/all"' to include hash extensions (otherwise symbolize! & reverse_merge method will raise exceptions.. right now trying to fix some jruby-rack issues.. (Rack::Runtime not loaded)..will update once thats done.</p>

Title: Anyone using JRuby-Rack with Rails 3?


问:
How to create a floating search view on android with google maps as the background?
so i am currently trying to develop and app that needs to integrate google maps on the home page, so i was wondering how to add a floating search view on that home page</p>

答: This might serve your purpose, Link</p>

Body: This might serve your purpose, Link


问:
How to configure multiple analyzers for one field in elasticsearch?
I am trying to add path hierarchy analyzer to one field in my type.

I want to configure path analyzer and reverse path analyzer on same field so I can get normal path and reverse path of the one field.

for eg.

path="/angular/directive/structural"

I want to configure this path field such as whenever I analyze this field, I should get tokens in normal order and reverse order if I specify reverse.

Below is my mapping.

```<code>PUT /elastic_course
{
  "settings": {
    "analysis": {
      "analyzer": {
        "path_analyzer": {
          "tokenizer": "path_tokenizer"
        },
        "reverse_path_analyzer": {
          "tokenizer": "reverse_path_tokenizer"
        }
      },
      "tokenizer": {
        "path_tokenizer": {
          "type": "path_hierarchy",
          "delimiter": "/",
          "replacement": "-"
        },
        "reverse_path_tokenizer": {
          "type": "path_hierarchy",
          "delimiter": "/",
          "replacement": "-"
        }
      }
    }
  },
  "mappings": {
    "book" : {
        "properties": {
           "author": {
              "type": "string",
              "index": "not_analyzed"
           },
           "genre": {
              "type": "string",
              "index": "not_analyzed"
           },
           "score": {
              "type": "double"
           },
           "synopsis": {
              "type": "string",
              "index":"analyzed",
              "analyzer":"english"
           },
           "title": {
              "type": "string"
           },
           "path":{
              "type":"string",
              "analyzer":"path_analyzer",
              "fields": {
                "reverse": {
                  "type":"string",
                  "analyzer":"reverse_path_analyzer"
                }
              }
          }
      }
    }
  }
}
</code>```

I have configured this analyzers. Now How to I get tokens for path and reverse path?

Thanks.

答:
You can declare sub-fields for the path field, each with a different analyzer:

```<code>       "path":{
          "type":"string",
          "analyzer":"path_analyzer",
          "fields": {
            "reverse": {
              "type":"string",
              "analyzer":"reverse_path_analyzer"
            }
          }
       }
</code>```

Then you can refer to path and path.reverse in your queries.

Body:
I am trying to add path hierarchy analyzer to one field in my type.

I want to configure path analyzer and reverse path analyzer on same field so I can get normal path and reverse path of the one field.

for eg.

path="/angular/directive/structural"

I want to configure this path field such as whenever I analyze this field, I should get tokens in normal order and reverse order if I specify reverse.

Below is my mapping.

PUT /elastic_course
{
  "settings": {
    "analysis": {
      "analyzer": {
        "path_analyzer": {
          "tokenizer": "path_tokenizer"
        },
        "reverse_path_analyzer": {
          "tokenizer": "reverse_path_tokenizer"
        }
      },
      "tokenizer": {
        "path_tokenizer": {
          "type": "path_hierarchy",
          "delimiter": "/",
          "replacement": "-"
        },
        "reverse_path_tokenizer": {
          "type": "path_hierarchy",
          "delimiter": "/",
          "replacement": "-"
        }
      }
    }
  },
  "mappings": {
    "book" : {
        "properties": {
           "author": {
              "type": "string",
              "index": "not_analyzed"
           },
           "genre": {
              "type": "string",
              "index": "not_analyzed"
           },
           "score": {
              "type": "double"
           },
           "synopsis": {
              "type": "string",
              "index":"analyzed",
              "analyzer":"english"
           },
           "title": {
              "type": "string"
           },
           "path":{
              "type":"string",
              "analyzer":"path_analyzer",
              "fields": {
                "reverse": {
                  "type":"string",
                  "analyzer":"reverse_path_analyzer"
                }
              }
          }
      }
    }
  }
}

I have configured this analyzers. Now How to I get tokens for path and reverse path?

Thanks.

Body:
You can declare sub-fields for the path field, each with a different analyzer:

       "path":{
          "type":"string",
          "analyzer":"path_analyzer",
          "fields": {
            "reverse": {
              "type":"string",
              "analyzer":"reverse_path_analyzer"
            }
          }
       }

Then you can refer to path and path.reverse in your queries.


问:
PHP (7.1) inheritance issue
I have the following structure:

```<code>class AffiliateRepository extends GenericRepository implements IAffiliateRepository {

}

abstract class GenericRepository  {
    public function save(BaseModel $model) : int{
        $model->save();
        return $model->getId();
    }

}

interface IAffiliateRepository  {

    public function save(Affiliate $affiliate) : int;
}

public class Affiliate extends BaseModel{}

$affiliateRepository  = new AffiliateRepository();
$affiliateRepository->save(new Affiliate());
</code>```

I am expecting GenericRepository to take care on the save action.

but I'm getting the following error:

Declaration of App\Services\AffiliateRepository::save(App\Models\Affiliate $affiliate): int
should be compatible with
App\Services\GenericRepository::save(App\Models\BaseModel $model): int

Why is that? Affiliate inherits from BaseModel.

Whats the best way to overcome that and let GenericRepository handle the save function call.

thanks

答:
Seems a bit messy but the problem is, in order for AffiliateRepository to implement the IAffiliateRepository, the signature of save must be

```<code>save(Affiliate $affiliate) : int
</code>```

The implementation in GenericRepository does not satisfy this.

You could try this in AffiliateRepository...

```<code>public function save(Affiliate $affiliate) : int {
    return parent::save($affiliate);
}
</code>```

Title: PHP (7.1) inheritance issue

Body:
I have the following structure:

class AffiliateRepository extends GenericRepository implements IAffiliateRepository {

}

abstract class GenericRepository  {
    public function save(BaseModel $model) : int{
        $model->save();
        return $model->getId();
    }

}

interface IAffiliateRepository  {

    public function save(Affiliate $affiliate) : int;
}

public class Affiliate extends BaseModel{}

$affiliateRepository  = new AffiliateRepository();
$affiliateRepository->save(new Affiliate());

I am expecting GenericRepository to take care on the save action.

but I'm getting the following error:

Declaration of App\Services\AffiliateRepository::save(App\Models\Affiliate $affiliate): int
should be compatible with
App\Services\GenericRepository::save(App\Models\BaseModel $model): int

Why is that? Affiliate inherits from BaseModel.

Whats the best way to overcome that and let GenericRepository handle the save function call.

thanks

Body:
Seems a bit messy but the problem is, in order for AffiliateRepository to implement the IAffiliateRepository, the signature of save must be

save(Affiliate $affiliate) : int

The implementation in GenericRepository does not satisfy this.

You could try this in AffiliateRepository...

public function save(Affiliate $affiliate) : int {
    return parent::save($affiliate);
}


问:
scala BufferedSource Position
I have 2 questions about the Scala class BufferedSource.

How can I query the current reading position ?

I tried it with pos :

```<code>object testapp extends App {

 val doc = scala.io.Source.fromFile("text.txt")

 println(doc.pos)
 doc.next()
 println(doc.pos)
 doc.next()
 println(doc.pos)
 }
</code>```

Output:

```<code> 0
 2049
 2050
</code>```

Why it jumps from 0 to 2049 ?!

Is there another way to query the position and/or set it somewhere else ?

Thanks for your help :-)

答:
pos returns position of last character returned by next(), but the trick is that position is a combination of row and column encoded by position's encoder (scala.io.Position) as a single Integer:

The object Position provides convenience methods to encode  *  line
  and column number in one single integer.  The encoded line  *
  (column) numbers range from 0 to LINE_MASK (COLUMN_MASK),  *
  where 0 indicates that the line (column) is undefined and  *  1
  represents the first line (column)...

https://github.com/scala/scala/blob/v2.11.8/src/library/scala/io/Position.scala

http://www.scala-lang.org/api/2.11.8/#scala.io.Source$RelaxedPosition$

Use Postioner in order to get more readable info:

The current input and position, as well as the next character methods
  delegate to the positioner.

Example:

```<code>val doc = scala.io.Source.fromFile("aaa.txt")
val positioner =  new doc.Positioner()
val positioned = doc.withPositioning(positioner)
positioned.next()
scala> positioner.cline -> positioner.ccol
res15: (Int, Int) = (1,2)
positioned.next()
scala> positioner.cline -> positioner.ccol
res17: (Int, Int) = (1,3)
</code>```

P.S. Source is intended for reading data as stream of characters, so it provides you conveniences like getLines() etc, so basically that's why Positioner works with rows and columns instead of an absolute position.

If you need an Iterator that returns you an absolute position of every character, use zipWithIndex:

```<code>scala> val doc = scala.io.Source.fromFile("aaa.txt").zipWithIndex
doc: Iterator[(Char, Int)] = non-empty iterator

scala> doc.next()
res38: (Char, Int) = (a,0)

scala> doc.next()
res39: (Char, Int) = (a,1)

scala> doc.next()
res40: (Char, Int) = (a,2)

scala> doc.next()
res41: (Char, Int) = (a,3)

scala> doc.next()
res42: (Char, Int) =
(
,4)
</code>```

Title: scala BufferedSource Position

Body:
I have 2 questions about the Scala class BufferedSource.

How can I query the current reading position ?

I tried it with pos :

object testapp extends App {

 val doc = scala.io.Source.fromFile("text.txt")

 println(doc.pos)
 doc.next()
 println(doc.pos)
 doc.next()
 println(doc.pos)
 }

Output:

 0
 2049
 2050

Why it jumps from 0 to 2049 ?!

Is there another way to query the position and/or set it somewhere else ?

Thanks for your help :-)

Body:
pos returns position of last character returned by next(), but the trick is that position is a combination of row and column encoded by position's encoder (scala.io.Position) as a single Integer:

The object Position provides convenience methods to encode  *  line
  and column number in one single integer.  The encoded line  *
  (column) numbers range from 0 to LINE_MASK (COLUMN_MASK),  *
  where 0 indicates that the line (column) is undefined and  *  1
  represents the first line (column)...

https://github.com/scala/scala/blob/v2.11.8/src/library/scala/io/Position.scala

http://www.scala-lang.org/api/2.11.8/#scala.io.Source$RelaxedPosition$

Use Postioner in order to get more readable info:

The current input and position, as well as the next character methods
  delegate to the positioner.

Example:

val doc = scala.io.Source.fromFile("aaa.txt")
val positioner =  new doc.Positioner()
val positioned = doc.withPositioning(positioner)
positioned.next()
scala> positioner.cline -> positioner.ccol
res15: (Int, Int) = (1,2)
positioned.next()
scala> positioner.cline -> positioner.ccol
res17: (Int, Int) = (1,3)

P.S. Source is intended for reading data as stream of characters, so it provides you conveniences like getLines() etc, so basically that's why Positioner works with rows and columns instead of an absolute position.

If you need an Iterator that returns you an absolute position of every character, use zipWithIndex:

scala> val doc = scala.io.Source.fromFile("aaa.txt").zipWithIndex
doc: Iterator[(Char, Int)] = non-empty iterator

scala> doc.next()
res38: (Char, Int) = (a,0)

scala> doc.next()
res39: (Char, Int) = (a,1)

scala> doc.next()
res40: (Char, Int) = (a,2)

scala> doc.next()
res41: (Char, Int) = (a,3)

scala> doc.next()
res42: (Char, Int) =
(
,4)


问:
ASP.net: Display PDF in a asp.net web page
User click on a link button and it will direct them to a url that is dynmaically generated which a pdf file. The browser will prompt the user to either save or open it.

I want to know if it is possible to downlaod the pdf file to the server then show the pdf file in the asp.net web page. When i google on this question, 99% of top link are some third party component. Is it a way to do this without purchase any 3rd party component?

thank

答: Look up the Content-Disposition HTTP header. You can send back a value that requests the content be displayed inline instead of downloaded. </p>

OwnerDisplayName: Jack

OwnerDisplayName: stevex


问:
How do numpy block matrices work?
The outcome of this code doesn't make any sense to me:

```<code>a = np.zeros((2, 2))
b = np.bmat([[a, a], [a, a]])
print(b.shape, b.dot(np.zeros(4)).shape)
</code>```

How can a matrix with shape (4, 4) when doing a sum-product over its final axis return a matrix of shape (1, 4)?

答:
bmat doesn't do anything exotic or fancy; basically it's just a couple  of levels on concatenation:

```<code>In [308]: np.bmat([[a,a],[a,a]]).A
Out[308]:
array([[0, 1, 0, 1],
       [2, 3, 2, 3],
       [0, 1, 0, 1],
       [2, 3, 2, 3]])

In [309]: alist = [[a,a],[a,a]]
In [310]: np.concatenate([np.concatenate(sublist, axis=1) for sublist in alist], axis=0)
Out[310]:
array([[0, 1, 0, 1],
       [2, 3, 2, 3],
       [0, 1, 0, 1],
       [2, 3, 2, 3]])
</code>```

Title: How do numpy block matrices work?

Body:
The outcome of this code doesn't make any sense to me:

a = np.zeros((2, 2))
b = np.bmat([[a, a], [a, a]])
print(b.shape, b.dot(np.zeros(4)).shape)

How can a matrix with shape (4, 4) when doing a sum-product over its final axis return a matrix of shape (1, 4)?

Body:
bmat doesn't do anything exotic or fancy; basically it's just a couple  of levels on concatenation:

In [308]: np.bmat([[a,a],[a,a]]).A
Out[308]:
array([[0, 1, 0, 1],
       [2, 3, 2, 3],
       [0, 1, 0, 1],
       [2, 3, 2, 3]])

In [309]: alist = [[a,a],[a,a]]
In [310]: np.concatenate([np.concatenate(sublist, axis=1) for sublist in alist], axis=0)
Out[310]:
array([[0, 1, 0, 1],
       [2, 3, 2, 3],
       [0, 1, 0, 1],
       [2, 3, 2, 3]])