问:
Integrate new rails app with existing external MS SQL Server database
I need to create a new rails application that will use an existing external Microsoft SQL server database as its primary database. This DB is running on an external server that i'll need to connect to. Here where i work there's a separate DB Admins section so im not sure what steps i need to perform. I think the easy part is connect to the server and set the app to work with that DB. But i get confused after that.

Should i create a db dump and migration?

Should i add models to represent existing database structure?

In case i need to create new models and tables in the db...

Should i generate its models from the rails generator and run migrations on the db or contact the DB admins to create the tables, and then specify manually the models inside the app? <- this really confuses me

Thank you in advance and sorry for my english! :)

EDIT!! -> The Rails Way

I've found another great way to integrate multiple database data... You can define a model and specify in which database it's located (so db connection is never closed)... This is definitely The Rails Way and should be followed...

Here's a nice tut:
Multiple Databases in Rails

TL;DR

Define your secondary_db in database.yml

Define your model and specify its database and table name

```<code>Class ExternalDatabaseModel < ActiveRecord::Base
  establish_connection(:secondary_db)
  self.table_name = "the_table"
  self.primary_key = 'someWeirdIDColumn'
end
</code>```

Then use as any other rails model, specify relationships and more :)

Hope it helps to somebody!

答:
I would suggest you take a look at tiny tds gem: https://github.com/rails-sqlserver/tiny_tds. It's really use to config and use... you can use it to connect on your external sql server db and make the queries you want. Don't know which type of system you're working, but if you're constantly retrieving data, making external requests may get your system slower. Depending on your application, you could consider synchronizing the data, making a local database redundant. Hope it helps you, good luck!

EDIT: about the models part: if you're going to retrieve the data from that sql server every time you need, than you don't need to store it locally. But if you're doing that redundancy, you should create the models with the attributes you'll need, than when you retrieve from the server, you save it normally, just attributing the values to your model and calling save! method.

Body:
I need to create a new rails application that will use an existing external Microsoft SQL server database as its primary database. This DB is running on an external server that i'll need to connect to. Here where i work there's a separate DB Admins section so im not sure what steps i need to perform. I think the easy part is connect to the server and set the app to work with that DB. But i get confused after that.

Should i create a db dump and migration?

Should i add models to represent existing database structure?

In case i need to create new models and tables in the db...

Should i generate its models from the rails generator and run migrations on the db or contact the DB admins to create the tables, and then specify manually the models inside the app? <- this really confuses me

Thank you in advance and sorry for my english! :)

EDIT!! -> The Rails Way

I've found another great way to integrate multiple database data... You can define a model and specify in which database it's located (so db connection is never closed)... This is definitely The Rails Way and should be followed...

Here's a nice tut:
Multiple Databases in Rails

TL;DR

Define your secondary_db in database.yml

Define your model and specify its database and table name

Class ExternalDatabaseModel < ActiveRecord::Base
  establish_connection(:secondary_db)
  self.table_name = "the_table"
  self.primary_key = 'someWeirdIDColumn'
end

Then use as any other rails model, specify relationships and more :)

Hope it helps to somebody!


来源: stackexchange

问:
can not find networkx module
I am trying to use networkx's networkx.algorithms.community.quality module to use coverage() But when I execute

```<code>from networkx.algorithms.community.quality import coverage
</code>```

It shows

```<code>ImportError: No module named 'networkx.algorithms.community.quality'
</code>```

Letter i found, my python only only find networkx.algorithms.community.kclique and networkx.algorithms.community.tests module. No quality module. My networkx version in 1.11, which is the latest.

Can anybody give me clue?

答: That module doesn't exist on 1.11. I don't know if its functionality is somewhere else on 1.11 or if that functionality just doesn't exist on 1.11, but you're not going to find it in networkx.algorithms.community.quality

ContentLicense: CC BY-SA 3.0

Title: can not find networkx module

Body:
I am trying to use networkx's networkx.algorithms.community.quality module to use coverage() But when I execute

from networkx.algorithms.community.quality import coverage

It shows

ImportError: No module named 'networkx.algorithms.community.quality'

Letter i found, my python only only find networkx.algorithms.community.kclique and networkx.algorithms.community.tests module. No quality module. My networkx version in 1.11, which is the latest.

Can anybody give me clue?


问:
Rsponsive Thumbnail with caption and link
Hi how can i make something like in this picture:

example

i tried with bootstrap gridbut i always got a frame around the corners.

答:
.image-block {
  position: relative;
  display: inline-block;
  width: 200px;
  text-decoration: none;
  color: #000;
  box-shadow: 0 0 20px 0 rgba(0,0,0,.2);
  margin: 20px;
  transition: box-shadow .3s ease-in-out;
  will-change: box-shadow;
}
.image-block:hover {
  box-shadow: 0 0 4px 0 rgba(0,0,0,.2);
}
.image-block figure {
  margin: 0;
}
.image-block figure img {
  width: 100%;
}
.image-block figcaption {
  padding: 15px;
}
.image-block figcaption .date {
  font-size: 12px;
  color: #999;
}
.image-block figcaption .message {
  font-size: 16px;
}
.image-block figcaption .message p {
  margin: 0;
}
.image-block footer {
  background-color: purple;
  color: #FFF;
  font-size: 14px;
}
.image-block footer p {
  margin: 0;
  padding: 7px 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <figure>
    <img src="https://static.pexels.com/photos/324658/pexels-photo-324658.jpeg">
  </figure>
  <figcaption>
    <span class="date">4/07/2017</span>
    <div class="message">
      <p>Lorem ipsum dolor sit amer</p>
    </div>
  </figcaption>
  <footer>
    <p>Read more</p>
  </footer>
</code>```

Body:
.image-block {
  position: relative;
  display: inline-block;
  width: 200px;
  text-decoration: none;
  color: #000;
  box-shadow: 0 0 20px 0 rgba(0,0,0,.2);
  margin: 20px;
  transition: box-shadow .3s ease-in-out;
  will-change: box-shadow;
}
.image-block:hover {
  box-shadow: 0 0 4px 0 rgba(0,0,0,.2);
}
.image-block figure {
  margin: 0;
}
.image-block figure img {
  width: 100%;
}
.image-block figcaption {
  padding: 15px;
}
.image-block figcaption .date {
  font-size: 12px;
  color: #999;
}
.image-block figcaption .message {
  font-size: 16px;
}
.image-block figcaption .message p {
  margin: 0;
}
.image-block footer {
  background-color: purple;
  color: #FFF;
  font-size: 14px;
}
.image-block footer p {
  margin: 0;
  padding: 7px 15px;
}

<a href="#" class="image-block">
  <figure>
    <img src="https://static.pexels.com/photos/324658/pexels-photo-324658.jpeg">
  </figure>
  <figcaption>
    <span class="date">4/07/2017</span>
    <div class="message">
      <p>Lorem ipsum dolor sit amer</p>
    </div>
  </figcaption>
  <footer>
    <p>Read more</p>
  </footer>
</a>


问:
How to set a hex color to an ImageView inside a notification?
I'm trying to set a color as an image to an ImageView that exists inside a custom notification. I can give it predefined colors by writing this line:

```<code>remoteViews.setImageViewResource(R.id.imageView, R.color.Green);
</code>```

But i want to be able to give it hex color values, and set that as the color. I tried setting the color as the background of the ImageView, but i couldn't get access to it, and the only options i have to access the ImageView are these:

```<code>remoteViews
    .setImageViewResource()
    .setImageViewBitmap()
    .setImageViewIcon()
    .setImageViewUri()
</code>```

Is there a way to pass in a color by parsing the hex value to any of these?
I think if I was able to create a bitmap and set the bitmap to the image view, it could be done, so i wrote the code bellow to create the bitmap:

```<code>    int[] colors = {Color.parseColor("#64DD17"), Color.parseColor("#D32F2F")};
    Bitmap bitmap = Bitmap.createBitmap(colors, 10, 10, Bitmap.Config.RGB_565);
</code>```

, but i get a java.lang.ArrayIndexOutOfBoundsException. I tried with one element in the colors array too, but same error.
What is my error here?

答:
The int[] is your image; so you create an image 2px wide, since that's the length of your array. However, you call createBitmap and specify that the image is in fact 10pxx10px; this is why the ArrayIndexOutOfBoundsException is thrown, as Android starts looking for pixels that aren't there.

Using Bitmap bitmap = Bitmap.createBitmap(colors, 2, 1, Bitmap.Config.RGB_565); would solve this problem, albeit generate a very tiny image!

Body:
I'm trying to set a color as an image to an ImageView that exists inside a custom notification. I can give it predefined colors by writing this line:

remoteViews.setImageViewResource(R.id.imageView, R.color.Green);

But i want to be able to give it hex color values, and set that as the color. I tried setting the color as the background of the ImageView, but i couldn't get access to it, and the only options i have to access the ImageView are these:

remoteViews
    .setImageViewResource()
    .setImageViewBitmap()
    .setImageViewIcon()
    .setImageViewUri()

Is there a way to pass in a color by parsing the hex value to any of these?
I think if I was able to create a bitmap and set the bitmap to the image view, it could be done, so i wrote the code bellow to create the bitmap:

    int[] colors = {Color.parseColor("#64DD17"), Color.parseColor("#D32F2F")};
    Bitmap bitmap = Bitmap.createBitmap(colors, 10, 10, Bitmap.Config.RGB_565);

, but i get a java.lang.ArrayIndexOutOfBoundsException. I tried with one element in the colors array too, but same error.
What is my error here?


问:
Call child component method from parent class - Angular
I have created a child component which has a method I want to invoke.

When I invoke this method it only fires the console.log() line, it will not set the test property??

Below is the quick start Angular app with my changes.

Parent

```<code>import { Component } from '@angular/core';
import { NotifyComponent }  from './notify.component';

@Component({
    selector: 'my-app',
    template:
    `
    <button (click)="submit()">Call Child Component Method</button>
    `
})
export class AppComponent {
    private notify: NotifyComponent;

    constructor() {
      this.notify = new NotifyComponent();
    }

    submit(): void {
        // execute child component method
        notify.callMethod();
    }
}
</code>```

Child

```<code>import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'notify',
    template: '<h3>Notify {{test}}</h3>'
})
export class NotifyComponent implements OnInit {
   test:string;
   constructor() { }

    ngOnInit() { }

    callMethod(): void {
        console.log('successfully executed.');
        this.test = 'Me';
    }
}
</code>```

How can I set the test property as well?

答:
This Worked for me ! For Angular 2 , Call child component method in parent component

Parent.component.ts

```<code>    import { Component, OnInit, ViewChild } from '@angular/core';
    import { ChildComponent } from '../child/child';
    @Component({
               selector: 'parent-app',
               template: `<child-cmp></child-cmp>`
              })
    export class parentComponent implements OnInit{
        @ViewChild(ChildComponent ) child: ChildComponent ;

        ngOnInit() {
           this.child.ChildTestCmp(); }
}
</code>```

Child.component.ts

```<code>import { Component } from '@angular/core';
@Component({
  selector: 'child-cmp',
  template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> `
})
export class ChildComponent {
  test: string;
  ChildTestCmp()
  {
    this.test = "I am child component!";
  }
 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created a child component which has a method I want to invoke.

When I invoke this method it only fires the console.log() line, it will not set the test property??

Below is the quick start Angular app with my changes.

Parent

import { Component } from '@angular/core';
import { NotifyComponent }  from './notify.component';

@Component({
    selector: 'my-app',
    template:
    `
    <button (click)="submit()">Call Child Component Method</button>
    `
})
export class AppComponent {
    private notify: NotifyComponent;

    constructor() {
      this.notify = new NotifyComponent();
    }

    submit(): void {
        // execute child component method
        notify.callMethod();
    }
}

Child

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'notify',
    template: '
Notify {{test}}
'
})
export class NotifyComponent implements OnInit {
   test:string;
   constructor() { }

    ngOnInit() { }

    callMethod(): void {
        console.log('successfully executed.');
        this.test = 'Me';
    }
}

How can I set the test property as well?

Body:
This Worked for me ! For Angular 2 , Call child component method in parent component

Parent.component.ts

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { ChildComponent } from '../child/child';
    @Component({
               selector: 'parent-app',
               template: `<child-cmp></child-cmp>`
              })
    export class parentComponent implements OnInit{
        @ViewChild(ChildComponent ) child: ChildComponent ;

        ngOnInit() {
           this.child.ChildTestCmp(); }
}

Child.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'child-cmp',
  template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> `
})
export class ChildComponent {
  test: string;
  ChildTestCmp()
  {
    this.test = "I am child component!";
  }
 }


问:
Getting response from serve the wrong Json format. How to make it respond in required format?
I am trying to create a search Module in my application but the response from my database is in the following format and i am getting a error

```<code>ERROR SyntaxError: Unexpected token s in JSON at position 0

sa[{"id":"4","worklocation":"Hyderabad","firstname":"Sanjay","lastname":"Tutuki","gender":"Male","aadharno":"0","panno":"2147483647","employeetype":"asdasd","dateofbirth":"2017-07-12","city":"Mumbai"}]
</code>```

How do i make it respond without the term which i searched with? Or how to I get the values in my component without the Error.

This is my code:

service.ts:

```<code>search(terms: Observable<string>) {
    return terms.debounceTime(400)
      .distinctUntilChanged()
      .switchMap(term => this.searchEntries(term));
  }
            searchEntries(term) {
                const baseUrl="http://localhost/Angular/search.php?search="
    return this.http
        .get(baseUrl + term)
        .map(res => res.json());
  }
</code>```

Component :

```<code>export class EmployeeDirectory {
    data : Data[];
    searchTerm$ = new Subject<string>();

    constructor(private dataservice : DataService){

        this.dataservice.search(this.searchTerm$)
      .subscribe(data => {
        this.data = data.data;
        console.log(data);

      });
  }

  search(searchTerm$){
    this.dataservice.search(this.searchTerm$)
      .subscribe(data => {
        this.data = data.data;
        console.log(data);
      });
  }
    }
</code>```

Template :

```<code><div class="col-md-6 col-sm-12 col-xs-12 ">
   <form method="GET" name="form" autocomplete="off">
    <div class="col-lg-9">
    <div class="input-group">
      <input type="text" class="form-control" (keyup)="searchTerm$.next($event.target.value)"  placeholder="Search for...">
      <span class="input-group-btn">
        <button class="btn btn-secondary" type="button" (click)="search(this.searchTerm$)" ><i class="glyphicon glyphicon-search"></i></button>
      </span>
    </div>
  </div>
  </form>
</div>

   <div *ngIf="data">
      <table *ngFor="let employee of data">
        <tr><td>First Name: </td><td>{{employee.firstname}}</td></tr>
      </table>
</code>```

PHP File :

```<code><?php
header("Allow-Access-Header-Origin: *");
$servername ="localhost";
$username ="root";
$password="sandeepchetikam";
$dbase = "mydb";

$conn = mysqli_connect($servername,$username,$password,$dbase);
if(!$conn){
    echo "Error" .mysqli_error($conn);
}
$name =$_GET['search'];
print_r($name);
$sql = "SELECT * FROM newdb WHERE firstname LIKE '%{$name}%' ";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($result))
{
    $rows[] = $row;
}
echo json_encode($rows);
?>
</code>```

And also the function is responding only for first search key up and it's not working for other search items. Can anyone help me with this?

答:
```<code>print_r($name);
</code>```

<p>Looks kinda suspicious </p>

Body:
I am trying to create a search Module in my application but the response from my database is in the following format and i am getting a error

ERROR SyntaxError: Unexpected token s in JSON at position 0

sa[{"id":"4","worklocation":"Hyderabad","firstname":"Sanjay","lastname":"Tutuki","gender":"Male","aadharno":"0","panno":"2147483647","employeetype":"asdasd","dateofbirth":"2017-07-12","city":"Mumbai"}]

How do i make it respond without the term which i searched with? Or how to I get the values in my component without the Error.

This is my code:

service.ts:

search(terms: Observable<string>) {
    return terms.debounceTime(400)
      .distinctUntilChanged()
      .switchMap(term => this.searchEntries(term));
  }
            searchEntries(term) {
                const baseUrl="http://localhost/Angular/search.php?search="
    return this.http
        .get(baseUrl + term)
        .map(res => res.json());
  }

Component :

export class EmployeeDirectory {
    data : Data[];
    searchTerm$ = new Subject<string>();

    constructor(private dataservice : DataService){

        this.dataservice.search(this.searchTerm$)
      .subscribe(data => {
        this.data = data.data;
        console.log(data);

      });
  }

  search(searchTerm$){
    this.dataservice.search(this.searchTerm$)
      .subscribe(data => {
        this.data = data.data;
        console.log(data);
      });
  }
    }

Template :

   <form method="GET" name="form" autocomplete="off">

      <input type="text" class="form-control" (keyup)="searchTerm$.next($event.target.value)"  placeholder="Search for...">

        <button class="btn btn-secondary" type="button" (click)="search(this.searchTerm$)" ></button>

  </form>

First Name: 	{{employee.firstname}}

PHP File :

<?php
header("Allow-Access-Header-Origin: *");
$servername ="localhost";
$username ="root";
$password="sandeepchetikam";
$dbase = "mydb";

$conn = mysqli_connect($servername,$username,$password,$dbase);
if(!$conn){
    echo "Error" .mysqli_error($conn);
}
$name =$_GET['search'];
print_r($name);
$sql = "SELECT * FROM newdb WHERE firstname LIKE '%{$name}%' ";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($result))
{
    $rows[] = $row;
}
echo json_encode($rows);
?>

And also the function is responding only for first search key up and it's not working for other search items. Can anyone help me with this?

Body:
print_r($name);

Looks kinda suspicious


问:
I need to align 3 divs in the center of my page with flexbox
I have a flex container and 3 divs inside it of equal width and I am trying to get the divs to align in the centre of the page with equal distance between them and also equal distance from the edge of the page.

.container {
    display : flex;
    width : 60%;
}

.para {
    width : 33%;
    padding : 1em;
    border:.5px solid black;
    margin :1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "container">
<div class ="para one">para one para one para one para one para one para one
para one para one para one para one para one</div>

<div class ="para two">para two para two para two para two para two para two
para two para two para two para two para two para two </div>

<div class ="para three">para three  para three para three para three para
three para three para three para three para three para three</div>
</div></code>```

答:
Use justify-content: space-between; to add equal space between the items

.container {
  display: flex;
  justify-content: space-between;
  margin: 0 auto;
}

.para {
  width: 33%;
  padding: 1em;
  border: .5px solid black;
  margin: 1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="para one">
    para one para one para one para one para one para one para one para one para one para one para one</div>

  <div class="para two">
    para two para two para two para two para two para two para two para two para two para two para two para two </div>

  <div class="para three">
    para three para three para three para three para three para three para three para three para three para three</div>

</div></code>```

Body:
I have a flex container and 3 divs inside it of equal width and I am trying to get the divs to align in the centre of the page with equal distance between them and also equal distance from the edge of the page.

.container {
    display : flex;
    width : 60%;
}

.para {
    width : 33%;
    padding : 1em;
    border:.5px solid black;
    margin :1em;
}

para one para one para one para one para one para one
para one para one para one para one para one

para two para two para two para two para two para two
para two para two para two para two para two para two

para three  para three para three para three para
three para three para three para three para three para three

Body:
Use justify-content: space-between; to add equal space between the items

.container {
  display: flex;
  justify-content: space-between;
  margin: 0 auto;
}

.para {
  width: 33%;
  padding: 1em;
  border: .5px solid black;
  margin: 1em;
}

<div class="container">
  <div class="para one">
    para one para one para one para one para one para one para one para one para one para one para one</div>

  <div class="para two">
    para two para two para two para two para two para two para two para two para two para two para two para two </div>

  <div class="para three">
    para three para three para three para three para three para three para three para three para three para three</div>

</div>


问:
Setting timeout so php is run to avoid double debit (due to loss of connection) of user points balance
I have the following code:

```<code>$user_id = $_GET["user_id"];
$user = get_user_by('id',$user_id);
$balance = mycred_get_users_balance($user_id);
if ($balance > "0") {
        mycred_subtract( 'Check-in',$user_id, -1, 'Checked in.' );
        echo "You are checked in.";
echo ' ' . $user->first_name;
}
else{ echo "You have a balance of " . $balance . ".";
    echo "<br/>";
    echo "Please purchase more credits at our website freethemind.biz";
}
</code>```

As part of my custom page, what I want to do is first echo the users first name based on the integer in the variable $user_id which does not seem to echo anything at the moment.
Also, I'd like to have a timeout so that lets say if the page is visited and the user_id is 1, the mycred_subtract can only run once every 10 seconds or so. This will avoid the user being debited a point for multiple page requests if there was a loss of connection or something of that sort.
I'm not sure on how to implement that but what I did read was you can sleep() but its not recommended server side.

My point is to avoid double debiting the user because of a browser deciding to send multiple requests to the webpage in a very short period of time (2-3 seconds).

EDIT

I see that it is possible to create confirm dialog box so a user can only be debited once it has been manually confirmed, would this be through the follow code:
onclick="return confirm('Are you sure?');">My Link
If so, could I pass a php variable into that JavaScript, I'd like to contstruct it such that:
onclick="return confirm(' 'Check-in' . $user->first_name . '?' ');">My Link

答:
You want to be transactionally atomic, transactionally safe.

I'd consider holding some unique value (the primary key is fine, but you might not want to reveal that to the world - UUID() would work fine too) of the table you're editing.

When submitting the request to debit the ledger, submit the last known primary key with the request.  When processing the request, start a transaction - confirm the submitted primary key is still the latest - and commit.

This protects the customer from double-debiting.  If the request is sent twice, the "latest" primary key value in the debit request will no longer be up-to-date.  The database can detect this and refuse to perform the action.

In MySQL + PHP, you can handle the start/commit of the transaction several ways, personally I've found (having worked in the financial sector with PHP) that calling a stored procedure is the most robust approach.  Thusly there's practically zero risk of the transaction never completing (if PHP looses contact with the database, for example).

So the flow would look something like:

```<code>GET /view-account
  <form method="post" action="debit-account">
     <input type="hidden" name="last_trx_id_for_customer" value="123">
     <input type="numeric" name="amount" value="10.00">
     <button type="submit">Debit me</button>
  </form>

POST /debit-account
  <?php
  $db->execute('CALL sp_debit_account(:last_trx_id_for_customer, :customer_id, :amount)', ...);

  ...

  (Stored proc:)
  START TRANSACTION;
     SELECT MAX(trx_id) FROM ledger WHERE customer_id = p_customer_id INTO p_trx_id;
     IF (p_trx_id != p_supplied_last_trx_id) THEN
         ROLLBACK;
     ELSE
         ... debit account
         COMMIT;
     END IF;
</code>```

Body:
I have the following code:

$user_id = $_GET["user_id"];
$user = get_user_by('id',$user_id);
$balance = mycred_get_users_balance($user_id);
if ($balance > "0") {
        mycred_subtract( 'Check-in',$user_id, -1, 'Checked in.' );
        echo "You are checked in.";
echo ' ' . $user->first_name;
}
else{ echo "You have a balance of " . $balance . ".";
    echo "
";
    echo "Please purchase more credits at our website freethemind.biz";
}

As part of my custom page, what I want to do is first echo the users first name based on the integer in the variable $user_id which does not seem to echo anything at the moment.
Also, I'd like to have a timeout so that lets say if the page is visited and the user_id is 1, the mycred_subtract can only run once every 10 seconds or so. This will avoid the user being debited a point for multiple page requests if there was a loss of connection or something of that sort.
I'm not sure on how to implement that but what I did read was you can sleep() but its not recommended server side.

My point is to avoid double debiting the user because of a browser deciding to send multiple requests to the webpage in a very short period of time (2-3 seconds).

EDIT

I see that it is possible to create confirm dialog box so a user can only be debited once it has been manually confirmed, would this be through the follow code:
onclick="return confirm('Are you sure?');">My Link
If so, could I pass a php variable into that JavaScript, I'd like to contstruct it such that:
onclick="return confirm(' 'Check-in' . $user->first_name . '?' ');">My Link

Body:
You want to be transactionally atomic, transactionally safe.

I'd consider holding some unique value (the primary key is fine, but you might not want to reveal that to the world - UUID() would work fine too) of the table you're editing.

When submitting the request to debit the ledger, submit the last known primary key with the request.  When processing the request, start a transaction - confirm the submitted primary key is still the latest - and commit.

This protects the customer from double-debiting.  If the request is sent twice, the "latest" primary key value in the debit request will no longer be up-to-date.  The database can detect this and refuse to perform the action.

In MySQL + PHP, you can handle the start/commit of the transaction several ways, personally I've found (having worked in the financial sector with PHP) that calling a stored procedure is the most robust approach.  Thusly there's practically zero risk of the transaction never completing (if PHP looses contact with the database, for example).

So the flow would look something like:

GET /view-account
  <form method="post" action="debit-account">
     <input type="hidden" name="last_trx_id_for_customer" value="123">
     <input type="numeric" name="amount" value="10.00">
     <button type="submit">Debit me</button>
  </form>

POST /debit-account
  <?php
  $db->execute('CALL sp_debit_account(:last_trx_id_for_customer, :customer_id, :amount)', ...);

  ...

  (Stored proc:)
  START TRANSACTION;
     SELECT MAX(trx_id) FROM ledger WHERE customer_id = p_customer_id INTO p_trx_id;
     IF (p_trx_id != p_supplied_last_trx_id) THEN
         ROLLBACK;
     ELSE
         ... debit account
         COMMIT;
     END IF;


问:
Trigger android download manager Cordova
I'm trying to download files with a Cordova app, this is working fine for smaller files using the File transfer plugin, but for bigger files I would like to trigger the android download manager. Is this possible(probably with a plugin)?

I need to be able to change the headers of the request, so the 'cordova plugin background download'
plugin didn't help me.

答:
This is one readymade downloader plugin which matches your requirement and comparitively active.

It also provides various options for downloading as mentioned in the usage link


问:
How can I group by month from a date field using Python and Pandas?
I have a dataframe, df, which is as follows:

| date      | Revenue |
|-----------|---------|
| 6/2/2017  | 100     |
| 5/23/2017 | 200     |
| 5/20/2017 | 300     |
| 6/22/2017 | 400     |
| 6/21/2017 | 500     |
```
<p>I need to group the above data by month to get output as:</p>
<pre class="lang-none prettyprint-override"><code>| date | SUM(Revenue) |
|------|--------------|
| May  | 500          |
| June | 1000         |
</code>```

I tried this code, but it did not work:

```<code>df.groupby(month('date')).agg({'Revenue': 'sum'})
</code>```

I want to only use Pandas or NumPy and no additional libraries.

答:
Try a groupby using a pandas Grouper:

df = pd.DataFrame({'date':['6/2/2017','5/23/2017','5/20/2017','6/22/2017','6/21/2017'],'Revenue':[100,200,300,400,500]})
df.date = pd.to_datetime(df.date)
dg = df.groupby(pd.Grouper(key='date', freq='1M')).sum() # groupby each 1 month
dg.index = dg.index.strftime('%B')
```
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>     Revenue
 May    500
June    1000
</code>```

Body:
I have a dataframe, df, which is as follows:

| date      | Revenue |
|-----------|---------|
| 6/2/2017  | 100     |
| 5/23/2017 | 200     |
| 5/20/2017 | 300     |
| 6/22/2017 | 400     |
| 6/21/2017 | 500     |

I need to group the above data by month to get output as:

| date | SUM(Revenue) |
|------|--------------|
| May  | 500          |
| June | 1000         |

I tried this code, but it did not work:

df.groupby(month('date')).agg({'Revenue': 'sum'})

I want to only use Pandas or NumPy and no additional libraries.

Body:
Try a groupby using a pandas Grouper:

df = pd.DataFrame({'date':['6/2/2017','5/23/2017','5/20/2017','6/22/2017','6/21/2017'],'Revenue':[100,200,300,400,500]})
df.date = pd.to_datetime(df.date)
dg = df.groupby(pd.Grouper(key='date', freq='1M')).sum() # groupby each 1 month
dg.index = dg.index.strftime('%B')

Output:

     Revenue
 May    500
June    1000


问:
notifyItemChanged() make the RecyclerView scroll and jump to UP
i have a RecycleView with an adapter that show a list of servers
and the user must select one server.

when i call notifyItemChanged(previousPosition) inside the onClick() method
to make the old server unselected and the new server selected,
that's make the RecycleView list jump to up exactly in the middle of list.

and this problem happen just when i click on one of the last 2 or 3 servers inside the RecycleView list

here is the code of my RecyclerView.Adapter :

```<code>public class ServerAdapter extends RecyclerView.Adapter<ServerAdapter.ServerViewHolder> {

    private List<Server> listServers = new ArrayList<>();
    private int[] icons = new int[]{R.drawable.server1,R.drawable.server2,R.drawable.server3,R.drawable.server4,R.drawable.server5,R.drawable.server6,R.drawable.offline};
    private int selected = 0;
    private int previousSelected = 0;

    public ServerAdapter(List<Server> listServers){
        this.listServers = listServers;
    }

    @Override
    public ServerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.server_relative_layout,parent,false);
        return new ServerViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ServerViewHolder holder, final int position) {
        if(position == selected){
            holder.getBackground().setSelected(true);
        }else{
            holder.getBackground().setSelected(false);
        }
        holder.getBackground().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(position != selected){
                    previousSelected = selected;
                    selected = position;
                    holder.getBackground().setSelected(true);
                    notifyItemChanged(previousSelected);
                }
            }
        });
        holder.getImageServer().setImageResource(icons[position%6]);
        holder.getTextNameServer().setText(listServers.get(position).getName());
        holder.getTextConnected().setText(listServers.get(position).getUrl());
    }

    @Override
    public int getItemCount() {
        return listServers.size();
    }

    public class ServerViewHolder extends RecyclerView.ViewHolder{
        private ImageView imageServer;
        private TextView textNameServer;
        private TextView textConnected;
        private View background;
        public ServerViewHolder(View itemView) {
            super(itemView);
            imageServer = (ImageView)itemView.findViewById(R.id.imageServer);
            textNameServer = (TextView)itemView.findViewById(R.id.textNameServer);
            textConnected = (TextView)itemView.findViewById(R.id.textConnected);
            background = itemView;
        }

        public ImageView getImageServer() {
            return imageServer;
        }

        public TextView getTextConnected() {
            return textConnected;
        }

        public TextView getTextNameServer() {
            return textNameServer;
        }

        public View getBackground() {
            return background;
        }
    }
}
</code>```

any solutions to solve this problem ? thanks.

The problem happened exactly when i specify the layout height and do not let it to wrap_content

```<code><android.support.v7.widget.RecyclerView
    android:layout_width="wrap_content"
    android:layout_height="400dp"
    android:id="@+id/serverRecyclerView"
    android:layout_margin="10dp"
/>
</code>```

or when i put it below something for expample like that :

```<code><android.support.v7.widget.RecyclerView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/serverRecyclerView"
    android:layout_margin="10dp"
    android:layout_below="@+id/image"/>
</code>```

my code exactly is :

```<code><android.support.v7.widget.RecyclerView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/serverRecyclerView"
    android:layout_margin="10dp"
    android:layout_alignTop="@+id/imageBall"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@+id/camera"
    android:layout_toEndOf="@+id/camera"/>
</code>```

答:
```<code>RecyclerView.ItemAnimator animator = myRecyclerListView.getItemAnimator();
if (animator instanceof SimpleItemAnimator) {
    ((SimpleItemAnimator)animator).setSupportsChangeAnimations(false);
}
</code>```

Body:
i have a RecycleView with an adapter that show a list of servers
and the user must select one server.

when i call notifyItemChanged(previousPosition) inside the onClick() method
to make the old server unselected and the new server selected,
that's make the RecycleView list jump to up exactly in the middle of list.

and this problem happen just when i click on one of the last 2 or 3 servers inside the RecycleView list

here is the code of my RecyclerView.Adapter :

public class ServerAdapter extends RecyclerView.Adapter<ServerAdapter.ServerViewHolder> {

    private List<Server> listServers = new ArrayList<>();
    private int[] icons = new int[]{R.drawable.server1,R.drawable.server2,R.drawable.server3,R.drawable.server4,R.drawable.server5,R.drawable.server6,R.drawable.offline};
    private int selected = 0;
    private int previousSelected = 0;

    public ServerAdapter(List<Server> listServers){
        this.listServers = listServers;
    }

    @Override
    public ServerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.server_relative_layout,parent,false);
        return new ServerViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ServerViewHolder holder, final int position) {
        if(position == selected){
            holder.getBackground().setSelected(true);
        }else{
            holder.getBackground().setSelected(false);
        }
        holder.getBackground().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(position != selected){
                    previousSelected = selected;
                    selected = position;
                    holder.getBackground().setSelected(true);
                    notifyItemChanged(previousSelected);
                }
            }
        });
        holder.getImageServer().setImageResource(icons[position%6]);
        holder.getTextNameServer().setText(listServers.get(position).getName());
        holder.getTextConnected().setText(listServers.get(position).getUrl());
    }

    @Override
    public int getItemCount() {
        return listServers.size();
    }

    public class ServerViewHolder extends RecyclerView.ViewHolder{
        private ImageView imageServer;
        private TextView textNameServer;
        private TextView textConnected;
        private View background;
        public ServerViewHolder(View itemView) {
            super(itemView);
            imageServer = (ImageView)itemView.findViewById(R.id.imageServer);
            textNameServer = (TextView)itemView.findViewById(R.id.textNameServer);
            textConnected = (TextView)itemView.findViewById(R.id.textConnected);
            background = itemView;
        }

        public ImageView getImageServer() {
            return imageServer;
        }

        public TextView getTextConnected() {
            return textConnected;
        }

        public TextView getTextNameServer() {
            return textNameServer;
        }

        public View getBackground() {
            return background;
        }
    }
}

any solutions to solve this problem ? thanks.

The problem happened exactly when i specify the layout height and do not let it to wrap_content

<android.support.v7.widget.RecyclerView
    android:layout_width="wrap_content"
    android:layout_height="400dp"
    android:id="@+id/serverRecyclerView"
    android:layout_margin="10dp"
/>

or when i put it below something for expample like that :

<android.support.v7.widget.RecyclerView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/serverRecyclerView"
    android:layout_margin="10dp"
    android:layout_below="@+id/image"/>

my code exactly is :

<android.support.v7.widget.RecyclerView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/serverRecyclerView"
    android:layout_margin="10dp"
    android:layout_alignTop="@+id/imageBall"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@+id/camera"
    android:layout_toEndOf="@+id/camera"/>


问:
Universal library for C++ strings
Please recommend me universal library for C++ strings. I want to manipulate ascii text and unicode text in one build without making two versions of builds for std::string/char and for std::wstring/wchar; Also I want to convert them to each other (where it is possible);

Thank you very much!!!

答:
In Java and Objective-C (and C#?) the strategy is to encode everything internally as UTF-16 and use conversions when getting strings from or sending strings to external entities (e.g. files, the UI).  For sanity, you should probably do the same thing.  Hold everything internally as UTF-16 (you need 16 bits per character for this).  Use string libraries to convert between UTF-16 and external representations. In C I can think of three off the top of my head

ICU

iconv

CFLite (quite limited set of supported encodings).

In C++, I don't know of any libraries.  Your OS platform may also contain its own library to do the conversion.

Unless you know you will always be dealing with straight ASCII or ISO-8859-1 you should always use a library to do conversions rather than rolling your own because the gotchas are many and varied.

ContentLicense: CC BY-SA 2.5

Title: Universal library for C++ strings


问:
updating list, set during iteration -- while loop
I have a scrapy script as follows

1) Collects navigation_path into a list and calls a new parse

```<code>g_next_page_list = []
g_next_page_set = set()

def parse(self,response):

    #code to extract nav_links

    for nav_link in nav_links:
        if nav_link not in g_next_page_set:
            g_next_page_list.append(nav_link)
            g_next_page_set.add(nav_link)

    for next_page in g_next_page_list:
        next_page = response.urljoin(next_page)
        yield scrapy.Request(next_page, callback=self.parse_start_url,  dont_filter=True, )
</code>```

And i've defined parse_start_url as:

```<code>def parse_start_url(self,response):

    #code to extract nav_links

    for nav_link in nav_links:
        if nav_link not in g_next_page_set:
            g_next_page_list.append(nav_link)
            g_next_page_set.add(nav_link)
</code>```

However, the global list and set in the main parse (g_next_page_set, g_next_page_list) are not getting appended. What am I doing wrong?

Thanks in advance!

答:
You don't use global here, you use self.variable_name

```<code>g_next_page_list = []
g_next_page_set = set()

def parse(self,response):

    #code to extract nav_links

    for nav_link in nav_links:
        if nav_link not in v_next_page_set:
            self.g_next_page_list.append(nav_link)
            self.g_next_page_set.add(nav_link)

    for next_page in v_next_page_list:
        next_page = response.urljoin(next_page)
        yield scrapy.Request(next_page, callback=self.parse_start_url,  dont_filter=True, )

def parse_start_url(self,response):

    #code to extract nav_links

    for nav_link in nav_links:
        if nav_link not in v_next_page_set:
            self.g_next_page_list.append(nav_link)
            self.g_next_page_set.add(nav_link)
</code>```

This should make it work

Body:
I have a scrapy script as follows

1) Collects navigation_path into a list and calls a new parse

g_next_page_list = []
g_next_page_set = set()

def parse(self,response):

    #code to extract nav_links

    for nav_link in nav_links:
        if nav_link not in g_next_page_set:
            g_next_page_list.append(nav_link)
            g_next_page_set.add(nav_link)

    for next_page in g_next_page_list:
        next_page = response.urljoin(next_page)
        yield scrapy.Request(next_page, callback=self.parse_start_url,  dont_filter=True, )

And i've defined parse_start_url as:

def parse_start_url(self,response):

    #code to extract nav_links

    for nav_link in nav_links:
        if nav_link not in g_next_page_set:
            g_next_page_list.append(nav_link)
            g_next_page_set.add(nav_link)

However, the global list and set in the main parse (g_next_page_set, g_next_page_list) are not getting appended. What am I doing wrong?

Thanks in advance!

Body:
You don't use global here, you use self.variable_name

g_next_page_list = []
g_next_page_set = set()

def parse(self,response):

    #code to extract nav_links

    for nav_link in nav_links:
        if nav_link not in v_next_page_set:
            self.g_next_page_list.append(nav_link)
            self.g_next_page_set.add(nav_link)

    for next_page in v_next_page_list:
        next_page = response.urljoin(next_page)
        yield scrapy.Request(next_page, callback=self.parse_start_url,  dont_filter=True, )

def parse_start_url(self,response):

    #code to extract nav_links

    for nav_link in nav_links:
        if nav_link not in v_next_page_set:
            self.g_next_page_list.append(nav_link)
            self.g_next_page_set.add(nav_link)

This should make it work


问:
How can I rearrange an array in MATLAB by a specific rule?
Suppose that I have this array:

```<code>a = [1,2,3,4,5];
</code>```

The output should be something like this:

```<code>1,2,3,4,5
2,1,3,4,5
3,1,2,4,5
4,1,2,3,5
5,1,2,3,4
</code>```

how Can I do this? This function should be valid for different lengths of a.

答:
A simple solution can be:</p>

```<code>primarySet = 1:5;
result = zeros(length(primarySet));
for i = 1: length(primarySet)
    temp = primarySet;
    temp(i) = [];
    result(i,:) = [primarySet(i) temp];
end
</code>```

Body:
Suppose that I have this array:

a = [1,2,3,4,5];

The output should be something like this:

1,2,3,4,5
2,1,3,4,5
3,1,2,4,5
4,1,2,3,5
5,1,2,3,4

how Can I do this? This function should be valid for different lengths of a.

Body:
A simple solution can be:

primarySet = 1:5;
result = zeros(length(primarySet));
for i = 1: length(primarySet)
    temp = primarySet;
    temp(i) = [];
    result(i,:) = [primarySet(i) temp];
end


答:
Do you use any type of the framework? To load JS file in another file, you need to require it somehow, either by using AMD, ES imports or any other way (be it synchronous or asynchronous).

If you are just adding the files to the HTML (using script tags), then the only thing you have to do is to make sure that the files are loaded (DOMContentLoaded event) and then, you have to attach the data to a global scope.

Global scope in the browsers is called a window and every time when you use variable that was not declared in your scope by var it means that the JS is searching for it in the global scope. In order to assign something to a global scope you can just omit var or explicitely assign it like this:

```<code>window.desktopData = [];

// And then in another file, assuming that the data is ready

var myData = window.desktopData
</code>```

Please also remember that including files in

Title: Unable to refer javascript array from another javascript file

Body:
I am trying to create a chart using highcharts in which i am not able to fetch data which i store in another js file.

My main.js file has all the code for creating chart. It has the section of series.

series: [{
            name: 'Desktops',
            data: '/data/desktop.js',
            tooltip: {
                valueDecimals: 2
            }
        }]

Here i want to refer data from another js file. The name of file is desktop.js and it has just the below array

var desktopData = [[1475272800000, 117759], [1475359200000, 106147], [1475445600000, 147747], [1475532000000, 302031], [1475618400000, 520539], [1475704800000, 245353], [1475791200000, 180376], [1475877600000, 78819], [1475964000000, 90466], [1476050400000, 257822], [1476136800000, 284465], [1476223200000, 242898], [1476309600000, 297186], [1476396000000, 268069], [1476482400000, 183149], [1476568800000, 410442], [1476655200000, 1117798], [1476741600000, 1274668], [1476828000000, 1331799], [1476914400000, 1230213], [1477000800000, 888251], [1477087200000, 572050], [1477173600000, 931144], [1477260000000, 1556641], [1477346400000, 1526736], [1477432800000, 1310133], [1477519200000, 1207422], [1477605600000, 785556], [1477692000000, 487264], [1477778400000, 787714], [1477868400000, 942663]];

How can i refer array defined in another file?

Body:
Do you use any type of the framework? To load JS file in another file, you need to require it somehow, either by using AMD, ES imports or any other way (be it synchronous or asynchronous).

If you are just adding the files to the HTML (using script tags), then the only thing you have to do is to make sure that the files are loaded (DOMContentLoaded event) and then, you have to attach the data to a global scope.

Global scope in the browsers is called a window and every time when you use variable that was not declared in your scope by var it means that the JS is searching for it in the global scope. In order to assign something to a global scope you can just omit var or explicitely assign it like this:

window.desktopData = [];

// And then in another file, assuming that the data is ready

var myData = window.desktopData

Please also remember that including files in <script> tags usually means that they will block your browser and the order of the files matters (at least when you want to rely on the fact of one file already loaded before another file). I'd suggest using some kind of import system then:

http://requirejs.org/docs/whyamd.html


问:
Conditionally replace elements of a vector based on an index
It's best explained with an example.

I have a vector, or column from data.frame named vec:

```<code>vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)
</code>```

I would like a vectorized process (not a for loop) to change the three trailing NA when a 1 is observed.

The end vector would be:

```<code>c(NA, NA, 1, 1, 1, 1, NA, 1, 1, 1, 1, NA, NA, NA)
</code>```

If we had:

```<code>vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)
</code>```

The end vector would look like:

```<code>c(NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA)
</code>```

A very badly written solution is:

```<code>vec2 <- vec
for(i in index(v)){
  if(!is.na(v[i])) vec2[i] <- 1
  if(i>3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
    if(!is.na(vec[i-3])) vec2[i] <- 1
  }
  if(i==3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
  }
  if(i==2){
    if(!is.na(vec[i-1])) vec2[i] <- 1
  }
}
</code>```

Body:
It's best explained with an example.

I have a vector, or column from data.frame named vec:

vec <- c(NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA)

I would like a vectorized process (not a for loop) to change the three trailing NA when a 1 is observed.

The end vector would be:

c(NA, NA, 1, 1, 1, 1, NA, 1, 1, 1, 1, NA, NA, NA)

If we had:

vec <- c(NA, NA, 1, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA)

The end vector would look like:

c(NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA)

A very badly written solution is:

vec2 <- vec
for(i in index(v)){
  if(!is.na(v[i])) vec2[i] <- 1
  if(i>3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
    if(!is.na(vec[i-3])) vec2[i] <- 1
  }
  if(i==3){
    if(!is.na(vec[i-1])) vec2[i] <- 1
    if(!is.na(vec[i-2])) vec2[i] <- 1
  }
  if(i==2){
    if(!is.na(vec[i-1])) vec2[i] <- 1
  }
}

Body:
The following code does what you asked for. It involves "shifting" the vector and then adding the shifted versions

vec[is.na(vec)] <- 0
n <- length(vec)
vec <- vec + c(0, vec[1:(n-1)]) + c(0, 0, vec[1:(n-2)]) + c(0, 0, 0, vec[1:(n-3)])
vec[vec == 0] <- NA
vec[vec != 0] <- 1

# vec                    |   0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0 ,0, 0
# c(0, vec[1:(n-1)])     | + 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0 ,0, 0
# c(0, 0, vec[1:(n-2)])  | + 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0 ,0
# c(0,0,0,vec[1:(n-3)])  | + 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0
#                        |-------------------------------------------
#                        |   0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0


答:
A non-Vectorized solution, but nevertheless, another option using base R,

```<code>vec[unique(as.vector(t(sapply(which(vec == 1), function(i) seq(i+1, length.out = 3)))))] <- 1
vec
#[1] NA NA  1  1  1  1 NA  1  1  1  1 NA NA NA

vec1[unique(as.vector(t(sapply(which(vec1 == 1), function(i) seq(i+1, length.out = 3)))))] <- 1
vec1
#[1] NA NA  1  1  1  1  1  1  1  1  1 NA NA NA
</code>```

Title: Conditionally replace elements of a vector based on an index

Body:
A non-Vectorized solution, but nevertheless, another option using base R,

vec[unique(as.vector(t(sapply(which(vec == 1), function(i) seq(i+1, length.out = 3)))))] <- 1
vec
#[1] NA NA  1  1  1  1 NA  1  1  1  1 NA NA NA

vec1[unique(as.vector(t(sapply(which(vec1 == 1), function(i) seq(i+1, length.out = 3)))))] <- 1
vec1
#[1] NA NA  1  1  1  1  1  1  1  1  1 NA NA NA


问:
JQuery adds a comma when sending a variable to the server
I am using the https://jqueryvalidation.org/ library for form validation. When passing a variable to the controller, a comma is added to the beginning of the string. I do not know why.

Validation code

```<code>$('#registrationForm').validate({
    rules: {
        username: {
            nowhitespace: true,
            required: true,
            minlength: 6,
            maxlength: 36,
            remote : {
                url: '/checkUsername?username=' + encodeURIComponent($('#username').val()),
                type: "GET",
                data: {
                    username: function() {
                        return $('#username').val();
                    }
                }
            }
        },
</code>```

And this is my controller

```<code>@GetMapping("/checkUsername")
public boolean checkUsername(@RequestParam("username") String username) {
    System.out.println("User: " + username);
    return !userService.existsByUsername(username);
}
</code>```

In addition to checking what happens, I added a username display and when passing the username to the controller the result is the following

```<code>User: ,j
User: ,jo
User: ,jon
User: ,jonk
User: ,jonki
</code>```

I did not enter this comma. He added himself at the beginning. Appears out of nowhere.

答:
You need to remove from your validate code

```<code>      data: {
                username: function() {
                    return $('#username').val();
                }
            }
</code>```

Your final code should be

```<code>$('#registrationForm').validate({
    rules: {
        username: {
            nowhitespace: true,
            required: true,
            minlength: 6,
            maxlength: 36,
            remote : {
                url: '/checkUsername?username=' + encodeURIComponent($('#username').val()),
                type: "GET"
            }
        },
</code>```

Or you could try :

```<code>        remote : {
            url: '/checkUsername',
            type: "GET",
            data: {
                username: function() {
                    return $('#username').val();
                }
            }
        }
</code>```

Body:
I am using the https://jqueryvalidation.org/ library for form validation. When passing a variable to the controller, a comma is added to the beginning of the string. I do not know why.

Validation code

$('#registrationForm').validate({
    rules: {
        username: {
            nowhitespace: true,
            required: true,
            minlength: 6,
            maxlength: 36,
            remote : {
                url: '/checkUsername?username=' + encodeURIComponent($('#username').val()),
                type: "GET",
                data: {
                    username: function() {
                        return $('#username').val();
                    }
                }
            }
        },

And this is my controller

@GetMapping("/checkUsername")
public boolean checkUsername(@RequestParam("username") String username) {
    System.out.println("User: " + username);
    return !userService.existsByUsername(username);
}

In addition to checking what happens, I added a username display and when passing the username to the controller the result is the following

User: ,j
User: ,jo
User: ,jon
User: ,jonk
User: ,jonki

I did not enter this comma. He added himself at the beginning. Appears out of nowhere.

Body:
You need to remove from your validate code

      data: {
                username: function() {
                    return $('#username').val();
                }
            }

Your final code should be

$('#registrationForm').validate({
    rules: {
        username: {
            nowhitespace: true,
            required: true,
            minlength: 6,
            maxlength: 36,
            remote : {
                url: '/checkUsername?username=' + encodeURIComponent($('#username').val()),
                type: "GET"
            }
        },

Or you could try :

        remote : {
            url: '/checkUsername',
            type: "GET",
            data: {
                username: function() {
                    return $('#username').val();
                }
            }
        }


问:
can you gzip with zlib compression off
I am really trying to get up to speed with website optimization as most off my websites really lack in speed. I am using http://gtmetrix.com/ to test my website speed.

One thing I really need to do is use gzip compression. I spent ages trying to get it to work and could not figure out where i was going wrong.

If I click more information in web developer toolbar it said gzip enabled so this was decieving as it isn’t. I contacted my hosting providers and got the following response:

Unfortunately not, Gzip would cause too much load on our hosted
  servers therefore any similar programs would cause the same strain.

So even when it says it is enabled, I think I am right in saying what you need to check for in the php.ini file is:

```<code>zlib.output_compression        Off       Off
zlib.output_compression_level  -1        -1
zlib.output_handler            no value  no value
</code>```

Ok, so I assume this needs to be set to on to allow gzip compression. Is this correct?

Basically I would have to go for a dedicated server to allow for gzip £70 a month.

So I guess what I am asking is: Is there a way using PHP to utillise gzip compression without it being enabled by the hosting provider? I have tried many option but none successful so far.

Thanks

答:
gzip/deflate adds no significant load. Those rip-off prices aren't worth it however.

As for PHP, it can also be enabled from within scripts:

```<code>ob_start("ob_gzhandler");
</code>```

Would be emulatable via gzencode() if not available; but too much overhead I'd assume..

Title: can you gzip with zlib compression off

Body:
I am really trying to get up to speed with website optimization as most off my websites really lack in speed. I am using http://gtmetrix.com/ to test my website speed.

One thing I really need to do is use gzip compression. I spent ages trying to get it to work and could not figure out where i was going wrong.

If I click more information in web developer toolbar it said gzip enabled so this was decieving as it isn’t. I contacted my hosting providers and got the following response:

Unfortunately not, Gzip would cause too much load on our hosted
  servers therefore any similar programs would cause the same strain.

So even when it says it is enabled, I think I am right in saying what you need to check for in the php.ini file is:

zlib.output_compression        Off       Off
zlib.output_compression_level  -1        -1
zlib.output_handler            no value  no value

Ok, so I assume this needs to be set to on to allow gzip compression. Is this correct?

Basically I would have to go for a dedicated server to allow for gzip £70 a month.

So I guess what I am asking is: Is there a way using PHP to utillise gzip compression without it being enabled by the hosting provider? I have tried many option but none successful so far.

Thanks

Body:
gzip/deflate adds no significant load. Those rip-off prices aren't worth it however.

As for PHP, it can also be enabled from within scripts:

ob_start("ob_gzhandler");

Would be emulatable via gzencode() if not available; but too much overhead I'd assume..


问:
Umbraco cannot start. A connection string is configured -running correctly in local but error on hosted one
My project is working perfectly on local host but I am trying to host it on iis and following error is showing

Steps which I have tried so far:

1.checked my connection string which is

```<code><connectionStrings>
    <remove name="umbracoDbDSN" />
    <add name="umbracoDbDSN" connectionString="Server=EIL-IT-360-39\SQLEXPRESS;Database=umbraco_16_6;Integrated Security=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
</code>```

2.Using window authentication to login into my DB.

I have also refrered given sites but could not found desired solution:

Umbraco cannot start. A connection string is configured but the Umbraco cannot connect to the database

Umbraco cannot start after switching to local SQL database

答:
Check which identity your website is running under in IIS:

open IIS

got to Applications Pools in the tree on the left

find your website in the list

go to Advanced Settings

switch the Identity to Network Service rather than ApplicationPoolIdentity

I believe this is the user which runs the website. If this doesn't work, you may want to check that your selected Identity has access to the database.

Body:
My project is working perfectly on local host but I am trying to host it on iis and following error is showing

Steps which I have tried so far:

1.checked my connection string which is

<connectionStrings>
    <remove name="umbracoDbDSN" />
    <add name="umbracoDbDSN" connectionString="Server=EIL-IT-360-39\SQLEXPRESS;Database=umbraco_16_6;Integrated Security=true" providerName="System.Data.SqlClient" />
  </connectionStrings>

2.Using window authentication to login into my DB.

I have also refrered given sites but could not found desired solution:

Umbraco cannot start. A connection string is configured but the Umbraco cannot connect to the database

Umbraco cannot start after switching to local SQL database


问:
Spring RestTemplate - Need to release connection?
This is my Configuration for Rest Template,

```<code>    @Bean
    @Qualifier("myRestService")
    public RestTemplate createRestTemplate(@Value("${connection.timeout}") String maxConn) {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
         connectionManager.setMaxTotal(maxTotalConn);
         connectionManager.setDefaultMaxPerRoute(maxPerChannel);

        RequestConfig config = RequestConfig.custom().setConnectTimeout(100000).build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(config).build();
        ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

        RestTemplate restTemplate = new RestTemplate(factory);

        restTemplate.setErrorHandler(new RestResponseErrorHandler());
         restTemplate.setMessageConverters(createMessageConverters());

        return restTemplate;
    }
</code>```

Am using PoolingHttpClientConnectionManager for managing the connections.

Its being accessed by the following code,

```<code>ResponseEntity<String> response = restClient.exchange( url, HttpMethod.GET, entity , String.class );
</code>```

Do i need to release the connection after the above call or is it taken care by RestTemplate. If we need to take care of releasing connection.

Please can some one explain/show how to release the connection.

答:
The question which you have asked:
Do i need to release the connection after the above call or is it taken care by RestTemplate. If we need to take care of releasing connection.

No, you do not need to close the connection on the response, if you use resttemplate.

From the apache httpclient, you need to consume the complete response (EntityUtils.consume(HttpEntity) and close the response.

This can be verified in the ClientConnectionRelease.java

But RestTemplate does this for you, to verify the same have a look into
RestTemplate.java

Look for method

```<code>protected <T> T doExecute(URI url,...) {
 try {
        ClientHttpRequest request = this.createRequest(url, method);
        ...
        response = request.execute();
        ...
        if(responseExtractor != null) {
            var7 = responseExtractor.extractData(response);
            return var7;
        }
       ...
       ...
    } finally {
        if(response != null) {
            response.close();
        }

    }
}
</code>```

Where response extractor does the work for you by consuming the response using
responseExtractor.extractData(response);

And after extracting the data completely it is closing response.close() as well.

Body:
This is my Configuration for Rest Template,

    @Bean
    @Qualifier("myRestService")
    public RestTemplate createRestTemplate(@Value("${connection.timeout}") String maxConn) {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
         connectionManager.setMaxTotal(maxTotalConn);
         connectionManager.setDefaultMaxPerRoute(maxPerChannel);

        RequestConfig config = RequestConfig.custom().setConnectTimeout(100000).build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(config).build();
        ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

        RestTemplate restTemplate = new RestTemplate(factory);

        restTemplate.setErrorHandler(new RestResponseErrorHandler());
         restTemplate.setMessageConverters(createMessageConverters());

        return restTemplate;
    }

Am using PoolingHttpClientConnectionManager for managing the connections.

Its being accessed by the following code,

ResponseEntity<String> response = restClient.exchange( url, HttpMethod.GET, entity , String.class );

Do i need to release the connection after the above call or is it taken care by RestTemplate. If we need to take care of releasing connection.

Please can some one explain/show how to release the connection.

Body:
The question which you have asked:
Do i need to release the connection after the above call or is it taken care by RestTemplate. If we need to take care of releasing connection.

No, you do not need to close the connection on the response, if you use resttemplate.

From the apache httpclient, you need to consume the complete response (EntityUtils.consume(HttpEntity) and close the response.

This can be verified in the ClientConnectionRelease.java

But RestTemplate does this for you, to verify the same have a look into
RestTemplate.java

Look for method

protected <T> T doExecute(URI url,...) {
 try {
        ClientHttpRequest request = this.createRequest(url, method);
        ...
        response = request.execute();
        ...
        if(responseExtractor != null) {
            var7 = responseExtractor.extractData(response);
            return var7;
        }
       ...
       ...
    } finally {
        if(response != null) {
            response.close();
        }

    }
}

Where response extractor does the work for you by consuming the response using
responseExtractor.extractData(response);

And after extracting the data completely it is closing response.close() as well.


问:
SQL update row with info from another row (rookie)
I'm new to SQL so be gentle! I'm working for a charity in London so I'm having a stab at SQL and I've gotten stuck with something you can probably all do with your eyes shut.

I've got a table with rows that I want to update:

It's a table showing up potential duplicate records in our database. There's a stored procedure that creates a criterion field from data on a customer account and if criterion fields from 2 records match, they are flagged as potential duplicates.

We have some known duplicates that we had to create a while ago that have Placeholder as the last name.

The criterion field matches other 'real' records with real last names that we want to keep.

What I want to do is:

update the status of the Placeholder ones to Delete; and the 'real' ones to Keep (even I can totally blitz that!)

update the keep ID field of the Placeholder ones so it's the customer_no field of the row with the matching criterion field

Once that's done, another stored procedure will take it from there.

Help!

答:
Hi Welcome to Stack Overflow.

If I have understood you correctly you need something like this:

```<code>declare @customers table(
    customer_no int NOT NULL,
    matching_criteria varchar(50) NOT NULL,
    lname varchar(50) NOT NULL,
    keepID int NULL,
    [status] varchar(50) NULL);

INSERT INTO @customers VALUES(1, 'a', 'Smith', null, null);
INSERT INTO @customers VALUES(2, 'a', 'Placeholder', null, null);
INSERT INTO @customers VALUES(3, 'b', 'Jones', null, null);
INSERT INTO @customers VALUES(4, 'b', 'Placeholder', null, null);
INSERT INTO @customers VALUES(5, 'c', 'Brown', null, null);
INSERT INTO @customers VALUES(6, 'c', 'Placeholder', null, null);
INSERT INTO @customers VALUES(7, 'd', 'Williams', null, null);
INSERT INTO @customers VALUES(8, 'd', 'Placeholder', null, null);
INSERT INTO @customers VALUES(9, 'e', 'Taylor', null, null);
INSERT INTO @customers VALUES(10, 'e', 'Placeholder', null, null);

SELECT * FROM @customers;

UPDATE @customers set [status] = case lname WHEN 'Placeholder' THEN 'DELETE' ELSE 'Keep' END;

SELECT * FROM @customers;

UPDATE k
SET keepID = d.customer_no
FROM
@customers k
INNER JOIN @customers d
on k.matching_criteria = d.matching_criteria
WHERE d.[status] = 'Delete' AND k.[status] = 'Keep';

SELECT * FROM @customers;
</code>```

If you are using SQL Server you can paste this in a Query window and observe the results.

Please for future reference tell us which DB you are using, as the answers do vary from db to db.  The above is specifically SQL Server.  Whilst most dbs will behave similarly, some do not.  The above updates on a join.  Oracle, for example, does not allow this, so the syntax when using Oracle is different - Oracle can of course achieve the same thing, it just uses different SQL to do so.

Body:
Hi Welcome to Stack Overflow.

If I have understood you correctly you need something like this:

declare @customers table(
    customer_no int NOT NULL,
    matching_criteria varchar(50) NOT NULL,
    lname varchar(50) NOT NULL,
    keepID int NULL,
    [status] varchar(50) NULL);

INSERT INTO @customers VALUES(1, 'a', 'Smith', null, null);
INSERT INTO @customers VALUES(2, 'a', 'Placeholder', null, null);
INSERT INTO @customers VALUES(3, 'b', 'Jones', null, null);
INSERT INTO @customers VALUES(4, 'b', 'Placeholder', null, null);
INSERT INTO @customers VALUES(5, 'c', 'Brown', null, null);
INSERT INTO @customers VALUES(6, 'c', 'Placeholder', null, null);
INSERT INTO @customers VALUES(7, 'd', 'Williams', null, null);
INSERT INTO @customers VALUES(8, 'd', 'Placeholder', null, null);
INSERT INTO @customers VALUES(9, 'e', 'Taylor', null, null);
INSERT INTO @customers VALUES(10, 'e', 'Placeholder', null, null);

SELECT * FROM @customers;

UPDATE @customers set [status] = case lname WHEN 'Placeholder' THEN 'DELETE' ELSE 'Keep' END;

SELECT * FROM @customers;

UPDATE k
SET keepID = d.customer_no
FROM
@customers k
INNER JOIN @customers d
on k.matching_criteria = d.matching_criteria
WHERE d.[status] = 'Delete' AND k.[status] = 'Keep';

SELECT * FROM @customers;

If you are using SQL Server you can paste this in a Query window and observe the results.

Please for future reference tell us which DB you are using, as the answers do vary from db to db.  The above is specifically SQL Server.  Whilst most dbs will behave similarly, some do not.  The above updates on a join.  Oracle, for example, does not allow this, so the syntax when using Oracle is different - Oracle can of course achieve the same thing, it just uses different SQL to do so.


问:
ES7 - how can I replace Promise with await?
One thing puts me off with Promise is that it is difficult to grasp with resolve and reject. Also the need of wrapping for Promise is ugly. Unless you use it very often, I tend to forget how to use them over time. Besides, code with Promise is still messy and hard to read. Hence I don't really like using it at all - because it has not much different from the callback hell. So I thought with ES7 await, I can avoid using Promise and giving me some more faith in JavaScript, but it seems that it is not the case. For instance:

```<code>const getOne = async () => {
    return Weather.findOne(options, function(err, weather) {
        //
    });
}
const getWeather = async () => {
    const exist = await getOne();
    if (exist == null) {
        return new Promise(function(resolve, reject) {
            // Use request library.
           request(pullUrl, function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    // Resolve with the data.
                    resolve(body);
                } else {
                    // Reject with the error.
                    reject(error);
                }
            });
        });
    }
}

const insertWeather = async () => {
    try {
        const data = await getWeather();
    } catch (err) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Error occurs: ' + err);
    }
}
insertWeather();
</code>```

request(pullUrl, function (error, response, body) {} is an AJAX call from request package for nodejs.

I have to wrap it with Promise - but not precede it with await. Ideally this is what I imagine:

```<code>return await request(pullUrl, function (error, response, body) {...}
</code>```

But if I do that, I will get the request object in return, instead of the data return from the request package - at this line:

const data = await getWeather();

Any ideas or solutions to avoid using Promise in the case such as the one above?

答: As mentionned in the documentation here, you will need to wrap request with interfaces wrappers like request-promise (or you can find alternatives interface in the documentation) in order to return a Promise from request.

Body:
One thing puts me off with Promise is that it is difficult to grasp with resolve and reject. Also the need of wrapping for Promise is ugly. Unless you use it very often, I tend to forget how to use them over time. Besides, code with Promise is still messy and hard to read. Hence I don't really like using it at all - because it has not much different from the callback hell. So I thought with ES7 await, I can avoid using Promise and giving me some more faith in JavaScript, but it seems that it is not the case. For instance:

const getOne = async () => {
    return Weather.findOne(options, function(err, weather) {
        //
    });
}
const getWeather = async () => {
    const exist = await getOne();
    if (exist == null) {
        return new Promise(function(resolve, reject) {
            // Use request library.
           request(pullUrl, function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    // Resolve with the data.
                    resolve(body);
                } else {
                    // Reject with the error.
                    reject(error);
                }
            });
        });
    }
}

const insertWeather = async () => {
    try {
        const data = await getWeather();
    } catch (err) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Error occurs: ' + err);
    }
}
insertWeather();

request(pullUrl, function (error, response, body) {} is an AJAX call from request package for nodejs.

I have to wrap it with Promise - but not precede it with await. Ideally this is what I imagine:

return await request(pullUrl, function (error, response, body) {...}

But if I do that, I will get the request object in return, instead of the data return from the request package - at this line:

const data = await getWeather();

Any ideas or solutions to avoid using Promise in the case such as the one above?


问:
Side loading instant app failed: Reading bundle timed out
Unable to use Android Emulator, for testing the Instant Apps!! Every-time I'm getting "Side loading instant app failed: Reading bundle timed out."

I'm using, Android Studio 3.0 Canary-5

Emulator: Nexus 5X image running Android 6.0 (API level 23), x86, with Google APIs. Google APIs Intel x86 Atom System Image (Revision 21)

Note: After updating Android Studio 3.0 (Canary-4 > Canary-5) &
  Emulator system image from revision (20 > 21). I'm unable to run the
  instant App through emulator. Always I'm getting the error message saying "Side loading instant app failed: Reading bundle timed out."

```<code>com.google.android.gms.persistent E/InstantApps: DomainFilterImpl: Error while reading domain filter from WHAPI
                                                                              java.util.concurrent.ExecutionException: awjr: INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header.
                                                                                at java.util.concurrent.FutureTask.report(FutureTask.java:94)
                                                                                at java.util.concurrent.FutureTask.get(FutureTask.java:164)
                                                                                at tey.get(:com.google.android.gms:1)
                                                                                at tir.a(:com.google.android.gms:25)
                                                                                at tir.a(:com.google.android.gms:16)
                                                                                at tir.a(:com.google.android.gms:9)
                                                                                at tir.b(:com.google.android.gms:0)
                                                                                at tio.b(:com.google.android.gms:0)
                                                                                at com.google.android.gms.instantapps.routing.DomainFilterUpdateChimeraService.a(:com.google.android.gms:14)
                                                                                at tiu.run(:com.google.android.gms:0)
                                                                                at lhb.run(:com.google.android.gms:24)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                at lmc.run(:com.google.android.gms:0)
                                                                                at java.lang.Thread.run(Thread.java:818)
                                                                               Caused by: awjr: INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header.
                                                                                at awjn.c(:com.google.android.gms:0)
                                                                                at lbb.a(:com.google.android.gms:97)
                                                                                at tem.b(:com.google.android.gms:43)
                                                                                at tem.a(:com.google.android.gms:0)
                                                                                at tez.call(:com.google.android.gms:1)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at lhb.run(:com.google.android.gms:24)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                at lmc.run(:com.google.android.gms:0)
                                                                                at java.lang.Thread.run(Thread.java:818)

    W/ActivityManager: Unable to start service Intent { act=com.google.android.instantapps.devman.iapk.LOAD cmp=com.google.android.instantapps.devman/.iapk.IapkLoadService (has extras) } U=0: not found
</code>```

Appreciate your help.

Update:

Found solution in Android studio release notes here. This is a known-issue under Android Studio canary-5.

Reliability issue with instant app provisioning cache. If you manually
  unprovision your device or emulator image for instant app development,
  and then deploy the instant app from Android Studio, the deployment
  will fail because Android Studio will not provision your
  device/emulator image again. To workaround for this issue: Go into the
  Run Configuration dialog and select the instantapp module on the
  left-hand pane. Click the “Instant App Provision” task under “Before
  launch:Gradle-aware Make, Instant App Provision” Click the edit (the
  pencil icon) Check “Clear provisioned devices cache”

答:
I had a similar error when building the project using compileSDK 26 and targetSDK 26.
Going back to SDK 25 and supportLibrary 25.4.0 solved the problem for me.

Body:
Unable to use Android Emulator, for testing the Instant Apps!! Every-time I'm getting "Side loading instant app failed: Reading bundle timed out."

I'm using, Android Studio 3.0 Canary-5

Emulator: Nexus 5X image running Android 6.0 (API level 23), x86, with Google APIs. Google APIs Intel x86 Atom System Image (Revision 21)

Note: After updating Android Studio 3.0 (Canary-4 > Canary-5) &
  Emulator system image from revision (20 > 21). I'm unable to run the
  instant App through emulator. Always I'm getting the error message saying "Side loading instant app failed: Reading bundle timed out."

com.google.android.gms.persistent E/InstantApps: DomainFilterImpl: Error while reading domain filter from WHAPI
                                                                              java.util.concurrent.ExecutionException: awjr: INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header.
                                                                                at java.util.concurrent.FutureTask.report(FutureTask.java:94)
                                                                                at java.util.concurrent.FutureTask.get(FutureTask.java:164)
                                                                                at tey.get(:com.google.android.gms:1)
                                                                                at tir.a(:com.google.android.gms:25)
                                                                                at tir.a(:com.google.android.gms:16)
                                                                                at tir.a(:com.google.android.gms:9)
                                                                                at tir.b(:com.google.android.gms:0)
                                                                                at tio.b(:com.google.android.gms:0)
                                                                                at com.google.android.gms.instantapps.routing.DomainFilterUpdateChimeraService.a(:com.google.android.gms:14)
                                                                                at tiu.run(:com.google.android.gms:0)
                                                                                at lhb.run(:com.google.android.gms:24)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                at lmc.run(:com.google.android.gms:0)
                                                                                at java.lang.Thread.run(Thread.java:818)
                                                                               Caused by: awjr: INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header.
                                                                                at awjn.c(:com.google.android.gms:0)
                                                                                at lbb.a(:com.google.android.gms:97)
                                                                                at tem.b(:com.google.android.gms:43)
                                                                                at tem.a(:com.google.android.gms:0)
                                                                                at tez.call(:com.google.android.gms:1)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at lhb.run(:com.google.android.gms:24)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                at lmc.run(:com.google.android.gms:0)
                                                                                at java.lang.Thread.run(Thread.java:818)

    W/ActivityManager: Unable to start service Intent { act=com.google.android.instantapps.devman.iapk.LOAD cmp=com.google.android.instantapps.devman/.iapk.IapkLoadService (has extras) } U=0: not found

Appreciate your help.

Update:

Found solution in Android studio release notes here. This is a known-issue under Android Studio canary-5.

Reliability issue with instant app provisioning cache. If you manually
  unprovision your device or emulator image for instant app development,
  and then deploy the instant app from Android Studio, the deployment
  will fail because Android Studio will not provision your
  device/emulator image again. To workaround for this issue: Go into the
  Run Configuration dialog and select the instantapp module on the
  left-hand pane. Click the “Instant App Provision” task under “Before
  launch:Gradle-aware Make, Instant App Provision” Click the edit (the
  pencil icon) Check “Clear provisioned devices cache”


答:
```<code>.container {
    display: flex;
    width: 60%;
    height: 100%;  /* takes full height so that it can align vertically  */
    justify-content: center; /* horizontal center */
    align-items: center;  /* vertical center */
    margin: 0 auto;   /* makes container in center  */

}
</code>```

Title: I need to align 3 divs in the center of my page with flexbox

Body:
I have a flex container and 3 divs inside it of equal width and I am trying to get the divs to align in the centre of the page with equal distance between them and also equal distance from the edge of the page.

.container {
    display : flex;
    width : 60%;
}

.para {
    width : 33%;
    padding : 1em;
    border:.5px solid black;
    margin :1em;
}

para one para one para one para one para one para one
para one para one para one para one para one

para two para two para two para two para two para two
para two para two para two para two para two para two

para three  para three para three para three para
three para three para three para three para three para three


问:
issue with FILE
I'm getting the folowing error for below code,
"1506-221 (S) Initializer must be a valid constant expression"

```<code>FILE          *fp[] = {stdout, dump_f};
</code>```

is this acceptable? what is the proper way to achive this?

答:
More than likely, stdout and/or dump_f are macros or (more likely the problem) external globals.

If I have this code:

```<code>// external.c
int hello = 1234;

// external.h
extern int hello;

// main.c
#include "external.h"

int world = hello; // error!
</code>```

You would receive an error at the indicated line because the value of hello is not known.

stdout and dump_f are most likely declared as extern globals, like so:

```<code>extern FILE *stdout, *stdin, *stderr, *dump_f;
</code>```

OwnerDisplayName: Thi

Title: issue with FILE

Body:
I'm getting the folowing error for below code,
"1506-221 (S) Initializer must be a valid constant expression"

FILE          *fp[] = {stdout, dump_f};

is this acceptable? what is the proper way to achive this?

LastEditorDisplayName: strager

Body:
More than likely, stdout and/or dump_f are macros or (more likely the problem) external globals.

If I have this code:

// external.c
int hello = 1234;

// external.h
extern int hello;

// main.c
#include "external.h"

int world = hello; // error!

You would receive an error at the indicated line because the value of hello is not known.

stdout and dump_f are most likely declared as extern globals, like so:

extern FILE *stdout, *stdin, *stderr, *dump_f;

OwnerDisplayName: strager


问:
Android admob can't see
Admob code can't see on device.

I followed the instructions here: http://www.admob.com/docs/AdMob_Android_SDK_Instructions.pdf

everything ok, but the 6. not clear for me

"
  Step 6

When integrating AdMob ads into your application it is
  recommended to use test mode. In test mode test, ads are always
  returned. Test mode is enabled on a per-device basis. To enable test
  mode for a device, first request an ad, then look in LogCat for a line
  like the following: To get test ads on the emulator use
  AdManager.setTestDevices... Once you have the device ID you can enable
  test mode by calling AdManager.setTestDevices:

```<code>AdManager.setTestDevices( new String[] { AdManager.TEST_EMULATOR, //    Android emulator
"E83D20734F72FB3108F104ABC0FFC738", // My T-Mobile G1 Test Phone
} ); }
</code>```

"

What is that long number on the code? How do I get that number?

In the oncreate method I put this code:

```<code>AdManager.setTestDevices(new String[] { AdManager.TEST_EMULATOR } );
</code>```

(into the help activity, not into the main activity)

答: Of course you must start the app on the real device to get a device id</p>

Title: Android admob can't see

Body:
Admob code can't see on device.

I followed the instructions here: http://www.admob.com/docs/AdMob_Android_SDK_Instructions.pdf

everything ok, but the 6. not clear for me

"
  Step 6

When integrating AdMob ads into your application it is
  recommended to use test mode. In test mode test, ads are always
  returned. Test mode is enabled on a per-device basis. To enable test
  mode for a device, first request an ad, then look in LogCat for a line
  like the following: To get test ads on the emulator use
  AdManager.setTestDevices... Once you have the device ID you can enable
  test mode by calling AdManager.setTestDevices:

AdManager.setTestDevices( new String[] { AdManager.TEST_EMULATOR, //    Android emulator
"E83D20734F72FB3108F104ABC0FFC738", // My T-Mobile G1 Test Phone
} ); }

"

What is that long number on the code? How do I get that number?

In the oncreate method I put this code:

AdManager.setTestDevices(new String[] { AdManager.TEST_EMULATOR } );

(into the help activity, not into the main activity)


Title: How can I group by month from a date field using Python and Pandas?

Body:
I have a dataframe, df, which is as follows:

| date      | Revenue |
|-----------|---------|
| 6/2/2017  | 100     |
| 5/23/2017 | 200     |
| 5/20/2017 | 300     |
| 6/22/2017 | 400     |
| 6/21/2017 | 500     |

I need to group the above data by month to get output as:

| date | SUM(Revenue) |
|------|--------------|
| May  | 500          |
| June | 1000         |

I tried this code, but it did not work:

df.groupby(month('date')).agg({'Revenue': 'sum'})

I want to only use Pandas or NumPy and no additional libraries.

Body:
Try this:

In [6]: df['date'] = pd.to_datetime(df['date'])

In [7]: df
Out[7]:
        date  Revenue
0 2017-06-02      100
1 2017-05-23      200
2 2017-05-20      300
3 2017-06-22      400
4 2017-06-21      500

In [59]: df.groupby(df['date'].dt.strftime('%B'))['Revenue'].sum().sort_values()
Out[59]:
date
May      500
June    1000


问:
How can I make my cells selectable when there is an UIView below the UICollectionView?
I have a collection view, and added a UIView below it. The cells shows up on top of it, but they aren't selectable. How can I make them selectable again?

What I have tried so far:

UIView has zPosition -1 and my cells have +1
UIView.isUserInteractionEnabled = true

I have tried to add the UIView both as view.addSubview and collectionView?.addSubview

collectionView?.insertSubview(UIView, belowSubview: collectionView!)

This guy has the same problem, with no solution provided: Inserting Subview Below UICollectionView

Edit: I'm using this code to determine what cells are selected

```<code>override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    //Code here...
}
</code>```

It all works when there is no UIView below. But I want to have a visible "container" for my collectionview content insets, so I created an UIView.
Problem is the above code doesn't get fired at all when clicking on the cells with the UIView below.

答:
It's happening because your other view is covering the collection view.

Use view.addSubview first and then call view.bringSubview(toFront: collectionView!)

Body:
I have a collection view, and added a UIView below it. The cells shows up on top of it, but they aren't selectable. How can I make them selectable again?

What I have tried so far:

UIView has zPosition -1 and my cells have +1
UIView.isUserInteractionEnabled = true

I have tried to add the UIView both as view.addSubview and collectionView?.addSubview

collectionView?.insertSubview(UIView, belowSubview: collectionView!)

This guy has the same problem, with no solution provided: Inserting Subview Below UICollectionView

Edit: I'm using this code to determine what cells are selected

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    //Code here...
}

It all works when there is no UIView below. But I want to have a visible "container" for my collectionview content insets, so I created an UIView.
Problem is the above code doesn't get fired at all when clicking on the cells with the UIView below.


问:
Fading between images
How can i fade rotate between two images using jQuery?
Say for example.

```<code><img src="image01.jpg" />
<img src="image02.jpg" />
</code>```

I like the images to fade in/out between for say 2seconds each.

Thanks! Much appreciated. :)

答:
You can do it without jquery. Only with css :
And cool fade between image

.fade img {
  transition: all .8s;
  max-width: 200px;
}
.fade:hover img:nth-child(2) {
 opacity: 0;
}
.fade img:first-child {
  position: absolute;
 z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='fade'>
  <img src="https://image.freepik.com/free-vector/software-logo_1103-316.jpg">
  <img src='https://image.freepik.com/free-vector/m-letter-logo-template_1061-150.jpg'>
</div></code>```

Title: Fading between images

Body:
How can i fade rotate between two images using jQuery?
Say for example.

I like the images to fade in/out between for say 2seconds each.

Thanks! Much appreciated. :)

Body:
You can do it without jquery. Only with css :
And cool fade between image

.fade img {
  transition: all .8s;
  max-width: 200px;
}
.fade:hover img:nth-child(2) {
 opacity: 0;
}
.fade img:first-child {
  position: absolute;
 z-index: -1;
}

<div class='fade'>
  <img src="https://image.freepik.com/free-vector/software-logo_1103-316.jpg">
  <img src='https://image.freepik.com/free-vector/m-letter-logo-template_1061-150.jpg'>
</div>