问:
How to get real time current location update as we walk
I want to discuss if there is possibility of getting real time current location update as we move, I tried with FusedLocationProviderClient to request for current location update every 2 minutes

What can we do to achieve this, implement detectActivity for walk and request current location update every 2 minutes or less in it?

or there is on location change listener thing in FusedLocationProviderClient? so that we can listen for if there is change in location and get latlng in real time and display in textview in application? the location change listener is available on GoogleMap object but isn't recommended to use now, am I right?

or should i stick to requestupdate of FusedLocationProviderClient?

Thanks beforehand

Also tell me if i move my phone from one room to another, will there be change in latlng?

答:
You can use this class that i created :

```<code>public class LocationFetcher implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
public GoogleApiClient googleApiClient;
Context context;
private LocationRequest locationRequest;

public LocationFetcher(Context context) {
    this.context = context;
    googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    locationRequest = new LocationRequest();

}

public void connectGps() {
    googleApiClient.connect();
}

public void requestLocationUpdate() {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
    } else {
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
     //Getting location every 3 seconds. You can change this.
            locationRequest.setInterval(3000);
            locationRequest.setFastestInterval(3000);

        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }
}

public boolean isConnected() {
    return googleApiClient.isConnected();
}

@Override
public void onLocationChanged(Location location) {
//You will get location updates here.
}

@Override
public void onConnected(@Nullable Bundle bundle) {

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);

    builder.setAlwaysShow(true);
    PendingResult result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());

    if (result != null) {
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult locationSettingsResult) {
                final Status status = locationSettingsResult.getStatus();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        requestLocationUpdate();
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            if (status.hasResolution()) {
                                status.startResolutionForResult((Activity) context, 1000);
                            }
                        } catch (IntentSender.SendIntentException e) {
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        break;
                }
            }
        });
    }

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    DialogPopup.getInstance().showLocationSettingsAlert(context);
}

public void removeLocationUpdates() {
   if (googleApiClient.isConnected()){
       LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
   }
}

public void disconnectGps() {
    googleApiClient.disconnect();
}

}
</code>```

In onStart of your activity call this :

```<code>LocationFetcher locationFetcher = new LocationFetcher(this);
locationFetcher.connectGps();
</code>```

And in onStop use this:

```<code>locationFetcher.disconnectGps();
</code>```

You will get the location updates in the onLocationChangedMethod of the class.

You have to add this dependency too:

```<code>compile 'com.google.android.gms:play-services-location:10.2.1'
</code>```

Hope this helps.

Body:
You can use this class that i created :

public class LocationFetcher implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
public GoogleApiClient googleApiClient;
Context context;
private LocationRequest locationRequest;

public LocationFetcher(Context context) {
    this.context = context;
    googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    locationRequest = new LocationRequest();

}

public void connectGps() {
    googleApiClient.connect();
}

public void requestLocationUpdate() {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
    } else {
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
     //Getting location every 3 seconds. You can change this.
            locationRequest.setInterval(3000);
            locationRequest.setFastestInterval(3000);

        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }
}

public boolean isConnected() {
    return googleApiClient.isConnected();
}

@Override
public void onLocationChanged(Location location) {
//You will get location updates here.
}

@Override
public void onConnected(@Nullable Bundle bundle) {

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);

    builder.setAlwaysShow(true);
    PendingResult result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());

    if (result != null) {
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult locationSettingsResult) {
                final Status status = locationSettingsResult.getStatus();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        requestLocationUpdate();
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            if (status.hasResolution()) {
                                status.startResolutionForResult((Activity) context, 1000);
                            }
                        } catch (IntentSender.SendIntentException e) {
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        break;
                }
            }
        });
    }

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    DialogPopup.getInstance().showLocationSettingsAlert(context);
}

public void removeLocationUpdates() {
   if (googleApiClient.isConnected()){
       LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
   }
}

public void disconnectGps() {
    googleApiClient.disconnect();
}

}

In onStart of your activity call this :

LocationFetcher locationFetcher = new LocationFetcher(this);
locationFetcher.connectGps();

And in onStop use this:

locationFetcher.disconnectGps();

You will get the location updates in the onLocationChangedMethod of the class.

You have to add this dependency too:

compile 'com.google.android.gms:play-services-location:10.2.1'

Hope this helps.


来源: stackexchange

问:
Why .remove() doesn't remove the element?
Here is my code:

```<code>$(document).ready(function(){
  $('a').bind('mouseenter', function() {
    var self = $(this);
    this.iid = setTimeout(function() {
      var tag_name = self.text(),
          top      = self.position().top + self.outerHeight(true),
          left     = self.position().left;
      $('body').append("<div class='tag_info'>Some explanations about "+tag_name+"</div>");
      $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
    }, 525);
  }).bind('mouseleave', function(){
    if(this.iid){
      clearTimeout(this.iid)
      remove($('.tag_info'));
    }
  });
});
</code>```

As you see in the fiddle I've provided, when your mouse leaves the tag, that black box still exists. Why? And how can I remove it?

答:
```<code>remove($('.tag_info'));
</code>```

<p>should be </p>

```<code>$('.tag_info').remove();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is my code:

$(document).ready(function(){
  $('a').bind('mouseenter', function() {
    var self = $(this);
    this.iid = setTimeout(function() {
      var tag_name = self.text(),
          top      = self.position().top + self.outerHeight(true),
          left     = self.position().left;
      $('body').append("
Some explanations about "+tag_name+"
");
      $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
    }, 525);
  }).bind('mouseleave', function(){
    if(this.iid){
      clearTimeout(this.iid)
      remove($('.tag_info'));
    }
  });
});

As you see in the fiddle I've provided, when your mouse leaves the tag, that black box still exists. Why? And how can I remove it?

Body:
remove($('.tag_info'));

should be

$('.tag_info').remove();


问:
Symfony, clear:cache "Failed to remove directory " on Vagrant
I've a problem when I clear the cache in a Vagrant VM. Here a part of the config file :

```<code>synced_folder:
    vflsf_19mkvk0x71hk:
        source: /var/www/vm/vmnginx
        target: /var/www
        sync_type: default
        smb:
            smb_host: ''
            smb_username: ''
            smb_password: ''
            mount_options:
                dir_mode: '0775'
                file_mode: '0664'
        rsync:
            args:
                - '--verbose'
                - '--archive'
                - '-z'
            exclude:
                - .vagrant/
                - .git/
                - vendor/
            auto: 'true'
        owner: vagrant
        group: www-data
</code>```

The error message tell me it can't be possible to remove a folder :

```<code>$ sfconsole cache:clear -vv
22:46:17 INFO      [php] User Deprecated: The "Symfony\Component\Console\Event\ConsoleExceptionEvent" class is deprecated since version 3.3 and will be removed in 4.0. Use the ConsoleErrorEvent instead. ["exception" => Symfony\Component\Debug\Exception\ContextErrorException {trace: { …} …}] []

  [Symfony\Component\Filesystem\Exception\IOException]
  Failed to remove directory "/var/www/formation/symfony-blog/var/cache/de~/translations": .

Exception trace:
 () at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Filesystem/Filesystem.php:176
 Symfony\Component\Filesystem\Filesystem->remove() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Filesystem/Filesystem.php:172
 Symfony\Component\Filesystem\Filesystem->remove() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php:70
 Symfony\Bundle\FrameworkBundle\Command\CacheClearCommand->execute() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:264
 Symfony\Component\Console\Command\Command->run() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:887
 Symfony\Component\Console\Application->doRunCommand() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:223
 Symfony\Component\Console\Application->doRun() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php:81
 Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:130
 Symfony\Component\Console\Application->run() at /var/www/formation/symfony-blog/bin/console:28

cache:clear [--no-warmup] [--no-optional-warmers] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command>
</code>```

I've add the "vagrant" user in the "www-data" group.

Folder :

```<code>$ ll var/cache/
total 16K
drwxrwxr-x 1 vagrant www-data 4,0K juil.  8 22:43 ./
drwxrwxr-x 1 vagrant www-data 4,0K juil.  7 16:01 ../
drwxrwxr-x 1 vagrant www-data 4,0K juil.  8 22:43 de~/
drwxrwxr-x 1 vagrant www-data 4,0K juil.  8 22:43 dev/
</code>```

Here the "real" folder outside the VM :

```<code>✔ /var/www/vm/vmnginx/formation/symfony-blog [master {origin/master}|✚ 9]
11:10 $ ll var/cache/
total 16K
drwxrwxr-x 4 fabrice fabrice 4,0K juil.  9 09:56 ./
drwxrwxr-x 5 fabrice fabrice 4,0K juil.  7 16:01 ../
drwxrwxr-x 3 fabrice fabrice 4,0K juil.  9 09:56 de~/
drwxrwxr-x 7 fabrice fabrice 4,0K juil.  9 09:56 dev/
</code>```

And, I can't change the permissions, even in with sudo. There's no error message, but nothing happend.

The "rm -fr var/cache" works.

Can u help me please.

Fabrice

答:
```<code>$ ll var/cache/de~
total 1,3M
drwxrwxr-x 1 vagrant www-data 4,0K juil.  9 09:56 ./
drwxrwxr-x 1 vagrant www-data 4,0K juil.  9 09:56 ../
-rwxrwxr-- 1 vagrant www-data 130K juil.  8 22:43 appDevDebugProjectContainerCompiler.log*
-rwxrwxr-- 1 vagrant www-data 459K juil.  9 09:56 appDevDebugProjectContainer.php*
-rwxrwxr-- 1 vagrant www-data  26K juil.  9 09:56 appDevDebugProjectContainer.php.meta*
-rwxrwxr-- 1 vagrant www-data 365K juil.  8 22:43 appDevDebugProjectContainer.xml*
-rwxrwxr-- 1 vagrant www-data 314K juil.  8 22:43 classes.php*
drwxrwxr-x 1 vagrant www-data 4,0K juil.  9 09:56 pools/
</code>```

and

```<code>$ ll var/cache/de~/pools/
total 8,0K
drwxrwxr-x 1 vagrant www-data 4,0K juil.  9 09:56 ./
drwxrwxr-x 1 vagrant www-data 4,0K juil.  9 09:56 ../
</code>```

Body:
I've a problem when I clear the cache in a Vagrant VM. Here a part of the config file :

synced_folder:
    vflsf_19mkvk0x71hk:
        source: /var/www/vm/vmnginx
        target: /var/www
        sync_type: default
        smb:
            smb_host: ''
            smb_username: ''
            smb_password: ''
            mount_options:
                dir_mode: '0775'
                file_mode: '0664'
        rsync:
            args:
                - '--verbose'
                - '--archive'
                - '-z'
            exclude:
                - .vagrant/
                - .git/
                - vendor/
            auto: 'true'
        owner: vagrant
        group: www-data

The error message tell me it can't be possible to remove a folder :

$ sfconsole cache:clear -vv
22:46:17 INFO      [php] User Deprecated: The "Symfony\Component\Console\Event\ConsoleExceptionEvent" class is deprecated since version 3.3 and will be removed in 4.0. Use the ConsoleErrorEvent instead. ["exception" => Symfony\Component\Debug\Exception\ContextErrorException {trace: { …} …}] []

  [Symfony\Component\Filesystem\Exception\IOException]
  Failed to remove directory "/var/www/formation/symfony-blog/var/cache/de~/translations": .

Exception trace:
 () at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Filesystem/Filesystem.php:176
 Symfony\Component\Filesystem\Filesystem->remove() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Filesystem/Filesystem.php:172
 Symfony\Component\Filesystem\Filesystem->remove() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php:70
 Symfony\Bundle\FrameworkBundle\Command\CacheClearCommand->execute() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:264
 Symfony\Component\Console\Command\Command->run() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:887
 Symfony\Component\Console\Application->doRunCommand() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:223
 Symfony\Component\Console\Application->doRun() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php:81
 Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:130
 Symfony\Component\Console\Application->run() at /var/www/formation/symfony-blog/bin/console:28

cache:clear [--no-warmup] [--no-optional-warmers] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command>

I've add the "vagrant" user in the "www-data" group.

Folder :

$ ll var/cache/
total 16K
drwxrwxr-x 1 vagrant www-data 4,0K juil.  8 22:43 ./
drwxrwxr-x 1 vagrant www-data 4,0K juil.  7 16:01 ../
drwxrwxr-x 1 vagrant www-data 4,0K juil.  8 22:43 de~/
drwxrwxr-x 1 vagrant www-data 4,0K juil.  8 22:43 dev/

Here the "real" folder outside the VM :

✔ /var/www/vm/vmnginx/formation/symfony-blog [master {origin/master}|✚ 9]
11:10 $ ll var/cache/
total 16K
drwxrwxr-x 4 fabrice fabrice 4,0K juil.  9 09:56 ./
drwxrwxr-x 5 fabrice fabrice 4,0K juil.  7 16:01 ../
drwxrwxr-x 3 fabrice fabrice 4,0K juil.  9 09:56 de~/
drwxrwxr-x 7 fabrice fabrice 4,0K juil.  9 09:56 dev/

And, I can't change the permissions, even in with sudo. There's no error message, but nothing happend.

The "rm -fr var/cache" works.

Can u help me please.

Fabrice

Body:
$ ll var/cache/de~
total 1,3M
drwxrwxr-x 1 vagrant www-data 4,0K juil.  9 09:56 ./
drwxrwxr-x 1 vagrant www-data 4,0K juil.  9 09:56 ../
-rwxrwxr-- 1 vagrant www-data 130K juil.  8 22:43 appDevDebugProjectContainerCompiler.log*
-rwxrwxr-- 1 vagrant www-data 459K juil.  9 09:56 appDevDebugProjectContainer.php*
-rwxrwxr-- 1 vagrant www-data  26K juil.  9 09:56 appDevDebugProjectContainer.php.meta*
-rwxrwxr-- 1 vagrant www-data 365K juil.  8 22:43 appDevDebugProjectContainer.xml*
-rwxrwxr-- 1 vagrant www-data 314K juil.  8 22:43 classes.php*
drwxrwxr-x 1 vagrant www-data 4,0K juil.  9 09:56 pools/

and

$ ll var/cache/de~/pools/
total 8,0K
drwxrwxr-x 1 vagrant www-data 4,0K juil.  9 09:56 ./
drwxrwxr-x 1 vagrant www-data 4,0K juil.  9 09:56 ../


问:
how to repeat result from math.random in javascript?
just to clarify my question, i need to generate a 2 digits numbers separately to make it set of 6 like this "12,45,24,63,64,1"</p>

```<code><html>
 <head>
    <title>lotto picker</title>

 </head>
 <body>

    <p> I can generate you a lotto numbers to bet right now!</p>
    <button id="generateButton">Generate!</button>

 <script type="text/javascript">
   document.getElementById("generateButton").onclick = function() {

                var msg = " ";
                var lottoNum = Math.floor((Math.random() * 64) + 1);

                alert(lottoNum);

            }
 </script>
 </body>

</html>
</code>```

答:
To generate 6 2-digit number you need to loop six times. Below is the program to generate 6 2-digit number

document.getElementById("generateButton").onclick = function() {
                var msg = " ";
                for(var i = 0 ;i < 6 ; ++i) {
                var lottoNum = Math.floor(Math.random() * 89) + 10;
                msg += lottoNum + ",";
                }
                msg = msg.slice(0, -1);
                alert(msg);
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
    <title>lotto picker</title>
</head>

<body>
    <p> I can generate you a lotto numbers to bet right now!</p>
    <button id="generateButton">Generate!</button>
</body></code>```

Body:
just to clarify my question, i need to generate a 2 digits numbers separately to make it set of 6 like this "12,45,24,63,64,1"

    <title>lotto picker</title>

 I can generate you a lotto numbers to bet right now!

    <button id="generateButton">Generate!</button>

Body:
To generate 6 2-digit number you need to loop six times. Below is the program to generate 6 2-digit number

document.getElementById("generateButton").onclick = function() {
                var msg = " ";
                for(var i = 0 ;i < 6 ; ++i) {
                var lottoNum = Math.floor(Math.random() * 89) + 10;
                msg += lottoNum + ",";
                }
                msg = msg.slice(0, -1);
                alert(msg);
            }

<html>
<head>
    <title>lotto picker</title>
</head>

<body>
    <p> I can generate you a lotto numbers to bet right now!</p>
    <button id="generateButton">Generate!</button>
</body>


问:
How can I test methods where I need a file?
I have the class "Password". In this class I have got two public methods, "setPassword" and "getPassword"
Here is the code:

```<code>public static void setPassword(String password) throws IOException {

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("password", password);

    FileWriter fileWriter = new FileWriter("data/password/" + User.getCurrentUser() + "_password.json");
    fileWriter.write(jsonObject.toJSONString());
    fileWriter.close();
}

public static String getPassword(String user) throws IOException, ParseException {

    File passwordFile = new File("data/password/" + user.toLowerCase() + "_password.json");

    return readPassword(passwordFile);
}

private static String readPassword(File passwordFile) throws IOException, ParseException {

    JSONParser jsonParser = new JSONParser();
    FileReader fileReader = new FileReader(passwordFile);
    Object object = jsonParser.parse(fileReader);

    JSONObject jsonObject = (JSONObject) object;
    fileReader.close();

    return (String) jsonObject.get("password");
}
</code>```

How can I test this methods with JUnit?
Should I use the Mockito-Framework?

答:
Instead of mocking things, I would redesign the class to make it testable:

pass the file name in a constructor

make the methods non static

In your test, you can now create a temporary file and use it for your tests.

Body:
I have the class "Password". In this class I have got two public methods, "setPassword" and "getPassword"
Here is the code:

public static void setPassword(String password) throws IOException {

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("password", password);

    FileWriter fileWriter = new FileWriter("data/password/" + User.getCurrentUser() + "_password.json");
    fileWriter.write(jsonObject.toJSONString());
    fileWriter.close();
}

public static String getPassword(String user) throws IOException, ParseException {

    File passwordFile = new File("data/password/" + user.toLowerCase() + "_password.json");

    return readPassword(passwordFile);
}

private static String readPassword(File passwordFile) throws IOException, ParseException {

    JSONParser jsonParser = new JSONParser();
    FileReader fileReader = new FileReader(passwordFile);
    Object object = jsonParser.parse(fileReader);

    JSONObject jsonObject = (JSONObject) object;
    fileReader.close();

    return (String) jsonObject.get("password");
}

How can I test this methods with JUnit?
Should I use the Mockito-Framework?


问:
Android Custom button with imageview and textview inside?
I'm looking to create a custom button. This button ideally would have an image on the left and a textview on the right. How would I accomplish this?</p>

答:
You can do this by using NoboButton

Simple and fast way to create android button with icon, radius, background

Library url  https://github.com/alex31n/NoboButton

Screenshot  https://raw.githubusercontent.com/alex31n/NoboButton/master/Assets/button_screenshot.jpg


问:
VueJs: Textarea input binding
I'm trying to figure out how to detect change of the value on the textarea from within the component.

For input we can simply use

```<code><input
  :value="value"
  @input="update($event.target.value)"
>
</code>```

However on textarea this won't work.

What I'm working with is the CKEditor component, which should update wysiwyg's content when model value of the parent component (attached to this child component) is updated.

My Editor component currently looks like this:

```<code><template>
    <div class="editor" :class="groupCss">
        <textarea :id="id" v-model="input"></textarea>
    </div>
</template>

<script>
    export default {
        props: {
            value: {
                type: String,
                default: ''
            },
            id: {
                type: String,
                required: false,
                default: 'editor'
            }
        },
        data() {
            return {
                input: this.$slots.default ? this.$slots.default[0].text : '',
                config: {
                    ...
                }
            }
        },
        watch: {
            input(value) {
                this.update(value);
            }
        },
        methods: {
            update(value) {
                CKEDITOR.instances[this.id].setData(value);
            },
            fire(value) {
                this.$emit('input', value);
            }
        },
        mounted () {
            CKEDITOR.replace(this.id, this.config);
            CKEDITOR.instances[this.id].setData(this.input);
            this.fire(this.input);
            CKEDITOR.instances[this.id].on('change', () => {
                this.fire(CKEDITOR.instances[this.id].getData());
            });
        },
        destroyed () {
            if (CKEDITOR.instances[this.id]) {
                CKEDITOR.instances[this.id].destroy()
            }
        }
    }
</script>
</code>```

and I include it within the parent component

```<code><html-editor
    v-model="fields.body"
    id="body"
></html-editor>
</code>```

however, whenever parent component's model value changes - it does not trigger the watcher - effectively not updating the editor's window.

I only need update() method to be called when parent component's model fields.body is updated.

Any pointer as to how could I approach it?

答:
That's a fair bit of code to decipher, but what I would do is break down the text area and the WYSIWYG HTML window into two distinct components and then have the parent sync the values, so:

TextArea Component:

```<code><template id="editor">
  <textarea :value="value" @input="$emit('input', $event.target.value)" rows="10" cols="50"></textarea>
</template>

/**
 *  Editor TextArea
 */
Vue.component('editor', {
  template: '#editor',
  props: {
    value: {
      default: '',
      type: String
    }
  }
});
</code>```

All I'm doing here is emitting the input back to the parent when it changes, I'm using input as the event name and value as the prop so I can use v-model on the editor. Now I just need a wysiwyg window to show the code:

WYSIWYG Window:

```<code>/**
 * WYSIWYG window
 */
Vue.component('wysiwyg', {
  template: `<div v-html="html"></div>`,
  props: {
    html: {
      default: '',
      type: String
    }
  }
});
</code>```

Nothing much going on there, it simply renders the HTML that is passed as a prop.

Finally I just need to sync the values between the components:

```<code><div id="app">
  <wysiwyg :html="value"></wysiwyg>
  <editor v-model="value"></editor>
</div>

new Vue({
  el: '#app',
  data: {
    value: '<b>Hello World</b>'
  }
})
</code>```

Now, when the editor changes it emits the event back to the parent, which updates value and in turn fires that change in the wysiwyg window. Here's the entire thing in action: https://jsfiddle.net/Lnpmbpcr/

Title: VueJs: Textarea input binding

Body:
I'm trying to figure out how to detect change of the value on the textarea from within the component.

For input we can simply use

<input
  :value="value"
  @input="update($event.target.value)"
>

However on textarea this won't work.

What I'm working with is the CKEditor component, which should update wysiwyg's content when model value of the parent component (attached to this child component) is updated.

My Editor component currently looks like this:

<template>

        <textarea :id="id" v-model="input"></textarea>

</template>

and I include it within the parent component

however, whenever parent component's model value changes - it does not trigger the watcher - effectively not updating the editor's window.

I only need update() method to be called when parent component's model fields.body is updated.

Any pointer as to how could I approach it?

Body:
That's a fair bit of code to decipher, but what I would do is break down the text area and the WYSIWYG HTML window into two distinct components and then have the parent sync the values, so:

TextArea Component:

<template id="editor">
  <textarea :value="value" @input="$emit('input', $event.target.value)" rows="10" cols="50"></textarea>
</template>

/**
 *  Editor TextArea
 */
Vue.component('editor', {
  template: '#editor',
  props: {
    value: {
      default: '',
      type: String
    }
  }
});

All I'm doing here is emitting the input back to the parent when it changes, I'm using input as the event name and value as the prop so I can use v-model on the editor. Now I just need a wysiwyg window to show the code:

WYSIWYG Window:

/**
 * WYSIWYG window
 */
Vue.component('wysiwyg', {
  template: `<div v-html="html"></div>`,
  props: {
    html: {
      default: '',
      type: String
    }
  }
});

Nothing much going on there, it simply renders the HTML that is passed as a prop.

Finally I just need to sync the values between the components:

<div id="app">
  <wysiwyg :html="value"></wysiwyg>
  <editor v-model="value"></editor>
</div>

new Vue({
  el: '#app',
  data: {
    value: '<b>Hello World</b>'
  }
})

Now, when the editor changes it emits the event back to the parent, which updates value and in turn fires that change in the wysiwyg window. Here's the entire thing in action: https://jsfiddle.net/Lnpmbpcr/


问:
Why color changes after redrawing again on canvas using javascript?
Here a sample of code that product the effect on color.

The question is "why rectangles (rect 1 and rect 2) are not the same color ?

```<code>    <!DOCTYPE html>
    <html>
    <body>
    <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>

    <script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");

    ctx.strokeRect(5, 5, 25, 15); //rect 1

    ctx.strokeRect(55, 5, 25, 15); // rect 2
    ctx.strokeRect(55, 5, 25, 15); // rect 2 again
    </script>
    </body>
    </html>
</code>```

答:
The problem here is the line width. If you change it to 2, you get the same rectangles, but without the opacity.

```<code>ctx.lineWidth = 2;

ctx.strokeRect(5, 5, 24, 14); //rect 1
ctx.strokeRect(55, 5, 24, 14); // rect 2
ctx.strokeRect(55, 5, 24, 14); // rect 2 again
</code>```

I assume that for some reason, the browser uses a stroke that is below 1 pixel at the point on the line and to compensate for that, it reduces the opacity of the stroke.

Example with line width of 2:
https://jsfiddle.net/2buo5cfw/4/

Body:
Here a sample of code that product the effect on color.

The question is "why rectangles (rect 1 and rect 2) are not the same color ?

    <!DOCTYPE html>

    <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>

Body:
The problem here is the line width. If you change it to 2, you get the same rectangles, but without the opacity.

ctx.lineWidth = 2;

ctx.strokeRect(5, 5, 24, 14); //rect 1
ctx.strokeRect(55, 5, 24, 14); // rect 2
ctx.strokeRect(55, 5, 24, 14); // rect 2 again

I assume that for some reason, the browser uses a stroke that is below 1 pixel at the point on the line and to compensate for that, it reduces the opacity of the stroke.

Example with line width of 2:
https://jsfiddle.net/2buo5cfw/4/


问:
View doesn't return anything in Laravel
I just started to learn the laravel framework and have a strange situation here.

First of all in my web.php I have code like:

```<code><?php
Route::get('/', function () {
    return view('welcome');
});

Route::get('users', ['uses' => 'UsersController@index']);
</code>```

In my UsersController.php file I have code like:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function index(){
        return view('users.index');
    }
}
</code>```

I have a file named index.blade.php in directory views/users that has the same content as the default welcome.blade.php. But when I try to return view('users.index'); there is no result (no error, or text) but when I try to return view('welcome'); it works just fine.

The directory and the file truly exists.
I'm using Macbook Pro.

welcome.blade.php and the /users/index.blade.php content (default welcome page):

```<code><!doctype html>
<html lang="{{ config('app.locale') }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Raleway', sans-serif;
                font-weight: 100;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 12px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @if (Auth::check())
                        <a href="{{ url('/home') }}">Home</a>
                    @else
                        <a href="{{ url('/login') }}">Login</a>
                        <a href="{{ url('/register') }}">Register</a>
                    @endif
                </div>
            @endif

            <div class="content">
                <div class="title m-b-md">
                    Laravel
                </div>

                <div class="links">
                    <a href="https://laravel.com/docs">Documentation</a>
                    <a href="https://laracasts.com">Laracasts</a>
                    <a href="https://laravel-news.com">News</a>
                    <a href="https://forge.laravel.com">Forge</a>
                    <a href="https://github.com/laravel/laravel">GitHub</a>
                </div>
            </div>
        </div>
    </body>
</html>
</code>```

答:
You Need To Give permission of Storage directory to 777
Open the terminal and visit to laravel directory and change the permission chmod 777 storage</p>

Title: View doesn't return anything in Laravel

Body:
I just started to learn the laravel framework and have a strange situation here.

First of all in my web.php I have code like:

<?php
Route::get('/', function () {
    return view('welcome');
});

Route::get('users', ['uses' => 'UsersController@index']);

In my UsersController.php file I have code like:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function index(){
        return view('users.index');
    }
}

I have a file named index.blade.php in directory views/users that has the same content as the default welcome.blade.php. But when I try to return view('users.index'); there is no result (no error, or text) but when I try to return view('welcome'); it works just fine.

The directory and the file truly exists.
I'm using Macbook Pro.

welcome.blade.php and the /users/index.blade.php content (default welcome page):

<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">

            @if (Route::has('login'))

                    @if (Auth::check())
                        Home
                    @else
                        Login
                        Register
                    @endif

            @endif

                    Laravel

                    Documentation
                    Laracasts
                    News
                    Forge
                    GitHub


问:
Trying to find strings from a huge file and replace the result with another string
Below is my code -

```<code>import tarfile
import os
import sys
import re

script, bak = sys.argv
bakfile = str(bak)
currentwd = os.path.dirname(os.path.realpath(__file__))
file_to_work = tarfile.open(name=currentwd+"/"+bakfile, mode="r")
file_to_work.extractall()

currentwd = os.path.dirname(os.path.realpath(__file__))
with open(currentwd+"/onedb.xml", "r") as file:
    f = file.read()
    words = re.findall(r'{ssha}_\w*?=', f)
    re.sub(words,r'string_to_replace',f)
</code>```

I used tarfile module and extracted a gzfile, from the extracted files, picked onedb.xml. Used regex to find the strings and that was successful.

Now when I try to replace searched strings using re.sub, I get the below error.

```<code>Traceback (most recent call last):
  File "preset.py", line 16, in <module>
    re.sub(words,r'string_to_replace',f)
  File "/usr/lib/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/lib/python2.7/re.py", line 232, in _compile
    p = _cache.get(cachekey)
TypeError: unhashable type: 'list'
</code>```

答:
Use all in one Expression:</p>

```<code>re.sub(r'{ssha}_\w*?=', r'string_to_replace', f)
</code>```

Body:
Below is my code -

import tarfile
import os
import sys
import re

script, bak = sys.argv
bakfile = str(bak)
currentwd = os.path.dirname(os.path.realpath(__file__))
file_to_work = tarfile.open(name=currentwd+"/"+bakfile, mode="r")
file_to_work.extractall()

currentwd = os.path.dirname(os.path.realpath(__file__))
with open(currentwd+"/onedb.xml", "r") as file:
    f = file.read()
    words = re.findall(r'{ssha}_\w*?=', f)
    re.sub(words,r'string_to_replace',f)

I used tarfile module and extracted a gzfile, from the extracted files, picked onedb.xml. Used regex to find the strings and that was successful.

Now when I try to replace searched strings using re.sub, I get the below error.

Traceback (most recent call last):
  File "preset.py", line 16, in <module>
    re.sub(words,r'string_to_replace',f)
  File "/usr/lib/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/lib/python2.7/re.py", line 232, in _compile
    p = _cache.get(cachekey)
TypeError: unhashable type: 'list'

Body:
Use all in one Expression:

re.sub(r'{ssha}_\w*?=', r'string_to_replace', f)


问:
Python selenium is_displayed method
I want to be able to reach the else statement and not get an exceptions when the element is not displayed.

for example:

```<code> if driver.find_element_by_xpath("/html/body/main/div/article[2]/div[4]/header/div[2]/div/div[3]/a[4]").is_displayed():
            print("yeah found it")
        else:
            print("not found")
</code>```

答:
I ran into the same issue and this Q&A block was the game changer. I tweaked the given code by Saifur too, to match my needs, which I believe similar to this question's request:

```<code>elementlist = []
found = False
while not found:
    try:
        element_ = browser.find_element_by_xpath("//*[@class='class' and (contains(text(),'Optional-text-contain'))]")
        if element_.is_displayed():
            value = element_.find_element_by_css_selector("*")
            elementlist.append(value.text)
            print("Element: " + value.text)
            found = True
    except NoSuchElementException:
        elementlist.append("N/A")
        print("Element: N/A")
        found = True
</code>```

This code looks for an alternating element within the page (sometimes exists, sometimes doesn't). If it exists, it gives its' value. If not - it continues normally while appending the list a "NaN" style value, just to match axis for later DFing

Again, Saifur delivered enormous assistance in this issue. Thank you user3691239 for asking this question, and mentioning it worked for you after a lil' tweak.

Title: Python selenium is_displayed method

Body:
I want to be able to reach the else statement and not get an exceptions when the element is not displayed.

for example:

 if driver.find_element_by_xpath("/html/body/main/div/article[2]/div[4]/header/div[2]/div/div[3]/a[4]").is_displayed():
            print("yeah found it")
        else:
            print("not found")

Body:
I ran into the same issue and this Q&A block was the game changer. I tweaked the given code by Saifur too, to match my needs, which I believe similar to this question's request:

elementlist = []
found = False
while not found:
    try:
        element_ = browser.find_element_by_xpath("//*[@class='class' and (contains(text(),'Optional-text-contain'))]")
        if element_.is_displayed():
            value = element_.find_element_by_css_selector("*")
            elementlist.append(value.text)
            print("Element: " + value.text)
            found = True
    except NoSuchElementException:
        elementlist.append("N/A")
        print("Element: N/A")
        found = True

This code looks for an alternating element within the page (sometimes exists, sometimes doesn't). If it exists, it gives its' value. If not - it continues normally while appending the list a "NaN" style value, just to match axis for later DFing

Again, Saifur delivered enormous assistance in this issue. Thank you user3691239 for asking this question, and mentioning it worked for you after a lil' tweak.


问:
cakephp 2.X Connection timed out on redirect on a live server
I have a "register" page that accepts the username, password and confirm password data from the user. on my local machine it just redirects just fine. I think the problem is on php's max execution time but i've talked with my hosting's support and was told that the max execution time of the hosting company is not subject to be changed.

Here is my code. I don't think there is any problem with my code because it works fine with my local machine.

```<code>public function register($role = null){
    $this->reg_status();
    if($this->Auth->user()){
        return $this->redirect(array('action' => 'dashboard'));
    }

    if ($this->request->is('post')) {

        $this->User->create();
        $existing = $this->User->find('first', array(
        'conditions' => array('email' => $this->request->data['User']['email'])
        ));
        if($existing){
            $this->Session->setFlash(__('Email is already used.'), 'default', array('class' => 'alert alert-danger'));
        } else{
            if($this->request->data['User']['password']==$this->request->data['User']['conf_password']){

                if($role){
                    $role = ($role == 'as_adviser') ? 'adviser' : 'client';
                    $this->request->data['User']['role'] = $role;
                }
                if ($this->User->save($this->request->data)) {
                    $id = $this->User->getLastInsertId();
                    $this->sendMail($this->request->data['User']['email'], $id, 'verify');
                    return $this->redirect(array('action' => 'confirm_email', $id, urlencode(base64_encode($this->request->data['User']['email']))));
                } else {
                    $this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
                }
            } else{
                $this->Session->setFlash(__("Password did not match."), 'default', array('class' => 'alert alert-danger'));
            }
        }
    }

    $this->set('role', $role);
}
</code>```

this is the error i am having on the live server.

i am currently out of clue because even if i turned "on" the debug on cakephp's config/core the error still seems vague.

edit
had to change Email config smtp settings. made sure they were correct and the error disappeared.

答:
```<code>$this->sendMail($this->request->data['User']['email'], $id, 'verify');
</code>```

This line problem comment this line & check.

Body:
I have a "register" page that accepts the username, password and confirm password data from the user. on my local machine it just redirects just fine. I think the problem is on php's max execution time but i've talked with my hosting's support and was told that the max execution time of the hosting company is not subject to be changed.

Here is my code. I don't think there is any problem with my code because it works fine with my local machine.

public function register($role = null){
    $this->reg_status();
    if($this->Auth->user()){
        return $this->redirect(array('action' => 'dashboard'));
    }

    if ($this->request->is('post')) {

        $this->User->create();
        $existing = $this->User->find('first', array(
        'conditions' => array('email' => $this->request->data['User']['email'])
        ));
        if($existing){
            $this->Session->setFlash(__('Email is already used.'), 'default', array('class' => 'alert alert-danger'));
        } else{
            if($this->request->data['User']['password']==$this->request->data['User']['conf_password']){

                if($role){
                    $role = ($role == 'as_adviser') ? 'adviser' : 'client';
                    $this->request->data['User']['role'] = $role;
                }
                if ($this->User->save($this->request->data)) {
                    $id = $this->User->getLastInsertId();
                    $this->sendMail($this->request->data['User']['email'], $id, 'verify');
                    return $this->redirect(array('action' => 'confirm_email', $id, urlencode(base64_encode($this->request->data['User']['email']))));
                } else {
                    $this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
                }
            } else{
                $this->Session->setFlash(__("Password did not match."), 'default', array('class' => 'alert alert-danger'));
            }
        }
    }

    $this->set('role', $role);
}

this is the error i am having on the live server.

i am currently out of clue because even if i turned "on" the debug on cakephp's config/core the error still seems vague.

edit
had to change Email config smtp settings. made sure they were correct and the error disappeared.

Body:
$this->sendMail($this->request->data['User']['email'], $id, 'verify');

This line problem comment this line & check.


问:
How can I brew link a specific version?
I have a few kegs of the same package in /usr/local/Cellar/libfoo like /usr/local/Cellar/libfoo/1.0.1, /usr/local/Cellar/libfoo/HEAD and /usr/local/Cellar/libfoo/mycopy

How can I brew link to a specific version?

答:
if @simon's answer is not working in some of the mac's please follow the below process.

If you have already installed swiftgen using the following commands:

$ brew update
$ brew install swiftgen

then follow the steps below in order to run swiftgen with older version.

Step 1: brew uninstall swiftgen
Step 2: Navigate to: https://github.com/SwiftGen/SwiftGen/releases
and download the swiftgen with version: swiftgen-4.2.0.zip.

Unzip the package in any of the directories.

Step 3:
Execute the following in a terminal:

```<code>$ mkdir -p ~/dependencies/swiftgen
$ cp -R ~/<your_directory_name>/swiftgen-4.2.0/ ~/dependencies/swiftgen
$ cd /usr/local/bin
$ ln -s ~/dependencies/swiftgen/bin/swiftgen swiftgen
$ mkdir ~/Library/Application\ Support/SwiftGen
$ ln -s ~/dependencies/swiftgen/templates/ ~/Library/Application\ Support/SwiftGen/

$ swiftgen --version
</code>```

You should get: SwiftGen v0.0 (Stencil v0.8.0, StencilSwiftKit v1.0.0, SwiftGenKit v1.0.1)

Title: How can I brew link a specific version?

Body:
if @simon's answer is not working in some of the mac's please follow the below process.

If you have already installed swiftgen using the following commands:

$ brew update
$ brew install swiftgen

then follow the steps below in order to run swiftgen with older version.

Step 1: brew uninstall swiftgen
Step 2: Navigate to: https://github.com/SwiftGen/SwiftGen/releases
and download the swiftgen with version: swiftgen-4.2.0.zip.

Unzip the package in any of the directories.

Step 3:
Execute the following in a terminal:

$ mkdir -p ~/dependencies/swiftgen
$ cp -R ~/<your_directory_name>/swiftgen-4.2.0/ ~/dependencies/swiftgen
$ cd /usr/local/bin
$ ln -s ~/dependencies/swiftgen/bin/swiftgen swiftgen
$ mkdir ~/Library/Application\ Support/SwiftGen
$ ln -s ~/dependencies/swiftgen/templates/ ~/Library/Application\ Support/SwiftGen/

$ swiftgen --version

You should get: SwiftGen v0.0 (Stencil v0.8.0, StencilSwiftKit v1.0.0, SwiftGenKit v1.0.1)


问:
Unable to capture city, and country values from Facebook iOS SDK in Swift
I am currently using the Facebook iOS SDK to capture email, first, and last name successfully in my app.  However, for some reason, I am having difficulty capturing the location information such as city, and country for the user.

Here is my relevant code:

```<code>override func viewDidLoad() {

        super.viewDidLoad()
        fbLoginButton.delegate = self
        fbLoginButton.readPermissions = ["email", "public_profile", "user_location"]
}

extension RegisterViewController: FBSDKLoginButtonDelegate {

    func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
        print("Did log out of facebook")
    }

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
        if error != nil {
            print(error)
            return
        }

        print("Successfully logged in with facebook...")
        FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, first_name, last_name, email, location{location}"]).start { (connection, result, err) in

            if err != nil {
                print("Failed to start graph request:", err)
                return
            }

            print(result)

            let fbDetails = result as! NSDictionary
            let location : NSDictionary! = fbDetails.value(forKey: "location") as! NSDictionary //code crashes here
            let locationContents : NSDictionary! = location.value(forKey: "location") as! NSDictionary
            let city: String! = locationContents.value(forKey: "city") as? String
            let state: String! = locationContents.value(forKey: "state") as? String
            let country: String! = locationContents.value(forKey: "country") as? String

            print(fbDetails)
            print("city:", city)
            print("state:", state)
            print("country:", country)

        }
    }
}
</code>```

When I run the code, in my console, I see the output for email, first_name, last_name, id, name, but nothing for location, and my app crashes with:

```<code>fatal error: unexpectedly found nil while unwrapping an Optional value
</code>```

when it reaches the line:

```<code>let location : NSDictionary! = fbDetails.value(forKey: "location") as! NSDictionary
</code>```

Can anyone see what it is I'm doing wrong?

答:
You need to add 'user_location' to your read_permission.

```<code>fbLoginButton.readPermissions = ["email", "public_profile", "user_location"]
</code>```

Remember to verify this permission in your fb application.(user_location is not default allowed permissions)

Body:
I am currently using the Facebook iOS SDK to capture email, first, and last name successfully in my app.  However, for some reason, I am having difficulty capturing the location information such as city, and country for the user.

Here is my relevant code:

override func viewDidLoad() {

        super.viewDidLoad()
        fbLoginButton.delegate = self
        fbLoginButton.readPermissions = ["email", "public_profile", "user_location"]
}

extension RegisterViewController: FBSDKLoginButtonDelegate {

    func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
        print("Did log out of facebook")
    }

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
        if error != nil {
            print(error)
            return
        }

        print("Successfully logged in with facebook...")
        FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, first_name, last_name, email, location{location}"]).start { (connection, result, err) in

            if err != nil {
                print("Failed to start graph request:", err)
                return
            }

            print(result)

            let fbDetails = result as! NSDictionary
            let location : NSDictionary! = fbDetails.value(forKey: "location") as! NSDictionary //code crashes here
            let locationContents : NSDictionary! = location.value(forKey: "location") as! NSDictionary
            let city: String! = locationContents.value(forKey: "city") as? String
            let state: String! = locationContents.value(forKey: "state") as? String
            let country: String! = locationContents.value(forKey: "country") as? String

            print(fbDetails)
            print("city:", city)
            print("state:", state)
            print("country:", country)

        }
    }
}

When I run the code, in my console, I see the output for email, first_name, last_name, id, name, but nothing for location, and my app crashes with:

fatal error: unexpectedly found nil while unwrapping an Optional value

when it reaches the line:

let location : NSDictionary! = fbDetails.value(forKey: "location") as! NSDictionary

Can anyone see what it is I'm doing wrong?

Body:
You need to add 'user_location' to your read_permission.

fbLoginButton.readPermissions = ["email", "public_profile", "user_location"]

Remember to verify this permission in your fb application.(user_location is not default allowed permissions)


问:
What are zeromq use cases?
Could you give some examples of zeromq?</p>

答: Please see the ZeroMQ blog -- they regularly post usage stories about different deployments, language bindings, etc.

ContentLicense: CC BY-SA 4.0

Title: What are zeromq use cases?

Body: Could you give some examples of zeromq?


答:
in jQuery selector define in first.</p>

```<code>$('.tag_info').remove();
</code>```

Title: Why .remove() doesn't remove the element?

Body:
Here is my code:

$(document).ready(function(){
  $('a').bind('mouseenter', function() {
    var self = $(this);
    this.iid = setTimeout(function() {
      var tag_name = self.text(),
          top      = self.position().top + self.outerHeight(true),
          left     = self.position().left;
      $('body').append("
Some explanations about "+tag_name+"
");
      $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
    }, 525);
  }).bind('mouseleave', function(){
    if(this.iid){
      clearTimeout(this.iid)
      remove($('.tag_info'));
    }
  });
});

As you see in the fiddle I've provided, when your mouse leaves the tag, that black box still exists. Why? And how can I remove it?

Body:
in jQuery selector define in first.

$('.tag_info').remove();


问:
ASP.NET Identity
I'm currently building a new ASP.NET MVC 5 project which I want to release around September. I need to choose a membership system, but I'm currently quite confused about which direction should I take. The current SimpleMembership works well, but will apparently be incompatible with the upcoming ASP.NET Identity. ASP.NET Identity on the other hand is absolutely new with zero documentation and can change anytime. Finally it seems that string based IDs are used here, which seems like a very unnecessary overhead compared to integer based IDs, which SimpleMembership supports. Is there a good, future proof way I can choose?</p>

答: I believe ASP.NET is quite good framework and provide almost all required functionality for an applications. It also provide feasibility to choose type of Id column as per your choice. I created basic a wrapper over ASP.NET identity and published a nuget, so that it would be easily use. You can take a look on code at github</p>

Title: ASP.NET Identity


问:
Can you specify a "data-target" for Bootstrap which refers to a sibling DOM element without using an ID?
I am dynamically adding Collapsable elements to a page.  Bootstrap uses the "data-target" attribute to specify which element the collapse toggle applies to.

From the docs:

```<code>The data-target attribute accepts a css selector
</code>```

Is there a way to write a selector which specifies the next sibling of the parent element?  All of the examples from the docs seem to use selections by ID.

Specifically the HTML looks like:

```<code><div class="accordion-group">
<div class="accordion-heading">
  <a class="accordion-toggle" data-toggle="collapse" data-target="#collapseOne">
    Generated Title
  </a>
</div>
<div id="collapseOne" class="accordion-body collapse in">
  <div class="accordion-inner">
    Generated Content... this is big and sometimes needs collapsing
  </div>
</div>
</div>
</code>```

I would like to write something like (pseudo code using jquery syntax illegally):

```<code><a class="accordion-toggle" data-toggle="collapse" data-target="$(this).parent().next()">
</code>```

But I am starting to suspect this may not be possible with CSS selectors.

Right now as a workaround I am generating a new ID (an incrementing number appended to a string) when I create the element.

Is there a nicer approach using a selector?  Should I be using some post-creation javascript  to set the data-target attribute? Is generating IDs for dynamic content the standard approach?

答:
No javascript solution or the solution depends on bootstrap's JS already in use, just exploiting the DOM structure-

See the data-target=""...

A hint to avoid bulky solutions and need no ID or extra JS, trick using markup placement-

```<code><button data-toggle="collapse" data-target=".dropdown-toggle:hover + .more-menu" type="button" class="btn btn-primary dropdown-toggle" >
  Show More Menu +
</button>
<div class="collapse more-menu">More menu here...</div>
</code>```

This CSS selection structure will select the desired DOM .dropdown-toggle:hover + .more-menu and there we can apply our desired CSS.
There are more ways to exploit what we have. :hover or :active or so many other ways.

Body:
I am dynamically adding Collapsable elements to a page.  Bootstrap uses the "data-target" attribute to specify which element the collapse toggle applies to.

From the docs:

The data-target attribute accepts a css selector

Is there a way to write a selector which specifies the next sibling of the parent element?  All of the examples from the docs seem to use selections by ID.

Specifically the HTML looks like:

    Generated Title

    Generated Content... this is big and sometimes needs collapsing

I would like to write something like (pseudo code using jquery syntax illegally):

But I am starting to suspect this may not be possible with CSS selectors.

Right now as a workaround I am generating a new ID (an incrementing number appended to a string) when I create the element.

Is there a nicer approach using a selector?  Should I be using some post-creation javascript  to set the data-target attribute? Is generating IDs for dynamic content the standard approach?

Body:
No javascript solution or the solution depends on bootstrap's JS already in use, just exploiting the DOM structure-

See the data-target=""...

A hint to avoid bulky solutions and need no ID or extra JS, trick using markup placement-

<button data-toggle="collapse" data-target=".dropdown-toggle:hover + .more-menu" type="button" class="btn btn-primary dropdown-toggle" >
  Show More Menu +
</button>
<div class="collapse more-menu">More menu here...</div>

This CSS selection structure will select the desired DOM .dropdown-toggle:hover + .more-menu and there we can apply our desired CSS.
There are more ways to exploit what we have. :hover or :active or so many other ways.


问:
I have a Objective C function that takes any type of object by reference. But when i pass a NSMutableArray My function does not recognise It
I have a function  That takes by reference any kind of object
-(BOOL)RemoteCall:(id**)DataClass;
in the implementation i use [*DataClass isMemberOfClass:[NSMutableArray class] to find out the type of the object. The problem is it does not work with NSMUtableArrays Does anybody have a solution to this problem ? Here is the relevant code:

Implementation:

```<code>-(BOOL)RemoteCall:(id**)DataClass
{
    if([*DataClass isMemberOfClass:[NSMutableArray class] ] == YES)
    {
            NSMutableArray * SW =(NSMutableArray *)*DataClass;
                       //do something with SW
            DataClass= (id**)SW;
                        return TRUE;
    }
}
</code>```

Any help and I mean anything at all will be appreciated, I'm stuck.

```<code>Method Call:
NSMutableArray * channelArray = [[NSMutableArray alloc]init]
Services * serv = [[Services alloc] init];
return [serv RemoteCall:&channelArray];
</code>```

答:
As Eiko said before, i'd use just id and not double pointers to ID.

I'm also pretty sure that isMemberOfClass is your Problem. isMember does not check for inheritance, so you're only asking for Top level Classes. isKindOfClass is probably the better choice, as there is no guarantee that Apple doesn't use an internal subclass of NSMutableArray internally. Check the Apple Docs.
i'd write it as such:

```<code>-(BOOL)RemoteCall:(id)dataClass
{
   if([dataClass isKindOfClass:[NSMutableArray class] ] == YES)
   {
       NSMutableArray * SW =(NSMutableArray *)dataClass;
       //do something with SW
       return TRUE;
   }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a function  That takes by reference any kind of object
-(BOOL)RemoteCall:(id**)DataClass;
in the implementation i use [*DataClass isMemberOfClass:[NSMutableArray class] to find out the type of the object. The problem is it does not work with NSMUtableArrays Does anybody have a solution to this problem ? Here is the relevant code:

Implementation:

-(BOOL)RemoteCall:(id**)DataClass
{
    if([*DataClass isMemberOfClass:[NSMutableArray class] ] == YES)
    {
            NSMutableArray * SW =(NSMutableArray *)*DataClass;
                       //do something with SW
            DataClass= (id**)SW;
                        return TRUE;
    }
}

Any help and I mean anything at all will be appreciated, I'm stuck.

Method Call:
NSMutableArray * channelArray = [[NSMutableArray alloc]init]
Services * serv = [[Services alloc] init];
return [serv RemoteCall:&channelArray];

Body:
As Eiko said before, i'd use just id and not double pointers to ID.

I'm also pretty sure that isMemberOfClass is your Problem. isMember does not check for inheritance, so you're only asking for Top level Classes. isKindOfClass is probably the better choice, as there is no guarantee that Apple doesn't use an internal subclass of NSMutableArray internally. Check the Apple Docs.
i'd write it as such:

-(BOOL)RemoteCall:(id)dataClass
{
   if([dataClass isKindOfClass:[NSMutableArray class] ] == YES)
   {
       NSMutableArray * SW =(NSMutableArray *)dataClass;
       //do something with SW
       return TRUE;
   }
}


问:
How do you disable viewport zooming on Mobile Safari?
I've tried all three of these to no avail:

```<code><meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;” />

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=false;” />

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;” />
</code>```

each are different values I found recommended by google searching or SO searching, but none of the 'user-scalable=X' values seem to be working

I also tried comma delimiting the values instead of semicolon, no luck. Then I tried ONLY having the user-scalable value present, still no luck.

UPDATE

Got this from Apple's site and it works:

```<code><meta name="viewport" content="width=device-width, user-scalable=no" />
</code>```

it turns out that the problem was the non-standard quotes because I had copied the meta tag from a website that was using them, whoops

答:
This one should be working on iphone etc.</p>

```<code><meta name="viewport" content="width=device-width, initial-scale=1 initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
</code>```

Body:
I've tried all three of these to no avail:

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;” />

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=false;” />

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;” />

each are different values I found recommended by google searching or SO searching, but none of the 'user-scalable=X' values seem to be working

I also tried comma delimiting the values instead of semicolon, no luck. Then I tried ONLY having the user-scalable value present, still no luck.

UPDATE

Got this from Apple's site and it works:

<meta name="viewport" content="width=device-width, user-scalable=no" />

it turns out that the problem was the non-standard quotes because I had copied the meta tag from a website that was using them, whoops

Body:
This one should be working on iphone etc.

<meta name="viewport" content="width=device-width, initial-scale=1 initial-scale=1.0, maximum-scale=1.0, user-scalable=no">


问:
Json info through url php
I'm trying to get specific data from a Json url but i'm stuck in how to get the data i need. The output of my url looks like:

```<code>{
"dev_settings_device":{"uuid":"eneco-001-018946:hdrv_zwave_63523C6205B", "name":"settings_device", "internalAddress":"settings_device", "type":"settings_device", "supportsCrc":"49", "location":"(null)"},
"dev_10":{"uuid":"eneco-001-018946:hdrv_zwave_69423C65F08", "name":"HAE_METER_v2", "internalAddress":"10", "type":"HAE_METER_v2", "supportsCrc":"1", "supportedCC":"22 3c 3d 3e 56 60 70 72 7a 86 8b 73", "IsConnected":"1", "HealthValue":"10", "location":"(null)"},
"dev_10.1":{"uuid":"eneco-001-018946:hdrv_zwave_69448735F0E", "name":"HAE_METER_v2_1", "internalAddress":"10.1", "type":"gas", "supportsCrc":"0", "CurrentGasFlow":"0.00", "CurrentGasQuantity":"670.00", "location":"(null)"},
"dev_10.2":{"uuid":"eneco-001-018946:hdrv_zwave_6945CFF5F0E", "name":"HAE_METER_v2_2", "internalAddress":"10.2", "type":"elec", "supportsCrc":"0", "CurrentElectricityFlow":"428.00", "CurrentElectricityQuantity":"49464.00", "location":"(null)"},
"dev_10.3":{"uuid":"eneco-001-018946:hdrv_zwave_69458EC5F0E", "name":"HAE_METER_v2_3", "internalAddress":"10.3", "type":"elec_delivered_nt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"},
"dev_10.4":{"uuid":"eneco-001-018946:hdrv_zwave_6947CCD5F0E", "name":"HAE_METER_v2_4", "internalAddress":"10.4", "type":"elec_received_nt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"},
"dev_10.5":{"uuid":"eneco-001-018946:hdrv_zwave_694D7AB5F0E", "name":"HAE_METER_v2_5", "internalAddress":"10.5", "type":"elec_delivered_lt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"},
"dev_10.6":{"uuid":"eneco-001-018946:hdrv_zwave_6941EFB5F0E", "name":"HAE_METER_v2_6", "internalAddress":"10.6", "type":"elec_received_lt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"}
}
</code>```

My file looks like this

```<code><?php
error_reporting(E_ALL);
/* Written by Ierlandfan */
/* 1-11-2015 */
/* Version 1.1 */

/* Change ip_toon to the IP of your Toon */
/* start of current Energy usage import */
$file_string_gas = file_get_contents('http://192.168.1.66/hdrv_zwave?
action=getDevices.json');
$parsed_json = json_decode($file_string_gas, true);
var_dump($parsed_json['dev_10.1']);

/* Create new virtual sensor and write down the idx value */
/* Define idxvalue here */
$gasUsage=$parsed_json['CurrentGasQuantity'];
$idx = 933;

/* If this script is not run locally on the Domoticz server change 127.0.0.1
according to your Domoticz IP */
/* Send currentUsage to Domoticz */
$gasusage = curl_init("http://192.168.1.27:8080/json.htm?
type=command&param=udevice&idx=$idx&nvalue=0&svalue=$gasUsage");
curl_exec($gasusage);
echo $gasUsage;
?>
</code>```

The output i get from the var dump is:

```<code>array(8) {
  ["uuid"]=>
  string(39) "eneco-001-018946:hdrv_zwave_69448735F0E"
  ["name"]=>
  string(14) "HAE_METER_v2_1"
  ["internalAddress"]=>
  string(4) "10.1"
  ["type"]=>
  string(3) "gas"
  ["supportsCrc"]=>
  string(1) "0"
  ["CurrentGasFlow"]=>
  string(4) "0.00"
  ["CurrentGasQuantity"]=>
  string(6) "670.00"
  ["location"]=>
  string(6) "(null)"
</code>```

The error i receive is: PHP Notice:  Undefined index: CurrentGasQuantity in /home/pi/domoticz/scripts/php/gas_data_json1.php on line 16, but for the life of me i don't understand why. I tried a couple of thing but it seems i'm stuck.

答:
CurrentGasQuantity is index of $parsed_json['dev_10.1']. So you can retrieve it as below :

```<code>$gasUsage= $parsed_json['dev_10.1']['CurrentGasQuantity']
</code>```

Title: Json info through url php

Body:
I'm trying to get specific data from a Json url but i'm stuck in how to get the data i need. The output of my url looks like:

{
"dev_settings_device":{"uuid":"eneco-001-018946:hdrv_zwave_63523C6205B", "name":"settings_device", "internalAddress":"settings_device", "type":"settings_device", "supportsCrc":"49", "location":"(null)"},
"dev_10":{"uuid":"eneco-001-018946:hdrv_zwave_69423C65F08", "name":"HAE_METER_v2", "internalAddress":"10", "type":"HAE_METER_v2", "supportsCrc":"1", "supportedCC":"22 3c 3d 3e 56 60 70 72 7a 86 8b 73", "IsConnected":"1", "HealthValue":"10", "location":"(null)"},
"dev_10.1":{"uuid":"eneco-001-018946:hdrv_zwave_69448735F0E", "name":"HAE_METER_v2_1", "internalAddress":"10.1", "type":"gas", "supportsCrc":"0", "CurrentGasFlow":"0.00", "CurrentGasQuantity":"670.00", "location":"(null)"},
"dev_10.2":{"uuid":"eneco-001-018946:hdrv_zwave_6945CFF5F0E", "name":"HAE_METER_v2_2", "internalAddress":"10.2", "type":"elec", "supportsCrc":"0", "CurrentElectricityFlow":"428.00", "CurrentElectricityQuantity":"49464.00", "location":"(null)"},
"dev_10.3":{"uuid":"eneco-001-018946:hdrv_zwave_69458EC5F0E", "name":"HAE_METER_v2_3", "internalAddress":"10.3", "type":"elec_delivered_nt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"},
"dev_10.4":{"uuid":"eneco-001-018946:hdrv_zwave_6947CCD5F0E", "name":"HAE_METER_v2_4", "internalAddress":"10.4", "type":"elec_received_nt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"},
"dev_10.5":{"uuid":"eneco-001-018946:hdrv_zwave_694D7AB5F0E", "name":"HAE_METER_v2_5", "internalAddress":"10.5", "type":"elec_delivered_lt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"},
"dev_10.6":{"uuid":"eneco-001-018946:hdrv_zwave_6941EFB5F0E", "name":"HAE_METER_v2_6", "internalAddress":"10.6", "type":"elec_received_lt", "supportsCrc":"0", "CurrentElectricityFlow":"NaN", "CurrentElectricityQuantity":"NaN", "location":"(null)"}
}

My file looks like this

<?php
error_reporting(E_ALL);
/* Written by Ierlandfan */
/* 1-11-2015 */
/* Version 1.1 */

/* Change ip_toon to the IP of your Toon */
/* start of current Energy usage import */
$file_string_gas = file_get_contents('http://192.168.1.66/hdrv_zwave?
action=getDevices.json');
$parsed_json = json_decode($file_string_gas, true);
var_dump($parsed_json['dev_10.1']);

/* Create new virtual sensor and write down the idx value */
/* Define idxvalue here */
$gasUsage=$parsed_json['CurrentGasQuantity'];
$idx = 933;

/* If this script is not run locally on the Domoticz server change 127.0.0.1
according to your Domoticz IP */
/* Send currentUsage to Domoticz */
$gasusage = curl_init("http://192.168.1.27:8080/json.htm?
type=command&param=udevice&idx=$idx&nvalue=0&svalue=$gasUsage");
curl_exec($gasusage);
echo $gasUsage;
?>

The output i get from the var dump is:

array(8) {
  ["uuid"]=>
  string(39) "eneco-001-018946:hdrv_zwave_69448735F0E"
  ["name"]=>
  string(14) "HAE_METER_v2_1"
  ["internalAddress"]=>
  string(4) "10.1"
  ["type"]=>
  string(3) "gas"
  ["supportsCrc"]=>
  string(1) "0"
  ["CurrentGasFlow"]=>
  string(4) "0.00"
  ["CurrentGasQuantity"]=>
  string(6) "670.00"
  ["location"]=>
  string(6) "(null)"

The error i receive is: PHP Notice:  Undefined index: CurrentGasQuantity in /home/pi/domoticz/scripts/php/gas_data_json1.php on line 16, but for the life of me i don't understand why. I tried a couple of thing but it seems i'm stuck.

Body:
CurrentGasQuantity is index of $parsed_json['dev_10.1']. So you can retrieve it as below :

$gasUsage= $parsed_json['dev_10.1']['CurrentGasQuantity']


问:
Output text file with line breaks in PHP
I'm trying to open a text file and output its contents with the code below. The text file includes line breaks but when I echo the file its unformatted. How do I fix this?

Thanks.

```<code><html>

<head>

</head>

<body>

        $fh = fopen("filename.txt", 'r');

        $pageText = fread($fh, 25000);

        echo $pageText;

</body>

</html>
</code>```

答:
Say you have an index.php file hosted by the web server. You want to insert some multi-line text file contents into it. That's how you do it:

```<code><body>
        <div>Some multi-line message below:</div>
        <div><?= nl2br(file_get_contents('message.txt.asc')); ?></div>
</body>
</code>```

This <?= ... ?> part is just a shorthand, which instructs the web server, that it needs to be treated as a PHP echo argument.

Body:
I'm trying to open a text file and output its contents with the code below. The text file includes line breaks but when I echo the file its unformatted. How do I fix this?

Thanks.

        $fh = fopen("filename.txt", 'r');

        $pageText = fread($fh, 25000);

        echo $pageText;

Body:
Say you have an index.php file hosted by the web server. You want to insert some multi-line text file contents into it. That's how you do it:

<body>
        <div>Some multi-line message below:</div>
        <div><?= nl2br(file_get_contents('message.txt.asc')); ?></div>
</body>

This <?= ... ?> part is just a shorthand, which instructs the web server, that it needs to be treated as a PHP echo argument.


问:
How can I use multiple guard (or if let) statements without exiting the code in Swift?
I tried to perform simple mathematical calculations based on input from several textfields. When one field is not filled in, I would like to continue the calculation for other fields. However, this does not work with my use of the (inappropriate?) guard statement.

Put simply:

If field1 is filled in, perform calculation (i.e. multiply that amount by 0.5) and store the result.

If field2 is filled in, perform calculation (i.e. multiply that amount by 0.2) and store the result.

etc.

As an absolute beginner, I tried this:

```<code>@IBAction func calculate(_ sender: Any) {
    //amount 1
    guard let amount1 = textField1.text else{
        return}
    guard let amount1double = Double(amount1) else{
        return}

    var amt1 = amount1double
    amt1 = amt1 * 0.5

    //amount 2
    guard let amount2 = textField2.text else{
        return }

    guard let amount2double = Double(amount2) else{
        return }

    var amt2 = amount2double
    amt2 = amt2 * 0.2
}
</code>```

The above code will stop if textField1 is not filled in. However I want the code to continue to calculate amount2 if textField1 is empty.

I read about if let statements to maybe continue with the rest of the code after a nil in the texfField, however I could not make it work. Furthermore I understand this will only allow me to access that value within that block.

The goal is to ultimately get the highest / maximum amount from all calculated amounts, if available.

答:
UPDATE

You don't need to use guard or if-let then. You can just use let with default value.

```<code>@IBAction func calculate(_ sender: Any) {
    let amount1double = Double(textField1.text ?? "") ?? 0 // 0 is default value, Change it to whatever you want.
    let amount2double = Double(textField2.text ?? "") ?? 0 // 0 is default value, Change it to whatever you want.

    var amt1 = amount1double
    amt1 = amt1 * 0.5

    var amt2 = amount2double
    amt2 = amt2 * 0.5
}
</code>```

Using if let

```<code>@IBAction func calculate(_ sender: Any) {
    if let amount1 = textField1.text,
        let amount2 = textField2.text,
        let amount1double = Double(amount1),
        let amount2double = Double(amount2) {

        var amt1 = amount1double
        amt1 = amt1 * 0.5

        var amt2 = amount2double
        amt2 = amt2 * 0.5
    }
}
</code>```

Using guard

```<code>@IBAction func calculate(_ sender: Any) {
    guard let amount1 = textField1.text,
        let amount2 = textField2.text,
        let amount1double = Double(amount1),
        let amount2double = Double(amount2)  else {
        return
    }

    var amt1 = amount1double
    amt1 = amt1 * 0.5

    var amt2 = amount2double
    amt2 = amt2 * 0.5
}
</code>```

Body:
I tried to perform simple mathematical calculations based on input from several textfields. When one field is not filled in, I would like to continue the calculation for other fields. However, this does not work with my use of the (inappropriate?) guard statement.

Put simply:

If field1 is filled in, perform calculation (i.e. multiply that amount by 0.5) and store the result.

If field2 is filled in, perform calculation (i.e. multiply that amount by 0.2) and store the result.

etc.

As an absolute beginner, I tried this:

@IBAction func calculate(_ sender: Any) {
    //amount 1
    guard let amount1 = textField1.text else{
        return}
    guard let amount1double = Double(amount1) else{
        return}

    var amt1 = amount1double
    amt1 = amt1 * 0.5

    //amount 2
    guard let amount2 = textField2.text else{
        return }

    guard let amount2double = Double(amount2) else{
        return }

    var amt2 = amount2double
    amt2 = amt2 * 0.2
}

The above code will stop if textField1 is not filled in. However I want the code to continue to calculate amount2 if textField1 is empty.

I read about if let statements to maybe continue with the rest of the code after a nil in the texfField, however I could not make it work. Furthermore I understand this will only allow me to access that value within that block.

The goal is to ultimately get the highest / maximum amount from all calculated amounts, if available.

Body:
UPDATE

You don't need to use guard or if-let then. You can just use let with default value.

@IBAction func calculate(_ sender: Any) {
    let amount1double = Double(textField1.text ?? "") ?? 0 // 0 is default value, Change it to whatever you want.
    let amount2double = Double(textField2.text ?? "") ?? 0 // 0 is default value, Change it to whatever you want.

    var amt1 = amount1double
    amt1 = amt1 * 0.5

    var amt2 = amount2double
    amt2 = amt2 * 0.5
}

Using if let

@IBAction func calculate(_ sender: Any) {
    if let amount1 = textField1.text,
        let amount2 = textField2.text,
        let amount1double = Double(amount1),
        let amount2double = Double(amount2) {

        var amt1 = amount1double
        amt1 = amt1 * 0.5

        var amt2 = amount2double
        amt2 = amt2 * 0.5
    }
}

Using guard

@IBAction func calculate(_ sender: Any) {
    guard let amount1 = textField1.text,
        let amount2 = textField2.text,
        let amount1double = Double(amount1),
        let amount2double = Double(amount2)  else {
        return
    }

    var amt1 = amount1double
    amt1 = amt1 * 0.5

    var amt2 = amount2double
    amt2 = amt2 * 0.5
}


答:
I tried to solve your problem using if-let. Check below code.

```<code>var amt1 : Double = 0.0
        if let amount1 = textfield1.text{
            if let amount1InDouble = Double(amount1){
                amt1 = amount1InDouble
                amt1 = amt1 * 0.5
            }
        }

        var amt2 : Double = 0.0
        if let amount2 = textfield2.text{
            if let amount2InDouble = Double(amount2){
                amt2 = amount2InDouble
                amt2 = amt2 * 0.2
            }
        }
</code>```

Title: How can I use multiple guard (or if let) statements without exiting the code in Swift?

Body:
I tried to solve your problem using if-let. Check below code.

var amt1 : Double = 0.0
        if let amount1 = textfield1.text{
            if let amount1InDouble = Double(amount1){
                amt1 = amount1InDouble
                amt1 = amt1 * 0.5
            }
        }

        var amt2 : Double = 0.0
        if let amount2 = textfield2.text{
            if let amount2InDouble = Double(amount2){
                amt2 = amount2InDouble
                amt2 = amt2 * 0.2
            }
        }


问:
How to play video .avi or mp4 in ionic
I have some files in format .avi and mp4, but I need to play those video in ionic.

How to play those files?

答:
crosswalk problem , I install these plugin:

ionic plugin add cordova-plugin-crosswalk-webview

and problem is solved

Title: How to play video .avi or mp4 in ionic


问:
Mutate state of children
I have two components in my react application, one is parent and the second is the child.

I pass fakedata state as a props to child and then in child component save this as state of child component. But when I change something in child it's affect on parent state and I don't want this I want it's only effect on child state.

This is how I call child component from parent :

```<code><FakeDataAddEditComponent  {...this.props} fakedata={{...this.state.fakedata}} />
</code>```

and in child component this is how I set fakedata props to state :

```<code>  componentDidMount() {
     this.setState({fakedata:{...this.props.fakedata}},()=>{

     })
}
</code>```

but when I change fakedata state in child it's also changend in fakedata of parent and I don't want this.

答:
To answer your question directly, the reason you are seeing this behaviour is because Javascript passes a reference to the original object down the props and to the state of child component. When you update the child component it is the same instance as the parent is holding.

To fix the problem you should use Object.assign to make a copy of the object, however keep in ming that you will run into problems with nested objects.

Also, if parent object mutates the state in any way after the child state changed it will pass old object as props to the child.
In general you're trying to do something you shouldn't do because you will run into trouble.

On a high level you should go for a proper state management solution like Redux of Flux.

Title: Mutate state of children

Body:
I have two components in my react application, one is parent and the second is the child.

I pass fakedata state as a props to child and then in child component save this as state of child component. But when I change something in child it's affect on parent state and I don't want this I want it's only effect on child state.

This is how I call child component from parent :

<FakeDataAddEditComponent  {...this.props} fakedata={{...this.state.fakedata}} />

and in child component this is how I set fakedata props to state :

  componentDidMount() {
     this.setState({fakedata:{...this.props.fakedata}},()=>{

     })
}

but when I change fakedata state in child it's also changend in fakedata of parent and I don't want this.


问:
Completly deinstall and remove Elasticsearch for complete restart and begin new
After experimenting with Elasticsearch I'm searching for a way to completely remove everything concerning Elasticsearch on my server. I made quite a few mistakes and want to start completely new with a new installation.</p>

答:
use the following command to know the pid of the node already running.

curl -XGET 'http://localhost:9200/_nodes/process'

It took me an hour to find out the way to kill the node and could finally do it after using this command in the terminal window.

**For Linux users:

kill -9 {pid}

** will terminate the elasticsearch from the RAM. And then you can delete as the other answers suggest.


问:
content expand on overflow
I'm somewhat of a designer but i kind of suck at css, and cannot seem to get the site to expand right when the content changes. I hope you guys can help...

css:
http://pastebin.com/CasrrGe9

html:
http://pastebin.com/WN8XhAHd

I revised the html with the absolute path to the images

答:
I would just recommend little things like changing all those id's of index-## to have the positioned declared once

```<code>#index-01,#index-02,#index-03,#index-04{
position:absolute;
}
</code>```

Clean it all up then start worrying about other things, as otherwise you are going to be in a real mess in about an hour or so.

you shouldn't be positioning them at all though

You should declare one class that is in control of all the divs and that is floating left:

```<code>.float_left {float:left;}
.clear_both {clear:both}
</code>```

And apply that to each of the divs you want to use then at the end clear the float

```<code><div class="float_left"><img src="index-1.jpg" /></div>
<div class="float_left"><img src="index-2.jpg" /></div>
<div class="float_left"><img src="index-3.jpg" /></div>
<div class="clear_both"></div>
</code>```

Then the divs should expand automatically :)

Title: content expand on overflow

Body:
I would just recommend little things like changing all those id's of index-## to have the positioned declared once

#index-01,#index-02,#index-03,#index-04{
position:absolute;
}

Clean it all up then start worrying about other things, as otherwise you are going to be in a real mess in about an hour or so.

you shouldn't be positioning them at all though

You should declare one class that is in control of all the divs and that is floating left:

.float_left {float:left;}
.clear_both {clear:both}

And apply that to each of the divs you want to use then at the end clear the float

<div class="float_left"><img src="index-1.jpg" /></div>
<div class="float_left"><img src="index-2.jpg" /></div>
<div class="float_left"><img src="index-3.jpg" /></div>
<div class="clear_both"></div>

Then the divs should expand automatically :)


问:
How to read resource file from unit test?
I have a Java-only module in my Android project. In that project I want to have a unit test that reads the contents from a local json file that is stored in the resources folder. Android Studio changes the icon of the resources folder, so I'd think it recognises it as the resources folder.

How I'm reading:

```<code>String json = Files.lines(Paths.get("file.json"))
                .parallel()
                .collect(Collectors.joining());
</code>```

folder structure:

```<code>+project
  +app (android)
  +module (java only)
    +src
      +main
        +java
          +package
            -the java file
        +resources
            -file.json
</code>```

My question is how can I read the file?

updated below

```<code>URL resource1 = getClass().getResource("file.json");
URL resource2 = getClass().getClassLoader().getResource("file.json");
URL resource3 = Thread.currentThread().getContextClassLoader().getResource("file.json");
URL resource4 = ClassLoader.getSystemClassLoader().getResource("file.json");
</code>```

All these are null.
I've copied the json file to resources/same.package.structure too, but to no success.

答:
Don't need to do all this complicated stuff with ClassLoaders. You have access to test/resources directory from you /test/* classes.

UPD
This is how to deserialize file using its path using SimpleXML. So here source method param is your path to resource file

Body:
I have a Java-only module in my Android project. In that project I want to have a unit test that reads the contents from a local json file that is stored in the resources folder. Android Studio changes the icon of the resources folder, so I'd think it recognises it as the resources folder.

How I'm reading:

String json = Files.lines(Paths.get("file.json"))
                .parallel()
                .collect(Collectors.joining());

folder structure:

+project
  +app (android)
  +module (java only)
    +src
      +main
        +java
          +package
            -the java file
        +resources
            -file.json

My question is how can I read the file?

updated below

URL resource1 = getClass().getResource("file.json");
URL resource2 = getClass().getClassLoader().getResource("file.json");
URL resource3 = Thread.currentThread().getContextClassLoader().getResource("file.json");
URL resource4 = ClassLoader.getSystemClassLoader().getResource("file.json");

All these are null.
I've copied the json file to resources/same.package.structure too, but to no success.


问:
Missing dependencies lua-cjson >= 2.1.0 for installing fblualib?
When installing fblualib, encountered the following error:

```<code>Missing dependencies for fbluaunit:
lua-cjson >= 2.1.0

^CWarning: Failed searching manifest: Failed loading manifest: Failed     fetching manifest for http://luarocks.org/repositories/rocks - Error fetching file: Failed downloading http://luarocks.org/repositories/rocks/manifest

Error: Could not satisfy dependency: lua-cjson >= 2.1.0

Missing dependencies for fbluaunit:
lua-cjson >= 2.1.0

^CWarning: Failed searching manifest: Failed loading manifest: Failed fetching manifest for http://luarocks.org/repositories/rocks - Error fetching file: Failed downloading http://luarocks.org/repositories/rocks/manifest

Error: Could not satisfy dependency: lua-cjson >= 2.1.0
    cmake -E make_directory build &&
    cd build &&
    cmake -DROCKS_PREFIX=/usr/local/lib/luarocks/rocks/fbpython/0.1-1 \
          -DROCKS_LUADIR=/usr/local/lib/luarocks/rocks/fbpython/0.1-1/lua \
          -DROCKS_LIBDIR=/usr/local/lib/luarocks/rocks/fbpython/0.1-1/lib \
          .. &&
    make

CMake Error at CMakeLists.txt:25 (FIND_PACKAGE):
  By not providing "FindTorch.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Torch", but
  CMake did not find one.

  Could not find a package configuration file provided by "Torch" with any of
  the following names:

    TorchConfig.cmake
    torch-config.cmake

  Add the installation prefix of "Torch" to CMAKE_PREFIX_PATH or set
  "Torch_DIR" to a directory containing one of the above files.  If     "Torch"
  provides a separate development package or SDK, be sure it has been
  installed.

-- Configuring incomplete, errors occurred!
See also "/tmp/fblualib-build.0APMyV/fblualib/fblualib/python/build/CMakeFiles/CMakeOutput.log".

Error: Build error: Failed building.
</code>```

I have tried to using my luarocks to install lua-cjson and when the installation complete it showed:

```<code>lua-cjson 2.1.0-1 is now built and installed in /home/XXXXXXXXX/torch/install/ (license: MIT)
</code>```

I think it was installed, but when I installed fblualib again cause the same error.
How to overcome it? Thanks in advance.

答: As far as I checked, it was network fault. After set right network environment, all went smoothly.</p>

Body:
When installing fblualib, encountered the following error:

Missing dependencies for fbluaunit:
lua-cjson >= 2.1.0

^CWarning: Failed searching manifest: Failed loading manifest: Failed     fetching manifest for http://luarocks.org/repositories/rocks - Error fetching file: Failed downloading http://luarocks.org/repositories/rocks/manifest

Error: Could not satisfy dependency: lua-cjson >= 2.1.0

Missing dependencies for fbluaunit:
lua-cjson >= 2.1.0

^CWarning: Failed searching manifest: Failed loading manifest: Failed fetching manifest for http://luarocks.org/repositories/rocks - Error fetching file: Failed downloading http://luarocks.org/repositories/rocks/manifest

Error: Could not satisfy dependency: lua-cjson >= 2.1.0
    cmake -E make_directory build &&
    cd build &&
    cmake -DROCKS_PREFIX=/usr/local/lib/luarocks/rocks/fbpython/0.1-1 \
          -DROCKS_LUADIR=/usr/local/lib/luarocks/rocks/fbpython/0.1-1/lua \
          -DROCKS_LIBDIR=/usr/local/lib/luarocks/rocks/fbpython/0.1-1/lib \
          .. &&
    make

CMake Error at CMakeLists.txt:25 (FIND_PACKAGE):
  By not providing "FindTorch.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Torch", but
  CMake did not find one.

  Could not find a package configuration file provided by "Torch" with any of
  the following names:

    TorchConfig.cmake
    torch-config.cmake

  Add the installation prefix of "Torch" to CMAKE_PREFIX_PATH or set
  "Torch_DIR" to a directory containing one of the above files.  If     "Torch"
  provides a separate development package or SDK, be sure it has been
  installed.

-- Configuring incomplete, errors occurred!
See also "/tmp/fblualib-build.0APMyV/fblualib/fblualib/python/build/CMakeFiles/CMakeOutput.log".

Error: Build error: Failed building.

I have tried to using my luarocks to install lua-cjson and when the installation complete it showed:

lua-cjson 2.1.0-1 is now built and installed in /home/XXXXXXXXX/torch/install/ (license: MIT)

I think it was installed, but when I installed fblualib again cause the same error.
How to overcome it? Thanks in advance.