问:
How to display a variable in my info window on Google Maps
I want to display my "double CO2Data" in my textView in my info window. I am not sure where and how I write that code. Does anyone have any tips or ideas on how to do that?

My MapsActivity:

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private boolean initiateApp;
double CO2data = 1.02;
double N2data = 0.002;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }
    // 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);
    initiateApp = true;

}

/**
 * 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.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }
}

/* Here we create the infoWindow **/
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();

    mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

        public View getInfoWindow(Marker arg0) {
            View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);

            return v;
        }

        public View getInfoContents(Marker arg0) {

            //View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);

            return null;

        }
    });

}

@Override
public void onConnected(Bundle bundle) {

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(0);
    mLocationRequest.setFastestInterval(0);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    //Place current location marker
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mMap.addMarker(markerOptions);
    mCurrLocationMarker.showInfoWindow();

    Log.d("ADebugTag", "Value: " + Double.toString(location.getLatitude()));
    Log.d("ADebugTag", "Value: " + Double.toString(location.getLongitude()));

    //move map camera

    if(initiateApp){
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
    }
    initiateApp = false;

    boolean contains = mMap.getProjection()
            .getVisibleRegion()
            .latLngBounds
            .contains(latLng);

    if(!contains){
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    }

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Asking user if explanation is needed
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

            //Prompt the user once explanation has been shown
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);

        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted. Do the
                // contacts-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }

            } else {

                // Permission denied, Disable the functionality that depends on this permission.
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

        // other 'case' lines to check for other permissions this app might request.
        // You can add here other case statements according to your requirement.
    }
}
}
</code>```

My custom infowindow xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="110dp"
android:layout_height="110dp"
android:orientation="vertical"
android:gravity="center"
>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/infoText"
        android:textColor="#000000"
        android:padding="10dp"
        android:layout_centerInParent="true"
        android:background="#ffffff"
        />

</RelativeLayout>

</LinearLayout>
</code>```

The code that I used to for the info window

```<code>mMap.setInfoWindowAdapter(new InfoWindowAdapter() {

public View getInfoWindow(Marker arg0) {
    View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);
    return v;
}

public View getInfoContents(Marker arg0) {

    //View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);

    return null;

}
});
</code>```

答:
Change your info window content code, right now you are returning null I guess</p>

```<code>public View getInfoContents(Marker arg0) {

    View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);
    TextView tv = (TextView) v.findViewById(R.id.infoText);
    tv.setText(String.valueOf(CO2data));

    return v;

}
</code>```

Body:
I want to display my "double CO2Data" in my textView in my info window. I am not sure where and how I write that code. Does anyone have any tips or ideas on how to do that?

My MapsActivity:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private boolean initiateApp;
double CO2data = 1.02;
double N2data = 0.002;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }
    // 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);
    initiateApp = true;

}

/**
 * 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.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }
}

/* Here we create the infoWindow **/
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();

    mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

        public View getInfoWindow(Marker arg0) {
            View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);

            return v;
        }

        public View getInfoContents(Marker arg0) {

            //View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);

            return null;

        }
    });

}

@Override
public void onConnected(Bundle bundle) {

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(0);
    mLocationRequest.setFastestInterval(0);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    //Place current location marker
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mMap.addMarker(markerOptions);
    mCurrLocationMarker.showInfoWindow();

    Log.d("ADebugTag", "Value: " + Double.toString(location.getLatitude()));
    Log.d("ADebugTag", "Value: " + Double.toString(location.getLongitude()));

    //move map camera

    if(initiateApp){
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
    }
    initiateApp = false;

    boolean contains = mMap.getProjection()
            .getVisibleRegion()
            .latLngBounds
            .contains(latLng);

    if(!contains){
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    }

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Asking user if explanation is needed
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

            //Prompt the user once explanation has been shown
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);

        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted. Do the
                // contacts-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }

            } else {

                // Permission denied, Disable the functionality that depends on this permission.
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

        // other 'case' lines to check for other permissions this app might request.
        // You can add here other case statements according to your requirement.
    }
}
}

My custom infowindow xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="110dp"
android:layout_height="110dp"
android:orientation="vertical"
android:gravity="center"
>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/infoText"
        android:textColor="#000000"
        android:padding="10dp"
        android:layout_centerInParent="true"
        android:background="#ffffff"
        />

</RelativeLayout>

</LinearLayout>

The code that I used to for the info window

mMap.setInfoWindowAdapter(new InfoWindowAdapter() {

public View getInfoWindow(Marker arg0) {
    View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);
    return v;
}

public View getInfoContents(Marker arg0) {

    //View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);

    return null;

}
});

Body:
Change your info window content code, right now you are returning null I guess

public View getInfoContents(Marker arg0) {

    View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);
    TextView tv = (TextView) v.findViewById(R.id.infoText);
    tv.setText(String.valueOf(CO2data));

    return v;

}


来源: stackexchange

问:
Hidden app icon on iOS launcher
How can i hidden app icon on iOS, I develop App for Enterprise, there are two Apps，for some reason，I need to hidden App A's icon form launcher, make it only can be open in App B.

Because Apps will not distribution on App store, any private API can be used. Is there any way to achieve this？

答:
If you archive your application for enterprise distribution, you are asked to provide additional information in a manifest.plist:

The App URL is not really important, most of the time you just enter "https://"

But in the Display Image URL and Full Size Image URL your should provide a valid URL, which is resolvable by your clients to the app icon of your app.

This image will only be displayed until the app was successfully installed.

ContentLicense: CC BY-SA 3.0

Title: Hidden app icon on iOS launcher


问:
i converted a bitmap picture to byte arraye and string .how can i convert this string to that bitmap picture again?
```<code> public byte[] PictureByteArray
        {
            get
            {
                //get a TypeConverter object for converting Bitmap to bytes
                TypeConverter converter = TypeDescriptor.GetConverter(typeof(Bitmap));
                byte[] byteArr = (byte[])converter.ConvertTo(source, typeof(byte[]));
                return byteArr;
            }
            set
            {
                source = new Bitmap(new MemoryStream(value));
            }
        }

  System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            s = enc.GetString(bytes);
</code>```

答:
I usually use these two methods for converting an image to a byte array, and back again, for example when transferring an image to a web service, and retrieving it back again:</p>

```<code>public static byte[] ImageToByteArray(System.Drawing.Image imageIn) {
  MemoryStream ms = new MemoryStream();
  Bitmap image = new Bitmap(imageIn);
  image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  return ms.ToArray();
}

public static Image ByteArrayToImage(byte[] byteArray) {
  MemoryStream ms = new MemoryStream(byteArray);
  Image returnImage = Image.FromStream(ms);
  return returnImage;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I usually use these two methods for converting an image to a byte array, and back again, for example when transferring an image to a web service, and retrieving it back again:

public static byte[] ImageToByteArray(System.Drawing.Image imageIn) {
  MemoryStream ms = new MemoryStream();
  Bitmap image = new Bitmap(imageIn);
  image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  return ms.ToArray();
}

public static Image ByteArrayToImage(byte[] byteArray) {
  MemoryStream ms = new MemoryStream(byteArray);
  Image returnImage = Image.FromStream(ms);
  return returnImage;
}


问:
How to compare if any of the elements in a row is same
Is there a way to compare whether "any value of" a row is identical to "any value" of the row above -- regardless of the order? Below is a very random input data table.

```<code>DT <- data.table(A=c("a","a","b","d","e","f","h","i","j"),
                 B=c("a","b","c","c","f","g",NA,"j",NA),
                 C=c("a","b","c","b","g","h",NA,NA,NA))

> DT
   A  B  C
1: a  a  a
2: a  b  b
3: b  c  c
4: d  c  b
5: e  f  g
6: f  g  h
7: h NA NA
8: i  j NA
9: j NA NA
</code>```

I would like to add a column D that compares a row with the row above, and compare whether any values of the two rows are identical (regardless of the order). So the desired output would be:

```<code> > DT
   A  B  C  D
1: a  a  a  0 #No row above to compare; could be either NA or 0
2: a  b  b  1 #row 2 has "a", which is in row 1; returns 1
3: b  c  c  1 #row 3 has "b", which is in row 2; returns 1
4: d  c  b  1 #row 4 has "b" and "c", which are in row 3; returns 1
5: e  f  g  0 #row 5 has nothing that is in row 4; returns 0
6: f  g  h  1 #row 6 has "f" and "g", which are in row 5; returns 1
7: h NA NA  1 #row 7 has "h", which is in row 6; returns 1
8: i  j NA  0 #row 8 has nothing that is in row 7 (NA doesn't count)
9: j NA NA  1 #row 9 has "j", which is in row 8; returns 1 (NA doesn't count)
</code>```

The main idea is that I would like to compare a row (or a vector) with another row (vector), and define two rows to be identical if any of the elements in each row (vector) are.  (without reiterating to compare each element)

答:
Here is another method. It's probably not advisable on large data.tables as it uses by=1:nrow(DT) which tends to be quite slow.

```<code>DT[, D:= sign(DT[, c(.SD, shift(.SD))][,
   sum(!is.na(intersect(unlist(.SD[, .(A, B, C)]), unlist(.SD[, .(V4, V5, V6)])))),
   by=1:nrow(DT)]$V1)]
</code>```

Here, [, c(.SD, shift(.SD))] creates a copy of the data.frame, with the lagged variables included (cbinded). Then the second chain intersects the unlisted variables in the original data.table and the shifted data.table. NAs are assigned 0 and non-NAs are assigned 1 and these results are summed. This operation occurs for each row of the copied data.table. The sum is extracted with $v1 and is turned into binary (0 and 1) using sign.

It returns

```<code>DT
   A  B  C D
1: a  a  a 0
2: a  b  b 1
3: b  c  c 1
4: d  c  b 1
5: e  f  g 0
6: f  g  h 1
7: h NA NA 1
8: i  j NA 0
9: j NA NA 1
</code>```

Body:
Is there a way to compare whether "any value of" a row is identical to "any value" of the row above -- regardless of the order? Below is a very random input data table.

DT <- data.table(A=c("a","a","b","d","e","f","h","i","j"),
                 B=c("a","b","c","c","f","g",NA,"j",NA),
                 C=c("a","b","c","b","g","h",NA,NA,NA))

> DT
   A  B  C
1: a  a  a
2: a  b  b
3: b  c  c
4: d  c  b
5: e  f  g
6: f  g  h
7: h NA NA
8: i  j NA
9: j NA NA

I would like to add a column D that compares a row with the row above, and compare whether any values of the two rows are identical (regardless of the order). So the desired output would be:

 > DT
   A  B  C  D
1: a  a  a  0 #No row above to compare; could be either NA or 0
2: a  b  b  1 #row 2 has "a", which is in row 1; returns 1
3: b  c  c  1 #row 3 has "b", which is in row 2; returns 1
4: d  c  b  1 #row 4 has "b" and "c", which are in row 3; returns 1
5: e  f  g  0 #row 5 has nothing that is in row 4; returns 0
6: f  g  h  1 #row 6 has "f" and "g", which are in row 5; returns 1
7: h NA NA  1 #row 7 has "h", which is in row 6; returns 1
8: i  j NA  0 #row 8 has nothing that is in row 7 (NA doesn't count)
9: j NA NA  1 #row 9 has "j", which is in row 8; returns 1 (NA doesn't count)

The main idea is that I would like to compare a row (or a vector) with another row (vector), and define two rows to be identical if any of the elements in each row (vector) are.  (without reiterating to compare each element)

Body:
Here is another method. It's probably not advisable on large data.tables as it uses by=1:nrow(DT) which tends to be quite slow.

DT[, D:= sign(DT[, c(.SD, shift(.SD))][,
   sum(!is.na(intersect(unlist(.SD[, .(A, B, C)]), unlist(.SD[, .(V4, V5, V6)])))),
   by=1:nrow(DT)]$V1)]

Here, [, c(.SD, shift(.SD))] creates a copy of the data.frame, with the lagged variables included (cbinded). Then the second chain intersects the unlisted variables in the original data.table and the shifted data.table. NAs are assigned 0 and non-NAs are assigned 1 and these results are summed. This operation occurs for each row of the copied data.table. The sum is extracted with $v1 and is turned into binary (0 and 1) using sign.

It returns

DT
   A  B  C D
1: a  a  a 0
2: a  b  b 1
3: b  c  c 1
4: d  c  b 1
5: e  f  g 0
6: f  g  h 1
7: h NA NA 1
8: i  j NA 0
9: j NA NA 1


问:
Convert string date long format to 12h date format
I have a function that works well if the format is in 24h but however in 12h it does not work well, I'm trying to apply this to correct it but the result of the 3 line is 'nil', some reason why this is happening?

```<code>  let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let date = dateFormatter.date(from: "2017-02-01 14:55:08")
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
    let stringdate = dateFormatter.string(from: date)
    let newDate12h = dateFormatter.date(from: stringdate)
</code>```

this line return nil :

```<code>let date = dateFormatter.date(from: "2017-02-01 14:55:08")
</code>```

答:
Maybe you are simply missing an a in the format?

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.date(from: "2017-02-01 14:55:08")
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss a"
let stringdate = dateFormatter.string(from: date!)
let newDate12h = dateFormatter.date(from: stringdate)
</code>```

works for me in Swift Playground.

Body:
I have a function that works well if the format is in 24h but however in 12h it does not work well, I'm trying to apply this to correct it but the result of the 3 line is 'nil', some reason why this is happening?

  let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let date = dateFormatter.date(from: "2017-02-01 14:55:08")
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
    let stringdate = dateFormatter.string(from: date)
    let newDate12h = dateFormatter.date(from: stringdate)

this line return nil :

let date = dateFormatter.date(from: "2017-02-01 14:55:08")

Body:
Maybe you are simply missing an a in the format?

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.date(from: "2017-02-01 14:55:08")
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss a"
let stringdate = dateFormatter.string(from: date!)
let newDate12h = dateFormatter.date(from: stringdate)

works for me in Swift Playground.


问:
NetBeans background scanning projects takes too long
NetBeans background scanning projects takes too long. Every time when I open netbeans it scanning for ages. I used NetBeans 7.2 and it works perfecly. Now I formatted pc and reinstalled windows, install the same version of NetBeans 7.2, and it works to slow.</p>

答: It should be called foreground scanning of projects. Closing the program and restarting solves it for me sometimes.</p>


问:
using multiple return statements in a c++ function
I was wondering if it might be sort of advantageous for a c++ compiler if there's only one return statement in a function. one of my ex-bosses once told me so but I don't get the point if there would be any difference between declaring a return variable or simply having multiple return statements, e.g. in a switch-case statement.

So my question is: is there any difference, maybe in quality, performance or stack memory savings?

答:
No, not really.

I do actullay like having many return values. It simplify's the code greatly and I have found no problem with it. Visual Studio, the IDE that I use, handles it with no problem.


问:
Join two integers into one double
I need to transfer a double value (-47.1235648, for example) using sockets. Since I'll have a lot of platforms, I must convert to network byte order to ensure correct endian of all ends....but this convert doesn't accept double, just integer and short, so I'm 'cutting' my double into two integer to transfer, like this:

```<code>double lat = -47.848945;
int a;
int b;
a = (int)lat;
b = (int)(lat+1);
</code>```

Now, I need to restore this on the other end, but using the minimum computation as possible (I saw some examples using POW, but looks like pow use a lot of resources for this, I'm not sure). Is there any way to join this as simples as possible, like bit manipulating?

答:
Your code makes no sense.

The typical approach is to use memcpy():

```<code>const double lat = -47.848945;
uint32_t ints[sizeof lat / sizeof (uint32_t)];
memcpy(ints, &lat, sizeof lat);
</code>```

Now send the elements of ints, which are just 32-bit unsigned integers.

This of course assumes:

That you know how to send uint32_ts in a safe manner, i.e. byte per byte or using endian-conversion functions.

That all hosts share the same binary double format (typically IEEE-754).

That you somehow can manage the byte order requirements when moving to/from a pair of integers from/to a single double value (see @JohnBollinger's answer).

I interpreted your question to mean all of these assumptions were safe, that might be a bit over the top. I can't delete this answer as long as it's accepted.

Title: Join two integers into one double

Body:
I need to transfer a double value (-47.1235648, for example) using sockets. Since I'll have a lot of platforms, I must convert to network byte order to ensure correct endian of all ends....but this convert doesn't accept double, just integer and short, so I'm 'cutting' my double into two integer to transfer, like this:

double lat = -47.848945;
int a;
int b;
a = (int)lat;
b = (int)(lat+1);

Now, I need to restore this on the other end, but using the minimum computation as possible (I saw some examples using POW, but looks like pow use a lot of resources for this, I'm not sure). Is there any way to join this as simples as possible, like bit manipulating?

Body:
Your code makes no sense.

The typical approach is to use memcpy():

const double lat = -47.848945;
uint32_t ints[sizeof lat / sizeof (uint32_t)];
memcpy(ints, &lat, sizeof lat);

Now send the elements of ints, which are just 32-bit unsigned integers.

This of course assumes:

That you know how to send uint32_ts in a safe manner, i.e. byte per byte or using endian-conversion functions.

That all hosts share the same binary double format (typically IEEE-754).

That you somehow can manage the byte order requirements when moving to/from a pair of integers from/to a single double value (see @JohnBollinger's answer).

I interpreted your question to mean all of these assumptions were safe, that might be a bit over the top. I can't delete this answer as long as it's accepted.


问:
Facebook does not load image from og:image
It was already working, but today I was surprized, when I tryed to share the link, and Facebook did not show the image, from og:image meta tag.

from facebook debugger:

```<code>Meta Tag:   <meta property="og:description" content="Профессиональная сеть вопросов и ответов,создаваемая и управляемая сообществом пользователей. Ресурс для тех, кто хочет знать ответы на все вопросы." />
Meta Tag:   <meta property="og:title" content="Закрытое экспертное сообщество OdinOtvet" />
Meta Tag:   <meta property="og:type" content="website" />
Meta Tag:   <meta property="og:image" content="http://www.odinotvet.ru/images/logo_250.png" />
Meta Tag:   <meta property="og:url" content="http://www.odinotvet.ru" />
Meta Tag:   <meta property="og:site_name" content="ОдинОтвет" />
Meta Tag:   <meta property="fb:app_id" content="286967601317982" />
Meta Tag:   <meta property="fb:admins" content="100002890978393,100001666575542" />
</code>```

Where is the image?

答:
Try this it will help

```<code><?php

$params = array();
if(count($_GET) > 0) {
    $params = $_GET;
} else {
    $params = $_POST;
}
// defaults
if($params['type'] == "") $params['type'] = "restaurant";
if($params['locale'] == "") $params['locale'] = "en_US";
if($params['title'] == "") $params['title'] = "default title";
if($params['image'] == "") $params['image'] = "thumb";
if($params['description'] == "") $params['description'] = "default description";

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# MY_APP_NAME_SPACE: http://ogp.me/ns/fb/MY_APP_NAME_SPACE#">
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

        <!-- Open Graph meta tags -->
        <meta property="fb:app_id" content="MY_APP_ID" />
        <meta property="og:site_name" content="meta site name"/>
        <meta property="og:url" content="URL/index.php?type=<?php echo $params['type']; ?>&locale=<?php echo $params['locale']; ?>&title=<?php echo $params['title']; ?>&image=<?php echo $params['image']; ?>&description=<?php echo $params['description']; ?>"/>
        <meta property="og:type" content="MY_APP_NAME_SPACE:<?php echo $params['type']; ?>"/>
        <meta property="og:locale" content="<?php echo $params['locale']; ?>"/>
        <meta property="og:title" content="<?php echo $params['title']; ?>"/>
        <meta property="og:image" content="URL/img/<?php echo $params['image']; ?>.png"/>
        <meta property="og:description" content="<?php echo $params['description']; ?>"/>

    </head>
</html>
</code>```

Body:
It was already working, but today I was surprized, when I tryed to share the link, and Facebook did not show the image, from og:image meta tag.

from facebook debugger:

Meta Tag:   <meta property="og:description" content="Профессиональная сеть вопросов и ответов,создаваемая и управляемая сообществом пользователей. Ресурс для тех, кто хочет знать ответы на все вопросы." />
Meta Tag:   <meta property="og:title" content="Закрытое экспертное сообщество OdinOtvet" />
Meta Tag:   <meta property="og:type" content="website" />
Meta Tag:   <meta property="og:image" content="http://www.odinotvet.ru/images/logo_250.png" />
Meta Tag:   <meta property="og:url" content="http://www.odinotvet.ru" />
Meta Tag:   <meta property="og:site_name" content="ОдинОтвет" />
Meta Tag:   <meta property="fb:app_id" content="286967601317982" />
Meta Tag:   <meta property="fb:admins" content="100002890978393,100001666575542" />

Where is the image?

Body:
Try this it will help

<?php

$params = array();
if(count($_GET) > 0) {
    $params = $_GET;
} else {
    $params = $_POST;
}
// defaults
if($params['type'] == "") $params['type'] = "restaurant";
if($params['locale'] == "") $params['locale'] = "en_US";
if($params['title'] == "") $params['title'] = "default title";
if($params['image'] == "") $params['image'] = "thumb";
if($params['description'] == "") $params['description'] = "default description";

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# MY_APP_NAME_SPACE: http://ogp.me/ns/fb/MY_APP_NAME_SPACE#">
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

        <!-- Open Graph meta tags -->
        <meta property="fb:app_id" content="MY_APP_ID" />
        <meta property="og:site_name" content="meta site name"/>
        <meta property="og:url" content="URL/index.php?type=<?php echo $params['type']; ?>&locale=<?php echo $params['locale']; ?>&title=<?php echo $params['title']; ?>&image=<?php echo $params['image']; ?>&description=<?php echo $params['description']; ?>"/>
        <meta property="og:type" content="MY_APP_NAME_SPACE:<?php echo $params['type']; ?>"/>
        <meta property="og:locale" content="<?php echo $params['locale']; ?>"/>
        <meta property="og:title" content="<?php echo $params['title']; ?>"/>
        <meta property="og:image" content="URL/img/<?php echo $params['image']; ?>.png"/>
        <meta property="og:description" content="<?php echo $params['description']; ?>"/>

    </head>
</html>


问:
C++ Rehashing Algorithm Vectors
I have been asked to create a rehashing algorithm with instructions:

 Backup the old vector Table to a temporary vector oldTable

 Delete the elements in the old Table

 Obtain the new table size

 Expand Table to the new size

 Reinsert elements from oldTable into the expanded new Table

 Delete the elements in the oldTable

Hash Table.h Class:

```<code>#ifndef HASHTABLE_H
#define HASHTABLE_H
#include "Math.h"

// hash table storing class X objects using linear probing
template <class X>
class HashTable {
public:
    // constructor sets the hash table size & load threshold
    HashTable(int table_size, double load_threshold = 0.75);
    // destructor
    ~HashTable() { for (int i = 0; i < Table.size(); i++) if (Table[i]) delete Table[i]; }

    // search for object a in the table
    size_t find(X& a);  // size_t = unsigned int

    // insert new object a in the table, return true if done
    bool insert(X& a);

    //function to return a new prime table size
    size_t newTableSize();

    //rehash func
    void reHash();

private:
    // the hash table & number of objects stored
    vector<X*> Table;
    size_t num_x;

    // maximum load threshold
    double LOAD_TH;
};

template <class X>
HashTable<X>::HashTable(int table_size, double load_threshold)
{
    for (int i = 0; i < table_size; i++) Table.push_back(NULL);
    num_x = 0;
    LOAD_TH = load_threshold;
}

template <class X>
size_t HashTable<X>::newTableSize() {

    bool found = true;

    int newSize = 2 * Table.size() + 1; // = now odd because oldSize is a prime

    do {
        int x = sqrt(newSize);
        for (int i = 3; i <= x; i += 2) {
            if (newSize % i == 0) {
                newSize = newSize + 2;
                x = sqrt(newSize);
                break;
            }
            else
            {
                found = true;
            }

        }
    } while (!found);

    return newSize;
}

template<class X>

void HashTable<X>::reHash() {

        //Backup the old vector<X*> Table to a temporary vector<X*> oldTable
        vector<X*> tempTable;
        tempTable = Table;

        //Delete the elements in the old Table
        Table.clear();

        //Obtain the new table size
        int newPrimeSize = newTableSize();

        //Expand Table to the new size
        Table.resize(newPrimeSize);

        //Reinsert elements from oldTable into the expanded new Table

        //Table = tempTable;
        //or method below??
        for (int i = 0; i < tempTable.size; i++) {
            if (tempTable[i] != NULL){
                Table.insert(tempTable[i]);
            }
        }

        //Delete the elements in the oldTable
        tempTable.clear();
}

template <class X>
size_t HashTable<X>::find(X& a)
{
    // calculate the hash index
    size_t index = a.hash_index() % Table.size();
    // search - find index of matching key or the 1st empty slot
    while (Table[index] != NULL && Table[index]->get_key() != a.get_key())
        index = (index + 1) % Table.size();
    // retrieve matching value to a if found
    if (Table[index] != NULL) a.set_value(Table[index]->get_value());

    return index;
}

template <class X>
bool HashTable<X>::insert(X& a)
{
    // calculate the load factor of the table
    double load_factor = (double)num_x / (double)Table.size();
    if (load_factor > LOAD_TH) {
        // replace the following return by rehashing - practical work
        return 0;

    }

    // search a in the able
    size_t index = find(a);
    // not found, create a new entry in the table
    if (Table[index] == NULL) {
        Table[index] = new X(a);
        num_x++;
        return 1;
    }

    // object already in table, do nothing
    return 0;
}
#endif
</code>```

Test Class:

```<code>#include <iostream>
#include <vector>
#include <string>
#include <time.h>
#include "Math.h"
using namespace std;

#include "HashTable.h"

// a class of phone records
class PhoneDir {
public:
    PhoneDir(string name, int number = -1)
        : name(name), number(number) {};

    string get_key() { return name; }
    int get_value() { return number; }
    void set_value(int num) { number = num; }

    size_t hash_index(); // return hash index of key: name

private:
    string name;    // key
    int number;     // value
};

size_t PhoneDir::hash_index()
{
    size_t hash_index = 0;
    for (int i = 0; i < name.size(); i++) {
        char c = name[i];
        hash_index = 37 * hash_index + c;
    }
    return hash_index;
}

int main()
{
    int oldSize = 5;
    // store phone records in hash table with size 11
    HashTable<PhoneDir> HTable(7);
    HTable.insert(PhoneDir("Tom", 123456));
    HTable.insert(PhoneDir("Sam", 346834));
    HTable.insert(PhoneDir("Pete", 347980));
    HTable.insert(PhoneDir("Jack", 328709));
    HTable.insert(PhoneDir("David", 335566));

    // serach using name for phone number over the hash table
    char yn = 'y';
    do {
            //test function part 1
    cout << " Test " << endl;
    cout << HTable.newTableSize();

        cout << "Whose number are you looking for? ";
        string name; cin >> name;

        // form enquiry and search
        PhoneDir enquiry(name);
        clock_t t0 = clock();
        size_t index = HTable.find(enquiry);
        clock_t t1 = clock();

        cout << "index = " << index;
        cout << ", name = " << enquiry.get_key();
        cout << ", number = " << enquiry.get_value() << endl;
        cout << "time taken = " << t1 - t0 << endl << endl;

        cout << "Another (y/n)? "; cin >> yn;
    } while (yn == 'y');

    return 0;

}
</code>```

I successfully created & tested the newTableSize function & now I am on the rehash algorithm function.
The use of vectors is confusing me and I am new to this.
Am i on the right track? Will the parts of my re-hash algorithm work?
Thanks

答:
One of the most easy way is create a new HashTable and swap the two.

Create a new HashTable<X>

insert all items into it.

call std::swap(*this,new_hashTable);

if you want minimun change to your code,

change
Table.insert(tempTable[i]); to
this->insert(*tempTable[i]); would probably work.

Don't forget the rehash as you currently use would generate collision, you need to handle this.

Title: C++ Rehashing Algorithm Vectors

Body:
I have been asked to create a rehashing algorithm with instructions:

 Backup the old vector Table to a temporary vector oldTable

 Delete the elements in the old Table

 Obtain the new table size

 Expand Table to the new size

 Reinsert elements from oldTable into the expanded new Table

 Delete the elements in the oldTable

Hash Table.h Class:

#ifndef HASHTABLE_H
#define HASHTABLE_H
#include "Math.h"

// hash table storing class X objects using linear probing
template <class X>
class HashTable {
public:
    // constructor sets the hash table size & load threshold
    HashTable(int table_size, double load_threshold = 0.75);
    // destructor
    ~HashTable() { for (int i = 0; i < Table.size(); i++) if (Table[i]) delete Table[i]; }

    // search for object a in the table
    size_t find(X& a);  // size_t = unsigned int

    // insert new object a in the table, return true if done
    bool insert(X& a);

    //function to return a new prime table size
    size_t newTableSize();

    //rehash func
    void reHash();

private:
    // the hash table & number of objects stored
    vector<X*> Table;
    size_t num_x;

    // maximum load threshold
    double LOAD_TH;
};

template <class X>
HashTable<X>::HashTable(int table_size, double load_threshold)
{
    for (int i = 0; i < table_size; i++) Table.push_back(NULL);
    num_x = 0;
    LOAD_TH = load_threshold;
}

template <class X>
size_t HashTable<X>::newTableSize() {

    bool found = true;

    int newSize = 2 * Table.size() + 1; // = now odd because oldSize is a prime

    do {
        int x = sqrt(newSize);
        for (int i = 3; i <= x; i += 2) {
            if (newSize % i == 0) {
                newSize = newSize + 2;
                x = sqrt(newSize);
                break;
            }
            else
            {
                found = true;
            }

        }
    } while (!found);

    return newSize;
}

template<class X>

void HashTable<X>::reHash() {

        //Backup the old vector<X*> Table to a temporary vector<X*> oldTable
        vector<X*> tempTable;
        tempTable = Table;

        //Delete the elements in the old Table
        Table.clear();

        //Obtain the new table size
        int newPrimeSize = newTableSize();

        //Expand Table to the new size
        Table.resize(newPrimeSize);

        //Reinsert elements from oldTable into the expanded new Table

        //Table = tempTable;
        //or method below??
        for (int i = 0; i < tempTable.size; i++) {
            if (tempTable[i] != NULL){
                Table.insert(tempTable[i]);
            }
        }

        //Delete the elements in the oldTable
        tempTable.clear();
}

template <class X>
size_t HashTable<X>::find(X& a)
{
    // calculate the hash index
    size_t index = a.hash_index() % Table.size();
    // search - find index of matching key or the 1st empty slot
    while (Table[index] != NULL && Table[index]->get_key() != a.get_key())
        index = (index + 1) % Table.size();
    // retrieve matching value to a if found
    if (Table[index] != NULL) a.set_value(Table[index]->get_value());

    return index;
}

template <class X>
bool HashTable<X>::insert(X& a)
{
    // calculate the load factor of the table
    double load_factor = (double)num_x / (double)Table.size();
    if (load_factor > LOAD_TH) {
        // replace the following return by rehashing - practical work
        return 0;

    }

    // search a in the able
    size_t index = find(a);
    // not found, create a new entry in the table
    if (Table[index] == NULL) {
        Table[index] = new X(a);
        num_x++;
        return 1;
    }

    // object already in table, do nothing
    return 0;
}
#endif

Test Class:

#include <iostream>
#include <vector>
#include <string>
#include <time.h>
#include "Math.h"
using namespace std;

#include "HashTable.h"

// a class of phone records
class PhoneDir {
public:
    PhoneDir(string name, int number = -1)
        : name(name), number(number) {};

    string get_key() { return name; }
    int get_value() { return number; }
    void set_value(int num) { number = num; }

    size_t hash_index(); // return hash index of key: name

private:
    string name;    // key
    int number;     // value
};

size_t PhoneDir::hash_index()
{
    size_t hash_index = 0;
    for (int i = 0; i < name.size(); i++) {
        char c = name[i];
        hash_index = 37 * hash_index + c;
    }
    return hash_index;
}

int main()
{
    int oldSize = 5;
    // store phone records in hash table with size 11
    HashTable<PhoneDir> HTable(7);
    HTable.insert(PhoneDir("Tom", 123456));
    HTable.insert(PhoneDir("Sam", 346834));
    HTable.insert(PhoneDir("Pete", 347980));
    HTable.insert(PhoneDir("Jack", 328709));
    HTable.insert(PhoneDir("David", 335566));

    // serach using name for phone number over the hash table
    char yn = 'y';
    do {
            //test function part 1
    cout << " Test " << endl;
    cout << HTable.newTableSize();

        cout << "Whose number are you looking for? ";
        string name; cin >> name;

        // form enquiry and search
        PhoneDir enquiry(name);
        clock_t t0 = clock();
        size_t index = HTable.find(enquiry);
        clock_t t1 = clock();

        cout << "index = " << index;
        cout << ", name = " << enquiry.get_key();
        cout << ", number = " << enquiry.get_value() << endl;
        cout << "time taken = " << t1 - t0 << endl << endl;

        cout << "Another (y/n)? "; cin >> yn;
    } while (yn == 'y');

    return 0;

}

I successfully created & tested the newTableSize function & now I am on the rehash algorithm function.
The use of vectors is confusing me and I am new to this.
Am i on the right track? Will the parts of my re-hash algorithm work?
Thanks


问:
How to get the height of an element and use it in a function?
I'm trying to use jquery to determine the height of an element and then determine if a user has scrolled that distance. The application is that I have a header followed by a navbar. As the user scrolls down the page the header will disappear and the navbar will stay fixed to the top of the screen. I have this working using the following code:

```<code>    <script type="text/javascript">
jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() > 100 ) {
    jQuery("#top-header").hide(300);
} else {
    jQuery("#top-header").show(300);
}
</code>```

});

But I want to use media queries to change the height of #top-header based on screen size instead of leaving it the same. So what I'd like to do is determine the height of #top-header (or some element within it) and then use that value in the function to hide it. I know I can use some form of $('#top-header).height but I'm not sure how to incorporate it into the function.

Thanks,
CJ

答:
Try this</p>

```<code>$('document').ready(function(){
   $(window).scroll(function(event){
     var scroll = $(window).scrollTop();
     var header = $("#top-header").height();

     if(scroll > header){
        header.hide(300);
     }else{
        header.show(300);
     }
   }
}
</code>```

Body:
Try this

$('document').ready(function(){
   $(window).scroll(function(event){
     var scroll = $(window).scrollTop();
     var header = $("#top-header").height();

     if(scroll > header){
        header.hide(300);
     }else{
        header.show(300);
     }
   }
}


问:
Jsoup div Shows nothing
I have a problem the Jsoup is not selecting the div and shows nothingI have no error but it shows nothing</p>

```<code>private void getWebsite() {
    Document doc = null;

    try {
        doc = Jsoup.connect("http://test.com/test.html").get();
        Elements text = doc.select("div[id=content]");
        System.out.println(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

答:
Try</p>

```<code>Elements text = doc.select("div#content"); (or)
Element text = doc.getElementById("context");
</code>```

Title: Jsoup div Shows nothing

Body:
I have a problem the Jsoup is not selecting the div and shows nothingI have no error but it shows nothing

private void getWebsite() {
    Document doc = null;

    try {
        doc = Jsoup.connect("http://test.com/test.html").get();
        Elements text = doc.select("div[id=content]");
        System.out.println(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Body:
Try

Elements text = doc.select("div#content"); (or)
Element text = doc.getElementById("context");


问:
Is there a way to use ffmpeg for RGB to true YUV (not YCbCr) conversion?
As far as I can see in the documentation, all conversions involving YUV actually use YCbCr. There are slight differences though, and I would like to convert to the actual YUV format. Is there any way at all using ffmpeg? As an afterthought, is there any other way that is as fast as ffmpeg?

Image source

答:
It turns out it is possible: for example when processing an AVFrame using an AVCodecContext,

use AV_PIX_FMT_YUVJ420P instead of AV_PIX_FMT_YUV_420P  (deprecated),

or use AV_PIX_FMT_YUV_420P and set the color_range to AVCOL_RANGE_JPEG.

All links are relative to release 3.2.

Edit:
I believe the actual mathematical conversions are in yuv2rgb.c.


问:
How can I upload my local wordpress to a digital ocean droplet I have set up?
I have recently finished developing my first wordpress site for a client, I have set up a digital ocean droplet and installed Wordpress (which works successfully!).

Can somebody please give me layman terms instructions on how to upload my local site to the digital ocean droplet please?

I am a beginner and struggling!

Many thanks in advance!

答:
You can install the All-in-one wp migration plugin on local and droplet versions.

After the installation, click on "Export" and it will generate a .wpress file that contain code, content and database in one file.
Go to the droplet, click "Import" and drag'n drop the wpress file. Follow the instructions and update the permalinks.


问:
Efficiently updating lines/markers on top of a JavaFX chart
I use a JavaFX LineChart which takes nearly a second to be rendered and I want to move a vertical marker (cursor position) over this chart which is updated very frequently.

I tested the following solutions:

Adding a line in a JavaFX chart

How to add a value marker to JavaFX chart?

However, these solutions are not made for frequent marker updates on big charts.  Whenever a marker changes the whole chart is redrawn.

How can I prevent Java from redrawing the whole chart when the marker gets updated?
I thought of a wrapper component that can be put around the chart and caches the chart image as long as the chart content and chart boundaries do not change.  Does something like that exist or how could one implement this?

答:
As mentioned by Stefan the best way is to set the cache property to true of the nodes that you do not want to update. What I want to add is that the StackPane is not strickly necessary, it could be a Pane or another region (actually a StackPane has its own way to add new children which make you dificult to manipulate).
Here is a snippet of the code I used to implement a LineMarker that moves along the LineChart (in my example I had a video and the LineMarker followed the time in the chart)

Main Example

```<code>Pane pane;
LineChart chart;
MediaPlayer mediaPlayer;
// Create pane, chart (and mediaplayer for this example)
pane.getChildren.add(chart);
List<XYChart.Data<Number, Number> dataList;
XYChart.Series series = new XYChart.Series();
// Fill the data
ObservableList<XYChart.Data<Number, Number>> list;
list = FXCollections.observableList(dataList);
series.setData(list);
chart.getData().add(series);
chart.setCache(true);
LineMarker lineMarker = new LineMarker(pane, (ValueAxis) chart.getXAxis(), 0, (ValueAxis) chart.getYAxis());
mediaPlayer.currentTimeProperty().addListener((v, oldValue, newValue) -> lineMarker.updateMarker(newValue.doubleValue()));
</code>```

LineMarker.java

```<code>public class LineMarker extends Line{
private final DoubleProperty value = new SimpleDoubleProperty();
private Pane pane;
private ValueAxis xAxis;
private ValueAxis yAxis;

public LineMarker(Pane pane, ValueAxis xAxis, double value, ValueAxis yAxis){
    this.pane = pane;
    this.xAxis = xAxis;
    this.yAxis = yAxis;
    Number lowerY = yAxis.toRealValue(yAxis.getLowerBound());
    double minY = yAxis.getDisplayPosition(lowerY);
    setStartY(getYPositionParent(minY, pane));
    Number upperY = yAxis.toRealValue(yAxis.getUpperBound());
    double maxY = yAxis.getDisplayPosition(upperY);
    setEndY(getYPositionParent(maxY, pane));
    double xPosInAxis = xAxis.getDisplayPosition(value);
    setStartX(getXPositionParent(xPosInAxis, pane));
    setEndX(getStartX());
    pane.getChildren().add(this);
}

private double getXPositionParent(double xPosInAxis, Node parent){
    double xPosInParent = xPosInAxis - xAxis.getBoundsInLocal().getMinX();
    Node node = xAxis;
    while(!node.equals(parent)){
        xPosInParent = xPosInParent + node.getBoundsInParent().getMinX();
        node = node.getParent();
    }
    return xPosInParent;
}

private double getYPositionParent(double yPosInAxis, Node parent){
    double yPosInParent = yPosInAxis - yAxis.getBoundsInLocal().getMinY();
    Node node = yAxis;
    while(!node.equals(parent)){
        yPosInParent = yPosInParent + node.getBoundsInParent().getMinY();
        node = node.getParent();
    }
    return yPosInParent;
}

public void updateMarker(double value){
    pane.getChildren().remove(this);
    double xPosInAxis = xAxis.getDisplayPosition(value);
    setStartX(getXPositionParent(xPosInAxis, pane));
    setEndX(getStartX());
    pane.getChildren().add(this);
    pane.requestLayout();
}
</code>```

Body:
As mentioned by Stefan the best way is to set the cache property to true of the nodes that you do not want to update. What I want to add is that the StackPane is not strickly necessary, it could be a Pane or another region (actually a StackPane has its own way to add new children which make you dificult to manipulate).
Here is a snippet of the code I used to implement a LineMarker that moves along the LineChart (in my example I had a video and the LineMarker followed the time in the chart)

Main Example

Pane pane;
LineChart chart;
MediaPlayer mediaPlayer;
// Create pane, chart (and mediaplayer for this example)
pane.getChildren.add(chart);
List<XYChart.Data<Number, Number> dataList;
XYChart.Series series = new XYChart.Series();
// Fill the data
ObservableList<XYChart.Data<Number, Number>> list;
list = FXCollections.observableList(dataList);
series.setData(list);
chart.getData().add(series);
chart.setCache(true);
LineMarker lineMarker = new LineMarker(pane, (ValueAxis) chart.getXAxis(), 0, (ValueAxis) chart.getYAxis());
mediaPlayer.currentTimeProperty().addListener((v, oldValue, newValue) -> lineMarker.updateMarker(newValue.doubleValue()));

LineMarker.java

public class LineMarker extends Line{
private final DoubleProperty value = new SimpleDoubleProperty();
private Pane pane;
private ValueAxis xAxis;
private ValueAxis yAxis;

public LineMarker(Pane pane, ValueAxis xAxis, double value, ValueAxis yAxis){
    this.pane = pane;
    this.xAxis = xAxis;
    this.yAxis = yAxis;
    Number lowerY = yAxis.toRealValue(yAxis.getLowerBound());
    double minY = yAxis.getDisplayPosition(lowerY);
    setStartY(getYPositionParent(minY, pane));
    Number upperY = yAxis.toRealValue(yAxis.getUpperBound());
    double maxY = yAxis.getDisplayPosition(upperY);
    setEndY(getYPositionParent(maxY, pane));
    double xPosInAxis = xAxis.getDisplayPosition(value);
    setStartX(getXPositionParent(xPosInAxis, pane));
    setEndX(getStartX());
    pane.getChildren().add(this);
}

private double getXPositionParent(double xPosInAxis, Node parent){
    double xPosInParent = xPosInAxis - xAxis.getBoundsInLocal().getMinX();
    Node node = xAxis;
    while(!node.equals(parent)){
        xPosInParent = xPosInParent + node.getBoundsInParent().getMinX();
        node = node.getParent();
    }
    return xPosInParent;
}

private double getYPositionParent(double yPosInAxis, Node parent){
    double yPosInParent = yPosInAxis - yAxis.getBoundsInLocal().getMinY();
    Node node = yAxis;
    while(!node.equals(parent)){
        yPosInParent = yPosInParent + node.getBoundsInParent().getMinY();
        node = node.getParent();
    }
    return yPosInParent;
}

public void updateMarker(double value){
    pane.getChildren().remove(this);
    double xPosInAxis = xAxis.getDisplayPosition(value);
    setStartX(getXPositionParent(xPosInAxis, pane));
    setEndX(getStartX());
    pane.getChildren().add(this);
    pane.requestLayout();
}


问:
.NET's GUID structure
http://msdn.microsoft.com/en-us/library/system.guid.aspx

How does it work? How does it guarantee unique ID? Does it only rely on probability or is there another trick? Can I always trust it to give unique id or what are cases where I should avoid guid?

答: It uses a special algorithm designed to produce unique IDs. Yes, they might collide, but that's highly unlikely. Also see this closely related question.</p>

Title: .NET's GUID structure


问:
ContentValue is inserting null data into my Table in SQLite - android
It inserts a row but without any content. i have used this method in previous applications and they all worked well. please help i'm stuck

```<code>public boolean Insert(){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_BUSINESS_NAME,"TEster"); // i tried putting the value directly
    cv.put(COLUMN_BUSINESS_CATEGORY,business_category);
    cv.put(COLUMN_BUSINESS_DESCRIPTION,business_description);
    cv.put(COLUMN_BUSINESS_PHONE,phone_number);
    cv.put(COLUMN_BUSINESS_EMAIL,email_address);
    cv.put(COLUMN_BUSINESS_URL,website);
    cv.put(COLUMN_BUSINESS_ADDRESS,locationAddress.address);
    cv.put(COLUMN_BUSINESS_F_ADDRESS,locationAddress.fAddress);
    cv.put(COLUMN_BUSINESS_LATITUDE,locationAddress.latLng.latitude);
    cv.put(COLUMN_BUSINESS_LONGITUDE,locationAddress.latLng.longitude);
    db.delete(TABLE_MY_BUSINESS, null, null);
    db.insert(TABLE_MY_BUSINESS, COLUMN_ID, cv);
    return true;
}
</code>```

this is how i fetch from the database

```<code>public void Fetch(){
    SQLiteDatabase db = this.getReadableDatabase();
    final String[] column = {COLUMN_BUSINESS_NAME,COLUMN_BUSINESS_CATEGORY,COLUMN_BUSINESS_DESCRIPTION,
            COLUMN_BUSINESS_PHONE,COLUMN_BUSINESS_EMAIL,COLUMN_BUSINESS_URL,COLUMN_BUSINESS_ADDRESS,
            COLUMN_BUSINESS_F_ADDRESS,COLUMN_BUSINESS_LATITUDE,COLUMN_BUSINESS_LONGITUDE};
    String table = TABLE_MY_BUSINESS;
    String selection = COLUMN_ID + " >= ? ";
    String[] selectionArgs = {"0"};
    Cursor cursor = db.query(table,column,selection,selectionArgs,null,null,null);
    cursor.moveToFirst();
    while (cursor.isAfterLast()) {
        this.business_name = cursor.getString(0);
        this.business_category = cursor.getString(1);
        this.business_description = cursor.getString(2);
        this.phone_number = cursor.getString(3);
        this.email_address = cursor.getString(4);
        this.website = cursor.getString(5);
        this.locationAddress.setAddress(cursor.getString(6));
        this.locationAddress.setfAddress(cursor.getString(7));
        this.locationAddress.setLatLng(cursor.getInt(8),cursor.getInt(9));
        cursor.moveToNext();
    }
    cursor.close();
    db.close();
}
</code>```

this is how i created the table

```<code>String CREATE_MY_BUSINESS_TABLE = "CREATE TABLE "+TABLE_MY_BUSINESS+" " + "("
            +COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"
            +COLUMN_BUSINESS_NAME+" TEXT,"
            +COLUMN_BUSINESS_CATEGORY+" TEXT,"
            +COLUMN_BUSINESS_DESCRIPTION+" TEXT,"
            +COLUMN_BUSINESS_PHONE+" TEXT,"
            +COLUMN_BUSINESS_EMAIL+" TEXT,"
            +COLUMN_BUSINESS_URL+" TEXT,"
            +COLUMN_BUSINESS_ADDRESS+" TEXT,"
            +COLUMN_BUSINESS_F_ADDRESS+" TEXT,"
            +COLUMN_BUSINESS_LONGITUDE+" INTEGER,"
            +COLUMN_BUSINESS_LATITUDE+" INTEGER)";
    db.execSQL(CREATE_USER_TABLE);
</code>```

答:
while (cursor.isAfterLast()) {
```

<p>The body of this <code>while</code> loop is executed only if the cursor is empty.</p>

<p>Executing a query positions a cursor before the first entry, so the easiest way to iterate through a cursor is like this:</p>

<pre class="lang-java prettyprint-override"><code>Cursor cursor = db.query(...);
while (cursor.moveToNext()) {
    ...
}
</code>```

Body:
It inserts a row but without any content. i have used this method in previous applications and they all worked well. please help i'm stuck

public boolean Insert(){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_BUSINESS_NAME,"TEster"); // i tried putting the value directly
    cv.put(COLUMN_BUSINESS_CATEGORY,business_category);
    cv.put(COLUMN_BUSINESS_DESCRIPTION,business_description);
    cv.put(COLUMN_BUSINESS_PHONE,phone_number);
    cv.put(COLUMN_BUSINESS_EMAIL,email_address);
    cv.put(COLUMN_BUSINESS_URL,website);
    cv.put(COLUMN_BUSINESS_ADDRESS,locationAddress.address);
    cv.put(COLUMN_BUSINESS_F_ADDRESS,locationAddress.fAddress);
    cv.put(COLUMN_BUSINESS_LATITUDE,locationAddress.latLng.latitude);
    cv.put(COLUMN_BUSINESS_LONGITUDE,locationAddress.latLng.longitude);
    db.delete(TABLE_MY_BUSINESS, null, null);
    db.insert(TABLE_MY_BUSINESS, COLUMN_ID, cv);
    return true;
}

this is how i fetch from the database

public void Fetch(){
    SQLiteDatabase db = this.getReadableDatabase();
    final String[] column = {COLUMN_BUSINESS_NAME,COLUMN_BUSINESS_CATEGORY,COLUMN_BUSINESS_DESCRIPTION,
            COLUMN_BUSINESS_PHONE,COLUMN_BUSINESS_EMAIL,COLUMN_BUSINESS_URL,COLUMN_BUSINESS_ADDRESS,
            COLUMN_BUSINESS_F_ADDRESS,COLUMN_BUSINESS_LATITUDE,COLUMN_BUSINESS_LONGITUDE};
    String table = TABLE_MY_BUSINESS;
    String selection = COLUMN_ID + " >= ? ";
    String[] selectionArgs = {"0"};
    Cursor cursor = db.query(table,column,selection,selectionArgs,null,null,null);
    cursor.moveToFirst();
    while (cursor.isAfterLast()) {
        this.business_name = cursor.getString(0);
        this.business_category = cursor.getString(1);
        this.business_description = cursor.getString(2);
        this.phone_number = cursor.getString(3);
        this.email_address = cursor.getString(4);
        this.website = cursor.getString(5);
        this.locationAddress.setAddress(cursor.getString(6));
        this.locationAddress.setfAddress(cursor.getString(7));
        this.locationAddress.setLatLng(cursor.getInt(8),cursor.getInt(9));
        cursor.moveToNext();
    }
    cursor.close();
    db.close();
}

this is how i created the table

String CREATE_MY_BUSINESS_TABLE = "CREATE TABLE "+TABLE_MY_BUSINESS+" " + "("
            +COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"
            +COLUMN_BUSINESS_NAME+" TEXT,"
            +COLUMN_BUSINESS_CATEGORY+" TEXT,"
            +COLUMN_BUSINESS_DESCRIPTION+" TEXT,"
            +COLUMN_BUSINESS_PHONE+" TEXT,"
            +COLUMN_BUSINESS_EMAIL+" TEXT,"
            +COLUMN_BUSINESS_URL+" TEXT,"
            +COLUMN_BUSINESS_ADDRESS+" TEXT,"
            +COLUMN_BUSINESS_F_ADDRESS+" TEXT,"
            +COLUMN_BUSINESS_LONGITUDE+" INTEGER,"
            +COLUMN_BUSINESS_LATITUDE+" INTEGER)";
    db.execSQL(CREATE_USER_TABLE);

Body:
while (cursor.isAfterLast()) {

The body of this while loop is executed only if the cursor is empty.

Executing a query positions a cursor before the first entry, so the easiest way to iterate through a cursor is like this:

Cursor cursor = db.query(...);
while (cursor.moveToNext()) {
    ...
}


问:
javascript skip duplicate permutation from array
I have an array with permutations but I need to remove duplicate permutations.

Permutations for 3 different digits is always 6 ways, so 345 and 453 are the same number. 497, 479 and 749 likewise would be considered the same number.

Also, 128, 281, 812, 182, 218 and 821 are all the same number.

It means I need to keep any only one permutation from 128, 281, 812, 182, 218 and 821 all others should be removed from the array.

Like if array has 497, 479, 749, 128, 281, 812, 182, 218, 821

output should be : 497, 128

答:
If you need to keep the digits only, then you can sort before storing:

var newList = [],
  list = [345, 453, 497, 479, 749, 128, 281, 812, 182, 218, 821, 128, 281, 812, 182, 218, 821, 497, 479, 749, 128, 281, 812, 182, 218, 821, 497, 128];
list.forEach(function(item) {
  var norm = +String(item).split("").sort().join("");
  if (newList.indexOf(norm) == -1) newList.push(norm); // or save item instead
})
console.log(newList);```


问:
Design a layout from bottom to top
I want to programm a quiz app for android. My layout should look/looks like this:
Layout

The problem is, when I first designed it I had no idea about layouting for different screen sizes. Now i do have an idea about it, but my question is: Can I stick the timer and points to the top, and the answers and the ad banner to the bottom to let the question textview be as big as possible? Because if I switch to a device with a resolution > 1080x1920 everything jumps to the top.

Sorry if my question had already been asked, it's my first post here, be kind please ;-)

Dave

Edit: Now I put alignParentBottom on the answers and the ad banner, and they are aligned to the bottom, but I don't know how to let the question textviews height scale automatically.

答:
Use a RelativeLayout and anchor the top and bottom views using alignParentBottom / alignParentTop together with height="wrap_content".
Then anchor the remaining views above or below the others, as needed, and set their height to match_parent.

Title: Design a layout from bottom to top


问:
Unity save image to gallery android / ios
I am trying to save my screenshot to the image gallery of my device.
It works fine but it won't show up in the gallery.

This is what I do

```<code>selfie= new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
selfie.ReadPixels(new Rect(0, 0,Screen.width, Screen.height), 0, 0,false);

selfie.Apply ();
byte[] bytes = selfie.EncodeToPNG();
string filename = "Screenshot.png";

fileLocation = Path.Combine( Application.persistentDataPath, filename );
File.WriteAllBytes(fileLocation, bytes );

string myFolderLocation = "/mnt/sdcard/DCIM/Camera/";
myScreenshotLocation = myFolderLocation + filename;

System.IO.File.Move(fileLocation, myScreenshotLocation);
</code>```

It saves the image on the right place. If I look it up on the sdcard, it is there.
But in the gallery it is not showing up. So I tried this after File.move, to refresh the gallery.

```<code>//REFRESHING THE ANDROID PHONE PHOTO GALLERY IS BEGUN
    AndroidJavaClass classPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject objActivity = classPlayer.GetStatic<AndroidJavaObject>("currentActivity");
    AndroidJavaClass classUri = new AndroidJavaClass("android.net.Uri");
    AndroidJavaObject objIntent = new AndroidJavaObject("android.content.Intent", new object[2]{"android.intent.action.MEDIA_MOUNTED", classUri.CallStatic<AndroidJavaObject>("parse", "file://" + myScreenshotLocation)});
    objActivity.Call ("sendBroadcast", objIntent);
//REFRESHING THE ANDROID PHONE PHOTO GALLERY IS COMPLETE
</code>```

But this is doing nothing.
I am working with the latest Unity version 5.3 and it should work on all android and ios devices. Any ideas how to get this working and show up anywhere in the galler?

Thank you!

答:
```<code>    AndroidJavaClass classPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject objActivity = classPlayer.GetStatic<AndroidJavaObject>("currentActivity");
    AndroidJavaClass classMedia = new AndroidJavaClass("android.media.MediaScannerConnection");
    classMedia.CallStatic("scanFile", new object[4] { objActivity,
        new string[] { _path },
        new string[] { "image/png" },
        null  });
</code>```

Try the code above, since you have already saved the image. Just replace the _path with your myScreenshotLocation. Note this will only works with android KitKat 4.4 above.

Body:
I am trying to save my screenshot to the image gallery of my device.
It works fine but it won't show up in the gallery.

This is what I do

selfie= new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
selfie.ReadPixels(new Rect(0, 0,Screen.width, Screen.height), 0, 0,false);

selfie.Apply ();
byte[] bytes = selfie.EncodeToPNG();
string filename = "Screenshot.png";

fileLocation = Path.Combine( Application.persistentDataPath, filename );
File.WriteAllBytes(fileLocation, bytes );

string myFolderLocation = "/mnt/sdcard/DCIM/Camera/";
myScreenshotLocation = myFolderLocation + filename;

System.IO.File.Move(fileLocation, myScreenshotLocation);

It saves the image on the right place. If I look it up on the sdcard, it is there.
But in the gallery it is not showing up. So I tried this after File.move, to refresh the gallery.

//REFRESHING THE ANDROID PHONE PHOTO GALLERY IS BEGUN
    AndroidJavaClass classPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject objActivity = classPlayer.GetStatic<AndroidJavaObject>("currentActivity");
    AndroidJavaClass classUri = new AndroidJavaClass("android.net.Uri");
    AndroidJavaObject objIntent = new AndroidJavaObject("android.content.Intent", new object[2]{"android.intent.action.MEDIA_MOUNTED", classUri.CallStatic<AndroidJavaObject>("parse", "file://" + myScreenshotLocation)});
    objActivity.Call ("sendBroadcast", objIntent);
//REFRESHING THE ANDROID PHONE PHOTO GALLERY IS COMPLETE

But this is doing nothing.
I am working with the latest Unity version 5.3 and it should work on all android and ios devices. Any ideas how to get this working and show up anywhere in the galler?

Thank you!

Body:
    AndroidJavaClass classPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject objActivity = classPlayer.GetStatic<AndroidJavaObject>("currentActivity");
    AndroidJavaClass classMedia = new AndroidJavaClass("android.media.MediaScannerConnection");
    classMedia.CallStatic("scanFile", new object[4] { objActivity,
        new string[] { _path },
        new string[] { "image/png" },
        null  });

Try the code above, since you have already saved the image. Just replace the _path with your myScreenshotLocation. Note this will only works with android KitKat 4.4 above.


问:
how can i add foreign key to existing class in django
I have two simple models of country and town:

```<code>from django.db import models

class Country(models.Model):
    name = models.CharField(max_length=50)

class Town(models.Model):
    belongs_to = models.ForeignKey(country, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
</code>```

Now I would like to play around a bit... and I would like to add continent. I guess correct way from the start would be to do this:

```<code>from django.db import models

class Continent(models.Model):
    name = models.CharField(max_length=50)

class Country(models.Model):
    belongs_to = models.ForeignKey(continent, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)

class Town(models.Model):
    belongs_to = models.ForeignKey(country, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
</code>```

If I do that and save the file, add continents in admin.py to admin.site.register(continent), start with makemigrations... I get this:

You are trying to add a non-nullable field 'belongs' to country without a default; we can't do that (the database needs som
ething to populate existing rows).
Please select a fix:

1.) Provide a one-off default now (will be set on all existing rows
with a null value for this column)  2.) Quit, and let me add a
default in models.py

I get stuck here, because I do not know what to do from here?

答:
I think the message you get is quite self explanatory.

You are adding the belongs_to field to the country model (classes should be named with first capital letter, like this Country though) but it's declared as not nullable. That is, it must have a value declared.

Now, because you already have some rows (objects) of the country model populated, Django asks you what value of belongs_to should add to those existing rows.

There are 2 solutions to this:

Add an integer (which is going to be the id of the continent model) to all of them and change it later, or

Change to belongs_to = models.ForeignKey(continent, on_delete=models.CASCADE, null=True, blank=True) so that after you migrate this field can be nullable, so existing rows will have that field as null.

Hope you understand.

ContentLicense: CC BY-SA 4.0

Body:
I have two simple models of country and town:

from django.db import models

class Country(models.Model):
    name = models.CharField(max_length=50)

class Town(models.Model):
    belongs_to = models.ForeignKey(country, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)

Now I would like to play around a bit... and I would like to add continent. I guess correct way from the start would be to do this:

from django.db import models

class Continent(models.Model):
    name = models.CharField(max_length=50)

class Country(models.Model):
    belongs_to = models.ForeignKey(continent, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)

class Town(models.Model):
    belongs_to = models.ForeignKey(country, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)

If I do that and save the file, add continents in admin.py to admin.site.register(continent), start with makemigrations... I get this:

You are trying to add a non-nullable field 'belongs' to country without a default; we can't do that (the database needs som
ething to populate existing rows).
Please select a fix:

1.) Provide a one-off default now (will be set on all existing rows
with a null value for this column)  2.) Quit, and let me add a
default in models.py

I get stuck here, because I do not know what to do from here?


问:
ElasticSearch : search more like this in java
Let's say I've indexed a document like this :

```<code>{
    "_index": "indexapm",
    "_type": "membres",
    "_id": "3708",
    "_score": 1,
    "_source": {
          "firstname": "John",
          "lastname": "GUERET-TALON"
     }
}
</code>```

I want to retrieve this document when searching for "GUER", "GUERET", "TAL" for example.

I have a Java application and I tried this :

```<code>MoreLikeThisQueryBuilder qb = QueryBuilders.moreLikeThisQuery(
            "firstname^3",
            "lastname^3")
            .likeText("GUER");

SearchResponse response = client.prepareSearch("myindex")
            .setTypes("mytype")
            .setSearchType(SearchType.DFS_QUERY_AND_FETCH)
            .setQuery(qb)             // Query
            .setFrom(0)
            .setSize(limit)
            .setExplain(true)
            .execute()
            .actionGet();
</code>```

But this search doen't retrieve my document. Of course if I try an exact match query and search for "GUERET", it works.

Does anyone know what kind of query I have to use and how to make it work with the Java library? Thanks!

答:
```<code>QueryBuilders.boolQuery().should(QueryBuilders.wildcardQuery("lastname", "*GUER*"));
</code>```

I got the result using WildcardQueryBuilder it generates following:

```<code>{"bool":{"should":[{"wildcard":{"firstname":"*GUER*"}}]}}
</code>```

Body:
Let's say I've indexed a document like this :

{
    "_index": "indexapm",
    "_type": "membres",
    "_id": "3708",
    "_score": 1,
    "_source": {
          "firstname": "John",
          "lastname": "GUERET-TALON"
     }
}

I want to retrieve this document when searching for "GUER", "GUERET", "TAL" for example.

I have a Java application and I tried this :

MoreLikeThisQueryBuilder qb = QueryBuilders.moreLikeThisQuery(
            "firstname^3",
            "lastname^3")
            .likeText("GUER");

SearchResponse response = client.prepareSearch("myindex")
            .setTypes("mytype")
            .setSearchType(SearchType.DFS_QUERY_AND_FETCH)
            .setQuery(qb)             // Query
            .setFrom(0)
            .setSize(limit)
            .setExplain(true)
            .execute()
            .actionGet();

But this search doen't retrieve my document. Of course if I try an exact match query and search for "GUERET", it works.

Does anyone know what kind of query I have to use and how to make it work with the Java library? Thanks!

Body:
QueryBuilders.boolQuery().should(QueryBuilders.wildcardQuery("lastname", "*GUER*"));

I got the result using WildcardQueryBuilder it generates following:

{"bool":{"should":[{"wildcard":{"firstname":"*GUER*"}}]}}


问:
Is it possible to get FTP to work in VirtualBox using NAT networking or get php's ftp functions to work
I'm trying to get php's ftp methods to work from within a VM.  I can connect using ftp_connect but not actually do anything afterwards.

HOST: Ubuntu 14.10
 GUEST: Debian 7
 Stack: Vagrant - VirtualBox - Debian - LAMP

I'm using vagrant to run a virtual box VM that runs a lamp stack.  In php I'm running some method calls (ftp_pasv, ftp_nlist) that are not working.
I discovered that because of the FTP protocol using random ports for connections, the issue is caused by the use of NAT networking in virtualbox.  I have the perfect vagrant-virtualbox setup except for this one issue.  Does anyone know of a method to get ftp to work on the guest OS in this scenario.  I know I could try using a bridged setup, but that means a bunch more work setting it up and the machine will be available to the public.  So I would prefer to try to get it working behind that NAT.

I also have tried to use ftp_pasv to get passive mode turned on, which would fix the issue.  But the method returns false when I call it to turn on passive mode.

答: I had this issue and it turned out that upgrading Virtual Box solved the issue. Possibly some bug in the NAT interface.</p>


问:
How can I disable the responsive behaviour in Bootstrap 4?
How can I disable the responsive behaviour in Bootstrap 4, while maintaining the styles? I want users that access the website in the mobile phone to have the same website as the desktop version and zoom in and zoom out with finger gestures. How can I do it?</p>

答:
While Bootstrap is not really made to be unresponsive, you can achieve something like that by altering the viewport meta-tag.

<meta name="viewport" content="initial-scale=0.1">

This will set the initial scale at 10% of the original scale.

Also see https://www.w3.org/TR/css-device-adapt-1/#translate-meta-to-at-viewport for more.


问:
Get Length of nested JavaScript object
I want to fill a list with elements from a database. The data comes from a PHP file in JSON format. The JSON looks like this:

{"Venues" : [{"name":"McManus Galleries","id":"1"},{"name":"Dundee Law","id":"2"},{"name":"University of Abertay","id":"3"},{"name":"Baxter Park","id":"4"},{"name":"Overgate Shopping Centre","id":"5"}]}
```

<p>Now I am handling this text with the following code: </p>

<pre class="lang-js prettyprint-override"><code>obj = JSON.parse(this.responseText);

document.getElementById("list").innerHTML = "" + obj.Venues[0].name + "<br>";
document.getElementById("list").innerHTML += "" + obj.Venues[1].name + "<br>";
</code>```

...and it works, but now I want to do it with a for-loop so no matter how many items "Venues" contains it is showing them all in the list. I got this code right now:

for(i = 0; i < obj.length; i++){
  document.getElementById("list").innerHTML += obj.Venues[i].name;
}
```

The problem here is, that obj.length returns 1. Does anybody know how to solve this?

答:
obj is the main object that has child Venues (that is an array to be used for iteration as below)

for(i = 0; i < obj.Venues.length; i++){
  document.getElementById("list").innerHTML += obj.Venues[i].name;
}```

Title: Get Length of nested JavaScript object

Body:
I want to fill a list with elements from a database. The data comes from a PHP file in JSON format. The JSON looks like this:

{"Venues" : [{"name":"McManus Galleries","id":"1"},{"name":"Dundee Law","id":"2"},{"name":"University of Abertay","id":"3"},{"name":"Baxter Park","id":"4"},{"name":"Overgate Shopping Centre","id":"5"}]}

Now I am handling this text with the following code:

obj = JSON.parse(this.responseText);

document.getElementById("list").innerHTML = "" + obj.Venues[0].name + "
";
document.getElementById("list").innerHTML += "" + obj.Venues[1].name + "
";

...and it works, but now I want to do it with a for-loop so no matter how many items "Venues" contains it is showing them all in the list. I got this code right now:

for(i = 0; i < obj.length; i++){
  document.getElementById("list").innerHTML += obj.Venues[i].name;
}

The problem here is, that obj.length returns 1. Does anybody know how to solve this?


问:
Weird query string at the end of url posts in worspress
This is a basic url format in my wordpress site:

mysite.com/lang/name-of-post/

or mysite.com/name-of-post/

The problem is that wordpress adds this query string at the end of the url:

.WNzbB2f-uM8

So it becomes mysite.com/lang/name-of-post/#.WNzbB2f-uM8

How to remove this query string?

答:
1- first go to settings / permalinks menu and see it's option for this string .

2- second change your active theme with default wordpress theme like 2016 and check url.

3- third disable all plugin and see your site urls for this string

i thinks you can find the problem with above suggestions


问:
Class 'Inline\PDF\PDF' not found in laravel using wemersonjanuario/laravelpdf package
I am trying to use this package -> http://packalyst.com/packages/package/wemersonjanuario/laravelpdf

I have installed and configured as per the website and also I had used this package couple of times which worked following the same procedure.

But now its giving the error Class 'Inline\PDF\PDF' not found

Not sure whats the mistake.

Can someone please help me sort this issue.

Below is the sample code

Composer.json file

```<code>"h4cc/wkhtmltopdf-i386": "0.12.3",
"wemersonjanuario/laravelpdf": "1.0.*"
</code>```

app.php file

```<code>'providers' => [
        //  other providers
        Inline\LaravelPDF\PDFServiceProvider::class
    ],

'aliases' => [
        // other aliases
        'PDF' => Inline\LaravelPDF\PDFFacade::class,

    ],
</code>```

In config/laravelpdf.php file

```<code><?php
return [
    'executable' => base_path().'/vendor/h4cc/wkhtmltopdf-i386/bin/wkhtmltopdf-i386'
];
</code>```

PHP Pdf code

```<code>use Inline\LaravelPDF\PDFFacade as PDF;

class SummaryHelper
{
   public function getReport($date)
   {
      // Some code
      $data = [ ];   // some data in it

      $pdf_obj = PDF::loadView('vendor/daily-report', $data);
   }
}
</code>```

Github issue link

答:
I've installed the package and got the same error. The thing is it's just a fork from another package and the guy didn't updated readme.md for correct namespaces. What you need to do it to change Inline to Novanti in config/app.php. Both for service provider and facade.

Then add this to the class where you want to use PDF facade:

```<code>use PDF;
</code>```

Or just use full namespace:

```<code>$pdf_obj = \PDF::loadView('vendor/daily-report', $data);
</code>```

Body:
I am trying to use this package -> http://packalyst.com/packages/package/wemersonjanuario/laravelpdf

I have installed and configured as per the website and also I had used this package couple of times which worked following the same procedure.

But now its giving the error Class 'Inline\PDF\PDF' not found

Not sure whats the mistake.

Can someone please help me sort this issue.

Below is the sample code

Composer.json file

"h4cc/wkhtmltopdf-i386": "0.12.3",
"wemersonjanuario/laravelpdf": "1.0.*"

app.php file

'providers' => [
        //  other providers
        Inline\LaravelPDF\PDFServiceProvider::class
    ],

'aliases' => [
        // other aliases
        'PDF' => Inline\LaravelPDF\PDFFacade::class,

    ],

In config/laravelpdf.php file

<?php
return [
    'executable' => base_path().'/vendor/h4cc/wkhtmltopdf-i386/bin/wkhtmltopdf-i386'
];

PHP Pdf code

use Inline\LaravelPDF\PDFFacade as PDF;

class SummaryHelper
{
   public function getReport($date)
   {
      // Some code
      $data = [ ];   // some data in it

      $pdf_obj = PDF::loadView('vendor/daily-report', $data);
   }
}

Github issue link

Body:
I've installed the package and got the same error. The thing is it's just a fork from another package and the guy didn't updated readme.md for correct namespaces. What you need to do it to change Inline to Novanti in config/app.php. Both for service provider and facade.

Then add this to the class where you want to use PDF facade:

use PDF;

Or just use full namespace:

$pdf_obj = \PDF::loadView('vendor/daily-report', $data);


问:
Liquibase loading data from csv
I want to load an entire column of my PostgreSql table with data from csv file but when I do that I get an exception saying that the primary key of my table should not be null. It looks like Liquibase is creating new rows to insert the data. Is there a way to load the data in existing rows ?</p>

```<code>DatabaseChangeLog dbChangeLog = new DatabaseChangeLog();
Liquibase liquibase = new Liquibase(dbChangeLog, new FileSystemResourceAccessor(), database);
ChangeSet loadChangeSet = new ChangeSet(id + "", "nasri", false, false, "", "", "", liquibase.getDatabaseChangeLog());

LoadDataChange loadDataChange = new LoadDataChange();
loadDataChange.setTableName(key);
loadDataChange.setChangeSet(loadChangeSet);
loadDataChange.setResourceAccessor(new FileSystemResourceAccessor());

String path = context.getBundle().getVersion() + "." + key + "." + columnKey + "." + targetFieldKey + ".csv";
loadDataChange.setFile(path);

loadDataChange.setSchemaName("public");

LoadDataColumnConfig columnConfig = new LoadDataColumnConfig();
columnConfig.setName(targetFieldKey);
columnConfig.setType("String");
loadDataChange.addColumn(columnConfig);
loadChangeSet.addChange(loadDataChange);
liquibase.getDatabaseChangeLog().addChangeSet(loadChangeSet);
liquibase.update("");
</code>```

答:
There is a class thats called: LoadUpdateDataChange

The description says:

Loads or updates data from a CSV file into an existing table. Differs from loadData by issuing a SQL batch that checks for the existence of a record. If found, the record is UPDATEd, else the record is INSERTed. Also, generates DELETE statements for a rollback.

Looks like it should do what you are looking for (I have not used this myself though).

Title: Liquibase loading data from csv

Body:
I want to load an entire column of my PostgreSql table with data from csv file but when I do that I get an exception saying that the primary key of my table should not be null. It looks like Liquibase is creating new rows to insert the data. Is there a way to load the data in existing rows ?

DatabaseChangeLog dbChangeLog = new DatabaseChangeLog();
Liquibase liquibase = new Liquibase(dbChangeLog, new FileSystemResourceAccessor(), database);
ChangeSet loadChangeSet = new ChangeSet(id + "", "nasri", false, false, "", "", "", liquibase.getDatabaseChangeLog());

LoadDataChange loadDataChange = new LoadDataChange();
loadDataChange.setTableName(key);
loadDataChange.setChangeSet(loadChangeSet);
loadDataChange.setResourceAccessor(new FileSystemResourceAccessor());

String path = context.getBundle().getVersion() + "." + key + "." + columnKey + "." + targetFieldKey + ".csv";
loadDataChange.setFile(path);

loadDataChange.setSchemaName("public");

LoadDataColumnConfig columnConfig = new LoadDataColumnConfig();
columnConfig.setName(targetFieldKey);
columnConfig.setType("String");
loadDataChange.addColumn(columnConfig);
loadChangeSet.addChange(loadDataChange);
liquibase.getDatabaseChangeLog().addChangeSet(loadChangeSet);
liquibase.update("");


问:
how do I compile with 3.2 even though I have 4.1.2 installed
I am having trouble with the new 4.1 for iPad. I want to still compile against 3.2. Do I set the base version in the project settings? If so, why is it marked as missing? How do I get it and where do I put it?

Sorry a lot of questions there but they have changed the way drawing works and I don't want to change my whole app right now. My app when compiled against 3.2 works on 4.1 iPads fine, but not when compiled against 4.2. Is this because when you compile against an iOS version it imports the frameworks from that iOS version?

答:
yeah unfortunately Apple are doing everything to "unmarket" any previous versions of iOS.

After you update your XCode with the latest version usually you see "Base SDK missing" and you need to update your project configuration to get it compiling again. Double click the project item in your project tree (or right click it and choose Get info) and in the properties windows choose the tab called "Build" (make sure you have "All configurations" selected in the Configuration select box), then find the "Base SDK" property - this is the version of iOS which you are targeting (apple usually make sure to be able to select only the latest iOS version here), then find the property called "iOS deployment target" - here you select the earliest version of iOS you will support - choose here 3.2 in your case.

There you go :) Just couple of notes:

when you make those changes to the project properties, you might need to close XCode and run it again and open the project again - sometimes it does work right after you change your project properties

if you support 3.2 make sure that if you add frameworks from 4.x to your project you soft link them, so it doesn't crash under 3.2 bcz the frameworks don't exist on the device

Marin


问:
Export data into SPSS file (*.sav)
Is there any solution to export data into SPSS (*.sav) files?
I have a web service with surveys, and result needed to be exported to different formats.
I cant find any solution for SPSS.
(in any language, free or non-free products - but need to execute on the server!)</p>

答:
I found a good library https://github.com/tiamo/spss.
It was updated, and works as a charm</p>

Title: Export data into SPSS file (*.sav)


问:
How to get Switch value from one Activity and display it in other activity
I am a beginner in Android application development. I'm just trying to get Switch value from one Activity and display it in another activity. But I am getting 'null' as output. Please help me.

Question1.java

```<code>public class Question1Activity extends AppCompatActivity {
Switch swi;
Button back1, next1;
String value = "NO";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_question1);
    swi = (Switch) findViewById(R.id.Switch_Ques_1);
    back1 = (Button) findViewById(R.id.Button_back1);
    next1 = (Button) findViewById(R.id.Button_next1);
    swi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                                     boolean isChecked) {

            if (isChecked) {
                swi.setText("YES");
                value="YES";
                swi.setTextColor(Color.GREEN);
            } else {
                swi.setText("NO");
                value="NO";
                swi.setTextColor(Color.RED);
            }

        }
    });
    back1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent intent = new Intent(Question1Activity.this,LoginActivity.class);
            startActivity(intent);
        }
    });
    next1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent intent = new Intent(Question1Activity.this,Question2Activity.class);
            intent.putExtra("Ans1",swi.isChecked());
            startActivity(intent);
        }
    });
}
}
</code>```

Question3.java

```<code>public class Question3Activity extends AppCompatActivity {
TextView t1;
private SQLiteDatabase database;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_question3);
    t1 = (TextView) findViewById(R.id.result);
    Intent intent = getIntent();
    String s1 =(String) intent.getStringExtra("Ans1");
    String s2 = intent.getStringExtra("Ans2");
    t1.setText(s1+" "+s2);
}
}
</code>```

答:
In Question3.java, you are getting the intent method of getStringExtra although the value you want to pass is a switch value.

Option 1:  Use .toString method to convert the value from the switch widget to get the value in String.

Option 2 (Recommended): Since you already have the setup to take String values in Question3 class, simply pass the value string and just get it in the next Activity.

Hope it helps.

Body:
I am a beginner in Android application development. I'm just trying to get Switch value from one Activity and display it in another activity. But I am getting 'null' as output. Please help me.

Question1.java

public class Question1Activity extends AppCompatActivity {
Switch swi;
Button back1, next1;
String value = "NO";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_question1);
    swi = (Switch) findViewById(R.id.Switch_Ques_1);
    back1 = (Button) findViewById(R.id.Button_back1);
    next1 = (Button) findViewById(R.id.Button_next1);
    swi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                                     boolean isChecked) {

            if (isChecked) {
                swi.setText("YES");
                value="YES";
                swi.setTextColor(Color.GREEN);
            } else {
                swi.setText("NO");
                value="NO";
                swi.setTextColor(Color.RED);
            }

        }
    });
    back1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent intent = new Intent(Question1Activity.this,LoginActivity.class);
            startActivity(intent);
        }
    });
    next1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent intent = new Intent(Question1Activity.this,Question2Activity.class);
            intent.putExtra("Ans1",swi.isChecked());
            startActivity(intent);
        }
    });
}
}

Question3.java

public class Question3Activity extends AppCompatActivity {
TextView t1;
private SQLiteDatabase database;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_question3);
    t1 = (TextView) findViewById(R.id.result);
    Intent intent = getIntent();
    String s1 =(String) intent.getStringExtra("Ans1");
    String s2 = intent.getStringExtra("Ans2");
    t1.setText(s1+" "+s2);
}
}