问:
how to save or prevent my background service from the force stop or clear task from user
Hello friends i am creating one android app App lock application in which user can lock the application for that i am using one background service which run in background always. My service is run fine in all device but in some new device like OPPO,Redme Mi and Lenovo Mobile there is one advace feature like user can clean all the running task from the cleaner and because of this advance features when user clean all the task my service also stop and app lock will not work so user need to go in application and manual start the service is there any solution to protect my service from this.
one of app lock have this kind of solution
https://play.google.com/store/apps/details?id=com.domobile.applock
This app service is start after the clean task i also want to do same for my application i tried many solution but not getting any result i my service code is as below </p>

```<code>public class MyAppLockService extends Service {
public static int BuildV = 0;
public static final int NOTIFICATION_ID = 11259186;
private static boolean flag;
public static boolean isLauncher;
public static boolean isRunning;
public static ArrayList<String> locked_list;
public static String pack;
public static Thread th;
String currentHomePackage;
private boolean isRefreshedList;
boolean mAllowDestroy;
BroadcastReceiver mReciever;
private boolean mShowNotification;
UsageStatsManager mUsageStatsManager;
ActivityManager manager;
PowerManager pmanager;
SharedPreferences prefs;
public boolean run;
Timer f6t;
TimerTask tt;

class C02221 extends BroadcastReceiver {
    C02221() {
    }

    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(Utils.ACTION_UPDATE)) {
            MyAppLockService.this.refreshList();
        } else if (intent.getAction().equals(Utils.ACTION_STOP_SELF)) {
            MyAppLockService.this.doStopSelf();
        } else if (intent.getAction().equals(Utils.ACTION_REMOVE_APP)) {
            MyAppLockService.this.removeAppFromLockedList(intent
                    .getStringExtra("packName"));
        }
    }
}

@SuppressLint("NewApi")

class C02232 extends TimerTask {
    C02232() {
    }

    @SuppressLint("NewApi")
    public void run() {
        if (Utils.isScreenOn(MyAppLockService.this.pmanager)) {
            MyAppLockService.this.isRefreshedList = false;
            String current = "";
            try {
                current = Utils.getProcess(
                        MyAppLockService.this.mUsageStatsManager,
                        MyAppLockService.this.getApplicationContext());
            } catch (Exception e) {
                current = "";
            }
            if (current != null) {
                if (MyAppLockService.flag
                        && current
                                .equals(MyAppLockService.this.currentHomePackage)) {
                    if (MyAppLockService.this.prefs.getBoolean(
                            "immediately", true)) {
                        MyAppLockService.locked_list = new DBHelper(
                                MyAppLockService.this
                                        .getApplicationContext())
                                .getApsHasStateTrue();
                    }
                    MyAppLockService.flag = false;
                }
                if (!current
                        .equals(MyAppLockService.this.currentHomePackage)
                        && MyAppLockService.locked_list.contains(current)) {
                    Intent it;
                    if (MyAppLockService.BuildV >= 23) {
                        long endTime = System.currentTimeMillis();
                        UsageEvents usageEvents = MyAppLockService.this.mUsageStatsManager
                                .queryEvents(endTime - 10000, endTime);
                        Event event = new Event();
                        while (usageEvents.hasNextEvent()) {
                            usageEvents.getNextEvent(event);
                        }
                        if (current.equals(event.getPackageName())
                                && event.getEventType() == 1) {
                            MyAppLockService.pack = current;
                            if (MyAppLockService.this.prefs.getBoolean(
                                    "isPattern", false)) {
                                MyAppLockService.this
                                        .confirmPattern(current);
                            } else {
                                it = new Intent(
                                        MyAppLockService.this
                                                .getApplicationContext(),
                                        AppLockActivity.class);
                                it.setFlags(DriveFile.MODE_READ_ONLY);
                                MyAppLockService.this
                                        .getApplicationContext()
                                        .startActivity(it);
                            }
                            MyAppLockService.flag = true;
                            return;
                        }
                        return;
                    }
                    MyAppLockService.pack = current;
                    if (MyAppLockService.this.prefs.getBoolean("isPattern",
                            false)) {
                        MyAppLockService.this.confirmPattern(current);
                    } else {
                        it = new Intent(
                                MyAppLockService.this
                                        .getApplicationContext(),
                                AppLockActivity.class);
                        it.setFlags(DriveFile.MODE_READ_ONLY);
                        MyAppLockService.this.getApplicationContext()
                                .startActivity(it);
                    }
                    MyAppLockService.flag = true;
                }
            }
        } else if (!MyAppLockService.this.isRefreshedList) {
            MyAppLockService.this.refreshList();
        }
    }
}

public MyAppLockService() {
    this.run = true;
}

static {
    BuildV = VERSION.SDK_INT;
}

public IBinder onBind(Intent intent) {
    return null;
}

public void onCreate() {

    this.prefs = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    this.manager = (ActivityManager) getApplicationContext()
            .getSystemService("activity");
    this.pmanager = (PowerManager) getApplicationContext()
            .getSystemService("power");
    if (BuildV >= 21) {
        this.mUsageStatsManager = (UsageStatsManager) getApplicationContext()
                .getSystemService("usagestats");
    }
    startNotification();
    Intent intent = new Intent("android.intent.action.MAIN");
    intent.addCategory("android.intent.category.HOME");
    this.currentHomePackage = getPackageManager().resolveActivity(intent,
            Cast.MAX_MESSAGE_LENGTH).activityInfo.packageName;
    this.mReciever = new C02221();
    IntentFilter filter = new IntentFilter(Utils.ACTION_UPDATE);
    filter.addAction(Utils.ACTION_STOP_SELF);
    filter.addAction(Utils.ACTION_REMOVE_APP);
    registerReceiver(this.mReciever, filter);
    refreshList();
    this.tt = new C02232();
    this.f6t = new Timer();
    this.f6t.schedule(this.tt, 500, 500);
    super.onCreate();
    Calendar cal = Calendar.getInstance();
    Intent intent12 = new Intent(getBaseContext(),MyAppLockService.class);
    PendingIntent pintent = PendingIntent.getService(getBaseContext(), 0, intent12, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),5, pintent);
}

public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, START_STICKY_COMPATIBILITY, startId);

}

public void onDestroy() {
    try {
        this.f6t.cancel();
        this.tt.cancel();
    } catch (Exception e) {
        e.printStackTrace();
    }

        Intent intent1 = new Intent("com.android.techtrainner");
        intent1.putExtra("yourvalue", "torestore");
        sendBroadcast(intent1);

}

public void refreshList() {
    locked_list = new DBHelper(getApplicationContext())
            .getApsHasStateTrue();
    if (locked_list.size() == 0) {
        doStopSelf();
    }
    this.isRefreshedList = true;
}

@SuppressLint({ "InlinedApi" })
private void startForegroundWithNotification() {
    PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
            Calculator_Activity.class), 0);
    String title = getString(R.string.app_name);
    String content = getString(R.string.app_name);
    Builder nb = new Builder(this);
    nb.setSmallIcon(R.drawable.ic_transparent);
    nb.setContentTitle(title);
    nb.setContentText(content);
    nb.setWhen(System.currentTimeMillis());
    nb.setContentIntent(pi);
    nb.setOngoing(true);
    nb.setPriority(0);
    startForeground(NOTIFICATION_ID, nb.build());
}

private void startNotification() {
    startForegroundWithNotification();
    if (!this.mShowNotification) {
        HelperService.removeNotification(this);
    }
}

private void doStopSelf() {
    this.mAllowDestroy = true;
    unregisterReceiver(this.mReciever);
    stopForeground(true);
    stopSelf();
}

private void confirmPattern(String st) {

    Intent pIntent = new Intent(getApplicationContext(),
            ResetActivity.class);
    pIntent.putExtra("isFromReset", true);
    PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
            12345, pIntent, DriveFile.MODE_READ_ONLY);

    Intent intent = new Intent(LockPatternActivity.ACTION_COMPARE_PATTERN, null,
            getApplicationContext(), LockPatternActivity.class);
    intent.putExtra("packName", st);
    intent.putExtra("isStealthMode", this.prefs.getBoolean(
            AlpSettings.Display.METADATA_STEALTH_MODE, false));
    intent.putExtra("isFromLock", true);
    intent.setFlags(DriveFile.MODE_READ_ONLY);
    intent.addFlags(Cast.MAX_MESSAGE_LENGTH);

    intent.putExtra(LockPatternActivity.EXTRA_PENDING_INTENT_FORGOT_PATTERN, pi);

    startActivity(intent);

}

private void removeAppFromLockedList(String packName) {
    locked_list.remove(packName);
}
</code>```

<p>if there is any solution for it then please help me out thanks in advance </p>

答: Restart the service when it's stopped i.e. System will call onDestroy() on service which is stopped.</p>

Body:
Hello friends i am creating one android app App lock application in which user can lock the application for that i am using one background service which run in background always. My service is run fine in all device but in some new device like OPPO,Redme Mi and Lenovo Mobile there is one advace feature like user can clean all the running task from the cleaner and because of this advance features when user clean all the task my service also stop and app lock will not work so user need to go in application and manual start the service is there any solution to protect my service from this.
one of app lock have this kind of solution
https://play.google.com/store/apps/details?id=com.domobile.applock
This app service is start after the clean task i also want to do same for my application i tried many solution but not getting any result i my service code is as below

public class MyAppLockService extends Service {
public static int BuildV = 0;
public static final int NOTIFICATION_ID = 11259186;
private static boolean flag;
public static boolean isLauncher;
public static boolean isRunning;
public static ArrayList<String> locked_list;
public static String pack;
public static Thread th;
String currentHomePackage;
private boolean isRefreshedList;
boolean mAllowDestroy;
BroadcastReceiver mReciever;
private boolean mShowNotification;
UsageStatsManager mUsageStatsManager;
ActivityManager manager;
PowerManager pmanager;
SharedPreferences prefs;
public boolean run;
Timer f6t;
TimerTask tt;

class C02221 extends BroadcastReceiver {
    C02221() {
    }

    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(Utils.ACTION_UPDATE)) {
            MyAppLockService.this.refreshList();
        } else if (intent.getAction().equals(Utils.ACTION_STOP_SELF)) {
            MyAppLockService.this.doStopSelf();
        } else if (intent.getAction().equals(Utils.ACTION_REMOVE_APP)) {
            MyAppLockService.this.removeAppFromLockedList(intent
                    .getStringExtra("packName"));
        }
    }
}

@SuppressLint("NewApi")

class C02232 extends TimerTask {
    C02232() {
    }

    @SuppressLint("NewApi")
    public void run() {
        if (Utils.isScreenOn(MyAppLockService.this.pmanager)) {
            MyAppLockService.this.isRefreshedList = false;
            String current = "";
            try {
                current = Utils.getProcess(
                        MyAppLockService.this.mUsageStatsManager,
                        MyAppLockService.this.getApplicationContext());
            } catch (Exception e) {
                current = "";
            }
            if (current != null) {
                if (MyAppLockService.flag
                        && current
                                .equals(MyAppLockService.this.currentHomePackage)) {
                    if (MyAppLockService.this.prefs.getBoolean(
                            "immediately", true)) {
                        MyAppLockService.locked_list = new DBHelper(
                                MyAppLockService.this
                                        .getApplicationContext())
                                .getApsHasStateTrue();
                    }
                    MyAppLockService.flag = false;
                }
                if (!current
                        .equals(MyAppLockService.this.currentHomePackage)
                        && MyAppLockService.locked_list.contains(current)) {
                    Intent it;
                    if (MyAppLockService.BuildV >= 23) {
                        long endTime = System.currentTimeMillis();
                        UsageEvents usageEvents = MyAppLockService.this.mUsageStatsManager
                                .queryEvents(endTime - 10000, endTime);
                        Event event = new Event();
                        while (usageEvents.hasNextEvent()) {
                            usageEvents.getNextEvent(event);
                        }
                        if (current.equals(event.getPackageName())
                                && event.getEventType() == 1) {
                            MyAppLockService.pack = current;
                            if (MyAppLockService.this.prefs.getBoolean(
                                    "isPattern", false)) {
                                MyAppLockService.this
                                        .confirmPattern(current);
                            } else {
                                it = new Intent(
                                        MyAppLockService.this
                                                .getApplicationContext(),
                                        AppLockActivity.class);
                                it.setFlags(DriveFile.MODE_READ_ONLY);
                                MyAppLockService.this
                                        .getApplicationContext()
                                        .startActivity(it);
                            }
                            MyAppLockService.flag = true;
                            return;
                        }
                        return;
                    }
                    MyAppLockService.pack = current;
                    if (MyAppLockService.this.prefs.getBoolean("isPattern",
                            false)) {
                        MyAppLockService.this.confirmPattern(current);
                    } else {
                        it = new Intent(
                                MyAppLockService.this
                                        .getApplicationContext(),
                                AppLockActivity.class);
                        it.setFlags(DriveFile.MODE_READ_ONLY);
                        MyAppLockService.this.getApplicationContext()
                                .startActivity(it);
                    }
                    MyAppLockService.flag = true;
                }
            }
        } else if (!MyAppLockService.this.isRefreshedList) {
            MyAppLockService.this.refreshList();
        }
    }
}

public MyAppLockService() {
    this.run = true;
}

static {
    BuildV = VERSION.SDK_INT;
}

public IBinder onBind(Intent intent) {
    return null;
}

public void onCreate() {

    this.prefs = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    this.manager = (ActivityManager) getApplicationContext()
            .getSystemService("activity");
    this.pmanager = (PowerManager) getApplicationContext()
            .getSystemService("power");
    if (BuildV >= 21) {
        this.mUsageStatsManager = (UsageStatsManager) getApplicationContext()
                .getSystemService("usagestats");
    }
    startNotification();
    Intent intent = new Intent("android.intent.action.MAIN");
    intent.addCategory("android.intent.category.HOME");
    this.currentHomePackage = getPackageManager().resolveActivity(intent,
            Cast.MAX_MESSAGE_LENGTH).activityInfo.packageName;
    this.mReciever = new C02221();
    IntentFilter filter = new IntentFilter(Utils.ACTION_UPDATE);
    filter.addAction(Utils.ACTION_STOP_SELF);
    filter.addAction(Utils.ACTION_REMOVE_APP);
    registerReceiver(this.mReciever, filter);
    refreshList();
    this.tt = new C02232();
    this.f6t = new Timer();
    this.f6t.schedule(this.tt, 500, 500);
    super.onCreate();
    Calendar cal = Calendar.getInstance();
    Intent intent12 = new Intent(getBaseContext(),MyAppLockService.class);
    PendingIntent pintent = PendingIntent.getService(getBaseContext(), 0, intent12, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),5, pintent);
}

public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, START_STICKY_COMPATIBILITY, startId);

}

public void onDestroy() {
    try {
        this.f6t.cancel();
        this.tt.cancel();
    } catch (Exception e) {
        e.printStackTrace();
    }

        Intent intent1 = new Intent("com.android.techtrainner");
        intent1.putExtra("yourvalue", "torestore");
        sendBroadcast(intent1);

}

public void refreshList() {
    locked_list = new DBHelper(getApplicationContext())
            .getApsHasStateTrue();
    if (locked_list.size() == 0) {
        doStopSelf();
    }
    this.isRefreshedList = true;
}

@SuppressLint({ "InlinedApi" })
private void startForegroundWithNotification() {
    PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
            Calculator_Activity.class), 0);
    String title = getString(R.string.app_name);
    String content = getString(R.string.app_name);
    Builder nb = new Builder(this);
    nb.setSmallIcon(R.drawable.ic_transparent);
    nb.setContentTitle(title);
    nb.setContentText(content);
    nb.setWhen(System.currentTimeMillis());
    nb.setContentIntent(pi);
    nb.setOngoing(true);
    nb.setPriority(0);
    startForeground(NOTIFICATION_ID, nb.build());
}

private void startNotification() {
    startForegroundWithNotification();
    if (!this.mShowNotification) {
        HelperService.removeNotification(this);
    }
}

private void doStopSelf() {
    this.mAllowDestroy = true;
    unregisterReceiver(this.mReciever);
    stopForeground(true);
    stopSelf();
}

private void confirmPattern(String st) {

    Intent pIntent = new Intent(getApplicationContext(),
            ResetActivity.class);
    pIntent.putExtra("isFromReset", true);
    PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
            12345, pIntent, DriveFile.MODE_READ_ONLY);

    Intent intent = new Intent(LockPatternActivity.ACTION_COMPARE_PATTERN, null,
            getApplicationContext(), LockPatternActivity.class);
    intent.putExtra("packName", st);
    intent.putExtra("isStealthMode", this.prefs.getBoolean(
            AlpSettings.Display.METADATA_STEALTH_MODE, false));
    intent.putExtra("isFromLock", true);
    intent.setFlags(DriveFile.MODE_READ_ONLY);
    intent.addFlags(Cast.MAX_MESSAGE_LENGTH);

    intent.putExtra(LockPatternActivity.EXTRA_PENDING_INTENT_FORGOT_PATTERN, pi);

    startActivity(intent);

}

private void removeAppFromLockedList(String packName) {
    locked_list.remove(packName);
}

if there is any solution for it then please help me out thanks in advance


来源: stackexchange

问:
How to crop multiple part of image file in android?

show this image in multiple part of crop.and save this multiple crop parts in different files.

答:
You can do it with XML ImageViewes

Maybe you can play with the scaleType and scaleX-Y (example.: with a bar) and you can save the ImageView Bitmap as a File or a Drawable in the resources.

link (little help)

ContentLicense: CC BY-SA 3.0


问:
Getting "Missing SDK in target picChoice: iphoneos4.0" error when building a test release of my app in Xcode 4, pvw 5
I have opened a functioning Xcode 3x project in Xcode 4.0 pvw 5 and am getting the following error whei I try to build a debug version of the app: "Missing SDK in target picChoice: iphoneos4.0"

I am trying to find where and how to remedy this, and I am coming up with bupkus.

I apologize if this is not very clear, but I am rather flummoxed by Xcode 4 so far....

答:
Ok...I resolved this, but I did not properly track HOW I resolved it....

I think my Target's Base SDK was not set, and I set it to: Latest iOS (iOS 4.2)....

I think that's how I did it....

But, now it builds with no errors and loads onto my iPhone as expected.

ContentLicense: CC BY-SA 2.5


问:
Send message to UI thread
I create a thread to listening the input stream of the serial port.
And when there is input data coming, I want to send a message to UI thread.

Before doing my task, I try to send message from the thread with interval 5000 ms, and send a message to UI thread and Toast it.
From the log, I know that the thread is created and running succefully, but the number is not toasted in the UI thread.

I think it may be due to fail to send a message from the thread to UI thread, or fail to handle the message in the MessageQueue of UI thread.

What's wrong with my code?
Many thanks!

MainActivity.java:

```<code>public class MainActivity extends Activity {
    ...
    @Override
    protected void onCreate(Bundle savedInstancesState) {
        ...
        setMessageProcessor();
        SerialPortListener.start();
    }

    private void setMessageProcessor() {
        new Handler(Looper.getMainLooper()) {
            public void handleMessage(Message msg) {
                Toast.makeText(MainActivity.this,
                    "Message: " + msg.obj.toString(),
                    Toast.LENGTH_SHORT).show();
            }
        };
    }
}
</code>```

SerialPortListener.java:

```<code>public class SerialPortListener {
    ...
    private static int testNumber = 1;
    public static void start() {
        ...
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Message msg = new Message();
                    msg.obj = testNumber++;
                    new Handler(Looper.getMainLooper()).sendMessage(msg);
                    Log.i("TEST", "TEST);
                    try {
                        Thread.sleep(5000);
                    } catche(Exception e) {
                        ...
                    }
                }
            }
        });
        thread.start();
    }
}
</code>```

答:
It's because you are creating a second Handler bound to the main thread from within your "reader thread".  Don't use an anonymous object for the handler in the main thread, make it a member field. Then in your reader thread, send the Message to that specific Handler:

```<code>private void setMessageProcessor() {
    mHandler = new Handler() {
        ...
    }
}

public class SerialPortListener {
...
private static int testNumber = 1;
public static void start() {
    ...
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                Message msg = mHandler.obtainMessage();
                msg.obj = testNumber++;
                msg.sendToTarget();
                Log.i("TEST", "TEST);
                ...
        }
    }
}
</code>```

Title: Send message to UI thread

Body:
I create a thread to listening the input stream of the serial port.
And when there is input data coming, I want to send a message to UI thread.

Before doing my task, I try to send message from the thread with interval 5000 ms, and send a message to UI thread and Toast it.
From the log, I know that the thread is created and running succefully, but the number is not toasted in the UI thread.

I think it may be due to fail to send a message from the thread to UI thread, or fail to handle the message in the MessageQueue of UI thread.

What's wrong with my code?
Many thanks!

MainActivity.java:

public class MainActivity extends Activity {
    ...
    @Override
    protected void onCreate(Bundle savedInstancesState) {
        ...
        setMessageProcessor();
        SerialPortListener.start();
    }

    private void setMessageProcessor() {
        new Handler(Looper.getMainLooper()) {
            public void handleMessage(Message msg) {
                Toast.makeText(MainActivity.this,
                    "Message: " + msg.obj.toString(),
                    Toast.LENGTH_SHORT).show();
            }
        };
    }
}

SerialPortListener.java:

public class SerialPortListener {
    ...
    private static int testNumber = 1;
    public static void start() {
        ...
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Message msg = new Message();
                    msg.obj = testNumber++;
                    new Handler(Looper.getMainLooper()).sendMessage(msg);
                    Log.i("TEST", "TEST);
                    try {
                        Thread.sleep(5000);
                    } catche(Exception e) {
                        ...
                    }
                }
            }
        });
        thread.start();
    }
}

Body:
It's because you are creating a second Handler bound to the main thread from within your "reader thread".  Don't use an anonymous object for the handler in the main thread, make it a member field. Then in your reader thread, send the Message to that specific Handler:

private void setMessageProcessor() {
    mHandler = new Handler() {
        ...
    }
}

public class SerialPortListener {
...
private static int testNumber = 1;
public static void start() {
    ...
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                Message msg = mHandler.obtainMessage();
                msg.obj = testNumber++;
                msg.sendToTarget();
                Log.i("TEST", "TEST);
                ...
        }
    }
}


问:
How to delete all the Existing tables in DynamoDb?
I wants to delete all the existing tables in my database in DynamoDb?

Is there any way to do it?

答:
```<code>require 'json'
tables=JSON.parse(`aws dynamodb list-tables`)["TableNames"]

tables.each do |table|
  `aws dynamodb delete-table  --table-name #{table}`
  sleep 2 # Only 10 tables can be created, updated, or deleted simultaneously
  puts "#{table} deleted"
end
</code>```


问:
Do I need a wildcard ssl certificate for subdomains in Azure?
In our Azure subscription, we have 3 apps: dev.myapp.com, test.myapp.com, prod.myapp.com (www.myapp.com, myapp.com).

Previously I just purchased a wildcard cert, and then converted it to PFX format and uploaded it.

But I see now that I can get an SSL cert directly from Azure, and save a bit of hassle. But I am wondering if I buy an S1 certificate, if I can use it with my subdomains, or if I need to buy the wildcard (which is quite expensive compared to getting it from another source).

I assume I need the wildcard, would just like to confirm.

答:
You can take either single domain SSL or Wildcard SSL certificate to secure sub domains.

If the time of the various SSL certificate management does not matter to you, but the price is important then go for a single domain SSL certiifcate, otherwise go for Wildcard SSL certificate which secures number of sub domains.

If have price concern for wildcard ssl certificate then go with comodo certificate authority resellers.


问:
What is the best way to deal with JSON object?
I have a big string that represents JSON feed. My app downloads this feed from remote web service.

Questions:

1) Once I download JSON feed, where should I store it? Right now I am storing it in app Preferences and it works fine. I am just interested if there is any reason not to do that, or if there are better/faster options, like Internal Storage or something else?

2) When I am about to show data from this feed in my activity, I do something like this:

```<code>JSONObject jsonObj = new JSONObject(json_string);
JSONArray jsonArr = jsonObj.getJSONArray("root");
for (int m = 0; m < jsonArr.length(); m++) {
    ....
}
</code>```

The problem is, the first line that parses JSON feed is sort of expensive. At my current size feed (that might grow in the future) it takes maybe half a second to complete, not much, but still a problem. For example, I click button to call activity (to show data) and this 1/2 sec pause is noticeable and not good.

To avoid this pause, I should probably parse JSON immediately after feed is downloaded. Then question is, where should I keep parsed JSON object?

i) I can't save JSON object to preferences since only primitive data can be stored there.

ii) Should I do parsing every time my app starts, and make my parsed JSON objects (I have more of them) global (on application level) so I can access them from all of my activities?

iii) Or, I believe my 3rd option would be to declare JSON objests static so they can be easy accessed from other activities?

What is the best way to do this?

THX.

答: Do you need to store it? If you download it once from a webpage and that's all you need, storing it in shared preferences is fine. If you need to get it a lot, why even store it? You could also store it in the cache directory</p>

Body:
I have a big string that represents JSON feed. My app downloads this feed from remote web service.

Questions:

1) Once I download JSON feed, where should I store it? Right now I am storing it in app Preferences and it works fine. I am just interested if there is any reason not to do that, or if there are better/faster options, like Internal Storage or something else?

2) When I am about to show data from this feed in my activity, I do something like this:

JSONObject jsonObj = new JSONObject(json_string);
JSONArray jsonArr = jsonObj.getJSONArray("root");
for (int m = 0; m < jsonArr.length(); m++) {
    ....
}

The problem is, the first line that parses JSON feed is sort of expensive. At my current size feed (that might grow in the future) it takes maybe half a second to complete, not much, but still a problem. For example, I click button to call activity (to show data) and this 1/2 sec pause is noticeable and not good.

To avoid this pause, I should probably parse JSON immediately after feed is downloaded. Then question is, where should I keep parsed JSON object?

i) I can't save JSON object to preferences since only primitive data can be stored there.

ii) Should I do parsing every time my app starts, and make my parsed JSON objects (I have more of them) global (on application level) so I can access them from all of my activities?

iii) Or, I believe my 3rd option would be to declare JSON objests static so they can be easy accessed from other activities?

What is the best way to do this?

THX.


问:
Ordering Checkbox and its label
I am working in the Oracle CPQ tool, and I'm trying to create a checkbox as an attribute.

In the UI I am getting the following:

When reviewed in the browser source (which is generated by the CPQ tool), I can see the following HTML code:

```<code><div class="form-item clearfix null" id="attr_wrapper_1_chkmembershipFeePayment_t" style="display: table;">
<label class="form-label" for="chkmembershipFeePayment_t" style="width: 100px">
    <span style="padding-right: 5px;display: table-cell;">Membership Fee</span>
</label>
<div class="form-element field-wrapper" id="field_wrapper_1_chkmembershipFeePayment_t" style="padding-left:100px">
    <div class="boolean-wrapper field" message="" style="display: table-cell;">
        <div class="boolean-wrapper-inner"><input value="false" class=" form-input  cm-attr-value " name="chkmembershipFeePayment_t" onclick="if (this.checked) { this.value='true'; } else { this.value='false'; }" data-is-boolean="true" type="checkbox">
        </div>
        <input value="true" name="_boolean_present_chkmembershipFeePayment_t" type="hidden">
    </div>
    <div id="msg_1_chkmembershipFeePayment_t" class="error-hover" data-action-message="" message=""></div>
</div>
::after</div>
</code>```

My question is: How can I switch the checkbox and the label, placing the checkbox before the label 'Membership free' using CSS or JavaScript, considering I cannot directly edit the HTML using the CPQ tool attribute.

So any way to do that?

After Sagar V updated javascript

答:
The JavaScript

get the label element

remove it from original position

add it after the input

elm = document.querySelector('label[for=chkmembershipFeePayment_t]');

target = document.querySelector("input[type=checkbox]");

elm.parentNode.removeChild(elm);

target.parentNode.insertBefore(elm, target.nextSibling);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="form-label" for="chkmembershipFeePayment_t" style="width: 100px">
<span style="padding-right: 5px">Membership Fee</span>
</label>
<div class="form-element field-wrapper" id="field_wrapper_1_chkmembershipFeePayment_t" style="padding-left:100px">
  <div class="boolean-wrapper field" message="">
    <div class="boolean-wrapper-inner">
      <input value="false" class=" form-input  cm-attr-value " name="chkmembershipFeePayment_t" onclick="if (this.checked) { this.value='true'; } else { this.value='false'; }" data-is-boolean="true" type="checkbox">
    </div>
    <input value="true" name="_boolean_present_chkmembershipFeePayment_t" type="hidden">
  </div>
  <div id="msg_1_chkmembershipFeePayment_t" class="error-hover" data-action-message="" message=""></div></code>```

Title: Ordering Checkbox and its label

Body:
I am working in the Oracle CPQ tool, and I'm trying to create a checkbox as an attribute.

In the UI I am getting the following:

When reviewed in the browser source (which is generated by the CPQ tool), I can see the following HTML code:

    Membership Fee

<input value="false" class=" form-input  cm-attr-value " name="chkmembershipFeePayment_t" onclick="if (this.checked) { this.value='true'; } else { this.value='false'; }" data-is-boolean="true" type="checkbox">

        <input value="true" name="_boolean_present_chkmembershipFeePayment_t" type="hidden">

::after

My question is: How can I switch the checkbox and the label, placing the checkbox before the label 'Membership free' using CSS or JavaScript, considering I cannot directly edit the HTML using the CPQ tool attribute.

So any way to do that?

After Sagar V updated javascript

Body:
The JavaScript

get the label element

remove it from original position

add it after the input

elm = document.querySelector('label[for=chkmembershipFeePayment_t]');

target = document.querySelector("input[type=checkbox]");

elm.parentNode.removeChild(elm);

target.parentNode.insertBefore(elm, target.nextSibling);

<label class="form-label" for="chkmembershipFeePayment_t" style="width: 100px">
<span style="padding-right: 5px">Membership Fee</span>
</label>
<div class="form-element field-wrapper" id="field_wrapper_1_chkmembershipFeePayment_t" style="padding-left:100px">
  <div class="boolean-wrapper field" message="">
    <div class="boolean-wrapper-inner">
      <input value="false" class=" form-input  cm-attr-value " name="chkmembershipFeePayment_t" onclick="if (this.checked) { this.value='true'; } else { this.value='false'; }" data-is-boolean="true" type="checkbox">
    </div>
    <input value="true" name="_boolean_present_chkmembershipFeePayment_t" type="hidden">
  </div>
  <div id="msg_1_chkmembershipFeePayment_t" class="error-hover" data-action-message="" message=""></div>


问:
Dealing with randomly generated JSON
Pleaseeeeeeee help me, it's been three weeks since I turned around to found how make POJO jackson with this json, random is randonm keyname.

{
   "a": {
     "b1": "1",
     "b2": "{
        "random" : {
            "c1": "10"
            "c2": "20"
        }
    }
 }

Somebody can help me ?

答:
You can use the online utility
http://www.jsonschema2pojo.org/</p>

Title: Dealing with randomly generated JSON


问:
QGIS - Mapping Ward Areas into Thiessen Polygons
I am designing a water supply distribution network. I have various pipes represented by Lines. Each start and end point of Line is a Junction (Node).
I have created Thiessen Polygons (Voronoi) using QGIS for each Junction (The Thiessen Polygon represents flow area for its corresponding Junction.)
I also have various Ward Boundaries (also represented as irregular Polygons), with each Ward having different Population.

My requirement : I want to calculate area of intersection between each Thiessen Polygon and each Ward and get a table, so that I can calculate the exact population within each Thiessen Polygon.

Example of Thiessen Polygons (The Dot within polygon represents corresponding Junction) :-

Example of Wards (also represented as Closed Polygons) :-

Final output desired :-

答:
I have found the solution in ARCGIS -> Intersect Tool where it intersects Two Shapefiles (each having multiple polygons) and gives intersection results.
I think the same is not possible in QGIS as of now.</p>


问:
How to append the following characters ‡, †, * as superscript to NSString in iOS
I need append the following  characters ‡, †, * as superscript  to NSString in iOS . Need your help. I use the following http://en.wikipedia.org/wiki/General_Punctuation_(Unicode_block) link but they are appending to NSString , But i want them as superscript

答:
Swift

Step 1.

```<code>    import CoreText
</code>```

Step 2.

```<code>    let range1 = NSMakeRange(1, 1)
    let range2 = NSMakeRange(5, 1)

    let mutableStr : NSMutableAttributedString = NSMutableAttributedString(string: "h20 x2")
    mutableStr.addAttribute(kCTSuperscriptAttributeName as String, value:-1, range: range1)
    mutableStr.addAttribute(kCTSuperscriptAttributeName as String, value:1, range: range2)

    self.lbl.attributedText = mutableStr
</code>```

Output:

Body:
Swift

Step 1.

    import CoreText

Step 2.

    let range1 = NSMakeRange(1, 1)
    let range2 = NSMakeRange(5, 1)

    let mutableStr : NSMutableAttributedString = NSMutableAttributedString(string: "h20 x2")
    mutableStr.addAttribute(kCTSuperscriptAttributeName as String, value:-1, range: range1)
    mutableStr.addAttribute(kCTSuperscriptAttributeName as String, value:1, range: range2)

    self.lbl.attributedText = mutableStr

Output:


问:
Why do we need AML - ACPI Machine Language?
As I understand, ACPI defines a generic hardware programming model where operating system relies on the OEM firmware provided AML (ACPI machine language) code to manipulate the hardware.

In order to execute the AML code, operating system has to incorporate an AML interpreter.

So, it looks to me that firmware developers use AML to provide a control interface between platform hardware and operating system.

But do we really need AML?

I think ultimately the hardware can only be configured through the native instruction of the platform. So the AML interpreter must translate the AML into native instructions otherwise it cannot be executed on the platform.

But what's the point of using an intermediate language like AML? I mean though the AML is said to be platform-independent, which means I can use AML to describe my platform in a non-native way.

But the AML is part of the platform firmware in practice. And the entire firmware has already been built into the target platform's native instructions. So what good can it be to make such a little part of the firmware as platform-independent? Why not just use native instructions? There must be some way to let OS use it as well. And this way operating system doesn't need the AML interpreter at all. A lot of complexity can be avoided.

答:
One of the big goals of ACPI over its predecessor APM was to give the OS more viability and control over power state transitions.

APM was a black box. The OS knew nothing about the power management implementation. It would just call a BIOS function and the BIOS handled all of the magic. Did it work?  Did the system sleep properly? Did the system freeze?  Was a user application able to handle the BIOS implementation?  The sad truth was that many systems had power management that was downright broken, and Microsoft wanted to provide a better power management experience for the growing laptop industry.

Now, the BIOS hands the ASL/AML code over to the OS and the OS executes it not the BIOS. If the BIOS code does something dumb (like messing with registers it shouldn't), Windows can detect that by parsing the code and block it. AML is 100% decompilable unlike C.

Remember that ACPI is not x86 specific. At the time it was developed, Itanium and Xscale were around. Intel and Microsoft needed a language that would work on all platforms, both 32 and 64 bit.

Lastly, ASL is more than just a list of executable functions. It is also number of static configuration tables. The ASL code has tables to define the non PnP hardware built onto your motherboard.  It has tables of supported power states.  A traditional programming language like C isn't really setup for that.

If ACPI was invented today, they would probably use something like XML to provide the info to the OS.

ContentLicense: CC BY-SA 4.0


问:
How do you override bootstrap.min.css? Django
On my page I have a toolbar which is supposed to be centered in the middle. I have a seperate css sheet which centres it, however it keeps being overriden by the min.css file.

In my body content.css I have:

```<code>.btn-toolbar .btn, .btn-toolbar .btn-group, .btn-toolbar .input-group {
  float:none !important;
}
</code>```

But when I inspect the page via the console it it always shows this in the min.css:

```<code>.btn-toolbar .btn, .btn-toolbar .btn-group, .btn-toolbar .input-group {
  float:left;
}
</code>```

How do I override it?

答:
On  reorder your CSS files:

```<code><!--CSS-->
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="contents.css" rel="stylesheet" type="text/css">
</code>```

Body:
On my page I have a toolbar which is supposed to be centered in the middle. I have a seperate css sheet which centres it, however it keeps being overriden by the min.css file.

In my body content.css I have:

.btn-toolbar .btn, .btn-toolbar .btn-group, .btn-toolbar .input-group {
  float:none !important;
}

But when I inspect the page via the console it it always shows this in the min.css:

.btn-toolbar .btn, .btn-toolbar .btn-group, .btn-toolbar .input-group {
  float:left;
}

How do I override it?

Body:
On <head> reorder your CSS files:

<!--CSS-->
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="contents.css" rel="stylesheet" type="text/css">


问:
Symfony2 - Accessing entity from NativeQuery result key
I'm trying to generate a nativeQuery using a mixed ResultSetMapping that contains entities and scalar results. For example:

```<code>$rsm = new ResultSetMapping();
$rsm->addEntityResult('MyBundle:Evaluation','e');
$rsm->addFieldResult('e','id','id');
$rsm->addScalarResult('company','company');
</code>```

when i {{dump()}} one of the query result elements, it looks like this:

```<code>array:2 [▼
  0 => Evaluation {▼
    #id: 24
  }
  "company" => "INRA"
]
</code>```

So in the result array, the company is identified with the "company" key while my Evaluation entity is identified with the "0" key.

My question is: is there another way to access entities defined in ResultSetMapping() other than with their numeric key ? like ScalarResults ?

答:
Number of results returned is connected with query, not the ResultSetMapping object.

Assuming you have used $query->getResult(); to fetch data, you can switch to $query->getSingleResult() or $query->getOneOrNullResult() Keep in mind those methods throw exceptions when more than one result is available.

You also (most likely) need to update last line, and place everything under the same alias:

$rsm->addScalarResult('company','e');

Second param represents alias docs. Additionally simillar issues was covered here

Hope this helps.

Body:
I'm trying to generate a nativeQuery using a mixed ResultSetMapping that contains entities and scalar results. For example:

$rsm = new ResultSetMapping();
$rsm->addEntityResult('MyBundle:Evaluation','e');
$rsm->addFieldResult('e','id','id');
$rsm->addScalarResult('company','company');

when i {{dump()}} one of the query result elements, it looks like this:

array:2 [▼
  0 => Evaluation {▼
    #id: 24
  }
  "company" => "INRA"
]

So in the result array, the company is identified with the "company" key while my Evaluation entity is identified with the "0" key.

My question is: is there another way to access entities defined in ResultSetMapping() other than with their numeric key ? like ScalarResults ?


问:
Move to new row every 4th column
I got data that is stored in one row of columns in an excel sheet.
Is there a way to move data to next row every 4th column? Is there a built in function for this?
For example:

Data:

```<code>Actinium | Ac | 89 | 227.0278* | Aluminum | Al | 13 | 26,981539 ...
</code>```

Output:

```<code>Actinium |Ac | 89 | 227.0278*
Aluminum |Al | 13 | 26,981539
</code>```

答:
I made a macro:

```<code>Sub dela_igen()
Dim i As Integer, j As Integer, cur_column As Integer

cur_column = 1
For i = 1 To 100
    For j = 1 To 4
        Cells(i, j).Value = Cells(1, cur_column).Value
        cur_column = cur_column + 1
    Next j
Next i

End Sub
</code>```

Worked like a charm!

Title: Move to new row every 4th column

Body:
I got data that is stored in one row of columns in an excel sheet.
Is there a way to move data to next row every 4th column? Is there a built in function for this?
For example:

Data:

Actinium | Ac | 89 | 227.0278* | Aluminum | Al | 13 | 26,981539 ...

Output:

Actinium |Ac | 89 | 227.0278*
Aluminum |Al | 13 | 26,981539

Body:
I made a macro:

Sub dela_igen()
Dim i As Integer, j As Integer, cur_column As Integer

cur_column = 1
For i = 1 To 100
    For j = 1 To 4
        Cells(i, j).Value = Cells(1, cur_column).Value
        cur_column = cur_column + 1
    Next j
Next i

End Sub

Worked like a charm!


问:
Preserving stack trace when rethrowing exceptions in Silverlight
I need to rethrow an Exception that was caught and stored elsewhere without losing the stack trace information about when the Exception was first caught/stored.  My code looks something like this:

```<code>    public void Test()
    {
        int someParameter = 12;
        ExecuteSomeAsyncMethod(someParameter, CallbackMethod);
    }

    public void CallbackMethod(object result, Exception error)
    {
        //Check for exceptions that were previously caught and passed to us
        if(error != null)
            //Throwing like this will lose the stack trace already in Exception
            //We'd like to be able to rethrow it without overwriting the stack trace
            throw error;

        //Success case: Process 'result'...etc...
    }
</code>```

I've seen solutions to this problem that use reflection (for example here and here) or use Serialization (for example here) but none of those will work for me in Silverlight (private reflection is not allowed and the classes/methods used in the serialization approach don't exist in Silverlight).

Is there any way to preserve the stack trace that works in Silverlight?

答:
You can either use

```<code>catch(Exeption)
{
   throw;
}
</code>```

or

```<code>catch(Exception e)
{
   throw new Exception(e);
}
</code>```

Both will keep the stack trace. The first solution seems not to be possible in your example, but the second should work.

Of cause in your case you would throw the parameter error instead of e.

Body:
I need to rethrow an Exception that was caught and stored elsewhere without losing the stack trace information about when the Exception was first caught/stored.  My code looks something like this:

    public void Test()
    {
        int someParameter = 12;
        ExecuteSomeAsyncMethod(someParameter, CallbackMethod);
    }

    public void CallbackMethod(object result, Exception error)
    {
        //Check for exceptions that were previously caught and passed to us
        if(error != null)
            //Throwing like this will lose the stack trace already in Exception
            //We'd like to be able to rethrow it without overwriting the stack trace
            throw error;

        //Success case: Process 'result'...etc...
    }

I've seen solutions to this problem that use reflection (for example here and here) or use Serialization (for example here) but none of those will work for me in Silverlight (private reflection is not allowed and the classes/methods used in the serialization approach don't exist in Silverlight).

Is there any way to preserve the stack trace that works in Silverlight?

Body:
You can either use

catch(Exeption)
{
   throw;
}

or

catch(Exception e)
{
   throw new Exception(e);
}

Both will keep the stack trace. The first solution seems not to be possible in your example, but the second should work.

Of cause in your case you would throw the parameter error instead of e.


问:
Convert list of dataframes to list of numeric vectors in R
I have a list L of dataframes. The elements (dataframes) of L are unnamed. Each element includes only one variable Var (same for all elements) and one observation (unique across elements). The observations are lists of random "numbers". An elements of L can look like: :'data.frame': 1 obs. of 1 variable: $ Var: chr "\"4\", \"32\", \"25\", \"4\", ". And is.atomic(L[[1]]$Var) returns TRUE. I am looking for a way to convert L into a list of unnamed numeric vectors. End result should be:

```<code>> L
[[1]]
[1]  4 32  25 4
</code>```

Right now I have:

```<code>> L
[[1]]
                   Var
1 "4", "32", "25", "4",
</code>```

I have tried as.numeric but keep getting the warning NAs introduced by coercion and the result is not as expected. Obviously I am doing something wrong. Any help is appreciated!

edit: deleted the L sample as it was unnecessary.

答:
Your strings need separating and stripping of quotation marks, by the look of it. They might also be factors. Try something like this...</p>

```<code>L <- list(data.frame(Var='"1","2","3","4"'),data.frame(Var='"3","4","5","6"'))

K <- lapply(L,function(df) as.numeric(gsub('"','',unlist(strsplit(as.character(df[1,1]),',')))))
</code>```

Body:
I have a list L of dataframes. The elements (dataframes) of L are unnamed. Each element includes only one variable Var (same for all elements) and one observation (unique across elements). The observations are lists of random "numbers". An elements of L can look like: :'data.frame': 1 obs. of 1 variable: $ Var: chr "\"4\", \"32\", \"25\", \"4\", ". And is.atomic(L[[1]]$Var) returns TRUE. I am looking for a way to convert L into a list of unnamed numeric vectors. End result should be:

> L
[[1]]
[1]  4 32  25 4

Right now I have:

> L
[[1]]
                   Var
1 "4", "32", "25", "4",

I have tried as.numeric but keep getting the warning NAs introduced by coercion and the result is not as expected. Obviously I am doing something wrong. Any help is appreciated!

edit: deleted the L sample as it was unnecessary.

Body:
Your strings need separating and stripping of quotation marks, by the look of it. They might also be factors. Try something like this...

L <- list(data.frame(Var='"1","2","3","4"'),data.frame(Var='"3","4","5","6"'))

K <- lapply(L,function(df) as.numeric(gsub('"','',unlist(strsplit(as.character(df[1,1]),',')))))


问:
Excel Pivot Table filters values changing on source update
In our BI infrastructure we're using Excel's pivot tables to expose the data in an Analysis Service instance (the cube), and thus far we have nothing to complain about.

Excel "reports" can be defined containing pre-selected dimensions as rows, columns and filters, for example we can set the Time dimension as a column slicer, or the Country dimension as a filter slicer. This allows the users to access this pre-defined report with the slicers already in place where they just have to select there own values to slice with if needs be.

However, even tough this is working perfectly the issue emerges when we try to actually pre-define specific values in a filter slicer. These values are getting "randomly" changed after a few days without any particular pattern from what we can observe. (Note that the cube i.e. the data source is being updated daily)

For example, we want to create a report were the users would have the data already filtered by the countries Italy and France upon opening it. So we created a report where we have the Country as a filter slicer and the countries Italy and France set as specific slicers under the Country filter.

Now the problem is that this report would maintain it's structure and selected filter values for just a few days, after which Italy may get de-selected and Germany would now be selected, or only France is maintained as a slicer. And again, we can't seem to observe any particular pattern in these changes, neither the time it's taking to "lose its format", or the filter values being selected to filter with.

Furthermore, note that even tough the underlying data source is changing daily, the pre-selected values are always there and never deleted, i.e. Italy and France in this case, would always be available in the data source. In fact you could still select them in the report, even tough they are no longer selected by default.

Anyone can help us understand why this is occurring and what can be done to go around it?

EDIT
Just realized that the slicer which values keeps changing every once in a while, is a column in another table. For example the Country Italy is in reality a column in a table City and therefore can be found in multiple records such as Rome, Milan etc., and then is exposed as a dimension in SSAS.

答:
In PivotTable Options/Data there is an option called: "Number of items to retain per field" which default is set to automatic.

I believe this might be what causes it to work at random, and then suddenly change. Try changing it to 'max'.


问:
Automated Apps Script for BigQuery Not Connecting To Right Project?
I'm getting the below problem with apps script which is attempting to run a query and create a table, TEST4, in BigQuery. The error is:

"Project 603804914871 is not found and cannot be used for API calls.
  (line 19, file "Code")"

Query is:

```<code>saveQueryToTable() {
      var projectId = 'fiery-cabinet-****';
      var datasetId = '11234***1';
      var tableId = 'TEST4';
      var job = {
        configuration: {
          query: {
            query: 'SELECT *' +
                   'FROM Test2;',
            destinationTable: {
              projectId: projectId,
              datasetId: datasetId,
              tableId: tableId
            }
          }
        }
      };

  var queryResults = BigQuery.Jobs.insert(job, projectId);
  Logger.log(queryResults.status);
}
</code>```

Could anyone let me know where I'm going wrong?

I can find that project in my console, I can enable the bigquery API for that project and then I don't get any errors... however it doesn't run the query or save to a new table "TEST4"?

答: Response from @KENDi was correct. I had to enable the API in the Google Developer Console.</p>

Body:
I'm getting the below problem with apps script which is attempting to run a query and create a table, TEST4, in BigQuery. The error is:

"Project 603804914871 is not found and cannot be used for API calls.
  (line 19, file "Code")"

Query is:

saveQueryToTable() {
      var projectId = 'fiery-cabinet-****';
      var datasetId = '11234***1';
      var tableId = 'TEST4';
      var job = {
        configuration: {
          query: {
            query: 'SELECT *' +
                   'FROM Test2;',
            destinationTable: {
              projectId: projectId,
              datasetId: datasetId,
              tableId: tableId
            }
          }
        }
      };

  var queryResults = BigQuery.Jobs.insert(job, projectId);
  Logger.log(queryResults.status);
}

Could anyone let me know where I'm going wrong?

I can find that project in my console, I can enable the bigquery API for that project and then I don't get any errors... however it doesn't run the query or save to a new table "TEST4"?


问:
SQL query get last value
I want to get the last time (by date) that appears a (Empleado) where the value "Entrar" is 1
enter image description here

```<code>SELECT '20498090R'
FROM fichajes
WHERE fecha IN (SELECT MAX(fecha) FROM fichajes)
  AND entrada = '1'
</code>```

But this give me the las register where entrada= '1' and I just want to return information if the last entry is 1, not the las entry where entrada ='1'

In this case my last register entrada = "0" so i need no information
What is wrong?

答:
Select the latest record for employee '20498090R' (with LIMIT). Then select this record only if entrada = 1.

```<code>select *
from fichejes
where (empleado, fecha) in
(
  select empleado, fecha
  from fichejes
  where empleado = '20498090R'
  order by fecha desc
  limit 1
)
and entrada = 1;
</code>```

Title: SQL query get last value

Body:
I want to get the last time (by date) that appears a (Empleado) where the value "Entrar" is 1
enter image description here

SELECT '20498090R'
FROM fichajes
WHERE fecha IN (SELECT MAX(fecha) FROM fichajes)
  AND entrada = '1'

But this give me the las register where entrada= '1' and I just want to return information if the last entry is 1, not the las entry where entrada ='1'

In this case my last register entrada = "0" so i need no information
What is wrong?

Body:
Select the latest record for employee '20498090R' (with LIMIT). Then select this record only if entrada = 1.

select *
from fichejes
where (empleado, fecha) in
(
  select empleado, fecha
  from fichejes
  where empleado = '20498090R'
  order by fecha desc
  limit 1
)
and entrada = 1;


问:
How to successfully unload classes when those classes are potentially in use?
I have built in my application the ability to reload classes. However, I need to clarification on the behaviour of the class loader.

Let me explain what I know and then ask the questions...

What I do is provide a special jar that is loaded by a custom classloader. Then during the bootstrap of the jar a bunch of spring beans are created and the ones which implement certain interfaces get registered for use by the central app.

Now I kick off a process in the application which uses these new classes. I can successfully unload the "jar", change classes in the jar and reload and I get the changes. Unloading in class loader parlance means making the class loader that loaded the classes unreachable - this causes any classes loaded by that class loader to be unreachable and thus effectively unloaded.

However, from what I know so far, once the vm has loaded the class it stores it in some shared space so does not have to load it again.

The issue that I have is that sometimes the unload and reload of a new class does not work. The old class stays around. It stands to reason that if I unload a class loader (i.e. make the class loader unreachable) and one of the classes in that class loader is currently in use (an object of that type exists) then the class cannot be unloaded.

Is this true? It seems to be true in practice.

If that is so, how do I successfully unload classes that are in use at the time the class loader goes unreachable. Could I for example, put a weak reference on each class so I can detect when the class goes unreachable and act when the class goes unreachable? (not sure what action I could take though).

Update in response to @Kayaman

My use case is that I have the core application and then based on the customers requirements I can load different classes that implement known interfaces in the core application (so they can be accessed). Then the core application kicks off various processes which use these classes. The big strength of this is that I can update these plugin classes without doing a big redeploy and every customer does not need every one of these. The problem comes in when I want to load a new version of one of these and  the current version is in use. Kinda stands to reason that this is not possible.

Conclusion

@Kayamam many thanks for your consult. It has been very helpful. This has codified my thinking somewhat. The conclusion is that no matter what technique I use you cannot ever, with the VM the way it is, reload a class for which there is currently a strongly reachable object. For some of my reloads I have control over these objects as I can make them unreachable before I unload and reload but for other classes I cannot do this... that is where my problem lies. What I need to do is to ring fence the objects of the classes that I wish to reload so that I can the process that is using them to pause while I reload the classes for those objects.

答:
As you said, in order to unload a class, you need to get rid of the classloader. For example URLClassLoader can be used to load classes, and then null out the reference to make it eligible for GC and therefore unload the classes it loaded.

However, all classes know which classloader loaded them. That means that if you've got instances of your classes in use, they have a reference to the Class which has a reference to the ClassLoader and will prevent it from being collected and classes being unloaded. This is understandable, since having an object without a class would be quite an interesting situation.

So for a full reload you need to get rid of old instances and get rid of the classloader. That also avoids situations where you get mysterious exceptions about MyClass != MyClass.

WeakReference (or PhantomReference would probably be better here) would allow you to notice when your existing objects get collected, you just need to make sure you're tracking them all.

Spring adds to the complexity here, so I strongly recommend spending some time imagining that this approach is impossible, and to see if Spring has something that could be used to fulfil your business requirement. After all it does a lot of classloading itself, so you might be reinventing the wheel in a less clear way.

With quick Googling I found this http://docs.spring.io/spring-boot/docs/current/reference/html/howto-hotswapping.html which mentions among other things Spring Loaded which can apparently do class reloading and then some.


问:
OpenCV2 - Narrow Rectangles found using SimpleBlobDetector, but can't extract the angle
I'm trying to get the angle of the middle line in a domino. SimpleBlobDetector can find it, but it gives me an angle value of -1.
Does anyone know why that can be? and how can i fix that still using SimpleBlobDetector? and if SimpleBlobDetector is not an option, what else can i do to find the center and angle of these lines?

```<code>import numpy as np
import cv2
import os
import time
#from matplotlib import pyplot as plt

def main():
    capWebcam = cv2.VideoCapture(0)         # declare a VideoCapture object and associate to webcam, 0 => use 1st webcam

    params = cv2.SimpleBlobDetector_Params()
    params.filterByCircularity = True
    params.minCircularity = 0.73

    params2 = cv2.SimpleBlobDetector_Params()
    params2.filterByInertia = True
    params2.maxInertiaRatio = 0.3

                    # show original resolution
    print "default resolution = " + str(capWebcam.get(cv2.CAP_PROP_FRAME_WIDTH)) + "x" + str(capWebcam.get(cv2.CAP_PROP_FRAME_HEIGHT))

    capWebcam.set(cv2.CAP_PROP_FRAME_WIDTH, 320.0)              # change resolution to 320x240 for faster processing
    capWebcam.set(cv2.CAP_PROP_FRAME_HEIGHT, 240.0)
    capWebcam.set(cv2.CAP_PROP_FPS, 1)

                                            # show updated resolution
    print "updated resolution = " + str(capWebcam.get(cv2.CAP_PROP_FRAME_WIDTH)) + "x" + str(capWebcam.get(cv2.CAP_PROP_FRAME_HEIGHT))

    if capWebcam.isOpened() == False:               # check if VideoCapture object was associated to webcam successfully
        print "error: capWebcam not accessed successfully\n\n"      # if not, print error message to std out
        os.system("pause")                                          # pause until user presses a key so user can see error message
        return                                                      # and exit function (which exits program)
    # end if

    while cv2.waitKey(1) != 27 and capWebcam.isOpened():            # until the Esc key is pressed or webcam connection is lost
        blnFrameReadSuccessfully, img = capWebcam.read()            # read next frame

        if not blnFrameReadSuccessfully or img is None:     # if frame was not read successfully
            print "error: frame not read from webcam\n"             # print error message to std out
            os.system("pause")                                      # pause until user presses a key so user can see error message
            break                                                   # exit while loop (which exits program)

        det = cv2.SimpleBlobDetector_create(params)
        det2 = cv2.SimpleBlobDetector_create(params2)

        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

        time.sleep(0.1)
        keypts = det.detect(gray)
        time.sleep(0.1)
        keypts2 = det2.detect(gray)

        print len(keypts)
        print len(keypts2)

        for l in keypts2:
            print l.pt
            print l.angle

        time.sleep(0.3)
        imgwk = cv2.drawKeypoints(gray, keypts, img,color= (200,0,139),flags=2)

        time.sleep(0.1)
        imgwk2 = cv2.drawKeypoints(img, keypts2, gray,color= (200,0,139),flags=2)

        cv2.namedWindow("img", cv2.WINDOW_AUTOSIZE)           # or use WINDOW_NORMAL to allow window resizing

        cv2.imshow("img", img)

                              # hold windows open until user presses a key

    cv2.destroyAllWindows()

    return

###################################################################################################
if __name__ == "__main__":
    main()
</code>```

答:
I'm not sure if SimpleBlob detector is the best for this, but have you looked at

Detect centre and angle of rectangles in an image using Opencv

It seems quite similar to you question, and seems to do very well at identifying the angle of the rectangles

Body:
I'm trying to get the angle of the middle line in a domino. SimpleBlobDetector can find it, but it gives me an angle value of -1.
Does anyone know why that can be? and how can i fix that still using SimpleBlobDetector? and if SimpleBlobDetector is not an option, what else can i do to find the center and angle of these lines?

import numpy as np
import cv2
import os
import time
#from matplotlib import pyplot as plt

def main():
    capWebcam = cv2.VideoCapture(0)         # declare a VideoCapture object and associate to webcam, 0 => use 1st webcam

    params = cv2.SimpleBlobDetector_Params()
    params.filterByCircularity = True
    params.minCircularity = 0.73

    params2 = cv2.SimpleBlobDetector_Params()
    params2.filterByInertia = True
    params2.maxInertiaRatio = 0.3

                    # show original resolution
    print "default resolution = " + str(capWebcam.get(cv2.CAP_PROP_FRAME_WIDTH)) + "x" + str(capWebcam.get(cv2.CAP_PROP_FRAME_HEIGHT))

    capWebcam.set(cv2.CAP_PROP_FRAME_WIDTH, 320.0)              # change resolution to 320x240 for faster processing
    capWebcam.set(cv2.CAP_PROP_FRAME_HEIGHT, 240.0)
    capWebcam.set(cv2.CAP_PROP_FPS, 1)

                                            # show updated resolution
    print "updated resolution = " + str(capWebcam.get(cv2.CAP_PROP_FRAME_WIDTH)) + "x" + str(capWebcam.get(cv2.CAP_PROP_FRAME_HEIGHT))

    if capWebcam.isOpened() == False:               # check if VideoCapture object was associated to webcam successfully
        print "error: capWebcam not accessed successfully\n\n"      # if not, print error message to std out
        os.system("pause")                                          # pause until user presses a key so user can see error message
        return                                                      # and exit function (which exits program)
    # end if

    while cv2.waitKey(1) != 27 and capWebcam.isOpened():            # until the Esc key is pressed or webcam connection is lost
        blnFrameReadSuccessfully, img = capWebcam.read()            # read next frame

        if not blnFrameReadSuccessfully or img is None:     # if frame was not read successfully
            print "error: frame not read from webcam\n"             # print error message to std out
            os.system("pause")                                      # pause until user presses a key so user can see error message
            break                                                   # exit while loop (which exits program)

        det = cv2.SimpleBlobDetector_create(params)
        det2 = cv2.SimpleBlobDetector_create(params2)

        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

        time.sleep(0.1)
        keypts = det.detect(gray)
        time.sleep(0.1)
        keypts2 = det2.detect(gray)

        print len(keypts)
        print len(keypts2)

        for l in keypts2:
            print l.pt
            print l.angle

        time.sleep(0.3)
        imgwk = cv2.drawKeypoints(gray, keypts, img,color= (200,0,139),flags=2)

        time.sleep(0.1)
        imgwk2 = cv2.drawKeypoints(img, keypts2, gray,color= (200,0,139),flags=2)

        cv2.namedWindow("img", cv2.WINDOW_AUTOSIZE)           # or use WINDOW_NORMAL to allow window resizing

        cv2.imshow("img", img)

                              # hold windows open until user presses a key

    cv2.destroyAllWindows()

    return

###################################################################################################
if __name__ == "__main__":
    main()


问:
Distinct() returns duplicates with a user-defined type
I'm trying to write a Linq query which returns an array of objects, with unique values in their constructors.  For integer types, Distinct returns only one copy of each value, but when I try creating my list of objects, things fall apart.  I suspect it's a problem with the equality operator for my class, but when I set a breakpoint, it's never hit.

Filtering out the duplicate int in a sub-expression solves the problem, and also saves me from constructing objects that will be immediately discarded, but I'm curious why this version doesn't work.

UPDATE: 11:04 PM  Several folks have pointed out that MyType doesn't override GetHashCode().  I'm afraid I oversimplified the example.  The original MyType does indeed implement it.  I've added it below, modified only to put the hash code in a temp variable before returning it.

Running through the debugger, I see that all five invocations of GetHashCode return a different value. And since MyType only inherits from Object, this is presumably the same behavior Object would exhibit.

Would I be correct then to conclude that the hash should instead be based on the contents of Value?  This was my first attempt at overriding operators, and at the time, it didn't appear that GetHashCode needed to be particularly fancy.  (This is the first time one of my equality checks didn't seem to work properly.)

```<code>class Program
{
    static void Main(string[] args)
    {
        int[] list = { 1, 3, 4, 4, 5 };
        int[] list2 =
            (from value in list
             select value).Distinct().ToArray();    // One copy of each value.
        MyType[] distinct =
            (from value in list
             select new MyType(value)).Distinct().ToArray(); // Two objects created with 4.

        Array.ForEach(distinct, value => Console.WriteLine(value));
    }
}

class MyType
{
    public int Value { get; private set; }

    public MyType(int arg)
    {
        Value = arg;
    }

    public override int GetHashCode()
    {
        int retval = base.GetHashCode();
        return retval;
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        MyType rhs = obj as MyType;
        if ((Object)rhs == null)
            return false;

        return this == rhs;
    }

    public static bool operator ==(MyType lhs, MyType rhs)
    {
        bool result;

        if ((Object)lhs != null && (Object)rhs != null)
            result = lhs.Value == rhs.Value;
        else
            result = (Object)lhs == (Object)rhs;

        return result;
    }

    public static bool operator !=(MyType lhs, MyType rhs)
    {
        return !(lhs == rhs);
    }
}
</code>```

答: You need to override GetHashCode() in your class.  GetHashCode must be implemented in tandem with Equals overloads. It is common for code to check for hashcode equality before calling Equals.  That's why your Equals implementation is not getting called.</p>

Body:
I'm trying to write a Linq query which returns an array of objects, with unique values in their constructors.  For integer types, Distinct returns only one copy of each value, but when I try creating my list of objects, things fall apart.  I suspect it's a problem with the equality operator for my class, but when I set a breakpoint, it's never hit.

Filtering out the duplicate int in a sub-expression solves the problem, and also saves me from constructing objects that will be immediately discarded, but I'm curious why this version doesn't work.

UPDATE: 11:04 PM  Several folks have pointed out that MyType doesn't override GetHashCode().  I'm afraid I oversimplified the example.  The original MyType does indeed implement it.  I've added it below, modified only to put the hash code in a temp variable before returning it.

Running through the debugger, I see that all five invocations of GetHashCode return a different value. And since MyType only inherits from Object, this is presumably the same behavior Object would exhibit.

Would I be correct then to conclude that the hash should instead be based on the contents of Value?  This was my first attempt at overriding operators, and at the time, it didn't appear that GetHashCode needed to be particularly fancy.  (This is the first time one of my equality checks didn't seem to work properly.)

class Program
{
    static void Main(string[] args)
    {
        int[] list = { 1, 3, 4, 4, 5 };
        int[] list2 =
            (from value in list
             select value).Distinct().ToArray();    // One copy of each value.
        MyType[] distinct =
            (from value in list
             select new MyType(value)).Distinct().ToArray(); // Two objects created with 4.

        Array.ForEach(distinct, value => Console.WriteLine(value));
    }
}

class MyType
{
    public int Value { get; private set; }

    public MyType(int arg)
    {
        Value = arg;
    }

    public override int GetHashCode()
    {
        int retval = base.GetHashCode();
        return retval;
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        MyType rhs = obj as MyType;
        if ((Object)rhs == null)
            return false;

        return this == rhs;
    }

    public static bool operator ==(MyType lhs, MyType rhs)
    {
        bool result;

        if ((Object)lhs != null && (Object)rhs != null)
            result = lhs.Value == rhs.Value;
        else
            result = (Object)lhs == (Object)rhs;

        return result;
    }

    public static bool operator !=(MyType lhs, MyType rhs)
    {
        return !(lhs == rhs);
    }
}


问:
Identifier expected but integer literal found
I got this problem when writing a recursive function that calculates the number of points where two general functions f1 and f2 are equal(Assuming only Integer values).

```<code>    object X1 {
    def numEqual(f1:Int=>Int,f2:Int=>Int)(a:Int,b:Int):Int=
    if(a>b) 0
    else f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b):0+numEqual(f1,f2)(a+1,b)
</code>```

And this is what compiler says :

X1.scala:5: error: identifier expected but integer literal found.
              f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b) : 0+numEqual(f1,f2)(a+1,b)
                                                                  ^
  one error found.

Thank you!

答: the ? : operator doesn't exist in scala

Body:
I got this problem when writing a recursive function that calculates the number of points where two general functions f1 and f2 are equal(Assuming only Integer values).

    object X1 {
    def numEqual(f1:Int=>Int,f2:Int=>Int)(a:Int,b:Int):Int=
    if(a>b) 0
    else f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b):0+numEqual(f1,f2)(a+1,b)

And this is what compiler says :

X1.scala:5: error: identifier expected but integer literal found.
              f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b) : 0+numEqual(f1,f2)(a+1,b)
                                                                  ^
  one error found.

Thank you!

Body: the ? : operator doesn't exist in scala


问:
accessing services outside kubernetes
I want to access external services/APIs

like calling wikipedia so I need port 80 http://en.wikipedia.org/w/api.php?action=opensearch&search=bee&limit=1&format=json

my app is in a pod inside a container and I exposed port 8000 and binded it 300 in the service type loadbalncer  .

Also accessing external databases hosted outside kubernetes  like mysql so I need  port 3306 how that can be done .

those are both the deployment and service files

https://github.com/hadyrashwan/request-wiki/blob/feature/open-internal-80/wiki-request-deployment.yaml

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: request-wiki-deployment
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: request-wiki
    spec:
      containers:
      - name: request-wiki
        image: hadyrashwan/request-wiki:0.0.4
        imagePullPolicy: Always
        ports:
        - containerPort: 8000
        - containerPort: 80
</code>```

https://github.com/hadyrashwan/request-wiki/blob/feature/open-internal-80/wiki-request-service.yaml

```<code>apiVersion: v1
kind: Service
metadata:
  labels:
    name: request-wiki
  name:  request-wiki-service
spec:
  selector:
    app: request-wiki
  ports:
#  - name: app
  - port: 3000
    protocol: TCP
    targetPort: 8000
#  - name: app
#    protocol: TCP
#    targetPort: 80
  type: LoadBalancer
</code>```

still not using configurations/secrets or tls

I'm using rancher with 2 hosts for kubernetes environment one on GCP and the other on AWS

答:
By default, your pods will use the docker bridge of the node they are located in for egress connections.

Try to test connections from the nodes you are going to use to deploy your pods, if you can connect from the nodes, your pods should be able to do it too. This way you will be able to track any issue related to egress connections easily (check firewall rules, interfaces configured correctly, etc.).

These port options you are configuring in your yamls are for ingress traffic only.

Title: accessing services outside kubernetes

Body:
I want to access external services/APIs

like calling wikipedia so I need port 80 http://en.wikipedia.org/w/api.php?action=opensearch&search=bee&limit=1&format=json

my app is in a pod inside a container and I exposed port 8000 and binded it 300 in the service type loadbalncer  .

Also accessing external databases hosted outside kubernetes  like mysql so I need  port 3306 how that can be done .

those are both the deployment and service files

https://github.com/hadyrashwan/request-wiki/blob/feature/open-internal-80/wiki-request-deployment.yaml

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: request-wiki-deployment
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: request-wiki
    spec:
      containers:
      - name: request-wiki
        image: hadyrashwan/request-wiki:0.0.4
        imagePullPolicy: Always
        ports:
        - containerPort: 8000
        - containerPort: 80

https://github.com/hadyrashwan/request-wiki/blob/feature/open-internal-80/wiki-request-service.yaml

apiVersion: v1
kind: Service
metadata:
  labels:
    name: request-wiki
  name:  request-wiki-service
spec:
  selector:
    app: request-wiki
  ports:
#  - name: app
  - port: 3000
    protocol: TCP
    targetPort: 8000
#  - name: app
#    protocol: TCP
#    targetPort: 80
  type: LoadBalancer

still not using configurations/secrets or tls

I'm using rancher with 2 hosts for kubernetes environment one on GCP and the other on AWS


问:
buttons shifts below when the heading tag is large
I am working on a mobile site and I have a code like below.

```<code><div class="profile-div-wrapper">
   <div class="profile-div">
    <div class="header">
     <img src="assets/images/image.png" alt=""><h3 id="txtDisplayUserName">Surajjjjjjjjjjj Shukla</h3>
     <a href="update_user_profile.html" class="bttn3">Edit Profile</a>
    </div>
   </div>
</div>
</code>```

When the heading is bigger, anchor Edit Profile shifts below.

Here's the fiddle for the same. What can be done to solve this?

Note: Please make sure you make the fiddle of mobile device size to see the problem..

答:
CSS

Try adding this to your existing code:

```<code>.profile-div .header {
  display: flex;
  align-items: center;
}
.profile-div .header a.bttn3 {
  margin-left: auto; //instead of float: right;
  display: flex; //instead of display: block;
  //to vertically & horizontaly align the text inside the button
  align-items: center;
  justify-content: center;
}
</code>```

https://jsfiddle.net/o3Lfprw6/2/

Body:
I am working on a mobile site and I have a code like below.

Surajjjjjjjjjjj Shukla

     Edit Profile

When the heading is bigger, anchor Edit Profile shifts below.

Here's the fiddle for the same. What can be done to solve this?

Note: Please make sure you make the fiddle of mobile device size to see the problem..

Body:
CSS

Try adding this to your existing code:

.profile-div .header {
  display: flex;
  align-items: center;
}
.profile-div .header a.bttn3 {
  margin-left: auto; //instead of float: right;
  display: flex; //instead of display: block;
  //to vertically & horizontaly align the text inside the button
  align-items: center;
  justify-content: center;
}

https://jsfiddle.net/o3Lfprw6/2/


问:
When using GSON, do I have to keep the same POJO at REST-WS consumer & provider end for serialization & deserialization?
I am new to GSON, JSON & hence asking the question:

At the android end, I have to send a booking information to the REST WS on the server. So here is the question:

I have a BookingDTO & I use GSON to serialize it. I send it the REST WS on the server. Now do I also need the same BookingDTO at the server end for GSON deserialize it? (But that would mean tight coupling right?) Do I have to use GSON or can I use normal JSON?

What should be my approach?

答:
You can use Json and parse that content into your objects or directly deal with JsonObject and JsonArray in your methods (server side).

if you want to use objects like BookingDTO you can either re create the classes on android project or reuse those classes from your server side, (or vice versa).

by creating a JAR file that only contains those classes (ex, export model package only) where all POJO classes are located.

using a JAR file makes you maintain a consistency between server and client code, when you add/delete a field, you don't have to change 2 classes, just change in one place and re export the JAR.

now to the tight coupling issue, i don't think there is a one here.
because you are using a list of classes (and you need them in 2 or more separate locations/projects...) this is not coupling, this is reusing same code which should be a good practice.

Coupling is -for example- when Class A is a member of Class B, but it's not when you use Class A and Class B in 2 different systems/components ...


问:
Remove empty elements from an array in Javascript
How do I remove empty elements from an array in JavaScript?

Is there a straightforward way, or do I need to loop through it and remove them manually?

答:
```<code>var data = [null, 1,2,3];
var r = data.filter(function(i){ return i != null; })
</code>```

```<code>console.log(r)
</code>```

[1,2,3]

OwnerDisplayName: DrJokepu

Body:
var data = [null, 1,2,3];
var r = data.filter(function(i){ return i != null; })

console.log(r)

[1,2,3]


问:
Webrequest.GetResponse() works on development machine, not on client machines
I tried using WebRequest.GetResponse() on my developement machine(XP) and it works properly and I can read the response stream from the URL, but the compiled code fails on two client machines(Windows 7) when the URL is identical. The WebException.Status is "The network request is not supported." Why would that occur whan trying to access the same URL? The WebException is fired by the GetResponse method. In the catch clause, the response object and the WebException.Response objects are both null. What can I do to further diagnose the problem?</p>

```<code>WebRequest request = null;
HttpWebResponse response = null;
Stream dataStream = null;
StreamReader reader = null;
String responseFromServer = string.Empty;
string http = string.Empty;
int timeOut = 30000;
string errorMsg = string.Empty;
http = this.URLstring;
bool error = false;

try
{
    request = System.Net.WebRequest.Create(http);
    request.Timeout = timeOut;
    response = (System.Net.HttpWebResponse)request.GetResponse();
}
catch (System.Net.WebException wex)
{
    error = true;
    errorMsg = wex.Message + " " + wex.Status.ToString();

    if (wex.Response != null)
    {
        WebHeaderCollection hdrs = wex.Response.Headers;

        for (int i = 0; i < hdrs.Count; i++)
            errorMsg += Environment.NewLine + hdrs.Keys[i] + ", " + hdrs[i];
    }
}

// Code to read the response stream goes here. it works on development machine.
</code>```

答: It could be a privileges matter. To test that, run the App under Win7 'As Administrator'</p>

Body:
I tried using WebRequest.GetResponse() on my developement machine(XP) and it works properly and I can read the response stream from the URL, but the compiled code fails on two client machines(Windows 7) when the URL is identical. The WebException.Status is "The network request is not supported." Why would that occur whan trying to access the same URL? The WebException is fired by the GetResponse method. In the catch clause, the response object and the WebException.Response objects are both null. What can I do to further diagnose the problem?

WebRequest request = null;
HttpWebResponse response = null;
Stream dataStream = null;
StreamReader reader = null;
String responseFromServer = string.Empty;
string http = string.Empty;
int timeOut = 30000;
string errorMsg = string.Empty;
http = this.URLstring;
bool error = false;

try
{
    request = System.Net.WebRequest.Create(http);
    request.Timeout = timeOut;
    response = (System.Net.HttpWebResponse)request.GetResponse();
}
catch (System.Net.WebException wex)
{
    error = true;
    errorMsg = wex.Message + " " + wex.Status.ToString();

    if (wex.Response != null)
    {
        WebHeaderCollection hdrs = wex.Response.Headers;

        for (int i = 0; i < hdrs.Count; i++)
            errorMsg += Environment.NewLine + hdrs.Keys[i] + ", " + hdrs[i];
    }
}

// Code to read the response stream goes here. it works on development machine.


问:
OpenCPU server requests
I'm developing a web application that should interact with some R scripts and I would very much like to use openCPU. However, I do not see if there is any way I can do other AJAX requests besides calling the R scripts or fetching their results.

I need to send R script descriptions and other stuff which can change so it has to be done in runtime by requests to server.

If anyone would be kind enough to briefly explain if this is possible, I would be very grateful.

答:
I'm assuming when you say update descriptions that you mean the DESCRIPTION file that acts as the definition of the R package itself.  When you change this or the contents of the R script, you will need to publish a new version to Open CPU.  A few notes from my experience, which seems similar to yours:

I have had some trouble having scripts running inside of OpenCPU install packages that are in CRAN but not available in the OpenCPU package list.  OpenCPU can pull packages in from Github using the install_github function found in the devtools package.  You might have to manually install in your R script using install.packages if your script is using an R function that the public OpenCPU doesn't have.  This might be helpful if calling library or install.packages by itself doesn't work.

```<code>library('devtools')

install.packages("BIOMASS", repos = "https://cran.opencpu.org", method = "libcurl")
library("BIOMASS")
</code>```

The list of installed packages on the public OpenCPU is here  If you are using another package that is available on CRAN, you will need to add it as a dependency in your Imports section in the R package DESCRIPTION file.  You can also use namespacing to avoid having to use PACKAGENAME::FUNCTIONNAME in your script.

If you publish to the public OpenCPU, you can only update your package once every 24 hours.

The pipeline I've found helpful is to develop my package, write some test code locally that uses it, and once I'm fairly confident, push it to my github repository.  Here I have a webhook setup to publish the new package to the public OpenCPU instance.  Depending on how you have your development environment setup, you might publish it manually instead.  For example, if you are hosting your own OpenCPU instance, it would make more sense to publish it to your instance instead of the public one.

The relevant section in the OpenCPU API documentation is where it talks about the R Package API.  There's also documentation in the server manual about how to install packages if you are hosting your own OpenCPU.

If you happen to be using Meteor, my experience was that it was best to make direct calls to the ReSTful / HTTP API in OpenCPU directly.  The Javascript client package didn't work for me in Meteor and the HTTP API works just fine.

Title: OpenCPU server requests

Body:
I'm assuming when you say update descriptions that you mean the DESCRIPTION file that acts as the definition of the R package itself.  When you change this or the contents of the R script, you will need to publish a new version to Open CPU.  A few notes from my experience, which seems similar to yours:

I have had some trouble having scripts running inside of OpenCPU install packages that are in CRAN but not available in the OpenCPU package list.  OpenCPU can pull packages in from Github using the install_github function found in the devtools package.  You might have to manually install in your R script using install.packages if your script is using an R function that the public OpenCPU doesn't have.  This might be helpful if calling library or install.packages by itself doesn't work.

library('devtools')

install.packages("BIOMASS", repos = "https://cran.opencpu.org", method = "libcurl")
library("BIOMASS")

The list of installed packages on the public OpenCPU is here  If you are using another package that is available on CRAN, you will need to add it as a dependency in your Imports section in the R package DESCRIPTION file.  You can also use namespacing to avoid having to use PACKAGENAME::FUNCTIONNAME in your script.

If you publish to the public OpenCPU, you can only update your package once every 24 hours.

The pipeline I've found helpful is to develop my package, write some test code locally that uses it, and once I'm fairly confident, push it to my github repository.  Here I have a webhook setup to publish the new package to the public OpenCPU instance.  Depending on how you have your development environment setup, you might publish it manually instead.  For example, if you are hosting your own OpenCPU instance, it would make more sense to publish it to your instance instead of the public one.

The relevant section in the OpenCPU API documentation is where it talks about the R Package API.  There's also documentation in the server manual about how to install packages if you are hosting your own OpenCPU.

If you happen to be using Meteor, my experience was that it was best to make direct calls to the ReSTful / HTTP API in OpenCPU directly.  The Javascript client package didn't work for me in Meteor and the HTTP API works just fine.


问:
How to make a toggle cell in GTK TreeView editable by using Glade?
I'm using Glade 3.20 but i don't known how to make a toggle column editable. I do not see any options.
screenshots

Please help me!

答:
Look at this CellRendererToggle usage example  (in python).

The source (in case the link breaks someday):

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class CellRendererToggleWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="CellRendererToggle Example")

        self.set_default_size(200, 200)

        self.liststore = Gtk.ListStore(str, bool, bool)
        self.liststore.append(["Debian", False, True])
        self.liststore.append(["OpenSuse", True, False])
        self.liststore.append(["Fedora", False, False])

        treeview = Gtk.TreeView(model=self.liststore)

        renderer_text = Gtk.CellRendererText()
        column_text = Gtk.TreeViewColumn("Text", renderer_text, text=0)
        treeview.append_column(column_text)

        renderer_toggle = Gtk.CellRendererToggle()
        renderer_toggle.connect("toggled", self.on_cell_toggled)

        column_toggle = Gtk.TreeViewColumn("Toggle", renderer_toggle, active=1)
        treeview.append_column(column_toggle)

        renderer_radio = Gtk.CellRendererToggle()
        renderer_radio.set_radio(True)
        renderer_radio.connect("toggled", self.on_cell_radio_toggled)

        column_radio = Gtk.TreeViewColumn("Radio", renderer_radio, active=2)
        treeview.append_column(column_radio)

        self.add(treeview)

    def on_cell_toggled(self, widget, path):
        self.liststore[path][1] = not self.liststore[path][1]

    def on_cell_radio_toggled(self, widget, path):
        selected_path = Gtk.TreePath(path)
        for row in self.liststore:
            row[2] = (row.path == selected_path)

win = CellRendererToggleWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
```


问:
Firebase security - let each user to write himself
I have the following structure of 'neighbors' in firebase:

```<code>neighbors: {
user100:{
    user200:{
        from:'1.2'
    },
    user300:{
        from:'4.2'
    },
    user400:{
        from:'2.4'
    }
},
user700:{
    user200:{
        from:'8.7'
    },
    user500:{
        from:'10.3'
    }
}

}
</code>```

support user100, user200 are auth-ids.
I want to let each user to write only him-self, but to do it for every other user he want.
For example, I want to let user200 to write that he is neighbor of user500, but I don't want to let him write that other user (like user 800) is neighbor of someone.

I tried hard but didn't success.
By default I tried this following solution but still not work!!!
the solution was to change the structure to look like:

```<code>neighbors:  {
user100:{
    user200:{
        from:'1.2',
        neighbor:'user200'
    },
    user300:{
        from:'4.2',
        neighbor:'user300'
    },
    user400:{
        from:'2.4',
        neighbor:'user400'
    }
},
user700:{
    user200:{
        from:'8.7',
        neighbor:'user200'
    },
    user500:{
        from:'10.3',
        neighbor:'user500'
    }
}

  }
</code>```

And the rule is:

```<code> neighbors:{
    ".write":"newData.child('neighbor').val() == auth.uid
 }
</code>```

But I get permission-denied!

Any solution?

答:
Try this:</p>

```<code>    "neighbors":{
    "$user_id":{
        ".write":"newData.child('neighbor').val() == auth.uid"
    }
}
</code>```

Body:
I have the following structure of 'neighbors' in firebase:

neighbors: {
user100:{
    user200:{
        from:'1.2'
    },
    user300:{
        from:'4.2'
    },
    user400:{
        from:'2.4'
    }
},
user700:{
    user200:{
        from:'8.7'
    },
    user500:{
        from:'10.3'
    }
}

}

support user100, user200 are auth-ids.
I want to let each user to write only him-self, but to do it for every other user he want.
For example, I want to let user200 to write that he is neighbor of user500, but I don't want to let him write that other user (like user 800) is neighbor of someone.

I tried hard but didn't success.
By default I tried this following solution but still not work!!!
the solution was to change the structure to look like:

neighbors:  {
user100:{
    user200:{
        from:'1.2',
        neighbor:'user200'
    },
    user300:{
        from:'4.2',
        neighbor:'user300'
    },
    user400:{
        from:'2.4',
        neighbor:'user400'
    }
},
user700:{
    user200:{
        from:'8.7',
        neighbor:'user200'
    },
    user500:{
        from:'10.3',
        neighbor:'user500'
    }
}

  }

And the rule is:

 neighbors:{
    ".write":"newData.child('neighbor').val() == auth.uid
 }

But I get permission-denied!

Any solution?

Body:
Try this:

    "neighbors":{
    "$user_id":{
        ".write":"newData.child('neighbor').val() == auth.uid"
    }
}