问:
All com.android.support libraries must use the exact same version
When i updated my android studio today from version 2.2.3 to 2.3 i suddenly got this error in my build.gradle on the first compile line in dependencies

(It doesnt matter which dependencie will be at the first place but it will always give me this error):

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 25.2.0, 24.0.0. Examples include com.android.support:animated-vector-drawable:25.2.0 and com.android.support:mediarouter-v7:24.0.0

i have looked through my entire project and i can not find any usage of versions 24.0.0 (I have looked with ctrl + shift + F to search in entire project)

this is my build.gradle:

```<code>android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 25
        versionName "1.0"
        versionCode 1
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
        debug {
            minifyEnabled true
            shrinkResources true
        }
    }
    dexOptions {
        javaMaxHeapSize "4g"
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.google.android.gms:play-services:+'
    compile 'com.squareup:otto:1.3.8'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
}
</code>```

答: Make all the dependencies of same version or latest version in your case replace support library versions with 25.2.0 . </p>

Body:
When i updated my android studio today from version 2.2.3 to 2.3 i suddenly got this error in my build.gradle on the first compile line in dependencies

(It doesnt matter which dependencie will be at the first place but it will always give me this error):

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 25.2.0, 24.0.0. Examples include com.android.support:animated-vector-drawable:25.2.0 and com.android.support:mediarouter-v7:24.0.0

i have looked through my entire project and i can not find any usage of versions 24.0.0 (I have looked with ctrl + shift + F to search in entire project)

this is my build.gradle:

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 25
        versionName "1.0"
        versionCode 1
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
        debug {
            minifyEnabled true
            shrinkResources true
        }
    }
    dexOptions {
        javaMaxHeapSize "4g"
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.google.android.gms:play-services:+'
    compile 'com.squareup:otto:1.3.8'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
}


来源: stackexchange

问:
Insert array of json data into json file using javascript & JSP
I have one function in my code which gives me x & y coordinates. I have formatted that data and saved that data into an array in JSON format. Now, want to save this variable data into a JSON file. Can anyone help me out from this?
        The variable arrayData contains String of JSON data which I want to save to the new JSON file.
OR
Can I use JSP to save this data into JSON file? But the only problem here is, data is in JavaScript variable.</p>

```<code>game.input.onDown.add(function() {
    x = Math.floor(game.input.activePointer.worldX / 15);
    y = Math.floor(game.input.activePointer.worldY / 15);
    arrayData.push("{'x':'" + x+"','Y':'"+y+"'}");
    document.getElementById('test').innerHTML = ' Data: {"x":' + x+',"Y":'+y+'}';
    console.log(" Data: " + arrayData);
});
</code>```

答:
Thank you all for replying to this question. The problem is solved. Actually, I send the javascript variable to JSP using Ajax post method. It was more than simple than I thought.`function check(){

```<code> $.ajax({
      type: 'POST',
      url: "CollectData.jsp",
      data: {xydata:arrayData},
      dataType: "json",
      success: function(resultData) {
          alert("here");
          console.log("New Data :"+resultData);
      //$("#list").html(resultData);
      }
});
</code>```

}`

and finally, Saved into the JSON file

```<code>String data =request.getParameter("xydata");
JSONObject obj = new JSONObject();
obj.put("arr", data);

try {
FileWriter file = new FileWriter("D:\\test\\testFile.json");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have one function in my code which gives me x & y coordinates. I have formatted that data and saved that data into an array in JSON format. Now, want to save this variable data into a JSON file. Can anyone help me out from this?
        The variable arrayData contains String of JSON data which I want to save to the new JSON file.
OR
Can I use JSP to save this data into JSON file? But the only problem here is, data is in JavaScript variable.

game.input.onDown.add(function() {
    x = Math.floor(game.input.activePointer.worldX / 15);
    y = Math.floor(game.input.activePointer.worldY / 15);
    arrayData.push("{'x':'" + x+"','Y':'"+y+"'}");
    document.getElementById('test').innerHTML = ' Data: {"x":' + x+',"Y":'+y+'}';
    console.log(" Data: " + arrayData);
});

Body:
Thank you all for replying to this question. The problem is solved. Actually, I send the javascript variable to JSP using Ajax post method. It was more than simple than I thought.`function check(){

 $.ajax({
      type: 'POST',
      url: "CollectData.jsp",
      data: {xydata:arrayData},
      dataType: "json",
      success: function(resultData) {
          alert("here");
          console.log("New Data :"+resultData);
      //$("#list").html(resultData);
      }
});

}`

and finally, Saved into the JSON file

String data =request.getParameter("xydata");
JSONObject obj = new JSONObject();
obj.put("arr", data);

try {
FileWriter file = new FileWriter("D:\\test\\testFile.json");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();}


问:
How do I use an equivalent to C++ reference parameters in Java?
Suppose I have this in C++:

```<code>void test(int &i, int &j)
{
    ++i;
    ++j;
}
</code>```

The values are altered inside the function and then used outside. How could I write a code that does the same in Java? I imagine I could return a class that encapsulates both values, but that seems really cumbersome.

答:
Simulating reference with wrappers.

One way you can have this behavior somehow simulated is create a generic wrapper.

```<code>public class _<E> {
    E ref;
    public _( E e ){
        ref = e;
    }
    public E g() { return ref; }
    public void s( E e ){ this.ref = e; }

    public String toString() {
        return ref.toString();
    }
}
</code>```

I'm not too convinced about the value of this code, by I couldn't help it, I had to code it :)

So here it is.

The sample usage:

```<code>public class Test {

    public static void main ( String [] args ) {
        _<Integer> iByRef = new _<Integer>( 1 );
        addOne( iByRef );
        System.out.println( iByRef ); // prints 2

        _<String> sByRef = new _<String>( "Hola" );
        reverse( sByRef );
        System.out.println( sByRef ); // prints aloH

    }

    // Change the value of ref by adding 1
    public static void addOne( _<Integer> ref ) {
        int i = ref.g();
        ref.s( ++i  );

        // or
        //int i = ref.g();
        //ref.s( i + 1 );

    }
    // Reverse the vale of a string.
    public static void reverse( _<String> otherRef ) {
        String v = otherRef.g();
        String reversed = new StringBuilder( v ).reverse().toString();
        otherRef.s( reversed );
    }

}
</code>```

The amusing thing here, is the generic wrapper class name is "_" which is a valid class identifier.  So a declaration reads:

For an integer:

```<code>_<Integer> iByRef = new _<Integer>( 1 );
</code>```

For a String:

```<code>_<String> sByRef = new _<String>( "Hola" );
</code>```

For any other class

```<code>_<Employee> employee = new _<Employee>( Employee.byId(123) );
</code>```

The methods "s" and "g" stands for set and get :P

OwnerDisplayName: al bundy

ContentLicense: CC BY-SA 2.5

Body:
Suppose I have this in C++:

void test(int &i, int &j)
{
    ++i;
    ++j;
}

The values are altered inside the function and then used outside. How could I write a code that does the same in Java? I imagine I could return a class that encapsulates both values, but that seems really cumbersome.

Body:
Simulating reference with wrappers.

One way you can have this behavior somehow simulated is create a generic wrapper.

public class _<E> {
    E ref;
    public _( E e ){
        ref = e;
    }
    public E g() { return ref; }
    public void s( E e ){ this.ref = e; }

    public String toString() {
        return ref.toString();
    }
}

I'm not too convinced about the value of this code, by I couldn't help it, I had to code it :)

So here it is.

The sample usage:

public class Test {

    public static void main ( String [] args ) {
        _<Integer> iByRef = new _<Integer>( 1 );
        addOne( iByRef );
        System.out.println( iByRef ); // prints 2

        _<String> sByRef = new _<String>( "Hola" );
        reverse( sByRef );
        System.out.println( sByRef ); // prints aloH

    }

    // Change the value of ref by adding 1
    public static void addOne( _<Integer> ref ) {
        int i = ref.g();
        ref.s( ++i  );

        // or
        //int i = ref.g();
        //ref.s( i + 1 );

    }
    // Reverse the vale of a string.
    public static void reverse( _<String> otherRef ) {
        String v = otherRef.g();
        String reversed = new StringBuilder( v ).reverse().toString();
        otherRef.s( reversed );
    }

}

The amusing thing here, is the generic wrapper class name is "_" which is a valid class identifier.  So a declaration reads:

For an integer:

_<Integer> iByRef = new _<Integer>( 1 );

For a String:

_<String> sByRef = new _<String>( "Hola" );

For any other class

_<Employee> employee = new _<Employee>( Employee.byId(123) );

The methods "s" and "g" stands for set and get :P

OwnerDisplayName: Oscar Reyes

LastEditorDisplayName: Oscar Reyes


问:
ERROR ITMS-90512: Invalid sdk value... 8.2 is higher than maximum allowed value of 10.3?
Trying to upload a binary, which includes a watch app.  The error I'm getting (which I wasn't getting a couple days ago) is the value provided for LC_VERSION_MIN_IPHONEOS for the watchkit extension is 8.2 which is greater than the maximum allowed value of 10.3... apparently 8.2 > 10.3?

I'm updated to the latest XCode, 8.3, that didn't fix the problem.  Tried changing the iOS deployment target for the watch app and extension, no apparent effect on the message.

答:
This is not related to Xcode 8.3, the error is in the Apple validation process. I had an app in review (no problems in uploading it) that got rejected because the user provided for login had expired. I made no changes to the app, just activated the user and submitted. I have the error now.

Edit: I can also confirm that if Watch support is removed everything goes well.


问:
duplicate entry: com/android/volley/AuthFailureError.class while compiling project in android studio
I am using external libraries payu money sdk and linkedin-sdk, both uses volley libraries, which while compiling project gives duplicate entry of AuthFailureError.class

Error:Execution failed for task ':app:packageAllDebugClassesForMultiDex'.

java.util.zip.ZipException: duplicate entry: com/android/volley/AuthFailureError.class"

i have also added following code to exclude module, but still same error

configurations{
    all*.exclude module: 'com.android.volley'
}

please help

答:
I stumbled upon this same error, and after reading this, I was able to solve it.

Try adding this line inside your app dir build.gradle file -

```<code>android{
configurations {
    all*.exclude group: 'com.android.volley'
}}
</code>```

Hope this helps.

Body:
I stumbled upon this same error, and after reading this, I was able to solve it.

Try adding this line inside your app dir build.gradle file -

android{
configurations {
    all*.exclude group: 'com.android.volley'
}}

Hope this helps.


问:
Android Java Bluetooth RSSI signal strength
I have problem about RSSI. I have reviewed resources from internet. But all of codes not working or I don't know way of the this. Just I want to receive the signal strength of the device that I connect via Bluetooth. Also, Am I need to use any a permission? Can you explain all of details about this? My codes as follows.</p>

```<code>    private final BroadcastReceiver receiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if(BluetoothDevice.ACTION_FOUND.equals(action)) {
            int  rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
            Toast.makeText(BtControl.this,"  RSSI: " + rssi + "dBm", Toast.LENGTH_SHORT).show();
        }
    }
};

registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
</code>```

答:
you should register for ACTION_FOUND action. Change your registerreciever code to below.

```<code>registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
</code>```

Also make sure you declare BLUETOOTH_ADMIN permission in the manifest file.

Body:
I have problem about RSSI. I have reviewed resources from internet. But all of codes not working or I don't know way of the this. Just I want to receive the signal strength of the device that I connect via Bluetooth. Also, Am I need to use any a permission? Can you explain all of details about this? My codes as follows.

    private final BroadcastReceiver receiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if(BluetoothDevice.ACTION_FOUND.equals(action)) {
            int  rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
            Toast.makeText(BtControl.this,"  RSSI: " + rssi + "dBm", Toast.LENGTH_SHORT).show();
        }
    }
};

registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

Body:
you should register for ACTION_FOUND action. Change your registerreciever code to below.

registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));

Also make sure you declare BLUETOOTH_ADMIN permission in the manifest file.


问:
FOSUserBundle ignore password field
So I'm using the FOSUserBundle with LDAP as my authentication method, and I'm wondering whether there is a way to remove/ignore the password field for my FOSUser entity?

I realize removal might not be ideal (in case it messes with internal logic), but the column is never used, and I'm forced to fill it when I'm creating FOSUsers from fixtures:

```<code>$user = new FOSUser();

$user->setDn($item["dn"]);
$user->setEnabled(1);
$user->setUsername($item["samaccountname"][0]);
$user->setUsernameCanonical(strtolower($item["samaccountname"][0]));
$user->setEmail($item["mail"][0]);
$user->setEmailCanonical(strtolower($item["mail"][0]));
$user->setDepartment($ldap_groups[$matches[1]]);
$user->setDepartmentDn($group);
$user->setPassword('blank'); // Is there away to avoid this?

$manager->persist($user);
</code>```

答:
So to override a column doctrine allows for Inheritance Mapping:

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 * @ORM\AttributeOverrides({
 *     @ORM\AttributeOverride(name="password",
 *          column=@ORM\Column(
 *              name     = "password",
 *              type     = "string",
 *              nullable=true
 *          )
 *      )
 * })
 */
class FOSUser extends BaseUser implements LdapUserInterface
{
  // Extended logic.
}
</code>```

The password field still resides in BaseUser, but is overwritten by the @ORM\AttributeOverride annotation.

Title: FOSUserBundle ignore password field

Body:
So I'm using the FOSUserBundle with LDAP as my authentication method, and I'm wondering whether there is a way to remove/ignore the password field for my FOSUser entity?

I realize removal might not be ideal (in case it messes with internal logic), but the column is never used, and I'm forced to fill it when I'm creating FOSUsers from fixtures:

$user = new FOSUser();

$user->setDn($item["dn"]);
$user->setEnabled(1);
$user->setUsername($item["samaccountname"][0]);
$user->setUsernameCanonical(strtolower($item["samaccountname"][0]));
$user->setEmail($item["mail"][0]);
$user->setEmailCanonical(strtolower($item["mail"][0]));
$user->setDepartment($ldap_groups[$matches[1]]);
$user->setDepartmentDn($group);
$user->setPassword('blank'); // Is there away to avoid this?

$manager->persist($user);

Body:
So to override a column doctrine allows for Inheritance Mapping:

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 * @ORM\AttributeOverrides({
 *     @ORM\AttributeOverride(name="password",
 *          column=@ORM\Column(
 *              name     = "password",
 *              type     = "string",
 *              nullable=true
 *          )
 *      )
 * })
 */
class FOSUser extends BaseUser implements LdapUserInterface
{
  // Extended logic.
}

The password field still resides in BaseUser, but is overwritten by the @ORM\AttributeOverride annotation.


问:
Assign a floating ip to an openstack instance using a heat template
Here is my template that works. I execute a 'heat stack-create' command with that template and it creates a stack and an instance with an ip. I have access to an interface to manage my instances. From that interface, I am able to create a floating IP and then assign it to my newly created instance.

```<code>heat_template_version: 2013-05-23

description: >
    Docker generic server

parameters:
    image_id: {default: centos-7, description: image, type: string}
    instance_type: {default: ug1.medium, description: instance, type: string}
    key_name: {default: user, description: Name of an existing key pair to use for the instance, type: string}

resources:
    nginx_securitygroup:
      properties:
        GroupDescription: Generic security group for nginx stack
        SecurityGroupIngress:
          - {CidrIp: 10.0.0.0/8, FromPort: '80', IpProtocol: TCP, ToPort: '80'}
  type: AWS::EC2::SecurityGroup

server_securitygroup:
    type: AWS::EC2::SecurityGroup
    properties:
        GroupDescription: Generic security group from docker nginx
        SecurityGroupIngress:
            # This is needed to allow pinging the server
            - {"CidrIp": "10.0.0.0/8", "FromPort": "-1", "ToPort": "-1", "IpProtocol": "ICMP"}

            # Ssh port
            - {"CidrIp": "10.0.0.0/8", "FromPort": "22", "ToPort": "22", "IpProtocol": "TCP"}

            # Open docker ports
            - {"CidrIp": "10.0.0.0/8", "FromPort": "2375", "ToPort": "2375", "IpProtocol": "TCP"}
            - {"CidrIp": "10.0.0.0/8", "FromPort": "2376", "ToPort": "2376", "IpProtocol": "TCP"}

docker_server:
    type: AWS::EC2::Instance
    properties:

        ImageId: { get_param: image_id }
        InstanceType: { get_param: instance_type }
        KeyName: { get_param: key_name }
        SecurityGroups:
            - Ref: server_securitygroup
            - {Ref: nginx_securitygroup}

        UserData: |
            #!/bin/bash -v

            #Do some operations to start the docker container on the instance

outputs:
    ipaddress_private:
        description: Private ip
        value:
            "Fn::GetAtt":
                - docker_server
                - PrivateIp
</code>```

My issue is that I do not want to assign manually my created floating IP to the instance, I want it to be assigned automatically when my stack and instance are created. I tried following some documentatio, this one for example: http://blog.oddbit.com/2013/12/06/an-introduction-to-openstack-heat/

But it does not work. Maybe it's because it's trying to assign a floating IP to another existing resource (server). How can I make the association work?

答:
Use the FloatingIPAssociation resources. Example :

```<code>  association:
    type: OS::Nova::FloatingIPAssociation
    properties:
      floating_ip: { get_param: floatingIpId }
      server_id: { get_resource: instance }
</code>```

Other example with NeutronFloatingAssociation:

```<code>  association:
     type: OS::Neutron::FloatingIPAssociation
     properties:
       floatingip_id: { get_param: floatingIpId }
       port_id: { get_param: port_id }
</code>```

Body:
Here is my template that works. I execute a 'heat stack-create' command with that template and it creates a stack and an instance with an ip. I have access to an interface to manage my instances. From that interface, I am able to create a floating IP and then assign it to my newly created instance.

heat_template_version: 2013-05-23

description: >
    Docker generic server

parameters:
    image_id: {default: centos-7, description: image, type: string}
    instance_type: {default: ug1.medium, description: instance, type: string}
    key_name: {default: user, description: Name of an existing key pair to use for the instance, type: string}

resources:
    nginx_securitygroup:
      properties:
        GroupDescription: Generic security group for nginx stack
        SecurityGroupIngress:
          - {CidrIp: 10.0.0.0/8, FromPort: '80', IpProtocol: TCP, ToPort: '80'}
  type: AWS::EC2::SecurityGroup

server_securitygroup:
    type: AWS::EC2::SecurityGroup
    properties:
        GroupDescription: Generic security group from docker nginx
        SecurityGroupIngress:
            # This is needed to allow pinging the server
            - {"CidrIp": "10.0.0.0/8", "FromPort": "-1", "ToPort": "-1", "IpProtocol": "ICMP"}

            # Ssh port
            - {"CidrIp": "10.0.0.0/8", "FromPort": "22", "ToPort": "22", "IpProtocol": "TCP"}

            # Open docker ports
            - {"CidrIp": "10.0.0.0/8", "FromPort": "2375", "ToPort": "2375", "IpProtocol": "TCP"}
            - {"CidrIp": "10.0.0.0/8", "FromPort": "2376", "ToPort": "2376", "IpProtocol": "TCP"}

docker_server:
    type: AWS::EC2::Instance
    properties:

        ImageId: { get_param: image_id }
        InstanceType: { get_param: instance_type }
        KeyName: { get_param: key_name }
        SecurityGroups:
            - Ref: server_securitygroup
            - {Ref: nginx_securitygroup}

        UserData: |
            #!/bin/bash -v

            #Do some operations to start the docker container on the instance

outputs:
    ipaddress_private:
        description: Private ip
        value:
            "Fn::GetAtt":
                - docker_server
                - PrivateIp

My issue is that I do not want to assign manually my created floating IP to the instance, I want it to be assigned automatically when my stack and instance are created. I tried following some documentatio, this one for example: http://blog.oddbit.com/2013/12/06/an-introduction-to-openstack-heat/

But it does not work. Maybe it's because it's trying to assign a floating IP to another existing resource (server). How can I make the association work?

Body:
Use the FloatingIPAssociation resources. Example :

  association:
    type: OS::Nova::FloatingIPAssociation
    properties:
      floating_ip: { get_param: floatingIpId }
      server_id: { get_resource: instance }

Other example with NeutronFloatingAssociation:

  association:
     type: OS::Neutron::FloatingIPAssociation
     properties:
       floatingip_id: { get_param: floatingIpId }
       port_id: { get_param: port_id }


问:
Downloading an image being cached and showing in my imageview
I need to download an image where it saves in the cache using Imageview, somehow for me to do it in a simple way ?

I can download it as you can see below more in not saved in cache

```<code>private Bitmap GetImageBitmapFromUrl(string url)
    {
        Bitmap imageBitmap = null;

        using (var webClient = new WebClient())
        {
            try
            {
                var imageBytes = webClient.DownloadData(url);
                if (imageBytes != null && imageBytes.Length > 0)
                {
                    imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
                }
            }
            catch
            {

            }
        }

        return imageBitmap;
    }

    //-----------

        **Show image**
        var imageBitmap = GetImageBitmapFromUrl("URL");
        imageView.SetImageBitmap(imageBitmap);
</code>```

答:
https://github.com/luberda-molinet/FFImageLoading

Example :-

```<code>ImageService.Instance.LoadUrl(urlToImage)
                .Retry(3, 200)
                .DownSample(300, 300)
                .Transform(new CircleTransformation())
                .Transform(new GrayscaleTransformation())
                .LoadingPlaceholder(Config.LoadingPlaceholderPath, ImageSource.ApplicationBundle)
                .ErrorPlaceholder(Config.ErrorPlaceholderPath, ImageSource.ApplicationBundle)
.Into(_imgDisplay);
</code>```

Body:
I need to download an image where it saves in the cache using Imageview, somehow for me to do it in a simple way ?

I can download it as you can see below more in not saved in cache

private Bitmap GetImageBitmapFromUrl(string url)
    {
        Bitmap imageBitmap = null;

        using (var webClient = new WebClient())
        {
            try
            {
                var imageBytes = webClient.DownloadData(url);
                if (imageBytes != null && imageBytes.Length > 0)
                {
                    imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
                }
            }
            catch
            {

            }
        }

        return imageBitmap;
    }

    //-----------

        **Show image**
        var imageBitmap = GetImageBitmapFromUrl("URL");
        imageView.SetImageBitmap(imageBitmap);

Body:
https://github.com/luberda-molinet/FFImageLoading

Example :-

ImageService.Instance.LoadUrl(urlToImage)
                .Retry(3, 200)
                .DownSample(300, 300)
                .Transform(new CircleTransformation())
                .Transform(new GrayscaleTransformation())
                .LoadingPlaceholder(Config.LoadingPlaceholderPath, ImageSource.ApplicationBundle)
                .ErrorPlaceholder(Config.ErrorPlaceholderPath, ImageSource.ApplicationBundle)
.Into(_imgDisplay);


问:
Function mcrypt_get_iv_size() is deprecated in laravel 4.2 on PHP 5.6 server
I'm using ubuntu 16.04 and my php version is php5.6.
When i run here laravel version 4.2 project, then show a deprecated message "Function mcrypt_get_iv_size() is deprecated" .
But Laravel 5.2 project is fine. There is no problem. It occurred when i run laravel 4.2 project.

答:
This is a known issue.

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

source: php.net

You either disable exceptions on warning or you upgrade your Laravel project to 5.2, or you stick to a version where your Laravel project supports the PHP version you are using.


问:
C++ linker cannot find reference to local functions
I have this simple code inserted in myfile.hpp file inside a project of mine:

```<code>#ifndef _PERFORMANCE_INDEX_HPP_
#define _PERFORMANCE_INDEX_HPP_

#include <boost/math/special_functions/powm1.hpp>
#include <boost/math/special_functions/log1p.hpp>
#include <boost/math/special_functions/sqrt1pm1.hpp>

//-----------------------------------------------------------------------------
// Enum, struct, aliases
namespace middleware {
namespace calculus {
/*!
 * Parameters needed for calculating PI.
 */
typedef struct {
    double eval_cpu_mhz; /* CPU MHz */
    double eval_ram_mb; /* RAM in MegaBytes */
    unsigned int eval_core_num; /* Number of cores per processor */
    unsigned int eval_cpu_num; /* Number of processors */
    unsigned int eval_hops; /* INET hop distance */
    double eval_bandwidth; /* Bandwidth in KBit/s */
    unsigned int eval_load; /* Number of tasks in queue in worker */
} PerformanceEvalParams;
/*!
 * PI type.
 */
typedef double PIType;
}
}
//-----------------------------------------------------------------------------
// Constants
namespace middleware {
namespace calculus {
const double kPerformanceEvalBeta = 3.0;
const double kPerformanceEvalDelta = 1.0;
const double kPerformanceEvalG = 1.60;
const double kPerformanceEvalH = 1.014;
const double kPerformanceEvalR = 512;
}
}
//-----------------------------------------------------------------------------
// Functions declarations
namespace middleware {
namespace calculus {
/*!
 * Used to calculate log in a given base.
 */
double Log(double base, double arg);
/*!
 * Used to calculate sqrt.
 */
double Sqrt(double arg);
/*!
 * Used to calculate exp by a given base.
 */
double Exp(double base, double arg);
/*!
 * Used for calculate PI
 */
PIType CalulatePI(const PerformanceEvalParams& pep);
}
}
//-----------------------------------------------------------------------------
// Functions implementations
using namespace middleware::calculus;
PIType CalculatePI(const PerformanceEvalParams& pep) {
    double N = -1, S = -1, C = -1; /* Parts */
    double PI = -1; /* Final result */
    N = (double)(kPerformanceEvalBeta * pep.eval_bandwidth);
    N = (double)(N / (double)((kPerformanceEvalDelta * (pep.eval_hops + 1))));
    N = (double)(Sqrt(N));
    S = (double)(pep.eval_cpu_mhz * pep.eval_cpu_num);
    S = (double)(S / ((double)(pep.eval_load + 1)));
    C = Log(kPerformanceEvalG, pep.eval_core_num);
    C = (double)(C + 1);
    C = (double)((double)1 + Exp(kPerformanceEvalH, -(pep.eval_ram_mb - 512)));
    PI = (double)(N * S * C);
    return PI;
}
double Log(double base, double arg) {
    // Boost Log returns boost::math::log1p(x) = log(e, x + 1)
    double res = (double)(boost::math::log1p(arg - 1));
    // Base conversion: log(new, y) = log(old, y) / log(old, new)
    // Then ==> log(base, arg) = log(e, arg) / log(e, base)
    res = (double)(res / boost::math::log1p(base));
    return res;
}
double Sqrt(double arg) {
    // Boost Sqrt returns boost::math::sqrt1pm1(x) = sqrt(1 + x) - 1
    double res = (double)(boost::math::sqrt1pm1(arg - 1));
    res = (double)(res + 1);
    return res;
}
double Exp(double base, double arg) {
    // Boost Pow returns boost::math::powm1(x, y) = x^y - 1
    double res = (double)(boost::math::powm1(base, arg));
    res = (double)(res + 1);
    return res;
}

#endif
</code>```

I compile using this compilation directive:

g++ *.cpp

In main.cpp notice that there is #include "myfile.hpp", so it is compiled.

g++ tells me this:

/tmp/ccY04BAx.o: In function
  CalculatePI(middleware::calculus::PerformanceEvalParams
  const&)': main.cpp:(.text+0x1edd):
  undefined reference to
  middleware::calculus::Sqrt(double)'
  main.cpp:(.text+0x1f43): undefined
  reference to
  middleware::calculus::Log(double,
  double)' main.cpp:(.text+0x1f72):
  undefined reference to
  middleware::calculus::Exp(double,
  double)' collect2: ld returned 1 exit
  status

What's the problem? Thank you

答:
Your functions declarations are in namespace middleware::calculus, your functions definitions are not.

The using declarations you added before the implementations is not of any help here (and is by the way, generally not recommended in a header file), and surely doesn't mean that omitting the namespace in the definitions will implicitly 'match' the declarations.

Body:
I have this simple code inserted in myfile.hpp file inside a project of mine:

#ifndef _PERFORMANCE_INDEX_HPP_
#define _PERFORMANCE_INDEX_HPP_

#include <boost/math/special_functions/powm1.hpp>
#include <boost/math/special_functions/log1p.hpp>
#include <boost/math/special_functions/sqrt1pm1.hpp>

//-----------------------------------------------------------------------------
// Enum, struct, aliases
namespace middleware {
namespace calculus {
/*!
 * Parameters needed for calculating PI.
 */
typedef struct {
    double eval_cpu_mhz; /* CPU MHz */
    double eval_ram_mb; /* RAM in MegaBytes */
    unsigned int eval_core_num; /* Number of cores per processor */
    unsigned int eval_cpu_num; /* Number of processors */
    unsigned int eval_hops; /* INET hop distance */
    double eval_bandwidth; /* Bandwidth in KBit/s */
    unsigned int eval_load; /* Number of tasks in queue in worker */
} PerformanceEvalParams;
/*!
 * PI type.
 */
typedef double PIType;
}
}
//-----------------------------------------------------------------------------
// Constants
namespace middleware {
namespace calculus {
const double kPerformanceEvalBeta = 3.0;
const double kPerformanceEvalDelta = 1.0;
const double kPerformanceEvalG = 1.60;
const double kPerformanceEvalH = 1.014;
const double kPerformanceEvalR = 512;
}
}
//-----------------------------------------------------------------------------
// Functions declarations
namespace middleware {
namespace calculus {
/*!
 * Used to calculate log in a given base.
 */
double Log(double base, double arg);
/*!
 * Used to calculate sqrt.
 */
double Sqrt(double arg);
/*!
 * Used to calculate exp by a given base.
 */
double Exp(double base, double arg);
/*!
 * Used for calculate PI
 */
PIType CalulatePI(const PerformanceEvalParams& pep);
}
}
//-----------------------------------------------------------------------------
// Functions implementations
using namespace middleware::calculus;
PIType CalculatePI(const PerformanceEvalParams& pep) {
    double N = -1, S = -1, C = -1; /* Parts */
    double PI = -1; /* Final result */
    N = (double)(kPerformanceEvalBeta * pep.eval_bandwidth);
    N = (double)(N / (double)((kPerformanceEvalDelta * (pep.eval_hops + 1))));
    N = (double)(Sqrt(N));
    S = (double)(pep.eval_cpu_mhz * pep.eval_cpu_num);
    S = (double)(S / ((double)(pep.eval_load + 1)));
    C = Log(kPerformanceEvalG, pep.eval_core_num);
    C = (double)(C + 1);
    C = (double)((double)1 + Exp(kPerformanceEvalH, -(pep.eval_ram_mb - 512)));
    PI = (double)(N * S * C);
    return PI;
}
double Log(double base, double arg) {
    // Boost Log returns boost::math::log1p(x) = log(e, x + 1)
    double res = (double)(boost::math::log1p(arg - 1));
    // Base conversion: log(new, y) = log(old, y) / log(old, new)
    // Then ==> log(base, arg) = log(e, arg) / log(e, base)
    res = (double)(res / boost::math::log1p(base));
    return res;
}
double Sqrt(double arg) {
    // Boost Sqrt returns boost::math::sqrt1pm1(x) = sqrt(1 + x) - 1
    double res = (double)(boost::math::sqrt1pm1(arg - 1));
    res = (double)(res + 1);
    return res;
}
double Exp(double base, double arg) {
    // Boost Pow returns boost::math::powm1(x, y) = x^y - 1
    double res = (double)(boost::math::powm1(base, arg));
    res = (double)(res + 1);
    return res;
}

#endif

I compile using this compilation directive:

g++ *.cpp

In main.cpp notice that there is #include "myfile.hpp", so it is compiled.

g++ tells me this:

/tmp/ccY04BAx.o: In function
  CalculatePI(middleware::calculus::PerformanceEvalParams
  const&)': main.cpp:(.text+0x1edd):
  undefined reference to
  middleware::calculus::Sqrt(double)'
  main.cpp:(.text+0x1f43): undefined
  reference to
  middleware::calculus::Log(double,
  double)' main.cpp:(.text+0x1f72):
  undefined reference to
  middleware::calculus::Exp(double,
  double)' collect2: ld returned 1 exit
  status

What's the problem? Thank you


问:
Find name using like operator in SQL Server
I have table with columns

```<code>surname    forename
Dane jr    Carlo
Dane Br    Carlo
Daniel     Gerard
</code>```

forename should be same and surname partially same (means string before space  should be same after space should not same)

Output like

```<code>surname    forename
Dane jr    Carlo
Dane Br    Carlo
</code>```

答:
```<code>WITH CTE (namee, forename) AS (
select  LEFT(surname,charindex(' ',surname,1)) as namee, forename
from tabTestName
group by forename, LEFT(surname,charindex(' ',surname,1)) having count(*)>1
) select t.* from CTE join tabTestName t
</code>```

on t.surname like '%'+CTE.namee+'%'
and t.forename=CTE.forename

Body:
I have table with columns

surname    forename
Dane jr    Carlo
Dane Br    Carlo
Daniel     Gerard

forename should be same and surname partially same (means string before space  should be same after space should not same)

Output like

surname    forename
Dane jr    Carlo
Dane Br    Carlo

Body:
WITH CTE (namee, forename) AS (
select  LEFT(surname,charindex(' ',surname,1)) as namee, forename
from tabTestName
group by forename, LEFT(surname,charindex(' ',surname,1)) having count(*)>1
) select t.* from CTE join tabTestName t

on t.surname like '%'+CTE.namee+'%'
and t.forename=CTE.forename


问:
Errors Installing mysql2 gem via the Bundler
I am trying to install the mysql2 gem via the Bundler, but it keeps dying with the following error:

```<code>** executing command
/home/cc_rails/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems/installer.rb:483:in 'rescue in block in build_extensions':
ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

/home/cc_rails/.rvm/rubies/ruby-1.9.2-p0/bin/ruby extconf.rb --with-mysql-config=/usr/bin/mysql_config
checking for rb_thread_blocking_region()... yes
checking for mysql.h... no
checking for mysql/mysql.h... no

-----
mysql.h is missing.  please check your installation of mysql and try again.
-----

*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/home/cc_rails/.rvm/rubies/ruby-1.9.2-p0/bin/ruby
--with-mysql-config
Gem files will remain installed for inspection.
</code>```

Most things I found via Googling recommended passing the --with-mysql-config parameter to fix it.  So, based on:

```<code>$ which mysql_config
/usr/bin/mysql_config
</code>```

I added the following to the Bundler's config:

```<code>$ bundle config build.mysql2 --with-mysql-config='/usr/bin/mysql_config'
</code>```

However, still no luck -- same crash as above.

Since it's dying with the error mysql.h is missing, I checked for that, and it's allegedly around, just can't be found by the Bundler.

```<code>$ find / -name mysql.h
/usr/include/mysql5/mysql/mysql.h
</code>```

Any thoughts?

答:
I got the same error. and for ubuntu 16. I had to write below command:

```<code>sudo apt-get install libmysqlclient-dev
</code>```

and it work back.

Body:
I am trying to install the mysql2 gem via the Bundler, but it keeps dying with the following error:

** executing command
/home/cc_rails/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems/installer.rb:483:in 'rescue in block in build_extensions':
ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

/home/cc_rails/.rvm/rubies/ruby-1.9.2-p0/bin/ruby extconf.rb --with-mysql-config=/usr/bin/mysql_config
checking for rb_thread_blocking_region()... yes
checking for mysql.h... no
checking for mysql/mysql.h... no

-----
mysql.h is missing.  please check your installation of mysql and try again.
-----

*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/home/cc_rails/.rvm/rubies/ruby-1.9.2-p0/bin/ruby
--with-mysql-config
Gem files will remain installed for inspection.

Most things I found via Googling recommended passing the --with-mysql-config parameter to fix it.  So, based on:

$ which mysql_config
/usr/bin/mysql_config

I added the following to the Bundler's config:

$ bundle config build.mysql2 --with-mysql-config='/usr/bin/mysql_config'

However, still no luck -- same crash as above.

Since it's dying with the error mysql.h is missing, I checked for that, and it's allegedly around, just can't be found by the Bundler.

$ find / -name mysql.h
/usr/include/mysql5/mysql/mysql.h

Any thoughts?

Body:
I got the same error. and for ubuntu 16. I had to write below command:

sudo apt-get install libmysqlclient-dev

and it work back.


问:
Resize image - keep ratio - without background image
Im trying to achieve the effect shown on this site:

http://fofwebdesign.co.uk/template/_testing/scale-img/target-ratio-resize.htm

BUT this site does it using a background image for a div. I cannot use the background image as the image is inside Wordpress and it's being brought in dynamically using the following code:

```<code><div class="featured-image">
   <?php the_post_thumbnail(); ?>
</div>
</code>```

So I have tried the same approach and tried the following things o try and bring the image in as a background image:

```<code>.featured-image {
  max-width: 960px;
  /* actual img width */
  max-height: 150px;
  /* actual img height */*
  height: 150px;
  /* actual img height - IE7 */
  background-image: <?php the_post_thumbnail(); ?>;
  background-size: cover;
  background-position: center;
}
</code>```

and using this:

```<code>background-image: url(<?php the_post_thumbnail(); ?>);
</code>```

Alas, I cant seem to get it to work - Im not even sure I can use PHP inside a CSS document...

So I'm looking for a way to achieve this image resize just on the following class without using a background image...

```<code><div class="featured-image">
   <?php the_post_thumbnail(); ?>
</div>
</code>```

Any help would be massively appreciated - I don't even know if I'm thinking about it correctly or I'm missing something - Thanks!

Example of what I'm trying to achieve here:

答:
There is probably an easier way, But using Jquery does the trick. Don't think you really need my CSS, apart from the position:relative for the image.

https://jsfiddle.net/ny746vLx/2/ (Non WordPress)

Jquery as follows:

```<code>$(".featured-image>img").each(function(i, img) {
    $(img).css({
        left: ($(img).parent().width() - $(img).width()) / 2
    });
});
</code>```

https://jsfiddle.net/ny746vLx/4/ (Wordpress)

```<code>;(function($){
    imageChange = function(){
        $(".featured-image>img").each(function(i, img) {
        $(img).css({
            left: ($(img).parent().width() - $(img).width()) / 2
        });
    });
}
    $(window).resize(imageChange);
})(jQuery);

imageChange();
</code>```

This will physically move the image to the left enough for the image to center.

The jQuery selector '>' means that it will target all img tags directly after the .imageContainer div. You can use these declarations in your CSS too.

EDIT: I've used the classes that you've printed above. Don't think you'll need to change anything from the fiddle. Just remember to add position:relative to your css for the image.

EDIT2: I've added another fiddle that will work (Hopefully) with wordpress. jQuery has some conflicts with it. There are easier ways but I'm unfamiliar really with conflicts in jQuery.

Body:
Im trying to achieve the effect shown on this site:

http://fofwebdesign.co.uk/template/_testing/scale-img/target-ratio-resize.htm

BUT this site does it using a background image for a div. I cannot use the background image as the image is inside Wordpress and it's being brought in dynamically using the following code:

   <?php the_post_thumbnail(); ?>

So I have tried the same approach and tried the following things o try and bring the image in as a background image:

.featured-image {
  max-width: 960px;
  /* actual img width */
  max-height: 150px;
  /* actual img height */*
  height: 150px;
  /* actual img height - IE7 */
  background-image: <?php the_post_thumbnail(); ?>;
  background-size: cover;
  background-position: center;
}

and using this:

background-image: url(<?php the_post_thumbnail(); ?>);

Alas, I cant seem to get it to work - Im not even sure I can use PHP inside a CSS document...

So I'm looking for a way to achieve this image resize just on the following class without using a background image...

   <?php the_post_thumbnail(); ?>

Any help would be massively appreciated - I don't even know if I'm thinking about it correctly or I'm missing something - Thanks!

Example of what I'm trying to achieve here:

Body:
There is probably an easier way, But using Jquery does the trick. Don't think you really need my CSS, apart from the position:relative for the image.

https://jsfiddle.net/ny746vLx/2/ (Non WordPress)

Jquery as follows:

$(".featured-image>img").each(function(i, img) {
    $(img).css({
        left: ($(img).parent().width() - $(img).width()) / 2
    });
});

https://jsfiddle.net/ny746vLx/4/ (Wordpress)

;(function($){
    imageChange = function(){
        $(".featured-image>img").each(function(i, img) {
        $(img).css({
            left: ($(img).parent().width() - $(img).width()) / 2
        });
    });
}
    $(window).resize(imageChange);
})(jQuery);

imageChange();

This will physically move the image to the left enough for the image to center.

The jQuery selector '>' means that it will target all img tags directly after the .imageContainer div. You can use these declarations in your CSS too.

EDIT: I've used the classes that you've printed above. Don't think you'll need to change anything from the fiddle. Just remember to add position:relative to your css for the image.

EDIT2: I've added another fiddle that will work (Hopefully) with wordpress. jQuery has some conflicts with it. There are easier ways but I'm unfamiliar really with conflicts in jQuery.


问:
Proper placement of q.all inside array.map with _.forEach
I have the following code which searches my mongodb using find() using values extracted using array.map. Said search returns an object, which I then used a _.forEach to extract the values.

I used this article as basis, however the difference between his examples and mine was he used only one loop. I'm using two. In this case, where should I put my q.all()?

Here's my code. Please note that is server-side:

```<code>'use strict';
var q = require('q');

exports.downloadEmployee = function (req, res) {
    var tempCtr = [];

    if (req.params.hasdr === "yes") {
        return queries.generateDirectReportsCSV(req.params.id).then(function (directReports) {
            return directReports;
        }).then(function (directReports) {
            var empIDcoll = _.pluck(directReports.Data, "employeenumber");
            return empIDcoll;
        }).then(function (empIDcoll) {
            var promises = [];

            empIDcoll.map(function (id) {

                return EmployeeInfo.find({ employeeID: id }, function (err, results) {
                    if (err) { return err; }

                    _.forEach(results, function (item) {
                        if (item) {
                            tempCtr.push({
                                employeeID: item.employeeID,
                                employeeName: item.employeeName
                            });
                            promises.push(tempCtr);
                        }
                    });
                });

                q.all(promises).then(function (results) {
                    return res.json(results);
                });
            });
        });
    }
</code>```

When I run this, I don't get any result back.

Any answers will be greatly appreciated.

Thank you.

UPDATE: I've decided to revise my code and replaced array.map with the usual for loop:

```<code>.then(function (empIDcoll) {

    for (var i = 0; i <= empIDcoll.length - 1; i++) {
        var promise = EmployeeInfo.find({ employeeID: empIDcoll[i] }, function (err, results) {
            if (err) { return err; }

            _.forEach(results, function (item) {
                if (item) {
                    tempCtr.push({
                        employeeID: item.employeeID,
                        employeeName: item.employeeName,
                        currentShift: item.currentShift,
                        isOpenToIntlAssignment: item.isOpenToIntlAssignment,
                        desiredRole1: item.desiredRole1,
                        desiredRole2: item.desiredRole2,
                        desiredRole3: item.desiredRole3,
                        desiredRoleOther: item.desiredRoleOther,
                        passportInfo: item.passportInfo,
                        visaInfo: item.visaInfo,
                        yrsInIT: item.yrsInIT,
                        yrsAsCustomerPM: item.yrsAsCustomerPM,
                        yrsAsCustomerProgM: item.yrsAsCustomerProgM,
                        primaryDomain: item.primaryDomain,
                        primaryDomainOther: item.primaryDomainOther,
                        primaryIndustry: item.primaryIndustry,
                        primaryIndustryOther: item.primaryIndustryOther,
                        isPMPCertified: item.isPMPCertified,
                        pmpCertExpiryDate: item.pmpCertExpiryDate,
                        isPGMPCertified: item.isPGMPCertified,
                        pgmpCertExpiryDate: item.pgmpCertExpiryDate,
                        isScrumCertified: item.isScrumCertified,
                        scrumCertExpiryDate: item.scrumCertExpiryDate,
                        biggestProjectTCV: item.biggestProjectTCV,
                        biggestTeamSizeManaged: item.biggestTeamSizeManaged,
                        avgTeamSizeManaged: item.avgTeamSizeManaged,
                        biggestBilledFTE: item.biggestBilledFTE,
                        avgBilledFTE: item.avgBilledFTE
                    });
                }
            });
        });
        promises.push(promise);
    }

    return q.all(promises).then(function(data){
        return res.json(data);
    });

});
</code>```

...but it's still not returning anything. What am I doing wrong?

答: Remove the return statement before EmployeeInfo.find?

Body:
I have the following code which searches my mongodb using find() using values extracted using array.map. Said search returns an object, which I then used a _.forEach to extract the values.

I used this article as basis, however the difference between his examples and mine was he used only one loop. I'm using two. In this case, where should I put my q.all()?

Here's my code. Please note that is server-side:

'use strict';
var q = require('q');

exports.downloadEmployee = function (req, res) {
    var tempCtr = [];

    if (req.params.hasdr === "yes") {
        return queries.generateDirectReportsCSV(req.params.id).then(function (directReports) {
            return directReports;
        }).then(function (directReports) {
            var empIDcoll = _.pluck(directReports.Data, "employeenumber");
            return empIDcoll;
        }).then(function (empIDcoll) {
            var promises = [];

            empIDcoll.map(function (id) {

                return EmployeeInfo.find({ employeeID: id }, function (err, results) {
                    if (err) { return err; }

                    _.forEach(results, function (item) {
                        if (item) {
                            tempCtr.push({
                                employeeID: item.employeeID,
                                employeeName: item.employeeName
                            });
                            promises.push(tempCtr);
                        }
                    });
                });

                q.all(promises).then(function (results) {
                    return res.json(results);
                });
            });
        });
    }

When I run this, I don't get any result back.

Any answers will be greatly appreciated.

Thank you.

UPDATE: I've decided to revise my code and replaced array.map with the usual for loop:

.then(function (empIDcoll) {

    for (var i = 0; i <= empIDcoll.length - 1; i++) {
        var promise = EmployeeInfo.find({ employeeID: empIDcoll[i] }, function (err, results) {
            if (err) { return err; }

            _.forEach(results, function (item) {
                if (item) {
                    tempCtr.push({
                        employeeID: item.employeeID,
                        employeeName: item.employeeName,
                        currentShift: item.currentShift,
                        isOpenToIntlAssignment: item.isOpenToIntlAssignment,
                        desiredRole1: item.desiredRole1,
                        desiredRole2: item.desiredRole2,
                        desiredRole3: item.desiredRole3,
                        desiredRoleOther: item.desiredRoleOther,
                        passportInfo: item.passportInfo,
                        visaInfo: item.visaInfo,
                        yrsInIT: item.yrsInIT,
                        yrsAsCustomerPM: item.yrsAsCustomerPM,
                        yrsAsCustomerProgM: item.yrsAsCustomerProgM,
                        primaryDomain: item.primaryDomain,
                        primaryDomainOther: item.primaryDomainOther,
                        primaryIndustry: item.primaryIndustry,
                        primaryIndustryOther: item.primaryIndustryOther,
                        isPMPCertified: item.isPMPCertified,
                        pmpCertExpiryDate: item.pmpCertExpiryDate,
                        isPGMPCertified: item.isPGMPCertified,
                        pgmpCertExpiryDate: item.pgmpCertExpiryDate,
                        isScrumCertified: item.isScrumCertified,
                        scrumCertExpiryDate: item.scrumCertExpiryDate,
                        biggestProjectTCV: item.biggestProjectTCV,
                        biggestTeamSizeManaged: item.biggestTeamSizeManaged,
                        avgTeamSizeManaged: item.avgTeamSizeManaged,
                        biggestBilledFTE: item.biggestBilledFTE,
                        avgBilledFTE: item.avgBilledFTE
                    });
                }
            });
        });
        promises.push(promise);
    }

    return q.all(promises).then(function(data){
        return res.json(data);
    });

});

...but it's still not returning anything. What am I doing wrong?


问:
reset the dropdown default value using ngOptions and selectpickerintable
Controller:-

```<code>var selecteduser = [];
$scope.dataList = [
{ id:1, fname: 'abc', lname: 'xyz' },
{ id:2, fname: 'xyz', lname: 'abc' },
{ id:3, fname: 'foo', lname: 'bar' }
];
$scope.addUser = function (user) {
   selecteduser.push(user);
$scope.selectedItem = '';
}
</code>```

HTML:-

```<code><select class="dropdown" ng-model="selectedItem"
ng-options =" data as data.fname +''+ data.lname for data in dataList"
ng-change="addUser(selectedItem)">
</select>'
</code>```

Here I reset the dropdown value after pushing the value in array. But it is not working $scope.selectedItem = '';. Anything I missed ? Please help me!

Thanks

答:
Change

```<code>ng-change="addUser(selectedItem)">
</code>```

In

```<code>ng-change="adduser(selectedItem)">
</code>```

Body:
Controller:-

var selecteduser = [];
$scope.dataList = [
{ id:1, fname: 'abc', lname: 'xyz' },
{ id:2, fname: 'xyz', lname: 'abc' },
{ id:3, fname: 'foo', lname: 'bar' }
];
$scope.addUser = function (user) {
   selecteduser.push(user);
$scope.selectedItem = '';
}

HTML:-

<select class="dropdown" ng-model="selectedItem"
ng-options =" data as data.fname +''+ data.lname for data in dataList"
ng-change="addUser(selectedItem)">
</select>'

Here I reset the dropdown value after pushing the value in array. But it is not working $scope.selectedItem = '';. Anything I missed ? Please help me!

Thanks

Body:
Change

ng-change="addUser(selectedItem)">

In

ng-change="adduser(selectedItem)">


问:
Scrapy yield utf-8
I am trying to rewrite an official Scrapy tutorial (http://doc.scrapy.org/en/latest/intro/tutorial.html)
code with russian site habrahabr.ru.

Here is my code:

```<code>import scrapy

class DmozSpider(scrapy.Spider):
    name = 'habr'

    allowed_domains = ['habrahabr.ru']

    start_urls = [
        'http://habrahabr.ru/interesting/'
    ]

    def parse(self, response):
        yield {'title': response.xpath('//title/text()').extract()[0]}
</code>```

it returns: {'title': u'\u0418\u043d\u0442\u0435\u0440\u0435\u0441\u043d\u044b\u0435 \u043f\u0443\u0431\u043b\u0438\u043a\u0430\u0446\u0438\u0438 / \u0425\u0430\u0431\u0440\u0430\u0445\u0430\u0431\u0440'}

when I try:

```<code> yield {'title': response.xpath('//title/text()').extract()[0].encode('utf-8')}
</code>```

returns:

```<code>{'title': '\xd0\x98\xd0\xbd\xd1\x82\xd0\xb5\xd1\x80\xd0\xb5\xd1\x81\xd0\xbd\xd1\x8b\xd0\xb5 \xd0\xbf\xd1\x83\xd0\xb1\xd0\xbb\xd0\xb8\xd0\xba\xd0\xb0\xd1\x86\xd0\xb8\xd0\xb8 / \xd0\xa5\xd0\xb0\xd0\xb1\xd1\x80\xd0\xb0\xd1\x85\xd0\xb0\xd0\xb1\xd1\x80'}
</code>```

How can I change this behavior?

答:
If I get you right you are confused because the value you got not looks like a cyrillic text. But actually everything is fine you get the correct value. The string just automatically encoded to unicode. To see readable/cyrillic value you can do that:

```<code>#Python - 2
title = u'\u0418\u043d\u0442\u0435\u0440\u0435\u0441\u043d\u044b\u0435 \u043f\u0443\u0431\u043b\u0438\u043a\u0430\u0446\u0438\u0438 / \u0425\u0430\u0431\u0440\u0430\u0445\u0430\u0431\u0440'
print(title.encode('utf-8'))

#Python - 3
title = u'\u0418\u043d\u0442\u0435\u0440\u0435\u0441\u043d\u044b\u0435 \u043f\u0443\u0431\u043b\u0438\u043a\u0430\u0446\u0438\u0438 / \u0425\u0430\u0431\u0440\u0430\u0445\u0430\u0431\u0440'
print(title)
</code>```

result would be the:

```<code>Интересные публикации / Хабрахабр
</code>```

Title: Scrapy yield utf-8

Body:
I am trying to rewrite an official Scrapy tutorial (http://doc.scrapy.org/en/latest/intro/tutorial.html)
code with russian site habrahabr.ru.

Here is my code:

import scrapy

class DmozSpider(scrapy.Spider):
    name = 'habr'

    allowed_domains = ['habrahabr.ru']

    start_urls = [
        'http://habrahabr.ru/interesting/'
    ]

    def parse(self, response):
        yield {'title': response.xpath('//title/text()').extract()[0]}

it returns: {'title': u'\u0418\u043d\u0442\u0435\u0440\u0435\u0441\u043d\u044b\u0435 \u043f\u0443\u0431\u043b\u0438\u043a\u0430\u0446\u0438\u0438 / \u0425\u0430\u0431\u0440\u0430\u0445\u0430\u0431\u0440'}

when I try:

 yield {'title': response.xpath('//title/text()').extract()[0].encode('utf-8')}

returns:

{'title': '\xd0\x98\xd0\xbd\xd1\x82\xd0\xb5\xd1\x80\xd0\xb5\xd1\x81\xd0\xbd\xd1\x8b\xd0\xb5 \xd0\xbf\xd1\x83\xd0\xb1\xd0\xbb\xd0\xb8\xd0\xba\xd0\xb0\xd1\x86\xd0\xb8\xd0\xb8 / \xd0\xa5\xd0\xb0\xd0\xb1\xd1\x80\xd0\xb0\xd1\x85\xd0\xb0\xd0\xb1\xd1\x80'}

How can I change this behavior?

Body:
If I get you right you are confused because the value you got not looks like a cyrillic text. But actually everything is fine you get the correct value. The string just automatically encoded to unicode. To see readable/cyrillic value you can do that:

#Python - 2
title = u'\u0418\u043d\u0442\u0435\u0440\u0435\u0441\u043d\u044b\u0435 \u043f\u0443\u0431\u043b\u0438\u043a\u0430\u0446\u0438\u0438 / \u0425\u0430\u0431\u0440\u0430\u0445\u0430\u0431\u0440'
print(title.encode('utf-8'))

#Python - 3
title = u'\u0418\u043d\u0442\u0435\u0440\u0435\u0441\u043d\u044b\u0435 \u043f\u0443\u0431\u043b\u0438\u043a\u0430\u0446\u0438\u0438 / \u0425\u0430\u0431\u0440\u0430\u0445\u0430\u0431\u0440'
print(title)

result would be the:

Интересные публикации / Хабрахабр


问:
Start an exe. via Windows Service
I'm currently working on a project to automatize my backup to run only under certain circumstances. Therefor I'm writing a Windows Service in C# using Visual Studios 2015. I already got my requirements set and now I can't get my Service to run sdclt.exe (the Microsoft Default Backup). I already searched for a solution but i only found people saying that Windows Services can't start .exe anymore. Does anyone here have an idea how it might still work?

Thank You

答: you can create BatchFile that Run sdclt.exe or use System.Thredin.Process to Run that exe. use verbs if require to run with administrator rights. </p>

Title: Start an exe. via Windows Service


问:
Creating a table in SQL with column of unique entries
I have the following table:

```<code>Create table [dbo].[Medewerker]
(
    [Id] int PRIMARY KEY IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) UNIQUE NOT NULL
)
</code>```

I'm trying to make it so that the bottom line makes it so that each entry in the "Gebruikersnaam" column is unique. Is what I did right? What do you call this type of feature?

答:
each entry in the "Gebruikersnaam" column is unique

Yes it's right. Essentially what you did is nothing but adding a UNIQUE CONSTRAINT to your column Gebruikersnaam.

Per comment, yes it's better to name your constraint explicitly than let DB engine assign a default name implicitly like

```<code>Create table [dbo].[Medewerker]
(
    [Id] int PRIMARY KEY IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) NOT NULL,
    CONSTRAINT idx_unique_Gebruikersnaam UNIQUE(Gebruikersnaam) --Here
)
</code>```

Body:
I have the following table:

Create table [dbo].[Medewerker]
(
    [Id] int PRIMARY KEY IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) UNIQUE NOT NULL
)

I'm trying to make it so that the bottom line makes it so that each entry in the "Gebruikersnaam" column is unique. Is what I did right? What do you call this type of feature?

Body:
each entry in the "Gebruikersnaam" column is unique

Yes it's right. Essentially what you did is nothing but adding a UNIQUE CONSTRAINT to your column Gebruikersnaam.

Per comment, yes it's better to name your constraint explicitly than let DB engine assign a default name implicitly like

Create table [dbo].[Medewerker]
(
    [Id] int PRIMARY KEY IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) NOT NULL,
    CONSTRAINT idx_unique_Gebruikersnaam UNIQUE(Gebruikersnaam) --Here
)


问:
Mesos unsets some environment variables
My mesos jobs run without the LANG environment variable set. I have verified that the slaves have the variable set, so the mesos job must be unsetting the variable, but I cannot figure out where this is done.

I can explicitly set the environment variable for each job, but I would like this to be set globally.

答:
Try using the agent flag --executor_environment_variables.

From the agent command line help:

JSON object representing the environment variables that should be
  passed to the executor, and thus subsequently task(s). By default this
  flag is none.

Users have to define executor environment explicitly.

Example:

mesos-slave --executor_environment_variables='{ "LANG": "C" }' [...]

Title: Mesos unsets some environment variables


问:
Slow pywinauto Import
When I import all most any module, it loads almost/seemingly instantly or at least fast enough to be unnoticeable.

However, there is an issue with PyWinAuto. When i try to import it, it takes a huge amount of time (~1min) which is highly annoying for the users.

I am wondering if there is anyway to be able to speed up the time it takes to load up the module.

答:
If you use backend='uia' it looks impossible, because import comtypes and loading UIAutomationCore.dll should take the most time and it's functionally required.

But if you need only default backend='win32' (i.e. if you create Application() object without backend parameter), you can run pip uninstall -y comtypes. Only Win32 backend will be available after that. But the import should work much faster.

More details about these 2 backends could be found in the Getting Started Guide.

Title: Slow pywinauto Import


问:
How to change the structure of JSON
I have a JSON like this

```<code>{"a":1,"b":2,"c":3}
</code>```

how can I convert its structure like this

```<code>[{
"option_id": "a",
"option_value": "1"
},
{
"option_id": "b",
"option_value": "2"
},
{
"option_id": "c",
"option_value": "3"
}]
</code>```

I tried JSON.stringify, result.push([i,data[i]]) etc but to no success so far

答:
If you are using ECMAScript 5.1 or newer (or a suitable polyfill) then the following will do what you have asked for</p>

```<code>let value = {"a":1,"b":2,"c":3};
let newValue = Object.keys(value).map(key => ({option_id:key,option_value:a[value]}));
</code>```

Title: How to change the structure of JSON

Body:
I have a JSON like this

{"a":1,"b":2,"c":3}

how can I convert its structure like this

[{
"option_id": "a",
"option_value": "1"
},
{
"option_id": "b",
"option_value": "2"
},
{
"option_id": "c",
"option_value": "3"
}]

I tried JSON.stringify, result.push([i,data[i]]) etc but to no success so far

Body:
If you are using ECMAScript 5.1 or newer (or a suitable polyfill) then the following will do what you have asked for

let value = {"a":1,"b":2,"c":3};
let newValue = Object.keys(value).map(key => ({option_id:key,option_value:a[value]}));


问:
Mongoose select,populate and save behaving differently on Mac and Windows
Here's what i did

```<code>static populateReferralLinks(){
    return Promise.coroutine(function*(){
       let companies = yield Company.find({},'billing referral current_referral_program')
                                        .populate('billing.user','emails name');

       for(let i = 0 ; i < length ; i++){
         companies[i].referral.is_created = true;
         companies[i].referral.referral_email = companies[i].billing.user.emails[0].email;
         companies[i] = yield companies[i].save();
       }
       return companies;
    }).apply(this)
        .catch((err) => {
            throw err;
        });
}
</code>```

I have a funciton in which i am selecting only 3 fields to go ahead with i.e billing,current_referral_program and referral.
And populating user using the reference stored in billing.user.
Now when i call this function then on line

companies[i].save();

The following command is shown in the terminal in windows

```<code>Mongoose: companies.update(
{ _id: ObjectId("58d12e1a588a96311075c45c") },
{ '$set':
   { billing:
      { configured: false,
        user: ObjectId("58d12e16588a96311075c45a") },
     referral:
     { is_created: true,
       referral_email: 'jadon.devesh98@gmail.com',
     },
     updatedAt: new Date("Wed, 22 Mar 2017 12:02:55 GMT")
   }
}
)
</code>```

But in Mac's terminal it shows this command

```<code>Mongoose: companies.update({ _id: ObjectId("58d12e1a588a96311075c45c") }) { '$set': { billing: { configured: false, user: ObjectId("58d12e16588a96311075c45a") }, current_limit: {}, current_usage: {},referral: { is_created: true, referral_email: 'jadon.devesh98@gmail.com'}}, '$unset': { updatedAt: 1 } }
</code>```

Now, I haven't mentioned current_limit and current_usage to be empty. it's executing fine on windows but on Mac it's setting current_limit and current_usage empty thus updating my document with empty objects on Mac but not on windows.

It should behave same way on both OS but it is not.

答:
Apparently this problem was there in Mongoose 4.5.8 and is resolved in the latest version i.e 4.9.1
Check it here</p>

Body:
Here's what i did

static populateReferralLinks(){
    return Promise.coroutine(function*(){
       let companies = yield Company.find({},'billing referral current_referral_program')
                                        .populate('billing.user','emails name');

       for(let i = 0 ; i < length ; i++){
         companies[i].referral.is_created = true;
         companies[i].referral.referral_email = companies[i].billing.user.emails[0].email;
         companies[i] = yield companies[i].save();
       }
       return companies;
    }).apply(this)
        .catch((err) => {
            throw err;
        });
}

I have a funciton in which i am selecting only 3 fields to go ahead with i.e billing,current_referral_program and referral.
And populating user using the reference stored in billing.user.
Now when i call this function then on line

companies[i].save();

The following command is shown in the terminal in windows

Mongoose: companies.update(
{ _id: ObjectId("58d12e1a588a96311075c45c") },
{ '$set':
   { billing:
      { configured: false,
        user: ObjectId("58d12e16588a96311075c45a") },
     referral:
     { is_created: true,
       referral_email: 'jadon.devesh98@gmail.com',
     },
     updatedAt: new Date("Wed, 22 Mar 2017 12:02:55 GMT")
   }
}
)

But in Mac's terminal it shows this command

Mongoose: companies.update({ _id: ObjectId("58d12e1a588a96311075c45c") }) { '$set': { billing: { configured: false, user: ObjectId("58d12e16588a96311075c45a") }, current_limit: {}, current_usage: {},referral: { is_created: true, referral_email: 'jadon.devesh98@gmail.com'}}, '$unset': { updatedAt: 1 } }

Now, I haven't mentioned current_limit and current_usage to be empty. it's executing fine on windows but on Mac it's setting current_limit and current_usage empty thus updating my document with empty objects on Mac but not on windows.

It should behave same way on both OS but it is not.


问:
Regext for matching a listing of items separated by "," or "and"
I want to match this: first, second, third and fourth section and get the different sections like this:

match 1: first

match 2: second

match 3: third

match 4: fourth

Also the string sections have to end with the word section. If it does not it should drop all matches.

How can i achieve this with regex? I have tried this so far:
https://regex101.com/r/Qwnh6m/3

(?P
(first|second|third|fourth)(?=(\ssection|\sog\s(first|second|third|fourth)\ssection|,\s(first|second|third|fourth))))

NB: It is important that the regex works on a string like this.

something else lalala and then first, second, third and fourth section something more.

答:
You can use this regex using lookaheads:

```<code>\b(first|second|third|fourth)(?=,|\h+(?:and|section)\b)(?=.*\hsection\b)
</code>```

RegEx Demo

RegEx Breakup:

\b(first|second|third|fourth) - Match 1 or more given words in the group

(?= - Start a lookahead

, - Containing comma

| - OR

\h+ - 1 or more horizontal white-spaces

(?: - start non-capturing group

and - containing word "and"

| - OR

section$ - word "section"

) - end non-capturing group

\b - word boundary

) - end lookahead

(?= - start second lookahead

.*section\b - containing word "section"

)- end second lookahead

Edit: This was the final regex after further fixes:
\b(first|second|third|fourth)(?=(?:\s*(?:,|and)\s*(?:first|second|third|fourth))*\s+section\b)

https://regex101.com/r/NXVwZl/21

Body:
You can use this regex using lookaheads:

\b(first|second|third|fourth)(?=,|\h+(?:and|section)\b)(?=.*\hsection\b)

RegEx Demo

RegEx Breakup:

\b(first|second|third|fourth) - Match 1 or more given words in the group

(?= - Start a lookahead

, - Containing comma

| - OR

\h+ - 1 or more horizontal white-spaces

(?: - start non-capturing group

and - containing word "and"

| - OR

section$ - word "section"

) - end non-capturing group

\b - word boundary

) - end lookahead

(?= - start second lookahead

.*section\b - containing word "section"

)- end second lookahead

Edit: This was the final regex after further fixes:
\b(first|second|third|fourth)(?=(?:\s*(?:,|and)\s*(?:first|second|third|fourth))*\s+section\b)

https://regex101.com/r/NXVwZl/21


答:
```<code>//with old syntax
q = {"a":1,"b":2,"c":3}
arr = []
for(i in q) {
  arr.push({'object_id': i, 'object_value': q[i] });
}
</code>```

Title: How to change the structure of JSON


问:
Boost Statechart vs. Meta State Machine
Apparently boost contains two separate libraries for state machines: Statechart and Meta State Machine (MSM). The taglines give very similar descriptions:

Boost.Statechart - Arbitrarily complex finite state machines can be implemented in easily readable and maintainable C++ code.

Meta State Machine - A very high-performance library for expressive UML2 finite state machines.

Do you know what are the key differences and what are considerations in choosing between the two?

答:
As Christophe has already mentioned, one of the key differences between the two libraries is runtime performance. While MSM probably offers the best you can get here, Statechart consciously trades memory and processor cycles towards better scalability.

With Boost.Statechart you can spread the layout (i.e. states, transitions) of your state machine over multiple translation units (cpp files) in ways you can't with MSM. This allows you to make the implementation of large FSMs more maintainable and get much faster compilation than with MSM.

Whether or not the performance overhead of Statechart compared to MSM will actually be significant for your application is often quite easy to answer when you ask yourself how many events your app will have to process per second.

Assuming a moderately complex FSM implemented with Boost.Statechart, here are a few ballpark numbers:

Most current PC hardware will easily cope with >100'000 events per second

Even very resource-constrained hardware will be able to process a few hundred events per second.

Regarding CPU load, if the number of events to process is much lower than these numbers, Boost.Statechart overhead compared to MSM will almost certainly not be noticeable. If the number is much higher, you're definitely better off with MSM.

More in-depth information on the performance/scalability tradeoffs can be found here:
http://www.boost.org/doc/libs/1_45_0/libs/statechart/doc/performance.html

Title: Boost Statechart vs. Meta State Machine


问:
How to listen for a WebView finishing loading a URL?
I have a WebView that is loading a page from the Internet. I want to show a ProgressBar until the loading is complete.

How do I listen for the completion of page loading of a WebView?

答:
Here's a novel method for detected when a URL has loaded by utilising Android's capability for JavaScript hooks. Using this pattern, we exploit JavaScript's knowledge of the document's state to generate a native method call within the Android runtime. These JavaScript-accessible calls can be made using the @JavaScriptInterface annotation.

This implementation requires that we call setJavaScriptEnabled(true) on the WebView's settings, so it might not be suitable depending on your application's requirements, e.g. security concerns.

src/io/github/cawfree/webviewcallback/MainActivity.java (Jelly Bean, API Level 16)

```<code>package io.github.cawfree.webviewcallback;

/**
 *  Created by Alex Thomas (@Cawfree), 30/03/2017.
 **/

import android.net.http.SslError;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

/** An Activity demonstrating how to introduce a callback mechanism into Android's WebView. */
public class MainActivity extends AppCompatActivity {

    /* Static Declarations. */
    private static final String HOOK_JS             = "Android";
    private static final String URL_TEST            = "http://www.zonal.co.uk/";
    private static final String URL_PREPARE_WEBVIEW = "";

    /* Member Variables. */
    private WebView mWebView = null;

    /** Create the Activity. */
    @Override protected final void onCreate(final Bundle pSavedInstanceState) {
        // Initialize the parent definition.
        super.onCreate(pSavedInstanceState);
        // Set the Content View.
        this.setContentView(R.layout.activity_main);
        // Fetch the WebView.
        this.mWebView = (WebView)this.findViewById(R.id.webView);
        // Enable JavaScript.
        this.getWebView().getSettings().setJavaScriptEnabled(true);
        // Define the custom WebClient. (Here I'm just suppressing security errors, since older Android devices struggle with TLS.)
        this.getWebView().setWebViewClient(new WebViewClient() { @Override     public final void onReceivedSslError(final WebView pWebView, final SslErrorHandler pSslErrorHandler, final SslError pSslError) { pSslErrorHandler.proceed(); } });
        // Define the WebView JavaScript hook.
        this.getWebView().addJavascriptInterface(this, MainActivity.HOOK_JS);
        // Make this initial call to prepare JavaScript execution.
        this.getWebView().loadUrl(MainActivity.URL_PREPARE_WEBVIEW);
    }

    /** When the Activity is Resumed. */
    @Override protected final void onPostResume() {
        // Handle as usual.
        super.onPostResume();
        // Load the URL as usual.
        this.getWebView().loadUrl(MainActivity.URL_TEST);
        // Use JavaScript to embed a hook to Android's MainActivity. (The onExportPageLoaded() function implements the callback, whilst we add some tests for the state of the WebPage so as to infer when to export the event.)
        this.getWebView().loadUrl("javascript:" + "function onExportPageLoaded() { " + MainActivity.HOOK_JS + ".onPageLoaded(); }" + "if(document.readyState === 'complete') { onExportPageLoaded(); } else { window.addEventListener('onload', function () { onExportPageLoaded(); }, false); }");
    }

    /** Javascript-accessible callback for declaring when a page has loaded. */
    @JavascriptInterface @SuppressWarnings("unused") public final void onPageLoaded() {
        // Display the Message.
        Toast.makeText(this, "Page has loaded!", Toast.LENGTH_SHORT).show();
    }

    /* Getters. */
    public final WebView getWebView() {
        return this.mWebView;
    }

}
</code>```

res/layout/activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<WebView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>
</code>```

Essentially, we're appending an additional JavaScript function that is used to test the state of the document. If it's loaded, we launch a custom onPageLoaded() event in Android's MainActivity; otherwise, we register an event listener that updates Android once the page is ready, using window.addEventListener('onload', ...);.

Since we're appending this script after the call to this.getWebView().loadURL("") has been made, it's probable that we don't need to 'listen' for the events at all, since we only get a chance to append the JavaScript hook by making a successive call to loadURL, once the page has already been loaded.

Body:
Here's a novel method for detected when a URL has loaded by utilising Android's capability for JavaScript hooks. Using this pattern, we exploit JavaScript's knowledge of the document's state to generate a native method call within the Android runtime. These JavaScript-accessible calls can be made using the @JavaScriptInterface annotation.

This implementation requires that we call setJavaScriptEnabled(true) on the WebView's settings, so it might not be suitable depending on your application's requirements, e.g. security concerns.

src/io/github/cawfree/webviewcallback/MainActivity.java (Jelly Bean, API Level 16)

package io.github.cawfree.webviewcallback;

/**
 *  Created by Alex Thomas (@Cawfree), 30/03/2017.
 **/

import android.net.http.SslError;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

/** An Activity demonstrating how to introduce a callback mechanism into Android's WebView. */
public class MainActivity extends AppCompatActivity {

    /* Static Declarations. */
    private static final String HOOK_JS             = "Android";
    private static final String URL_TEST            = "http://www.zonal.co.uk/";
    private static final String URL_PREPARE_WEBVIEW = "";

    /* Member Variables. */
    private WebView mWebView = null;

    /** Create the Activity. */
    @Override protected final void onCreate(final Bundle pSavedInstanceState) {
        // Initialize the parent definition.
        super.onCreate(pSavedInstanceState);
        // Set the Content View.
        this.setContentView(R.layout.activity_main);
        // Fetch the WebView.
        this.mWebView = (WebView)this.findViewById(R.id.webView);
        // Enable JavaScript.
        this.getWebView().getSettings().setJavaScriptEnabled(true);
        // Define the custom WebClient. (Here I'm just suppressing security errors, since older Android devices struggle with TLS.)
        this.getWebView().setWebViewClient(new WebViewClient() { @Override     public final void onReceivedSslError(final WebView pWebView, final SslErrorHandler pSslErrorHandler, final SslError pSslError) { pSslErrorHandler.proceed(); } });
        // Define the WebView JavaScript hook.
        this.getWebView().addJavascriptInterface(this, MainActivity.HOOK_JS);
        // Make this initial call to prepare JavaScript execution.
        this.getWebView().loadUrl(MainActivity.URL_PREPARE_WEBVIEW);
    }

    /** When the Activity is Resumed. */
    @Override protected final void onPostResume() {
        // Handle as usual.
        super.onPostResume();
        // Load the URL as usual.
        this.getWebView().loadUrl(MainActivity.URL_TEST);
        // Use JavaScript to embed a hook to Android's MainActivity. (The onExportPageLoaded() function implements the callback, whilst we add some tests for the state of the WebPage so as to infer when to export the event.)
        this.getWebView().loadUrl("javascript:" + "function onExportPageLoaded() { " + MainActivity.HOOK_JS + ".onPageLoaded(); }" + "if(document.readyState === 'complete') { onExportPageLoaded(); } else { window.addEventListener('onload', function () { onExportPageLoaded(); }, false); }");
    }

    /** Javascript-accessible callback for declaring when a page has loaded. */
    @JavascriptInterface @SuppressWarnings("unused") public final void onPageLoaded() {
        // Display the Message.
        Toast.makeText(this, "Page has loaded!", Toast.LENGTH_SHORT).show();
    }

    /* Getters. */
    public final WebView getWebView() {
        return this.mWebView;
    }

}

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<WebView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>

Essentially, we're appending an additional JavaScript function that is used to test the state of the document. If it's loaded, we launch a custom onPageLoaded() event in Android's MainActivity; otherwise, we register an event listener that updates Android once the page is ready, using window.addEventListener('onload', ...);.

Since we're appending this script after the call to this.getWebView().loadURL("") has been made, it's probable that we don't need to 'listen' for the events at all, since we only get a chance to append the JavaScript hook by making a successive call to loadURL, once the page has already been loaded.


问:
Tensorflow: how do I extract/export variable values at every iteration of training?
I have been playing around with some neural networks on Tensorflow and I wanted to make a visualization of the neural network's learning process.
To do so, I intend to extract the following variables into text/JSON/csv: pre-activation result before 1st layer, activation, bias and weight values for testing and training, each layer and for all time steps. I am looking for a generalizable solution so that I don't have to modify my source code (or at least not more than one or two lines) when applying visualization to future networks. Ideally I could run some function from another python program to read any python/TF code and extract the variables described above. So far I have considered the following solutions:
1) use tf.summary and the filewriter to save as a serialized protocol buffer, then find a way to go from protocol buffer --> JSON format. This unfortunately would not fit the bill as it requires me to modify too much inner code.
2) Perhaps using https://www.tensorflow.org/api_docs/python/tf/train/export_meta_graph
Although I am not sure how to implement given my TF foundations are not quite there yet
3) I have also found this solution:

```<code>W_val, b_val= sess.run([W, b])
np.savetxt("W1.csv", W_val, delimiter=",")
np.savetxt("b1.csv", b_val, delimiter=",")
</code>```

But the problem is that it only saves the final values of the weights and biases, whereas I am looking to save their values at all timesteps of training.

If anyone has any suggestions on how to tackle this problem or any guidance I would appreciate it.

Many thanks

答:
```<code>for step in range(num_train_steps):
    _, weight_values, bias_values = sess.run([your_train_op, weight, bias])
    # save weight_values and bias_values
</code>```

Body:
I have been playing around with some neural networks on Tensorflow and I wanted to make a visualization of the neural network's learning process.
To do so, I intend to extract the following variables into text/JSON/csv: pre-activation result before 1st layer, activation, bias and weight values for testing and training, each layer and for all time steps. I am looking for a generalizable solution so that I don't have to modify my source code (or at least not more than one or two lines) when applying visualization to future networks. Ideally I could run some function from another python program to read any python/TF code and extract the variables described above. So far I have considered the following solutions:
1) use tf.summary and the filewriter to save as a serialized protocol buffer, then find a way to go from protocol buffer --> JSON format. This unfortunately would not fit the bill as it requires me to modify too much inner code.
2) Perhaps using https://www.tensorflow.org/api_docs/python/tf/train/export_meta_graph
Although I am not sure how to implement given my TF foundations are not quite there yet
3) I have also found this solution:

W_val, b_val= sess.run([W, b])
np.savetxt("W1.csv", W_val, delimiter=",")
np.savetxt("b1.csv", b_val, delimiter=",")

But the problem is that it only saves the final values of the weights and biases, whereas I am looking to save their values at all timesteps of training.

If anyone has any suggestions on how to tackle this problem or any guidance I would appreciate it.

Many thanks