问:
MacBook Pro (13" 2017 2TDB3) won't power up
My 2 weeks old computer doesn't power up anymore! After unplugging it from USB-C docking station I'm not able to get it working again - no sound, picture, connection.

Here is what I've tried:

hold the power button for ~10s, then pressing it again

hold Option+Cmd+Shift+Alt and press power for ~10s

hit the computer hard (this is how I usually repair stuff)

verify that the power adapter is working correctly

call support

Nothing helped :(

答:
After giving up and having a beer I decided to give it last try.

I've opened the lid and started pressing the power button like crazy (~6Hz = ~6 times a sec).

After 5s I've noticed the backlight to turn on and after few seconds the sleeping beauty woke up like nothing ever happened! Since then, everything is fine..

I'm happy, but scared at the same time as

I don't know what caused this issue

how I fixed it

why holding the power button for ~10s didn't have any effect


来源: stackexchange

问:
Android show marker onClick button
I want to plot all the coordinates of latitude and longitude values I get. Check the first and last of the plot and change with different icons. Add Poly lines on each mark plot and buttons on popup that can hide/dismiss.

The problem I am having now is that whenever I remove the for-loop outside the button I am having a null pointer error.

```<code>      @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map1);
        mapFragment.getMapAsync(this);

        new GetVehicleValue().execute();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_contact_us, container, false);
Button b = (Button) v.findViewById(R.id.button3);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        if(vehicleHolder.size() != 0) {
        for(int i =0; i < vehicleHolder.size(); i++) {
            createMarker(i,vehicleHolder.get(i).getLatitude(),vehicleHolder.get(i).getLongitude(),vehicleHolder.get(i).getVehicle());
        }
    }

        return v;
    }

    public void createMarker(int index, String latitude, String longitude, String vehicle) {
        // Adding the taped point to the ArrayList
        BitmapDescriptor image = BitmapDescriptorFactory.fromResource(R.drawable.bus);
        Double lat = Double.parseDouble(latitude);
        Double Longitude = Double.parseDouble(longitude);
        float color = 0;

        mMap.addMarker(new MarkerOptions()
                .position(new LatLng(lat, Longitude))
                .anchor(0.5f, 0.5f)
                .title("title")
                .snippet("snippet"  )
                .icon(image));

    }

    class GetVehicleValue extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            if (jsonStr != null) {
                try {
                    JSONArray jr = new JSONArray(jsonStr);

                    vehicleHolder = new ArrayList<>();
                    for (int i = 0; i < jsonStr.length(); i++) {
                        JSONObject jb = (JSONObject) jr.getJSONObject(i);
                        plate_num = jb.getString("plate_num");
                        gps_num = jb.getString("gps_num");
                        location = jb.getString("location");
                        date = jb.getString("date");
                        time = jb.getString("time");
                        lat = jb.getString("lat");
                        lng = jb.getString("lng");
                        engine = jb.getString("engine");
                        remarks = jb.getString("remarks");

                        vehicleHolder.add(new VehicleHolder(lat, lng));

                    }

                } catch (final JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.d("JSON:", "is null");
            }

            return null;
        }
</code>```

答:
Your location model class:

```<code>public class LocationHolder {

    private String longitude,latitude,location,direction;

    public LocationHolder(String longitude, String latitude, String location, String direction) {
        this.longitude = longitude;
        this.latitude = latitude;
        this.location = location;
        this.direction = direction;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }
}
</code>```

Parsing :

```<code>public static ArrayList<LocationHolder>list_location=new ArrayList<>();
for (int i = 0; i < contacts.length(); i++) {
    JSONObject c = contacts.getJSONObject(i);
    String account = c.getString("account");
    String trxdate = c.getString("trxdate");
    String trxtime = c.getString("trxtime");
    String longitude = c.getString("long");
    String latitude = c.getString("lat");
    String location = c.getString("location");
    String direction = c.getString("direction");
    String compass = c.getString("compass");
    String id = c.getString("id");
    String remarks = c.getString("remarks");
    String status = c.getString("status");
    String kmrun = c.getString("kmrun");
    String speed = c.getString("speed");
    String totalkm = c.getString("totalkm");
    String engine = c.getString("engine");
    String plateno = c.getString("plateno");

    list_location.add(new LocationHolder(longitude,latitude,location,direction,))
}
</code>```

button click

```<code>btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        for(int i=0;i<list_location.length();i++)
        {
            createMarker(list_location.get(i).getLatitude(),list_location.get(i).getLongitude(),list_location.get(i).getLocation());
        }
});
</code>```

createMarker Function:

```<code>private void createMarker(String latitude, String longitude,String snippet) {

    BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.map_pin);
    Double lat = Double.parseDouble(latitude);
    Double Longitude = Double.parseDouble(longitude);

    googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(lat, Longitude))
            .anchor(0.5f, 0.5f)
            .title(title)
            .snippet(snippet)
            .icon(icon));

    googleMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());

    googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {

            for (int i = 0; i < locationList.size(); i++) {
                  Log.d("TAG","getLatitude:"+list_location.get(i).getLatitude()+" getLongitude:"+list_location.get(i).getLongitude());
                if (marker.getSnippet().equals(list_location.get(i).getLocation())) {
                  Log.d("TAG","Selected Marker");
                }
            }
        }
    });
}
</code>```

MarkerInfoWindowAdapter:Add your custom window info UI

```<code>  public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

    public MarkerInfoWindowAdapter() {
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(final Marker marker) {
       View v = getLayoutInflater().inflate(R.layout.custom_mapview, null);

        TextView markerLabel = (TextView) v.findViewById(R.id.tv_title);
        markerLabel.setText(marker.getTitle());

        return v;
    }
}
</code>```

MyFragment

```<code>GoogleMap googleMap;

class MyFragment extends Fragment implements OnMapReadyCallback {

    @Override
    public void onMapReady(GoogleMap map) {
        googleMap = map;
        setUpMap();
    }

    /*set up map*/
    private void setUpMap() {
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.setTrafficEnabled(true);
        googleMap.setIndoorEnabled(true);
        googleMap.setBuildingsEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(0.0, 0.0)).zoom(15).build();
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        //set marker here
    }
}
</code>```

Try this to store list into array list,

```<code>dependencies {
    compile 'com.google.code.gson:gson:2.2.+'
}
</code>```

Set the values

```<code>    SharedPreferences preferences = getSharedPreferences("AppPrefs", MODE_PRIVATE);
    SharedPreferences.Editor PrefsEditor = preferences.edit();

Gson gson = new Gson();

String jsonText = gson.toJson(list_location );
prefsEditor.putString("key", jsonText);
prefsEditor.commit();
</code>```

Retrieve the values

```<code>List<LocationHolder> addArray  = new ArrayList<>();
Gson gson = new Gson();
String jsonText = Prefs.getString("key", null);
String[] text = gson.fromJson(jsonText, String[].class);

addArray = Arrays.asList(text);
addArray = new ArrayList(addArray);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android show marker onClick button

Body:
I want to plot all the coordinates of latitude and longitude values I get. Check the first and last of the plot and change with different icons. Add Poly lines on each mark plot and buttons on popup that can hide/dismiss.

The problem I am having now is that whenever I remove the for-loop outside the button I am having a null pointer error.

      @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map1);
        mapFragment.getMapAsync(this);

        new GetVehicleValue().execute();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_contact_us, container, false);
Button b = (Button) v.findViewById(R.id.button3);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        if(vehicleHolder.size() != 0) {
        for(int i =0; i < vehicleHolder.size(); i++) {
            createMarker(i,vehicleHolder.get(i).getLatitude(),vehicleHolder.get(i).getLongitude(),vehicleHolder.get(i).getVehicle());
        }
    }

        return v;
    }

    public void createMarker(int index, String latitude, String longitude, String vehicle) {
        // Adding the taped point to the ArrayList
        BitmapDescriptor image = BitmapDescriptorFactory.fromResource(R.drawable.bus);
        Double lat = Double.parseDouble(latitude);
        Double Longitude = Double.parseDouble(longitude);
        float color = 0;

        mMap.addMarker(new MarkerOptions()
                .position(new LatLng(lat, Longitude))
                .anchor(0.5f, 0.5f)
                .title("title")
                .snippet("snippet"  )
                .icon(image));

    }

    class GetVehicleValue extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            if (jsonStr != null) {
                try {
                    JSONArray jr = new JSONArray(jsonStr);

                    vehicleHolder = new ArrayList<>();
                    for (int i = 0; i < jsonStr.length(); i++) {
                        JSONObject jb = (JSONObject) jr.getJSONObject(i);
                        plate_num = jb.getString("plate_num");
                        gps_num = jb.getString("gps_num");
                        location = jb.getString("location");
                        date = jb.getString("date");
                        time = jb.getString("time");
                        lat = jb.getString("lat");
                        lng = jb.getString("lng");
                        engine = jb.getString("engine");
                        remarks = jb.getString("remarks");

                        vehicleHolder.add(new VehicleHolder(lat, lng));

                    }

                } catch (final JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.d("JSON:", "is null");
            }

            return null;
        }

Body:
Your location model class:

public class LocationHolder {

    private String longitude,latitude,location,direction;

    public LocationHolder(String longitude, String latitude, String location, String direction) {
        this.longitude = longitude;
        this.latitude = latitude;
        this.location = location;
        this.direction = direction;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }
}

Parsing :

public static ArrayList<LocationHolder>list_location=new ArrayList<>();
for (int i = 0; i < contacts.length(); i++) {
    JSONObject c = contacts.getJSONObject(i);
    String account = c.getString("account");
    String trxdate = c.getString("trxdate");
    String trxtime = c.getString("trxtime");
    String longitude = c.getString("long");
    String latitude = c.getString("lat");
    String location = c.getString("location");
    String direction = c.getString("direction");
    String compass = c.getString("compass");
    String id = c.getString("id");
    String remarks = c.getString("remarks");
    String status = c.getString("status");
    String kmrun = c.getString("kmrun");
    String speed = c.getString("speed");
    String totalkm = c.getString("totalkm");
    String engine = c.getString("engine");
    String plateno = c.getString("plateno");

    list_location.add(new LocationHolder(longitude,latitude,location,direction,))
}

button click

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        for(int i=0;i<list_location.length();i++)
        {
            createMarker(list_location.get(i).getLatitude(),list_location.get(i).getLongitude(),list_location.get(i).getLocation());
        }
});

createMarker Function:

private void createMarker(String latitude, String longitude,String snippet) {

    BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.map_pin);
    Double lat = Double.parseDouble(latitude);
    Double Longitude = Double.parseDouble(longitude);

    googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(lat, Longitude))
            .anchor(0.5f, 0.5f)
            .title(title)
            .snippet(snippet)
            .icon(icon));

    googleMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());

    googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {

            for (int i = 0; i < locationList.size(); i++) {
                  Log.d("TAG","getLatitude:"+list_location.get(i).getLatitude()+" getLongitude:"+list_location.get(i).getLongitude());
                if (marker.getSnippet().equals(list_location.get(i).getLocation())) {
                  Log.d("TAG","Selected Marker");
                }
            }
        }
    });
}

MarkerInfoWindowAdapter:Add your custom window info UI

  public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

    public MarkerInfoWindowAdapter() {
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(final Marker marker) {
       View v = getLayoutInflater().inflate(R.layout.custom_mapview, null);

        TextView markerLabel = (TextView) v.findViewById(R.id.tv_title);
        markerLabel.setText(marker.getTitle());

        return v;
    }
}

MyFragment

GoogleMap googleMap;

class MyFragment extends Fragment implements OnMapReadyCallback {

    @Override
    public void onMapReady(GoogleMap map) {
        googleMap = map;
        setUpMap();
    }

    /*set up map*/
    private void setUpMap() {
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.setTrafficEnabled(true);
        googleMap.setIndoorEnabled(true);
        googleMap.setBuildingsEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(0.0, 0.0)).zoom(15).build();
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        //set marker here
    }
}

Try this to store list into array list,

dependencies {
    compile 'com.google.code.gson:gson:2.2.+'
}

Set the values

    SharedPreferences preferences = getSharedPreferences("AppPrefs", MODE_PRIVATE);
    SharedPreferences.Editor PrefsEditor = preferences.edit();

Gson gson = new Gson();

String jsonText = gson.toJson(list_location );
prefsEditor.putString("key", jsonText);
prefsEditor.commit();

Retrieve the values

List<LocationHolder> addArray  = new ArrayList<>();
Gson gson = new Gson();
String jsonText = Prefs.getString("key", null);
String[] text = gson.fromJson(jsonText, String[].class);

addArray = Arrays.asList(text);
addArray = new ArrayList(addArray);


问:
Maya UI not docking after rerunning script
I have made a UI window for Autodesk Maya 2015. Every time I run the script within Maya's script editor, it works fine, the UI gets launched and it docks properly on the main Maya window.

However, after closing the UI window and rerunning the script, the window doesn't dock anymore. It gets stuck on the main screen and I have to close the whole software. It seems that the UI can't find the main Maya Window anymore after I close it the first time round. I'm not sure how to fix this. Can anyone give me some advice on how to fix this problem?

Here is my code:

```<code>def getMayaWindow():
    ptr = apiUI.MQtUtil.mainWindow()
    if ptr is not None:
        return shiboken.wrapInstance(long(ptr), QtGui.QMainWindow)

class pipeWindow(formClass,baseClass):
    def __init__(self, parent=getMayaWindow()):
        super(pipeWindow,self).__init__(parent)

        self.setupUi(self)
        self.setObjectName('pipe_window')

        try:
            cmds.deleteUI('dockPane')
        except:
            pass
        self.pane = cmds.paneLayout('dockPane', cn='single')

        if 'pipeDock' not in cmds.lsUI(ctl=1) :
            cmds.dockControl('pipeDock', con=self.pane, area='right',
                              allowedArea = ['right','left'], label =
                             "ANMD_Pipeline", w=365)
        else:
            pass
        cmds.control( 'pipe_window', e=True, p=self.pane)
</code>```

答:
After trying out multiple things, I have managed to resolve this issue. I have used

```<code>if cmds.dockControl('pipeDock', q=1, ex=1):
    cmds.deleteUI('pipeDock')
</code>```

Then I have a super(className, self).closeEvent(event) inside a closeEvent function. This did the trick for me. This did the trick for me. Previously I had the cmds.deleteUI within my closeEvent function which did not work, I suspect it was because I did not close the Event itself, so the UI just hides  itself whenever I press the cross button instead of deleting it.

Body:
I have made a UI window for Autodesk Maya 2015. Every time I run the script within Maya's script editor, it works fine, the UI gets launched and it docks properly on the main Maya window.

However, after closing the UI window and rerunning the script, the window doesn't dock anymore. It gets stuck on the main screen and I have to close the whole software. It seems that the UI can't find the main Maya Window anymore after I close it the first time round. I'm not sure how to fix this. Can anyone give me some advice on how to fix this problem?

Here is my code:

def getMayaWindow():
    ptr = apiUI.MQtUtil.mainWindow()
    if ptr is not None:
        return shiboken.wrapInstance(long(ptr), QtGui.QMainWindow)

class pipeWindow(formClass,baseClass):
    def __init__(self, parent=getMayaWindow()):
        super(pipeWindow,self).__init__(parent)

        self.setupUi(self)
        self.setObjectName('pipe_window')

        try:
            cmds.deleteUI('dockPane')
        except:
            pass
        self.pane = cmds.paneLayout('dockPane', cn='single')

        if 'pipeDock' not in cmds.lsUI(ctl=1) :
            cmds.dockControl('pipeDock', con=self.pane, area='right',
                              allowedArea = ['right','left'], label =
                             "ANMD_Pipeline", w=365)
        else:
            pass
        cmds.control( 'pipe_window', e=True, p=self.pane)

Body:
After trying out multiple things, I have managed to resolve this issue. I have used

if cmds.dockControl('pipeDock', q=1, ex=1):
    cmds.deleteUI('pipeDock')

Then I have a super(className, self).closeEvent(event) inside a closeEvent function. This did the trick for me. This did the trick for me. Previously I had the cmds.deleteUI within my closeEvent function which did not work, I suspect it was because I did not close the Event itself, so the UI just hides  itself whenever I press the cross button instead of deleting it.


问:
Label is displayed below the input textbox
This is my input code sample. So whenever an error is generated, this error label would be visible. But it is coming up below the input element. I want it to be on the right side of the input.

I am able to modify the css for this bit using the label.error code bit I have. Label being the type and error is the class of that label being generated.

```<code>label.error
{
display:inline;
float:right;
}

> <td><input
> name="answer_engineeringjobs_1^11"
> id="answer_engineeringjobs_1"
> class="reqfield required zipUS error"
> type="text"><label class="error"
> generated="true"
> for="answer_engineeringjobs_1">This
> field is required.</label></td>
</code>```

答:
Floating an element makes it a block, which triggers a new line before it.

You would need to float the input left too.

ContentLicense: CC BY-SA 2.5

Body:
This is my input code sample. So whenever an error is generated, this error label would be visible. But it is coming up below the input element. I want it to be on the right side of the input.

I am able to modify the css for this bit using the label.error code bit I have. Label being the type and error is the class of that label being generated.

label.error
{
display:inline;
float:right;
}

> <input
> name="answer_engineeringjobs_1^11"
> id="answer_engineeringjobs_1"
> class="reqfield required zipUS error"
> type="text"> generated="true"
> for="answer_engineeringjobs_1">This
> field is required.


问:
Swift 3.0 Manipulate and Call Upon Elements in MKAnnotation Array
I am wondering how I am able to manipulate an array consisting of MKAnnotations. An example of this array is

```<code>[<MKUserLocation: 0x608000631500>, <Swift.ColorPointAnnotation: 0x600000861e00>]
</code>```

but my issue is that when this array is generated, the order is randomized (MKUserLocation is first in the array sometimes, second other times). I was wondering if there was a way to be able to grab, in this case, Swift.ColorPointAnnotation such that I am able to manipulate the map with this annotation.

Here is how I have been manipulating the array. I wish to be able to grab the specific annotation in order to center the mapRegion around it.

```<code>let annotations = self.mapView.annotations
let coordinateRegion = MKCoordinateRegionMakeWithDistance((annotations.last?.coordinate)!, 500, 500)
mapView.setRegion(coordinateRegion, animated: true)
</code>```

答:
You could do this to get the first ColorPointAnnotation from that array.

```<code>if let pin = mapView.annotations.first(where: { $0 is ColorPointAnnotation }) {

    mapView.setRegion(MKCoordinateRegionMakeWithDistance(pin.coordinate, 500, 500), animated: true)

}
</code>```

Body:
I am wondering how I am able to manipulate an array consisting of MKAnnotations. An example of this array is

[<MKUserLocation: 0x608000631500>, <Swift.ColorPointAnnotation: 0x600000861e00>]

but my issue is that when this array is generated, the order is randomized (MKUserLocation is first in the array sometimes, second other times). I was wondering if there was a way to be able to grab, in this case, Swift.ColorPointAnnotation such that I am able to manipulate the map with this annotation.

Here is how I have been manipulating the array. I wish to be able to grab the specific annotation in order to center the mapRegion around it.

let annotations = self.mapView.annotations
let coordinateRegion = MKCoordinateRegionMakeWithDistance((annotations.last?.coordinate)!, 500, 500)
mapView.setRegion(coordinateRegion, animated: true)

Body:
You could do this to get the first ColorPointAnnotation from that array.

if let pin = mapView.annotations.first(where: { $0 is ColorPointAnnotation }) {

    mapView.setRegion(MKCoordinateRegionMakeWithDistance(pin.coordinate, 500, 500), animated: true)

}


问:
How to keep service alive when remove app from stack
I want to show notification every minute using Alarm Manager, I have implemented below code, it's working fine but the problem is when I remove app from stack the service is not running.

I want keep alive, I have tried START_STICKY in onStartCommand and also used onTaskRemoved but it's same.

I also tried to implement using WakefulIntentService but the problem is same. My code is below.

In MainActivity

```<code>    Intent myIntent = new Intent(NotificationDemo.this, MyReceiver.class);

                myIntent.putExtra("title", "2 minutes");

                Random random = new Random();
                int m = random.nextInt(9999 - 1000) + 1000;

                Log.d("m::: In Notification", m + "");
                myIntent.putExtra("id", m);

                pendingIntent = PendingIntent.getBroadcast(NotificationDemo.this, m, myIntent, 0);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
//                alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),alarmManager.Inte pendingIntent);
                alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        SystemClock.elapsedRealtime(),
                        1 * 60 * 1000,
                        pendingIntent);
</code>```

MyService

```<code>       public class MyAlarmService extends Service {

            private NotificationManager mManager;

            @Override
            public IBinder onBind(Intent arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public void onCreate() {
                // TODO Auto-generated method stub
                super.onCreate();
            }

            @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
        String title = intent.getStringExtra("title");
        int id = intent.getIntExtra("id", 0);
        mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);

        Notification notification = new Notification(R.mipmap.ic_launcher, title, System.currentTimeMillis());
        intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        Log.d("id::", id + "");

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
//        notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(MyAlarmService.this);

        notification = builder.setContentTitle(title)
                .setContentText("Hellooo...")
                .setTicker("Good Evening...")
                .setSmallIcon(android.R.drawable.ic_btn_speak_now)
                .setVibrate(new long[]{1000, 1000, 1000, 100})
                .setLights(5, 5, 5)
                .setContentIntent(pendingNotificationIntent).build();

        mManager.notify(id, notification);
        startForeground(1337, notification);
        return START_STICKY;
    }

            @Override
            public void onDestroy() {
                // TODO Auto-generated method stub
                super.onDestroy();
               // sendBroadcast(new Intent("IWillStartAuto"));
            }

            @Override
            public void onTaskRemoved(Intent rootIntent) {
                super.onTaskRemoved(rootIntent);
        //        sendBroadcast(new Intent("IWillStartAuto"));
        //        Intent intent = new Intent(getApplicationContext(),MyReceiver.class);
        //        sendBroadcast(intent);
            }
        }
</code>```

and this is my receiver

```<code>public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
         String title = intent.getStringExtra("title");
    int id = intent.getIntExtra("id", 0);
    Intent service1 = new Intent(context, MyAlarmService.class);
    service1.putExtra("title", title);
    service1.putExtra("id", id);
    context.startService(service1);

    }
}
</code>```

In Manifest

```<code><receiver android:name=".MyReceiver">
        <!--<intent-filter>
            <action android:name="IWillStartAuto"/>
        </intent-filter>-->
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service
        android:name=".MyAlarmService"
        android:enabled="true"
        android:stopWithTask="false" />
</code>```

答: You can try with receiver configuration process=":remote" to keep receiver alive. I faced with this problem and here is my solution.</p>

Body:
I want to show notification every minute using Alarm Manager, I have implemented below code, it's working fine but the problem is when I remove app from stack the service is not running.

I want keep alive, I have tried START_STICKY in onStartCommand and also used onTaskRemoved but it's same.

I also tried to implement using WakefulIntentService but the problem is same. My code is below.

In MainActivity

    Intent myIntent = new Intent(NotificationDemo.this, MyReceiver.class);

                myIntent.putExtra("title", "2 minutes");

                Random random = new Random();
                int m = random.nextInt(9999 - 1000) + 1000;

                Log.d("m::: In Notification", m + "");
                myIntent.putExtra("id", m);

                pendingIntent = PendingIntent.getBroadcast(NotificationDemo.this, m, myIntent, 0);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
//                alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),alarmManager.Inte pendingIntent);
                alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        SystemClock.elapsedRealtime(),
                        1 * 60 * 1000,
                        pendingIntent);

MyService

       public class MyAlarmService extends Service {

            private NotificationManager mManager;

            @Override
            public IBinder onBind(Intent arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public void onCreate() {
                // TODO Auto-generated method stub
                super.onCreate();
            }

            @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
        String title = intent.getStringExtra("title");
        int id = intent.getIntExtra("id", 0);
        mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);

        Notification notification = new Notification(R.mipmap.ic_launcher, title, System.currentTimeMillis());
        intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        Log.d("id::", id + "");

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
//        notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(MyAlarmService.this);

        notification = builder.setContentTitle(title)
                .setContentText("Hellooo...")
                .setTicker("Good Evening...")
                .setSmallIcon(android.R.drawable.ic_btn_speak_now)
                .setVibrate(new long[]{1000, 1000, 1000, 100})
                .setLights(5, 5, 5)
                .setContentIntent(pendingNotificationIntent).build();

        mManager.notify(id, notification);
        startForeground(1337, notification);
        return START_STICKY;
    }

            @Override
            public void onDestroy() {
                // TODO Auto-generated method stub
                super.onDestroy();
               // sendBroadcast(new Intent("IWillStartAuto"));
            }

            @Override
            public void onTaskRemoved(Intent rootIntent) {
                super.onTaskRemoved(rootIntent);
        //        sendBroadcast(new Intent("IWillStartAuto"));
        //        Intent intent = new Intent(getApplicationContext(),MyReceiver.class);
        //        sendBroadcast(intent);
            }
        }

and this is my receiver

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
         String title = intent.getStringExtra("title");
    int id = intent.getIntExtra("id", 0);
    Intent service1 = new Intent(context, MyAlarmService.class);
    service1.putExtra("title", title);
    service1.putExtra("id", id);
    context.startService(service1);

    }
}

In Manifest

<receiver android:name=".MyReceiver">

        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service
        android:name=".MyAlarmService"
        android:enabled="true"
        android:stopWithTask="false" />


问:
Adding gridlines to Excel VBA userforms
Is there a way to add gridlines and snap objects to gridlines in an Excel VBA Userform?

I am generating a UserForm in Excel VBA with numerous textboxes and labels. Aligning them, even with the auto-align and grouping tools is quite tedious and time-consuming. The process would be expedited if horizontal and vertical gridlines were available to snap the objects to (think AutoCAD). The default UserForm has grid dots but not lines and snapping must be manually enabled for each object; it is not a built-in default for all objects.

答: Turn on "Align Controls to Grid" in Tools => Options (dialog box) / General (tab) as shown below.

Title: Adding gridlines to Excel VBA userforms


问:
Transitioning opacity and visibility
I have an element that is visibility: hidden until hovered over, with a transition on the opacity for a nice fade. The problem is that fade only works one way, because when the element instantly becomes visibility: hidden which hides the opacity transition. How can I work around this?

Edit: To be clear, it is important that the element have visibility: hidden until the hover is activated. An element with opacity: 0 can be interacted with, while an element with visibility: hidden cannot.

Example below. Notice how the popup fades in, but not out.

.hover {
  display: inline-block;
  position: relative;
}

.label {
  width: 80px;
  border: 1px solid black;
  padding: 20px;
}

.popup {
  width: 90px;
  padding: 15px;
  position: absolute;
  top: 100%;
  border: 1px dashed black;
  cursor: pointer;

  visibility: hidden;
  opacity: 0;
  transition: opacity 3s;
}

.hover:hover .popup {
  visibility: visible;
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hover">
  <div class="label">Hover me</div>
  <div class="popup">I am only visible on hover</div>
</div></code>```

答:
You don't need visibility:hidden; in .popup class since you won't see it anyway when its opacity is 0.

I don't actually know what exactly your case is. If this is not what you're looking for, please explain more specifically.

I have updated the code to meet your case. I use display: none instead of visibility:hidden and insert a simple Jquery code.

In my opinion, it should be nice if you make the .popup visible on clicking .label, instead of hovering it. The Jquery code for that should be

```<code>$(document).ready(function(){
    $(".label").click(function(){
        $(".popup").slideToggle("slow");
    });
});
</code>```

$(document).ready(function(){
  $(".label").mouseover(function(){
   $(".popup").stop().slideDown("slow");
  });
  $(".popup").mouseout(function(){
   $(".popup").slideUp("slow");
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hover {
  display: inline-block;
  position: relative;
}

.label {
  width: 80px;
  border: 1px solid black;
  padding: 20px;
}

.popup {
  width: 90px;
  padding: 15px;
  position: absolute;
  top: 100%;
  border: 1px dashed black;
  cursor: pointer;

  display: none;
  opacity: 1;
  transition: opacity 3s;
}

/*.hover:hover .popup {
  visibility: visible;
  opacity: 1;
}*/</code>```

Hover me

I am only visible on hover

```

Title: Transitioning opacity and visibility

Body:
I have an element that is visibility: hidden until hovered over, with a transition on the opacity for a nice fade. The problem is that fade only works one way, because when the element instantly becomes visibility: hidden which hides the opacity transition. How can I work around this?

Edit: To be clear, it is important that the element have visibility: hidden until the hover is activated. An element with opacity: 0 can be interacted with, while an element with visibility: hidden cannot.

Example below. Notice how the popup fades in, but not out.

.hover {
  display: inline-block;
  position: relative;
}

.label {
  width: 80px;
  border: 1px solid black;
  padding: 20px;
}

.popup {
  width: 90px;
  padding: 15px;
  position: absolute;
  top: 100%;
  border: 1px dashed black;
  cursor: pointer;

  visibility: hidden;
  opacity: 0;
  transition: opacity 3s;
}

.hover:hover .popup {
  visibility: visible;
  opacity: 1;
}

Hover me

I am only visible on hover

Body:
You don't need visibility:hidden; in .popup class since you won't see it anyway when its opacity is 0.

I don't actually know what exactly your case is. If this is not what you're looking for, please explain more specifically.

I have updated the code to meet your case. I use display: none instead of visibility:hidden and insert a simple Jquery code.

In my opinion, it should be nice if you make the .popup visible on clicking .label, instead of hovering it. The Jquery code for that should be

$(document).ready(function(){
    $(".label").click(function(){
        $(".popup").slideToggle("slow");
    });
});

$(document).ready(function(){
  $(".label").mouseover(function(){
   $(".popup").stop().slideDown("slow");
  });
  $(".popup").mouseout(function(){
   $(".popup").slideUp("slow");
  });
});

.hover {
  display: inline-block;
  position: relative;
}

.label {
  width: 80px;
  border: 1px solid black;
  padding: 20px;
}

.popup {
  width: 90px;
  padding: 15px;
  position: absolute;
  top: 100%;
  border: 1px dashed black;
  cursor: pointer;

  display: none;
  opacity: 1;
  transition: opacity 3s;
}

/*.hover:hover .popup {
  visibility: visible;
  opacity: 1;
}*/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hover">
  <div class="label">Hover me</div>
  <div class="popup">I am only visible on hover</div>
</div>


问:
How to do Million level Dictionary Search **(Non-English)**
There is a dictionary csv file, million level data & not English(Chinese or Japanese for example), the biggest word is up to 32bytes

Everytime I want to search word in the file.

Now my solution is Block Search:

First sort the data

Then and I split N datas into Sqrt(N) Blocks and get file offset of the first data in every Blocks using ftell in C, then store them in a Index file in this way: (word), (offset in dict)

Every time I get a word search request, I open the Index file and read line one by one until I find that this word is in this Block, then I use fseek to relocate to that block's first data at the dict file, and then read line one by one until I find the data in the dict.

Is this solution appropriate or is there any space to improve?
Or is there any other solutions? I don't know how to use hash or tree to search data in a file. Do I have to remake them at request?
Thanks!!!!!

答:
My first thought on this is that a million is not a big number for this sort of data set size. Using a basic balanced binary search should be log2(million) compares, or about 20 compares per search. Keeping it as simple as possible, I would read the 32-byte keys into an array of structures that contain (key, file offset):

```<code>struct record {
  uint8_t key[32];
  uint8_t key_length;
  uint64_t file_offset;
};

#define MAX_RECORDS 1000000

struct record my_index[MAX_RECORDS];
</code>```

Then ensure that 'my_index' array is sorted by key, which can be simply accomplished using the standard libraries qsort() function (https://linux.die.net/man/3/qsort). Once that is done, you may implement a divide-and-conquer binary array search following the algorithm laid out here https://en.wikipedia.org/wiki/Binary_search_algorithm ... This algorithm is implemented by the standard C library's bsearch() function (https://linux.die.net/man/3/bsearch).

Body:
My first thought on this is that a million is not a big number for this sort of data set size. Using a basic balanced binary search should be log2(million) compares, or about 20 compares per search. Keeping it as simple as possible, I would read the 32-byte keys into an array of structures that contain (key, file offset):

struct record {
  uint8_t key[32];
  uint8_t key_length;
  uint64_t file_offset;
};

#define MAX_RECORDS 1000000

struct record my_index[MAX_RECORDS];

Then ensure that 'my_index' array is sorted by key, which can be simply accomplished using the standard libraries qsort() function (https://linux.die.net/man/3/qsort). Once that is done, you may implement a divide-and-conquer binary array search following the algorithm laid out here https://en.wikipedia.org/wiki/Binary_search_algorithm ... This algorithm is implemented by the standard C library's bsearch() function (https://linux.die.net/man/3/bsearch).


问:
Sinon.JS stub a function that resolves a promise
I want to use Sinon to stub a function that uses callbacks which resolve a promise:

```<code>const callback = (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });

stub.me({}, callback);
</code>```

I tried:

```<code>var stub = {
  me: sinon.stub().yieldsTo("resolve", "my_data"),
};
</code>```

but I keep getting mocha timeouts.

The code doesn't define a const for callback. It's all in the stub.me function call. I just wrote it like that so it would be clear to read.

It's also wrapped in a new Promise((resolve,reject) => {} ); block.

答:
This was due to a scope error. Per the docks for aws-sdk-mock, AWS service needs to be initialized in the function.

Does not work:

```<code>var AWS      = require('aws-sdk');
var sns      = AWS.SNS();
var dynamoDb = AWS.DynamoDB();

exports.handler = function(event, context) {
  // do something with the services e.g. sns.publish
}
</code>```

Works:

```<code>var AWS = require('aws-sdk');

exports.handler = function(event, context) {
  var sns      = AWS.SNS();
  var dynamoDb = AWS.DynamoDB();
  // do something with the services e.g. sns.publish
}
</code>```

Body:
I want to use Sinon to stub a function that uses callbacks which resolve a promise:

const callback = (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });

stub.me({}, callback);

I tried:

var stub = {
  me: sinon.stub().yieldsTo("resolve", "my_data"),
};

but I keep getting mocha timeouts.

The code doesn't define a const for callback. It's all in the stub.me function call. I just wrote it like that so it would be clear to read.

It's also wrapped in a new Promise((resolve,reject) => {} ); block.

Body:
This was due to a scope error. Per the docks for aws-sdk-mock, AWS service needs to be initialized in the function.

Does not work:

var AWS      = require('aws-sdk');
var sns      = AWS.SNS();
var dynamoDb = AWS.DynamoDB();

exports.handler = function(event, context) {
  // do something with the services e.g. sns.publish
}

Works:

var AWS = require('aws-sdk');

exports.handler = function(event, context) {
  var sns      = AWS.SNS();
  var dynamoDb = AWS.DynamoDB();
  // do something with the services e.g. sns.publish
}


问:
Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click
I used explicit waits and I have the warning:

org.openqa.selenium.WebDriverException:
  Element is not clickable at point (36, 72). Other element would receive
  the click: ...
  Command duration or timeout: 393 milliseconds

If I use Thread.sleep(2000) I don't receive any warnings.

```<code>@Test(dataProvider = "menuData")
public void Main(String btnMenu, String TitleResultPage, String Text) throws InterruptedException {
    WebDriverWait wait = new WebDriverWait(driver, 10);
    driver.findElement(By.id("navigationPageButton")).click();

    try {
       wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(btnMenu)));
    } catch (Exception e) {
        System.out.println("Oh");
    }
    driver.findElement(By.cssSelector(btnMenu)).click();
    Assert.assertEquals(driver.findElement(By.cssSelector(TitleResultPage)).getText(), Text);
}
</code>```

答:
WebDriverException: Element is not clickable at point (x, y)

This is a typical org.openqa.selenium.WebDriverException which extends java.lang.RuntimeException.

The fields of this exception are :

BASE_SUPPORT_URL : protected static final java.lang.String BASE_SUPPORT_URL

DRIVER_INFO : public static final java.lang.String DRIVER_INFO

SESSION_ID : public static final java.lang.String SESSION_ID

About your individual usecase, the error tells it all :

```<code>WebDriverException: Element is not clickable at point (x, y). Other element would receive the click
</code>```

It is clear from your code block that you have defined the wait as WebDriverWait wait = new WebDriverWait(driver, 10); but you are calling the click() method on the element before  the ExplicitWait comes into play as in until(ExpectedConditions.elementToBeClickable).

Solution

The error Element is not clickable at point (x, y) can arise from different factors. You can address them by either of the following procedures:

1. Element not getting clicked due to JavaScript or AJAX calls present

Try to use Actions Class:

```<code>WebElement element = driver.findElement(By.id("navigationPageButton"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
</code>```

2. Element not getting clicked as it is not within Viewport

Try to use JavascriptExecutor to bring the element within the Viewport:

```<code>WebElement myelement = driver.findElement(By.id("navigationPageButton"));
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", myelement);
</code>```

3. The page is getting refreshed before the element gets clickable.

In this case induce ExplicitWait i.e WebDriverWait as mentioned in point 4.

4. Element is present in the DOM but not clickable.

In this case induce ExplicitWait with  ExpectedConditions set to elementToBeClickable for the element to be clickable:

```<code>WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("navigationPageButton")));
</code>```

5. Element is present but having temporary Overlay.

In this case, induce ExplicitWait with  ExpectedConditions set to invisibilityOfElementLocated for the Overlay to be invisible.

```<code>WebDriverWait wait3 = new WebDriverWait(driver, 10);
wait3.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));
</code>```

6. Element is present but having permanent Overlay.

Use JavascriptExecutor to send the click directly on the element.

```<code>WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I used explicit waits and I have the warning:

org.openqa.selenium.WebDriverException:
  Element is not clickable at point (36, 72). Other element would receive
  the click: ...
  Command duration or timeout: 393 milliseconds

If I use Thread.sleep(2000) I don't receive any warnings.

@Test(dataProvider = "menuData")
public void Main(String btnMenu, String TitleResultPage, String Text) throws InterruptedException {
    WebDriverWait wait = new WebDriverWait(driver, 10);
    driver.findElement(By.id("navigationPageButton")).click();

    try {
       wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(btnMenu)));
    } catch (Exception e) {
        System.out.println("Oh");
    }
    driver.findElement(By.cssSelector(btnMenu)).click();
    Assert.assertEquals(driver.findElement(By.cssSelector(TitleResultPage)).getText(), Text);
}

Body:
WebDriverException: Element is not clickable at point (x, y)

This is a typical org.openqa.selenium.WebDriverException which extends java.lang.RuntimeException.

The fields of this exception are :

BASE_SUPPORT_URL : protected static final java.lang.String BASE_SUPPORT_URL

DRIVER_INFO : public static final java.lang.String DRIVER_INFO

SESSION_ID : public static final java.lang.String SESSION_ID

About your individual usecase, the error tells it all :

WebDriverException: Element is not clickable at point (x, y). Other element would receive the click

It is clear from your code block that you have defined the wait as WebDriverWait wait = new WebDriverWait(driver, 10); but you are calling the click() method on the element before  the ExplicitWait comes into play as in until(ExpectedConditions.elementToBeClickable).

Solution

The error Element is not clickable at point (x, y) can arise from different factors. You can address them by either of the following procedures:

1. Element not getting clicked due to JavaScript or AJAX calls present

Try to use Actions Class:

WebElement element = driver.findElement(By.id("navigationPageButton"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

2. Element not getting clicked as it is not within Viewport

Try to use JavascriptExecutor to bring the element within the Viewport:

WebElement myelement = driver.findElement(By.id("navigationPageButton"));
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", myelement);

3. The page is getting refreshed before the element gets clickable.

In this case induce ExplicitWait i.e WebDriverWait as mentioned in point 4.

4. Element is present in the DOM but not clickable.

In this case induce ExplicitWait with  ExpectedConditions set to elementToBeClickable for the element to be clickable:

WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("navigationPageButton")));

5. Element is present but having temporary Overlay.

In this case, induce ExplicitWait with  ExpectedConditions set to invisibilityOfElementLocated for the Overlay to be invisible.

WebDriverWait wait3 = new WebDriverWait(driver, 10);
wait3.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));

6. Element is present but having permanent Overlay.

Use JavascriptExecutor to send the click directly on the element.

WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);


问:
Non-generic reference to generic class results in non-generic return types
I have a legacy class that the class itself is not a generic but one of its methods return type uses generics:

```<code>public class Thing {
    public Collection<String> getStuff() { ... }
}
</code>```

getStuff() uses generics to return a collection of strings. Therefore I can iterate over getStuff() and there's no need to cast the elements to a String:

```<code>Thing t = new Thing();
for (String s: t.getStuff())  // valid
{ ... }
</code>```

However, if I change Thing itself to be a generic but keep everything else the same:

```<code>public class Thing<T> {
    public Collection<String> getStuff() { ... }
}
</code>```

and then keep using the non-generic reference to Thing, getStuff() no longer returns Collection<String> and instead returns a non-typed Collection. Thus the client code does not compile:

```<code>Thing t = new Thing();
for (String s: t.getStuff())  // compiler complains that Object can't be cast to String
{ ... }
</code>```

Why is this? What are the workarounds?

My guess is that by using a non-generic reference to a generic class, Java turns off all generics for the entire class. This is pain, because now I've broken my client code by making Thing a generic.

Edit: I'm making Thing generic for another method which is not listed in the above example code. My question is educational as to why the above cannot be done.

答: It is failing because of erasure.  You can read more about it in these Java Tutorials</p>

OwnerDisplayName: Steve Kuo

Body:
I have a legacy class that the class itself is not a generic but one of its methods return type uses generics:

public class Thing {
    public Collection<String> getStuff() { ... }
}

getStuff() uses generics to return a collection of strings. Therefore I can iterate over getStuff() and there's no need to cast the elements to a String:

Thing t = new Thing();
for (String s: t.getStuff())  // valid
{ ... }

However, if I change Thing itself to be a generic but keep everything else the same:

public class Thing<T> {
    public Collection<String> getStuff() { ... }
}

and then keep using the non-generic reference to Thing, getStuff() no longer returns Collection<String> and instead returns a non-typed Collection. Thus the client code does not compile:

Thing t = new Thing();
for (String s: t.getStuff())  // compiler complains that Object can't be cast to String
{ ... }

Why is this? What are the workarounds?

My guess is that by using a non-generic reference to a generic class, Java turns off all generics for the entire class. This is pain, because now I've broken my client code by making Thing a generic.

Edit: I'm making Thing generic for another method which is not listed in the above example code. My question is educational as to why the above cannot be done.

LastEditorDisplayName: Steve Kuo

OwnerDisplayName: Ryan Ahearn


问:
ImportError: cannot import name 'MNIST'
I've able to pip install all other packages such as bumpy, sklearn etc. but mnist package throws me error as the following. I've been trying to use sudo pip install but it also says that

```<code>applesys$ pip install mnist
Requirement already satisfied: mnist in            /Users/applesys/anaconda3/lib/python3.5/site-packages
Requirement already satisfied: numpy in /Users/applesys/anaconda3/lib/python3.5/site-packages (from mnist)
applesys$ sudo pip install mnist
Password:
The directory '/Users/applesys/Library/Caches/pip/http' or its parent             directory is not owned by the current user and the cache has been disabled.     Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/applesys/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: mnist in    /Users/applesys/anaconda3/lib/python3.5/site-packages
Requirement already satisfied: numpy in /Users/applesys/anaconda3/lib/python3.5/site-packages (from mnist)
</code>```

答:
I had the same problem.  While inspecting the "mnist" folder that holds the "mnist" module, I could not find "MNIST" in the main module

```<code>    __init__.py
</code>```

However, the MNIST class was found in the "loader.py" file, at the same location.
I copied the "loader.py" file to the same folder where my Python script resides (where I'm trying to use this mnist module).
Now, instead of using:

```<code>    from mnist import MNIST
</code>```

I used:

```<code>    from loader import MNIST
</code>```

Now everything works fine for me.

Title: ImportError: cannot import name 'MNIST'

Body:
I've able to pip install all other packages such as bumpy, sklearn etc. but mnist package throws me error as the following. I've been trying to use sudo pip install but it also says that

applesys$ pip install mnist
Requirement already satisfied: mnist in            /Users/applesys/anaconda3/lib/python3.5/site-packages
Requirement already satisfied: numpy in /Users/applesys/anaconda3/lib/python3.5/site-packages (from mnist)
applesys$ sudo pip install mnist
Password:
The directory '/Users/applesys/Library/Caches/pip/http' or its parent             directory is not owned by the current user and the cache has been disabled.     Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/applesys/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: mnist in    /Users/applesys/anaconda3/lib/python3.5/site-packages
Requirement already satisfied: numpy in /Users/applesys/anaconda3/lib/python3.5/site-packages (from mnist)

Body:
I had the same problem.  While inspecting the "mnist" folder that holds the "mnist" module, I could not find "MNIST" in the main module

    __init__.py

However, the MNIST class was found in the "loader.py" file, at the same location.
I copied the "loader.py" file to the same folder where my Python script resides (where I'm trying to use this mnist module).
Now, instead of using:

    from mnist import MNIST

I used:

    from loader import MNIST

Now everything works fine for me.


问:
Can I add non-persistent fields to a model?
Is there a recommended practice for adding non-persistent attributes to an Objection model object such that it that won't overwrite predefined attributes?</p>

答:
Objection models have the virtualAttributes field. From the documentation:

The virtual values are not written to database. Only the “external” JSON format will contain them.

It is important to note these are functions, not just model properties.

Example from the docs:

```<code>class Person extends Model {
  static get virtualAttributes() {
    return ['fullName', 'isFemale'];
  }

  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  get isFemale() {
    return this.gender === 'female';
  }
}

const person = Person.fromJson({
  firstName: 'Jennifer',
  lastName: 'Aniston',
  gender: 'female'
});

console.log(person.toJSON());
// --> {"firstName": "Jennifer", "lastName": "Aniston", "isFemale": true, "fullName": "Jennifer Aniston"}
</code>```

Body:
Objection models have the virtualAttributes field. From the documentation:

The virtual values are not written to database. Only the “external” JSON format will contain them.

It is important to note these are functions, not just model properties.

Example from the docs:

class Person extends Model {
  static get virtualAttributes() {
    return ['fullName', 'isFemale'];
  }

  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  get isFemale() {
    return this.gender === 'female';
  }
}

const person = Person.fromJson({
  firstName: 'Jennifer',
  lastName: 'Aniston',
  gender: 'female'
});

console.log(person.toJSON());
// --> {"firstName": "Jennifer", "lastName": "Aniston", "isFemale": true, "fullName": "Jennifer Aniston"}


问:
Adding Decimal to a String in Javascript
I'm given numbers in cents:

eg.

```<code>  102042
  982123
  121212
</code>```

I want to convert them to dollars. I figured the easiest way to do this is to convert the digits into a string and add a decimal.

eg.

```<code>  1020.42
  9821.23
  1212.12
</code>```

I'm currently doing this but it only rounds to 1 decimal. What would I need to do it make it round to 2 decimals?

```<code>var number = 102042
number.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
</code>```

UPDATE: I found out what my issue was. It wasn't the rounding but the fact that I combined a lodash filter to a division incorrectly. Thanks again!

答:
A cent is 1/100th of a dollar, so you can calculate the dollar amount by doing</p>

```<code>dollars = number / 100
</code>```

Body:
I'm given numbers in cents:

eg.

  102042
  982123
  121212

I want to convert them to dollars. I figured the easiest way to do this is to convert the digits into a string and add a decimal.

eg.

  1020.42
  9821.23
  1212.12

I'm currently doing this but it only rounds to 1 decimal. What would I need to do it make it round to 2 decimals?

var number = 102042
number.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]

UPDATE: I found out what my issue was. It wasn't the rounding but the fact that I combined a lodash filter to a division incorrectly. Thanks again!

Body:
A cent is 1/100th of a dollar, so you can calculate the dollar amount by doing

dollars = number / 100


答:
Put the  before your <input> element. I know it's strange, but it will probably work.

Edit: wait, maybe you can't alter the order of your tags, in which case this is not very good advice.

Edit some more: You could try adding:

```<code>td {
    white-space: nowrap;
}
</code>```

to your css, so the label won't show up below the textbox anymore. You wouldn't need the float code anymore. HOWEVER, all td's would stop wrapping text, which may not be what you want. David's answer may be better.

Title: Label is displayed below the input textbox

Body:
This is my input code sample. So whenever an error is generated, this error label would be visible. But it is coming up below the input element. I want it to be on the right side of the input.

I am able to modify the css for this bit using the label.error code bit I have. Label being the type and error is the class of that label being generated.

label.error
{
display:inline;
float:right;
}

> <input
> name="answer_engineeringjobs_1^11"
> id="answer_engineeringjobs_1"
> class="reqfield required zipUS error"
> type="text"> generated="true"
> for="answer_engineeringjobs_1">This
> field is required.

Body:
Put the <label> before your <input> element. I know it's strange, but it will probably work.

Edit: wait, maybe you can't alter the order of your tags, in which case this is not very good advice.

Edit some more: You could try adding:

td {
    white-space: nowrap;
}

to your css, so the label won't show up below the textbox anymore. You wouldn't need the float code anymore. HOWEVER, all td's would stop wrapping text, which may not be what you want. David's answer may be better.


答: Did you try the code with any other output statements? Notifications are, off-late, not being fired for me either - I might blame Instant Run, nevertheless could you try replacing the notification-firing code snippet with maybe something like a Toast? Since Toasts don't work in services, maybe you could try creating a file in your external storage directory whenever the service starts to know that maybe it's up and running?</p>

Title: How to keep service alive when remove app from stack


问:
Adding numbers forth column of first file to second file using awk.
Hoping somebody can help me with this task. I have two infiles,

File1

```<code># name                  length  av.qual #-reads mx.cov. av.cov  GC% CnIUPAC CnFunny CnN CnX CnGap   CnNoCov
10-1_rep_c1             1406    80  8017    4637    1641.26 31.98   1   0   4   0   7   0
10-1_rep_c2             832 80  1641    1462    557.34  32.13   1   0   0   0   5   0
10-1_rep_c3             1284    83  4674    2338    1040.80 24.75   7   0   0   0   8   0
10-1_rep_c4             750 83  2335    2017    886.31  24.73   2   0   0   0   3   0
10-1_rep_c5             1180    78  2326    1486    572.51  19.76   1   0   0   0   7   0
</code>```

File2

```<code>>10-1_rep_c1
ttttttttttttttacaataaaatgcrccattattcctttcgtactaaacaatgccttat
ggccaccagatagaaaccaatctgactcacgtcgattttaactcaaatcatgtaaaattc
>10-1_rep_c2
aacagcagaattaatattgttcacaggtttttataaaacgacctattaatgaatttccat
cccctaaaaatggtcggcttacttgatgtaaccaccccctctagttaataataattgtat
>10-1_rep_c3
aattataaaaagaatttttaaagcataaattattagtaattttaagagaaattaaaggta
ttataaaagagtaatagtactgacaaggaaaaacttttatataaaaaaaagaaaatttaa
</code>```

The outfile I would like to have is,

```<code>>10-1_rep_c1_8017
ttttttttttttttacaataaaatgcrccattattcctttcgtactaaacaatgccttat
ggccaccagatagaaaccaatctgactcacgtcgattttaactcaaatcatgtaaaattc
>10-1_rep_c2_1641
aacagcagaattaatattgttcacaggtttttataaaacgacctattaatgaatttccat
cccctaaaaatggtcggcttacttgatgtaaccaccccctctagttaataataattgtat
>10-1_rep_c3_4674
aattataaaaagaatttttaaagcataaattattagtaattttaagagaaattaaaggta
ttataaaagagtaatagtactgacaaggaaaaacttttatataaaaaaaagaaaatttaa
</code>```

So the fourth column of the first file appended onto the second file header of each DNA sequence.

答:
This is an alternative using awk:

```<code>awk 'FNR==NR{a[">"$1]="_"$4;next}{print $0a[$0]}' File1 File2
</code>```

Body:
Hoping somebody can help me with this task. I have two infiles,

File1

# name                  length  av.qual #-reads mx.cov. av.cov  GC% CnIUPAC CnFunny CnN CnX CnGap   CnNoCov
10-1_rep_c1             1406    80  8017    4637    1641.26 31.98   1   0   4   0   7   0
10-1_rep_c2             832 80  1641    1462    557.34  32.13   1   0   0   0   5   0
10-1_rep_c3             1284    83  4674    2338    1040.80 24.75   7   0   0   0   8   0
10-1_rep_c4             750 83  2335    2017    886.31  24.73   2   0   0   0   3   0
10-1_rep_c5             1180    78  2326    1486    572.51  19.76   1   0   0   0   7   0

File2

>10-1_rep_c1
ttttttttttttttacaataaaatgcrccattattcctttcgtactaaacaatgccttat
ggccaccagatagaaaccaatctgactcacgtcgattttaactcaaatcatgtaaaattc
>10-1_rep_c2
aacagcagaattaatattgttcacaggtttttataaaacgacctattaatgaatttccat
cccctaaaaatggtcggcttacttgatgtaaccaccccctctagttaataataattgtat
>10-1_rep_c3
aattataaaaagaatttttaaagcataaattattagtaattttaagagaaattaaaggta
ttataaaagagtaatagtactgacaaggaaaaacttttatataaaaaaaagaaaatttaa

The outfile I would like to have is,

>10-1_rep_c1_8017
ttttttttttttttacaataaaatgcrccattattcctttcgtactaaacaatgccttat
ggccaccagatagaaaccaatctgactcacgtcgattttaactcaaatcatgtaaaattc
>10-1_rep_c2_1641
aacagcagaattaatattgttcacaggtttttataaaacgacctattaatgaatttccat
cccctaaaaatggtcggcttacttgatgtaaccaccccctctagttaataataattgtat
>10-1_rep_c3_4674
aattataaaaagaatttttaaagcataaattattagtaattttaagagaaattaaaggta
ttataaaagagtaatagtactgacaaggaaaaacttttatataaaaaaaagaaaatttaa

So the fourth column of the first file appended onto the second file header of each DNA sequence.

Body:
This is an alternative using awk:

awk 'FNR==NR{a[">"$1]="_"$4;next}{print $0a[$0]}' File1 File2


答:
var number = 102042;

console.log(number/100);```

Title: Adding Decimal to a String in Javascript


问:
ERROR SparkContext: Error initializing SparkContext. java.net.BindException: Cannot assign requested address: Service 'sparkDriver' failed
I have install below setup with version:
Hadoop version 1.0.3
java version "1.7.0_67"
Scala version 2.11.7
Spark version 2.1.1.

getting below error, can any one help me this.

```<code>root@sparkmaster:/home/user# spark-shell
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
17/07/05 01:07:35 WARN SparkContext: Support for Java 7 is deprecated as of Spark 2.0.0
17/07/05 01:07:36 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/07/05 01:07:37 WARN Utils: Service 'sparkDriver' could not bind on port 0. Attempting port 1.

17/07/05 01:07:37 ERROR SparkContext: Error initializing SparkContext.
java.net.BindException: Cannot assign requested address: Service 'sparkDriver' failed after 16 retries (starting from 0)! Consider explicitly setting the appropriate port for the service 'sparkDriver' (for example spark.ui.port for SparkUI) to an available port or increasing

<console>:14: error: not found: value spark
       import spark.implicits._

<console>:14: error: not found: value spark
       import spark.sql

Using Scala version 2.11.8 (Java HotSpot(TM) Client VM, Java 1.7.0_67)
Type in expressions to have them evaluated.
Type :help for more information.

scala>
</code>```

答:
Add SPARK_LOCAL_IP in load-spark-env.sh as

```<code>export SPARK_LOCAL_IP="127.0.0.1"
</code>```

The load-spark-env.sh file is located in spark/bin directory

Or you can add your hostname in /etc/hosts file as

```<code>127.0.0.1   hostname
</code>```

You can get your hostname by typing hostname in terminal

Hope this solves the issue!

Body:
I have install below setup with version:
Hadoop version 1.0.3
java version "1.7.0_67"
Scala version 2.11.7
Spark version 2.1.1.

getting below error, can any one help me this.

root@sparkmaster:/home/user# spark-shell
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
17/07/05 01:07:35 WARN SparkContext: Support for Java 7 is deprecated as of Spark 2.0.0
17/07/05 01:07:36 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/07/05 01:07:37 WARN Utils: Service 'sparkDriver' could not bind on port 0. Attempting port 1.

17/07/05 01:07:37 ERROR SparkContext: Error initializing SparkContext.
java.net.BindException: Cannot assign requested address: Service 'sparkDriver' failed after 16 retries (starting from 0)! Consider explicitly setting the appropriate port for the service 'sparkDriver' (for example spark.ui.port for SparkUI) to an available port or increasing

<console>:14: error: not found: value spark
       import spark.implicits._

<console>:14: error: not found: value spark
       import spark.sql

Using Scala version 2.11.8 (Java HotSpot(TM) Client VM, Java 1.7.0_67)
Type in expressions to have them evaluated.
Type :help for more information.

scala>

Body:
Add SPARK_LOCAL_IP in load-spark-env.sh as

export SPARK_LOCAL_IP="127.0.0.1"

The load-spark-env.sh file is located in spark/bin directory

Or you can add your hostname in /etc/hosts file as

127.0.0.1   hostname

You can get your hostname by typing hostname in terminal

Hope this solves the issue!


问:
C# fastest way to serialise object to xml string
Background: I have been tasked with serialising C# objects into xml string.  The xml string is then passed to webservice and are written to disk in xml file.  The task of serialising needs to occur within 5 mins timeframe that the process gets.  The consumer webservice only accepts string as xml.
I have been researching into various ways of creating xml string from xml serialiser,  xmlwriter, xdocument,  stringbuilder to write xml string,  object to json to xml,  linq to xml but I needed to know if anyone had experience of doing something similar.  Main aim is to have a high performant xml string that is not so verbose and error prone like creating xml in string.

My object is Called Employee and has 18 string/date properties.  The objects are created in memory and we get around 4000k objects in total once the process boots up.  The process runs for 1 hour a day,  loads data from data file and creates person objects.  A number of functions are performed on the objects.  Once objects are ready,  they need to be serialised and data in xml is sent to webservice and is writren to xml file.   So in short,  these objects need to be serialised and saved to disk and sent to webservice.

Does anyone recommend any high performant yet easy to. Maintain approach?  Apologies for not positing any code because I can create a class and add xml serialiser etc code but i dont think it will add any value at the moment as currently I am looking for past experiences  plus i want to ensure i dont go on a wild goose chase and want to implement with right solution.

I have tried following serialiser code but it takes 10+ mins to serialise all 4000k objects.

```<code>public static bool Serialize<T>(T value, ref string serializeXml)
{
    if (value == null)
    {
        return false;
    }
    try
    {
        XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
        StringWriter stringWriter = new StringWriter();
        XmlWriter writer = XmlWriter.Create(stringWriter);

        xmlserializer.Serialize(writer, value);

        serializeXml = stringWriter.ToString();

        writer.Close();
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}
</code>```

I have also tried caching serialiser but doesn't give any performance improvements

答:
According to your requirement, speed is the most demanding part. We need to write a benchmark here. As mentioned in the comment, besides XmlSerializer, we can use DataContractSerializer for our purpose. There are several Q&A related to the difference between these two, e.g.:

DataContractSerializer vs XmlSerializer: Pros and Cons of each serializer

Linq to Xml VS XmlSerializer VS DataContractSerializer

Difference between DataContractSerializer vs XmlSerializer

Another options are manually write your XML either using StringBuilder or XmlWriter. Although in the requirement you mentioned:

Main aim is to have a high performant xml string that is not so verbose and error prone like creating xml in string

these three serializer is added for comparison. Of course, in the case of StringBuilder, the text must be escaped. Here, I used System.Security.SecurityElement.Escape. The object to be serialized looks like:

```<code>//Simple POCO with 11 String properties, 7 DateTime properties
[DataContractAttribute()]
public class Employee
{
    [DataMember()]
    public string FirstName { set; get; }
    [DataMember()]
    public string LastName { set; get; }
    //...omitted for clarity
    [DataMember()]
    public DateTime Date03 { set; get; }
    [DataMember()]
    public DateTime Date04 { set; get; }
}
</code>```

and all the properties have value (not null), assigned prior to calling the serializer. The serializer codes looks like:

```<code>    //Serialize using XmlSerializer
public static bool Serialize<T>(T value, ref StringBuilder sb)
{
    if (value == null)
        return false;
    try
    {
        XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
        using (XmlWriter writer = XmlWriter.Create(sb))
        {
            xmlserializer.Serialize(writer, value);
            writer.Close();
        }
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
        return false;
    }
}

//Serialize using DataContractSerializer
public static bool SerializeDataContract<T>(T value, ref StringBuilder sb)
{
    if (value == null)
        return false;
    try
    {
        DataContractSerializer xmlserializer = new DataContractSerializer(typeof(T));
        using (XmlWriter writer = XmlWriter.Create(sb))
        {
            xmlserializer.WriteObject(writer, value);
            writer.Close();
        }
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
        return false;
    }
}

//Serialize using StringBuilder
public static bool SerializeStringBuilder(Employee obj, ref StringBuilder sb)
    {
        if (obj == null)
            return false;

        sb.Append(@"<?xml version=""1.0"" encoding=""utf-16""?>");
        sb.Append("<Employee>");

        sb.Append("<FirstName>");
        sb.Append(SecurityElement.Escape(obj.FirstName));
        sb.Append("</FirstName>");

        //... Omitted for clarity

        sb.Append("</Employee>");

        return true;
    }

//Serialize using XmlSerializer (manually add elements)
public static bool SerializeManual(Employee obj, ref StringBuilder sb)
{
    if (obj == null)
        return false;

    try
    {
        using (var xtw = XmlWriter.Create(sb))
        {
            xtw.WriteStartDocument();
            xtw.WriteStartElement("Employee");

            xtw.WriteStartElement("FirstName");
            xtw.WriteString(obj.FirstName);
            xtw.WriteEndElement();

            //...Omitted for clarity

            xtw.WriteEndElement();
            xtw.WriteEndDocument();

            xtw.Close();
        }
        return true;
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex);
        return false;
    }
}
</code>```

In the benchmark, 4M Employee objects are given as the argument and XML is written to preallocated StringBuilder (parameter ref StringBuilder sb). For DataContractSerializer and Manual XmlWriter, benchmark with Parallel.Invoke (3 parallel tasks) also performed. Required processing time for each serializer:

```<code>//Simple POCO with 11 String properties, 7 DateTime properties
XmlSerializer         =00:02:37.8151125 = 157 sec: 100% (reference)
DataContractSerializer=00:01:10.3384361 = 70  sec: 45% (3-Parallel: 47sec = 30%)
StringBuilder         =00:01:22.5742122 = 82  sec: 52%
Manual XmlWriter      =00:00:57.8436860 = 58  sec: 37% (3-Parallel: 40sec = 25%)
</code>```

Environment: .Net Framework 4.5.2, Intel(R) Core(TM) i5-3337U @ 1.80GHz 1.80GHz, Windows 10, 6.0GB Memory. I expect StringBuilder will be the fastest, but it wasn't. Perhaps, the bottleneck is in System.Security.SecurityElement.Escape().

The conclusion: DataContractSerializer is within the requirement, processing time is 30-45% compared to XmlSerializer. The results may differs depend on the environment, and you should make your own benchmark.

Body:
Background: I have been tasked with serialising C# objects into xml string.  The xml string is then passed to webservice and are written to disk in xml file.  The task of serialising needs to occur within 5 mins timeframe that the process gets.  The consumer webservice only accepts string as xml.
I have been researching into various ways of creating xml string from xml serialiser,  xmlwriter, xdocument,  stringbuilder to write xml string,  object to json to xml,  linq to xml but I needed to know if anyone had experience of doing something similar.  Main aim is to have a high performant xml string that is not so verbose and error prone like creating xml in string.

My object is Called Employee and has 18 string/date properties.  The objects are created in memory and we get around 4000k objects in total once the process boots up.  The process runs for 1 hour a day,  loads data from data file and creates person objects.  A number of functions are performed on the objects.  Once objects are ready,  they need to be serialised and data in xml is sent to webservice and is writren to xml file.   So in short,  these objects need to be serialised and saved to disk and sent to webservice.

Does anyone recommend any high performant yet easy to. Maintain approach?  Apologies for not positing any code because I can create a class and add xml serialiser etc code but i dont think it will add any value at the moment as currently I am looking for past experiences  plus i want to ensure i dont go on a wild goose chase and want to implement with right solution.

I have tried following serialiser code but it takes 10+ mins to serialise all 4000k objects.

public static bool Serialize<T>(T value, ref string serializeXml)
{
    if (value == null)
    {
        return false;
    }
    try
    {
        XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
        StringWriter stringWriter = new StringWriter();
        XmlWriter writer = XmlWriter.Create(stringWriter);

        xmlserializer.Serialize(writer, value);

        serializeXml = stringWriter.ToString();

        writer.Close();
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

I have also tried caching serialiser but doesn't give any performance improvements

Body:
According to your requirement, speed is the most demanding part. We need to write a benchmark here. As mentioned in the comment, besides XmlSerializer, we can use DataContractSerializer for our purpose. There are several Q&A related to the difference between these two, e.g.:

DataContractSerializer vs XmlSerializer: Pros and Cons of each serializer

Linq to Xml VS XmlSerializer VS DataContractSerializer

Difference between DataContractSerializer vs XmlSerializer

Another options are manually write your XML either using StringBuilder or XmlWriter. Although in the requirement you mentioned:

Main aim is to have a high performant xml string that is not so verbose and error prone like creating xml in string

these three serializer is added for comparison. Of course, in the case of StringBuilder, the text must be escaped. Here, I used System.Security.SecurityElement.Escape. The object to be serialized looks like:

//Simple POCO with 11 String properties, 7 DateTime properties
[DataContractAttribute()]
public class Employee
{
    [DataMember()]
    public string FirstName { set; get; }
    [DataMember()]
    public string LastName { set; get; }
    //...omitted for clarity
    [DataMember()]
    public DateTime Date03 { set; get; }
    [DataMember()]
    public DateTime Date04 { set; get; }
}

and all the properties have value (not null), assigned prior to calling the serializer. The serializer codes looks like:

    //Serialize using XmlSerializer
public static bool Serialize<T>(T value, ref StringBuilder sb)
{
    if (value == null)
        return false;
    try
    {
        XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
        using (XmlWriter writer = XmlWriter.Create(sb))
        {
            xmlserializer.Serialize(writer, value);
            writer.Close();
        }
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
        return false;
    }
}

//Serialize using DataContractSerializer
public static bool SerializeDataContract<T>(T value, ref StringBuilder sb)
{
    if (value == null)
        return false;
    try
    {
        DataContractSerializer xmlserializer = new DataContractSerializer(typeof(T));
        using (XmlWriter writer = XmlWriter.Create(sb))
        {
            xmlserializer.WriteObject(writer, value);
            writer.Close();
        }
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
        return false;
    }
}

//Serialize using StringBuilder
public static bool SerializeStringBuilder(Employee obj, ref StringBuilder sb)
    {
        if (obj == null)
            return false;

        sb.Append(@"<?xml version=""1.0"" encoding=""utf-16""?>");
        sb.Append("<Employee>");

        sb.Append("<FirstName>");
        sb.Append(SecurityElement.Escape(obj.FirstName));
        sb.Append("</FirstName>");

        //... Omitted for clarity

        sb.Append("</Employee>");

        return true;
    }

//Serialize using XmlSerializer (manually add elements)
public static bool SerializeManual(Employee obj, ref StringBuilder sb)
{
    if (obj == null)
        return false;

    try
    {
        using (var xtw = XmlWriter.Create(sb))
        {
            xtw.WriteStartDocument();
            xtw.WriteStartElement("Employee");

            xtw.WriteStartElement("FirstName");
            xtw.WriteString(obj.FirstName);
            xtw.WriteEndElement();

            //...Omitted for clarity

            xtw.WriteEndElement();
            xtw.WriteEndDocument();

            xtw.Close();
        }
        return true;
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex);
        return false;
    }
}

In the benchmark, 4M Employee objects are given as the argument and XML is written to preallocated StringBuilder (parameter ref StringBuilder sb). For DataContractSerializer and Manual XmlWriter, benchmark with Parallel.Invoke (3 parallel tasks) also performed. Required processing time for each serializer:

//Simple POCO with 11 String properties, 7 DateTime properties
XmlSerializer         =00:02:37.8151125 = 157 sec: 100% (reference)
DataContractSerializer=00:01:10.3384361 = 70  sec: 45% (3-Parallel: 47sec = 30%)
StringBuilder         =00:01:22.5742122 = 82  sec: 52%
Manual XmlWriter      =00:00:57.8436860 = 58  sec: 37% (3-Parallel: 40sec = 25%)

Environment: .Net Framework 4.5.2, Intel(R) Core(TM) i5-3337U @ 1.80GHz 1.80GHz, Windows 10, 6.0GB Memory. I expect StringBuilder will be the fastest, but it wasn't. Perhaps, the bottleneck is in System.Security.SecurityElement.Escape().

The conclusion: DataContractSerializer is within the requirement, processing time is 30-45% compared to XmlSerializer. The results may differs depend on the environment, and you should make your own benchmark.


问:
Python's UDP crashes when sending to ip/port that isn't listening
If you send a UDP packet to a random ip/port that isn't listening, python closes the server that sent it (resulting in a crash)?

Am I doing something wrong or is this a bug?

Example of issue:

```<code>import socket

# Launch the server
try:
    Sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    Sock.bind(("127.0.0.1", 25565))
except:
    print("Failed to launch server")

# Send a packet to a random (closed) place
# Comment out this line to prevent error
Sock.sendto(b'', ("127.0.0.1", 4623))

while True:
    # Wait for data
    print("Listening for data")
    data, addr = Sock.recvfrom(1024)
</code>```

error:

line 18, in
      data, addr = Sock.recvfrom(1024)
  ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

答:
recvfrom can fail, even on an UDP socket. This can be done for example if the previous send tried to send a packet to a system where nobody was listening on the port and the receiver send back an ICMP unreachable.

Your server only crashes because you don't expect recvfrom to fail, i.e. did not wrap it into a try-block as you did with the bind. If you catch the expected error using such block the server will not crash but properly handle the error.

Body:
If you send a UDP packet to a random ip/port that isn't listening, python closes the server that sent it (resulting in a crash)?

Am I doing something wrong or is this a bug?

Example of issue:

import socket

# Launch the server
try:
    Sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    Sock.bind(("127.0.0.1", 25565))
except:
    print("Failed to launch server")

# Send a packet to a random (closed) place
# Comment out this line to prevent error
Sock.sendto(b'', ("127.0.0.1", 4623))

while True:
    # Wait for data
    print("Listening for data")
    data, addr = Sock.recvfrom(1024)

error:

line 18, in
      data, addr = Sock.recvfrom(1024)
  ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host


答:
The easiest way is to do it with the number itself, you can multiply by 0.01 or divide by 100 and you'll get that amount in dollars:

var numbers = [102042,982123,121212];

for(num of numbers)
  console.log(num/100);```


问:
Extend SELECT IF statement
I am using a SELECT IF statement to translate data from my database:

```<code>IF(status = 1, 'Status one', 'Status two')
</code>```

If the status is 1 the statement shows Status one. If the status is something else the statement shows Status two.

I want to extend this statement and show:

```<code>IF status = 1, 'Status one'
IF status = 2, 'Status two'
IF status = 3, 'Status three'
IF status = 4, 'Status four'
</code>```

Does someone know how I can do that?

答:
You could also use a CASE expression:

```<code>SELECT
    CONCAT('Status ',
        CASE WHEN status = 1 THEN 'one'
             WHEN status = 2 THEN 'two'
             WHEN status = 3 THEN 'three'
             WHEN status = 4 THEN 'four' END) AS label
FROM yourTable
</code>```

Demo

Title: Extend SELECT IF statement

Body:
I am using a SELECT IF statement to translate data from my database:

IF(status = 1, 'Status one', 'Status two')

If the status is 1 the statement shows Status one. If the status is something else the statement shows Status two.

I want to extend this statement and show:

IF status = 1, 'Status one'
IF status = 2, 'Status two'
IF status = 3, 'Status three'
IF status = 4, 'Status four'

Does someone know how I can do that?

Body:
You could also use a CASE expression:

SELECT
    CONCAT('Status ',
        CASE WHEN status = 1 THEN 'one'
             WHEN status = 2 THEN 'two'
             WHEN status = 3 THEN 'three'
             WHEN status = 4 THEN 'four' END) AS label
FROM yourTable

Demo


答:
Something like this should work:

```<code>SELECT
    (CASE
        WHEN status = 1 THEN 'Status one'
        WHEN status = 2 THEN 'Status two'
        WHEN status = 3 THEN 'Status three'
        WHEN status = 4 THEN 'Status four'
        ELSE 'Incorrect Option'
    END) AS statustext
FROM yourtable;
</code>```

As per ysth's comment, this is more compact and probably more efficient:

```<code>SELECT
    (CASE status
        WHEN 1 THEN 'Status one'
        WHEN 2 THEN 'Status two'
        WHEN 3 THEN 'Status three'
        WHEN 4 THEN 'Status four'
        ELSE 'Incorrect Option'
    END) AS statustext
FROM yourtable;
</code>```

Thanks ysth!

Title: Extend SELECT IF statement

Body:
Something like this should work:

SELECT
    (CASE
        WHEN status = 1 THEN 'Status one'
        WHEN status = 2 THEN 'Status two'
        WHEN status = 3 THEN 'Status three'
        WHEN status = 4 THEN 'Status four'
        ELSE 'Incorrect Option'
    END) AS statustext
FROM yourtable;

As per ysth's comment, this is more compact and probably more efficient:

SELECT
    (CASE status
        WHEN 1 THEN 'Status one'
        WHEN 2 THEN 'Status two'
        WHEN 3 THEN 'Status three'
        WHEN 4 THEN 'Status four'
        ELSE 'Incorrect Option'
    END) AS statustext
FROM yourtable;

Thanks ysth!


问:
Angular 4 template "Pipe could not be found"
I'm trying to use a custom-built pipe in my Angular 4 project. Can't figure out why the compiler doesn't recognize my pipe in the component template.

QFormat pipe

```<code>@Pipe({  name: 'qFormat'})
export class QFormatPipe implements PipeTransform {...}
</code>```

SharedModule

```<code>@NgModule({
    declarations: [QFormatPipe],
    exports: [QFormatPipe]
})
export class SharedModule { }
</code>```

FeatureModule

```<code>@NgModule({
  imports: [SharedModule],
  declarations: [MyComponent]
})
export class FeatureModule{ }
</code>```

MyComponent.html

```<code><div>{{someProp | qformat}}</div>
                  ^^^^^^^
</code>```

The template throws error:

Angular: the pipe 'qformat' could not be found

Am I missing something?

答:
The reason it can't find the pipe is because you registered the pipe as 'qFormat' with a capital F but in the HTML you have 'qformat' with a lowercase f. This is why the error is occurring. Your shared module registration and import/export is completely on point. The HTML should be:

```<code><div>{{someProp | qFormat}}</div>
</code>```

Hopefully that helps!

Body:
I'm trying to use a custom-built pipe in my Angular 4 project. Can't figure out why the compiler doesn't recognize my pipe in the component template.

QFormat pipe

@Pipe({  name: 'qFormat'})
export class QFormatPipe implements PipeTransform {...}

SharedModule

@NgModule({
    declarations: [QFormatPipe],
    exports: [QFormatPipe]
})
export class SharedModule { }

FeatureModule

@NgModule({
  imports: [SharedModule],
  declarations: [MyComponent]
})
export class FeatureModule{ }

MyComponent.html

{{someProp | qformat}}

                  ^^^^^^^

The template throws error:

Angular: the pipe 'qformat' could not be found

Am I missing something?

Body:
The reason it can't find the pipe is because you registered the pipe as 'qFormat' with a capital F but in the HTML you have 'qformat' with a lowercase f. This is why the error is occurring. Your shared module registration and import/export is completely on point. The HTML should be:

<div>{{someProp | qFormat}}</div>

Hopefully that helps!