问:
Angular How do you know when Authentication Status changed?
Im currently working on a webapp with a login. But I have a problem with the Logout Button. The Logout Button is only supposed to show when you are logged in and vanish when you logout.

Thats my Button (menu-items.component):

```<code><ul class="list-group">
  <li *ngIf="isLoggedIn" (click)="onLogout()">Logout</li>
</ul>
</code>```

Code (menu-items.component):

```<code>import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../http.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-menu-items',
  templateUrl: './menu-items.component.html',
  styleUrls: ['./menu-items.component.css']
})
export class MenuItemsComponent implements OnInit {
  isLoggedIn: boolean = false;
  constructor(private httpService: HttpService) {

  }

  ngOnInit() {

  }
  onSignout(){
    this.isLoggedIn = false;
    localStorage.removeItem('currentUser');
  }
}
</code>```

Basically when I login I want "isLoggedIn" to be "true".

Login Part (login.component):

```<code> onSignin(){

    const username = this.loginForm.get('username').value;
    const password = this.loginForm.get('password').value;

    this.httpServie.sendDataLogin("grant_type=password&username=" + username + "&password=" + password)
      .subscribe(
        data => {
         this.token = JSON.parse(data["_body"]).access_token
         this.username = JSON.parse(data["_body"]).userName
         localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}))

        },
        err => {
          if (err.error instanceof Error) {

            this.ServerErrorMsg = err.error.message;
          } else {

            const returnArray = [];
            this.ServerErrorMsg = JSON.parse(err._body).error_description + "\n";
          }
        }
      );
  }
</code>```

The Login Part is working! Im sending my data to my API and in return im getting my Token.

But the thing is how do I tell my isLoggedIn boolean that im logged in now? I think I need an observable or something to listen to with subscribe, right?
Im new to Angular and I dont really understand observables. Could anyone help me, please?

答:
what i suggest to you is to do in your service (better) or in your component (no so better) one getter method like:

private _isLogged:boolean =false;

```<code>isLoggedIn(){

 var local= localStorage.getItem('currentUser');
var token= JSON.Parse(local) as any;

return local && token && token.access_token;
}
onSignin(){

    const username = this.loginForm.get('username').value;
    const password = this.loginForm.get('password').value;

    this.httpServie.sendDataLogin("grant_type=password&username=" + username + "&password=" + password)
      .subscribe(
        data => {
         this.token = JSON.parse(data["_body"]).access_token
         this.username = JSON.parse(data["_body"]).userName
         localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}));
</code>```

this._isLogged = true; //<-- sei it to true

```<code>        },
        err => {
          if (err.error instanceof Error) {

            this.ServerErrorMsg = err.error.message;
          } else {

            const returnArray = [];
            this.ServerErrorMsg = JSON.parse(err._body).error_description + "\n";
          }
        }
      );
  }
</code>```

then in your code :

```<code><ul class="list-group">
  <li *ngIf="isLoggedIn()" (click)="onLogout()">Logout</li>
</ul>
</code>```

Hope it helps you!

Body:
Im currently working on a webapp with a login. But I have a problem with the Logout Button. The Logout Button is only supposed to show when you are logged in and vanish when you logout.

Thats my Button (menu-items.component):

Logout

Code (menu-items.component):

import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../http.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-menu-items',
  templateUrl: './menu-items.component.html',
  styleUrls: ['./menu-items.component.css']
})
export class MenuItemsComponent implements OnInit {
  isLoggedIn: boolean = false;
  constructor(private httpService: HttpService) {

  }

  ngOnInit() {

  }
  onSignout(){
    this.isLoggedIn = false;
    localStorage.removeItem('currentUser');
  }
}

Basically when I login I want "isLoggedIn" to be "true".

Login Part (login.component):

 onSignin(){

    const username = this.loginForm.get('username').value;
    const password = this.loginForm.get('password').value;

    this.httpServie.sendDataLogin("grant_type=password&username=" + username + "&password=" + password)
      .subscribe(
        data => {
         this.token = JSON.parse(data["_body"]).access_token
         this.username = JSON.parse(data["_body"]).userName
         localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}))

        },
        err => {
          if (err.error instanceof Error) {

            this.ServerErrorMsg = err.error.message;
          } else {

            const returnArray = [];
            this.ServerErrorMsg = JSON.parse(err._body).error_description + "\n";
          }
        }
      );
  }

The Login Part is working! Im sending my data to my API and in return im getting my Token.

But the thing is how do I tell my isLoggedIn boolean that im logged in now? I think I need an observable or something to listen to with subscribe, right?
Im new to Angular and I dont really understand observables. Could anyone help me, please?

Body:
what i suggest to you is to do in your service (better) or in your component (no so better) one getter method like:

private _isLogged:boolean =false;

isLoggedIn(){

 var local= localStorage.getItem('currentUser');
var token= JSON.Parse(local) as any;

return local && token && token.access_token;
}
onSignin(){

    const username = this.loginForm.get('username').value;
    const password = this.loginForm.get('password').value;

    this.httpServie.sendDataLogin("grant_type=password&username=" + username + "&password=" + password)
      .subscribe(
        data => {
         this.token = JSON.parse(data["_body"]).access_token
         this.username = JSON.parse(data["_body"]).userName
         localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}));

this._isLogged = true; //<-- sei it to true

        },
        err => {
          if (err.error instanceof Error) {

            this.ServerErrorMsg = err.error.message;
          } else {

            const returnArray = [];
            this.ServerErrorMsg = JSON.parse(err._body).error_description + "\n";
          }
        }
      );
  }

then in your code :

<ul class="list-group">
  <li *ngIf="isLoggedIn()" (click)="onLogout()">Logout</li>
</ul>

Hope it helps you!


来源: stackexchange

问:
How to do a specific action on the first iteration of a while loop in a bash script
I need to make a script do a specific action on first loop iteration.

```<code>for file in /path/to/files/*; do
    echo "${file}"
done
</code>```

I want this output:

```<code>First run: file1
file2
file3
file4
...
</code>```

答:
A very common arrangement is to change a variable inside the loop.</p>

```<code>noise='First run: '
for file in /path/to/files/*; do
    echo "$noise$file"
    noise=''
done
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to make a script do a specific action on first loop iteration.

for file in /path/to/files/*; do
    echo "${file}"
done

I want this output:

First run: file1
file2
file3
file4
...

Body:
A very common arrangement is to change a variable inside the loop.

noise='First run: '
for file in /path/to/files/*; do
    echo "$noise$file"
    noise=''
done


问:
Remove item from list if in another list (lists of list)
I have a list that looks like this

```<code>a = [('Eth1', 'desc', 'date'), ('Eth2', 'dest', 'date'), ('Eth3', 'dest', 'date')]
</code>```

I have another list that has this:

```<code>b = = ['Eth1', 'Eth2']
</code>```

I want to remove all occurrences of b in a with its corresponding data, so at the minute I have

```<code>c = list(set(a) - set(b))
print c
</code>```

I want c to look like this

```<code>c = ['Eth3', 'dest', 'date']
</code>```

But it just prints the list in a different order, like this

```<code>[('Eth2', 'dest', 'date'), ('Eth1', 'desc', 'date'), ('Eth3', 'dest', 'date')]
</code>```

What would the best way to do this be?

答:
You can also do it using the filter function:

```<code>a = [('Eth1', 'desc', 'date'), ('Eth2', 'dest', 'date'), ('Eth3', 'dest', 'date')]
b = ['Eth1', 'Eth2']

res = list(filter(lambda i: i[0] not in b, a))
print(res)
</code>```

Output:

```<code>[('Eth3', 'dest', 'date')]
</code>```

Body:
I have a list that looks like this

a = [('Eth1', 'desc', 'date'), ('Eth2', 'dest', 'date'), ('Eth3', 'dest', 'date')]

I have another list that has this:

b = = ['Eth1', 'Eth2']

I want to remove all occurrences of b in a with its corresponding data, so at the minute I have

c = list(set(a) - set(b))
print c

I want c to look like this

c = ['Eth3', 'dest', 'date']

But it just prints the list in a different order, like this

[('Eth2', 'dest', 'date'), ('Eth1', 'desc', 'date'), ('Eth3', 'dest', 'date')]

What would the best way to do this be?

Body:
You can also do it using the filter function:

a = [('Eth1', 'desc', 'date'), ('Eth2', 'dest', 'date'), ('Eth3', 'dest', 'date')]
b = ['Eth1', 'Eth2']

res = list(filter(lambda i: i[0] not in b, a))
print(res)

Output:

[('Eth3', 'dest', 'date')]


问:
half yearly colorbar in matplotlib and pandas
I have a panda dataframe. I am making scatter plot and tried to categorize the data based on colorbar. I did it for monthly classification and quality classification as shown in the example code below.

```<code>a = np.random.rand(366)
b = np.random.rand(366)*0.4
index = (pd.date_range(pd.to_datetime('01-01-2000'), periods=366))
df = pd.DataFrame({'a':a,'b':b},index = index)
plt.scatter(df['a'],df['b'],c = df.index.month)
plt.colorbar()
</code>```

And also for quality:

```<code>plt.scatter(df['a'],df['b'],c = df.index.quarter)
plt.colorbar()
</code>```

My question: is there any way to categorize by half yearly. for example from the month 1-6 and 7-12 and also by month like: 10-3 and 4-9
Thank you and your help/suggestion will be highly appreciated.

答:
Make a custom function to put in scatter function to color argument. I made an example for half yearly division. You can use it as template for your own split function:

```<code>import numpy as np
import pandas as pd
import matplotlib.pylab as plt

# if month is 1 to 6 then the first halfyear else the second halfyear
def halfyear(m):
    return 0 if (m <= 6) else 1
# vectorize function to use with Series
hy = np.vectorize(halfyear)

a = np.random.rand(366)
b = np.random.rand(366)*0.4
index = (pd.date_range(pd.to_datetime('01-01-2000'), periods=366))
df = pd.DataFrame({'a':a,'b':b},index = index)

# apply custom function 'hy' for 'c' argument
plt.scatter(df['a'],df['b'], c = hy(df.index.month))
plt.colorbar()

plt.show()
</code>```

Another way to use lambda function like:

```<code>plt.scatter(df['a'],df['b'], \
 c = df.index.map(lambda m: 0 if (m.month > 0 and m.month < 7) else 1))
</code>```

Body:
I have a panda dataframe. I am making scatter plot and tried to categorize the data based on colorbar. I did it for monthly classification and quality classification as shown in the example code below.

a = np.random.rand(366)
b = np.random.rand(366)*0.4
index = (pd.date_range(pd.to_datetime('01-01-2000'), periods=366))
df = pd.DataFrame({'a':a,'b':b},index = index)
plt.scatter(df['a'],df['b'],c = df.index.month)
plt.colorbar()

And also for quality:

plt.scatter(df['a'],df['b'],c = df.index.quarter)
plt.colorbar()

My question: is there any way to categorize by half yearly. for example from the month 1-6 and 7-12 and also by month like: 10-3 and 4-9
Thank you and your help/suggestion will be highly appreciated.

Body:
Make a custom function to put in scatter function to color argument. I made an example for half yearly division. You can use it as template for your own split function:

import numpy as np
import pandas as pd
import matplotlib.pylab as plt

# if month is 1 to 6 then the first halfyear else the second halfyear
def halfyear(m):
    return 0 if (m <= 6) else 1
# vectorize function to use with Series
hy = np.vectorize(halfyear)

a = np.random.rand(366)
b = np.random.rand(366)*0.4
index = (pd.date_range(pd.to_datetime('01-01-2000'), periods=366))
df = pd.DataFrame({'a':a,'b':b},index = index)

# apply custom function 'hy' for 'c' argument
plt.scatter(df['a'],df['b'], c = hy(df.index.month))
plt.colorbar()

plt.show()

Another way to use lambda function like:

plt.scatter(df['a'],df['b'], \
 c = df.index.map(lambda m: 0 if (m.month > 0 and m.month < 7) else 1))


问:
Import XMI Deletes Sequences
I import XMI of a package hierarchy to a local model, and it's successfully imported.

When I import the same XMI to a shared model (Oracle DB), all the sequences and messages in sequence diagrams are deleted.

Any ideas?

答:
With Enterprise Architect v.13 I managed to get rid of the trouble;
Supposing that your sequences has Lifelines with Instance Classifier set to the Class/Component that you would like to use in our sequence:

Right Click on the Package that you would like to Export

Go to Package Baseline and create New Baseline for the package

Once Baseline is shown, from the "Baseline" choose "Export File"

Save it as XMI File

Import XMI file in the other EAP Project.

I compared the XMI file generated from a Baseline with an XMI generated by clicking on the option "Import/Export" and they have differences... it seems like that the Exported XMI of the Baseline contains full information of the model (included root nodes), thus I think the import process might resolve each link to objects that are not hold in the same package...

Title: Import XMI Deletes Sequences


问:
Getting the GUID of the current user?
I want to add a user's GUID in with the information I retrieve from a user when they submit a post. How can I get the GUID?

I am using the default authentication system that comes along with an ASP.NET MVC application.

答:
If you are using the ASP.NET Membership provider:

```<code>MembershipUser user = Membership.GetUser(User.Identity.Name);
Guid guid = (Guid)user.ProviderUserKey;
</code>```

or simply:

```<code>Guid guid = (Guid)Membership.GetUser().ProviderUserKey;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Getting the GUID of the current user?

Body:
If you are using the ASP.NET Membership provider:

MembershipUser user = Membership.GetUser(User.Identity.Name);
Guid guid = (Guid)user.ProviderUserKey;

or simply:

Guid guid = (Guid)Membership.GetUser().ProviderUserKey;


问:
Java client and python server connection
i am working on an app in android studio and basiclly i need that whenever i clicked a specific button it will create a connection between the java client and python server.

I first checked when u enter the page\activity of the specific button if there is a wifi connection in the phone.

It works fine. then i tried to do this and it didnt work (Important to say that the current code make my phone and my app crash and stop)

simple server:

```<code>HOST = '192.168.1.21'
PORT = 9000

def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((HOST, PORT))
    server_socket.listen(10)
    client_socket, client_address = server_socket.accept()
    print 'Connect with ' + client_address[0]
    data = client_socket.recv(1024)
    print "data :"
    print data
    print " end"
    if data == HOST+"/n":
        print 'hi'
    else:
        i = 0
        while i < 15:
            print i
            i += 1
    client_socket.close()
    server_socket.close()
if __name__ == '__main__':
    main()
</code>```

this is just to check a connection. it might look strange because of the host +/n in the if . i recently chenged it because i am new to java and dont know how the data is sent. but that is not the problem rn.

```<code>public void ButtonClicked(View view) {
        EditText editText = findViewById(R.id.edit_text);
        final String ip = editText.getText().toString();
        Toast.makeText(this, ip, Toast.LENGTH_SHORT).show();
        try {
            InetAddress host = InetAddress.getByName(ip);
            final Client client = new Client(host, 9000);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        client.send(ip);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            client.send(ip);
        }
        catch (IOException e) {
            System.out.println("Caught Exception: " + e.toString());
        }
</code>```

i read that in android studio 3.0 u need to create a thread when u send data.
the client class that u see here :

```<code>public class Client
{
    private Socket socket = null;
    private BufferedReader reader = null;
    private BufferedWriter writer = null;

    public Client(InetAddress address, int port) throws IOException
    {
        socket = new Socket(address, port);
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    }

    public void send(String msg) throws IOException
    {
        writer.write(msg, 0, msg.length());
        writer.flush();
    }

    public String recv() throws IOException
    {
        return reader.readLine();
    }

}
</code>```

it might be just a simple thing that i dont know of but those are the codes and i cant connect to the server. i figured out that the server works fine because if im connecting from the phone to 192.168.1.21 on the net i receive the connection and it does thw little while.
ty for the help - i would like to get the simplest fixes because im new to java.
(sorry if there where grammer\ spelling mistakes)

Edit- logcat for the crash

答: At the end of your log it says NetworkOnMainThread. In your code there is a line client.send(ip) below your seperate thread which is executed at the main thread.

Body:
i am working on an app in android studio and basiclly i need that whenever i clicked a specific button it will create a connection between the java client and python server.

I first checked when u enter the page\activity of the specific button if there is a wifi connection in the phone.

It works fine. then i tried to do this and it didnt work (Important to say that the current code make my phone and my app crash and stop)

simple server:

HOST = '192.168.1.21'
PORT = 9000

def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((HOST, PORT))
    server_socket.listen(10)
    client_socket, client_address = server_socket.accept()
    print 'Connect with ' + client_address[0]
    data = client_socket.recv(1024)
    print "data :"
    print data
    print " end"
    if data == HOST+"/n":
        print 'hi'
    else:
        i = 0
        while i < 15:
            print i
            i += 1
    client_socket.close()
    server_socket.close()
if __name__ == '__main__':
    main()

this is just to check a connection. it might look strange because of the host +/n in the if . i recently chenged it because i am new to java and dont know how the data is sent. but that is not the problem rn.

public void ButtonClicked(View view) {
        EditText editText = findViewById(R.id.edit_text);
        final String ip = editText.getText().toString();
        Toast.makeText(this, ip, Toast.LENGTH_SHORT).show();
        try {
            InetAddress host = InetAddress.getByName(ip);
            final Client client = new Client(host, 9000);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        client.send(ip);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            client.send(ip);
        }
        catch (IOException e) {
            System.out.println("Caught Exception: " + e.toString());
        }

i read that in android studio 3.0 u need to create a thread when u send data.
the client class that u see here :

public class Client
{
    private Socket socket = null;
    private BufferedReader reader = null;
    private BufferedWriter writer = null;

    public Client(InetAddress address, int port) throws IOException
    {
        socket = new Socket(address, port);
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    }

    public void send(String msg) throws IOException
    {
        writer.write(msg, 0, msg.length());
        writer.flush();
    }

    public String recv() throws IOException
    {
        return reader.readLine();
    }

}

it might be just a simple thing that i dont know of but those are the codes and i cant connect to the server. i figured out that the server works fine because if im connecting from the phone to 192.168.1.21 on the net i receive the connection and it does thw little while.
ty for the help - i would like to get the simplest fixes because im new to java.
(sorry if there where grammer\ spelling mistakes)

Edit- logcat for the crash


问:
How to order by aggregate function results?
How to get result of below tables.

catTbl

```<code>catId, name
11     fruit
12     vegetable
</code>```

prodTbl

```<code>pId | catTbl_catId | name
1     11             apple
2     11             orange
3     12             slag
</code>```

I want to get result for

```<code> cat name     total count
 fruit        2
 vegetable    1
</code>```

order by with total count--

How to use order by total below cakephp 3 query..

```<code> $cats=$this->catTbl->find()
            ->where(['catTbl.status'=>'1','is_deleted'=>'0'])
            ->select(['name','catId','modified'])
            ->contain([
            'prodTbl' => function($q) {
              $q->select([
                   'prodTbl.catTbl_catId',
                   'total' => $q->func()->count('prodTbl.catTbl_catId')
              ])
              ->where(['prodTbl.status'=>'1','prodTbl.is_deleted'=>'0'])
              ->group(['prodTbl.catTbl_catId']);

              return $q;
          }
          ]);
</code>```

Body:
How to get result of below tables.

catTbl

catId, name
11     fruit
12     vegetable

prodTbl

pId | catTbl_catId | name
1     11             apple
2     11             orange
3     12             slag

I want to get result for

 cat name     total count
 fruit        2
 vegetable    1

order by with total count--

How to use order by total below cakephp 3 query..

 $cats=$this->catTbl->find()
            ->where(['catTbl.status'=>'1','is_deleted'=>'0'])
            ->select(['name','catId','modified'])
            ->contain([
            'prodTbl' => function($q) {
              $q->select([
                   'prodTbl.catTbl_catId',
                   'total' => $q->func()->count('prodTbl.catTbl_catId')
              ])
              ->where(['prodTbl.status'=>'1','prodTbl.is_deleted'=>'0'])
              ->group(['prodTbl.catTbl_catId']);

              return $q;
          }
          ]);

Body:
I managed to get the results

+------------+---------+
|    Cat     |  Total  |
+------------+---------+
| fruit      |    2    |
| vegetable  |    1    |
+------------+---------+

using this query

$query = $this->Prod->find();

    $cats = $query->select([
        'Cat.name',
        'total' => $query->func()->count('catId')
    ])
    ->contain([
        'Cat'
    ])
    ->group([
        'catId'
    ])
    ->order([
        'total' => 'DESC'
    ])
    ->all();


问:
Laravel - Search through table by name & pagination
I'm making an admin panel and on my users page, I have a table with 53 users. (without pagination). On top of that table, I have an input field which is supposed to act as a search bar. But I don't know how to make it. I want the user to search a username and then the results immediately pop-up without a refresh. So the search needs to be searching by first name.

Are there any good tutorials for this that can help me on my way?

Also, The table has 53 users. How can I paginate the table to show only 25 per page? Because my table currently looks like this: https://imgur.com/a/bOgUn. Thanks in advance!

答:
You can use pagination with search like this.</p>

```<code>    $search    = strtolower($request->input('search'));
    if ($search != '') {
        $users = $user->where('name', 'like', "%$search%")
                      ->orWhere('email', 'like', "%$search%")
                      ->paginate(10);
    } else {
        $users = $user->paginate(10);
    }
</code>```

Body:
You can use pagination with search like this.

    $search    = strtolower($request->input('search'));
    if ($search != '') {
        $users = $user->where('name', 'like', "%$search%")
                      ->orWhere('email', 'like', "%$search%")
                      ->paginate(10);
    } else {
        $users = $user->paginate(10);
    }


问:
UnsatisfiedLinkError on ANeuralNetworksModel_identifyInputsAndOutputs in NNAPI of Android 8.1 Preview
I wrote a demo of NNAPI. But The app crashes with the error "java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol 'ANeuralNetworksModel_identifyInputsAndOutputs'". After I removed the line contains ANeuralNetworksModel_identifyInputsAndOutputs(and remains other lines about NNAPI, such as ANeuralNetworksModel_addOperation and so on), the app doesn't crash anymore.

My minSdkVersion, compileSdkVersion, targetSdkVersion are all 27.

Is it a bug, or just my fault? Could you please help me? Thanks in advance.

Thanks to the excellent solution following, I have written an NNAPI wrapper Library and demo, and published it on GitHub, only four lines are needed to deploy a model on phone. I hope my project would help developers who interested in NNAPI

答:
This issue is happening because the SDK package is not correct. Update the SDK package to the latest one.
If SDK manager is not showing any updates, then in Android Studio, from the File Menu, Chose the option Invalidate Caches and Restart.
Once this is done, Android studio will ask if any pending SDK updates are there.
Once the updates are installed, then recreate the new Virtual Device with AVD manager(if you are using Virtual Device).
And your program is ready to go...

SDK\system-images\android-27\google_apis\x86\source.properties

```<code>  Pkg.Desc=System Image x86 with Google APIs.
  ****Pkg.Revision=2****
  Pkg.Dependencies=emulator#26.1.3
  ****AndroidVersion.ApiLevel=27****
  SystemImage.Abi=x86
  SystemImage.TagId=google_apis
  SystemImage.TagDisplay=Google APIs
  SystemImage.GpuSupport=true
  Addon.VendorId=google
  Addon.VendorDisplay=Google Inc.
</code>```

Body:
This issue is happening because the SDK package is not correct. Update the SDK package to the latest one.
If SDK manager is not showing any updates, then in Android Studio, from the File Menu, Chose the option Invalidate Caches and Restart.
Once this is done, Android studio will ask if any pending SDK updates are there.
Once the updates are installed, then recreate the new Virtual Device with AVD manager(if you are using Virtual Device).
And your program is ready to go...

SDK\system-images\android-27\google_apis\x86\source.properties

  Pkg.Desc=System Image x86 with Google APIs.
  ****Pkg.Revision=2****
  Pkg.Dependencies=emulator#26.1.3
  ****AndroidVersion.ApiLevel=27****
  SystemImage.Abi=x86
  SystemImage.TagId=google_apis
  SystemImage.TagDisplay=Google APIs
  SystemImage.GpuSupport=true
  Addon.VendorId=google
  Addon.VendorDisplay=Google Inc.


问:
Python inheritance (OOP)
I want create inheritor (descadent) of python's class time. I use solving from next script, but I obtain message cannot create "builtin_function_or method" instance. Where is problem,please?

```<code>from time import time as time
import _classA

class UserTime(time):
    def __init__(self):
        pass
</code>```

答:
Actually what you're trying to do is ILLIGAL :)
Anyway, you're trying to subclass a method of the class time which you can't do.
Here's a little explanation why:

```<code>>>> import time
>>> type(time.time)
<class 'builtin_function_or_method'>
>>> type(time)
<class 'module'>
</code>```

From what you can see above the time.time is a builtin function or method of a class (in this case, the class "time"), even if you cast a type on "time" itself, would result a class of type "module", which you cannot subclass aswell.
But, you could do something that i don't reccomend since it is useless (in my opinion):

```<code>import time
class A(type(time)):
    pass
</code>```

and it would magically be a class of type "type", which is what you want and answers to your question.

```<code>>>> type(A)
<class 'type'>
</code>```

But you have to deal with it in someway, so my question is, What are you actually trying to accomplish? Do you really need to do sort of magic behind the scene to something that could be done in different ways (easily)?

Title: Python inheritance (OOP)

Body:
I want create inheritor (descadent) of python's class time. I use solving from next script, but I obtain message cannot create "builtin_function_or method" instance. Where is problem,please?

from time import time as time
import _classA

class UserTime(time):
    def __init__(self):
        pass

Body:
Actually what you're trying to do is ILLIGAL :)
Anyway, you're trying to subclass a method of the class time which you can't do.
Here's a little explanation why:

>>> import time
>>> type(time.time)
<class 'builtin_function_or_method'>
>>> type(time)
<class 'module'>

From what you can see above the time.time is a builtin function or method of a class (in this case, the class "time"), even if you cast a type on "time" itself, would result a class of type "module", which you cannot subclass aswell.
But, you could do something that i don't reccomend since it is useless (in my opinion):

import time
class A(type(time)):
    pass

and it would magically be a class of type "type", which is what you want and answers to your question.

>>> type(A)
<class 'type'>

But you have to deal with it in someway, so my question is, What are you actually trying to accomplish? Do you really need to do sort of magic behind the scene to something that could be done in different ways (easily)?


问:
Share global object between process nodejs
I'm having troubles with processes with Node.js

So I have a parent/child process implementation to send gps info of a device and I need to share the token from the device between both parent and child.

My problem is that thay dont share that object and the child always ask for a new tokwn. instead of using the same until it  expires.

My token is something like:

```<code>{"token":"f93cefe254ca873755b3bbbdca2f4c94","timeout":300,"expire":1512552810822}
</code>```

And when i debug in runChild I always get different values for radioAccess and for each new token I require, I make a new request to the device ...

What can I do to persiste the "radioAcess" global object?

nsGPSService.js

```<code>  require('./globals');

var listRoutDirectories = getDirectories(routeDirectory);
for (var i = 0; i < listRoutDirectories.length; i++) {
    var directoryName = listRoutDirectories[i];
    var directoryPath = routeDirectory + '/' + listRoutDirectories[i];
    var directoryFiles = getFiles(directoryPath);

    for (var j = 0; j < directoryFiles.length; j++) {
        var file = directoryFiles[j];
        if (file.indexOf('Controller.js') > -1) {
            global.Controllers[file.replace('Controller.js', '')] = require(directoryPath + '/' + file);
        } else if (file.indexOf('Model.js') > -1) {
            global.Models[file.replace('Model.js', '')] = require(directoryPath + '/' + file);
        } else if (file.indexOf('Database.js') > -1) {
            global.Database[file.replace('Database.js', '')] = require(directoryPath + '/' + file);
        }
    }
}

var child_process = require("child_process");
var argv = require('minimist')(process.argv.slice(2));

//ex: nsGPSService.js -d 1111-11-11-111
var deviceId = argv.d;
var processDevices = [];

function runParent () {
    setTimeout(function() {
    var numDevice = 1;
        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'runParent', "");
        return Database.Devices.getDevices().then(function (devices) {
            return new Promise(function (resolve, reject) {
                async.each(devices, function (device, callback) {
                    var result = _.filter(processDevices, {"id": device.id});

                    if(result.length == 0) {
                        logger.info('WSController-Service', 'runParent', 'getRadioInfo  --> ', device.id, ' :: ', numDevice++, '/', devices.length);
                        var process = child_process.fork(__dirname + '/nsGPSService.js', ["-d", device.id]);

                        processDevices.push({ "process": process, "id": device.id });

                        process.radioAccess = radioAccess[deviceId] || {};

                        createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'runParent', 'process.radioAccess ', process.radioAccess);

                        process.on('message', function(data) {
                            //receber mensagens do filho
                            createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), data.deviceId, 'runParent data', data);
                            if(data.reason == "deleted") {
                               //child acabou o processo e informa o parent para remover da lista
                                var index = _.findIndex(processDevices, {"id": data.deviceId});
                                processDevices.splice(index, 1);
                            }
                        });
                        process.on('exit', function(code) {
                            createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'runParent', 'Exiting with code', code);
                        });
                        process.on("uncaughtException", function (error) {
                            createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'runParent', 'error', error);
                            process.exit(1);
                        });
                    }

                    callback();
                }, function(error) {
                    // createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'runParent', 'error', error);
                     error ? reject(error) : resolve();
                });
            }).then(function() {
                runParent()
            }).catch(function(error) {
                createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'runParent', 'catch error', error);
                runParent()
            });
        });
    },5000);
}

if(!deviceId) {
    createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), deviceId, 'runParent');
    runParent();
}

function runChild (id) {
    createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), id, 'runChild', "");
    setTimeout(function() {
        return Database.Devices.getDeviceById(id).then(function(device) {
            process.radioAccess = radioAccess[deviceId] || {};
            createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'runChild', 'process.radioAccess 1', process.radioAccess);
            if(!device) {
                process.exit();
                return;
            }
            return Controllers.Gps.getRadioInfo('gps', 'info', {}, device).then(function (data) {
                createLog('debug', __dirname, __filename.slice(__dirname.length + 1, - 3), id, 'runChild', 'data', data);

                createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'runChild', 'process.radioAccess 2', process.radioAccess);

                return Controllers.Gps.sendDeviceInfo(data, device);
            }).then(function() {
                return runChild(id);
            }).catch(function (e) {
                createLog('error', __dirname, __filename.slice(__dirname.length + 1, - 3), id, 'runChild callback error', e);
                return runChild(id);
            });
        });
    }, 5000);
}

 runChild(deviceId);
</code>```

globals.js

```<code>global.radioAccess   = {};
</code>```

I tried to use the process global and add "process.radioAcess" but parent always give {} and child cant persist the token.

答:
Here is a working example of how you can do it. Please be careful trying to send messages from processes before they are initialized (example in two.js) and in the main.js I exit processes in a timeout to give two.js a chance to send something to one.js

Debugging this is very hard, I don't know why but chrome debugger cannot attach to the child processes and does not stop at debugger statements. Nor do any of the console.log statements from child processes show.

main.js

```<code>const fork = require('child_process').fork;
const path = require('path');

const[one,two] = ["one.js","two.js"]
  .map(
    fileName => [path.resolve(fileName),fileName]
  )
  .map(
    ([file,fileName]) => {
      const x = fork(
        file,
        [],
        {
          stdio: [ 'pipe', 'pipe', 'pipe', 'ipc' ],
          silent:false
        }
      );
      x.stderr.on(//doesn't do anything
        'error',
        data =>
          console.log(`got error from ${fileName}:`,data)
      );
      x.on(
        'message',
        message =>
          (message.type==="relay")
            ? one.send({type:"ping",text:`relayed from ${fileName}: ${message.text}`})
            : console.log(`got message from ${fileName}:`,message.text)
      );
      return x;
    }
  );
setTimeout(
  _=>{
    //do this after two can send relayd message (after the send on the que from two)
    one.send({type:"ping",text:"hello one"})
    one.send({type:"exit"})
    two.send({type:"ping",text:"hello two"})
    two.send({type:"exit"})
  }
  ,100
);
</code>```

two.js

```<code>//process is impossible to debug:
// debugger;//never breaks and about:inspect in chrome
//   after init doesn't show this process either
// console.log("useless in forked process"); console.log doesn't show

const processMessage = message => {
  switch (message.type) {
    case "exit":
      process.send({type:"string",text:"Going to exit."});
      process.exit(0);
      break;
    case "ping":
      process.send({type:"string",text:message.text});
      break;
    default:
      process.send({type:"string",text:"unknown message"});
  }
};

process.on(
  'message',
  message =>
    processMessage(message)
);

//this part is not in one.js
Promise.resolve()
.then(
  //send message after main had time to initialize all processes
  x=>process.send({type:"relay",text:"HELLO THERE ONE"})
)
</code>```

one.js

Same as two.js but without the last part.

Body:
I'm having troubles with processes with Node.js

So I have a parent/child process implementation to send gps info of a device and I need to share the token from the device between both parent and child.

My problem is that thay dont share that object and the child always ask for a new tokwn. instead of using the same until it  expires.

My token is something like:

{"token":"f93cefe254ca873755b3bbbdca2f4c94","timeout":300,"expire":1512552810822}

And when i debug in runChild I always get different values for radioAccess and for each new token I require, I make a new request to the device ...

What can I do to persiste the "radioAcess" global object?

nsGPSService.js

  require('./globals');

var listRoutDirectories = getDirectories(routeDirectory);
for (var i = 0; i < listRoutDirectories.length; i++) {
    var directoryName = listRoutDirectories[i];
    var directoryPath = routeDirectory + '/' + listRoutDirectories[i];
    var directoryFiles = getFiles(directoryPath);

    for (var j = 0; j < directoryFiles.length; j++) {
        var file = directoryFiles[j];
        if (file.indexOf('Controller.js') > -1) {
            global.Controllers[file.replace('Controller.js', '')] = require(directoryPath + '/' + file);
        } else if (file.indexOf('Model.js') > -1) {
            global.Models[file.replace('Model.js', '')] = require(directoryPath + '/' + file);
        } else if (file.indexOf('Database.js') > -1) {
            global.Database[file.replace('Database.js', '')] = require(directoryPath + '/' + file);
        }
    }
}

var child_process = require("child_process");
var argv = require('minimist')(process.argv.slice(2));

//ex: nsGPSService.js -d 1111-11-11-111
var deviceId = argv.d;
var processDevices = [];

function runParent () {
    setTimeout(function() {
    var numDevice = 1;
        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'runParent', "");
        return Database.Devices.getDevices().then(function (devices) {
            return new Promise(function (resolve, reject) {
                async.each(devices, function (device, callback) {
                    var result = _.filter(processDevices, {"id": device.id});

                    if(result.length == 0) {
                        logger.info('WSController-Service', 'runParent', 'getRadioInfo  --> ', device.id, ' :: ', numDevice++, '/', devices.length);
                        var process = child_process.fork(__dirname + '/nsGPSService.js', ["-d", device.id]);

                        processDevices.push({ "process": process, "id": device.id });

                        process.radioAccess = radioAccess[deviceId] || {};

                        createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'runParent', 'process.radioAccess ', process.radioAccess);

                        process.on('message', function(data) {
                            //receber mensagens do filho
                            createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), data.deviceId, 'runParent data', data);
                            if(data.reason == "deleted") {
                               //child acabou o processo e informa o parent para remover da lista
                                var index = _.findIndex(processDevices, {"id": data.deviceId});
                                processDevices.splice(index, 1);
                            }
                        });
                        process.on('exit', function(code) {
                            createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'runParent', 'Exiting with code', code);
                        });
                        process.on("uncaughtException", function (error) {
                            createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'runParent', 'error', error);
                            process.exit(1);
                        });
                    }

                    callback();
                }, function(error) {
                    // createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'runParent', 'error', error);
                     error ? reject(error) : resolve();
                });
            }).then(function() {
                runParent()
            }).catch(function(error) {
                createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'runParent', 'catch error', error);
                runParent()
            });
        });
    },5000);
}

if(!deviceId) {
    createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), deviceId, 'runParent');
    runParent();
}

function runChild (id) {
    createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), id, 'runChild', "");
    setTimeout(function() {
        return Database.Devices.getDeviceById(id).then(function(device) {
            process.radioAccess = radioAccess[deviceId] || {};
            createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'runChild', 'process.radioAccess 1', process.radioAccess);
            if(!device) {
                process.exit();
                return;
            }
            return Controllers.Gps.getRadioInfo('gps', 'info', {}, device).then(function (data) {
                createLog('debug', __dirname, __filename.slice(__dirname.length + 1, - 3), id, 'runChild', 'data', data);

                createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'runChild', 'process.radioAccess 2', process.radioAccess);

                return Controllers.Gps.sendDeviceInfo(data, device);
            }).then(function() {
                return runChild(id);
            }).catch(function (e) {
                createLog('error', __dirname, __filename.slice(__dirname.length + 1, - 3), id, 'runChild callback error', e);
                return runChild(id);
            });
        });
    }, 5000);
}

 runChild(deviceId);

globals.js

global.radioAccess   = {};

I tried to use the process global and add "process.radioAcess" but parent always give {} and child cant persist the token.

Body:
Here is a working example of how you can do it. Please be careful trying to send messages from processes before they are initialized (example in two.js) and in the main.js I exit processes in a timeout to give two.js a chance to send something to one.js

Debugging this is very hard, I don't know why but chrome debugger cannot attach to the child processes and does not stop at debugger statements. Nor do any of the console.log statements from child processes show.

main.js

const fork = require('child_process').fork;
const path = require('path');

const[one,two] = ["one.js","two.js"]
  .map(
    fileName => [path.resolve(fileName),fileName]
  )
  .map(
    ([file,fileName]) => {
      const x = fork(
        file,
        [],
        {
          stdio: [ 'pipe', 'pipe', 'pipe', 'ipc' ],
          silent:false
        }
      );
      x.stderr.on(//doesn't do anything
        'error',
        data =>
          console.log(`got error from ${fileName}:`,data)
      );
      x.on(
        'message',
        message =>
          (message.type==="relay")
            ? one.send({type:"ping",text:`relayed from ${fileName}: ${message.text}`})
            : console.log(`got message from ${fileName}:`,message.text)
      );
      return x;
    }
  );
setTimeout(
  _=>{
    //do this after two can send relayd message (after the send on the que from two)
    one.send({type:"ping",text:"hello one"})
    one.send({type:"exit"})
    two.send({type:"ping",text:"hello two"})
    two.send({type:"exit"})
  }
  ,100
);

two.js

//process is impossible to debug:
// debugger;//never breaks and about:inspect in chrome
//   after init doesn't show this process either
// console.log("useless in forked process"); console.log doesn't show

const processMessage = message => {
  switch (message.type) {
    case "exit":
      process.send({type:"string",text:"Going to exit."});
      process.exit(0);
      break;
    case "ping":
      process.send({type:"string",text:message.text});
      break;
    default:
      process.send({type:"string",text:"unknown message"});
  }
};

process.on(
  'message',
  message =>
    processMessage(message)
);

//this part is not in one.js
Promise.resolve()
.then(
  //send message after main had time to initialize all processes
  x=>process.send({type:"relay",text:"HELLO THERE ONE"})
)

one.js

Same as two.js but without the last part.


问:
Timeout does not log out if windows is locked
I have been recently working on the timeout function (used javascript - setInterval). I did test it, it worked exactly the way I want apart from one tiny detail. Whenever a logged in user sleeps the computer, the session is still active and timeout keeps counting the time. Consequently, after waking the PC up, let's say after 40 min, the timeout says e.g. -10 min and the user is still logged in. If he clicks anything or refresh the page, the service will refresh and the timeout is being restarted to the initial value like nothing happened (user is still logged in). Is there a way of making sure that the user is going to be logged out after waking the PC up?

Thanks a lot in advance!

答: If I understand your problem, the solution could be to call a script in ajax when the timeout has a value of 0, which will log out the user and then you could refresh the page, the all thing in javascript</p>


问:
JSON text did not start with array or object and option to allow fragments not set
I'm sending this json response from server for a request to my IOS 7 app.

```<code>{
 "root": {
    "success": "1",
    "message": "Successfully retrieved data.",
    "data": {
        "records": [
            {
                "receipt_key": "xxxxxxxx",
                "receipt_id": "xxxxxxxx",
                "store_name": "xxxxxx",
                "amount": "xxxx",
                "date_purchase": "xxxxxxxx",
                "is_processed": "x",
                "created_on": "xxxxxxxx",
                "modified_on": "xxxxxxxx",
                "modified_on_millis": "xxxxxxxx",
                "user_folder": "xxxxxxxx",
                "category_id": "xxxxxxxx",
                "is_deleted": "x",
                "currency_id": "xxxxxxxx"
            }
        ]
    }
}
}
</code>```

I use the following code for parsing the above json to NSDictionary object.

```<code> NSMutableDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
</code>```

But I'm getting this error on the above code.

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be
  completed. (Cocoa error 3840.)" (JSON text did not start with array or
  object and option to allow fragments not set.) UserInfo=0x8a8a700
  {NSDebugDescription=JSON text did not start with array or object and
  option to allow fragments not set.}

答:
I faced the same problem. But I found that the Url I was sending as a param to server was wrong. There was a little one character mistake. For example I was sending the below url

```<code>URL = https://somerUrl/api/v2/&venues/search?client_id=jkdasljf3242jka-fsdf-fadsfasd&lat=40.712488&long=-74.006277&distance=25
</code>```

The mistake was extra & symbol in front of venues making trouble. So i removed & symbol and found worked for me. So, make sure you are sending the correct param to server.

Body:
I'm sending this json response from server for a request to my IOS 7 app.

{
 "root": {
    "success": "1",
    "message": "Successfully retrieved data.",
    "data": {
        "records": [
            {
                "receipt_key": "xxxxxxxx",
                "receipt_id": "xxxxxxxx",
                "store_name": "xxxxxx",
                "amount": "xxxx",
                "date_purchase": "xxxxxxxx",
                "is_processed": "x",
                "created_on": "xxxxxxxx",
                "modified_on": "xxxxxxxx",
                "modified_on_millis": "xxxxxxxx",
                "user_folder": "xxxxxxxx",
                "category_id": "xxxxxxxx",
                "is_deleted": "x",
                "currency_id": "xxxxxxxx"
            }
        ]
    }
}
}

I use the following code for parsing the above json to NSDictionary object.

 NSMutableDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

But I'm getting this error on the above code.

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be
  completed. (Cocoa error 3840.)" (JSON text did not start with array or
  object and option to allow fragments not set.) UserInfo=0x8a8a700
  {NSDebugDescription=JSON text did not start with array or object and
  option to allow fragments not set.}

Body:
I faced the same problem. But I found that the Url I was sending as a param to server was wrong. There was a little one character mistake. For example I was sending the below url

URL = https://somerUrl/api/v2/&venues/search?client_id=jkdasljf3242jka-fsdf-fadsfasd&lat=40.712488&long=-74.006277&distance=25

The mistake was extra & symbol in front of venues making trouble. So i removed & symbol and found worked for me. So, make sure you are sending the correct param to server.


问:
Why are the result of preg_match not displayed?
I can't see the results of preg_match by regex! Where is the problem?

```<code>preg_match('@^(?:http://)?([^/]+)@i',"'".$urls['url']."'", $matches);
    $host = $matches[1];
    preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "from: <p id='long'>{$matches[0]}\n</p>";
}
</code>```

Output:

```<code>from:
</code>```

答: If the input is just an URL you can use parse_url(), in your case with the PHP_URL_HOST flag.

Body:
I can't see the results of preg_match by regex! Where is the problem?

preg_match('@^(?:http://)?([^/]+)@i',"'".$urls['url']."'", $matches);
    $host = $matches[1];
    preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "from:
{$matches[0]}\n
";
}

Output:

from:


问:
Adding a newline into a string in C#
I have a string.

```<code>string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
</code>```

I need to add a newline after every occurence of "@" symbol in the string.

My Output should be like this

```<code>fkdfdsfdflkdkfk@
dfsdfjk72388389@
kdkfkdfkkl@
jkdjkfjd@
jjjk@
</code>```

答:
```<code>protected void Button1_Click(object sender, EventArgs e)
{
    string str = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
    str = str.Replace("@", "@" + "<br/>");
    Response.Write(str);
}
</code>```

OwnerDisplayName: balaweblog

Title: Adding a newline into a string in C#

Body:
I have a string.

string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";

I need to add a newline after every occurence of "@" symbol in the string.

My Output should be like this

fkdfdsfdflkdkfk@
dfsdfjk72388389@
kdkfkdfkkl@
jkdjkfjd@
jjjk@

LastEditorDisplayName: balaweblog


问:
How can I add a PublisherId to a GetBlob call to the Office365 Rest API to avoid throttling?

I'm attempting to iteratively retrieve the content from the O365 management API (found here). When I get to the 'Retrieving Content' section, I am making a get request using the URI returned from the 'Get Available Content' method.

I am able to successfully iterate over the available content using the returned URI, but I am seeing the following message appear occasionally:

{"error": {"message": "Too many requests. Method=GetBlob, PublisherId=00000000-0000-0000-0000-000000000000", "code": "AF429"}}

This indicates a throttling error, as mentioned at the bottom of the documentation, but when I try to add the '&PublisherId={myid}' to that request, I get a Runtime Error returned from the server.

Does anyone know how to add the PublisherId to the GetBlob call so that I can avoid throttling?

答:
I had the same issue and added "?PublisherIdentifier={id}" to the url and it seems to be working now.

On another topic, be aware that if you use the list available content method the pagination header is 'NextPageUri' and not 'NextPageUrl' like the documentation says.


问:
Code stops working when I minimize it
There is a working code:drag-and-drop

Code does not work when through the GULP uglify()

```<code> 'use strict';
 const gulp = require('gulp');
 const $ = require('gulp-load-plugins')();
 const uglifyes = require('uglify-es');
 const composer = require('gulp-uglify/composer');
 const uglify = composer(uglifyes, console);

 module.exports = function(options) {
   return function() {
     return gulp.src(options.from)
     .pipe($.if(!isDevelopment, uglify()))
     .pipe(gulp.dest(options.to))
   };
 };
</code>```

Where is the mistake in the following code?

```<code>var app = angular.module('app', ['ui.sortable', 'Myanimate']);

angular.module('Myanimate', [])
    .factory('animate', function() {

    var time = 3000;
    var timeout = null;

    return {
        _hideAnimate: function(item) {
            timeout = timeout || setTimeout(function() {
                this.removeBackground(item);

                timeout = null;
            }.bind(this), time);
        },

        setBorder : function(item) {
            item.addClass('red-border');
            this.removeBorder(item);
            this._hideAnimate(item);
            return item;
        },
        setBackground: function(item) {
            item.addClass('red-border red-border-background');
            this._hideAnimate(item);
            return item;
        },
        removeBorder : function(item) {
            item.removeClass('red-border-background');
            return item;
        },
        removeBackground: function(item) {
            item.removeClass('red-border red-border-background');
            return item;
        }
    }
});

app.controller('appController', function ($scope, animate) {

  $scope.list1 = ['A', 'B', 'C'];
  $scope.list2 = ['1', '2', '3'];
  $scope.list3 = ['X', 'Y', 'Z'];
  $scope.elemMoved = null;

  $scope.sortableOptions = {
    over : function(e,ui) {
    var $targetElem = $(e.target);

      if($targetElem.hasClass('second')) {
        animate.setBorder(ui.item);
      } else if($targetElem.hasClass('third')) {
        animate.setBackground(ui.item);
      } else {
        animate.removeBackground(ui.item);
      }
    },

    update: function(e, ui) {

    var moveItem =  $scope.elemMoved = ui.item.sortable.moved;
    var ngModel = $(ui.item.sortable.droptarget).attr('ng-model');

    if(typeof moveItem === 'undefined') {
        return;
    }

     if($(ui.item.sortable.droptarget).hasClass('third')) {
      if($.inArray(moveItem, $scope.list1) === -1) {
          if(ui.item.sortable.droptarget || e.target != ui.item.sortable.droptarget[0]) {
                $scope.list1.push(moveItem);
          }
      }
    }

    },
    stop: function(e, ui) {
        ui.item.removeClass('red-border red-border-background');
    },
    connectWith: ".apps-container"
  };

});
</code>```

答:
You need to change the code and include an array with the stuff you want angular to inject into your controller

```<code>app.controller('appController', function ($scope, animate)
</code>```

should be

```<code>app.controller('appController', ['$scope', 'animate', function ($scope, animate) {
    // ...
}]);
</code>```

You could also use something like ng annotate which will do that automatically, so you could add

```<code>.pipe(ngAnnotate({
    // true helps add where @ngInject is not used. It infers.
    // Doesn't work with resolve, so we must be explicit there
    add: true
}))
</code>```

to your gulp pipeline and simply use the annotation above the function

```<code>/* @ngInject */
app.controller('appController', function ($scope, animate)
</code>```

Now angular will know what to inject even after the variables have been minified.

Title: Code stops working when I minimize it

Body:
There is a working code:drag-and-drop

Code does not work when through the GULP uglify()

 'use strict';
 const gulp = require('gulp');
 const $ = require('gulp-load-plugins')();
 const uglifyes = require('uglify-es');
 const composer = require('gulp-uglify/composer');
 const uglify = composer(uglifyes, console);

 module.exports = function(options) {
   return function() {
     return gulp.src(options.from)
     .pipe($.if(!isDevelopment, uglify()))
     .pipe(gulp.dest(options.to))
   };
 };

Where is the mistake in the following code?

var app = angular.module('app', ['ui.sortable', 'Myanimate']);

angular.module('Myanimate', [])
    .factory('animate', function() {

    var time = 3000;
    var timeout = null;

    return {
        _hideAnimate: function(item) {
            timeout = timeout || setTimeout(function() {
                this.removeBackground(item);

                timeout = null;
            }.bind(this), time);
        },

        setBorder : function(item) {
            item.addClass('red-border');
            this.removeBorder(item);
            this._hideAnimate(item);
            return item;
        },
        setBackground: function(item) {
            item.addClass('red-border red-border-background');
            this._hideAnimate(item);
            return item;
        },
        removeBorder : function(item) {
            item.removeClass('red-border-background');
            return item;
        },
        removeBackground: function(item) {
            item.removeClass('red-border red-border-background');
            return item;
        }
    }
});

app.controller('appController', function ($scope, animate) {

  $scope.list1 = ['A', 'B', 'C'];
  $scope.list2 = ['1', '2', '3'];
  $scope.list3 = ['X', 'Y', 'Z'];
  $scope.elemMoved = null;

  $scope.sortableOptions = {
    over : function(e,ui) {
    var $targetElem = $(e.target);

      if($targetElem.hasClass('second')) {
        animate.setBorder(ui.item);
      } else if($targetElem.hasClass('third')) {
        animate.setBackground(ui.item);
      } else {
        animate.removeBackground(ui.item);
      }
    },

    update: function(e, ui) {

    var moveItem =  $scope.elemMoved = ui.item.sortable.moved;
    var ngModel = $(ui.item.sortable.droptarget).attr('ng-model');

    if(typeof moveItem === 'undefined') {
        return;
    }

     if($(ui.item.sortable.droptarget).hasClass('third')) {
      if($.inArray(moveItem, $scope.list1) === -1) {
          if(ui.item.sortable.droptarget || e.target != ui.item.sortable.droptarget[0]) {
                $scope.list1.push(moveItem);
          }
      }
    }

    },
    stop: function(e, ui) {
        ui.item.removeClass('red-border red-border-background');
    },
    connectWith: ".apps-container"
  };

});

Body:
You need to change the code and include an array with the stuff you want angular to inject into your controller

app.controller('appController', function ($scope, animate)

should be

app.controller('appController', ['$scope', 'animate', function ($scope, animate) {
    // ...
}]);

You could also use something like ng annotate which will do that automatically, so you could add

.pipe(ngAnnotate({
    // true helps add where @ngInject is not used. It infers.
    // Doesn't work with resolve, so we must be explicit there
    add: true
}))

to your gulp pipeline and simply use the annotation above the function

/* @ngInject */
app.controller('appController', function ($scope, animate)

Now angular will know what to inject even after the variables have been minified.


问:
How to remove invalid characters from a string?
I have no idea how to remove invalid characters from a string in Java. I'm trying to remove all the characters that are not numbers, letters, or ( ) [ ] . How can I do this?

Thanks

答:
You can remove specials characters from your String/Url or any request   parameters you have get from user side</p>

```<code>  public static String removeSpecialCharacters(String inputString){
        final String[] metaCharacters = {"../","\\..","\\~","~/","~"};
        String outputString="";
        for (int i = 0 ; i < metaCharacters.length ; i++){
            if(inputString.contains(metaCharacters[i])){
                outputString = inputString.replace(metaCharacters[i],"");
                inputString = outputString;
            }else{
                outputString = inputString;
            }
        }
        return outputString;
   }
</code>```

Body:
You can remove specials characters from your String/Url or any request   parameters you have get from user side

  public static String removeSpecialCharacters(String inputString){
        final String[] metaCharacters = {"../","\\..","\\~","~/","~"};
        String outputString="";
        for (int i = 0 ; i < metaCharacters.length ; i++){
            if(inputString.contains(metaCharacters[i])){
                outputString = inputString.replace(metaCharacters[i],"");
                inputString = outputString;
            }else{
                outputString = inputString;
            }
        }
        return outputString;
   }


问:
Filter Stored Procedure Results using Linq
I have this code that get date from server using SP with EF

```<code>  List<sp_PlacementSearchResult_Result> listResults = new List<sp_PlacementSearchResult_Result>();
  var query = Context.sp_PlacementSearchResult(request.HasamaFormId, request.DepartmentId, request.InstitutionNum, request.IsSigned).AsQueryable();
</code>```

This is working, now i'd like to add some filter to the result like this:

```<code> if (role.PermissionId.Equals((int)Permission.Institution))
        {
            query = query.Where(form => PropRole.InstitutionNum.Contains((int)form.OrganizationOrInstitutionNum));
        }
</code>```

at the end of the function when i try to do

```<code> listResults = query.ToList();
</code>```

I get error, "Nullable object must have a value."

  The ToList() fail only if it's get into the if statement.

P.S:
At first i have done this query with EF without SP like this:

```<code>  var query = Context.APP_AuthorityHasamaForm.AsQueryable();
</code>```

And in that way i have no problem doing the ToList() even if it get into the if statement

Thanx

Edit: this is all the function:

```<code>  IEnumerable<sp_PlacementSearchResult_Result> IAuthorityHasamaFormRepository.GetByRequestFromSP(PlacementRequest request, APP_Role role, PropertiesRole PropRole)
    {
        List<sp_PlacementSearchResult_Result> listResults = new List<sp_PlacementSearchResult_Result>();

        request.HasamaFormId = (request.HasamaFormId > 0) ? request.HasamaFormId : null;
        request.InstitutionNum = (request.InstitutionNum > 0) ? request.InstitutionNum : null;

        if (request.StartDate.HasValue)
        {
            request.StartDate = new DateTime(request.StartDate.Value.Year, request.StartDate.Value.Month, request.StartDate.Value.Day, 00, 00, 00);

        }

        if (request.EndDate.HasValue)
        {
            request.EndDate = new DateTime(request.EndDate.Value.Year, request.EndDate.Value.Month, request.EndDate.Value.Day, 00, 00, 00);

        }

        var query = Context.sp_PlacementSearchResult(request.HasamaFormId, request.DepartmentId, request.InstitutionNum, request.IsSigned, request.IdentityIdSign,
            request.StartDate, request.EndDate, request.AuthorityNum, request.CertificateNum, null).AsQueryable();

        if (role.PermissionId.Equals((int)Permission.Department))
        {
            query = query.Where(form => PropRole.DepartmentId.Contains(form.DepartmentId));
        }

        if (role.PermissionId.Equals((int)Permission.Institution))
        {
            query = query.Where(form => PropRole.InstitutionNum.Contains((int)form.OrganizationOrInstitutionNum));
        }

        try
        {
            listResults = query.ToList();
            return listResults;
        }
        catch (Exception e)
        {

            throw;
        }

         listResults = query.ToList();

        return listResults;
    }
</code>```

答:
You should consider possible null values of form.OrganizationOrInstitutionNum

```<code> if (role.PermissionId.Equals((int)Permission.Institution))
        {
            query = query.Where(form => form.OrganizationOrInstitutionNum != null && PropRole.InstitutionNum.Contains(form.OrganizationOrInstitutionNum.Value));
        }
</code>```

Body:
I have this code that get date from server using SP with EF

  List<sp_PlacementSearchResult_Result> listResults = new List<sp_PlacementSearchResult_Result>();
  var query = Context.sp_PlacementSearchResult(request.HasamaFormId, request.DepartmentId, request.InstitutionNum, request.IsSigned).AsQueryable();

This is working, now i'd like to add some filter to the result like this:

 if (role.PermissionId.Equals((int)Permission.Institution))
        {
            query = query.Where(form => PropRole.InstitutionNum.Contains((int)form.OrganizationOrInstitutionNum));
        }

at the end of the function when i try to do

 listResults = query.ToList();

I get error, "Nullable object must have a value."

  The ToList() fail only if it's get into the if statement.

P.S:
At first i have done this query with EF without SP like this:

  var query = Context.APP_AuthorityHasamaForm.AsQueryable();

And in that way i have no problem doing the ToList() even if it get into the if statement

Thanx

Edit: this is all the function:

  IEnumerable<sp_PlacementSearchResult_Result> IAuthorityHasamaFormRepository.GetByRequestFromSP(PlacementRequest request, APP_Role role, PropertiesRole PropRole)
    {
        List<sp_PlacementSearchResult_Result> listResults = new List<sp_PlacementSearchResult_Result>();

        request.HasamaFormId = (request.HasamaFormId > 0) ? request.HasamaFormId : null;
        request.InstitutionNum = (request.InstitutionNum > 0) ? request.InstitutionNum : null;

        if (request.StartDate.HasValue)
        {
            request.StartDate = new DateTime(request.StartDate.Value.Year, request.StartDate.Value.Month, request.StartDate.Value.Day, 00, 00, 00);

        }

        if (request.EndDate.HasValue)
        {
            request.EndDate = new DateTime(request.EndDate.Value.Year, request.EndDate.Value.Month, request.EndDate.Value.Day, 00, 00, 00);

        }

        var query = Context.sp_PlacementSearchResult(request.HasamaFormId, request.DepartmentId, request.InstitutionNum, request.IsSigned, request.IdentityIdSign,
            request.StartDate, request.EndDate, request.AuthorityNum, request.CertificateNum, null).AsQueryable();

        if (role.PermissionId.Equals((int)Permission.Department))
        {
            query = query.Where(form => PropRole.DepartmentId.Contains(form.DepartmentId));
        }

        if (role.PermissionId.Equals((int)Permission.Institution))
        {
            query = query.Where(form => PropRole.InstitutionNum.Contains((int)form.OrganizationOrInstitutionNum));
        }

        try
        {
            listResults = query.ToList();
            return listResults;
        }
        catch (Exception e)
        {

            throw;
        }

         listResults = query.ToList();

        return listResults;
    }

Body:
You should consider possible null values of form.OrganizationOrInstitutionNum

 if (role.PermissionId.Equals((int)Permission.Institution))
        {
            query = query.Where(form => form.OrganizationOrInstitutionNum != null && PropRole.InstitutionNum.Contains(form.OrganizationOrInstitutionNum.Value));
        }


问:
I am getting a syntax Error near and keyword
```<code>SELECT   wrhwr.bl_id,
         Count(wrhwr.wr_id) AS ct_wr_id
FROM     (
                SELECT wrhwr.bl_id,
                       wrhwr.wr_id,
                       wrhwr.site_id,
                       wrhwr.date_requested
                FROM   wrhwr
                WHERE
                And    (
                              wrhwr.bl_id LIKE 'F0006440-B0001%')
                AND    wrhwr.bl_id IN
                       (
                                SELECT TOP 10
                                         q.bl_id
                                FROM     (
                                                  SELECT   bl_id,
                                                           Count(wr_id) AS wrcnt
                                                  FROM     afm.wrhwr
                                                  GROUP BY bl_id) AS q
                                WHERE    wrhwr.[status] IN ('Com',
                                                            'I',
                                                            'HL',
                                                            'HP',
                                                            'S')
                                ORDER BY q.wrcnt DESC))wrhwr
WHERE    ((
                  And      (
                                    wrhwr.bl_id LIKE 'F0006440-B0001%') ))
AND      (
                  wrhwr.site_id IN
                  (
                         SELECT site_id
                         FROM   site
                         WHERE  state_id = 'JHB')
         OR       wrhwr.site_id IS NULL)
GROUP BY wrhwr.bl_id
ORDER BY wrhwr.bl_id DESC
</code>```

答:
You have used AND + WHERE for the same statement which is giving you the error
like this

```<code>SELECT wrhwr.bl_id,
                       wrhwr.wr_id,
                       wrhwr.site_id,
                       wrhwr.date_requested
                FROM   wrhwr
                WHERE
                And    (
                              wrhwr.bl_id LIKE 'F0006440-B0001%')
</code>```

Here, AND is not needed, since you have only 1 filter criteria,  try this

```<code>SELECT   wrhwr.bl_id,
         Count(wrhwr.wr_id) AS ct_wr_id
FROM     (
                SELECT wrhwr.bl_id,
                       wrhwr.wr_id,
                       wrhwr.site_id,
                       wrhwr.date_requested
                FROM   wrhwr
                WHERE wrhwr.bl_id LIKE 'F0006440-B0001%'
                AND    wrhwr.bl_id IN
                       (
                                SELECT TOP 10
                                         q.bl_id
                                FROM     (
                                                  SELECT   bl_id,
                                                           Count(wr_id) AS wrcnt
                                                  FROM     afm.wrhwr
                                                  GROUP BY bl_id) AS q
                                WHERE    wrhwr.[status] IN ('Com',
                                                            'I',
                                                            'HL',
                                                            'HP',
                                                            'S')
                                ORDER BY q.wrcnt DESC)
        )wrhwr
WHERE   wrhwr.bl_id LIKE 'F0006440-B0001%'
AND      (
                  wrhwr.site_id IN
                  (
                         SELECT site_id
                         FROM   site
                         WHERE  state_id = 'JHB')
         OR       wrhwr.site_id IS NULL)
GROUP BY wrhwr.bl_id
ORDER BY wrhwr.bl_id DESC
</code>```

Body:
You have used AND + WHERE for the same statement which is giving you the error
like this

SELECT wrhwr.bl_id,
                       wrhwr.wr_id,
                       wrhwr.site_id,
                       wrhwr.date_requested
                FROM   wrhwr
                WHERE
                And    (
                              wrhwr.bl_id LIKE 'F0006440-B0001%')

Here, AND is not needed, since you have only 1 filter criteria,  try this

SELECT   wrhwr.bl_id,
         Count(wrhwr.wr_id) AS ct_wr_id
FROM     (
                SELECT wrhwr.bl_id,
                       wrhwr.wr_id,
                       wrhwr.site_id,
                       wrhwr.date_requested
                FROM   wrhwr
                WHERE wrhwr.bl_id LIKE 'F0006440-B0001%'
                AND    wrhwr.bl_id IN
                       (
                                SELECT TOP 10
                                         q.bl_id
                                FROM     (
                                                  SELECT   bl_id,
                                                           Count(wr_id) AS wrcnt
                                                  FROM     afm.wrhwr
                                                  GROUP BY bl_id) AS q
                                WHERE    wrhwr.[status] IN ('Com',
                                                            'I',
                                                            'HL',
                                                            'HP',
                                                            'S')
                                ORDER BY q.wrcnt DESC)
        )wrhwr
WHERE   wrhwr.bl_id LIKE 'F0006440-B0001%'
AND      (
                  wrhwr.site_id IN
                  (
                         SELECT site_id
                         FROM   site
                         WHERE  state_id = 'JHB')
         OR       wrhwr.site_id IS NULL)
GROUP BY wrhwr.bl_id
ORDER BY wrhwr.bl_id DESC


问:
Combine 2 Arrays of Different Lengths
I have two arrays, each of different counts, the example I'm working with is there's 132 in one and 136 in the other,

I need to array_combine() them (make the first one the key, and the second one the value). In my example I would like to keep 132 key/value pairs and drop of the extra 4 that have no corresponding match.

I have currently got this function (which I found on php.net's docs of array_combine()), but it isn't working:

```<code>function array_combine2($arr1, $arr2) {
            $count1 = count($arr1);
            $count2 = count($arr2);
            $numofloops = $count2/$count1;

            $i = 0;
            while($i < $numofloops){
                $arr3 = array_slice($arr2, $count1*$i, $count1);
                $arr4[] = array_combine($arr1,$arr3);
                $i++;
            }

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

I keep getting back

Warning: array_combine() [function.array-combine]: Both parameters
  should have an equal number of elements on the line that starts with
  $arr4[] = ...

Any advice would help,

thanks!

Title: Combine 2 Arrays of Different Lengths

Body:
I have two arrays, each of different counts, the example I'm working with is there's 132 in one and 136 in the other,

I need to array_combine() them (make the first one the key, and the second one the value). In my example I would like to keep 132 key/value pairs and drop of the extra 4 that have no corresponding match.

I have currently got this function (which I found on php.net's docs of array_combine()), but it isn't working:

function array_combine2($arr1, $arr2) {
            $count1 = count($arr1);
            $count2 = count($arr2);
            $numofloops = $count2/$count1;

            $i = 0;
            while($i < $numofloops){
                $arr3 = array_slice($arr2, $count1*$i, $count1);
                $arr4[] = array_combine($arr1,$arr3);
                $i++;
            }

            return $arr4;
     }

I keep getting back

Warning: array_combine() [function.array-combine]: Both parameters
  should have an equal number of elements on the line that starts with
  $arr4[] = ...

Any advice would help,

thanks!

Body:
here is perfect function in PHP itself called "array_combine()"

  /*-----------------------------------------------------------
  | Parameter            | Description                        |
  -------------------------------------------------------------
  | array1  Required.   | An array, specifying the keys       |
  -------------------------------------------------------------
  | array2  Required.   | An array, specifying the values     |
  -----------------------------------------------------------*/

$array1 = ('John','Mark','Ester');
$array2 = (1111,2222);

// if some elements dont exists, "add" them...
if(count($array1) != count($array2))
{
  foreach($array as $key => $value):
      if(!isset($array2[$key]) $array2[$key] = NULL;
  endforeach;
}

// now, combine them in classic way...
$combined = array_combine($array1,$array2);


问:
Centering a programatically created group not working in fabric js
I have used the following code to group all the objects in the canvas and centering the group. Here the grouping is working but the centering is not working.

```<code>var objs = canvas.getObjects();

//create group
var group = new fabric.Group(objs);

group.center().setCoords();

canvas.setActiveGroup(group).renderAll();
</code>```

I tried selecting all the objects manually using the mouse and tried this code in the console: canvas.getActiveGroup().center() and it worked fine.

What is the reason for this issue? Can anyone help me?

答:
Finally got it worked using canvas.centerObject():

```<code>var objs = canvas.getObjects();

//create group
var group = new fabric.Group(objs);

canvas.centerObject(group);

canvas.setActiveGroup(group).renderAll();
</code>```

But I don't know why the center() is not working.

Body:
I have used the following code to group all the objects in the canvas and centering the group. Here the grouping is working but the centering is not working.

var objs = canvas.getObjects();

//create group
var group = new fabric.Group(objs);

group.center().setCoords();

canvas.setActiveGroup(group).renderAll();

I tried selecting all the objects manually using the mouse and tried this code in the console: canvas.getActiveGroup().center() and it worked fine.

What is the reason for this issue? Can anyone help me?

Body:
Finally got it worked using canvas.centerObject():

var objs = canvas.getObjects();

//create group
var group = new fabric.Group(objs);

canvas.centerObject(group);

canvas.setActiveGroup(group).renderAll();

But I don't know why the center() is not working.


问:
BASH Mysql outputs part of statement
I'm trying to run the below script to get a list of Orgs and the amount of users each Org has:

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

array=(293 182 177 12 85 51 325 225 40 169 357 329 243 349 291 295 22 279 16 69 219 299 301 331 91 281 285 59 283 341 45 289 95 61 77 13 14 201 43 343 223 28 171 26 233 47 303 367 369 339 257 305 353 245 213 87 345 2 71 199 24 179 259 37 35 237)

for i in "${array[@]}"; do

query=$(export MYSQL_PWD=MYPASS; mysql -e "SELECT COUNT(*) FROM Org.Users WHERE HomeOrgID=$i;")

echo "Org_$i:$query"

done
</code>```

I expect the result to be a simple "Org:Number" list:

```<code>Org_1:150
Org_25:250
Org_17:64
Org_64:12
</code>```

But the output is not displayed correctly. It does show part of the MySQL statement:

```<code>Org_293:COUNT(*)
1
Org_182:COUNT(*)
0
Org_177:COUNT(*)
8
Org_12:COUNT(*)
0
Org_85:COUNT(*)
1
</code>```

How can I get the output to NOT display that "COUNT(*)" and display just a simple list?

Thanks in advance!

答:
One quick hack : use bash arrays to store your output.</p>

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

array=(293 182 177 12 85 51 325 225 40 169 357 329 243 349 291 295 22 279 16 69 219 299 301 331 91 281 285 59 283 341 45 289 95 61 77 13 14 201 43 343 223 28 171 26 233 47 303 367 369 339 257 305 353 245 213 87 345 2 71 199 24 179 259 37 35 237)

for i in "${array[@]}"; do
    # we store the result of the request as an array
    query=($(export MYSQL_PWD=MYPASS; mysql -e "SELECT COUNT(*) FROM Org.Users WHERE HomeOrgID=$i;"))

    # we echo the 2nd member of the array. ${query[0]} should contain 'count(*)'
    echo "Org_$i:${query[1]}"

done
</code>```

Title: BASH Mysql outputs part of statement

Body:
I'm trying to run the below script to get a list of Orgs and the amount of users each Org has:

#!/bin/bash

array=(293 182 177 12 85 51 325 225 40 169 357 329 243 349 291 295 22 279 16 69 219 299 301 331 91 281 285 59 283 341 45 289 95 61 77 13 14 201 43 343 223 28 171 26 233 47 303 367 369 339 257 305 353 245 213 87 345 2 71 199 24 179 259 37 35 237)

for i in "${array[@]}"; do

query=$(export MYSQL_PWD=MYPASS; mysql -e "SELECT COUNT(*) FROM Org.Users WHERE HomeOrgID=$i;")

echo "Org_$i:$query"

done

I expect the result to be a simple "Org:Number" list:

Org_1:150
Org_25:250
Org_17:64
Org_64:12

But the output is not displayed correctly. It does show part of the MySQL statement:

Org_293:COUNT(*)
1
Org_182:COUNT(*)
0
Org_177:COUNT(*)
8
Org_12:COUNT(*)
0
Org_85:COUNT(*)
1

How can I get the output to NOT display that "COUNT(*)" and display just a simple list?

Thanks in advance!

Body:
One quick hack : use bash arrays to store your output.

#!/bin/bash

array=(293 182 177 12 85 51 325 225 40 169 357 329 243 349 291 295 22 279 16 69 219 299 301 331 91 281 285 59 283 341 45 289 95 61 77 13 14 201 43 343 223 28 171 26 233 47 303 367 369 339 257 305 353 245 213 87 345 2 71 199 24 179 259 37 35 237)

for i in "${array[@]}"; do
    # we store the result of the request as an array
    query=($(export MYSQL_PWD=MYPASS; mysql -e "SELECT COUNT(*) FROM Org.Users WHERE HomeOrgID=$i;"))

    # we echo the 2nd member of the array. ${query[0]} should contain 'count(*)'
    echo "Org_$i:${query[1]}"

done


问:
PHP MySQL SQL parser (INSERT and UPDATE)
I am looking to parse INSERT and UPDATE MySQL SQL queries in PHP to determine what changes where made from what original data. Now this would be pretty easy to create, but I want to see if there are any existing libraries in PHP to do this.

Basically what I have is a table with all of the above queries that have been run on a database. I have already separated out the table name and type of query. I am looking to create a full change log for user viewing based on this data, so I need to get the values of the original INSERT and then changes that are made in each UPDATE. In the end I need field name and new value and with the record id(s). I'll do the rest of the checking/beautifying, including the column name to human readable and if a field value hasn't actually changed.

At the moment, I probably don't need to do multiple table UPDATE's, but it would be useful.

What libraries are there to do this?

答:
you can try :
dqml2tree sql(dql and dml) query parser written in php</p>

OwnerDisplayName: Darryl Hein

OwnerDisplayName: kalaspace


问:
NSPredicate matching string for Cloudkit
I need to pull the record from cloudkit matching a string.

I have a User record type, with an email field. I have multiple records with the same email, but I can't get the predicate to get me the records.

I've tried all of these:

```<code>let predicate = NSPredicate(format: "email = 'julio_ukohgsp_chevez@tfbnw.net'")
NSPredicate(format: "email == %@", argumentArray: [email])
NSPredicate(format: "email IN %@", [email])
NSPredicate(format: "email contains %@", email)
NSPredicate(format: "email = %@", email)
NSPredicate(format: "email == %@", email)
</code>```

My query specifies the record type:

```<code>let query = CKQuery(recordType: "User", predicate: NSPredicate(format: "email == %@", email))
</code>```

When I do a predicate with value: true, I get all records including the one I want.. I know for sure I have a User with that email, multiple in fact..

What am I missing?

Edit ..

```<code>let query = CKQuery(recordType: "User", predicate: NSPredicate(format: "email BEGINSWITH %@", email))
</code>```

Does work and brings back records, but I want an exact match!

答:
I had same issue and was able to resolve it by adding Queryable index on user field in my case. Note, after index was added I needed to write data again to CloudKit to be able to perform query.

Code for creation of  predicate:

```<code>let user = "test-user"
let userPredicate = NSPredicate(format: "user == %@", user)
</code>```

Body:
I need to pull the record from cloudkit matching a string.

I have a User record type, with an email field. I have multiple records with the same email, but I can't get the predicate to get me the records.

I've tried all of these:

let predicate = NSPredicate(format: "email = 'julio_ukohgsp_chevez@tfbnw.net'")
NSPredicate(format: "email == %@", argumentArray: [email])
NSPredicate(format: "email IN %@", [email])
NSPredicate(format: "email contains %@", email)
NSPredicate(format: "email = %@", email)
NSPredicate(format: "email == %@", email)

My query specifies the record type:

let query = CKQuery(recordType: "User", predicate: NSPredicate(format: "email == %@", email))

When I do a predicate with value: true, I get all records including the one I want.. I know for sure I have a User with that email, multiple in fact..

What am I missing?

Edit ..

let query = CKQuery(recordType: "User", predicate: NSPredicate(format: "email BEGINSWITH %@", email))

Does work and brings back records, but I want an exact match!

Body:
I had same issue and was able to resolve it by adding Queryable index on user field in my case. Note, after index was added I needed to write data again to CloudKit to be able to perform query.

Code for creation of  predicate:

let user = "test-user"
let userPredicate = NSPredicate(format: "user == %@", user)


问:
Convert CTE from Postgres to MSSQL
I hould convert a CTE from Postgresql zu MSSQL.
The Problem is, that the Postgresql-Query uses Arrays. I have no idea how to convert them to MSSQL.

Here is the complete Query with creating the data:

```<code>CREATE TABLE pairs (
    from_city VARCHAR(255) NOT NULL,
    to_city VARCHAR(255) NOT NULL,
    distance INTEGER NOT NULL,
    PRIMARY KEY(from_city, to_city),
    CHECK (from_city < to_city)
);

INSERT INTO pairs
VALUES
('Bari','Bologna',672),
('Bari','Genova',944),
('Bari','Milano',881),
('Bari','Napoli',257),
('Bari','Palermo',708),
('Bologna','Genova',190),
('Bologna','Milano',200),
('Bologna','Napoli',470),
('Bologna','Palermo',730),
('Bologna','Roma',300),
('Genova','Milano',120),
('Genova','Napoli',590),
('Genova','Palermo',790),
('Genova','Roma',400),
('Milano','Napoli',660),
('Milano','Palermo',890),
('Milano','Roma',480),
('Napoli','Palermo',310),
('Napoli','Roma',190),
('Palermo','Roma',430);

SELECT * FROM pairs;

-- Paths from Palermo to Milano...
;WITH RECURSIVE both_ways (
    from_city,
    to_city,
    distance
) /* Working Table containing all ways */
AS (
    SELECT
        from_city,
        to_city,
        distance
    FROM pairs
UNION ALL
    SELECT
        to_city AS "from_city",
        from_city AS "to_city",
        distance
    FROM pairs
),
paths (
    from_city,
    to_city,
    distance,
    path
)
AS (
    SELECT
        from_city,
        to_city,
        distance,
        ARRAY[from_city] AS "path"
    FROM both_ways b1
    WHERE b1.from_city = 'Palermo' --<<< Start Node >>>
  UNION ALL
    SELECT
        b2.from_city,
        b2.to_city,
        p.distance + b2.distance,
        p.path + b2.from_city
    FROM both_ways b2
    JOIN paths p
         ON (p.to_city = b2.from_city
             AND b2.from_city <> ALL (p.path[2:array_upper(p.path,1)]) /* Prevent re-tracing */
             AND array_upper(p.path,1) < 6)
)
SELECT
    path || to_city AS "path",
    distance
FROM paths
WHERE to_city = 'Milano'  --<<< End node >>>
AND ARRAY['Napoli','Roma','Bari'] <@ path -- <<< via... >>> - <@ means 'is contained by'
ORDER BY distance, path
LIMIT 5;
</code>```

I hope someone can help me, how to convert the

```<code>ARRAY[from_city] AS "path"
</code>```

in the Definition of paths

This Conditions in the paths-CTE:

```<code>AND b2.from_city <> ALL (p.path[2:array_upper(p.path,1)]) /* Prevent re-tracing */
         AND array_upper(p.path,1) < 6)
</code>```

And this condition of the select which is using the CTE:

```<code>AND ARRAY['Napoli','Roma','Bari'] <@ path -- <<< via... >>> - <@ means 'is contained by'
</code>```

答:
Try the following

```<code>-- Paths from Palermo to Milano...
;WITH both_ways (
    from_city,
    to_city,
    distance
) /* Working Table containing all ways */
AS (
    SELECT
        from_city,
        to_city,
        distance
    FROM pairs
UNION ALL
    SELECT
        to_city AS "from_city",
        from_city AS "to_city",
        distance
    FROM pairs
),
paths (
    from_city,
    to_city,
    distance,
    path,
    Step
)
AS (
    SELECT
        from_city,
        to_city,
        distance,
        CAST(CONCAT('[',from_city,']') AS varchar(MAX)) AS "path",
        1 Step
    FROM both_ways b1
    WHERE b1.from_city = 'Palermo' --<<< Start Node >>>
  UNION ALL
    SELECT
        b2.from_city,
        b2.to_city,
        p.distance + b2.distance,
        p.path + CONCAT('[',b2.from_city,']'),
        p.Step+1
    FROM both_ways b2
    JOIN paths p
         ON (p.to_city = b2.from_city
             AND CHARINDEX(CONCAT('[',b2.from_city,']'),p.path)=0 /* Prevent re-tracing */
             AND p.Step < 6)
)
SELECT TOP 5
    REPLACE(REPLACE(REPLACE(path,'][',','),'[',''),']',',') + to_city AS "path",
    distance
FROM paths
WHERE to_city = 'Milano'  --<<< End node >>>

  AND CHARINDEX('[Napoli]',path)>0
  AND CHARINDEX('[Roma]',path)>0
  AND CHARINDEX('[Bari]',path)>0  -- <<< via... >>> - <@ means 'is contained by'

ORDER BY distance, path
</code>```

If function CONCAT doesn't work then everywere use concatination with +

```<code>CONCAT('[',from_city,']') => '['+from_city+']'
</code>```

Title: Convert CTE from Postgres to MSSQL

Body:
I hould convert a CTE from Postgresql zu MSSQL.
The Problem is, that the Postgresql-Query uses Arrays. I have no idea how to convert them to MSSQL.

Here is the complete Query with creating the data:

CREATE TABLE pairs (
    from_city VARCHAR(255) NOT NULL,
    to_city VARCHAR(255) NOT NULL,
    distance INTEGER NOT NULL,
    PRIMARY KEY(from_city, to_city),
    CHECK (from_city < to_city)
);

INSERT INTO pairs
VALUES
('Bari','Bologna',672),
('Bari','Genova',944),
('Bari','Milano',881),
('Bari','Napoli',257),
('Bari','Palermo',708),
('Bologna','Genova',190),
('Bologna','Milano',200),
('Bologna','Napoli',470),
('Bologna','Palermo',730),
('Bologna','Roma',300),
('Genova','Milano',120),
('Genova','Napoli',590),
('Genova','Palermo',790),
('Genova','Roma',400),
('Milano','Napoli',660),
('Milano','Palermo',890),
('Milano','Roma',480),
('Napoli','Palermo',310),
('Napoli','Roma',190),
('Palermo','Roma',430);

SELECT * FROM pairs;

-- Paths from Palermo to Milano...
;WITH RECURSIVE both_ways (
    from_city,
    to_city,
    distance
) /* Working Table containing all ways */
AS (
    SELECT
        from_city,
        to_city,
        distance
    FROM pairs
UNION ALL
    SELECT
        to_city AS "from_city",
        from_city AS "to_city",
        distance
    FROM pairs
),
paths (
    from_city,
    to_city,
    distance,
    path
)
AS (
    SELECT
        from_city,
        to_city,
        distance,
        ARRAY[from_city] AS "path"
    FROM both_ways b1
    WHERE b1.from_city = 'Palermo' --<<< Start Node >>>
  UNION ALL
    SELECT
        b2.from_city,
        b2.to_city,
        p.distance + b2.distance,
        p.path + b2.from_city
    FROM both_ways b2
    JOIN paths p
         ON (p.to_city = b2.from_city
             AND b2.from_city <> ALL (p.path[2:array_upper(p.path,1)]) /* Prevent re-tracing */
             AND array_upper(p.path,1) < 6)
)
SELECT
    path || to_city AS "path",
    distance
FROM paths
WHERE to_city = 'Milano'  --<<< End node >>>
AND ARRAY['Napoli','Roma','Bari'] <@ path -- <<< via... >>> - <@ means 'is contained by'
ORDER BY distance, path
LIMIT 5;

I hope someone can help me, how to convert the

ARRAY[from_city] AS "path"

in the Definition of paths

This Conditions in the paths-CTE:

AND b2.from_city <> ALL (p.path[2:array_upper(p.path,1)]) /* Prevent re-tracing */
         AND array_upper(p.path,1) < 6)

And this condition of the select which is using the CTE:

AND ARRAY['Napoli','Roma','Bari'] <@ path -- <<< via... >>> - <@ means 'is contained by'

Body:
Try the following

-- Paths from Palermo to Milano...
;WITH both_ways (
    from_city,
    to_city,
    distance
) /* Working Table containing all ways */
AS (
    SELECT
        from_city,
        to_city,
        distance
    FROM pairs
UNION ALL
    SELECT
        to_city AS "from_city",
        from_city AS "to_city",
        distance
    FROM pairs
),
paths (
    from_city,
    to_city,
    distance,
    path,
    Step
)
AS (
    SELECT
        from_city,
        to_city,
        distance,
        CAST(CONCAT('[',from_city,']') AS varchar(MAX)) AS "path",
        1 Step
    FROM both_ways b1
    WHERE b1.from_city = 'Palermo' --<<< Start Node >>>
  UNION ALL
    SELECT
        b2.from_city,
        b2.to_city,
        p.distance + b2.distance,
        p.path + CONCAT('[',b2.from_city,']'),
        p.Step+1
    FROM both_ways b2
    JOIN paths p
         ON (p.to_city = b2.from_city
             AND CHARINDEX(CONCAT('[',b2.from_city,']'),p.path)=0 /* Prevent re-tracing */
             AND p.Step < 6)
)
SELECT TOP 5
    REPLACE(REPLACE(REPLACE(path,'][',','),'[',''),']',',') + to_city AS "path",
    distance
FROM paths
WHERE to_city = 'Milano'  --<<< End node >>>

  AND CHARINDEX('[Napoli]',path)>0
  AND CHARINDEX('[Roma]',path)>0
  AND CHARINDEX('[Bari]',path)>0  -- <<< via... >>> - <@ means 'is contained by'

ORDER BY distance, path

If function CONCAT doesn't work then everywere use concatination with +

CONCAT('[',from_city,']') => '['+from_city+']'


问:
Include root element in Swagger JSON sample
In our REST API we support both XML and JSON as input/output format and while generating Swagger documentation the sample input generated by Swagger is not showing Root Node value for JSON input but it's coming for XML sample.

As our REST API expecting root node for for JSON also, how can I make Swagger to show Root Node in sample?

Swagger sample XML -

```<code><Request>
    <EmployeeNumber>string</EmployeeNumber>
    <Department>
            <DepartmentId>string</DepartmentId>
            <DepartmentName>string</DepartmentName>
            <DepartmentHead>string</DepartmentHead>
            <DepartmentLocation>string</DepartmentLocation>
    </Department>
</Request>
</code>```

Swagger sample JSON -

```<code>{
    "EmployeeNumber": "string",
    "Department": {
      "DepartmentId": "string",
      "DepartmentName": "string",
      "DepartmentHead": "string",
      "DepartmentLocation": "string"
    }
  }
</code>```

Expected JSON sample -

```<code>{
  "Request": {
    "EmployeeNumber": "string",
    "Department": {
      "DepartmentId": "string",
      "DepartmentName": "string",
      "DepartmentHead": "string",
      "DepartmentLocation": "string"
    }
  }
}
</code>```

How to provide example sample in swagger annotations instead of automatically generating one?

答:
https://github.com/swagger-api/swagger-core/wiki/annotations

Have a look at this. Hope it will help you.

Body:
In our REST API we support both XML and JSON as input/output format and while generating Swagger documentation the sample input generated by Swagger is not showing Root Node value for JSON input but it's coming for XML sample.

As our REST API expecting root node for for JSON also, how can I make Swagger to show Root Node in sample?

Swagger sample XML -

<Request>
    <EmployeeNumber>string</EmployeeNumber>
    <Department>
            <DepartmentId>string</DepartmentId>
            <DepartmentName>string</DepartmentName>
            <DepartmentHead>string</DepartmentHead>
            <DepartmentLocation>string</DepartmentLocation>
    </Department>
</Request>

Swagger sample JSON -

{
    "EmployeeNumber": "string",
    "Department": {
      "DepartmentId": "string",
      "DepartmentName": "string",
      "DepartmentHead": "string",
      "DepartmentLocation": "string"
    }
  }

Expected JSON sample -

{
  "Request": {
    "EmployeeNumber": "string",
    "Department": {
      "DepartmentId": "string",
      "DepartmentName": "string",
      "DepartmentHead": "string",
      "DepartmentLocation": "string"
    }
  }
}

How to provide example sample in swagger annotations instead of automatically generating one?