问:
print lines after finding a key word in perl
I have a variable $string and i want to print all the lines after I find a keyword in the line (including the line with keyword)

```<code>$string=~ /apple /;
</code>```

I'm using this regexp to find the key word but I do not how to print lines after this keyword.

答:
It's not really clear where your data is coming from. Let's assume it's a string containing newlines. Let's start by splitting it into an array.

```<code>my @string = split /\n/, $string;
</code>```

We can then use the flip-flop operator to decide which lines to print. I'm using \0 as a regex that is very unlikely to match any string (so, effectively, it's always false).

```<code>for (@string) {
  say if /apple / .. /\0/;
}
</code>```

Body:
I have a variable $string and i want to print all the lines after I find a keyword in the line (including the line with keyword)

$string=~ /apple /;

I'm using this regexp to find the key word but I do not how to print lines after this keyword.

Body:
It's not really clear where your data is coming from. Let's assume it's a string containing newlines. Let's start by splitting it into an array.

my @string = split /\n/, $string;

We can then use the flip-flop operator to decide which lines to print. I'm using \0 as a regex that is very unlikely to match any string (so, effectively, it's always false).

for (@string) {
  say if /apple / .. /\0/;
}


来源: stackexchange

问:
ASP.NET Error: Could not load file or assembly App_Web_z9w33txs
How did you get rid of these annoying ASP.NET errors:
Could not load file or assembly 'App_Web_z9w33txs, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'

This has only happened to me once before. It seems like it is related to ASP.NET caching some assembly dynamically, but not recompiling it for some reason. Thoughts? How do you fix this? What causes it?

More Info:
This is happening to a WCF Service being called via Ajax from my Default.aspx page.
The Default.aspx page loads fine.

removed stack trace

Final Update:

So this is happening to me at least 5 times a day now.
I have to shutdown the app pool.

Go into C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files
and deleted the files here
Then restart the app pool.
Anybody else run into something like this? Should I just break down and create a support case with Microsoft.

答:
Sometime I have got such error and began to research how to resolve it. Just deleting ASP.NET temporary directory didn't any influence in my case. Then I just have added such attribute to web.config compilation node:

```<code><compilation debug="true" tempDirectory="c:\temp" >
</code>```

I hope that this can help and other people.

OwnerDisplayName: Bruno Tyndall

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Bruno Tyndall

Body:
Sometime I have got such error and began to research how to resolve it. Just deleting ASP.NET temporary directory didn't any influence in my case. Then I just have added such attribute to web.config compilation node:

<compilation debug="true" tempDirectory="c:\temp" >

I hope that this can help and other people.


问:
MySQL - How to parse a string value to DATETIME format inside an Update statement?
I have an application which logs entries with datetime format. Now I want to push that datetime string into db. So i have the query

```<code>db.query "update processing set start_time = STR_TO_DATE('2017053008:04:45', '%Y-%m-%d %H:%i:%s') where dated = '2017-06-07' and zone = 'W13';"
</code>```

I have the datetime format in my log as "2017060708:04:45" and when I run the above query its inputs NULL in the filed start_time.

Any help in this would be much appreciated. Thanks!

答:
```<code>db.query "update processing set start_time = STR_TO_DATE('2017053008:04:45', '%Y%m%d%H:%i:%s') where dated = '2017-06-07' and zone = 'W13';"
</code>```

Try above query .

Hope this will helps.

ContentLicense: CC BY-SA 3.0

Body:
I have an application which logs entries with datetime format. Now I want to push that datetime string into db. So i have the query

db.query "update processing set start_time = STR_TO_DATE('2017053008:04:45', '%Y-%m-%d %H:%i:%s') where dated = '2017-06-07' and zone = 'W13';"

I have the datetime format in my log as "2017060708:04:45" and when I run the above query its inputs NULL in the filed start_time.

Any help in this would be much appreciated. Thanks!

Body:
db.query "update processing set start_time = STR_TO_DATE('2017053008:04:45', '%Y%m%d%H:%i:%s') where dated = '2017-06-07' and zone = 'W13';"

Try above query .

Hope this will helps.


问:
How to detect PHP pfsockopen being closed by remote server?
I'm trying to make asynchronous HTTP POST requests from PHP server to an Nginx server. I read this very informative blog post about the issue, decided to use the technique with pfsockopen function, and imported the code doing this written by the blog author. I include the key sections below:

```<code>private function createSocket() {
  if ($this->socket_failed)
    return false;
  $protocol = $this->ssl() ? "ssl" : "tcp";
  $host = $this->options["host"];
  $port = $this->ssl() ? 443 : 80;
  $timeout = $this->options["timeout"];
  try {
    # Open our socket to the API Server.
    # Since we're try catch'ing prevent PHP logs.
    $socket = @pfsockopen($protocol . "://" . $host, $port, $errno,
                         $errstr, $timeout);
    # If we couldn't open the socket, handle the error.
    if (false === $socket) {
      ...
      return false;
    }
    return $socket;
  } catch (Exception $e) {
    ...
    return false;
  }
}

private function makeRequest($socket, $req, $retry = true) {
  $bytes_written = 0;
  $bytes_total = strlen($req);
  $closed = false;
  # Write the request
  while (!$closed && $bytes_written < $bytes_total) {
    try {
      # Since we're try catch'ing prevent PHP logs.
      $written = @fwrite($socket, substr($req, $bytes_written));
    } catch (Exception $e) {
      ...
      $closed = true;
    }
    if (!isset($written) || !$written) {
      $closed = true;
    } else {
      $bytes_written += $written;
    }
  }
  # If the socket has been closed, attempt to retry a single time.
  if ($closed) {
    fclose($socket);
    if ($retry) {
      $socket = $this->createSocket();
      if ($socket) return $this->makeRequest($socket, $req, false);
    }
    return false;
  }
  $success = true;
  ...
  return $success;
}
</code>```

It mostly works very well, but I'm observing the following problem. Usually, after about 30 seconds of inactivity, when I send a request this way, Nginx responds with a TCP RST (reset) packet, which I read indicates that the socket has been closed on the remote end. I can also see the connection statuses with netstat -na | grep 8080 and by that time, the connection PHP -> Nginx is in state CLOSE_WAIT, while Nginx -> PHP is in FIN_WAIT2. This guide confirms that this means the remote server wants to close the connection.

I know that the issue is caused by the connection timeout settings on the remote end, because when I increase it, connections shown by netstat remain in state ESTABLISHED for longer, and if PHP server decides to reuse such a connection, it works fine. However, I don't want to set connection timeout to a very high value, as I'm worried of running out of ports.

Is there any way I can detect in PHP that a connection went into a CLOSE_WAIT state? I tried the following and none of it works:

Checking if handle returned by pfsockopen is false.

Checking $errno variable written by pfsockopen.

Try-catching exceptions from pfsockopen and fwrite.

Checking if fwrite($socket) returns false.

Checking if fflush($socket) returns false.

Checking stream_get_meta_data($socket)['timed_out'].

答:
AFAIK the best way is to select for read and, if readable, do an fread().</p>

```<code>// $socket was opened via pfsockopen(...)
stream_set_blocking($socket,0);
while(1){
  // the do..while(0) is a trick to break out
  do{
     $rs = array($socket); $ws = NULL; $es = NULL;
     $ok = stream_select($rs,$ws,$es,0,100000);
     if ( $ok === false ) break; // select err, close and reconn
     if ( $ok <= 0 ) break 2; // select tout, conn is up/ok
     $rply = fread($socket,1024); // make one/two fread()
     if ( $rply === false ) break; // read err
     if ( strlen($rply) == 0  ) break; // conn reset by peer
     break 2; // conn is up/ok
  }while(0);
  // here i must reconn
  fclose($socket);
  $socket = pfsockopen(...);
  if ( $socket ) stream_set_blocking($socket,0);
  else return false;
  break;
}//endwhile1
// here the conn is up/ok
// check if some in $rply to be handled...
</code>```

Body:
I'm trying to make asynchronous HTTP POST requests from PHP server to an Nginx server. I read this very informative blog post about the issue, decided to use the technique with pfsockopen function, and imported the code doing this written by the blog author. I include the key sections below:

private function createSocket() {
  if ($this->socket_failed)
    return false;
  $protocol = $this->ssl() ? "ssl" : "tcp";
  $host = $this->options["host"];
  $port = $this->ssl() ? 443 : 80;
  $timeout = $this->options["timeout"];
  try {
    # Open our socket to the API Server.
    # Since we're try catch'ing prevent PHP logs.
    $socket = @pfsockopen($protocol . "://" . $host, $port, $errno,
                         $errstr, $timeout);
    # If we couldn't open the socket, handle the error.
    if (false === $socket) {
      ...
      return false;
    }
    return $socket;
  } catch (Exception $e) {
    ...
    return false;
  }
}

private function makeRequest($socket, $req, $retry = true) {
  $bytes_written = 0;
  $bytes_total = strlen($req);
  $closed = false;
  # Write the request
  while (!$closed && $bytes_written < $bytes_total) {
    try {
      # Since we're try catch'ing prevent PHP logs.
      $written = @fwrite($socket, substr($req, $bytes_written));
    } catch (Exception $e) {
      ...
      $closed = true;
    }
    if (!isset($written) || !$written) {
      $closed = true;
    } else {
      $bytes_written += $written;
    }
  }
  # If the socket has been closed, attempt to retry a single time.
  if ($closed) {
    fclose($socket);
    if ($retry) {
      $socket = $this->createSocket();
      if ($socket) return $this->makeRequest($socket, $req, false);
    }
    return false;
  }
  $success = true;
  ...
  return $success;
}

It mostly works very well, but I'm observing the following problem. Usually, after about 30 seconds of inactivity, when I send a request this way, Nginx responds with a TCP RST (reset) packet, which I read indicates that the socket has been closed on the remote end. I can also see the connection statuses with netstat -na | grep 8080 and by that time, the connection PHP -> Nginx is in state CLOSE_WAIT, while Nginx -> PHP is in FIN_WAIT2. This guide confirms that this means the remote server wants to close the connection.

I know that the issue is caused by the connection timeout settings on the remote end, because when I increase it, connections shown by netstat remain in state ESTABLISHED for longer, and if PHP server decides to reuse such a connection, it works fine. However, I don't want to set connection timeout to a very high value, as I'm worried of running out of ports.

Is there any way I can detect in PHP that a connection went into a CLOSE_WAIT state? I tried the following and none of it works:

Checking if handle returned by pfsockopen is false.

Checking $errno variable written by pfsockopen.

Try-catching exceptions from pfsockopen and fwrite.

Checking if fwrite($socket) returns false.

Checking if fflush($socket) returns false.

Checking stream_get_meta_data($socket)['timed_out'].

Body:
AFAIK the best way is to select for read and, if readable, do an fread().

// $socket was opened via pfsockopen(...)
stream_set_blocking($socket,0);
while(1){
  // the do..while(0) is a trick to break out
  do{
     $rs = array($socket); $ws = NULL; $es = NULL;
     $ok = stream_select($rs,$ws,$es,0,100000);
     if ( $ok === false ) break; // select err, close and reconn
     if ( $ok <= 0 ) break 2; // select tout, conn is up/ok
     $rply = fread($socket,1024); // make one/two fread()
     if ( $rply === false ) break; // read err
     if ( strlen($rply) == 0  ) break; // conn reset by peer
     break 2; // conn is up/ok
  }while(0);
  // here i must reconn
  fclose($socket);
  $socket = pfsockopen(...);
  if ( $socket ) stream_set_blocking($socket,0);
  else return false;
  break;
}//endwhile1
// here the conn is up/ok
// check if some in $rply to be handled...


问:
How can I create a datetime column without 'date' part?
I have a dataframe and there's a column named 'Time' in it like the below(HH:MM:SS:fffff).

```<code>>>> df['Time']
0        09:42:29:75284
1        09:42:29:95584
2        09:42:31:15036
3        09:42:35:15138
4        09:42:35:95491
5        09:42:43:55414
6        09:42:45:35866
7        09:42:46:74638
8        09:42:47:35582
9        09:42:47:74774
10       09:42:48:94582
...
Name: Time, Length: 18924, dtype: object
</code>```

I want to change its type as datetime, in order to make it easier to calculate. Is it possible to change its type, using pandas.to_datetime, as datetime without date?

Body:
I have a dataframe and there's a column named 'Time' in it like the below(HH:MM:SS:fffff).

>>> df['Time']
0        09:42:29:75284
1        09:42:29:95584
2        09:42:31:15036
3        09:42:35:15138
4        09:42:35:95491
5        09:42:43:55414
6        09:42:45:35866
7        09:42:46:74638
8        09:42:47:35582
9        09:42:47:74774
10       09:42:48:94582
...
Name: Time, Length: 18924, dtype: object

I want to change its type as datetime, in order to make it easier to calculate. Is it possible to change its type, using pandas.to_datetime, as datetime without date?

Body:
You can convert it to timedelta64[ns] dtype:

Source DF:

In [164]: df
Out[164]:
              Time
0   09:42:29:75284
1   09:42:29:95584
2   09:42:31:15036
3   09:42:35:15138
4   09:42:35:95491
5   09:42:43:55414
6   09:42:45:35866
7   09:42:46:74638
8   09:42:47:35582
9   09:42:47:74774
10  09:42:48:94582

In [165]: df.dtypes
Out[165]:
Time    object   # <-------- NOTE!
dtype: object

Converted:

In [166]: df.Time = pd.to_timedelta(df.Time.str.replace(r'\:(\d+)$', r'.\1'),
                                    errors='coerce')

In [167]: df
Out[167]:
              Time
0  09:42:29.752840
1  09:42:29.955840
2  09:42:31.150360
3  09:42:35.151380
4  09:42:35.954910
5  09:42:43.554140
6  09:42:45.358660
7  09:42:46.746380
8  09:42:47.355820
9  09:42:47.747740
10 09:42:48.945820

In [168]: df.dtypes
Out[168]:
Time    timedelta64[ns]   # <-------- NOTE!
dtype: object


问:
Trying to store multiple items in storage but only last one added gets stored
I'm making an app that can be thought of as a shopping cart. A user searches for a product, they click on the product, and they have the option of adding it to their cart.
After adding the item they are brought back to the search page. However if they go back to the search page, and search for something it refreshes the page in a sense because a new HTTP request is made and if they select a product, click add, only the last product is available in storage. I believe it is being overwritten.

When the user clicks the add button saveItem() is called in additems.ts  which creates a newItem object and calls addItem() which is suppose to push it to the items[] array and save it to storage.

What am I doing wrong?

addItem.ts

```<code>items = [];

// params passed from another page
name: string    = this.navParams.get('name');
desc: string    = this.navParams.get('desc');

// Called once users click on Add button in addItem.html
saveItem() {

  let newItem = {
    name: this.name,
    desc: this.desc
  };

  this.addItem(newItem);
}

addItem(item) {

  this.items.push(item);
  this.dataService.save(this.items);

  // Go back to search page. When the data is reloaded
  // on this page it resets all of the items in storage
  this.navCtrl.pop(Search);
}
</code>```

addItem.html

```<code><button (click)="saveItem()">Add</button>
</code>```

DataService.ts.

```<code>private storage: Storage;

constructor(storage: Storage) {
  this.storage = storage;
}

getData() {
  return this.storage.get('products');
}

save(data){
  let newData = JSON.stringify(data);
  this.storage.set('products', newData);
}
</code>```

// viewProducts.ts (This is where I want to view all current products in storage )
export class ConfirmOrderPage {

```<code>public items = [];

constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public dataService: DataStorage) {

   this.dataService.getData().then((products) => {
      if(products){
        this.items = JSON.parse(products);
        console.log("confirmorder", JSON.parse(products));
      }
    });
}
</code>```

viewProducts.html

```<code>ion-list>
<ion-item text-wrap *ngFor="let item of items">
  <h2>Name: {{ item.name }}</h2>
  <h3>Product Quantity: 3 </h3>
  <p>{{ item.desc }}</p>
</ion-item>
</ion-list>
</code>```

答:
in your .ts file, use the following code:

```<code>items = [];

// params passed from another page
name: string    = this.navParams.get('name');
desc: string    = this.navParams.get('desc');

// Called once users click on Add button in addItem.html
saveItem() {

  let newItem = {
    name: this.name,
    desc: this.desc
  };

  this.dataService.save(newItem).then(()=>{
    this.navCtrl.pop(Search);
  });
}
</code>```

and change the dataService.ts files's save() method as follows:

```<code>save(data): Promise<any>{
  return this.getData().then((products: any[]) => {
    products.push(data);
    return this.storage.set('products', products);
  });
}
</code>```

Body:
I'm making an app that can be thought of as a shopping cart. A user searches for a product, they click on the product, and they have the option of adding it to their cart.
After adding the item they are brought back to the search page. However if they go back to the search page, and search for something it refreshes the page in a sense because a new HTTP request is made and if they select a product, click add, only the last product is available in storage. I believe it is being overwritten.

When the user clicks the add button saveItem() is called in additems.ts  which creates a newItem object and calls addItem() which is suppose to push it to the items[] array and save it to storage.

What am I doing wrong?

addItem.ts

items = [];

// params passed from another page
name: string    = this.navParams.get('name');
desc: string    = this.navParams.get('desc');

// Called once users click on Add button in addItem.html
saveItem() {

  let newItem = {
    name: this.name,
    desc: this.desc
  };

  this.addItem(newItem);
}

addItem(item) {

  this.items.push(item);
  this.dataService.save(this.items);

  // Go back to search page. When the data is reloaded
  // on this page it resets all of the items in storage
  this.navCtrl.pop(Search);
}

addItem.html

<button (click)="saveItem()">Add</button>

DataService.ts.

private storage: Storage;

constructor(storage: Storage) {
  this.storage = storage;
}

getData() {
  return this.storage.get('products');
}

save(data){
  let newData = JSON.stringify(data);
  this.storage.set('products', newData);
}

// viewProducts.ts (This is where I want to view all current products in storage )
export class ConfirmOrderPage {

public items = [];

constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public dataService: DataStorage) {

   this.dataService.getData().then((products) => {
      if(products){
        this.items = JSON.parse(products);
        console.log("confirmorder", JSON.parse(products));
      }
    });
}

viewProducts.html

ion-list>
<ion-item text-wrap *ngFor="let item of items">

Name: {{ item.name }}

Product Quantity: 3

{{ item.desc }}

</ion-item>
</ion-list>

Body:
in your .ts file, use the following code:

items = [];

// params passed from another page
name: string    = this.navParams.get('name');
desc: string    = this.navParams.get('desc');

// Called once users click on Add button in addItem.html
saveItem() {

  let newItem = {
    name: this.name,
    desc: this.desc
  };

  this.dataService.save(newItem).then(()=>{
    this.navCtrl.pop(Search);
  });
}

and change the dataService.ts files's save() method as follows:

save(data): Promise<any>{
  return this.getData().then((products: any[]) => {
    products.push(data);
    return this.storage.set('products', products);
  });
}


问:
Entity Framework Core 2.0 on .NET 4.6.1
Microsoft just announced that Entity Framework Core 2.0 will now run on .NET Standard 2.0.

.Net Standard 2.0 is compatible (if that's the right term here) with .NET Framework 4.6.1.

However when I try add the latest NuGet package I get an error telling me that I'm using the wrong version:

```<code> Install-Package : Could not install package
 'Microsoft.EntityFrameworkCore.SqlServer 2.0.0-preview2-25332'. You are
 trying to install this package into a project that targets
 '.NETFramework,Version=v4.6.1', but
 the package does not contain any assembly references or content files
 that are compatible with that framework.
</code>```

If according to the announcement I can use EF Core 2.0 with .NET Framework 4.6.1, can someone please explain, and if possible give an example of what that would look like.

答:
It seems that in order to include .NET Standard 2.0 libraries within a .NET 4.6.1 project you need to include the NetStandard.Library.NetFramework NuGet package.

Example of current version in the packages.config file:

```<code><package id="NETStandard.Library.NETFramework" version="2.0.0-preview1-25305-02" targetFramework="net461" />
</code>```

Title: Entity Framework Core 2.0 on .NET 4.6.1

Body:
Microsoft just announced that Entity Framework Core 2.0 will now run on .NET Standard 2.0.

.Net Standard 2.0 is compatible (if that's the right term here) with .NET Framework 4.6.1.

However when I try add the latest NuGet package I get an error telling me that I'm using the wrong version:

 Install-Package : Could not install package
 'Microsoft.EntityFrameworkCore.SqlServer 2.0.0-preview2-25332'. You are
 trying to install this package into a project that targets
 '.NETFramework,Version=v4.6.1', but
 the package does not contain any assembly references or content files
 that are compatible with that framework.

If according to the announcement I can use EF Core 2.0 with .NET Framework 4.6.1, can someone please explain, and if possible give an example of what that would look like.

Body:
It seems that in order to include .NET Standard 2.0 libraries within a .NET 4.6.1 project you need to include the NetStandard.Library.NetFramework NuGet package.

Example of current version in the packages.config file:

<package id="NETStandard.Library.NETFramework" version="2.0.0-preview1-25305-02" targetFramework="net461" />


问:
SQL Server refactor a column from varchar(50) to uniqueidentifier and surrounding issues
I have a table message in a database that has almost a million rows. It has a externalId column which is varchar(50). The values stored in it are guid but I want to update this column to be uniqueidentifier.

So I think I am going to add a new column which is uniqueidentifier. Copy all the values across to this column and then drop the original column. Then I will rename this column to externalId.

My problem is there are hundreds of stored procs etc and I need to make sure that I don't break anything. I also have to grep through all the code and make changes so that we expect a Guid and not a string. (I am using C#)

Does anyone have some tips or recommendations?

Would I be better do just duplicate this column and not touch the existing column and make any code that does a select on it use the guid column instead of the string (currently it sometimes times-out!). I would also have to update any code then that inserts into this table to also insert a guid...)

I love legacy crap .......................

答:
The only real hint I can give you is to do it all at once.  Don't do this piece meal as you will have problems.

Add the column, copy the values, drop the old column, and rename the new one.  Then recompile all of your stored procedures.  This will give you a list of problem areas.  Fix them all and recompile.  If that part looks good, then move on to the code.  Being legacy you'll probably find a number of other issues here that you didn't even know about.

The code is going to be the toughest area.  Most likely the problems are going to involve runtime errors.  Make a test plan that covers absolutely everything and go through it.


问:
How to show updated data with update of model in angular 2?
i am currently working in pagination in angular 2. i am using  ng2-pagination for my purpose. what i have done so far is, i have shown data received through my api successfully. but when i click on next page button, data for next page fetched by calling again api for that page. but here problem occur, recieved data does not get updated in my view. can any body tell me how to update existing view with new data. my pagechanged function is,

```<code>pageChanged(event)
{
// alert(event)
this.p=event;
    this.httpService.getAllLaptops(event).subscribe(
    data => {
      const myArray = [];

      for (let key in data) {
        myArray.push(data[key]);

      }

      this.GetAllLaptop = myArray;

    }

  );

}
</code>```

and my view template

```<code>  <ul>
      <li *ngFor="let item of  GetAllLaptop[2] | paginate: { itemsPerPage: 10, currentPage:p,totalItems:GetAllLaptop[1] }"> {{item.SNR_Title}} </li>
    </ul>
     <pagination-controls (pageChange)="pageChanged($event)"

     directionLinks="true"
                      autoHide="true"
                      previousLabel="Previous"
                      nextLabel="Next"
                      screenReaderPaginationLabel="Pagination"></pagination-controls>
</code>```

on initially call, i received data and show it on view. but on page change event, data received for new page but view did not get updated. how can any update this view?
any help or suggestions are highly appreciated.

答:
Solved. That was my own mistake. i just used

```<code>this.ref.detectChanges();
  this.ref.reattach();
</code>```

and there was another problem with my api that was returning same data on every call.

Body:
i am currently working in pagination in angular 2. i am using  ng2-pagination for my purpose. what i have done so far is, i have shown data received through my api successfully. but when i click on next page button, data for next page fetched by calling again api for that page. but here problem occur, recieved data does not get updated in my view. can any body tell me how to update existing view with new data. my pagechanged function is,

pageChanged(event)
{
// alert(event)
this.p=event;
    this.httpService.getAllLaptops(event).subscribe(
    data => {
      const myArray = [];

      for (let key in data) {
        myArray.push(data[key]);

      }

      this.GetAllLaptop = myArray;

    }

  );

}

and my view template

 {{item.SNR_Title}}

     <pagination-controls (pageChange)="pageChanged($event)"

     directionLinks="true"
                      autoHide="true"
                      previousLabel="Previous"
                      nextLabel="Next"
                      screenReaderPaginationLabel="Pagination"></pagination-controls>

on initially call, i received data and show it on view. but on page change event, data received for new page but view did not get updated. how can any update this view?
any help or suggestions are highly appreciated.

Body:
Solved. That was my own mistake. i just used

this.ref.detectChanges();
  this.ref.reattach();

and there was another problem with my api that was returning same data on every call.


问:
LINQ query does not return child fields
I think I'm getting stupid because I can't get my LINQ query to work as I expect. I have one class that has 3 relationships to other classes.

This is the main class

```<code>[Table(Name = "scanResult")]
public class SniffResult
{
    public SniffResult()
    {

    }

    public SniffResult(Address address)
    {
        this.address = address;
    }

    private int _pk_SniffResult;

    [Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_SniffResult", Name ="pk_scanResult")]
    public int pk_SniffResult { get { return _pk_SniffResult; } set { this._pk_SniffResult = value; } }

    private int _fk_scan;

    [Column(Storage = "_fk_scan", Name = "scan")]
    public int fk_scan { get { return _fk_scan; } set { this._fk_scan = value; } }

    private Scan _scan;

    [Association(Storage = "_scan", IsForeignKey = true, ThisKey = "fk_scan", OtherKey = "pk_scan")]
    public Scan scan { get { return _scan; } set { this._scan = value; } }

    private int _fk_address;

    [Column(Storage = "_fk_address", Name = "address")]
    public int fk_adress { get { return _fk_address; } set { this._fk_address = value; } }

    private Address _address;

    [Association(Storage ="_address", IsForeignKey = true, ThisKey = "fk_adress", OtherKey = "pk_address")]
    public Address address { get { return _address; } set { this._address = value; } }

    private string _rawResult;

    [Column(Storage = "_rawResult", Name = "raw")]
    public string rawResult { get { return _rawResult; } set { this._rawResult = value; } }

    private int _code = -5;

    [Column(Storage = "_code")]
    public int code { get { return _code; } set { this._code = value; } }

    private DateTime _scanDate = DateTime.Now;

    [Column(Storage = "_scanDate")]
    public DateTime scanDate { get { return _scanDate; } set { this._scanDate = value; } }

    private int? _fk_proxy;

    [Column(Storage = "_fk_proxy", Name = "usedProxy", CanBeNull = true)]
    public int? fk_proxy { get { return _fk_proxy; } set { this._fk_proxy = value; } }

    private ProxyData _usedProxy;

    [Association(Storage = "_usedProxy", IsForeignKey = true, ThisKey = "fk_proxy", OtherKey = "pk_proxy")]
    public ProxyData usedProxy { get { return _usedProxy; } set { this._usedProxy = value; } }

    public string message { get; set; } = "";

    public bool availability { get; set; }

    public int planCode { get; set; }

    public string planning { get; set; }

    public override string ToString()
    {
        return string.Format("availability={0}, code={1}, message={2}", availability, code, message);
    }
}
</code>```

This is one of the child classes

```<code>[Table(Name = "address")]
public class Address
{
    private int _pk_address;

    [Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_address")]
    public int pk_address { get { return _pk_address; } set { this._pk_address = value; } }

    private string _provId;

    [Column(Storage = "_provId")]
    public string provId { get { return _provId; } set { this._provId = value; } }

    private string _zipcode;

    [Column(Storage = "_zipcode")]
    public string zipcode { get { return _zipcode; } set { this._zipcode = value; } }

    private int _houseNumber;

    [Column(Storage = "_houseNumber")]
    public int houseNumber { get { return _houseNumber; } set { this._houseNumber = value; } }

    private string _addressAddition;

    [Column(Storage = "_addressAddition")]
    public string addressAddition { get { return _addressAddition; } set { this._addressAddition = value; } }

    public string ToAddresString()
    {
        return string.Format("{0} {1}{2}", this.provId, zipcode, houseNumber, addressAddition);
    }

    public override string ToString()
    {
        return string.Format("{0}:\t{1}\t{2}{3}", this.provId, zipcode, houseNumber, addressAddition);
    }
}
</code>```

I want to get SniffResult including the associated fields. But they are all null. This is the code I use:

```<code>         SniffDAO dao = new SniffDAO();

         var test =  from sr in dao.SniffResults
                    where sr.fk_scan == 3
                    select sr;

        foreach (var one in test)
        {
            Console.WriteLine(one.pk_SniffResult);
            Console.WriteLine(one.address);
        }
</code>```

one.address gives me a null, what am I doing wrong?

This is the Dao class

```<code>public class SniffDAO
{
    private string currentDir;
    private DataContext db;
    public Table<Scan> Scans { get; set; }
    public Table<SniffResult> SniffResults { get; set; }
    public Table<Address> Addresses { get; set; }

    public SniffDAO()
    {
        db = new DataContext(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=********;Integrated Security=True;Asynchronous Processing=True");

        db.ObjectTrackingEnabled = true;

        Scans = db.GetTable<Scan>();
        SniffResults = db.GetTable<SniffResult>();
        Addresses = db.GetTable<Address>();

        currentDir = Directory.GetCurrentDirectory();
    }

    public void save()
    {
        db.SubmitChanges();
    }

}
</code>```

答:
I found the solution thanks to @Kris. I now use:

```<code>        DataLoadOptions dlo = new DataLoadOptions();
        dlo.LoadWith<SniffResult>(sr => sr.address);
        dlo.LoadWith<SniffResult>(sr => sr.usedProxy);
        dlo.LoadWith<SniffResult>(sr => sr.scan);

        db.LoadOptions = dlo; //db is the DataContext
</code>```

See https://msdn.microsoft.com/en-us/library/bb548760(v=vs.110).aspx for more info

Title: LINQ query does not return child fields

Body:
I think I'm getting stupid because I can't get my LINQ query to work as I expect. I have one class that has 3 relationships to other classes.

This is the main class

[Table(Name = "scanResult")]
public class SniffResult
{
    public SniffResult()
    {

    }

    public SniffResult(Address address)
    {
        this.address = address;
    }

    private int _pk_SniffResult;

    [Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_SniffResult", Name ="pk_scanResult")]
    public int pk_SniffResult { get { return _pk_SniffResult; } set { this._pk_SniffResult = value; } }

    private int _fk_scan;

    [Column(Storage = "_fk_scan", Name = "scan")]
    public int fk_scan { get { return _fk_scan; } set { this._fk_scan = value; } }

    private Scan _scan;

    [Association(Storage = "_scan", IsForeignKey = true, ThisKey = "fk_scan", OtherKey = "pk_scan")]
    public Scan scan { get { return _scan; } set { this._scan = value; } }

    private int _fk_address;

    [Column(Storage = "_fk_address", Name = "address")]
    public int fk_adress { get { return _fk_address; } set { this._fk_address = value; } }

    private Address _address;

    [Association(Storage ="_address", IsForeignKey = true, ThisKey = "fk_adress", OtherKey = "pk_address")]
    public Address address { get { return _address; } set { this._address = value; } }

    private string _rawResult;

    [Column(Storage = "_rawResult", Name = "raw")]
    public string rawResult { get { return _rawResult; } set { this._rawResult = value; } }

    private int _code = -5;

    [Column(Storage = "_code")]
    public int code { get { return _code; } set { this._code = value; } }

    private DateTime _scanDate = DateTime.Now;

    [Column(Storage = "_scanDate")]
    public DateTime scanDate { get { return _scanDate; } set { this._scanDate = value; } }

    private int? _fk_proxy;

    [Column(Storage = "_fk_proxy", Name = "usedProxy", CanBeNull = true)]
    public int? fk_proxy { get { return _fk_proxy; } set { this._fk_proxy = value; } }

    private ProxyData _usedProxy;

    [Association(Storage = "_usedProxy", IsForeignKey = true, ThisKey = "fk_proxy", OtherKey = "pk_proxy")]
    public ProxyData usedProxy { get { return _usedProxy; } set { this._usedProxy = value; } }

    public string message { get; set; } = "";

    public bool availability { get; set; }

    public int planCode { get; set; }

    public string planning { get; set; }

    public override string ToString()
    {
        return string.Format("availability={0}, code={1}, message={2}", availability, code, message);
    }
}

This is one of the child classes

[Table(Name = "address")]
public class Address
{
    private int _pk_address;

    [Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_address")]
    public int pk_address { get { return _pk_address; } set { this._pk_address = value; } }

    private string _provId;

    [Column(Storage = "_provId")]
    public string provId { get { return _provId; } set { this._provId = value; } }

    private string _zipcode;

    [Column(Storage = "_zipcode")]
    public string zipcode { get { return _zipcode; } set { this._zipcode = value; } }

    private int _houseNumber;

    [Column(Storage = "_houseNumber")]
    public int houseNumber { get { return _houseNumber; } set { this._houseNumber = value; } }

    private string _addressAddition;

    [Column(Storage = "_addressAddition")]
    public string addressAddition { get { return _addressAddition; } set { this._addressAddition = value; } }

    public string ToAddresString()
    {
        return string.Format("{0} {1}{2}", this.provId, zipcode, houseNumber, addressAddition);
    }

    public override string ToString()
    {
        return string.Format("{0}:\t{1}\t{2}{3}", this.provId, zipcode, houseNumber, addressAddition);
    }
}

I want to get SniffResult including the associated fields. But they are all null. This is the code I use:

         SniffDAO dao = new SniffDAO();

         var test =  from sr in dao.SniffResults
                    where sr.fk_scan == 3
                    select sr;

        foreach (var one in test)
        {
            Console.WriteLine(one.pk_SniffResult);
            Console.WriteLine(one.address);
        }

one.address gives me a null, what am I doing wrong?

This is the Dao class

public class SniffDAO
{
    private string currentDir;
    private DataContext db;
    public Table<Scan> Scans { get; set; }
    public Table<SniffResult> SniffResults { get; set; }
    public Table<Address> Addresses { get; set; }

    public SniffDAO()
    {
        db = new DataContext(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=********;Integrated Security=True;Asynchronous Processing=True");

        db.ObjectTrackingEnabled = true;

        Scans = db.GetTable<Scan>();
        SniffResults = db.GetTable<SniffResult>();
        Addresses = db.GetTable<Address>();

        currentDir = Directory.GetCurrentDirectory();
    }

    public void save()
    {
        db.SubmitChanges();
    }

}

Body:
I found the solution thanks to @Kris. I now use:

        DataLoadOptions dlo = new DataLoadOptions();
        dlo.LoadWith<SniffResult>(sr => sr.address);
        dlo.LoadWith<SniffResult>(sr => sr.usedProxy);
        dlo.LoadWith<SniffResult>(sr => sr.scan);

        db.LoadOptions = dlo; //db is the DataContext

See https://msdn.microsoft.com/en-us/library/bb548760(v=vs.110).aspx for more info


问:
Showing the same file in both columns of a Sublime Text window
When I have 2 columns set in a Sublime Text window, can I display the same file in both columns?</p>

答:
It is possible to edit same file in Split mode.
It is best explained in following youtube video.

https://www.youtube.com/watch?v=q2cMEeE1aOk

ContentLicense: CC BY-SA 4.0


问:
HowTo define soname in Code::Blocks
I have created a shared library with Code::Blocks under Linux and now I need to update it to a newer version and I want/need to increment its version.

If I were to use command line I would use a parameter like -Wl soname my_lib.so.2.0.1 but cannot find how to do it under Code:Blocks IDE

Any ideas/help?

thnx

答:
In your project Build options -> Linker settings -> Other linker options
enter, e.g.

```<code>-Wl,-soname=my_lib.so.2.0.1
</code>```

Then OK out and build.

Title: HowTo define soname in Code::Blocks

Body:
In your project Build options -> Linker settings -> Other linker options
enter, e.g.

-Wl,-soname=my_lib.so.2.0.1

Then OK out and build.


问:
Where to find available locale's and their information?
I am going to develop a Number Field component using jQuery. In that component, I need to find the thousandSeparator, decimalSeparator, and decimalPrecision based on the user locale given (like en-US, de-DE and etc....). I have tried using toLocaleString method but browser compatibility (Safari and IE) is missing. I didn't find any Web Contents containing a list of locales and their information in key-value pairs. Where can I find the same on the website? I don't want to use any external plugins and browser compatibility compromises. Assist me, please...Also, I don't know what are the available locales?

答: Unicode Consortium is responsible for updating locale related information. They are maintaining a repository called Common Locale Data Repository(CLDR). We can get the information about available locales and formats used in each locale with the help of their website.


问:
Email validation, using if else statements wont allow it to continue checking if there was an error with the first if?
I have:

```<code>if(isset($_POST['submit'])) {
    if (empty($name)) {
        echo'<span class="error">ERROR: Missing Name </span><br/>';
    } else if(empty($phone) || empty($email)) {
        echo'<span class="error">ERROR: You must insert a phone number or email</span><br/>';
    } else if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'<span class="error">ERROR: Please Insert a valid Email</span><br/>';
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'<span id="valid">Message has been sent</span><br/>';
    }
}
</code>```

How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.

Any ideas? Thank you

答: Use a dirty flag.  Check them all and append the message to the dirty variable.</p>

Body:
I have:

if(isset($_POST['submit'])) {
    if (empty($name)) {
        echo'ERROR: Missing Name
';
    } else if(empty($phone) || empty($email)) {
        echo'ERROR: You must insert a phone number or email
';
    } else if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'ERROR: Please Insert a valid Email
';
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'Message has been sent
';
    }
}

How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.

Any ideas? Thank you


问:
How to add two List<Class> together in c#?
I have two List<Student> that I want to concat.

Student is just a class that contains a few properties.

I also have another Form that creates the Student and populates a List<Student>

From there, when the StudentCreator closes, I want the List<Student> in StudentCreator to be concated to the List<Student> in the main form. Effectively updating the main list.

This is the main bit of code I'm having trouble with, I get an error saying I can't convert some IEnumerable<something> to List<something>

```<code>private void update_students(addStudent s)
        {
            Form activeForm = Form.ActiveForm;
            if(activeForm == this)
            {
                tempList = s.StudentList;
                studentList_HomeForm = tempList.Concat(tempList);
            }
        }
</code>```

This is the main line that gives the error

```<code>tempList.Concat(tempList)
</code>```

How do I fix this error?

答:
tempList.Concat returns an enumerable, something you can iterate over. If you want to transform that into a list, you can call ToList():

```<code>var newList = tempList.Concat(tempList).ToList();
// you are basically copying the same list... is this intentional?
</code>```

Another approach you could take is creating a new list, iterate over the existing lists and add them to the newly created list:

```<code>List<Student> newList = new List<Student>(firstList); // start of by copying list 1

// Add every item from list 2, one by one
foreach (Student s in secondList)
{
    newList.Add(s);
}

// Add every item from list 2, at once
newList.AddRange(secondList);
</code>```

Body:
I have two List<Student> that I want to concat.

Student is just a class that contains a few properties.

I also have another Form that creates the Student and populates a List<Student>

From there, when the StudentCreator closes, I want the List<Student> in StudentCreator to be concated to the List<Student> in the main form. Effectively updating the main list.

This is the main bit of code I'm having trouble with, I get an error saying I can't convert some IEnumerable<something> to List<something>

private void update_students(addStudent s)
        {
            Form activeForm = Form.ActiveForm;
            if(activeForm == this)
            {
                tempList = s.StudentList;
                studentList_HomeForm = tempList.Concat(tempList);
            }
        }

This is the main line that gives the error

tempList.Concat(tempList)

How do I fix this error?

Body:
tempList.Concat returns an enumerable, something you can iterate over. If you want to transform that into a list, you can call ToList():

var newList = tempList.Concat(tempList).ToList();
// you are basically copying the same list... is this intentional?

Another approach you could take is creating a new list, iterate over the existing lists and add them to the newly created list:

List<Student> newList = new List<Student>(firstList); // start of by copying list 1

// Add every item from list 2, one by one
foreach (Student s in secondList)
{
    newList.Add(s);
}

// Add every item from list 2, at once
newList.AddRange(secondList);


问:
PPT - chart data label alignment using PPTX4J
I'm using docx4j - pptx4j to update chart values in a PPT.

The values are getting updated , but the problem is the data label alignment is a mess post update.

What could be done to align label to the best possible position??

Thanks in advance :)

答:
After exploring for long time, I found the solution for my problem.

When i unzipped the ppt file and check that particular chart's XML, there was tag like below

```<code>        <c:layout>
            <c:manualLayout>
                <c:xMode val="edge" />
                <c:yMode val="edge" />
                <c:x val="0.37500645045178749" />
                <c:y val="0.19924874413552776" />
            </c:manualLayout>
        </c:layout>
</code>```

and removing the manual layout solved the issue :)

Body:
After exploring for long time, I found the solution for my problem.

When i unzipped the ppt file and check that particular chart's XML, there was tag like below

        <c:layout>
            <c:manualLayout>
                <c:xMode val="edge" />
                <c:yMode val="edge" />
                <c:x val="0.37500645045178749" />
                <c:y val="0.19924874413552776" />
            </c:manualLayout>
        </c:layout>

and removing the manual layout solved the issue :)


问:
How do I get clicked item position of a listView which contains WebView in each row on Android?
```<code>chatListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                       Toast.makeText(ChatActivity.this, "Position" + " " + i, Toast.LENGTH_SHORT).show();
            }
        );
</code>```

not working

only ontouch is working but how to get position

```<code>chatListView.setOnTouchListener(new View.OnTouchListener() {
</code>```

答:
You can try this in your ListView Item Click Listener

```<code>String selectedFromList =(listcontent.getItemAtPosition(position).toString());
</code>```

This will get the position of the item and you can then get the view

Body:
chatListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                       Toast.makeText(ChatActivity.this, "Position" + " " + i, Toast.LENGTH_SHORT).show();
            }
        );

not working

only ontouch is working but how to get position

chatListView.setOnTouchListener(new View.OnTouchListener() {

Body:
You can try this in your ListView Item Click Listener

String selectedFromList =(listcontent.getItemAtPosition(position).toString());

This will get the position of the item and you can then get the view


问:
How to mix persistent and transient state of a domain object?
I'm looking for a pattern/method do cleanly solve the following problem :

In a on-screen display application (various information is displayed on LCD screens in public places), I have Hibernate persistent POJOs, that can be created and updated in the administration part of my app.

In the "display" part, which is read-only, I use these objects. They must be always up-to-date with the persisted state, but they also have a transient state (that is never stored in the DB) for which the lifespan is the whole user (HTTP) session (can last a whole day or more) and which is specific to each session/user (here a "user" is a screen).

How to (cleanly) combine both states in order to maintain the transient state in-memory (in the HTTP session), while regularly refreshing the persistent state from the DB ? Use the same class and do Hibernate session.refresh() when needed ? Store both states in different classes and link them e.g. with the ID ? Decorator pattern ?

答: Not sure I understand. If the object is read-only, what kind of information is transient? If the object is read-only, it will always be the same among all sessions. Maybe you mean that the object is not read-only, but it won't be persisted back to the server? </p>


问:
COUNT in CASE statement?
I would like to categorize records based on the count of one field.
My code is :

```<code> select `posts`.`post_customer_fs_id` AS `post_customer_fs_id`,count(`post_id`) AS `open_post_count`,
CASE count(`post_id`)
WHEN count(`post_id`)=1 THEN 'A'
WHEN count(`post_id`)>1 THEN 'B'
END AS AAA
from `posts` where (`posts`.`post_status` = '3') AND posts.post_type_id='1' group by `posts`.`post_customer_fs_id` ;
</code>```

For some reason I m receiving A for the records with COUNT 1 but NULL for the records with COUNT bigger than 1.
The post_id is an INTEGER field..
Any help it will be very appreciated!

答:
TRY :::</p>

```<code>select post_customer_fs_id AS 'post_customer_fs_id', count(post_id) AS 'open_post_count',
CASE
    WHEN count(post_id)=1 THEN 'A'
    WHEN count(post_id)>1 THEN 'B'
    ELSE 'C'
END AS 'AAA'
from posts where post_status = '3' AND post_type_id= '1'
group by post_customer_fs_id ;
</code>```

Title: COUNT in CASE statement?

Body:
I would like to categorize records based on the count of one field.
My code is :

 select `posts`.`post_customer_fs_id` AS `post_customer_fs_id`,count(`post_id`) AS `open_post_count`,
CASE count(`post_id`)
WHEN count(`post_id`)=1 THEN 'A'
WHEN count(`post_id`)>1 THEN 'B'
END AS AAA
from `posts` where (`posts`.`post_status` = '3') AND posts.post_type_id='1' group by `posts`.`post_customer_fs_id` ;

For some reason I m receiving A for the records with COUNT 1 but NULL for the records with COUNT bigger than 1.
The post_id is an INTEGER field..
Any help it will be very appreciated!

Body:
TRY :::

select post_customer_fs_id AS 'post_customer_fs_id', count(post_id) AS 'open_post_count',
CASE
    WHEN count(post_id)=1 THEN 'A'
    WHEN count(post_id)>1 THEN 'B'
    ELSE 'C'
END AS 'AAA'
from posts where post_status = '3' AND post_type_id= '1'
group by post_customer_fs_id ;


问:
Best way for local HTML file to communicate with (read/write) local .xlsm Excel file
I'm a teacher. My grade book is a .xlsm file, located in my Google Drive folder. I'm building a web app, also in my Drive folder, that shows the students names arranged according to the seating chart. I want to run the app on my Android phone, and click a student's name to add a participation mark to the grade book. The app should also display the students' existing participation scores (from the grade book). What is the best way to go about accomplishing something like this?

*I initially tried to do this using another .xlsm file but, when I realized that macros don't run on the Android version of Excel, I switched to an HTML-based app. Was that the right decision?

Here is a sample .xlsm file. In this case, the app would check cell A2 to make sure it's the correct student and then both read and write to cell B2.

答:
Your best option is not to use Google Drive at all. If you are interested in doing something like you described, I would strongly recommend using either PHP and MySQL (a popular combination) or Google Cloud Platform's App Engine (they provide a lot of help, even allowing you to easily build an app that you can sign in to from your Android device with your Google account). If you're more in the mood for Do-It-Yourself, I would probably recommend Spring Boot (These tutorials look pretty good)

When it comes to integrating with Google Drive, it is technically possible to do, but so difficult that you would be much better off writing your own system from scratch and perhaps exporting to an Excel file. (See this page for a tutorial on exporting to Excel from Java)

You have several concerns with the final solution for your problem:

Security (You don't want students breaking into it, like I probably would have done)

Accessibility (You want to get at the information on your phone and your computer)

If I was in your position, I would probably write a Spring Boot application (which can house it's own database, website and API for a computer/phone to communicate with) and an Android application that talks to it.

Also, it would be helpful to know what programming languages and/or libraries/frameworks you have used in the past in order to make better recommendations for your situation. What have you used in the past?

If you need help or have questions, just message or comment.


问:
pytorch custom layer "is not a Module subclass"
I am new to PyTorch, trying it out after using a different toolkit for a while.

I would like understand how to program custom layers and functions. And as a simple test, I wrote this:

```<code>class Testme(nn.Module):         ## it _is_ a sublcass of module ##
    def __init__(self):
        super(Testme, self).__init__()

    def forward(self, x):
        return x / t_.max(x)
</code>```

which is intended to cause the data passing through it to sum to 1. Not actually useful, just at test.

Then I plug it to the example code from the PyTorch Playground:

```<code>def make_layers(cfg, batch_norm=False):
    layers = []
    in_channels = 3
    for i, v in enumerate(cfg):
        if v == 'M':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
            padding = v[1] if isinstance(v, tuple) else 1
            out_channels = v[0] if isinstance(v, tuple) else v
            conv2d = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=padding)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(out_channels, affine=False), nn.ReLU()]
            else:
                layers += [conv2d, nn.ReLU()]
            layers += [Testme]                           # here <------------------
            in_channels = out_channels
    return nn.Sequential(*layers)
</code>```

The result is an error!

```<code>TypeError: model.Testme is not a Module subclass
</code>```

Maybe this needs to be a Function rather than a Module? Also not clear what the difference is between Function, Module.

For example, why does a Function need a backward(), even if it is constructed entirely from standard pytorch primitive, whereas a Module does not need this?

答:
That's a simple one. You almost got it, but you forgot to actually create an instance of your new class Testme. You need to do this, even if the creation of an instance of a particular class doesn't take any parameters (as for Testme). But it's easier to forget than for a convolutional layer, to which you typically pass a lot of arguments.

Change the line you have indicated to the following and your problem is resolved.

```<code>layers += [Testme()]
</code>```

Body:
I am new to PyTorch, trying it out after using a different toolkit for a while.

I would like understand how to program custom layers and functions. And as a simple test, I wrote this:

class Testme(nn.Module):         ## it _is_ a sublcass of module ##
    def __init__(self):
        super(Testme, self).__init__()

    def forward(self, x):
        return x / t_.max(x)

which is intended to cause the data passing through it to sum to 1. Not actually useful, just at test.

Then I plug it to the example code from the PyTorch Playground:

def make_layers(cfg, batch_norm=False):
    layers = []
    in_channels = 3
    for i, v in enumerate(cfg):
        if v == 'M':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
            padding = v[1] if isinstance(v, tuple) else 1
            out_channels = v[0] if isinstance(v, tuple) else v
            conv2d = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=padding)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(out_channels, affine=False), nn.ReLU()]
            else:
                layers += [conv2d, nn.ReLU()]
            layers += [Testme]                           # here <------------------
            in_channels = out_channels
    return nn.Sequential(*layers)

The result is an error!

TypeError: model.Testme is not a Module subclass

Maybe this needs to be a Function rather than a Module? Also not clear what the difference is between Function, Module.

For example, why does a Function need a backward(), even if it is constructed entirely from standard pytorch primitive, whereas a Module does not need this?

Body:
That's a simple one. You almost got it, but you forgot to actually create an instance of your new class Testme. You need to do this, even if the creation of an instance of a particular class doesn't take any parameters (as for Testme). But it's easier to forget than for a convolutional layer, to which you typically pass a lot of arguments.

Change the line you have indicated to the following and your problem is resolved.

layers += [Testme()]


问:
Java toString() using reflection?
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.

Getting the field names is fairly simple, here is what a co-worker came up with:

```<code>public static List initFieldArray(String className) throws ClassNotFoundException {

    Class c = Class.forName(className);
    Field field[] = c.getFields();
    List<String> classFields = new ArrayList(field.length);

    for (int i = 0; i < field.length; i++) {
        String cf = field[i].toString();
        classFields.add(cf.substring(cf.lastIndexOf(".") + 1));
    }

    return classFields;
}
</code>```

Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.

Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.

答: Not reflection, but I had a look at generating the toString method (along with equals/hashCode) as a post-compilation step using bytecode manipulation. Results were mixed.</p>

OwnerDisplayName: nemo

Title: Java toString() using reflection?

Body:
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.

Getting the field names is fairly simple, here is what a co-worker came up with:

public static List initFieldArray(String className) throws ClassNotFoundException {

    Class c = Class.forName(className);
    Field field[] = c.getFields();
    List<String> classFields = new ArrayList(field.length);

    for (int i = 0; i < field.length; i++) {
        String cf = field[i].toString();
        classFields.add(cf.substring(cf.lastIndexOf(".") + 1));
    }

    return classFields;
}

Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.

Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.

OwnerDisplayName: McDowell


问:
Drupal : How to remove default.css in the .module file?
Is it possible to remove the module/system/default.css file. I'd like to do this in the .module file and not in the template.php file.

My goal is to disable this style in my drupal website without manipulating a template/theme.

Is it possible?

Thanks in advance,

Bat

答:
This is possible. You can use template_preprocess_page in your custom module to whack Drupal's default CSS:

```<code>function mymodule_preprocess_page(&$vars) {
  // Get CSS array and remove selected stylesheets
  $css = drupal_add_css();
  unset($css['all']['module']['modules/system/defaults.css']);

  // Override Drupal styles
  $vars['styles'] = drupal_get_css($css);
}
</code>```

Because of Drupal's architecture, you'll almost certainly need to set the module weight to something greater than your other installed modules to ensure that your preprocessor runs last and no other module will be adding CSS.

Body:
This is possible. You can use template_preprocess_page in your custom module to whack Drupal's default CSS:

function mymodule_preprocess_page(&$vars) {
  // Get CSS array and remove selected stylesheets
  $css = drupal_add_css();
  unset($css['all']['module']['modules/system/defaults.css']);

  // Override Drupal styles
  $vars['styles'] = drupal_get_css($css);
}

Because of Drupal's architecture, you'll almost certainly need to set the module weight to something greater than your other installed modules to ensure that your preprocessor runs last and no other module will be adding CSS.


问:
how to add padding top in CSS pseudo element class::after
I want to add padding top to ::after and want to make it centered.

But it's not happening, this is what I get :

After using this css :

```<code>.list-unstyled li::after {
content: url(images/heartborder.png)
text-align:center;
padding-top: 30px;
}
</code>```

and this is my HTML CODE :

View / Edit Profile

You can view or edit your profile from here. Phone no., address, other information etc. etc.

```

答:
you need to add semicolon after content: url(images/heartborder.png) attribute

OR

I think you need to do like this:

```<code>.list-unstyled li::after {
    content: url(images/heartborder.png);
    text-align: center;
    padding-top: 30px;
}
</code>```

Body:
I want to add padding top to ::after and want to make it centered.

But it's not happening, this is what I get :

After using this css :

.list-unstyled li::after {
content: url(images/heartborder.png)
text-align:center;
padding-top: 30px;
}

and this is my HTML CODE :

View / Edit Profile

You can view or edit your profile from here. Phone no., address, other information etc. etc.

Body:
you need to add semicolon after content: url(images/heartborder.png) attribute

OR

I think you need to do like this:

.list-unstyled li::after {
    content: url(images/heartborder.png);
    text-align: center;
    padding-top: 30px;
}


问:
Adding a custom directive to ng-grid

Can i add a custom directive to the input cell of the ng-grid..Can someone help me , i searched it but was unable to find Thanks for any help

Here is reference of ng-grid

```<code>https://angular-ui.github.io/ui-grid/
</code>```

答:
You can try to use custom editable cell templates like: </p>

```<code>{
    field: 'name',
    cellClass: 'nameCell',
    headerClass: 'nameHeader',
    editableCellTemplate: '<div your-custom-directive>' +
    '<form name="inputForm">' +
    '<input type="number" ng-class="\'colt\' + col.uid" ui-grid-editor ng-model="MODEL_COL_FIELD">' +
    '</form>' +
    '</div>'
}
</code>```

Title: Adding a custom directive to ng-grid

Body:
Can i add a custom directive to the input cell of the ng-grid..Can someone help me , i searched it but was unable to find Thanks for any help

Here is reference of ng-grid

https://angular-ui.github.io/ui-grid/

Body:
You can try to use custom editable cell templates like:

{
    field: 'name',
    cellClass: 'nameCell',
    headerClass: 'nameHeader',
    editableCellTemplate: '<div your-custom-directive>' +
    '<form name="inputForm">' +
    '<input type="number" ng-class="\'colt\' + col.uid" ui-grid-editor ng-model="MODEL_COL_FIELD">' +
    '</form>' +
    '</div>'
}


问:
How to Connect two tables in derby SQL
I am working on a project for getting my degree from university, as i am fresh graduated student of Computer Science, and i have a problem that how to connect two tables in SQL Netbeans java Derby database connection.

Thanks;

答:
Guessing you means joins- look at this it explains the different types well:

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

Title: How to Connect two tables in derby SQL


问:
How can I start php-fpm in a Docker container by default?
I have this Docker image -

```<code>FROM centos:7
MAINTAINER Me <me.me>
RUN yum update -y
RUN yum install -y git https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

RUN yum install -y ansible
RUN git clone https://github.com/.../dockerAnsible.git
RUN ansible-playbook dockerFileBootstrap.yml
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;

VOLUME [ "/sys/fs/cgroup" ]
EXPOSE 80 443 3306

CMD ["/usr/sbin/httpd", "-D", "FOREGROUND"]
</code>```

Basically, I want it so that php-fpm starts when the docker container starts.  I have php-fpm working if I manually go into the container and turn it on with /usr/sbin/php-fpm.

I tried it inside of my ansible file with this command (it didn't work).  I tried using the service module as well with no luck.-

```<code> - name: Start php fpm
   command: /usr/sbin/php-fpm
</code>```

How can I have php-fpm running along with apache?

答:
I needed similar thing recently. For alpine linux images it sufficed to run both php-fpm and a web server as the container command. Defined in Dockerfile somewhat like this:

```<code>CMD /usr/bin/php-fpm -D; nginx
</code>```

ie. to daemonize php-fpm and then run nginx in foreground.

On ubuntu/debian images there is also necessary to allow starting recently installed packages by running a Dockerfile RUN command like this:

```<code>RUN echo "exit 0" > /usr/sbin/policy-rc.d
</code>```

and then restart the php-fpm within a CMD command

```<code>CMD /etc/init.d/php7.0-fpm restart && nginx -g "daemon off;"
</code>```

More on policy-rc.d to be found in this askubuntu question

Body:
I have this Docker image -

FROM centos:7
MAINTAINER Me <me.me>
RUN yum update -y
RUN yum install -y git https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

RUN yum install -y ansible
RUN git clone https://github.com/.../dockerAnsible.git
RUN ansible-playbook dockerFileBootstrap.yml
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;

VOLUME [ "/sys/fs/cgroup" ]
EXPOSE 80 443 3306

CMD ["/usr/sbin/httpd", "-D", "FOREGROUND"]

Basically, I want it so that php-fpm starts when the docker container starts.  I have php-fpm working if I manually go into the container and turn it on with /usr/sbin/php-fpm.

I tried it inside of my ansible file with this command (it didn't work).  I tried using the service module as well with no luck.-

 - name: Start php fpm
   command: /usr/sbin/php-fpm

How can I have php-fpm running along with apache?

Body:
I needed similar thing recently. For alpine linux images it sufficed to run both php-fpm and a web server as the container command. Defined in Dockerfile somewhat like this:

CMD /usr/bin/php-fpm -D; nginx

ie. to daemonize php-fpm and then run nginx in foreground.

On ubuntu/debian images there is also necessary to allow starting recently installed packages by running a Dockerfile RUN command like this:

RUN echo "exit 0" > /usr/sbin/policy-rc.d

and then restart the php-fpm within a CMD command

CMD /etc/init.d/php7.0-fpm restart && nginx -g "daemon off;"

More on policy-rc.d to be found in this askubuntu question


问:
Hybrid web app - Android / iOS/ Amazon Fire TV
I need to create a hybrid web app for Android, iOS and Amazon fire tv. Does anyone know a platform I can use to support all 3 of these in one place?

I've looked at Cordova and there used to be specific docs for all these platforms, now it only contains Android and iOS. Does anyone know if Android would cover Amazon Fire TV as well?

If Cordova isn't the option then any other suggestions are welcome!

答:
Cordova is a great way to create an app for Fire TV and, just by adding the Android platform to your setup, you should cover both Android and Fire TV

```<code>cordova platform add android
</code>```

When the application runs on Fire TV, it will use the Amazon Webview which is an optimised version of the Android webview so you might see subtle differences performance wise.

One thing worth noting is that building cross platforms apps that provide a great user experience on TV can be tricky. You should not use the same UI as your iOS or mobile Android app as this will result in poor interactions on a 10-foot UI, you should map the remote keys appropriately and ensure the viewport and your CSS respond well to either 720p or 1080p.

More info on UI/UX on TV devices can be found on the Developer Portal.

In addition to that, have a look at the docs available on Building web apps on Fire TV, the Appstore allows you to submit your web app in 3 ways:

Hosted - you submit the URL to your webapp and the Appstore will automatically package it with a Cordova-like wrapper

ZIP - you upload the zip file containing the HTML/CSS/JS and media files and the Appstore will automatically package it with a Cordova-like wrapper

Traditional - you create a new "Android app" in your console and upload your packaged Cordova APK

You should also consider using some frameworks that are already optimised for TV experiences, like the Web App Starter Kit.

Body:
Cordova is a great way to create an app for Fire TV and, just by adding the Android platform to your setup, you should cover both Android and Fire TV

cordova platform add android

When the application runs on Fire TV, it will use the Amazon Webview which is an optimised version of the Android webview so you might see subtle differences performance wise.

One thing worth noting is that building cross platforms apps that provide a great user experience on TV can be tricky. You should not use the same UI as your iOS or mobile Android app as this will result in poor interactions on a 10-foot UI, you should map the remote keys appropriately and ensure the viewport and your CSS respond well to either 720p or 1080p.

More info on UI/UX on TV devices can be found on the Developer Portal.

In addition to that, have a look at the docs available on Building web apps on Fire TV, the Appstore allows you to submit your web app in 3 ways:

Hosted - you submit the URL to your webapp and the Appstore will automatically package it with a Cordova-like wrapper

ZIP - you upload the zip file containing the HTML/CSS/JS and media files and the Appstore will automatically package it with a Cordova-like wrapper

Traditional - you create a new "Android app" in your console and upload your packaged Cordova APK

You should also consider using some frameworks that are already optimised for TV experiences, like the Web App Starter Kit.


答:
use:</p>

```<code>$error = 0;
if(empty($var1)){ $error = 1; }
if(empty($var2)){ $error = 1; }
if(empty($var3)){ $error = 1; }
if(empty($var4)){ $error = 1; }
if(empty($var5)){ $error = 1; }

if($error > 0)
{
   // Do actions for your errors
}
else
{
   // Send Email
}
</code>```

Title: Email validation, using if else statements wont allow it to continue checking if there was an error with the first if?

Body:
I have:

if(isset($_POST['submit'])) {
    if (empty($name)) {
        echo'ERROR: Missing Name
';
    } else if(empty($phone) || empty($email)) {
        echo'ERROR: You must insert a phone number or email
';
    } else if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'ERROR: Please Insert a valid Email
';
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'Message has been sent
';
    }
}

How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.

Any ideas? Thank you

Body:
use:

$error = 0;
if(empty($var1)){ $error = 1; }
if(empty($var2)){ $error = 1; }
if(empty($var3)){ $error = 1; }
if(empty($var4)){ $error = 1; }
if(empty($var5)){ $error = 1; }

if($error > 0)
{
   // Do actions for your errors
}
else
{
   // Send Email
}


问:
One-To-Many - How to Link to Objects correctly?
I'm using JPA and have some difficulties to understand how the One-To-Many Realtionship works.

I have the following two classes:

```<code>@Entity
public class myCheck {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    protected int Check_id;

    @Column
    private String name;

    @ManyToOne
    private mySystem system;

    @Override
    public String toString() {
        return this.name;
    }

    public int getId() {
        return Check_id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public mySystem getLinkSystem() {
        return system;
    }

    public void linkSystem(mySystem system) {
        this.system = system;
    }

}
</code>```

and:

```<code>@Entity
public class mySystem {
    @Id
    @GeneratedValue
    @Column(name = "system_id")
    protected int system_id;
    @Column
    public String name;

    @ManyToOne(cascade=CascadeType.ALL)
    private mySystem parent;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "system", fetch = FetchType.EAGER)
    private List<myCheck> checks;

    public mySystem() {
        //subSystems = new ArrayList<mySystem>();
        checks = new ArrayList<myCheck>();
    }

    public boolean linkCheck(myCheck hc) {
        return checks.add(hc);
    }

    public boolean unlinkCheck(myCheck hc) {
        return checks.remove(hc);
    }

    public List<myCheck> getlinkedChecks() {
        return checks;
    }

    public myCheck getLinkCheck(int hcId) {
        for (myCheck hc : checks) {
            if (hc.getId() == hcId)
                return hc;
        }
        return null;
    }

    public int getId() {
        return system_id;
    }

    public void setId(int id) {
        this.system_id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return this.getName();
    }

}
</code>```

Now I have an existing System in my database, which is loaded:

```<code>    // load System
    EntityManager entityManager1 = entityManagerFactory.createEntityManager();
    List<mySystem> systems = entityManager1.createQuery("from mySystem").getResultList();
    entityManager1.close();
</code>```

I want to add two new checks to Systems. What is working is:

```<code>    EntityManager entityManager2 = entityManagerFactory.createEntityManager();
    entityManager2.getTransaction().begin();

    myCheck check = new myCheck();
    check.setName("Check 1");
    check.linkSystem(systems.get(0));
    entityManager2.persist(check);

    myCheck check2 = new myCheck();
    check2.setName("Check 2");
    check2.linkSystem(systems.get(0));
    entityManager2.persist(check2);

    entityManager2.merge(systems.get(0));
    entityManager2.getTransaction().commit();
    entityManager2.close();
</code>```

But I can't do this:

```<code>    EntityManager entityManager2 = entityManagerFactory.createEntityManager();
    entityManager2.getTransaction().begin();

    myCheck check = new myCheck();
    check.setName("Check 1");
    systems.get(0).linkCheck(check);
    entityManager2.persist(check);

    myCheck check2 = new myCheck();
    check2.setName("Check 2");
    systems.get(0).linkCheck(check);
    entityManager2.persist(check2);

    entityManager2.merge(systems.get(0));
    entityManager2.getTransaction().commit();
    entityManager2.close();
</code>```

The second solution will save the checks, but I don't link them with the system.

Has someone a explanation for this? I really want to understand this.

答:
You have bidirectional relation which means each side of the relation should have a reference to the other side.

so in your persistence logic you will also need to inject the system in your check

```<code>myCheck check = new myCheck();
check.setName("Check 1");
check.linkSystem(systems.get(0);
systems.get(0).linkCheck(check);
entityManager2.persist(check);
</code>```

But in this case you will have a problem if your (systems.get(0)) is not attached to the persistence context because you will be having reference to deatached object when persisting the check, you can either put Cascade on the system inside check class or instead persist the system, it already cascades the check so the check will be persisted

Body:
I'm using JPA and have some difficulties to understand how the One-To-Many Realtionship works.

I have the following two classes:

@Entity
public class myCheck {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    protected int Check_id;

    @Column
    private String name;

    @ManyToOne
    private mySystem system;

    @Override
    public String toString() {
        return this.name;
    }

    public int getId() {
        return Check_id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public mySystem getLinkSystem() {
        return system;
    }

    public void linkSystem(mySystem system) {
        this.system = system;
    }

}

and:

@Entity
public class mySystem {
    @Id
    @GeneratedValue
    @Column(name = "system_id")
    protected int system_id;
    @Column
    public String name;

    @ManyToOne(cascade=CascadeType.ALL)
    private mySystem parent;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "system", fetch = FetchType.EAGER)
    private List<myCheck> checks;

    public mySystem() {
        //subSystems = new ArrayList<mySystem>();
        checks = new ArrayList<myCheck>();
    }

    public boolean linkCheck(myCheck hc) {
        return checks.add(hc);
    }

    public boolean unlinkCheck(myCheck hc) {
        return checks.remove(hc);
    }

    public List<myCheck> getlinkedChecks() {
        return checks;
    }

    public myCheck getLinkCheck(int hcId) {
        for (myCheck hc : checks) {
            if (hc.getId() == hcId)
                return hc;
        }
        return null;
    }

    public int getId() {
        return system_id;
    }

    public void setId(int id) {
        this.system_id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return this.getName();
    }

}

Now I have an existing System in my database, which is loaded:

    // load System
    EntityManager entityManager1 = entityManagerFactory.createEntityManager();
    List<mySystem> systems = entityManager1.createQuery("from mySystem").getResultList();
    entityManager1.close();

I want to add two new checks to Systems. What is working is:

    EntityManager entityManager2 = entityManagerFactory.createEntityManager();
    entityManager2.getTransaction().begin();

    myCheck check = new myCheck();
    check.setName("Check 1");
    check.linkSystem(systems.get(0));
    entityManager2.persist(check);

    myCheck check2 = new myCheck();
    check2.setName("Check 2");
    check2.linkSystem(systems.get(0));
    entityManager2.persist(check2);

    entityManager2.merge(systems.get(0));
    entityManager2.getTransaction().commit();
    entityManager2.close();

But I can't do this:

    EntityManager entityManager2 = entityManagerFactory.createEntityManager();
    entityManager2.getTransaction().begin();

    myCheck check = new myCheck();
    check.setName("Check 1");
    systems.get(0).linkCheck(check);
    entityManager2.persist(check);

    myCheck check2 = new myCheck();
    check2.setName("Check 2");
    systems.get(0).linkCheck(check);
    entityManager2.persist(check2);

    entityManager2.merge(systems.get(0));
    entityManager2.getTransaction().commit();
    entityManager2.close();

The second solution will save the checks, but I don't link them with the system.

Has someone a explanation for this? I really want to understand this.

Body:
You have bidirectional relation which means each side of the relation should have a reference to the other side.

so in your persistence logic you will also need to inject the system in your check

myCheck check = new myCheck();
check.setName("Check 1");
check.linkSystem(systems.get(0);
systems.get(0).linkCheck(check);
entityManager2.persist(check);

But in this case you will have a problem if your (systems.get(0)) is not attached to the persistence context because you will be having reference to deatached object when persisting the check, you can either put Cascade on the system inside check class or instead persist the system, it already cascades the check so the check will be persisted


问:
Rails json/jbuilder - Group json view based on category
I have an web application maded in RoR.
I need to provide the json to an mobile App.
This is my code to generate the Json:

```<code>json.category do
 json.name monument.category.name
 json.monumento do
  json.name monument.name
  json.id monument.id
  json.pois monument.pois do |p|
   json.name p.name
  end
 end
end
</code>```

The output is:

```<code>{
    "category": {
        "name": "Igrejas",
        "monumento": {
            "name": "Igreja de Santa Maria do Olival",
            "id": 2,
            "pois": [{
                "name": "Igreja de Santa Maria do Olival"
            }]
        }
    }
},
{
    "category": {
        "name": "Igrejas",
        "monumento": {
            "name": "Igreja de São João Baptista",
            "id": 3,
            "pois": [{
                "name": "Igreja de São João Baptista"
            }]
        }
    }
},
{
    "category": {
        "name": "Igrejas",
        "monumento": {
            "name": "Igreja da Nossa Senhora da Graça",
            "id": 4,
            "pois": [{
                "name": "Igreja da Nossa Senhora da Graça"
            }]
        }
    }
},
</code>```

My Problem is that i need to group the categories.

something like this:

```<code>{
    "category": {
        "name": "Igrejas",
        "monumento": {
            "name": "Igreja de Santa Maria do Olival",
            "id": 2,
            "pois": [{
                "name": "Igreja de Santa Maria do Olival"
            }]
        },
        "monumento": {
            "name": "Igreja de São João Baptista",
            "id": 3,
            "pois": [{
                "name": "Igreja de São João Baptista"
            }]
        },

        "monumento": {
            "name": "Igreja da Nossa Senhora da Graça",
            "id": 4,
            "pois": [{
                "name": "Igreja da Nossa Senhora da Graça"
            }]
        }
    }
},
</code>```

Any ideas how can i solve this problem?

答:
You need to do something like this

In your controller,

```<code>@categories = Category.where(name: 'Igrejas').includes(monuments: :pois)
</code>```

In your view,

```<code>json.category @categories do |category|
  json.name category.name
  json.monuments category.monuments do |monument|
    json.name monument.name
    json.id monument.id
    json.pois monument.pois do |p|
      json.name p.name
    end
  end
end
</code>```

Body:
I have an web application maded in RoR.
I need to provide the json to an mobile App.
This is my code to generate the Json:

json.category do
 json.name monument.category.name
 json.monumento do
  json.name monument.name
  json.id monument.id
  json.pois monument.pois do |p|
   json.name p.name
  end
 end
end

The output is:

{
    "category": {
        "name": "Igrejas",
        "monumento": {
            "name": "Igreja de Santa Maria do Olival",
            "id": 2,
            "pois": [{
                "name": "Igreja de Santa Maria do Olival"
            }]
        }
    }
},
{
    "category": {
        "name": "Igrejas",
        "monumento": {
            "name": "Igreja de São João Baptista",
            "id": 3,
            "pois": [{
                "name": "Igreja de São João Baptista"
            }]
        }
    }
},
{
    "category": {
        "name": "Igrejas",
        "monumento": {
            "name": "Igreja da Nossa Senhora da Graça",
            "id": 4,
            "pois": [{
                "name": "Igreja da Nossa Senhora da Graça"
            }]
        }
    }
},

My Problem is that i need to group the categories.

something like this:

{
    "category": {
        "name": "Igrejas",
        "monumento": {
            "name": "Igreja de Santa Maria do Olival",
            "id": 2,
            "pois": [{
                "name": "Igreja de Santa Maria do Olival"
            }]
        },
        "monumento": {
            "name": "Igreja de São João Baptista",
            "id": 3,
            "pois": [{
                "name": "Igreja de São João Baptista"
            }]
        },

        "monumento": {
            "name": "Igreja da Nossa Senhora da Graça",
            "id": 4,
            "pois": [{
                "name": "Igreja da Nossa Senhora da Graça"
            }]
        }
    }
},

Any ideas how can i solve this problem?

Body:
You need to do something like this

In your controller,

@categories = Category.where(name: 'Igrejas').includes(monuments: :pois)

In your view,

json.category @categories do |category|
  json.name category.name
  json.monuments category.monuments do |monument|
    json.name monument.name
    json.id monument.id
    json.pois monument.pois do |p|
      json.name p.name
    end
  end
end


问:
Excel Sumifs Dynamic Sum Ranges and Criteria
I keep track of my personal budget by using Google Forms. Every time I spend money on something, I will submit a form that tracks what the expense was and how much it was. For example an entry could look like Gas -$24.00 or Groceries -$75.00. What I like about this is, when I get paid, I look at all my entries over the last pay period and I am able to adjust my budget accordingly.

Long story short, I have these form entries, which are all time-stamped, sync to an excel document on my computer. What I am trying to do is sum each 'category' (ie Gas, Groceries, etc) based on a range of dates.

For example, my form responses spreadsheet would look something like this:

```<code>     A          B            C
1    Timestamp  Envelope     Amount
2    5/26/2017  Groceries    $(50.00)
3    5/27/2017  Gas          $(30.00)
4    5/28/2017  Utilities    $(200.00)
5    6/5/2017   Gas          $(25.00)
6    6/5/2017   Pets         $(40.00)
7    6/6/2017   Groceries    $(75.00)
8    6/6/2017   Auto         $(40.00)
</code>```

Lets say I want to sum all the entries for 'Gas' in the last 10 days. So between 5/27/2017 and 6/6/2017, I want excel to automatically tell me I spent $55. Also, if I add a new entry tomorrow for -$20, Excel will automatically recalculate to include the new entry, but also exclude the entry on the 27th, since it's too old.

Any help would be greatly appreciated!

答:
Try this formula:

```<code>=SUMIFS(D4:D10,C4:C10,"Gas",$B$4:$B$10,">="&DATE(2017,5,27),B4:B10,"<="&TODAY())
</code>```

Let me know if that works for you.

Body:
I keep track of my personal budget by using Google Forms. Every time I spend money on something, I will submit a form that tracks what the expense was and how much it was. For example an entry could look like Gas -$24.00 or Groceries -$75.00. What I like about this is, when I get paid, I look at all my entries over the last pay period and I am able to adjust my budget accordingly.

Long story short, I have these form entries, which are all time-stamped, sync to an excel document on my computer. What I am trying to do is sum each 'category' (ie Gas, Groceries, etc) based on a range of dates.

For example, my form responses spreadsheet would look something like this:

     A          B            C
1    Timestamp  Envelope     Amount
2    5/26/2017  Groceries    $(50.00)
3    5/27/2017  Gas          $(30.00)
4    5/28/2017  Utilities    $(200.00)
5    6/5/2017   Gas          $(25.00)
6    6/5/2017   Pets         $(40.00)
7    6/6/2017   Groceries    $(75.00)
8    6/6/2017   Auto         $(40.00)

Lets say I want to sum all the entries for 'Gas' in the last 10 days. So between 5/27/2017 and 6/6/2017, I want excel to automatically tell me I spent $55. Also, if I add a new entry tomorrow for -$20, Excel will automatically recalculate to include the new entry, but also exclude the entry on the 27th, since it's too old.

Any help would be greatly appreciated!

Body:
Try this formula:

=SUMIFS(D4:D10,C4:C10,"Gas",$B$4:$B$10,">="&DATE(2017,5,27),B4:B10,"<="&TODAY())

Let me know if that works for you.


问:
Google chrome sync API?
Is there an API that allows accessing Google Chrome sync data, such as bookmarks, history and opened tabs, by a third-party web application, ideally using only client-side javascript?

Purpose

I am trying to write a self-contained HTML app, that can synchronize reading progress of webcomics across mobile and desktop devices. Ideally, such functionality would be redundant, as bookmarks in theory can fill that purpose. In practice however, especially mobile versions of Chrome lack the means to conveniently update bookmarks, and sorting mechanisms (e.g. sorting by last-modified date). Note that these issues only become apparent when following upwards of 50 webcomics, most of which at that point will only be caught up on very rarely.

Since this is meant as a hobby project, the cost of hosting a webservice or developing for iOS are prohibitive, thus the attempt to reuse existing cloud accounts of the user for synchronization.

Possible discontinued API

Until roughly one or two years ago, the Dolphin and Mercury browsers on iOS allowed synchronizing with Google Chrome directly, by authenticating the app for access to one's Google account. At that time both browsers required that bookmarks were synchronized without an encryption passphrase.

Then suddenly they both dropped this feature, and instead started providing their own synchronization extensions and servers (again, without end-to-end encryption).

So I fear, that Google might have once provided a limited public synchronization API, which was dropped within the last two years; I was however unable to verify even this.

答:
As far as I know they dropped support

We locked down access to chromesync scoped refresh tokens to address a security vulnerability. When we did so, we knew that this may break some 3P browsers which made use of chromesync scoped refresh tokens to leverage Chrome Sync for their users.

Chrome Sync has never officially been supported for 3P browsers. We do not intend to create a solution by which 3P browsers can whitelist themselves or their users so that they can get chromesync scoped refresh tokens. Note that Chromium for Android is technically considered a 3P browser.

Marking as WontFix, accordingly.

https://bugs.chromium.org/p/chromium/issues/detail?id=677887

Title: Google chrome sync API?


问:
Strange variable behaviour in Python
My first post here.

So I'm loading data into a variable called f1_data, then passing it to  pm.removeDC() function to do some signal processing, and keeping the result into the same variable. But then, I want to replace only the column 8, with the original f1_data that I called raw_data and I can't figure it out why it doesn't work. Here are the functions. Help anyone?

inside file pm.py

```<code>def removeDC(data):
    # define the filter
    butter_order = 2
    hp_cutoff_Hz = 1.0
    b, a = signal.butter(butter_order, hp_cutoff_Hz/(fs_Hz / 2.0), 'highpass')

    for i in range(1,9):
        data[:,i] = signal.lfilter(b, a, data[:,i], 0)

    return (data)

def get_epoch1(data, t_sec, epoch, f_tup, col):
#f_tup = (f_wdir, f_name, f_columns, out_save, out_dir, out_number, fig_width)
    f_name = f_tup[1]
    fig_width = f_tup[6]

    epoch_boolvector = (t_sec >= epoch[0][0]) & (t_sec <= epoch[0][1])
    epoch_timescale = t_sec[epoch_boolvector]
    epoch_data = data[epoch_boolvector]

    plt.figure(figsize=(fig_width,8), dpi=96)
    plt.plot(epoch_timescale, epoch_data[:,col]);
    plt.xlim(epoch_timescale[0], epoch_timescale[-1])
    plt.show()
    return (epoch_boolvector, epoch_timescale, epoch_data)
</code>```

inside main file

```<code>#load the whole data
(f1_data, f1_data_indices, f1_timescale) = pm.load_data(f1_wdir, f1_name)

raw_data = f1_data[:] #create copy of f1_data

(f1ep1_boolvector, f1ep1_timescale, f1ep1_data) = pm.get_epoch1(f1_data, f1_timescale, f1_epochs[1], f1_tup, 8)

#--- filter data to remove DC (1Hz)
f1_data = pm.removeDC(f1_data)

# replace only channel 8 with original data
f1_data[:,8] = raw_data[:,8]
(f1ep2_boolvector, f1ep2_timescale, f1ep2_data) = pm.get_epoch1(f1_data, f1_timescale, f1_epochs[1], f1_tup, 8)
</code>```

答:
The solution is import copy and use copy.deepcopy function.
For further info check this link:
 docs.python.org/2/library/copy.html

When I have raw_data = f1_data[:] I get, after pm.removeDC():

```<code> raw_data is f1_data: False
(raw_data == f1_data).all(): True
</code>```

But when I have raw_data = copy.deepcopy(f1_data) I get, after pm.removeDC():

```<code> raw_data is f1_data: False
(raw_data == f1_data).all(): False
</code>```

Title: Strange variable behaviour in Python

Body:
My first post here.

So I'm loading data into a variable called f1_data, then passing it to  pm.removeDC() function to do some signal processing, and keeping the result into the same variable. But then, I want to replace only the column 8, with the original f1_data that I called raw_data and I can't figure it out why it doesn't work. Here are the functions. Help anyone?

inside file pm.py

def removeDC(data):
    # define the filter
    butter_order = 2
    hp_cutoff_Hz = 1.0
    b, a = signal.butter(butter_order, hp_cutoff_Hz/(fs_Hz / 2.0), 'highpass')

    for i in range(1,9):
        data[:,i] = signal.lfilter(b, a, data[:,i], 0)

    return (data)

def get_epoch1(data, t_sec, epoch, f_tup, col):
#f_tup = (f_wdir, f_name, f_columns, out_save, out_dir, out_number, fig_width)
    f_name = f_tup[1]
    fig_width = f_tup[6]

    epoch_boolvector = (t_sec >= epoch[0][0]) & (t_sec <= epoch[0][1])
    epoch_timescale = t_sec[epoch_boolvector]
    epoch_data = data[epoch_boolvector]

    plt.figure(figsize=(fig_width,8), dpi=96)
    plt.plot(epoch_timescale, epoch_data[:,col]);
    plt.xlim(epoch_timescale[0], epoch_timescale[-1])
    plt.show()
    return (epoch_boolvector, epoch_timescale, epoch_data)

inside main file

#load the whole data
(f1_data, f1_data_indices, f1_timescale) = pm.load_data(f1_wdir, f1_name)

raw_data = f1_data[:] #create copy of f1_data

(f1ep1_boolvector, f1ep1_timescale, f1ep1_data) = pm.get_epoch1(f1_data, f1_timescale, f1_epochs[1], f1_tup, 8)

#--- filter data to remove DC (1Hz)
f1_data = pm.removeDC(f1_data)

# replace only channel 8 with original data
f1_data[:,8] = raw_data[:,8]
(f1ep2_boolvector, f1ep2_timescale, f1ep2_data) = pm.get_epoch1(f1_data, f1_timescale, f1_epochs[1], f1_tup, 8)

Body:
The solution is import copy and use copy.deepcopy function.
For further info check this link:
 docs.python.org/2/library/copy.html

When I have raw_data = f1_data[:] I get, after pm.removeDC():

 raw_data is f1_data: False
(raw_data == f1_data).all(): True

But when I have raw_data = copy.deepcopy(f1_data) I get, after pm.removeDC():

 raw_data is f1_data: False
(raw_data == f1_data).all(): False