问:
Android Studio - current position - Google Map
I try to set a marker on my MapActivity with my current position. If I use the emulator, the map dont have any marker. If I use my mobile device (API 24), the activity starts for a short time without marker and then the app crashed.
Thank your for your help guys.</p>

```<code>import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    LatLng latLng = new LatLng(latitude, longitude);
                    Geocoder geocoder = new Geocoder(getApplicationContext());
                    try {
                        List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
                        String str = addressList.get(0).getLocality();
                        str += addressList.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(latLng).title(str));
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

                }
            });
        } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    LatLng latLng = new LatLng(latitude, longitude);
                    Geocoder geocoder = new Geocoder(getApplicationContext());
                    try {
                        List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
                        String str = addressList.get(0).getLocality();
                        str += addressList.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(latLng).title(str));
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

                }
            });
        }
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
//        mMap = googleMap;
//        mMap.getMaxZoomLevel();
//        // Add a marker in Sydney and move the camera
//        LatLng posi = new LatLng(100, 100);
//        mMap.addMarker(new MarkerOptions().position(posi).title("my position"));
//        mMap.moveCamera(CameraUpdateFactory.newLatLng(posi));

    }

}
</code>```

答:
you should call get location in onMapReady

Remove all the logic of getting location from onCreate and add following code in onMapReady

```<code>  @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        if (mMap!=null){
            Log.d(TAG, "onMapReady: Map is "+mMap);
        }else {
            Log.d(TAG, "onMapReady: Map is not "+mMap);
        }
        mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
            @Override
            public boolean onMyLocationButtonClick() {
//                Toast.makeText(getActivity(), "Map button click"+mMap.getMyLocation().getLongitude(), Toast.LENGTH_SHORT).show();

                try {
                    displayLocationSettingsRequest(getContext());
                    latLngs=new LatLng(mMap.getMyLocation().getLatitude(),mMap.getMyLocation().getLongitude());
                    setLocationName(latLngs);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d(TAG, "onMyLocationButtonClick: "+e);
                }

                //check permission
                return false;
            }
        });
        markerOptions=new MarkerOptions().position(new LatLng(-34, 151));
        mMarker=mMap.addMarker(markerOptions);
}
</code>```

Body:
I try to set a marker on my MapActivity with my current position. If I use the emulator, the map dont have any marker. If I use my mobile device (API 24), the activity starts for a short time without marker and then the app crashed.
Thank your for your help guys.

import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    LatLng latLng = new LatLng(latitude, longitude);
                    Geocoder geocoder = new Geocoder(getApplicationContext());
                    try {
                        List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
                        String str = addressList.get(0).getLocality();
                        str += addressList.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(latLng).title(str));
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

                }
            });
        } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    LatLng latLng = new LatLng(latitude, longitude);
                    Geocoder geocoder = new Geocoder(getApplicationContext());
                    try {
                        List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
                        String str = addressList.get(0).getLocality();
                        str += addressList.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(latLng).title(str));
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

                }
            });
        }
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
//        mMap = googleMap;
//        mMap.getMaxZoomLevel();
//        // Add a marker in Sydney and move the camera
//        LatLng posi = new LatLng(100, 100);
//        mMap.addMarker(new MarkerOptions().position(posi).title("my position"));
//        mMap.moveCamera(CameraUpdateFactory.newLatLng(posi));

    }

}

Body:
you should call get location in onMapReady

Remove all the logic of getting location from onCreate and add following code in onMapReady

  @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        if (mMap!=null){
            Log.d(TAG, "onMapReady: Map is "+mMap);
        }else {
            Log.d(TAG, "onMapReady: Map is not "+mMap);
        }
        mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
            @Override
            public boolean onMyLocationButtonClick() {
//                Toast.makeText(getActivity(), "Map button click"+mMap.getMyLocation().getLongitude(), Toast.LENGTH_SHORT).show();

                try {
                    displayLocationSettingsRequest(getContext());
                    latLngs=new LatLng(mMap.getMyLocation().getLatitude(),mMap.getMyLocation().getLongitude());
                    setLocationName(latLngs);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d(TAG, "onMyLocationButtonClick: "+e);
                }

                //check permission
                return false;
            }
        });
        markerOptions=new MarkerOptions().position(new LatLng(-34, 151));
        mMarker=mMap.addMarker(markerOptions);
}


来源: stackexchange

问:
Case sensitive issue when making login in PHP Laravel
I have this code used to check login details. Specially to check password from user entered data and data in SQL.

```<code>if ($request->input('password') != $fromUser[0]->Password) {
    $currentStatus = "invalid_password";
  }
</code>```

This code works well in my local machine. Checking case sensitive too. It mean when "$request->input('password')" = "DemoTest" and "$fromUser[0]->Password" = "demotest",

 it's not matching and return false ($currentStatus = "invalid_password";).

But when I hosted this on server, this is not working. Not checking case sensitive and if above condition happened, it gives me true.

Why is that ? I hosted this in Windows server. But my local machine is Linux.

答:
As you are dealing with Password then you need to use Hash code to store the password in DB and use strcmp to password match.

Try like this

```<code>$var1=Hash::make($var1);
if(strcmp($var1, $var2) != 0) {
    $currentStatus = "invalid_password";
 }
</code>```

I thing it will work for you.

ContentLicense: CC BY-SA 3.0

Body:
I have this code used to check login details. Specially to check password from user entered data and data in SQL.

if ($request->input('password') != $fromUser[0]->Password) {
    $currentStatus = "invalid_password";
  }

This code works well in my local machine. Checking case sensitive too. It mean when "$request->input('password')" = "DemoTest" and "$fromUser[0]->Password" = "demotest",

 it's not matching and return false ($currentStatus = "invalid_password";).

But when I hosted this on server, this is not working. Not checking case sensitive and if above condition happened, it gives me true.

Why is that ? I hosted this in Windows server. But my local machine is Linux.

Body:
As you are dealing with Password then you need to use Hash code to store the password in DB and use strcmp to password match.

Try like this

$var1=Hash::make($var1);
if(strcmp($var1, $var2) != 0) {
    $currentStatus = "invalid_password";
 }

I thing it will work for you.


问:
Accessing source code of PowerApps and hosting it elsewhere
We are looking into using PowerApps to develop apps quickly. However, we are concerned about dependency on Azure and inability to access the source code.

We are interested in understanding the transportability of an app in PowerApps.

1) Can we access the source code?

2) In a scenario where PowerApps does not satisfy our needs, can we take away the source code and manage everything ourselves?

3) Can we deploy the code in another cloud provider such as AWS or Google Cloud or our own server?

Thanks!

答: No, you cannot access the source code. The whole point of PowerApps is that it is a zero code environment. Therefore you cannot take the code and use it elsewhere.</p>


问:
Hidden reusable blocks in YAML
I am trying to define a reusable block in a docker-compose.yml file in a way that the reusable block definition itself is NOT included in the final (evaluated) YAML.

I know how to define a reusable block with this syntax:

```<code>services:
  default: &default
    image: some/image

  dashboard:
    <<: *default
    command: run dashboard
    ports: ["3000:3000"]
</code>```

But, the above also creates an entry named default under services, which I would like to avoid. In other words, I need the final YAML result to only include dashboard under the services property.

Is this possible with YAML? I was unable to find any reference that discusses this structure clearly enough.

Intuitively, I have tried some variations of the below, but it also did not work.

```<code>services:
  &default:
    image: some/image

  dashboard:
    <<: *default
    command: run dashboard
    ports: ["3000:3000"]
</code>```

答:
This is not possible in YAML 1.2 (or any former version). The reasoning behind this is that YAML has been designed to be a serialization language, not a configuration language.

The Anchor/Alias construct is nice for serializing cyclic data structures. It was never intended to be used for declaring variables that will be used in multiple places. So currently, the only way to create a reusable structure which can be used in multiple places it to define the structure at the first place where it is used. For example:

```<code>services:
  dashboard:
    <<: &default
      image: some/image
    command: run dashboard
    ports: ["3000:3000"]
  some_other_service:
    <<: *default
    other_props: ...
</code>```

Also, be aware that the merge key << is not part of the YAML spec and only defined as additional feature for YAML 1.1. It is not defined for YAML 1.2 and will be explicitly deprecated for upcoming YAML 1.3.

We (as in: the people currently working on YAML 1.3) are aware of this missing feature and plan to provide a better solution with YAML 1.3.

Title: Hidden reusable blocks in YAML

Body:
I am trying to define a reusable block in a docker-compose.yml file in a way that the reusable block definition itself is NOT included in the final (evaluated) YAML.

I know how to define a reusable block with this syntax:

services:
  default: &default
    image: some/image

  dashboard:
    <<: *default
    command: run dashboard
    ports: ["3000:3000"]

But, the above also creates an entry named default under services, which I would like to avoid. In other words, I need the final YAML result to only include dashboard under the services property.

Is this possible with YAML? I was unable to find any reference that discusses this structure clearly enough.

Intuitively, I have tried some variations of the below, but it also did not work.

services:
  &default:
    image: some/image

  dashboard:
    <<: *default
    command: run dashboard
    ports: ["3000:3000"]

Body:
This is not possible in YAML 1.2 (or any former version). The reasoning behind this is that YAML has been designed to be a serialization language, not a configuration language.

The Anchor/Alias construct is nice for serializing cyclic data structures. It was never intended to be used for declaring variables that will be used in multiple places. So currently, the only way to create a reusable structure which can be used in multiple places it to define the structure at the first place where it is used. For example:

services:
  dashboard:
    <<: &default
      image: some/image
    command: run dashboard
    ports: ["3000:3000"]
  some_other_service:
    <<: *default
    other_props: ...

Also, be aware that the merge key << is not part of the YAML spec and only defined as additional feature for YAML 1.1. It is not defined for YAML 1.2 and will be explicitly deprecated for upcoming YAML 1.3.

We (as in: the people currently working on YAML 1.3) are aware of this missing feature and plan to provide a better solution with YAML 1.3.


问:
Cannot update JLabel background in Java
I have a label, redLabel, that I will need to change the background of multiple times. I have used NetBeans built-in GUI generator to make the GUI and the generation code is:

```<code>redLabel = new javax.swing.JLabel();
redLabel.setBackground(new java.awt.Color(110, 110, 110));
redLabel.setOpaque(true);
</code>```

To change the colour, I have tried redLabel.setBackground(new java.awt.Color(255,0,0)), but this does nothing. I even tried adding redLabel.repaint() after the code.

The code does not thrown an error when I try to update the code, but it does not change the colour.

So my question is, how do I change the background colour, as the other methods on this site haven't worked.

EDIT: The structure of the code:

```<code>imports

class noiseBarUi

    public noiseBarUI()
        initComponents()     //auto-generated

    private void initComponents()
        label creation
        set gui
        label property assignment

    public static void main(String args[])
        some code to do with audio sampling
        instantiate class
        try to modify labels    //this doesn't work

    label declarations    //autogenerated

    some method I created
</code>```

答:
Surround your JLabel with a JPanel, and change JPanel border color or background wherever you want.

Some code

```<code>JPanel panel = new JPanel();
pane.setBorder(BorderFactory.createLineBorder(Color.red))
pane.setBackground(new Color(*RGB*));
</code>```

Title: Cannot update JLabel background in Java

Body:
I have a label, redLabel, that I will need to change the background of multiple times. I have used NetBeans built-in GUI generator to make the GUI and the generation code is:

redLabel = new javax.swing.JLabel();
redLabel.setBackground(new java.awt.Color(110, 110, 110));
redLabel.setOpaque(true);

To change the colour, I have tried redLabel.setBackground(new java.awt.Color(255,0,0)), but this does nothing. I even tried adding redLabel.repaint() after the code.

The code does not thrown an error when I try to update the code, but it does not change the colour.

So my question is, how do I change the background colour, as the other methods on this site haven't worked.

EDIT: The structure of the code:

imports

class noiseBarUi

    public noiseBarUI()
        initComponents()     //auto-generated

    private void initComponents()
        label creation
        set gui
        label property assignment

    public static void main(String args[])
        some code to do with audio sampling
        instantiate class
        try to modify labels    //this doesn't work

    label declarations    //autogenerated

    some method I created

Body:
Surround your JLabel with a JPanel, and change JPanel border color or background wherever you want.

Some code

JPanel panel = new JPanel();
pane.setBorder(BorderFactory.createLineBorder(Color.red))
pane.setBackground(new Color(*RGB*));


问:
Viewing user responses from slack to errbot
I'm very new to bots. I'd like to develop a quick/simple test that makes it possible for a bot (errbot) to write a message to slack, then view responses back to the bot from users on slack.

How do I go about achieving this? Do I need to write a plugin for this?

Apologies if my question is too general/ambiguous -- I haven't come across an example that clearly explains this.

答: Yes, you need to program a bot a way or another, Errbot is just a framework that help you do that (concentrate on messages/responses) through plugins and not on the technicalities of the services it is connected to (Slack or any other).</p>


问:
Minor grid lines in ggplot2 with discrete values and facet grid
I have a plot created using ggplot2 where I'm trying to modify some of the minor grid lines.  Here is the current version:

```<code>library(tidyverse)

data(starwars)
starwars = starwars %>%
  filter(!is.na(homeworld), !is.na(skin_color)) %>%
  mutate(tatooine = factor(if_else(homeworld == "Tatooine", "Tatooine Native", "Other Native")),
         skin_color = factor(skin_color))

ggplot(starwars, aes(birth_year, skin_color)) +
  geom_point(aes(color = gender), size = 4, alpha = 0.7, show.legend = FALSE) +
  facet_grid(tatooine ~ ., scales = "free_y", space = "free_y", switch = "y") +
  theme_minimal() +
  theme(
    panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_blank(),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    strip.placement = "outside",
    strip.background = element_rect(fill="gray90", color = "white"),
  ) +
  geom_hline(yintercept = seq(0, length(unique(starwars$skin_color))) + .5, color="gray30")
</code>```

Y axis is a factor and a facet grid is used, with an uneven number of categories in each grid.  I added some minor grid lines using geom_hline (my understanding is that panel.grid.minor does not work with categorical data i.e., factors).

I would like to remove the lines highlighted in yellow below, and then ADD a single black line in between the two facet grids (i.e., where the current double lines are that are highlighted in yellow).

Any way to do this?  I'd prefer avoiding hard coding the position of any lines, in case the data change.  Thanks.

答:
Removing the top and bottom grid lines dynamically is relatively easy. You code the line positions in the data set based on the faceting groups and exclude the highest and lowest value, and plot the geom_hline with an xintercept inside the aes() statement. That approach is robust to changing the data (to see that this approach works if you change the data, comment out the # filter(!is.na(birth_year)) line below).

```<code>library(tidyverse)
library(grid)

data(starwars)
starwars = starwars %>%
  filter(!is.na(homeworld), !is.na(skin_color)) %>%
  mutate(tatooine = factor(if_else(homeworld == "Tatooine", "Tatooine Native", "Other Native")),
         skin_color = factor(skin_color)) %>%
  # filter(!is.na(birth_year)) %>%
  group_by(tatooine) %>%

  # here we assign the line_positions
  mutate(line_positions = as.numeric(factor(skin_color, levels = unique(skin_color))),
         line_positions = line_positions + .5,
         line_positions = ifelse(line_positions == max(line_positions), NA, line_positions))

plot_out <- ggplot(starwars, aes(birth_year, skin_color)) +
  geom_point(aes(color = gender), size = 4, alpha = 0.7, show.legend = FALSE) +
  geom_hline(aes(yintercept = line_positions)) +
  facet_grid(tatooine ~ ., scales = "free_y", space = "free_y", switch = "y") +
  theme_minimal() +
  theme(
    panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_blank(),
    panel.grid.minor.y = element_line(colour = "black"),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    strip.placement = "outside",
    strip.background = element_rect(fill="gray90", color = "white"),

  )

print(plot_out)
</code>```

gives

However, adding a solid between the facets without any hardcoding is difficult. There are some possible ways to add borders between facets (see here), but if we don't know whether the facets change it is not obvious to which value the border should be assigned. I guess there is a possible solution with drawing a hard coded line in the plot that divides the facets, but the tricky part is to determine dynamically where that border is going to be located, based on the data and how the facets are ultimately draw (e.g. in which order etc). I'd be interested in hearing other opinions on this.

Body:
I have a plot created using ggplot2 where I'm trying to modify some of the minor grid lines.  Here is the current version:

library(tidyverse)

data(starwars)
starwars = starwars %>%
  filter(!is.na(homeworld), !is.na(skin_color)) %>%
  mutate(tatooine = factor(if_else(homeworld == "Tatooine", "Tatooine Native", "Other Native")),
         skin_color = factor(skin_color))

ggplot(starwars, aes(birth_year, skin_color)) +
  geom_point(aes(color = gender), size = 4, alpha = 0.7, show.legend = FALSE) +
  facet_grid(tatooine ~ ., scales = "free_y", space = "free_y", switch = "y") +
  theme_minimal() +
  theme(
    panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_blank(),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    strip.placement = "outside",
    strip.background = element_rect(fill="gray90", color = "white"),
  ) +
  geom_hline(yintercept = seq(0, length(unique(starwars$skin_color))) + .5, color="gray30")

Y axis is a factor and a facet grid is used, with an uneven number of categories in each grid.  I added some minor grid lines using geom_hline (my understanding is that panel.grid.minor does not work with categorical data i.e., factors).

I would like to remove the lines highlighted in yellow below, and then ADD a single black line in between the two facet grids (i.e., where the current double lines are that are highlighted in yellow).

Any way to do this?  I'd prefer avoiding hard coding the position of any lines, in case the data change.  Thanks.

Body:
Removing the top and bottom grid lines dynamically is relatively easy. You code the line positions in the data set based on the faceting groups and exclude the highest and lowest value, and plot the geom_hline with an xintercept inside the aes() statement. That approach is robust to changing the data (to see that this approach works if you change the data, comment out the # filter(!is.na(birth_year)) line below).

library(tidyverse)
library(grid)

data(starwars)
starwars = starwars %>%
  filter(!is.na(homeworld), !is.na(skin_color)) %>%
  mutate(tatooine = factor(if_else(homeworld == "Tatooine", "Tatooine Native", "Other Native")),
         skin_color = factor(skin_color)) %>%
  # filter(!is.na(birth_year)) %>%
  group_by(tatooine) %>%

  # here we assign the line_positions
  mutate(line_positions = as.numeric(factor(skin_color, levels = unique(skin_color))),
         line_positions = line_positions + .5,
         line_positions = ifelse(line_positions == max(line_positions), NA, line_positions))

plot_out <- ggplot(starwars, aes(birth_year, skin_color)) +
  geom_point(aes(color = gender), size = 4, alpha = 0.7, show.legend = FALSE) +
  geom_hline(aes(yintercept = line_positions)) +
  facet_grid(tatooine ~ ., scales = "free_y", space = "free_y", switch = "y") +
  theme_minimal() +
  theme(
    panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_blank(),
    panel.grid.minor.y = element_line(colour = "black"),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    strip.placement = "outside",
    strip.background = element_rect(fill="gray90", color = "white"),

  )

print(plot_out)

gives

However, adding a solid between the facets without any hardcoding is difficult. There are some possible ways to add borders between facets (see here), but if we don't know whether the facets change it is not obvious to which value the border should be assigned. I guess there is a possible solution with drawing a hard coded line in the plot that divides the facets, but the tricky part is to determine dynamically where that border is going to be located, based on the data and how the facets are ultimately draw (e.g. in which order etc). I'd be interested in hearing other opinions on this.


问:
mapping highlights/annotations to text in pdf
So i have this sample pdf file with three words on separate lines:

```<code>"
hello
there
world
"
</code>```

I have highlighted the word "there" on the second line.  Internally, within the pdf, i'm trying to map the highlight/annotation structure to the text (BT) area.

The section corresponding to the word "there" looks like so:

```<code>BT
/F0 14.6599998 Tf
1 0 0 -1 0 130 Tm
96 0 Td <0057> Tj
4.0719757 0 Td <004B> Tj
8.1511078 0 Td <0048> Tj
8.1511078 0 Td <0055> Tj
4.8806458 0 Td <0048> Tj
ET
</code>```

I also have an annotation section where I have my highlight which has the following rect dimensions:

```<code>18 0 19 15 20 694 21 786 22 853 23 1058 24 1331 [19 0 R 20 0 R]<</AP<</N 10 0 R>>
...
(I left the top part of the annotation out on purpose because it is long.  I extracted what i thought were the most important parts.
Rect[68.0024 690.459 101.054 706.37]
</code>```

I'm kind of confused about how my text is mapped to this one highlight that I have. The coordinates do not seem to match (130 y vs 690 y)?  Am I looking in the right place and interpreting my text and/or highlight annotation coordinates correctly?

Update:

i want to add more info on how I created this test pdf.

Its pretty simple to recreate the pdf. I went to google docs and created an empty document. On three lines i wrote my text as described above. I downloaded that as a pdf and then opened it in adobe acrobat reader DC (the newest one i think). I then used adobe acrobat reader to highlight the specified line and re save it. After that I used some python to unzip the pdf sections.
The python code to decompress the pdf sections:

```<code>import re
import zlib

pdf = open("helloworld.pdf", "rb").read()
stream = re.compile(r'.*?FlateDecode.*?stream(.*?)endstream', re.S)

for s in stream.findall(pdf):
    s = s.strip('\r\n')
    try:
        print(zlib.decompress(s))
        print("")
    except:
        pass
</code>```

答:
Unfortunately the OP only explained how he created his document and did not share the document itself. I followed his instructions but the coordinates of the annotation differ. As I only have this document for explanation, though, the OP will have to mentally adapt the following to the precise numbers in his document.

The starting coordinate system

The starting (default) user coordinate system in the document is implied by the crop box. In the document at hand the crop box is defined as

```<code>/CropBox [0 0 596 843]
</code>```

i.e. the visible page is 596 units wide and 843 units high (given the default user unit of 1/72" this is an A4 format) and the origin is in the lower left corner. x coordinates increase to the right, y coordinate increase upwards. Thus, a coordinate system as usually started with in math, too.

The annotation rectangle

This also is the coordinate system of the annotation rectangle coordinates.

In the case at hand they are

```<code>/Rect [68.0595 741.373 101.138 757.298]
</code>```

i.e. the rectangle with the lower left corner at (68.0595, 741.373) and the upper right at (101.138, 757.298).

Transformations of the coordinate system

In the page content stream up to the text object already identified by the OP the coordinate system gets transformed a number of times.

Mirroring, translation

In the very first line of the page content

```<code>1 0 0 -1 0 843 cm
</code>```

This transformation moves the origin up by 843 units and mirrors (multiplies by -1) the y coordinate.

Thus, now be have a coordinate system with the origin in the upper left and y coordinate increasing downwards.

Scaling

A bit later in the content stream the coordinate system is scaled

```<code>.75062972 0 0 .75062972 0 0 cm
</code>```

Thus, the coordinate units are compressed to about 3/4 of their original width and height, i.e. each unit along the x or y is only 1/96" wide/high.

The text "there"

Only after these transformations have been applied to the coordinate system, the text object identified by the OP is drawn. It starts by setting and changing the text matrix:

```<code>1 0 0 -1 0 130 Tm
</code>```

This sets the text matrix to translate by 130 units in y direction and mirroring y coordinates once again. (Mirroring back again is necessary as otherwise the text would be drawn upside down.)

```<code>96 0 Td
</code>```

This changes the text matrix by moving 96 units along the x axis.

And the starting point where the text is drawn is at the origin of the coordinate system first changed by the mirroring and translation, and then by scaling of the current transformation matrix, and then by mirroring and translation according to the text matrix.

Does it match?

Which coordinate would this point be in the default user coordinate system?

```<code>x = (0 + 96) * .75062972 = 72 (approximately)
y = (((0 * (-1)) + 130) * .75062972) * (-1) + 843 = 745,4 (approximately)
</code>```

This matches with the annotation rectangle (see above) with x coordinates between 68.0595 and 101.138 and y coordinates between 741.373 and 757.298.

So

I'm kind of confused about how my text is mapped to this one highlight that I have. The coordinates do not seem to match (130 y vs 690 y)? Am I looking in the right place and interpreting my text and/or highlight annotation coordinates correctly?

The coordinates do match, you merely have to make sure you apply the transformations of the current transformation matrix and the text matrix.

Body:
So i have this sample pdf file with three words on separate lines:

"
hello
there
world
"

I have highlighted the word "there" on the second line.  Internally, within the pdf, i'm trying to map the highlight/annotation structure to the text (BT) area.

The section corresponding to the word "there" looks like so:

BT
/F0 14.6599998 Tf
1 0 0 -1 0 130 Tm
96 0 Td <0057> Tj
4.0719757 0 Td <004B> Tj
8.1511078 0 Td <0048> Tj
8.1511078 0 Td <0055> Tj
4.8806458 0 Td <0048> Tj
ET

I also have an annotation section where I have my highlight which has the following rect dimensions:

18 0 19 15 20 694 21 786 22 853 23 1058 24 1331 [19 0 R 20 0 R]<</AP<</N 10 0 R>>
...
(I left the top part of the annotation out on purpose because it is long.  I extracted what i thought were the most important parts.
Rect[68.0024 690.459 101.054 706.37]

I'm kind of confused about how my text is mapped to this one highlight that I have. The coordinates do not seem to match (130 y vs 690 y)?  Am I looking in the right place and interpreting my text and/or highlight annotation coordinates correctly?

Update:

i want to add more info on how I created this test pdf.

Its pretty simple to recreate the pdf. I went to google docs and created an empty document. On three lines i wrote my text as described above. I downloaded that as a pdf and then opened it in adobe acrobat reader DC (the newest one i think). I then used adobe acrobat reader to highlight the specified line and re save it. After that I used some python to unzip the pdf sections.
The python code to decompress the pdf sections:

import re
import zlib

pdf = open("helloworld.pdf", "rb").read()
stream = re.compile(r'.*?FlateDecode.*?stream(.*?)endstream', re.S)

for s in stream.findall(pdf):
    s = s.strip('\r\n')
    try:
        print(zlib.decompress(s))
        print("")
    except:
        pass

Body:
Unfortunately the OP only explained how he created his document and did not share the document itself. I followed his instructions but the coordinates of the annotation differ. As I only have this document for explanation, though, the OP will have to mentally adapt the following to the precise numbers in his document.

The starting coordinate system

The starting (default) user coordinate system in the document is implied by the crop box. In the document at hand the crop box is defined as

/CropBox [0 0 596 843]

i.e. the visible page is 596 units wide and 843 units high (given the default user unit of 1/72" this is an A4 format) and the origin is in the lower left corner. x coordinates increase to the right, y coordinate increase upwards. Thus, a coordinate system as usually started with in math, too.

The annotation rectangle

This also is the coordinate system of the annotation rectangle coordinates.

In the case at hand they are

/Rect [68.0595 741.373 101.138 757.298]

i.e. the rectangle with the lower left corner at (68.0595, 741.373) and the upper right at (101.138, 757.298).

Transformations of the coordinate system

In the page content stream up to the text object already identified by the OP the coordinate system gets transformed a number of times.

Mirroring, translation

In the very first line of the page content

1 0 0 -1 0 843 cm

This transformation moves the origin up by 843 units and mirrors (multiplies by -1) the y coordinate.

Thus, now be have a coordinate system with the origin in the upper left and y coordinate increasing downwards.

Scaling

A bit later in the content stream the coordinate system is scaled

.75062972 0 0 .75062972 0 0 cm

Thus, the coordinate units are compressed to about 3/4 of their original width and height, i.e. each unit along the x or y is only 1/96" wide/high.

The text "there"

Only after these transformations have been applied to the coordinate system, the text object identified by the OP is drawn. It starts by setting and changing the text matrix:

1 0 0 -1 0 130 Tm

This sets the text matrix to translate by 130 units in y direction and mirroring y coordinates once again. (Mirroring back again is necessary as otherwise the text would be drawn upside down.)

96 0 Td

This changes the text matrix by moving 96 units along the x axis.

And the starting point where the text is drawn is at the origin of the coordinate system first changed by the mirroring and translation, and then by scaling of the current transformation matrix, and then by mirroring and translation according to the text matrix.

Does it match?

Which coordinate would this point be in the default user coordinate system?

x = (0 + 96) * .75062972 = 72 (approximately)
y = (((0 * (-1)) + 130) * .75062972) * (-1) + 843 = 745,4 (approximately)

This matches with the annotation rectangle (see above) with x coordinates between 68.0595 and 101.138 and y coordinates between 741.373 and 757.298.

So

I'm kind of confused about how my text is mapped to this one highlight that I have. The coordinates do not seem to match (130 y vs 690 y)? Am I looking in the right place and interpreting my text and/or highlight annotation coordinates correctly?

The coordinates do match, you merely have to make sure you apply the transformations of the current transformation matrix and the text matrix.


问:
Does the initialization of a thread object lead to background thread (Android)?
I was searching for days for some information that helps me with Threads. my question is does this statement
Thread th = new Thread()
 leads to having a background  Thread?

Thanks in advance.

答:
To manage background operations you need to use the AsyncTask class .

check this documentation : https://developer.android.com/reference/android/os/AsyncTask.html


问:
Getting alias path of file in swift
I'm having trouble resolving the alias link on mac. I'm checking if the file is an alias and then I would want to receive the original path. Instead I'm only getting a File-Id.
Anly ideas?

```<code>func isFinderAlias(path:String) -> Bool? {

    var isAlias:Bool? = false // Initialize result var.

    // Create a CFURL instance for the given filesystem path.
    // This should never fail, because the existence isn't verified at this point.
    // Note: No need to call CFRelease(fUrl) later, because Swift auto-memory-manages CoreFoundation objects.
    print("path before \(path)");
    let fUrl = CFURLCreateWithFileSystemPath(nil, path, CFURLPathStyle.CFURLPOSIXPathStyle, false)
    print("path furl \(fUrl)");
    // Allocate void pointer - no need for initialization,
    // it will be assigned to by CFURLCopyResourcePropertyForKey() below.
    let ptrPropVal = UnsafeMutablePointer<Void>.alloc(1)

    // Call the CoreFoundation function that copies the desired information as
    // a CFBoolean to newly allocated memory that prt will point to on return.
    if CFURLCopyResourcePropertyForKey(fUrl, kCFURLIsAliasFileKey, ptrPropVal, nil) {

        // Extract the Bool value from the memory allocated.
        isAlias = UnsafePointer<CFBoolean>(ptrPropVal).memory as Bool

        // it will be assigned to by CFURLCopyResourcePropertyForKey() below.
        let ptrDarwin = UnsafeMutablePointer<DarwinBoolean>.alloc(1)

        if ((isAlias) == true){
            if let bookmark = CFURLCreateBookmarkDataFromFile(kCFAllocatorDefault, fUrl, nil){
                let url = CFURLCreateByResolvingBookmarkData(kCFAllocatorDefault, bookmark.takeRetainedValue(), CFURLBookmarkResolutionOptions.CFBookmarkResolutionWithoutMountingMask, nil, nil, ptrDarwin, nil)
                print("getting the path \(url)")
            }
        }

        // Since the CF*() call contains the word "Copy", WE are responsible
        // for destroying (freeing) the memory.
        ptrDarwin.destroy()
        ptrDarwin.dealloc(1)
        ptrPropVal.destroy()
    }

    // Deallocate the pointer
    ptrPropVal.dealloc(1)

    return isAlias
}
</code>```

EDIT:
Both Answers are correct!
I would choose the answer of mklement0 due to the originally not stated requirement that the code run on 10.9 which makes it more flexible

答:
URL variant I need to return nil (not an alias or error) else original - Swift4</p>

```<code>func resolvedFinderAlias() -> URL? {
    if (self.fileReferenceURL() != nil) { // item exists
        do {
            // Get information about the file alias.
            // If the file is not an alias files, an exception is thrown
            // and execution continues in the catch clause.
            let data = try NSURL.bookmarkData(withContentsOf: self as URL)
            // NSURLPathKey contains the target path.
            let rv = NSURL.resourceValues(forKeys: [ URLResourceKey.pathKey ], fromBookmarkData: data)
            var urlString = rv![URLResourceKey.pathKey] as! String
            if !urlString.hasPrefix("file://") {
                urlString = "file://" + urlString
            }
            return URL.init(string: urlString)
        } catch {
            // We know that the input path exists, but treating it as an alias
            // file failed, so we assume it's not an alias file so return nil.
            return nil
        }
    }
    return nil
}
</code>```

Title: Getting alias path of file in swift

Body:
I'm having trouble resolving the alias link on mac. I'm checking if the file is an alias and then I would want to receive the original path. Instead I'm only getting a File-Id.
Anly ideas?

func isFinderAlias(path:String) -> Bool? {

    var isAlias:Bool? = false // Initialize result var.

    // Create a CFURL instance for the given filesystem path.
    // This should never fail, because the existence isn't verified at this point.
    // Note: No need to call CFRelease(fUrl) later, because Swift auto-memory-manages CoreFoundation objects.
    print("path before \(path)");
    let fUrl = CFURLCreateWithFileSystemPath(nil, path, CFURLPathStyle.CFURLPOSIXPathStyle, false)
    print("path furl \(fUrl)");
    // Allocate void pointer - no need for initialization,
    // it will be assigned to by CFURLCopyResourcePropertyForKey() below.
    let ptrPropVal = UnsafeMutablePointer<Void>.alloc(1)

    // Call the CoreFoundation function that copies the desired information as
    // a CFBoolean to newly allocated memory that prt will point to on return.
    if CFURLCopyResourcePropertyForKey(fUrl, kCFURLIsAliasFileKey, ptrPropVal, nil) {

        // Extract the Bool value from the memory allocated.
        isAlias = UnsafePointer<CFBoolean>(ptrPropVal).memory as Bool

        // it will be assigned to by CFURLCopyResourcePropertyForKey() below.
        let ptrDarwin = UnsafeMutablePointer<DarwinBoolean>.alloc(1)

        if ((isAlias) == true){
            if let bookmark = CFURLCreateBookmarkDataFromFile(kCFAllocatorDefault, fUrl, nil){
                let url = CFURLCreateByResolvingBookmarkData(kCFAllocatorDefault, bookmark.takeRetainedValue(), CFURLBookmarkResolutionOptions.CFBookmarkResolutionWithoutMountingMask, nil, nil, ptrDarwin, nil)
                print("getting the path \(url)")
            }
        }

        // Since the CF*() call contains the word "Copy", WE are responsible
        // for destroying (freeing) the memory.
        ptrDarwin.destroy()
        ptrDarwin.dealloc(1)
        ptrPropVal.destroy()
    }

    // Deallocate the pointer
    ptrPropVal.dealloc(1)

    return isAlias
}

EDIT:
Both Answers are correct!
I would choose the answer of mklement0 due to the originally not stated requirement that the code run on 10.9 which makes it more flexible

Body:
URL variant I need to return nil (not an alias or error) else original - Swift4

func resolvedFinderAlias() -> URL? {
    if (self.fileReferenceURL() != nil) { // item exists
        do {
            // Get information about the file alias.
            // If the file is not an alias files, an exception is thrown
            // and execution continues in the catch clause.
            let data = try NSURL.bookmarkData(withContentsOf: self as URL)
            // NSURLPathKey contains the target path.
            let rv = NSURL.resourceValues(forKeys: [ URLResourceKey.pathKey ], fromBookmarkData: data)
            var urlString = rv![URLResourceKey.pathKey] as! String
            if !urlString.hasPrefix("file://") {
                urlString = "file://" + urlString
            }
            return URL.init(string: urlString)
        } catch {
            // We know that the input path exists, but treating it as an alias
            // file failed, so we assume it's not an alias file so return nil.
            return nil
        }
    }
    return nil
}


问:
Syntax highlighting of C function calls in emacs
I use a custom syntax highlighting theme for C in emacs, but I'm missing the possibility of highlighting function calls. For example:

```<code>int func(int foo)
{
    return foo;
}

void main()
{
    int bar = func(3);
}
</code>```

Is there any way to highlight the call to "func" in this example?
It doesn't matter if macros are highlighted too. Keywords like if, switch or sizeof should not match.

Thanks!

答: You can try Ctrl-s for searching or Ctrl-r for searching backward. Emacs will highlight your function for you. </p>

ContentLicense: CC BY-SA 2.5

Body:
I use a custom syntax highlighting theme for C in emacs, but I'm missing the possibility of highlighting function calls. For example:

int func(int foo)
{
    return foo;
}

void main()
{
    int bar = func(3);
}

Is there any way to highlight the call to "func" in this example?
It doesn't matter if macros are highlighted too. Keywords like if, switch or sizeof should not match.

Thanks!


问:
Get the link in the href tags
how can i get the link in the href tags? How i coded it appears the whole 'a' tag...
Code:</p>

```<code>page = urllib2.urlopen('https://www.meetup.com/')
soup = BeautifulSoup(page, 'lxml')

categories = soup.find('ul', class_='gridList')

A = []
B = []

for category in categories.findAll('li'):
    text = category.findAll('h4')
    if len(text) != 0:
        A.append(text[0].find(text = True))

for link in categories.findAll('li'):
    url = link.findAll('a', href=True)
    if len(url) != 0:
        B.append(url)
</code>```

答:
```<code>...
(your code above)
for link in categories.findAll('li'):
    url = link.find('a', href=True)
    if len(url) != 0:
        B.append(url['href'])
</code>```

Title: Get the link in the href tags

Body:
how can i get the link in the href tags? How i coded it appears the whole 'a' tag...
Code:

page = urllib2.urlopen('https://www.meetup.com/')
soup = BeautifulSoup(page, 'lxml')

categories = soup.find('ul', class_='gridList')

A = []
B = []

for category in categories.findAll('li'):
    text = category.findAll('h4')
    if len(text) != 0:
        A.append(text[0].find(text = True))

for link in categories.findAll('li'):
    url = link.findAll('a', href=True)
    if len(url) != 0:
        B.append(url)


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

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

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

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

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

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

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

const data = await getWeather();

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

答:
You'll find bluebird and node.js now come with promisify to allow you to consume Node callbacks as promises when you need too. Alternatively, you can consider a functional reactive approach and use a library like RxJS which will handle promises, node callbacks and other data types into streams.</p>

```<code>const promisify = require('utils').promisify // alternatively use bluebird
const request = require('request-promise');

const weatherFn = promisify(Weather.findOne);

const weatherOptions = {};

async function getWeatherIfDoesNotExist() {

 try {
   const records = await weatherFn(weatherOptions);

   if (records === null) {
     return await request('/pullUrl');
   }

 } catch(err) {
   throw new Error('Could not get weather');
 }
}

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

function altWeatherController(req, res) {

  return getWeatherIfDoesNotExist()
    .then((data) => { // do something })
    .catch((err) => {
      res.set('Content-Type', 'application/json');
      return res.status(200).send('Error occurs: ' + err);
    })
}
</code>```

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

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

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

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

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

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

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

const data = await getWeather();

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

Body:
You'll find bluebird and node.js now come with promisify to allow you to consume Node callbacks as promises when you need too. Alternatively, you can consider a functional reactive approach and use a library like RxJS which will handle promises, node callbacks and other data types into streams.

const promisify = require('utils').promisify // alternatively use bluebird
const request = require('request-promise');

const weatherFn = promisify(Weather.findOne);

const weatherOptions = {};

async function getWeatherIfDoesNotExist() {

 try {
   const records = await weatherFn(weatherOptions);

   if (records === null) {
     return await request('/pullUrl');
   }

 } catch(err) {
   throw new Error('Could not get weather');
 }
}

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

function altWeatherController(req, res) {

  return getWeatherIfDoesNotExist()
    .then((data) => { // do something })
    .catch((err) => {
      res.set('Content-Type', 'application/json');
      return res.status(200).send('Error occurs: ' + err);
    })
}


问:
Turn monitor on/off
How can I make programmatically turn off, on a multi monitor system, the monitor which have nothing active on it, and turn back on when activity is detected, like mouse move?</p>

答:
Short answer you can't.

Long answer: It is theoretically possible, but will require creating your own display driver and GUI library (maybe you can adapt standard one).

Title: Turn monitor on/off


问:
Swift Storyboard error: Unable to backwards deploy Storyboard References for Main.storyboard
We are currently trying to build a Swift ios app, getting a weird error.

/ com.apple.ibtool.warnings / : warning: Unable to validate Storyboard
  References for Main1.storyboard. : warning: Unable to validate
  Storyboard References for Main1.storyboard. / com.apple.ibtool.errors
  / : error: Unable to backwards deploy Storyboard References for
  Main1.storyboard.

what does backwards deploy mean?

答:
you may create storyboard use code, it will show warning. don't care about it.</p>

```<code>storyBoardName = @"MajorTest";
storyBoardName = @"SecondTest";
storyBoardName = @"UIDesign";

self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
self.window.backgroundColor = [UIColor whiteColor];

UIStoryboard* storyBoard = [UIStoryboard storyboardWithName:storyBoardName bundle:nil];
self.window.rootViewController = [storyBoard instantiateInitialViewController];
[self.window makeKeyAndVisible];
</code>```

Body:
you may create storyboard use code, it will show warning. don't care about it.

storyBoardName = @"MajorTest";
storyBoardName = @"SecondTest";
storyBoardName = @"UIDesign";

self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
self.window.backgroundColor = [UIColor whiteColor];

UIStoryboard* storyBoard = [UIStoryboard storyboardWithName:storyBoardName bundle:nil];
self.window.rootViewController = [storyBoard instantiateInitialViewController];
[self.window makeKeyAndVisible];


问:
camel rest dsl - any way to have GET with json body
I'm using camel rest java dsl with jetty component.
Camel version is 2.18.0

The route provides a rest service that consumes json formatted request and produces json response. Doing so using POST is no problem.

But since these routes don't change no data, it would be preferrable to use GET as verb.

Is there any way to accept a json body in the upstream together with GET?

Does it depend on the underlying consumer?

Are there any examples to do so or am I fundamentally wrong in trying so?

Thanx in advance
Henning

答: Jetty component is deprecated as per the docs. You could build your endpoint using camel-restlet component , there you can use the restletMethod to specify the endpoint method.


问:
EF5 create database in .\sqlexpress instead localdb?
I use EF5(code first) & VS2012 in my project.

I try to create tables in LocalDb with migrations.

Enable-Migrations

Add-Migration m1

Ubdate-Database

Every time I find my tables not in LocalDb but in sqlexpress, though i create ConnectionString like this:

```<code>    <add name="StihlDbContext" connectionString="Server=(localdb)\v11.0;Initial    Catalog=StihlDb;Integrated Security=True" providerName="System.Data.SqlClient" />
</code>```

I don't understand why EF create database in .\SQLEXPRESS but not in LocalDb

答:
I encountered the exact same problem. If you had per chance installed EntityFramework in a class library, then you need to set the class library as Startup Project. Otherwise your the connection string in your app.config located in the assembly will not be found and your DbContext instance constructor will have no parameters.

This means that when you run the update-database command in Package Manager Console the database will be created or updated in the default database server, in your case .\SQLExpress

Body:
I use EF5(code first) & VS2012 in my project.

I try to create tables in LocalDb with migrations.

Enable-Migrations

Add-Migration m1

Ubdate-Database

Every time I find my tables not in LocalDb but in sqlexpress, though i create ConnectionString like this:

    <add name="StihlDbContext" connectionString="Server=(localdb)\v11.0;Initial    Catalog=StihlDb;Integrated Security=True" providerName="System.Data.SqlClient" />

I don't understand why EF create database in .\SQLEXPRESS but not in LocalDb


问:
Upon upgrade to chromedriver 2.30, error: cannot parse capability: chromeOptions/cannot parse mobileEmulation/'Apple iPhone 6' must be a valid device
In our Capybara/Rspec suite written in Ruby, we use a special driver to test touch interactions and mobile screen sizes.

This code works in Chromedriver 2.28

our setup in spec/spec_helper.rb

```<code>Capybara.register_driver :chrome_emulating_iphone_6 do |app|
  mobile_emulation = { "deviceName" => "Apple iPhone 6" }
  caps = Selenium::WebDriver::Remote::Capabilities.chrome(
    'chromeOptions' => {
      'mobileEmulation' => mobile_emulation,
      'args' => [ ' --disable-web-security' ]
    }
  )
  Capybara::Selenium::Driver.new(app, :browser => :chrome,
                                 :desired_capabilities => caps)
end
</code>```

The above code worked in Chromedriver 2.28

checking exact version:

```<code>$ chromedriver -v
ChromeDriver 2.28.455517 (2c6d2707d8ea850c862f04ac066724273981e88f)
</code>```

Upon upgrading to Chromedriver 2.30, the code above breaks
the version after upgrading that seems to have broken the spec:

```<code>$ chromedriver -v
ChromeDriver 2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262)
</code>```

the ruby spec fails with:

1) sister selector view Mobile Sister Selector should be on the page
     Failure/Error: visit "/products/boxer-briefs"

```<code> Selenium::WebDriver::Error::UnknownError:
   unknown error: cannot parse capability: chromeOptions
   from unknown error: cannot parse mobileEmulation
   from unknown error: 'Apple iPhone 6' must be a valid device
   from unknown error: must be a valid device
     (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64)
</code>```

答:
Fixed with changing

```<code>mobile_emulation = { "deviceName" => "Apple iPhone 6" }
</code>```

to

```<code>mobile_emulation = { "deviceName" => "iPhone 6" }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In our Capybara/Rspec suite written in Ruby, we use a special driver to test touch interactions and mobile screen sizes.

This code works in Chromedriver 2.28

our setup in spec/spec_helper.rb

Capybara.register_driver :chrome_emulating_iphone_6 do |app|
  mobile_emulation = { "deviceName" => "Apple iPhone 6" }
  caps = Selenium::WebDriver::Remote::Capabilities.chrome(
    'chromeOptions' => {
      'mobileEmulation' => mobile_emulation,
      'args' => [ ' --disable-web-security' ]
    }
  )
  Capybara::Selenium::Driver.new(app, :browser => :chrome,
                                 :desired_capabilities => caps)
end

The above code worked in Chromedriver 2.28

checking exact version:

$ chromedriver -v
ChromeDriver 2.28.455517 (2c6d2707d8ea850c862f04ac066724273981e88f)

Upon upgrading to Chromedriver 2.30, the code above breaks
the version after upgrading that seems to have broken the spec:

$ chromedriver -v
ChromeDriver 2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262)

the ruby spec fails with:

1) sister selector view Mobile Sister Selector should be on the page
     Failure/Error: visit "/products/boxer-briefs"

 Selenium::WebDriver::Error::UnknownError:
   unknown error: cannot parse capability: chromeOptions
   from unknown error: cannot parse mobileEmulation
   from unknown error: 'Apple iPhone 6' must be a valid device
   from unknown error: must be a valid device
     (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64)

Body:
Fixed with changing

mobile_emulation = { "deviceName" => "Apple iPhone 6" }

to

mobile_emulation = { "deviceName" => "iPhone 6" }


问:
What does the following Array initialization syntax actually create?
What does the following actually create?

I ask because it cannot be enumerated with Array#foreach and it is represented (misleadingly?) in Chrome console as [undefined x 10].

```<code>const arr = new Array(10);
</code>```

答:
The Array constructor when supplied with a single integer value creates an Array instance with the length own-property set to that value.

Host environments like browsers can choose to render this as they choose. V8 chooses [undefined x 10] which is misleading because it implies there are ten instances of the predefined undefined value in an ordered sequence.

This is not the case.

Array#foreach, Array#map use the enumerable integer indices AND the length own-property value to enumerate the values of an array.

Because this specific Array constructor syntax does not initialize any integer properties on the Array object, they fail to enumerate Arrays initialized in this manner.

I can only presume that this syntax is soley present to enable code patterns that rely on the length own-property of the Array instance  WITHOUT needing any keys or values to be initialized.

Body:
What does the following actually create?

I ask because it cannot be enumerated with Array#foreach and it is represented (misleadingly?) in Chrome console as [undefined x 10].

const arr = new Array(10);


问:
Angular Dependancy Injection
I have a quick question about Angular Dependancy Injection. I have read that if you want a service to have only a single instance across your app, it should be included as a provider in the AppModule instead of any components that use it. Would this still apply other modules imported by the AppModule. For example, I want to have an AuthService as a provider in my SharedModule. If I then import this module to the AppModule, would all the components across my app share the same instance of the service?</p>

答:
No, you can't use the NgModule imports/exports to enforce a singleton pattern. As pointed out by echonax's answer lazy loaded modules bootstrap all services again.

With that said, you can block duplicate imports on a module via the constructor. This will force the developer to manage the module load order, and also prevent a lazy module from importing it directly. If the module is imported by a secondary module it appears to get around this problem.

You can block like this in your NgModule class constructor

```<code>@NgModule({
    providers: [
        MySingletonService
    ]
})
export class ExampleModule {
    public constructor(@Optional() @SkipSelf() parentModule: ExampleModule) {
        if (parentModule) {
            throw new Error('ExampleModule is already loaded');
        }
    }
}
</code>```

It's best to create modules that have just one service in them, and not use them for anything else. That makes it much easier to manage the kinds of dependencies.

Title: Angular Dependancy Injection

Body:
No, you can't use the NgModule imports/exports to enforce a singleton pattern. As pointed out by echonax's answer lazy loaded modules bootstrap all services again.

With that said, you can block duplicate imports on a module via the constructor. This will force the developer to manage the module load order, and also prevent a lazy module from importing it directly. If the module is imported by a secondary module it appears to get around this problem.

You can block like this in your NgModule class constructor

@NgModule({
    providers: [
        MySingletonService
    ]
})
export class ExampleModule {
    public constructor(@Optional() @SkipSelf() parentModule: ExampleModule) {
        if (parentModule) {
            throw new Error('ExampleModule is already loaded');
        }
    }
}

It's best to create modules that have just one service in them, and not use them for anything else. That makes it much easier to manage the kinds of dependencies.


问:
Query to display all tablespaces in a database and datafiles
How to write a query to display all tablespaces in database suppose db and it's corresponding datafiles belong to user SCOTT. I can connect to SCOTT account and see it but I like to connect to sys as sysdba to see all tablespaces and datafiles belong to SCOTT.</p>

答:
In oracle, generally speaking, there are number of facts that I will mention in following section:

Each database can have many Schema/User (Logical division).

Each database can have many tablespaces (Logical division).

A schema is the set of objects (tables, indexes, views, etc) that belong to a user.

In Oracle, a user can be considered the same as a schema.

A database is divided into logical storage units called tablespaces, which group related logical structures together. For example, tablespaces commonly group all of an application’s objects to simplify some administrative operations. You may have a tablespace for application data and an additional  one for application indexes.

Therefore, your question, "to see all tablespaces and datafiles belong to SCOTT" is s bit wrong.

However, there are some DBA views encompass information about all database objects, regardless of the owner. Only users with DBA privileges can access these views:
DBA_DATA_FILES, DBA_TABLESPACES, DBA_FREE_SPACE, DBA_SEGMENTS.

So, connect to your DB as sysdba and run query through these helpful views.
For example this query can help you to find all tablespaces and their data files that objects of your user are located:

```<code>SELECT DISTINCT sgm.TABLESPACE_NAME , dtf.FILE_NAME
FROM DBA_SEGMENTS sgm
JOIN DBA_DATA_FILES dtf ON (sgm.TABLESPACE_NAME = dtf.TABLESPACE_NAME)
WHERE sgm.OWNER = 'SCOTT'
</code>```

Body:
In oracle, generally speaking, there are number of facts that I will mention in following section:

Each database can have many Schema/User (Logical division).

Each database can have many tablespaces (Logical division).

A schema is the set of objects (tables, indexes, views, etc) that belong to a user.

In Oracle, a user can be considered the same as a schema.

A database is divided into logical storage units called tablespaces, which group related logical structures together. For example, tablespaces commonly group all of an application’s objects to simplify some administrative operations. You may have a tablespace for application data and an additional  one for application indexes.

Therefore, your question, "to see all tablespaces and datafiles belong to SCOTT" is s bit wrong.

However, there are some DBA views encompass information about all database objects, regardless of the owner. Only users with DBA privileges can access these views:
DBA_DATA_FILES, DBA_TABLESPACES, DBA_FREE_SPACE, DBA_SEGMENTS.

So, connect to your DB as sysdba and run query through these helpful views.
For example this query can help you to find all tablespaces and their data files that objects of your user are located:

SELECT DISTINCT sgm.TABLESPACE_NAME , dtf.FILE_NAME
FROM DBA_SEGMENTS sgm
JOIN DBA_DATA_FILES dtf ON (sgm.TABLESPACE_NAME = dtf.TABLESPACE_NAME)
WHERE sgm.OWNER = 'SCOTT'


问:
JAVAME: Sort Java Vector
What would be the best and most efficient way to sort a Java Vector in JAVAME.

My object has five properties, and I would like to sort by a property called price which is of type double. In my Vector I will have a maximum of 150 items. A sample code would be appreciated.

Thanx for your time.

答:
Adjusted code from JavaSE:</p>

```<code>public static void sort(List<YourObject> list) {
    Object[] a = list.toArray();
    sort(a);
    ListIterator<YourObject> i = list.listIterator();
    for (int j=0; j<a.length; j++) {
        i.next();
        i.set((YourObject)a[j]);
    }
}

public static void sort(YourObject[] a) {
    YourObject[] aux = (YourObject[])a.clone();
    mergeSort(aux, a, 0, a.length, 0);
}

private static void mergeSort(YourObject[] src,
              YourObject[] dest,
              int low,
              int high,
              int off) {
int length = high - low;

// Insertion sort on smallest arrays
    if (length < INSERTIONSORT_THRESHOLD) {
        for (int i=low; i<high; i++)
            for (int j=i; j>low &&
         dest[j-1].getPrice()-dest[j].getPrice()>0; j--)
                swap(dest, j, j-1);
        return;
    }

    // Recursively sort halves of dest into src
    int destLow  = low;
    int destHigh = high;
    low  += off;
    high += off;
    int mid = (low + high) >>> 1;
    mergeSort(dest, src, low, mid, -off);
    mergeSort(dest, src, mid, high, -off);

    // If list is already sorted, just copy from src to dest.  This is an
    // optimization that results in faster sorts for nearly ordered lists.
    if (src[mid-1].getPrice()-src[mid].getPrice() <= 0) {
        System.arraycopy(src, low, dest, destLow, length);
        return;
    }

    // Merge sorted halves (now in src) into dest
    for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
        if (q >= high || p < mid && src[p].getPrice()-src[q].getPrice()<=0)
            dest[i] = src[p++];
        else
            dest[i] = src[q++];
    }
}
</code>```

Title: JAVAME: Sort Java Vector

Body:
Adjusted code from JavaSE:

public static void sort(List<YourObject> list) {
    Object[] a = list.toArray();
    sort(a);
    ListIterator<YourObject> i = list.listIterator();
    for (int j=0; j<a.length; j++) {
        i.next();
        i.set((YourObject)a[j]);
    }
}

public static void sort(YourObject[] a) {
    YourObject[] aux = (YourObject[])a.clone();
    mergeSort(aux, a, 0, a.length, 0);
}

private static void mergeSort(YourObject[] src,
              YourObject[] dest,
              int low,
              int high,
              int off) {
int length = high - low;

// Insertion sort on smallest arrays
    if (length < INSERTIONSORT_THRESHOLD) {
        for (int i=low; i<high; i++)
            for (int j=i; j>low &&
         dest[j-1].getPrice()-dest[j].getPrice()>0; j--)
                swap(dest, j, j-1);
        return;
    }

    // Recursively sort halves of dest into src
    int destLow  = low;
    int destHigh = high;
    low  += off;
    high += off;
    int mid = (low + high) >>> 1;
    mergeSort(dest, src, low, mid, -off);
    mergeSort(dest, src, mid, high, -off);

    // If list is already sorted, just copy from src to dest.  This is an
    // optimization that results in faster sorts for nearly ordered lists.
    if (src[mid-1].getPrice()-src[mid].getPrice() <= 0) {
        System.arraycopy(src, low, dest, destLow, length);
        return;
    }

    // Merge sorted halves (now in src) into dest
    for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
        if (q >= high || p < mid && src[p].getPrice()-src[q].getPrice()<=0)
            dest[i] = src[p++];
        else
            dest[i] = src[q++];
    }
}


问:
Can anyone tell me what the 'for' line code of this program does, I dont understand the 2nd part of it with the question mark
```<code>#include<stdio.h>
#include<stdlib.h>

int main ()
{
    int x, i=2, k=1;

    for (x=15; x%i ? ++i : ++k, 1<x ; x-- , i++)
    {
        x -= k+i;
        i++;
        printf("X = %d , I = %d , K = %d\n",x,i,k);
    }
    switch(x) {
        case 2: printf("Display 2.\n");
        case 5: printf("Display 5.\n");
        case 0: printf("Display 0.\n");
                break;
        default:
            printf("Display default\n");
    }
system("pause");
    return 0;
}
</code>```

Can anyone tell me what the 'for' line code of this program does, I dont understand the 2nd part of it with the question mark

答: That is the ternary operator.  Google on that for more detail, but basically, if the part to the left of the ? is true, the whole expression evaluates to the value on the left of the :. If the part to the left of the ? is false, then the whole expression evaluates to the value on the right of the :.

Body:
#include<stdio.h>
#include<stdlib.h>

int main ()
{
    int x, i=2, k=1;

    for (x=15; x%i ? ++i : ++k, 1<x ; x-- , i++)
    {
        x -= k+i;
        i++;
        printf("X = %d , I = %d , K = %d\n",x,i,k);
    }
    switch(x) {
        case 2: printf("Display 2.\n");
        case 5: printf("Display 5.\n");
        case 0: printf("Display 0.\n");
                break;
        default:
            printf("Display default\n");
    }
system("pause");
    return 0;
}

Can anyone tell me what the 'for' line code of this program does, I dont understand the 2nd part of it with the question mark


问:
XAML code to put button in bottom right corner
I'm trying to get my floating action button in the bottom left corner of my application.

Currently it looks like this:

And I want it to look like this:

My XAML code:

```<code><?xml version="1.0" encoding="utf-8" ?>
 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:xxx;assembly=xxx"
         x:Class="xxx.xxx.xxx.xxxx">

 <AbsoluteLayout HorizontalOptions="FillAndExpand"  VerticalOptions="FillAndExpand">

    <StackLayout AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1">

        <StackLayout Orientation="Vertical" VerticalOptions="StartAndExpand">
            <StackLayout HorizontalOptions="CenterAndExpand"  Margin="0,15,0,0" Orientation="Vertical">
                <!--<local:CustomImage Source="logo.png" HeightRequest="100" WidthRequest="100" HorizontalOptions="Center" />-->

                <local:CustomImageButton  WidthRequest="150" Image="Foto.png" ClassId="Eigendommen" x:Name="buttonFoto" HeightRequest="150"/>

            </StackLayout>

            <StackLayout Orientation="Vertical" VerticalOptions="CenterAndExpand" Margin="10,0,0,0" x:Name="MainStack" >
                <BoxView BackgroundColor="#F15A35" HeightRequest="1" WidthRequest="400" Margin="0,-2,0,5" />
                <Label Text="Toegevoegd:" FontSize="Medium" FontAttributes="Bold" />
                <StackLayout Orientation="Horizontal">
                    <StackLayout Orientation="Vertical"  IsVisible="False" Margin="10,0,10,0" x:Name="hideImage1">
                        <local:CustomImage HeightRequest="100" WidthRequest="100"/>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="Verwijderen" FontSize="Small" VerticalTextAlignment="Center" />
                            <local:CustomImageButton Image="close_zwart.png" BackgroundColor="White" Clicked="Hide_Image_Click" HeightRequest="40" WidthRequest="40" />
                        </StackLayout>
                    </StackLayout>
                    <StackLayout Orientation="Vertical" Margin="10,0,10,0" x:Name="hideImage2" IsVisible="False">
                        <local:CustomImage HeightRequest="100" WidthRequest="100"/>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="Verwijderen" FontSize="Small" VerticalTextAlignment="Center" />
                            <local:CustomImageButton Image="close_zwart.png" Clicked="Hide_Image_Click" BackgroundColor="White" HeightRequest="40" WidthRequest="40" />
                        </StackLayout>
                    </StackLayout>
                    <StackLayout Orientation="Vertical" Margin="10,0,10,0" x:Name="hideImage3" IsVisible="False">
                        <local:CustomImage HeightRequest="100" WidthRequest="100"/>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="Verwijderen" FontSize="Small" VerticalTextAlignment="Center" />
                            <local:CustomImageButton Image="close_zwart.png" Clicked="Hide_Image_Click" BackgroundColor="White" HeightRequest="40" WidthRequest="40" />
                        </StackLayout>
                    </StackLayout>
                </StackLayout>

            </StackLayout>

        </StackLayout>

    </StackLayout>

    <StackLayout
             AbsoluteLayout.LayoutFlags="All"
             AbsoluteLayout.LayoutBounds="1,1,0.25,0.25">

        <StackLayout HorizontalOptions="End" VerticalOptions="End" Margin="0,0,0,0">
            <local:FloatingActionButton Image="checktaak.png" x:Name="insertTaak"  HeightRequest="60" WidthRequest="60" />
        </StackLayout>

    </StackLayout>

</AbsoluteLayout>

</ContentPage>
</code>```

You can find the my floating action button at the bottom of all the code ( the last stacklayout). if you need more code let me know in the comments.
Edit I want the button always there even if it overlaps a other stacklayout

答:
Found it!

Just had to tweak the layoutbounds a little, I didn't knew I could go over 1.
This is my new layoutbound for the stacklayout that includes the fab:

```<code> AbsoluteLayout.LayoutBounds="0.94,1.18,0.5,0.25"
</code>```

Body:
I'm trying to get my floating action button in the bottom left corner of my application.

Currently it looks like this:

And I want it to look like this:

My XAML code:

<?xml version="1.0" encoding="utf-8" ?>
 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:xxx;assembly=xxx"
         x:Class="xxx.xxx.xxx.xxxx">

 <AbsoluteLayout HorizontalOptions="FillAndExpand"  VerticalOptions="FillAndExpand">

    <StackLayout AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1">

        <StackLayout Orientation="Vertical" VerticalOptions="StartAndExpand">
            <StackLayout HorizontalOptions="CenterAndExpand"  Margin="0,15,0,0" Orientation="Vertical">

                <local:CustomImageButton  WidthRequest="150" Image="Foto.png" ClassId="Eigendommen" x:Name="buttonFoto" HeightRequest="150"/>

            </StackLayout>

            <StackLayout Orientation="Vertical" VerticalOptions="CenterAndExpand" Margin="10,0,0,0" x:Name="MainStack" >
                <BoxView BackgroundColor="#F15A35" HeightRequest="1" WidthRequest="400" Margin="0,-2,0,5" />

                <StackLayout Orientation="Horizontal">
                    <StackLayout Orientation="Vertical"  IsVisible="False" Margin="10,0,10,0" x:Name="hideImage1">
                        <local:CustomImage HeightRequest="100" WidthRequest="100"/>
                        <StackLayout Orientation="Horizontal">

                            <local:CustomImageButton Image="close_zwart.png" BackgroundColor="White" Clicked="Hide_Image_Click" HeightRequest="40" WidthRequest="40" />
                        </StackLayout>
                    </StackLayout>
                    <StackLayout Orientation="Vertical" Margin="10,0,10,0" x:Name="hideImage2" IsVisible="False">
                        <local:CustomImage HeightRequest="100" WidthRequest="100"/>
                        <StackLayout Orientation="Horizontal">

                            <local:CustomImageButton Image="close_zwart.png" Clicked="Hide_Image_Click" BackgroundColor="White" HeightRequest="40" WidthRequest="40" />
                        </StackLayout>
                    </StackLayout>
                    <StackLayout Orientation="Vertical" Margin="10,0,10,0" x:Name="hideImage3" IsVisible="False">
                        <local:CustomImage HeightRequest="100" WidthRequest="100"/>
                        <StackLayout Orientation="Horizontal">

                            <local:CustomImageButton Image="close_zwart.png" Clicked="Hide_Image_Click" BackgroundColor="White" HeightRequest="40" WidthRequest="40" />
                        </StackLayout>
                    </StackLayout>
                </StackLayout>

            </StackLayout>

        </StackLayout>

    </StackLayout>

    <StackLayout
             AbsoluteLayout.LayoutFlags="All"
             AbsoluteLayout.LayoutBounds="1,1,0.25,0.25">

        <StackLayout HorizontalOptions="End" VerticalOptions="End" Margin="0,0,0,0">
            <local:FloatingActionButton Image="checktaak.png" x:Name="insertTaak"  HeightRequest="60" WidthRequest="60" />
        </StackLayout>

    </StackLayout>

</AbsoluteLayout>

</ContentPage>

You can find the my floating action button at the bottom of all the code ( the last stacklayout). if you need more code let me know in the comments.
Edit I want the button always there even if it overlaps a other stacklayout

Body:
Found it!

Just had to tweak the layoutbounds a little, I didn't knew I could go over 1.
This is my new layoutbound for the stacklayout that includes the fab:

 AbsoluteLayout.LayoutBounds="0.94,1.18,0.5,0.25"


问:
Refactoring Backgroundworker to async/await
I've always used the Backgroundworker and I'm new to async/await keywords. Right now I'm trying to refactor some code from Backgroundworker to async/await (It's a WPF MVVM app).

I got a Command in my vm, which is instantiated like this:

```<code>GenerateCommand = new DelegateCommand(GenerateHandler, CanGenerate);
</code>```

I've seen there is an 'AsyncCommand' in the dev express lib, which will probably work for me.

All the handler does is register an eventhandler to the finished event and call the Generate method on a service.

```<code>private void GenerateHandler()
{
  generatorService.GenerationFinished += OnGenerationFinished;
  generatorService.Generate(mDataFields, mGenerateFilesViewModel, mAmount);
}
</code>```

Then the Generate method of the service starts a BackGroundWorker:

```<code>public void Generate(IEnumerable<IDataField> dataFields, IGenerateFilesViewModel generateFilesViewModel, int amount)
{
  BackgroundWorker worker = new BackgroundWorker();
  worker.DoWork += worker_DoWork;
  worker.RunWorkerAsync();
}
</code>```

The DoWork method does the time consuming task

```<code>private void worker_DoWork(object sender, DoWorkEventArgs e)
{
  GenerateCommand generateCommand = null;
  if (mUploadFiles)
  {
    generateCommand = new GenerateCommand(mDataFields, mOutputDirectory, mTemplateFileName, mAmount, mSelectedCollection, mSelectedAccountKey);
  }
  else
  {
    generateCommand = new GenerateCommand(mDataFields, mOutputDirectory, mTemplateFileName, mAmount);
  }

  try
  {
    generateCommand.Execute();
  }
  catch (SEHException ex)
  {
    Console.WriteLine(String.Format("Generation of files threw an exception. {0}", ex.Message));
  }
}
</code>```

I'm unsure which method I have to mark with the async keyword now and where I have to await for my async method. I tryed to mark the worker_DoWork as async and  await the call in the Generate method, but then the Generate method has to be marked as async too in order to be awaitable in the GenerateHandler of the vm?

Sorry if I'm confusing you, but all this is confusing me abit...

thanks for the help

答:
I don't think this is a good practice but it works just fine for me:</p>

```<code>    void Something()
    {
     if (!mybworker.IsBusy())
     {
      mybworker.RunWorkerAsync();
     }
    while (mybworker.IsBusy())
    {
     Application.DoEvents();
    }
   }
</code>```

Body:
I've always used the Backgroundworker and I'm new to async/await keywords. Right now I'm trying to refactor some code from Backgroundworker to async/await (It's a WPF MVVM app).

I got a Command in my vm, which is instantiated like this:

GenerateCommand = new DelegateCommand(GenerateHandler, CanGenerate);

I've seen there is an 'AsyncCommand' in the dev express lib, which will probably work for me.

All the handler does is register an eventhandler to the finished event and call the Generate method on a service.

private void GenerateHandler()
{
  generatorService.GenerationFinished += OnGenerationFinished;
  generatorService.Generate(mDataFields, mGenerateFilesViewModel, mAmount);
}

Then the Generate method of the service starts a BackGroundWorker:

public void Generate(IEnumerable<IDataField> dataFields, IGenerateFilesViewModel generateFilesViewModel, int amount)
{
  BackgroundWorker worker = new BackgroundWorker();
  worker.DoWork += worker_DoWork;
  worker.RunWorkerAsync();
}

The DoWork method does the time consuming task

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
  GenerateCommand generateCommand = null;
  if (mUploadFiles)
  {
    generateCommand = new GenerateCommand(mDataFields, mOutputDirectory, mTemplateFileName, mAmount, mSelectedCollection, mSelectedAccountKey);
  }
  else
  {
    generateCommand = new GenerateCommand(mDataFields, mOutputDirectory, mTemplateFileName, mAmount);
  }

  try
  {
    generateCommand.Execute();
  }
  catch (SEHException ex)
  {
    Console.WriteLine(String.Format("Generation of files threw an exception. {0}", ex.Message));
  }
}

I'm unsure which method I have to mark with the async keyword now and where I have to await for my async method. I tryed to mark the worker_DoWork as async and  await the call in the Generate method, but then the Generate method has to be marked as async too in order to be awaitable in the GenerateHandler of the vm?

Sorry if I'm confusing you, but all this is confusing me abit...

thanks for the help

Body:
I don't think this is a good practice but it works just fine for me:

    void Something()
    {
     if (!mybworker.IsBusy())
     {
      mybworker.RunWorkerAsync();
     }
    while (mybworker.IsBusy())
    {
     Application.DoEvents();
    }
   }


问:
Linking Libraries in Xcode
I'm using a powerbook (osx 10.5) and recently downloaded and installed FFTW 3.2 (link text). I've been able to compile and run some simple programs based on the online tutorial using the terminal:

```<code>g++ main.cpp -lfftw3 -lm
</code>```

However, I can't get the same program to compile in Xcode. I get a linking error, "symbol(s) not found". There is a file called libfftw3.a in /usr/local/lib. How can this be linked?  Furthermore, apparently the libraries have to be linked in a particular order, i.e. see: link text

thanks for any help

答:
To link to a .a library like this in Xcode you need to:

Double-click on your target or application in Xcode to open the Info window

Switch to the "Build" tab

Add -lfftw3 to "Other Linker Flags" (under "Linking")

Add the path to your library to the "Library Search Paths" (under "Search Paths"). In your case this will be /usr/local/lib

We use FFTW (it's great by the way), this works for us!

OwnerDisplayName: Dan

Title: Linking Libraries in Xcode

Body:
I'm using a powerbook (osx 10.5) and recently downloaded and installed FFTW 3.2 (link text). I've been able to compile and run some simple programs based on the online tutorial using the terminal:

g++ main.cpp -lfftw3 -lm

However, I can't get the same program to compile in Xcode. I get a linking error, "symbol(s) not found". There is a file called libfftw3.a in /usr/local/lib. How can this be linked?  Furthermore, apparently the libraries have to be linked in a particular order, i.e. see: link text

thanks for any help

OwnerDisplayName: Bids


问:
PHP forms which contain the £-sign as data, and the £ is convertrd to Â£ in the sent email msgsage?
Why is a £ symbol in a PHP form entry converted to Â£ in the sent email message?  How can I get it to send just the £ symbol?</p>

答:
This is because your e-mail is not correctly encoded.

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

```<code>$headers = "Content-Type: text/html; charset=UTF-8";
</code>```

If you use native mail() function $headers array will be the 4th parameter
mail($to, $subject, $message, $headers)

Body:
This is because your e-mail is not correctly encoded.

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

$headers = "Content-Type: text/html; charset=UTF-8";

If you use native mail() function $headers array will be the 4th parameter
mail($to, $subject, $message, $headers)


答:
```<code>x%i ?< ++i : ++k
</code>```

means :

```<code>int iterate(){
    if( x%i == 1 ) {
     return ++i;
    }else{
     return ++k;
    }
}

for (x = 15; iterate() ; 1...)
</code>```

Title: Can anyone tell me what the 'for' line code of this program does, I dont understand the 2nd part of it with the question mark

Body:
x%i ?< ++i : ++k

means :

int iterate(){
    if( x%i == 1 ) {
     return ++i;
    }else{
     return ++k;
    }
}

for (x = 15; iterate() ; 1...)


问:
c++11 regex lookahead exclude word
I have a string list:

ReferencePrice

ReferenceCurrentPrice

CostPrice

AverageCostPrice
...

I want to filter out all strings that:

Containing 'Price',

But not containing 'CostPrice'

My regex is '(?!Cost)Price', but it can match the 3rd string 'CostPrice', why? and what is the correct regex?

After some investigation, I know what 'lookahead' means. It means look right, so similarly lookbehind means look left.

The correct regex should be a negative lookbehind regex:

```<code>(?<!Cost)Price
</code>```

Try it: https://regex101.com/r/m3238r/1

Unfortunately, c++11 doesn't support lookbehind. Boost regex does.
http://www.boost.org/doc/libs/1_50_0/libs/regex/doc/html/boost_regex/syntax/perl_syntax.html

答:
Having to take of soon, I'll answer with an (in my opinion) silly solution (there must be much better ones :P).

```<code>((?!Cost)....|^.{0,3})Price
</code>```

If preceded by 4 characters (atleast), make sure it isn't Cost. Alternatively, make sure there aren't more than 3 characters preceding Price.

See it here at regex101.

Title: c++11 regex lookahead exclude word

Body:
I have a string list:

ReferencePrice

ReferenceCurrentPrice

CostPrice

AverageCostPrice
...

I want to filter out all strings that:

Containing 'Price',

But not containing 'CostPrice'

My regex is '(?!Cost)Price', but it can match the 3rd string 'CostPrice', why? and what is the correct regex?

After some investigation, I know what 'lookahead' means. It means look right, so similarly lookbehind means look left.

The correct regex should be a negative lookbehind regex:

(?<!Cost)Price

Try it: https://regex101.com/r/m3238r/1

Unfortunately, c++11 doesn't support lookbehind. Boost regex does.
http://www.boost.org/doc/libs/1_50_0/libs/regex/doc/html/boost_regex/syntax/perl_syntax.html

Body:
Having to take of soon, I'll answer with an (in my opinion) silly solution (there must be much better ones :P).

((?!Cost)....|^.{0,3})Price

If preceded by 4 characters (atleast), make sure it isn't Cost. Alternatively, make sure there aren't more than 3 characters preceding Price.

See it here at regex101.


问:
awk multiplication of all rows in a table with first row of the table
I have a table with several columns and I want to multiply all rows in the table with the values of the first row (column by column).

Table:

```<code>0,140   0,130   0,140   0,150   0,160 <- values to be used for multiplication
1,270   1,190   6,080   3,760   2,810
1,290   1,140   6,110   3,900   3,050
1,370   1,160   6,310   4,030   3,020
1,370   1,150   6,500   3,970   3,070
</code>```

Result:

```<code>0,178   0,155   0,851   0,564   0,450
0,181   0,148   0,855   0,585   0,488
0,192   0,151   0,883   0,605   0,483
0,192   0,150   0,910   0,596   0,491
</code>```

I have some experience with awk but I couldn't figure out the solution.

Body:
I have a table with several columns and I want to multiply all rows in the table with the values of the first row (column by column).

Table:

0,140   0,130   0,140   0,150   0,160 <- values to be used for multiplication
1,270   1,190   6,080   3,760   2,810
1,290   1,140   6,110   3,900   3,050
1,370   1,160   6,310   4,030   3,020
1,370   1,150   6,500   3,970   3,070

Result:

0,178   0,155   0,851   0,564   0,450
0,181   0,148   0,855   0,585   0,488
0,192   0,151   0,883   0,605   0,483
0,192   0,150   0,910   0,596   0,491

I have some experience with awk but I couldn't figure out the solution.

Body:
$ awk 'NR==1{split($0,m);CONVFMT="%.3f";next} {for (i=1;i<=NF;i++) $i=$i*m[i]} 1' file
0.178 0.155 0.851 0.564 0.450
0.181 0.148 0.855 0.585 0.488
0.192 0.151 0.883 0.605 0.483
0.192 0.149 0.910 0.596 0.491

I used .s instead of ,s in my sample as that's what my locale uses for decimal point.