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

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

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

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

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private LocationManager locationManager;

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

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

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

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

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

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

                }
            });
        }
    }

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

    }

}
</code>```

答:
check this code its working for me </p>

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    //buildGoogleApiClient();

    // 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);

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    mMap.setMyLocationEnabled(true);

    //add this here:
    buildGoogleApiClient();

    //LatLng loc = new LatLng(lat, lng);
    //mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
    //mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}

@Override
public void onConnected(Bundle bundle) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        lat = mLastLocation.getLatitude();
        lng = mLastLocation.getLongitude();

        LatLng loc = new LatLng(lat, lng);
        mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
    }
}
</code>```

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

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

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

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

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private LocationManager locationManager;

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

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

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

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

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

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

                }
            });
        }
    }

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

    }

}

Body:
check this code its working for me

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

    // 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);

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    mMap.setMyLocationEnabled(true);

    //add this here:
    buildGoogleApiClient();

    //LatLng loc = new LatLng(lat, lng);
    //mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
    //mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}

@Override
public void onConnected(Bundle bundle) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        lat = mLastLocation.getLatitude();
        lng = mLastLocation.getLongitude();

        LatLng loc = new LatLng(lat, lng);
        mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
    }
}


来源: stackexchange

问:
React-native shadow not appearing
I'm trying to get a shadow below my views, and from what I found online it should be quite simple:

shadowOffset: { width: 10, height: 10 },
shadowColor: 'black',
shadowOpacity: 1.0,
```
<p>but the problem is that the shadow is not appearing at all.</p>
<p>Here's my components</p>
<pre class="lang-html prettyprint-override"><code><View style={styles.shadow}>
    <View style={styles.box} >
        <View style={styles.ListComponent}>
            <Text style={styles.itemText}>Livestream</Text>
        </View>
    </View>
</View>
</code>```

and in my StyleSheet:

const styles = StyleSheet.create({
    shadow: {
    shadowOffset: { width: 10, height: 10 },
    shadowColor: 'black',
    shadowOpacity: 1.0
},
```

Any reason for this or is there something I've missed?

答:
Is the shadow working on IOs ?
Android and IOS work ≠ in React-Native. For android, it works with elevation.

```<code>const styles = StyleSheet.create({
shadow: {
  shadowOffset: { width: 10, height: 10 },
  shadowColor: 'black',
  shadowOpacity: 1,
  elevation: 3,
  // background color must be set
  backgroundColor : "#0000" // invisible color
}
</code>```

Otherwise, try to set a background color to your shadow component :)

ContentLicense: CC BY-SA 4.0

Title: React-native shadow not appearing

Body:
I'm trying to get a shadow below my views, and from what I found online it should be quite simple:

shadowOffset: { width: 10, height: 10 },
shadowColor: 'black',
shadowOpacity: 1.0,

but the problem is that the shadow is not appearing at all.

Here's my components

<View style={styles.shadow}>
    <View style={styles.box} >
        <View style={styles.ListComponent}>
            <Text style={styles.itemText}>Livestream</Text>
        </View>
    </View>
</View>

and in my StyleSheet:

const styles = StyleSheet.create({
    shadow: {
    shadowOffset: { width: 10, height: 10 },
    shadowColor: 'black',
    shadowOpacity: 1.0
},

Any reason for this or is there something I've missed?

Body:
Is the shadow working on IOs ?
Android and IOS work ≠ in React-Native. For android, it works with elevation.

const styles = StyleSheet.create({
shadow: {
  shadowOffset: { width: 10, height: 10 },
  shadowColor: 'black',
  shadowOpacity: 1,
  elevation: 3,
  // background color must be set
  backgroundColor : "#0000" // invisible color
}

Otherwise, try to set a background color to your shadow component :)

ContentLicense: CC BY-SA 3.0


问:
Git rebase local vs git pull --rebase origin
I have a local (never pushed to a remote) feature branch F1 made from master with a few commits. I don't seem to understand a difference between these two actions (F1 is the current branch):

```<code>git fetch origin
git rebase master
</code>```

and

```<code>git pull --rebase origin master
</code>```

My expectation is that they should be equivalent but they aren't - different results are produced.

What's wrong with my thinking?

答:
1. git fetch origin and git rebase master will apply changes from F1 to local master branch. Assume your commit history looks like below at first (the remote master branch has commit J in remote):

```<code>A---B---C---D---E    master
         \
          F---G---H  F1
</code>```

When you execute git fetch origin and git rebase master, even though origin/master points to J, it will only rebase F1 branch on the top of local master branch (commit E as the graph):

```<code>A---B---C---D---E(master)---J origin/master
                 \
                  F---G---H    F1
</code>```

2. The command git pull --rebase origin master will pull changes from remote master branch at first, then rebase current branch F1 on the top of it:

```<code>A---B---C---D---E---J      master,origin/master
                     \
                      F---G---H  F1
</code>```

In a word, if local master branch is sync with remote master branch, these two ways have the same result (rebase F1 branch on the top of master branch). If remote master branch has new commit(s) which is(are) not exist on local master branch, the results are different (one rebases on local master branch, the other rebase on origin/master branch).

Body:
I have a local (never pushed to a remote) feature branch F1 made from master with a few commits. I don't seem to understand a difference between these two actions (F1 is the current branch):

git fetch origin
git rebase master

and

git pull --rebase origin master

My expectation is that they should be equivalent but they aren't - different results are produced.

What's wrong with my thinking?

Body:
1. git fetch origin and git rebase master will apply changes from F1 to local master branch. Assume your commit history looks like below at first (the remote master branch has commit J in remote):

A---B---C---D---E    master
         \
          F---G---H  F1

When you execute git fetch origin and git rebase master, even though origin/master points to J, it will only rebase F1 branch on the top of local master branch (commit E as the graph):

A---B---C---D---E(master)---J origin/master
                 \
                  F---G---H    F1

2. The command git pull --rebase origin master will pull changes from remote master branch at first, then rebase current branch F1 on the top of it:

A---B---C---D---E---J      master,origin/master
                     \
                      F---G---H  F1

In a word, if local master branch is sync with remote master branch, these two ways have the same result (rebase F1 branch on the top of master branch). If remote master branch has new commit(s) which is(are) not exist on local master branch, the results are different (one rebases on local master branch, the other rebase on origin/master branch).


问:
How to invoke method from one component to another component in Angular 2?
I have two different component - one component has click event method for the list users & I want to inherit(invoke) that click event method on detail page(another component) )

How to do that, Please help me...

ANSWER UPDATE

Thanks For your Answers.

I have got the solution by Using extend Class & using super() in constructor.

First Class

```<code>export class TeamsView {
   constructor(private test:TestService){
   }
   ...
}
</code>```

Second Class

```<code>export class TeamsForm extends TeamsView {
   constructor(private test:TestService, private router: Router){
     super(test)
   }
   ...
}
</code>```

答:
Add common method in service

```<code>import {Injectable} from '@angular/core';
@Injectable()
export class MyService {
  constructor() { }
  doSomething(val) {
    return !val;
  }
}
</code>```

Use that in components by injecting that service, one component code follows. Write same as this in other component too.

```<code>import {Component, OnInit} from '@angular/core';
import {MyService} from './shared/my-service'; // see angular.io/styleguide

@Component({
  selector: '<my-component></my-component>',
  templateUrl: 'app/name.component.html',
  // This is unnecessary when installing MyService within Root NgModule
  providers: [MyService]
})

export class MyComponent implements OnInit {

  value1: boolean = true;

  constructor(private ms: MyService) {}

  ngOnInit() {  }

  click() {
    this.ms.doSomething(value1);
  }
}
</code>```

HTML

```<code><input type="button" (click)="click()">
</code>```

Body:
I have two different component - one component has click event method for the list users & I want to inherit(invoke) that click event method on detail page(another component) )

How to do that, Please help me...

ANSWER UPDATE

Thanks For your Answers.

I have got the solution by Using extend Class & using super() in constructor.

First Class

export class TeamsView {
   constructor(private test:TestService){
   }
   ...
}

Second Class

export class TeamsForm extends TeamsView {
   constructor(private test:TestService, private router: Router){
     super(test)
   }
   ...
}

Body:
Add common method in service

import {Injectable} from '@angular/core';
@Injectable()
export class MyService {
  constructor() { }
  doSomething(val) {
    return !val;
  }
}

Use that in components by injecting that service, one component code follows. Write same as this in other component too.

import {Component, OnInit} from '@angular/core';
import {MyService} from './shared/my-service'; // see angular.io/styleguide

@Component({
  selector: '<my-component></my-component>',
  templateUrl: 'app/name.component.html',
  // This is unnecessary when installing MyService within Root NgModule
  providers: [MyService]
})

export class MyComponent implements OnInit {

  value1: boolean = true;

  constructor(private ms: MyService) {}

  ngOnInit() {  }

  click() {
    this.ms.doSomething(value1);
  }
}

HTML

<input type="button" (click)="click()">


问:
Python, copying a rank 2 list structure with different values
Using python 3.6

Say I had this dictionary and list structure of keys:

```<code>dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}

keys = [['a','b'], ['c','d','e']]
</code>```

Whats the best way to get this?

```<code>values = [[1, 2], [3, 4, 5]]
</code>```

Thanks!

答:
Here's an alternative approach with a map:

```<code>dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
keys = [['a','b'], ['c','d','e']]

items = [list(map(dictionary.get, k)) for k in keys]
</code>```

Output:

```<code>[[1, 2], [3, 4, 5]]
</code>```

One huge plus point is it's a lot more robust with handling non-existent keys (thanks, @Ev.Kounis!).

Alternative ft. Ev Kounis involving returning a default value on no-key:

```<code>items = [[dictionary.get(x, 0) for x in sub] for sub in keys]
</code>```

Body:
Using python 3.6

Say I had this dictionary and list structure of keys:

dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}

keys = [['a','b'], ['c','d','e']]

Whats the best way to get this?

values = [[1, 2], [3, 4, 5]]

Thanks!

Body:
Here's an alternative approach with a map:

dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
keys = [['a','b'], ['c','d','e']]

items = [list(map(dictionary.get, k)) for k in keys]

Output:

[[1, 2], [3, 4, 5]]

One huge plus point is it's a lot more robust with handling non-existent keys (thanks, @Ev.Kounis!).

Alternative ft. Ev Kounis involving returning a default value on no-key:

items = [[dictionary.get(x, 0) for x in sub] for sub in keys]


问:
Dictionary in python with order I set at start
I'm making dictionary:

```<code>d = {"server":"mpilgrim", "database":"master"}
d['mynewkey'] = 'mynewvalue'
</code>```

But when I display it I saw that this dict is reversed.

```<code>print(d)

{'mynewkey': 'mynewvalue', 'database': 'master', 'server': 'mpilgrim'}
</code>```

How to reverse it back?

Or if it is true that dictionary is not sortable what I must to use to have collection where the order of that informations matters?

答:
Your dictionnary is not quite reverted. It is sorted partly according to the hash of you keys. You can't change this order (not without using a custom dictionary). In python 2.7 or later you can use an ordered dictionary (collections.OrderedDict).

In earlier version you can use the following recipe.

Also have a look at this question : What is the best ordered dict implementation in python?

Body:
I'm making dictionary:

d = {"server":"mpilgrim", "database":"master"}
d['mynewkey'] = 'mynewvalue'

But when I display it I saw that this dict is reversed.

print(d)

{'mynewkey': 'mynewvalue', 'database': 'master', 'server': 'mpilgrim'}

How to reverse it back?

Or if it is true that dictionary is not sortable what I must to use to have collection where the order of that informations matters?

ContentLicense: CC BY-SA 2.5


问:
Where does Maven store junit jar files
I changed the version of junit from 3.8.1 to 4.11 in my pom file, when I ran maven it downloaded junit 4.11.  I got the message

"Downloaded: https://repo.maven.apache.org/maven2/junit/junit/4.11/junit-4.11.jar (245 kB at 825 kB/s)"

My tests ran fine after the install but I cannot find the jar file anywhere.  Can someone tell me where it is stored?

答:
The jar files that maven downloads by default can be found in:

Windows 10: C:\Users\USERNAME\.m2\repository

Unix/Mac OS: ~/.m2

Title: Where does Maven store junit jar files


问:
On landscape the background blank
In landscape view, When the keyboard appears, the form in the background appears blank as the following picture:
background blank.

When the keyboard slides down, the activity appears correctly.
The correct activity  view

In the portrait view, it works fine.
 Can any one tell me how to fix it?

答:
The keyboard opened in fullscreen mode, covering the entire Activity with it's own UI. A keyboard app can decide to do this if the screen is not large enough to show both itself and the Activity (e.g. landscape on a smartphone).

You can request the keyboard not to go fullscreen by adding the noFullscreen flag in xml:

```<code><EditText
    ...
    android:imeOptions="flagNoFullscreen"
    />
</code>```

Title: On landscape the background blank

Body:
The keyboard opened in fullscreen mode, covering the entire Activity with it's own UI. A keyboard app can decide to do this if the screen is not large enough to show both itself and the Activity (e.g. landscape on a smartphone).

You can request the keyboard not to go fullscreen by adding the noFullscreen flag in xml:

<EditText
    ...
    android:imeOptions="flagNoFullscreen"
    />


问:
How do I generate IDs for objects imported from a .dae-file that will be the same the next load?
I'm building a CMS around THREE.js and I need to keep track of objects through some attribute that doesn't change when loading the file the next time. I'm using DAE-files that are exported from the Sketchup format .skp. The attributes "id" and "uuid" appears to be generated on each load. Sometimes the "name"-attribute have the format "group_41" or "instance_58", but it's often empty which makes it unreliable.

I'm not locked in using .DAE if anyone has another solution, but it's heavily favoured because it's easier to export from Sketchup than having to go through Blender to create the JSON-format (which from my experience also requires a lot of tweaks and settings to work properly).

Does anyone have any experience with this, or a workaround in either Sketchup or another third-party plugin/software to create lasting IDs?

答:
In SketchUp 2017, Entities have a persistent_id which will not change in a SketchUp model between sessions.

You could write a SketchUp Ruby script to rename all Groups to their persistent_id and then you can track the Entities from the SketchUp model to the export file.

http://ruby.sketchup.com/Sketchup/Entity.html#persistent_id-instance_method


问:
i got 'boost::fibers::lock_error' and can't figure out why
i run this code

```<code>class ttt {
public:
    ~ttt() {
        LOG(INFO);
        flush();
    }

    bool flush() {
        //std::lock_guard<boost::fibers::mutex> lock(_mutex);
        LOG(INFO);
        _mutex.lock();
        LOG(INFO);
        auto ret = flush_nonlock();
        LOG(INFO);
        _mutex.unlock();
        LOG(INFO);
        return ret;
    }
private:

    bool flush_nonlock() {
        LOG(INFO);
        return std::rand()%2;
    }
    boost::fibers::mutex _mutex;
};
int main() {
    static ttt t;
    std::cout << t.flush() << std::endl;
    return 0;
}
</code>```

and i got

```<code>terminate called after throwing an instance of 'boost::fibers::lock_error'
  what():  boost fiber: a deadlock is detected: Resource deadlock avoided
</code>```

the last log it print is before the _mutex.lock().
if t is not a static variable, it won't throw any error.
if i remove t.flush() in main func, it won't throw any error.
use std::lock_guard as i wrote in notes, the line next to it is not printed.
i can't figure out why and whats the diff about the cases i tried.

i build the code use gcc 5.4.0, with -O0

答:
static ttt t;

your static instance of ttt in main might be destructed after the internal data of boost.fiber have been destructed. Accesing context::active() in mutext::lock() from ~ttt() might return a null-pointer.

edit: boost.fiber uses internally a thread-local static holding the active fiber (in order to enable suspending from a deep call stack). because ttl is declared static, the compiler can destruct the ttl instance and the boost.fiber internall static in arbitrary order.

Body:
i run this code

class ttt {
public:
    ~ttt() {
        LOG(INFO);
        flush();
    }

    bool flush() {
        //std::lock_guard<boost::fibers::mutex> lock(_mutex);
        LOG(INFO);
        _mutex.lock();
        LOG(INFO);
        auto ret = flush_nonlock();
        LOG(INFO);
        _mutex.unlock();
        LOG(INFO);
        return ret;
    }
private:

    bool flush_nonlock() {
        LOG(INFO);
        return std::rand()%2;
    }
    boost::fibers::mutex _mutex;
};
int main() {
    static ttt t;
    std::cout << t.flush() << std::endl;
    return 0;
}

and i got

terminate called after throwing an instance of 'boost::fibers::lock_error'
  what():  boost fiber: a deadlock is detected: Resource deadlock avoided

the last log it print is before the _mutex.lock().
if t is not a static variable, it won't throw any error.
if i remove t.flush() in main func, it won't throw any error.
use std::lock_guard as i wrote in notes, the line next to it is not printed.
i can't figure out why and whats the diff about the cases i tried.

i build the code use gcc 5.4.0, with -O0


问:
Using https with Identity Server 4
I have followed all the IS4 tutorials here although none highlight how to use the https protocol in prod.  I might have missed something but when I deploy my IS4 server in IIS using https (using a cert I have installed on the IIS server) I can no longer call tokenClient.RequestClientCredentialsAsync. It simply returns Error=Unauthorised and ErrorType=Http as shown in the image:

My IS4 is setup as such

```<code>services.AddIdentityServer()
//.AddSigningCredential(cert)
.AddTemporarySigningCredential()...;
</code>```

I have also tried using the same SSL cert but with no progress.

EDIT (Answer):
Arghhh! I had basic authentication enabled on my deployed IIS site which was causing that error, after disabling it, it worked as expected

答:
AFAIK there are two ways to add https. On your startup project you can add the following code in ConfigureServices method

```<code>public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddMvc();

    if (!_env.IsDevelopment())
        services.Configure<Microsoft.AspNetCore.Mvc.MvcOptions>(o =>
            o.Filters.Add(new Microsoft.AspNetCore.Mvc.RequireHttpsAttribute()));
    //...
}
</code>```

Or adding the RequireHttps attribute into your controller, plus Enabling SSL

Title: Using https with Identity Server 4

Body:
I have followed all the IS4 tutorials here although none highlight how to use the https protocol in prod.  I might have missed something but when I deploy my IS4 server in IIS using https (using a cert I have installed on the IIS server) I can no longer call tokenClient.RequestClientCredentialsAsync. It simply returns Error=Unauthorised and ErrorType=Http as shown in the image:

My IS4 is setup as such

services.AddIdentityServer()
//.AddSigningCredential(cert)
.AddTemporarySigningCredential()...;

I have also tried using the same SSL cert but with no progress.

EDIT (Answer):
Arghhh! I had basic authentication enabled on my deployed IIS site which was causing that error, after disabling it, it worked as expected

Body:
AFAIK there are two ways to add https. On your startup project you can add the following code in ConfigureServices method

public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddMvc();

    if (!_env.IsDevelopment())
        services.Configure<Microsoft.AspNetCore.Mvc.MvcOptions>(o =>
            o.Filters.Add(new Microsoft.AspNetCore.Mvc.RequireHttpsAttribute()));
    //...
}

Or adding the RequireHttps attribute into your controller, plus Enabling SSL


问:
What is the most efficient way to join two lists in C# on a common field?
Could you tell me which one of those list joining methods is more efficient and why? Or is it the same performance-wise? Is there any other approach to this situation (joining 2 lists based on field property)?

My code:

```<code>public List<CombinedDatabaseStructure> Combine1(List<DatabaseStructure1> _Data1, List<DatabaseStructure2> _Data2)
{
    List<CombinedDatabaseStructure> combinedAll = new List<CombinedDatabaseStructure>();
    foreach (var row1 in _Data1)
    {
        foreach (var row2 in _Data2)
        {
            CombinedDatabaseStructure combined = new CombinedDatabaseStructure();
            if (row1.ID == row2.ID)
            {
                combined.DatabaseStructure1 = row1;
                combined.DatabaseStructure2 = row2;
                combinedAll.Add(combined);
            }
        }
    }

    return combinedAll;
}
</code>```

Code2:

```<code>public List<CombinedDatabaseStructure> Combine2(List<DatabaseStructure1> _Data1, List<DatabaseStructure2> _Data2)
{
    var joined = from item1 in _Data1.AsEnumerable()
                 join item2 in _Data2.AsEnumerable() on item1.ID equals item2.ID
                 select new CombinedDatabaseStructure (item1,item2);

    return  joined.ToList<CombinedDatabaseStructure>();
}
</code>```

答:
As a general rule: If there's a built-in method in the .NET framework which does exactly what you want, it's usually a good idea to use it instead of re-implementing it. It's easier, more readable, less error-prone, better tested and usually more efficiently implemented.

Let's look at your particular problem in detail:

Option 1 is basically a manual (naive) implementation of a nested loop join with a complexity of O(n*m).

Option 2 uses LINQ-to-object's implementation of join, which internally uses a hash join, which has a complexity of O(n+m).

If you are worried about efficiency, I'd recommend "Option 3": let the database do the join. It can use statistics to choose the optimal join strategy for your data.

Note: Your nested loop implementation is very inefficient. It can be implemented with O(n*log(m)) complexity by using some kind of index lookup to find matching Data2 rows instead of the inner loop. In that case, a nested loop join can be faster than a hash join, if n is very small and m is large. This, however, assumes that the index already exists, since creating an index (for example, by creating a C# dictionary from your list) is a O(m) operation itself.

Body:
Could you tell me which one of those list joining methods is more efficient and why? Or is it the same performance-wise? Is there any other approach to this situation (joining 2 lists based on field property)?

My code:

public List<CombinedDatabaseStructure> Combine1(List<DatabaseStructure1> _Data1, List<DatabaseStructure2> _Data2)
{
    List<CombinedDatabaseStructure> combinedAll = new List<CombinedDatabaseStructure>();
    foreach (var row1 in _Data1)
    {
        foreach (var row2 in _Data2)
        {
            CombinedDatabaseStructure combined = new CombinedDatabaseStructure();
            if (row1.ID == row2.ID)
            {
                combined.DatabaseStructure1 = row1;
                combined.DatabaseStructure2 = row2;
                combinedAll.Add(combined);
            }
        }
    }

    return combinedAll;
}

Code2:

public List<CombinedDatabaseStructure> Combine2(List<DatabaseStructure1> _Data1, List<DatabaseStructure2> _Data2)
{
    var joined = from item1 in _Data1.AsEnumerable()
                 join item2 in _Data2.AsEnumerable() on item1.ID equals item2.ID
                 select new CombinedDatabaseStructure (item1,item2);

    return  joined.ToList<CombinedDatabaseStructure>();
}


问:
isKindOfClass method to check Swift ViewController in Objective C
There's this AViewController which is written in Swift. Now in my Obj C manager class I want to check the type of the viewcontroller. But it doesn't read because Obj C read the class name as "ProjectName.AViewController". How can we have the below mentioned check?</p>

```<code>//Swift class
class AViewController: UIViewController {
}

//Obj C - Manager class
- (void)sampleMethod:(UIViewController *)viewController {
 if ([viewController isKindOfClass:[AViewController class]]) {
  //Action
 }
}
</code>```

答:
```<code>let arrControllers = self.navigationController.viewControllers

                    for (indx, vc) in (arrControllers?.enumerated())! {
                        if vc is YourViewController{
                            self.navigationController.viewControllers.remove(at: indx)
                        }
                    }
</code>```

Body:
There's this AViewController which is written in Swift. Now in my Obj C manager class I want to check the type of the viewcontroller. But it doesn't read because Obj C read the class name as "ProjectName.AViewController". How can we have the below mentioned check?

//Swift class
class AViewController: UIViewController {
}

//Obj C - Manager class
- (void)sampleMethod:(UIViewController *)viewController {
 if ([viewController isKindOfClass:[AViewController class]]) {
  //Action
 }
}


问:
Form won't store data in POST
I'm trying to mke a delete button by a simple form and php won't get any data from POST.

index.php

```<code>    echo '<tr style="background:green; border:1px solid black;"><td>' . date("d M y", strtotime($row["time"]))  . "</td>";
    echo "<td><b>" . $row["caseId"]. "</b></td>";
    echo "<td>" . $row["snPaper"]  . "</td>";
    echo "<td>" . $row["snBox"] . "</td>";
    echo "<td>" . $row["snUnit"] . '</td>';
    echo '<td><form action="remove.php" mehod="post" id="delete"><input type="text" value="kokot" name="id" id="id" /><input type="submit" name="submit" value="Delete"></td>';
    echo '<td>' . $row["id"] . '</td></tr>';
</code>```

remove.php

```<code>$id = $_POST['id'];
echo 'id=' . $id;
print_r($_POST);
// Create connection
$dir = 'sqlite:db.sqlite';

$conn = new PDO($dir) or die("hovno");

$conn->exec("'DELETE FROM favorite_apps WHERE id = '$id" );
</code>```

答:
Change your form method and it should work

```<code><form method="post">
</code>```

Instead of

```<code><form mehod="post">
</code>```

I've posted this just in case you didn't see the comment

Title: Form won't store data in POST

Body:
I'm trying to mke a delete button by a simple form and php won't get any data from POST.

index.php

    echo '
' . date("d M y", strtotime($row["time"]))  . "	";
    echo "" . $row["caseId"]. "	";
    echo "" . $row["snPaper"]  . "	";
    echo "" . $row["snBox"] . "	";
    echo "" . $row["snUnit"] . '	';
    echo '<form action="remove.php" mehod="post" id="delete"><input type="text" value="kokot" name="id" id="id" /><input type="submit" name="submit" value="Delete">	';
    echo '' . $row["id"] . '
';

remove.php

$id = $_POST['id'];
echo 'id=' . $id;
print_r($_POST);
// Create connection
$dir = 'sqlite:db.sqlite';

$conn = new PDO($dir) or die("hovno");

$conn->exec("'DELETE FROM favorite_apps WHERE id = '$id" );

Body:
Change your form method and it should work

<form method="post">

Instead of

<form mehod="post">

I've posted this just in case you didn't see the comment


问:
Python lxml etree.tostring() returns empty string running on mod_wsgi
I have Python 2.7.8 on CentOS 6.8 where my server is built upon Apache2 + WSGI. My application should handle the date received with http POST, then create an instruction based on XML template gotten from local .xml file. Finally, it must send xml instruction back with 200 OK response. The logic of the application is seems working Ok and I may see my updated xml tree with:

```<code>print etree.tostring(root, pretty_print=True, xml_declaration-True, encoding='UTF-8')
</code>```

The issue appears to be happened at next row of my code where I'm doing the same operation but trying assign the output to variable:

```<code>xml_body = etree.tostring(root, pretty_print=True, xml_declaration-True, encoding='UTF-8')
</code>```

print xml_body

The output is empty string, thus my application then returns nothing back to Apache.

My environment info may be helpful:

```<code>==For bug report ===
Python              : sys.version_info(major=2, minor=7, micro=8, releaselevel='final', serial=0)
lxml.etree          : (3, 6, 4, 0)
libxml used         : (2, 7, 6)
libxml compiled     : (2, 9, 4)
libxslt used        : (1, 1, 26)
libxslt compiled    : (1, 1, 29)
</code>```

It looks similar to this bug report   However, the author mentioned it doesn't work at all. There is another one request which contains similar issue, but it still isn't resolved.
I've checked out I might successfully play the same scenario in Python cli:

```<code>Python 2.7.8 (default, May 15 2016, 12:46:09)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lxml import etree
>>> foo = etree.Element('foo')
>>> foo
<Element foo at 0x7f5097c4fc20>
>>> foo.tag
'foo'
>>> foo.text = 'barrisimo'

>>> xmlb = etree.tostring(foo, pretty_print=True, xml_declaration=True, encoding='UTF-8')
>>> print xmlb
<?xml version='1.0' encoding='UTF-8'?>
<foo>barrisimo</foo>1
</code>```

Have somebody come across the same issue ever? I'm in dead end and I'd be appreciated for any help, ideas or helpful links.

答:
In case the libxml version at runtime is different from the compiled version it means there are more than one libxml version installed in your system:

```<code>libxml used         : (2, 7, 8)
libxml compiled     : (2, 9, 3)
</code>```

In my case mod_php5 was the problem. I have fixed this by re-compiling apache without PHP. It turns out PHP was using libxml version 2.7.8 and the python interpreter used in mod_wsgi was pointing to the same xmllib instead of using the python one.

Body:
I have Python 2.7.8 on CentOS 6.8 where my server is built upon Apache2 + WSGI. My application should handle the date received with http POST, then create an instruction based on XML template gotten from local .xml file. Finally, it must send xml instruction back with 200 OK response. The logic of the application is seems working Ok and I may see my updated xml tree with:

print etree.tostring(root, pretty_print=True, xml_declaration-True, encoding='UTF-8')

The issue appears to be happened at next row of my code where I'm doing the same operation but trying assign the output to variable:

xml_body = etree.tostring(root, pretty_print=True, xml_declaration-True, encoding='UTF-8')

print xml_body

The output is empty string, thus my application then returns nothing back to Apache.

My environment info may be helpful:

==For bug report ===
Python              : sys.version_info(major=2, minor=7, micro=8, releaselevel='final', serial=0)
lxml.etree          : (3, 6, 4, 0)
libxml used         : (2, 7, 6)
libxml compiled     : (2, 9, 4)
libxslt used        : (1, 1, 26)
libxslt compiled    : (1, 1, 29)

It looks similar to this bug report   However, the author mentioned it doesn't work at all. There is another one request which contains similar issue, but it still isn't resolved.
I've checked out I might successfully play the same scenario in Python cli:

Python 2.7.8 (default, May 15 2016, 12:46:09)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lxml import etree
>>> foo = etree.Element('foo')
>>> foo
<Element foo at 0x7f5097c4fc20>
>>> foo.tag
'foo'
>>> foo.text = 'barrisimo'

>>> xmlb = etree.tostring(foo, pretty_print=True, xml_declaration=True, encoding='UTF-8')
>>> print xmlb
<?xml version='1.0' encoding='UTF-8'?>
<foo>barrisimo</foo>1

Have somebody come across the same issue ever? I'm in dead end and I'd be appreciated for any help, ideas or helpful links.

Body:
In case the libxml version at runtime is different from the compiled version it means there are more than one libxml version installed in your system:

libxml used         : (2, 7, 8)
libxml compiled     : (2, 9, 3)

In my case mod_php5 was the problem. I have fixed this by re-compiling apache without PHP. It turns out PHP was using libxml version 2.7.8 and the python interpreter used in mod_wsgi was pointing to the same xmllib instead of using the python one.


问:
Copy text innerHTML of element to clipboard
I was try many solutions in stackoverflow, but it not work.(here and here)

I try it in Website and use chrome extension for run code (chrome 59.0.3071.104 64bit)

```<code><h4 align="center">text data to copy</h4>

var copy_text = document.getElementsByTagName("h4")[0];
copy_text.select(); //-> error: select is not a function
</code>```

and

```<code>var range = document.createRange();
range.selectNode(copy_text);
window.getSelection().addRange(range);
document.execCommand("copy"); //-> clipboard not change
</code>```

Any solution for this?
Thankyou.

Edit: I think my problem is page loading (security brower), all solution work with user interactive

答:
This works for me.

var copyTextareaBtn = document.querySelector('.copybtn');

copyTextareaBtn.addEventListener('click', function(event) {
  var copy_text = document.getElementsByTagName("h4")[0];
  var range = document.createRange();
  range.selectNode(copy_text);
  window.getSelection().addRange(range);

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="copybtn">Copy</button>
<h4 align="center">text data to copy</h4></code>```

But it isn't working if I try to copy not on click, but when the page is loaded

Body:
I was try many solutions in stackoverflow, but it not work.(here and here)

I try it in Website and use chrome extension for run code (chrome 59.0.3071.104 64bit)

text data to copy

var copy_text = document.getElementsByTagName("h4")[0];
copy_text.select(); //-> error: select is not a function

and

var range = document.createRange();
range.selectNode(copy_text);
window.getSelection().addRange(range);
document.execCommand("copy"); //-> clipboard not change

Any solution for this?
Thankyou.

Edit: I think my problem is page loading (security brower), all solution work with user interactive

Body:
This works for me.

var copyTextareaBtn = document.querySelector('.copybtn');

copyTextareaBtn.addEventListener('click', function(event) {
  var copy_text = document.getElementsByTagName("h4")[0];
  var range = document.createRange();
  range.selectNode(copy_text);
  window.getSelection().addRange(range);

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});

<button class="copybtn">Copy</button>
<h4 align="center">text data to copy</h4>

But it isn't working if I try to copy not on click, but when the page is loaded


问:
after pseudo with image not working
I try to get the same wave symbol underneath my headers as shown in this website http://harbr.co/ but it's not working. So far, I have the following CSS:

```<code>H2::after {
content: url ('images/wave.png');
position: absolute;
}
</code>```

Help?

答:
You have an extra space between url and (.

```<code>H2::after {
  content: url('images/wave.png');
  position: absolute;
}
</code>```

https://jsfiddle.net/qst68fLd/

Title: after pseudo with image not working

Body:
I try to get the same wave symbol underneath my headers as shown in this website http://harbr.co/ but it's not working. So far, I have the following CSS:

H2::after {
content: url ('images/wave.png');
position: absolute;
}

Help?

Body:
You have an extra space between url and (.

H2::after {
  content: url('images/wave.png');
  position: absolute;
}

https://jsfiddle.net/qst68fLd/


问:
How to clean CSV having double quote with-in double quote using R
Below is csv row which i am reading using R. But not getting all value separated in their column as I am having commas and inverted comma in data set.

Data: "18452","xx, yy & zz "Charles W","xxxx"

```<code>Desire Data Frame :
        Col A -> 18452
        Col B -> xx, yy & zz "Charles W
        Col C -> "xxxx"

OR
    Col A -> 18452
    Col B -> xx, yy & zz Charles W
    Col C -> "xxxx"

Any one will work.
</code>```

答:
Assuming that you meant xxxx and not "xxxx" as output for the last column replace each occurrence of "," (i.e. each occurrence of double quote, comma, double quote) with | and remove any double quote at the beginning and end of each line.  Finally, read using read.table:

```<code>read.table(text = gsub('^"|"$', "", gsub('","', '|', Data)), sep = "|", quote = "")
</code>```

giving:

```<code>     V1                     V2   V3
1 18452 xx, yy & zz "Charles W xxxx
</code>```

A variation of the above is to express it as a magrittr pipeline:

```<code>library(magrittr)

Data %>%
     gsub(pattern = '^"|"$', replacement = "") %>%
     gsub(pattern = '","', replacement = '|') %>%
     read.table(text = ., sep = "|", quote = "")
</code>```

Note: The input in reproducible form is:

```<code>Data <- '"18452","xx, yy & zz "Charles W","xxxx"'
</code>```

Body:
Below is csv row which i am reading using R. But not getting all value separated in their column as I am having commas and inverted comma in data set.

Data: "18452","xx, yy & zz "Charles W","xxxx"

Desire Data Frame :
        Col A -> 18452
        Col B -> xx, yy & zz "Charles W
        Col C -> "xxxx"

OR
    Col A -> 18452
    Col B -> xx, yy & zz Charles W
    Col C -> "xxxx"

Any one will work.

Body:
Assuming that you meant xxxx and not "xxxx" as output for the last column replace each occurrence of "," (i.e. each occurrence of double quote, comma, double quote) with | and remove any double quote at the beginning and end of each line.  Finally, read using read.table:

read.table(text = gsub('^"|"$', "", gsub('","', '|', Data)), sep = "|", quote = "")

giving:

     V1                     V2   V3
1 18452 xx, yy & zz "Charles W xxxx

A variation of the above is to express it as a magrittr pipeline:

library(magrittr)

Data %>%
     gsub(pattern = '^"|"$', replacement = "") %>%
     gsub(pattern = '","', replacement = '|') %>%
     read.table(text = ., sep = "|", quote = "")

Note: The input in reproducible form is:

Data <- '"18452","xx, yy & zz "Charles W","xxxx"'


问:
PHP do-while loop ending with exhausted memory error when executing sql code
Whilst executing the following code, the site crashes with:

"Allowed memory size of 268435456 bytes exhausted (tried to allocate 254643 bytes)"

```<code>        $queID = "LCGQ00" . $ID;
        $sqlquecheck = "Select QueryID FROM Questions Where QueryID = '$queID' limit 1;";
        $quequery = $this->db->query($sqlquecheck);

        if($quequery->num_rows() > 0)
        {
            do{
                $queID = $queID . "-" . $ID;
                $quequery = $this->db->query($sqlquecheck);
            }while($quequery->num_rows() > 0);
        }
</code>```

The error is pointing to the following line of code as the culprit:

```<code>$queID = $queID . "-" . $ID;
</code>```

What I'm trying to do is pad an existing ID to create a new one, and if that already exist then pad it again and again and so on.

So if there is already a result, do the pad function then resend the query and check again if it still returns a result.

Any help would be greatly appreciated!

Edit FIXED:

```<code>        if($quequery->num_rows() > 0)
        {
            do{
                $queID = $queID . "-" . $ID;
                $sqlquecheck2 = "Select QueryID FROM Questions Where QueryID = '$queID' limit 1;";
                $quequery2 = $this->db->query($sqlquecheck2);
            }while($quequery2->num_rows() > 0);
        }
</code>```

Also fetch_* and other methods were not working when I tried a different approach, which is why I used this method. This didn't need to be perfect, was just to eliminate a db error. Thanks again.

答:
You're never changing $sqlquecheck, so it will run while  Select QueryID FROM Questions Where QueryID = 'LCGQ00' limit 1;" returns something.

Unless some other process changes the database, it will run either 0 times or forever.

try

```<code>$queID = "LCGQ00" . $ID;
        $sqlquecheck = "Select QueryID FROM Questions Where QueryID = '$queID' limit 1;";
        $quequery = $this->db->query($sqlquecheck);

        if($quequery->num_rows() > 0)
        {
            do{
                $queID = $queID . "-" . $ID;
                $sqlquecheck = "Select QueryID FROM Questions Where QueryID = '$queID' limit 1;";

                $quequery = $this->db->query($sqlquecheck);
            }while($quequery->num_rows() > 0);
        }
</code>```

Body:
Whilst executing the following code, the site crashes with:

"Allowed memory size of 268435456 bytes exhausted (tried to allocate 254643 bytes)"

        $queID = "LCGQ00" . $ID;
        $sqlquecheck = "Select QueryID FROM Questions Where QueryID = '$queID' limit 1;";
        $quequery = $this->db->query($sqlquecheck);

        if($quequery->num_rows() > 0)
        {
            do{
                $queID = $queID . "-" . $ID;
                $quequery = $this->db->query($sqlquecheck);
            }while($quequery->num_rows() > 0);
        }

The error is pointing to the following line of code as the culprit:

$queID = $queID . "-" . $ID;

What I'm trying to do is pad an existing ID to create a new one, and if that already exist then pad it again and again and so on.

So if there is already a result, do the pad function then resend the query and check again if it still returns a result.

Any help would be greatly appreciated!

Edit FIXED:

        if($quequery->num_rows() > 0)
        {
            do{
                $queID = $queID . "-" . $ID;
                $sqlquecheck2 = "Select QueryID FROM Questions Where QueryID = '$queID' limit 1;";
                $quequery2 = $this->db->query($sqlquecheck2);
            }while($quequery2->num_rows() > 0);
        }

Also fetch_* and other methods were not working when I tried a different approach, which is why I used this method. This didn't need to be perfect, was just to eliminate a db error. Thanks again.

Body:
You're never changing $sqlquecheck, so it will run while  Select QueryID FROM Questions Where QueryID = 'LCGQ00' limit 1;" returns something.

Unless some other process changes the database, it will run either 0 times or forever.

try

$queID = "LCGQ00" . $ID;
        $sqlquecheck = "Select QueryID FROM Questions Where QueryID = '$queID' limit 1;";
        $quequery = $this->db->query($sqlquecheck);

        if($quequery->num_rows() > 0)
        {
            do{
                $queID = $queID . "-" . $ID;
                $sqlquecheck = "Select QueryID FROM Questions Where QueryID = '$queID' limit 1;";

                $quequery = $this->db->query($sqlquecheck);
            }while($quequery->num_rows() > 0);
        }


问:
Should CodeContracts replace the regular ArgumentExceptions?
Could I start using CodeContracts instead of:

```<code>if (XXX == Y)
    throw new ArgumentException("bla bla");
</code>```

How does it work if I develop a library and my library users do not use CodeContracts?

答:
Assuming that the code using code contracts is run through the binary rewriter, it will throw exceptions like code you posted. The re-writer goes through the code and replaces the contract code with argument checking etc.  It's kinda like aspect oriented programming.  It injects code to handle situations for you after you've compiled it.

If they don't use Code Contracts they will not get the benefit of having static analysis performed which is designed to look at the contract and warn them they might get an error based on the contract and their code.

Code Contracts

Body:
Could I start using CodeContracts instead of:

if (XXX == Y)
    throw new ArgumentException("bla bla");

How does it work if I develop a library and my library users do not use CodeContracts?


问:
XML Bulk Import of Records Using PostgreSQLCopyHelper - Npgsql.PostgresException: 42601
On importing records from an XML with two records file into database table, I have an issue were the first record is being inserted twice while the second record isn't getting saved into the table.

This is the XML file with the two records/products

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<ProdExtract>

 <ExtractHeader>
  <Schema>
   <id>Accord ePOS Product Extract</id>
   <Version>1.00</Version>
  </Schema>
 </ExtractHeader>

 <Product>
  <Mode>Modify</Mode>
   <ProductID>
    <LongDescription>ZOLMANS MINT SAUCE      #</LongDescription>
   </ProductID>
   <BasicFields>
    <Units>6</Units>
    <VAT VatCode="A" VatRate="0" />
   </BasicFields>
   <Price>
    <CurrentWSP>9.55</CurrentWSP>
    <CurrentRSP>2.01</CurrentRSP>
   </Price>
   <Barcode>
    <Eancode>5000147032921</Eancode>
   </Barcode>
 </Product>

 <Product>
  <Mode>Modify</Mode>
   <ProductID>
    <LongDescription>TEST XML IMPORT PRODUCT     </LongDescription>
   </ProductID>
   <BasicFields>
    <Units>10</Units>
    <VAT VatCode="A" VatRate="0" />
   </BasicFields>
   <Price>
    <CurrentWSP>8.88</CurrentWSP>
    <CurrentRSP>2.22</CurrentRSP>
   </Price>
   <Barcode>
    <Eancode>5000147032923</Eancode>
   </Barcode>
 </Product>

</ProdExtract>
</code>```

Reading the file and saving it to the database table

```<code>var entities = new List<ProductViewModel>();
        PostgreSQLCopyHelper<ProductViewModel> insert = null;

        NpgsqlConnection connection = new NpgsqlConnection("Host=192.168.0.52;Database=bolo;Username=western;Password=western");
        connection.Open(); /*OPEN DATABASE CONNECTION*/

        ProductViewModel p;

        try
        {
            if (ModelState.IsValid && upload != null)
            {
                //uploaded file
                Stream stream = upload.InputStream;

                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(stream);
                XmlElement root = xDoc.DocumentElement;
                XmlNodeList nodes = root.SelectNodes("Product");

                foreach (XmlNode node in nodes)
                {
                    //while((p = node.InnerText) != null)
                    {
                        insert = new PostgreSQLCopyHelper<ProductViewModel>("public", "q_product");
                        p = new ProductViewModel();
                        p.q_guid = Guid.NewGuid();
                        p.q_description = node.SelectSingleNode("ProductID/LongDescription").InnerText;
                        p.q_barcode = node.SelectSingleNode("Barcode / Eancode").InnerText;
                        p.q_casesize = Convert.ToDecimal(node.SelectSingleNode("BasicFields/Units").InnerText);
                        p.q_sellprice = Convert.ToDecimal(node.SelectSingleNode("Price/CurrentRSP").InnerText);
                        p.q_casecost = Convert.ToDecimal(node.SelectSingleNode("Price/CurrentWSP").InnerText);
                        entities.Add(p);
                    }
                }

                try
                {
                   insert.SaveAll(connection, entities);
                    int lineCount = entities.Count();
                    TempData["SuccessMessage"] = lineCount + " Records Inserted!";
                    connection.Close(); /*CLOSE CONNECTION*/
                }
                catch (DataException error)
                {
                    TempData["ErrorMessage"] = error.Message;
                }

                return RedirectToAction("Index");
            }
        }
        catch(DataException error)
        {

            ModelState.AddModelError("", error.Message);
        }

        return RedirectToAction("Index");
</code>```

UPDATE

Mapping this way, only gets the first row saved into the table. Testing with a file that only has 3 products, and the first row will get saved 3 times in the table.

```<code>insert = insert ?? new PostgreSQLCopyHelper<ProductViewModel>("public", "q_product")
   .MapUUID("q_guid", x => Guid.NewGuid())
   .MapText("q_description", x => node.SelectSingleNode("ProductID/LongDescription").InnerText)
   .MapText("q_barcode", x => node.SelectSingleNode("Barcode/Eancode").InnerText)
  etc........
                        ;
  entities.Add(p);
</code>```

Mapping this way gets all the approppiate records into entities.Add(p) but is crashing out on the line insert.SaveAll(connection, entities); with error Npgsql.PostgresException: 42601: syntax error at or near ")"... because insert has no columns to insert data into at time of saving.

```<code>insert = new PostgreSQLCopyHelper<ProductViewModel>("public", "q_product");
      p = new ProductViewModel();
      p.q_guid = Guid.NewGuid();
      p.q_description = node.SelectSingleNode("ProductID/LongDescription").InnerText;
      p.q_barcode = node.SelectSingleNode("Barcode / Eancode").InnerText;
      p.q_casesize = Convert.ToDecimal(node.SelectSingleNode("BasicFields/Units").InnerText);
      p.q_sellprice = Convert.ToDecimal(node.SelectSingleNode("Price/CurrentRSP").InnerText);
      p.q_casecost = Convert.ToDecimal(node.SelectSingleNode("Price/CurrentWSP").InnerText);
      entities.Add(p);
</code>```

Update Solution

Removing the line
insert = new PostgreSQLCopyHelper<ProductViewModel>("public", "q_product");

and using the following, works for my current needs. I am aware there are probably faster methods than this solution, but this works for my current needs at the moment.

```<code>NpgsqlCommand cmd = new NpgsqlCommand
                            ("INSERT INTO q_product (q_guid, q_description, q_barcode, q_casesize, q_sellprice, q_casecost, q_import_vatcode)" +
                            "VALUES (@pk, @des, @bcode, @csize, @sprice, @ccost, @vcode )",
                            con);

                        cmd.Parameters.AddWithValue("@pk", p.q_guid);
                        cmd.Parameters.AddWithValue("@des", p.q_description);
                        cmd.Parameters.AddWithValue("@bcode", p.q_barcode);
                        cmd.Parameters.AddWithValue("@csize", p.q_casesize);
                        cmd.Parameters.AddWithValue("@sprice", p.q_sellprice);
                        cmd.Parameters.AddWithValue("@ccost", p.q_casecost);
                        cmd.Parameters.AddWithValue("@vcode", p.q_import_vatcode);
                        cmd.ExecuteNonQuery();
</code>```

答:
Your issue is that you are repeatedly adding the same element:

```<code>entities.Add(p);
</code>```

On each iteration of the loop you need to create a new object and set properties on it:

```<code>p = new WhateverYourTypeIs();
p.Property1 = node.Something;
p.Property2 = node.SomethingElse;
entities.Add(p);
</code>```

etc.

Body:
On importing records from an XML with two records file into database table, I have an issue were the first record is being inserted twice while the second record isn't getting saved into the table.

This is the XML file with the two records/products

<?xml version="1.0" encoding="ISO-8859-1"?>
<ProdExtract>

 <ExtractHeader>
  <Schema>
   <id>Accord ePOS Product Extract</id>
   <Version>1.00</Version>
  </Schema>
 </ExtractHeader>

 <Product>
  <Mode>Modify</Mode>
   <ProductID>
    <LongDescription>ZOLMANS MINT SAUCE      #</LongDescription>
   </ProductID>
   <BasicFields>
    <Units>6</Units>
    <VAT VatCode="A" VatRate="0" />
   </BasicFields>
   <Price>
    <CurrentWSP>9.55</CurrentWSP>
    <CurrentRSP>2.01</CurrentRSP>
   </Price>
   <Barcode>
    <Eancode>5000147032921</Eancode>
   </Barcode>
 </Product>

 <Product>
  <Mode>Modify</Mode>
   <ProductID>
    <LongDescription>TEST XML IMPORT PRODUCT     </LongDescription>
   </ProductID>
   <BasicFields>
    <Units>10</Units>
    <VAT VatCode="A" VatRate="0" />
   </BasicFields>
   <Price>
    <CurrentWSP>8.88</CurrentWSP>
    <CurrentRSP>2.22</CurrentRSP>
   </Price>
   <Barcode>
    <Eancode>5000147032923</Eancode>
   </Barcode>
 </Product>

</ProdExtract>

Reading the file and saving it to the database table

var entities = new List<ProductViewModel>();
        PostgreSQLCopyHelper<ProductViewModel> insert = null;

        NpgsqlConnection connection = new NpgsqlConnection("Host=192.168.0.52;Database=bolo;Username=western;Password=western");
        connection.Open(); /*OPEN DATABASE CONNECTION*/

        ProductViewModel p;

        try
        {
            if (ModelState.IsValid && upload != null)
            {
                //uploaded file
                Stream stream = upload.InputStream;

                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(stream);
                XmlElement root = xDoc.DocumentElement;
                XmlNodeList nodes = root.SelectNodes("Product");

                foreach (XmlNode node in nodes)
                {
                    //while((p = node.InnerText) != null)
                    {
                        insert = new PostgreSQLCopyHelper<ProductViewModel>("public", "q_product");
                        p = new ProductViewModel();
                        p.q_guid = Guid.NewGuid();
                        p.q_description = node.SelectSingleNode("ProductID/LongDescription").InnerText;
                        p.q_barcode = node.SelectSingleNode("Barcode / Eancode").InnerText;
                        p.q_casesize = Convert.ToDecimal(node.SelectSingleNode("BasicFields/Units").InnerText);
                        p.q_sellprice = Convert.ToDecimal(node.SelectSingleNode("Price/CurrentRSP").InnerText);
                        p.q_casecost = Convert.ToDecimal(node.SelectSingleNode("Price/CurrentWSP").InnerText);
                        entities.Add(p);
                    }
                }

                try
                {
                   insert.SaveAll(connection, entities);
                    int lineCount = entities.Count();
                    TempData["SuccessMessage"] = lineCount + " Records Inserted!";
                    connection.Close(); /*CLOSE CONNECTION*/
                }
                catch (DataException error)
                {
                    TempData["ErrorMessage"] = error.Message;
                }

                return RedirectToAction("Index");
            }
        }
        catch(DataException error)
        {

            ModelState.AddModelError("", error.Message);
        }

        return RedirectToAction("Index");

UPDATE

Mapping this way, only gets the first row saved into the table. Testing with a file that only has 3 products, and the first row will get saved 3 times in the table.

insert = insert ?? new PostgreSQLCopyHelper<ProductViewModel>("public", "q_product")
   .MapUUID("q_guid", x => Guid.NewGuid())
   .MapText("q_description", x => node.SelectSingleNode("ProductID/LongDescription").InnerText)
   .MapText("q_barcode", x => node.SelectSingleNode("Barcode/Eancode").InnerText)
  etc........
                        ;
  entities.Add(p);

Mapping this way gets all the approppiate records into entities.Add(p) but is crashing out on the line insert.SaveAll(connection, entities); with error Npgsql.PostgresException: 42601: syntax error at or near ")"... because insert has no columns to insert data into at time of saving.

insert = new PostgreSQLCopyHelper<ProductViewModel>("public", "q_product");
      p = new ProductViewModel();
      p.q_guid = Guid.NewGuid();
      p.q_description = node.SelectSingleNode("ProductID/LongDescription").InnerText;
      p.q_barcode = node.SelectSingleNode("Barcode / Eancode").InnerText;
      p.q_casesize = Convert.ToDecimal(node.SelectSingleNode("BasicFields/Units").InnerText);
      p.q_sellprice = Convert.ToDecimal(node.SelectSingleNode("Price/CurrentRSP").InnerText);
      p.q_casecost = Convert.ToDecimal(node.SelectSingleNode("Price/CurrentWSP").InnerText);
      entities.Add(p);

Update Solution

Removing the line
insert = new PostgreSQLCopyHelper<ProductViewModel>("public", "q_product");

and using the following, works for my current needs. I am aware there are probably faster methods than this solution, but this works for my current needs at the moment.

NpgsqlCommand cmd = new NpgsqlCommand
                            ("INSERT INTO q_product (q_guid, q_description, q_barcode, q_casesize, q_sellprice, q_casecost, q_import_vatcode)" +
                            "VALUES (@pk, @des, @bcode, @csize, @sprice, @ccost, @vcode )",
                            con);

                        cmd.Parameters.AddWithValue("@pk", p.q_guid);
                        cmd.Parameters.AddWithValue("@des", p.q_description);
                        cmd.Parameters.AddWithValue("@bcode", p.q_barcode);
                        cmd.Parameters.AddWithValue("@csize", p.q_casesize);
                        cmd.Parameters.AddWithValue("@sprice", p.q_sellprice);
                        cmd.Parameters.AddWithValue("@ccost", p.q_casecost);
                        cmd.Parameters.AddWithValue("@vcode", p.q_import_vatcode);
                        cmd.ExecuteNonQuery();

Body:
Your issue is that you are repeatedly adding the same element:

entities.Add(p);

On each iteration of the loop you need to create a new object and set properties on it:

p = new WhateverYourTypeIs();
p.Property1 = node.Something;
p.Property2 = node.SomethingElse;
entities.Add(p);

etc.


问:
Error: Exception in monitor thread while connecting to server
In the connection the database and collection are found, but this is giving this error ..</p>

```<code>INFORMAÇÕES: Exception in monitor thread while connecting to server xarquigo01f:27017com.mongodb.MongoSocketException: xarquigo01f
at com.mongodb.ServerAddress.getSocketAddress(ServerAddress.java:188)
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:57)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:113)
at java.lang.Thread.run(Unknown Source)
</code>```

答: Sorted out. The problem was on the server, I just switched server and it worked.</p>

Body:
In the connection the database and collection are found, but this is giving this error ..

INFORMAÇÕES: Exception in monitor thread while connecting to server xarquigo01f:27017com.mongodb.MongoSocketException: xarquigo01f
at com.mongodb.ServerAddress.getSocketAddress(ServerAddress.java:188)
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:57)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:113)
at java.lang.Thread.run(Unknown Source)


问:
Getting response from serve the wrong Json format. How to make it respond in required format?
I am trying to create a search Module in my application but the response from my database is in the following format and i am getting a error

```<code>ERROR SyntaxError: Unexpected token s in JSON at position 0

sa[{"id":"4","worklocation":"Hyderabad","firstname":"Sanjay","lastname":"Tutuki","gender":"Male","aadharno":"0","panno":"2147483647","employeetype":"asdasd","dateofbirth":"2017-07-12","city":"Mumbai"}]
</code>```

How do i make it respond without the term which i searched with? Or how to I get the values in my component without the Error.

This is my code:

service.ts:

```<code>search(terms: Observable<string>) {
    return terms.debounceTime(400)
      .distinctUntilChanged()
      .switchMap(term => this.searchEntries(term));
  }
            searchEntries(term) {
                const baseUrl="http://localhost/Angular/search.php?search="
    return this.http
        .get(baseUrl + term)
        .map(res => res.json());
  }
</code>```

Component :

```<code>export class EmployeeDirectory {
    data : Data[];
    searchTerm$ = new Subject<string>();

    constructor(private dataservice : DataService){

        this.dataservice.search(this.searchTerm$)
      .subscribe(data => {
        this.data = data.data;
        console.log(data);

      });
  }

  search(searchTerm$){
    this.dataservice.search(this.searchTerm$)
      .subscribe(data => {
        this.data = data.data;
        console.log(data);
      });
  }
    }
</code>```

Template :

```<code><div class="col-md-6 col-sm-12 col-xs-12 ">
   <form method="GET" name="form" autocomplete="off">
    <div class="col-lg-9">
    <div class="input-group">
      <input type="text" class="form-control" (keyup)="searchTerm$.next($event.target.value)"  placeholder="Search for...">
      <span class="input-group-btn">
        <button class="btn btn-secondary" type="button" (click)="search(this.searchTerm$)" ><i class="glyphicon glyphicon-search"></i></button>
      </span>
    </div>
  </div>
  </form>
</div>

   <div *ngIf="data">
      <table *ngFor="let employee of data">
        <tr><td>First Name: </td><td>{{employee.firstname}}</td></tr>
      </table>
</code>```

PHP File :

```<code><?php
header("Allow-Access-Header-Origin: *");
$servername ="localhost";
$username ="root";
$password="sandeepchetikam";
$dbase = "mydb";

$conn = mysqli_connect($servername,$username,$password,$dbase);
if(!$conn){
    echo "Error" .mysqli_error($conn);
}
$name =$_GET['search'];
print_r($name);
$sql = "SELECT * FROM newdb WHERE firstname LIKE '%{$name}%' ";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($result))
{
    $rows[] = $row;
}
echo json_encode($rows);
?>
</code>```

And also the function is responding only for first search key up and it's not working for other search items. Can anyone help me with this?

答:
remove print_r($name); from your code. first you print your data so this is also response data and last echo json data also response data so your correct response data change . this is more important if you write html code or echo or print data in your file then it will send as response.

so your total code will be

```<code><?php
header("Allow-Access-Header-Origin: *");
$servername ="localhost";
$username ="root";
$password="sandeepchetikam";
$dbase = "mydb";

$conn = mysqli_connect($servername,$username,$password,$dbase);
if(!$conn){
    echo "Error" .mysqli_error($conn);
}
$name =$_GET['search'];
$sql = "SELECT * FROM newdb WHERE firstname LIKE '%{$name}%' ";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($result))
{
    $rows[] = $row;
}
echo json_encode($rows);
?>
</code>```

hope it will help you

Body:
I am trying to create a search Module in my application but the response from my database is in the following format and i am getting a error

ERROR SyntaxError: Unexpected token s in JSON at position 0

sa[{"id":"4","worklocation":"Hyderabad","firstname":"Sanjay","lastname":"Tutuki","gender":"Male","aadharno":"0","panno":"2147483647","employeetype":"asdasd","dateofbirth":"2017-07-12","city":"Mumbai"}]

How do i make it respond without the term which i searched with? Or how to I get the values in my component without the Error.

This is my code:

service.ts:

search(terms: Observable<string>) {
    return terms.debounceTime(400)
      .distinctUntilChanged()
      .switchMap(term => this.searchEntries(term));
  }
            searchEntries(term) {
                const baseUrl="http://localhost/Angular/search.php?search="
    return this.http
        .get(baseUrl + term)
        .map(res => res.json());
  }

Component :

export class EmployeeDirectory {
    data : Data[];
    searchTerm$ = new Subject<string>();

    constructor(private dataservice : DataService){

        this.dataservice.search(this.searchTerm$)
      .subscribe(data => {
        this.data = data.data;
        console.log(data);

      });
  }

  search(searchTerm$){
    this.dataservice.search(this.searchTerm$)
      .subscribe(data => {
        this.data = data.data;
        console.log(data);
      });
  }
    }

Template :

   <form method="GET" name="form" autocomplete="off">

      <input type="text" class="form-control" (keyup)="searchTerm$.next($event.target.value)"  placeholder="Search for...">

        <button class="btn btn-secondary" type="button" (click)="search(this.searchTerm$)" ></button>

  </form>

First Name: 	{{employee.firstname}}

PHP File :

<?php
header("Allow-Access-Header-Origin: *");
$servername ="localhost";
$username ="root";
$password="sandeepchetikam";
$dbase = "mydb";

$conn = mysqli_connect($servername,$username,$password,$dbase);
if(!$conn){
    echo "Error" .mysqli_error($conn);
}
$name =$_GET['search'];
print_r($name);
$sql = "SELECT * FROM newdb WHERE firstname LIKE '%{$name}%' ";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($result))
{
    $rows[] = $row;
}
echo json_encode($rows);
?>

And also the function is responding only for first search key up and it's not working for other search items. Can anyone help me with this?

Body:
remove print_r($name); from your code. first you print your data so this is also response data and last echo json data also response data so your correct response data change . this is more important if you write html code or echo or print data in your file then it will send as response.

so your total code will be

<?php
header("Allow-Access-Header-Origin: *");
$servername ="localhost";
$username ="root";
$password="sandeepchetikam";
$dbase = "mydb";

$conn = mysqli_connect($servername,$username,$password,$dbase);
if(!$conn){
    echo "Error" .mysqli_error($conn);
}
$name =$_GET['search'];
$sql = "SELECT * FROM newdb WHERE firstname LIKE '%{$name}%' ";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($result))
{
    $rows[] = $row;
}
echo json_encode($rows);
?>

hope it will help you


问:
Decode Base64 encoded data on the java server
Approach: I am encoding simple data to base64 and then sending it to the server. Similarly, i am trying to decode base64 encoded data on Java server but there is always exception that it is unable to decode it properly. Any help is appreciated.

Client Code Snippet(Android Application):

```<code>private String random(int size) {

  Random generator = new Random();
  StringBuilder randomStringBuilder = new StringBuilder();
  //int randomLength = generator.nextInt(size);
  char tempChar;
  for (int i = 0; i < size; i++){
      tempChar = (char) (generator.nextInt(90 - 65) + 65);
      randomStringBuilder.append(tempChar);
  }
  return randomStringBuilder.toString();
}

String data = random(packetSize);
Log.d(data, " Random String");

byte [] encodedBuffer = Base64.encode(data.getBytes("UTF-8"), 0);
DatagramPacket packet =
        new DatagramPacket(encodedBuffer, encodedBuffer.length, address, dstPort);
Log.d(String.valueOf(packetSize), "Sending packet Size");

SocketHandler.getSocket().send(packet);
</code>```

Server Code Snippet:

```<code>private String decodeBase64(String encoded) {
  try
  {
    byte[] decodedBytes = Base64.getMimeDecoder().decode(encoded.getBytes("UTF-8"));
    String decodeData = new String(decodedBytes);
    return decodeData;
  }
  catch (Exception e) {
    System.out.println("Unable to decode");
    return null;
  }
}

public void run() {
  try {
    byte[] buf = new byte[1400];
    DatagramPacket packet = packet = new DatagramPacket(buf, buf.length);
    System.out.println("UDP Server waiting");
    while(true)
    {

      try {
        SocketHandler.getSocket().receive(packet);
        System.out.println("Received: " + decodeBase64(new String(packet.getData())));

      }
      catch (SocketException e1) {
        System.out.println("Socket closed " + e1);
      }
    }
  }
  catch (Exception e) {
    e.printStackTrace();
  }
}
</code>```

Exception:

```
java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 147
    at java.util.Base64$Decoder.decode0(Base64.java:742)
    at java.util.Base64$Decoder.decode(Base64.java:526)
```

Sample Input(Random String generated):

LVYAGHNVAUUEVNSEQHLHNNHGOHKFJQICSGXMXLJGBICOGJTWGBFLRSROJQWIWCETRXMTDWASGILXCDPRBIYAWFTBRRWN

答:
Try to use class javax.xml.bind.DatatypeConverter for decoding instead of Base64. For me it helps.
For example replace:

```<code>byte[] decodedBytes = Base64.getMimeDecoder().decode(encoded.getBytes("UTF-8"));
</code>```

with

```<code>byte[] decodedBytes = DatatypeConverter.parseBase64Binary(base64str)
</code>```

Body:
Approach: I am encoding simple data to base64 and then sending it to the server. Similarly, i am trying to decode base64 encoded data on Java server but there is always exception that it is unable to decode it properly. Any help is appreciated.

Client Code Snippet(Android Application):

private String random(int size) {

  Random generator = new Random();
  StringBuilder randomStringBuilder = new StringBuilder();
  //int randomLength = generator.nextInt(size);
  char tempChar;
  for (int i = 0; i < size; i++){
      tempChar = (char) (generator.nextInt(90 - 65) + 65);
      randomStringBuilder.append(tempChar);
  }
  return randomStringBuilder.toString();
}

String data = random(packetSize);
Log.d(data, " Random String");

byte [] encodedBuffer = Base64.encode(data.getBytes("UTF-8"), 0);
DatagramPacket packet =
        new DatagramPacket(encodedBuffer, encodedBuffer.length, address, dstPort);
Log.d(String.valueOf(packetSize), "Sending packet Size");

SocketHandler.getSocket().send(packet);

Server Code Snippet:

private String decodeBase64(String encoded) {
  try
  {
    byte[] decodedBytes = Base64.getMimeDecoder().decode(encoded.getBytes("UTF-8"));
    String decodeData = new String(decodedBytes);
    return decodeData;
  }
  catch (Exception e) {
    System.out.println("Unable to decode");
    return null;
  }
}

public void run() {
  try {
    byte[] buf = new byte[1400];
    DatagramPacket packet = packet = new DatagramPacket(buf, buf.length);
    System.out.println("UDP Server waiting");
    while(true)
    {

      try {
        SocketHandler.getSocket().receive(packet);
        System.out.println("Received: " + decodeBase64(new String(packet.getData())));

      }
      catch (SocketException e1) {
        System.out.println("Socket closed " + e1);
      }
    }
  }
  catch (Exception e) {
    e.printStackTrace();
  }
}

Exception:

java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 147
    at java.util.Base64$Decoder.decode0(Base64.java:742)
    at java.util.Base64$Decoder.decode(Base64.java:526)

Sample Input(Random String generated):

LVYAGHNVAUUEVNSEQHLHNNHGOHKFJQICSGXMXLJGBICOGJTWGBFLRSROJQWIWCETRXMTDWASGILXCDPRBIYAWFTBRRWN

Body:
Try to use class javax.xml.bind.DatatypeConverter for decoding instead of Base64. For me it helps.
For example replace:

byte[] decodedBytes = Base64.getMimeDecoder().decode(encoded.getBytes("UTF-8"));

with

byte[] decodedBytes = DatatypeConverter.parseBase64Binary(base64str)


问:
Visual Studio 2005: static text control won't display with transparent background
I'm using the Dialog editor in Visual Studio 2005 to create a Dialog box with a static text control.  I'd like the background of the static text control to be transparent since I'm using an static image control underneath it and the grey text background looks hideous.  In the editor, I set the "Transparent" attribute to True and it causes the background to go transparent just like I want it to.  But as soon as I run my app and change the text using a SendMessage(hText, WM_SETTEXT, 0L, "newtext"), the background loses its transparency and goes grey again.  Any ideas?  Btw, I'm doing this in C++.

Thanks in advance for your help!

答:
As Anthony Johnson said, handle the WM_CTLCOLORSTATIC message in the dialog box (you don't have to handle WM_NOTIFY - I don't believe static controls use that message, anyway). But it doesn't seem to be enough to set the background mode to transparent. You also have to set the background brush to a null brush. Something like this should work (in your DialogProc):

```<code>case WM_CTLCOLORSTATIC:
    SetBkMode((HDC)wParam, TRANSPARENT);
    return (INT_PTR)(HBRUSH)GetStockObject(NULL_BRUSH);
</code>```

If you change the text on the static control, you may have to invalidate what's underneath it for it to draw correctly when you do this.

OwnerDisplayName: Joe Crotchett

Body:
As Anthony Johnson said, handle the WM_CTLCOLORSTATIC message in the dialog box (you don't have to handle WM_NOTIFY - I don't believe static controls use that message, anyway). But it doesn't seem to be enough to set the background mode to transparent. You also have to set the background brush to a null brush. Something like this should work (in your DialogProc):

case WM_CTLCOLORSTATIC:
    SetBkMode((HDC)wParam, TRANSPARENT);
    return (INT_PTR)(HBRUSH)GetStockObject(NULL_BRUSH);

If you change the text on the static control, you may have to invalidate what's underneath it for it to draw correctly when you do this.

OwnerDisplayName: Joel


问:
Are infinite lists useful for any real world applications?
I've been using haskell for quite a while now, and I've read most of Real World Haskell and Learn You a Haskell. What I want to know is whether there is a point to a language using lazy evaluation, in particular the "advantage" of having infinite lists, is there a task which infinite lists make very easy, or even a task that is only possible with infinite lists?</p>

答: An obvious example is chaining your data processing from input to whatever you want to do with it. E.g., reading a stream of characters into a lazy list, which is processed by a lexer, also producing a lazy list of tokens which are parsed into a lazy AST structure, then compiled and executed. It's like using Unix pipes.</p>


问:
Overwrite Add action of a grid
I have a standard Acumatica screen with a Form and a Grid. Is it possible to overwrite the Add Button of a grid, so that I can carry out a custom action rather than using the standard Add. </p>

答:
One of the ways is to hide the Standard Add New as I have described in the answer hide-add-button-from-grid and create your own.

Now you should create PXAction in your Graph with it's corresponding method like this:

```<code>public PXAction<SOOrder> CustomAddNew;

[PXButton(CommitChanges = true)]
[PXUIField(DisplayName = "Add New")]
protected void customAddNew()
{
    //your code here
}
</code>```

After this you should go to the page and do the following:

Add a button to the DataSource to Hide Action from the Action Bar of the Header in this way:
Where the  Name is your PXAction.

Add a button to the Grid with the following setting:
Where

ImageKey="AddNew" is for setting the Icon

AutoCallBack.Command="CustomAddNew" is the Name of your PXAction
DisplayStyle="Image" is for showing only the Icon.

As a result you will get the following :
Where the '+' is your PXAction

Title: Overwrite Add action of a grid

Body:
One of the ways is to hide the Standard Add New as I have described in the answer hide-add-button-from-grid and create your own.

Now you should create PXAction in your Graph with it's corresponding method like this:

public PXAction<SOOrder> CustomAddNew;

[PXButton(CommitChanges = true)]
[PXUIField(DisplayName = "Add New")]
protected void customAddNew()
{
    //your code here
}

After this you should go to the page and do the following:

Add a button to the DataSource to Hide Action from the Action Bar of the Header in this way:
Where the  Name is your PXAction.

Add a button to the Grid with the following setting:
Where

ImageKey="AddNew" is for setting the Icon

AutoCallBack.Command="CustomAddNew" is the Name of your PXAction
DisplayStyle="Image" is for showing only the Icon.

As a result you will get the following :
Where the '+' is your PXAction


问:
Ckeditor scrollbar marker / Text Position Indicator
I would like to implement scrollbar marker into ckeditor and i can't seem to find the right way to do it i have triyed this code

```<code>var win = new CKEDITOR.dom.window( window );
var pos = win.getScrollPosition();
console.log(pos);
</code>```

but it only return the google chrome scrollbar x=0 & Y=0

```<code>var win = new CKEDITOR.dom.window( domWindow );
var pos = win.getScrollPosition();
console.log(pos);
</code>```

and this give me an error domWindow is not defined

i found this example it may help: https://codepen.io/Rplus/pen/mEjWJm

```<code>(() => {
  var containerQS = '.article';
  var container = document.querySelector(containerQS);
  var form = document.querySelector('.form');
  var input = form.querySelector('input[type="text"]');
  var markClass = 'mark';
  var markerHeight = '2px';
  var _color = 'currentColor';
  var containerY = container.offsetTop;
  var containerH = container.scrollHeight;
  var customStyle = document.createElement('style');
  container.appendChild(customStyle);
  var renderScrollMarker = ($parent, posArr) => {
   var _posArr = posArr.map(i => {
      return `transparent ${i}, ${_color} ${i}, ${_color} calc(${i} +
${markerHeight}), transparent calc(${i} + ${markerHeight})`;
    });
    customStyle.innerHTML = `article::-webkit-scrollbar-track {
        background-image: linear-gradient(${_posArr.join()});
     }`;
  };
  var calcEleRelativePos = ($ele) => {
    return ($ele.offsetTop - containerY) / containerH;
  };
  var markOpt = {
    className: markClass,
    done: function () {
     var marks = document.querySelectorAll(`.${markClass}`);
     var allY = [].map.call(marks, (mark) => {
        return (calcEleRelativePos(mark) * 100).toFixed(2) + '%';
     });
     renderScrollMarker(container, allY);
     console.log(allY);
   }
  };
  var instance = new Mark(container);
  form.addEventListener('submit', (e) => {
   e.preventDefault();
   var _text = input.value.trim();
   console.log(_text, form.oldText);
    if (_text === '') {
       instance.unmark(markOpt);
      return;
   }
   form.oldText = _text;
    instance.unmark().mark(_text, markOpt);
 });
  // trigger
  form.querySelector('input[type="submit"]').click();
 })();
</code>```

but as ckeditor secures a lot of element, i would love to know if any one has done this before with CKeditor

答:
i just got the real editor scrollbar position, i only need to put a marker using style or any availble methode</p>

```<code>var win=CKEDITOR.instances.editor1.document.getWindow();
var pos = win.getScrollPosition().y;
console.log(pos);
</code>```

Body:
I would like to implement scrollbar marker into ckeditor and i can't seem to find the right way to do it i have triyed this code

var win = new CKEDITOR.dom.window( window );
var pos = win.getScrollPosition();
console.log(pos);

but it only return the google chrome scrollbar x=0 & Y=0

var win = new CKEDITOR.dom.window( domWindow );
var pos = win.getScrollPosition();
console.log(pos);

and this give me an error domWindow is not defined

i found this example it may help: https://codepen.io/Rplus/pen/mEjWJm

(() => {
  var containerQS = '.article';
  var container = document.querySelector(containerQS);
  var form = document.querySelector('.form');
  var input = form.querySelector('input[type="text"]');
  var markClass = 'mark';
  var markerHeight = '2px';
  var _color = 'currentColor';
  var containerY = container.offsetTop;
  var containerH = container.scrollHeight;
  var customStyle = document.createElement('style');
  container.appendChild(customStyle);
  var renderScrollMarker = ($parent, posArr) => {
   var _posArr = posArr.map(i => {
      return `transparent ${i}, ${_color} ${i}, ${_color} calc(${i} +
${markerHeight}), transparent calc(${i} + ${markerHeight})`;
    });
    customStyle.innerHTML = `article::-webkit-scrollbar-track {
        background-image: linear-gradient(${_posArr.join()});
     }`;
  };
  var calcEleRelativePos = ($ele) => {
    return ($ele.offsetTop - containerY) / containerH;
  };
  var markOpt = {
    className: markClass,
    done: function () {
     var marks = document.querySelectorAll(`.${markClass}`);
     var allY = [].map.call(marks, (mark) => {
        return (calcEleRelativePos(mark) * 100).toFixed(2) + '%';
     });
     renderScrollMarker(container, allY);
     console.log(allY);
   }
  };
  var instance = new Mark(container);
  form.addEventListener('submit', (e) => {
   e.preventDefault();
   var _text = input.value.trim();
   console.log(_text, form.oldText);
    if (_text === '') {
       instance.unmark(markOpt);
      return;
   }
   form.oldText = _text;
    instance.unmark().mark(_text, markOpt);
 });
  // trigger
  form.querySelector('input[type="submit"]').click();
 })();

but as ckeditor secures a lot of element, i would love to know if any one has done this before with CKeditor

Body:
i just got the real editor scrollbar position, i only need to put a marker using style or any availble methode

var win=CKEDITOR.instances.editor1.document.getWindow();
var pos = win.getScrollPosition().y;
console.log(pos);


问:
Tensorboard via Google Cloud Platform
I was following this walkthrough on creating a pet detector using tensorflow object detection.

I tried to run the following:

```<code>gcloud auth application-default login
tensorboard --logdir=gs://mybucket
</code>```

and then I got this error:

```<code>tensorflow.python.framework.errors_impl.UnimplementedError: File system scheme gs not implemented
</code>```

Anyone have any idea about how to access the google cloud platform logs through tensorboard? I can open tensorboard in the browser fine, but it doesn't show any data.

I'm sure it's fairly straightforwards, thanks!

(See section 'Monitoring Progress with Tensorboard
' in the walkthrough link)

答:
Are you running Tensorflow on a Compute Engine instance? If so, why are you trying to point your tensorboard to a cloud bucket? If you are running TF on a Google Cloud Compute Engine instance, it just creates a log file in the local file system and you point to it in the usual way. Then, open the browser at the IP address of that VM and it should work fine. Make sure to have enabled HTTP traffic when creating your VM

** UPDATE:

As discussed in the comment, you might want to look int using Google's gcsfuse utility if you want tensorboard to put its output onto a cloud storage bucket.

Read the instructions on installing gcsfuse. Once installed, create a directory on your VM, fuse that directory with your cloud bucket, and use that directory as output for tensorboard:

```<code>sudo mkdir vm_dir
sudo gcsfuse cloud_bucket vm_dir
tensorboard --logdir=vm_dir
</code>```

As a disclaimer, I haven't tried this myself, but can't see why this shouldn't work. Also keep in mind that once you stop/start your VM, the fuse will be lost, so don't forget to issue the gcsfuse command again to link the directory.

Title: Tensorboard via Google Cloud Platform

Body:
I was following this walkthrough on creating a pet detector using tensorflow object detection.

I tried to run the following:

gcloud auth application-default login
tensorboard --logdir=gs://mybucket

and then I got this error:

tensorflow.python.framework.errors_impl.UnimplementedError: File system scheme gs not implemented

Anyone have any idea about how to access the google cloud platform logs through tensorboard? I can open tensorboard in the browser fine, but it doesn't show any data.

I'm sure it's fairly straightforwards, thanks!

(See section 'Monitoring Progress with Tensorboard
' in the walkthrough link)

Body:
Are you running Tensorflow on a Compute Engine instance? If so, why are you trying to point your tensorboard to a cloud bucket? If you are running TF on a Google Cloud Compute Engine instance, it just creates a log file in the local file system and you point to it in the usual way. Then, open the browser at the IP address of that VM and it should work fine. Make sure to have enabled HTTP traffic when creating your VM

** UPDATE:

As discussed in the comment, you might want to look int using Google's gcsfuse utility if you want tensorboard to put its output onto a cloud storage bucket.

Read the instructions on installing gcsfuse. Once installed, create a directory on your VM, fuse that directory with your cloud bucket, and use that directory as output for tensorboard:

sudo mkdir vm_dir
sudo gcsfuse cloud_bucket vm_dir
tensorboard --logdir=vm_dir

As a disclaimer, I haven't tried this myself, but can't see why this shouldn't work. Also keep in mind that once you stop/start your VM, the fuse will be lost, so don't forget to issue the gcsfuse command again to link the directory.