问:
Firebase Android : How to get list inside specific child?
I'm trying to retrieve inner list of specific child. Please refer following structure.

If I want to retrieve "servicesArrayList" for "recipient" where "billNo" is "135", What query I should be writing so that I can pass that query to FirebaseRecyclerAdapter (firebase -ui)

FirebaseRecyclerAdapter is for servicesArrayList for specific recipient.

```<code>    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    String uid = user.getUid();

    Query query = FirebaseDatabase.getInstance()
            .getReference(RECIPIENT_NODE)
            .child(uid)
            .child("servicesArrayList")
            .orderByChild ?

recipient // parent Node

 2R1Q8qKEPHXFU1OiMq5TyxHBaZa2 // uId

   -KgJhMAWADwownv5tck6  // push Id
   -KgJhMAWADwownv5tck6
   -KgJoD77HQK-yACD_EuB
   -KgJoRXVUP_-Z0gLhIWy
   -KgJob82t47PvTjfTtig
   -KgK-N_Av_2kmmQS0Ulx

   -KgNu-fVWwFDLnRENj_b // Recipient Data
        billNo: 135
        billingMonth: "July 2017"
        childGender: "Ms."
        childName: "xyz"
        date: "29/03/2017"
        fineAmount: 0
        paymentStatus: "UNPAID"
        pushId: "-KgNu-fVWwFDLnRENj_b"
        receiptUrl:"https://firebasestorage.googleapis.com/v0/b/ngf..."
        recipientEmail: "abc@gmail.com"
        recipientName: "Abc C."
        servicesArrayList
                 -0
                    -amount: 1000
                    -charges: "1000"
                    -noOfSessions: 1
                    -serviceType: "Speech And Language Assessment"

        total: 1000
        vat: 0
</code>```

答:
If you knnow the uid and the push id, then this should do it:

```<code>Query query = FirebaseDatabase.getInstance().getReference(RECIPIENT_NODE)
    .child(uid).child(pushId).child("servicesArrayList");
</code>```

Hope this helps

Body:
I'm trying to retrieve inner list of specific child. Please refer following structure.

If I want to retrieve "servicesArrayList" for "recipient" where "billNo" is "135", What query I should be writing so that I can pass that query to FirebaseRecyclerAdapter (firebase -ui)

FirebaseRecyclerAdapter is for servicesArrayList for specific recipient.

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    String uid = user.getUid();

    Query query = FirebaseDatabase.getInstance()
            .getReference(RECIPIENT_NODE)
            .child(uid)
            .child("servicesArrayList")
            .orderByChild ?

recipient // parent Node

 2R1Q8qKEPHXFU1OiMq5TyxHBaZa2 // uId

   -KgJhMAWADwownv5tck6  // push Id
   -KgJhMAWADwownv5tck6
   -KgJoD77HQK-yACD_EuB
   -KgJoRXVUP_-Z0gLhIWy
   -KgJob82t47PvTjfTtig
   -KgK-N_Av_2kmmQS0Ulx

   -KgNu-fVWwFDLnRENj_b // Recipient Data
        billNo: 135
        billingMonth: "July 2017"
        childGender: "Ms."
        childName: "xyz"
        date: "29/03/2017"
        fineAmount: 0
        paymentStatus: "UNPAID"
        pushId: "-KgNu-fVWwFDLnRENj_b"
        receiptUrl:"https://firebasestorage.googleapis.com/v0/b/ngf..."
        recipientEmail: "abc@gmail.com"
        recipientName: "Abc C."
        servicesArrayList
                 -0
                    -amount: 1000
                    -charges: "1000"
                    -noOfSessions: 1
                    -serviceType: "Speech And Language Assessment"

        total: 1000
        vat: 0

Body:
If you knnow the uid and the push id, then this should do it:

Query query = FirebaseDatabase.getInstance().getReference(RECIPIENT_NODE)
    .child(uid).child(pushId).child("servicesArrayList");

Hope this helps


来源: stackexchange

问:
android 7.0 Notification icon appearing white square
I am using the below snippet to generate notifications in my android app.

```<code>private void sendNotification(String contentText, String message) {

    Intent resultIntent = new Intent(this, MainActivity.class);
    resultIntent.putExtra("clear","clear");
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
     Intent.FLAG_ACTIVITY_CLEAR_TASK);

   PendingIntent piResult = PendingIntent.getActivity(this, 0, resultIntent,0);

    NotificationCompat.Builder builder=new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setColor(ContextCompat.getColor(getApplicationContext(),R.color.red))
            .setContentTitle("title")
            .setContentText(message)
            .setAutoCancel(true)
            .setLargeIcon(BitmapFactory.decodeResource(getResources()
            ,R.drawable.notification))
            .setContentIntent(piResult);

    NotificationCompat.InboxStyle notification = new NotificationCompat.InboxStyle(builder);

    int i;
    for(i=0; i<messageList.size();i++){
        notification.addLine(messageList.get(i));
    }
    notification.setBigContentTitle("title");
    notification.setSummaryText(contentText);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID,notification.build());
}
</code>```

It works in android 5 and 6 but for android nougat it is not working

答:
According to this blog here

It says that

You’ll note that the icons are not present in the new notifications; instead more room is provided for the labels themselves in the constrained space of the notification shade. However, the notification action icons are still required and continue to be used on older versions of Android and on devices such as Android Wear.

If you’ve been building your notification with NotificationCompat.Builder and the standard styles available to you there, you’ll get the new look and feel by default with no code changes required.

ContentLicense: CC BY-SA 3.0

Body:
I am using the below snippet to generate notifications in my android app.

private void sendNotification(String contentText, String message) {

    Intent resultIntent = new Intent(this, MainActivity.class);
    resultIntent.putExtra("clear","clear");
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
     Intent.FLAG_ACTIVITY_CLEAR_TASK);

   PendingIntent piResult = PendingIntent.getActivity(this, 0, resultIntent,0);

    NotificationCompat.Builder builder=new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setColor(ContextCompat.getColor(getApplicationContext(),R.color.red))
            .setContentTitle("title")
            .setContentText(message)
            .setAutoCancel(true)
            .setLargeIcon(BitmapFactory.decodeResource(getResources()
            ,R.drawable.notification))
            .setContentIntent(piResult);

    NotificationCompat.InboxStyle notification = new NotificationCompat.InboxStyle(builder);

    int i;
    for(i=0; i<messageList.size();i++){
        notification.addLine(messageList.get(i));
    }
    notification.setBigContentTitle("title");
    notification.setSummaryText(contentText);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID,notification.build());
}

It works in android 5 and 6 but for android nougat it is not working


问:
How to calculate difference between tables in MySQL?
What is a good way to calculate difference (in a sense what should be added and deleted from one table to get another) between tables in MySQL?</p>

答:
```<code>SELECT DISTINCT id FROM a WHERE NOT EXISTS (SELECT * FROM b WHERE a.id = b.id);
SELECT DISTINCT id FROM b WHERE NOT EXISTS (SELECT * FROM a WHERE a.id = b.id);
</code>```

OwnerDisplayName: Vadim

ContentLicense: CC BY-SA 2.5


问:
Active Record (Rails) MySQL Secure Connection
Now, I haven't been able to find any good resources on this subject so I'll ask my question here and see if anyone has any suggestions/recommendations.

I will be deploying a Ruby on Rails application soon (Active Record ORM), and my database (MySQL or PostgreSQL) will be located at an external location (outside of 127.0.0.1 range).

I am able to connect to the external MySQL database, simply by unbinding the address in the /etc/mysql/my.conf and adding a user that takes connections from external locations. However, since the data is being transferred from my application server to my MySQL server, how (in)secure is this?

Do I need to do some form of encryption? Does Active Record do anything in the background to protect data from being hijacked (or whatever you call it) during the transfer? Or is my data secure enough by default with MySQL and/or PostgreSQL when working with databases at external locations?

So in short: Is there anything (extra) I should be doing when my MySQL or PostgreSQL database is located at an external location, rather than when it's in localhost range?

Any suggestions, pointers, recommendations and resources would be much appreciated!

Thanks!

答:
It strongly depends on how the application server and the database server are connected.

If the traffic is routed in the wild (i.e. you dont have a virtual private network connecting your servers), you can set up an SSL connection between your Rails app and MySQL:

MySQL supports secure (encrypted) connections between MySQL clients and the server using the Secure Sockets Layer (SSL) protocol. Reference.

ActiveRecord has options for SSL security (:sslkey and others in database.yml). Reference

Restricting external connection to MySQL from a given IP for a low privileged user still applies.


问:
Photo/Document Upload in Android Webview
I'm working on a wrapper application for Android and need to connect to the camera/photo gallery (so the user can upload a picture of themselves for example). I've found a number of posts on the subject, including Upload an Image from camera or gallery in WebView and Upload camera photo and filechooser from webview INPUT field, but the code that I've modeled after these solutions isn't working. I put a print statement inside the openFileChooser function, and it isn't being triggered when the add photo/document Javascript link is hit in my webview. Any suggestions would be appreciated, I'm including my code below:</p>

```<code> private Uri mCapturedImageURI = null;

//make HTML upload button work in Webview
private ValueCallback<Uri> mUploadMessage;
private String filePath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_log_in_page);
    Intent currentIntent = getIntent();
    String action = currentIntent.getAction();
    String url;

    //check for permissions
    boolean camera = checkCameraPermissions();
    boolean location = checkLocationPermissions();
    boolean photos = checkPhotoPermissions();

    if (!location){
        ActivityCompat.requestPermissions(this,
                new String[] {"android.permission.ACCESS_FINE_LOCATION"}, REQUEST_LOCATION);
        requested_location = true;
    }

    if (!camera ) {
        ActivityCompat.requestPermissions(this,
                new String[] {"android.permission.CAMERA"}, REQUEST_CAMERA);
        requested_camera = true;
    }

    if (!photos) {
        ActivityCompat.requestPermissions(this,
                new String[] {"android.permission.READ_EXTERNAL_STORAGE"}, REQUEST_PHOTOS);
        requested_photos = true;
    }

    url =  Constants.login_page;

    //start up the webview, initiate navigation client
    myWebView = (WebView) findViewById(R.id.webview);
    if (myWebView != null) {
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setDomStorageEnabled(true);
        myWebView.getSettings().setAllowFileAccess(true);
        myWebView.getSettings().setAllowFileAccessFromFileURLs(true);
        myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        myWebView.getSettings().setSupportMultipleWindows(true);
        myWebView.getSettings().setGeolocationEnabled(true);
        myWebView.setWebChromeClient(new WebChromeClient() {

            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }

            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType){
                this.openFileChooser(uploadMsg);
            }

            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
                this.openFileChooser(uploadMsg);
            }

            private Uri imageUri;

            public void openFileChooser(ValueCallback<Uri> uploadMsg ) {
                // Update message
                mUploadMessage = uploadMsg;

                System.out.println("we are here");

                File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "my_app");
                filePath = imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg";
                File file = new File(filePath);

                Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                LogInPage.this.startActivityForResult(captureIntent, REQUEST_PHOTOS);
            }

            });
        //myWebView.addJavascriptInterface(new MyJavascriptInterface(this), "Android");
        myWebView.loadUrl(url);
        myWebView.setWebViewClient(new NavigationClient());
    }
}

   @Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

    if ((requestCode == SELECT_PHOTO) ||(requestCode == REQUEST_CAMERA)) {
        if (null == this.mUploadMessage || (resultCode != RESULT_OK && !new File(filePath).exists())) {
            this.mUploadMessage.onReceiveValue(null);
        } else {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, this.filePath);
            this.mUploadMessage.onReceiveValue(this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values));
        }
        this.mUploadMessage = null;
    }
}
</code>```

答:
It looks like you are opening a startActivityForResult with result code REQUEST_PHOTOS, but in onActivityResult you check for codes REQUEST_PHOTOS or REQUEST_CAMERA. So you are never going to process result.
Change your onActivityResult with:

```<code>@Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if ((requestCode == REQUEST_PHOTOS) ) {
            if (null == this.mUploadMessage || (resultCode != RESULT_OK && !new File(filePath).exists())) {
                this.mUploadMessage.onReceiveValue(null);
            } else {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, this.filePath);
                this.mUploadMessage.onReceiveValue(getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values));
            }
            this.mUploadMessage = null;
        }
    }
</code>```

Body:
I'm working on a wrapper application for Android and need to connect to the camera/photo gallery (so the user can upload a picture of themselves for example). I've found a number of posts on the subject, including Upload an Image from camera or gallery in WebView and Upload camera photo and filechooser from webview INPUT field, but the code that I've modeled after these solutions isn't working. I put a print statement inside the openFileChooser function, and it isn't being triggered when the add photo/document Javascript link is hit in my webview. Any suggestions would be appreciated, I'm including my code below:

 private Uri mCapturedImageURI = null;

//make HTML upload button work in Webview
private ValueCallback<Uri> mUploadMessage;
private String filePath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_log_in_page);
    Intent currentIntent = getIntent();
    String action = currentIntent.getAction();
    String url;

    //check for permissions
    boolean camera = checkCameraPermissions();
    boolean location = checkLocationPermissions();
    boolean photos = checkPhotoPermissions();

    if (!location){
        ActivityCompat.requestPermissions(this,
                new String[] {"android.permission.ACCESS_FINE_LOCATION"}, REQUEST_LOCATION);
        requested_location = true;
    }

    if (!camera ) {
        ActivityCompat.requestPermissions(this,
                new String[] {"android.permission.CAMERA"}, REQUEST_CAMERA);
        requested_camera = true;
    }

    if (!photos) {
        ActivityCompat.requestPermissions(this,
                new String[] {"android.permission.READ_EXTERNAL_STORAGE"}, REQUEST_PHOTOS);
        requested_photos = true;
    }

    url =  Constants.login_page;

    //start up the webview, initiate navigation client
    myWebView = (WebView) findViewById(R.id.webview);
    if (myWebView != null) {
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setDomStorageEnabled(true);
        myWebView.getSettings().setAllowFileAccess(true);
        myWebView.getSettings().setAllowFileAccessFromFileURLs(true);
        myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        myWebView.getSettings().setSupportMultipleWindows(true);
        myWebView.getSettings().setGeolocationEnabled(true);
        myWebView.setWebChromeClient(new WebChromeClient() {

            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }

            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType){
                this.openFileChooser(uploadMsg);
            }

            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
                this.openFileChooser(uploadMsg);
            }

            private Uri imageUri;

            public void openFileChooser(ValueCallback<Uri> uploadMsg ) {
                // Update message
                mUploadMessage = uploadMsg;

                System.out.println("we are here");

                File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "my_app");
                filePath = imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg";
                File file = new File(filePath);

                Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                LogInPage.this.startActivityForResult(captureIntent, REQUEST_PHOTOS);
            }

            });
        //myWebView.addJavascriptInterface(new MyJavascriptInterface(this), "Android");
        myWebView.loadUrl(url);
        myWebView.setWebViewClient(new NavigationClient());
    }
}

   @Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

    if ((requestCode == SELECT_PHOTO) ||(requestCode == REQUEST_CAMERA)) {
        if (null == this.mUploadMessage || (resultCode != RESULT_OK && !new File(filePath).exists())) {
            this.mUploadMessage.onReceiveValue(null);
        } else {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, this.filePath);
            this.mUploadMessage.onReceiveValue(this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values));
        }
        this.mUploadMessage = null;
    }
}

Body:
It looks like you are opening a startActivityForResult with result code REQUEST_PHOTOS, but in onActivityResult you check for codes REQUEST_PHOTOS or REQUEST_CAMERA. So you are never going to process result.
Change your onActivityResult with:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if ((requestCode == REQUEST_PHOTOS) ) {
            if (null == this.mUploadMessage || (resultCode != RESULT_OK && !new File(filePath).exists())) {
                this.mUploadMessage.onReceiveValue(null);
            } else {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, this.filePath);
                this.mUploadMessage.onReceiveValue(getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values));
            }
            this.mUploadMessage = null;
        }
    }


问:
RxJava - counter with x of y
How can I do this? I came up with following, it allows me to calculate the x in x of y, but how can I improve that to calculate the y as well?

```<code>Observable<LoadedPhoneContact> phoneContacts = getPhoneContacts()
        .flatMapObservable(contacts -> Observable.fromIterable(contacts));

Observable<Integer> phoneContactsCounter = phoneContacts
        .cache()
        .map(contact -> 1)
        .reduce((c1, c2) -> c2 + c2)
        .toObservable();

mSimils = phoneContacts
        .zipWith(phoneContactsCounter, (contact, index) -> new Pair<>(contact, index))
        .doOnNext(data ->  {
            L.d("x / y = %d / %d", data.second, ?);
        })
        .map(data -> SimilUtil.calcSimils(data))
        ;
</code>```

Any ideas or better/alternative solutions?

I want to be able to see the progress in a format like "x of y items processed"...

I could zip with a third observable that just emits the count, but is this the correct way?

答:
I definitely recommend not to have side effects inside Rx callbacks, as this can easily cause thread synchronization issues (which you're avoiding by using Rx in the first place).

Instead, you can use rxjava-extras which has .mapWithIndex(...) -operator.

Title: RxJava - counter with x of y

Body:
How can I do this? I came up with following, it allows me to calculate the x in x of y, but how can I improve that to calculate the y as well?

Observable<LoadedPhoneContact> phoneContacts = getPhoneContacts()
        .flatMapObservable(contacts -> Observable.fromIterable(contacts));

Observable<Integer> phoneContactsCounter = phoneContacts
        .cache()
        .map(contact -> 1)
        .reduce((c1, c2) -> c2 + c2)
        .toObservable();

mSimils = phoneContacts
        .zipWith(phoneContactsCounter, (contact, index) -> new Pair<>(contact, index))
        .doOnNext(data ->  {
            L.d("x / y = %d / %d", data.second, ?);
        })
        .map(data -> SimilUtil.calcSimils(data))
        ;

Any ideas or better/alternative solutions?

I want to be able to see the progress in a format like "x of y items processed"...

I could zip with a third observable that just emits the count, but is this the correct way?


问:
Posting an (Image-) URL of a file from Fileserver and Associated Data as JSON via HTTP
I have developed a Node.js & Express Application that sends data as JSON.

Part of the application requires to send the Location of image files stored on different file servers (Windows Server 2012).

Currently the Node.js Application are delivering the file-location in a format like

```<code>[{"MulPfadS":"M:\\Originalbilder\\fos\\EID","MulDateiS":"EID00124","MulExtentS":"jpg","ObjId":178983}]
</code>```

Now the customer wants the location of the file in a format like

```<code>http://10.9.0.11/path_to_image
</code>```

There are no Webserver running on the file servers and the customer doesn't want to copy the image files from the file servers to the same server where the node.js application is running.

Is there a way to resolve this issue? And if so how?

答: You could convert the image as base64 encoded string and transfer across.</p>

Body:
I have developed a Node.js & Express Application that sends data as JSON.

Part of the application requires to send the Location of image files stored on different file servers (Windows Server 2012).

Currently the Node.js Application are delivering the file-location in a format like

[{"MulPfadS":"M:\\Originalbilder\\fos\\EID","MulDateiS":"EID00124","MulExtentS":"jpg","ObjId":178983}]

Now the customer wants the location of the file in a format like

http://10.9.0.11/path_to_image

There are no Webserver running on the file servers and the customer doesn't want to copy the image files from the file servers to the same server where the node.js application is running.

Is there a way to resolve this issue? And if so how?


问:
How to modify and add words sequentially in a list - Python
I don't know if this is possible as I'm a newbie to Python, but I wanted to create a list that has a sequential order to it. So I have two lists as follows:

```<code>stock_list = ['MSFT', 'YHOO']
ret = [0, 1, 2, 3]

returns = ["ret{}".format(*ret) for ret in enumerate(ret)]
</code>```

returns

```<code>['ret0', 'ret1', 'ret2', 'ret3']
</code>```

From the above lists of returns and stock_list, I can create the following:

```<code>for index, ret_stock in enumerate(returns):
    returns[index] += "_MSFT"
returns
</code>```

Output:

```<code>['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT']
</code>```

Ideally, what I'm trying to get is this using the stock_list for both tickers, MSFT and YHOO:

```<code>  ['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT',
       'ret0_YHOO', 'ret1_YHOO', 'ret2_YHOO', 'ret3_YHOO']
</code>```

So, I could do the previous method with enumerate, but that would become increasingly time consuming if, say instead of just two tickers, MSFT and YHOO, I had 100.

By creating a list of say, 100 or more tickers, and applying it to a list of returns such as this one already shown.

```<code>['ret0', 'ret1', 'ret2', 'ret3']
</code>```

Is it possible? Maybe I'm asking the wrong question or approaching from the wrong angle.

答:
Put your current code in another loop. You can even create it within the comprehension:</p>

```<code>>>> stock_list = ['MSFT', 'YHOO']
>>> ret = [0, 1, 2, 3]
>>> returns = ["ret{}_{}".format(r, stk) for stk in stock_list for r in ret]
>>> returns
['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT', 'ret0_YHOO', 'ret1_YHOO', 'ret2_YHOO', 'ret3_YHOO']
</code>```

Body:
I don't know if this is possible as I'm a newbie to Python, but I wanted to create a list that has a sequential order to it. So I have two lists as follows:

stock_list = ['MSFT', 'YHOO']
ret = [0, 1, 2, 3]

returns = ["ret{}".format(*ret) for ret in enumerate(ret)]

returns

['ret0', 'ret1', 'ret2', 'ret3']

From the above lists of returns and stock_list, I can create the following:

for index, ret_stock in enumerate(returns):
    returns[index] += "_MSFT"
returns

Output:

['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT']

Ideally, what I'm trying to get is this using the stock_list for both tickers, MSFT and YHOO:

  ['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT',
       'ret0_YHOO', 'ret1_YHOO', 'ret2_YHOO', 'ret3_YHOO']

So, I could do the previous method with enumerate, but that would become increasingly time consuming if, say instead of just two tickers, MSFT and YHOO, I had 100.

By creating a list of say, 100 or more tickers, and applying it to a list of returns such as this one already shown.

['ret0', 'ret1', 'ret2', 'ret3']

Is it possible? Maybe I'm asking the wrong question or approaching from the wrong angle.

Body:
Put your current code in another loop. You can even create it within the comprehension:

>>> stock_list = ['MSFT', 'YHOO']
>>> ret = [0, 1, 2, 3]
>>> returns = ["ret{}_{}".format(r, stk) for stk in stock_list for r in ret]
>>> returns
['ret0_MSFT', 'ret1_MSFT', 'ret2_MSFT', 'ret3_MSFT', 'ret0_YHOO', 'ret1_YHOO', 'ret2_YHOO', 'ret3_YHOO']


问:
Load 1000 records with Image to collection view CloudKit Swift
I have a CloudKit database with over 1000 record (image.jpg ~ 1.0 MB in image Asset)

Should I load Image in CollectionViewCell?

My code is:

```<code>func loadData(){
        self.loading.startAnimating()
        let query = CKQuery(recordType: self.recordType, predicate: predicate)
        query.sortDescriptors = [NSSortDescriptor(key: "productID", ascending: true)]
        operation.query = query
        operation.resultsLimit = 1000
        operation.qualityOfService = .userInteractive
        operation.recordFetchedBlock = { (record) in
            self.items.append(record)
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
        operation.queryCompletionBlock = { (queryCursor, error) in
            DispatchQueue.main.async {
                self.loading.stopAnimating()
            }
        }
        myData.add(operation)
    }
</code>```

My CollectionViewCell:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "productCell", for: indexPath)
        let img = UIImageView(frame: CGRect(x: 1, y: 1, width: w - 2, height: h - 2))
        img.contentMode = .scaleAspectFill
        img.image = UIImage(contentsOfFile: (self.items[indexPath.item]["productImage"] as! CKAsset).fileURL.path)
        cell.contentView.addSubview(img)

        return cell
    }
</code>```

答:
Instead of fetch 1000 records one time you should fetch a small set each time user scrolls on your UICollectionView.

With this you obtain better performance and recovers only the images that you need.

To do this you must set the resultsLimit property to a number that fits with images quantity that shows your CollectionView plus 5 or 6

Each time user reach the end of your CollectionView you should perform another fetch passing the CKQueryCursor as a parameter.

Body:
I have a CloudKit database with over 1000 record (image.jpg ~ 1.0 MB in image Asset)

Should I load Image in CollectionViewCell?

My code is:

func loadData(){
        self.loading.startAnimating()
        let query = CKQuery(recordType: self.recordType, predicate: predicate)
        query.sortDescriptors = [NSSortDescriptor(key: "productID", ascending: true)]
        operation.query = query
        operation.resultsLimit = 1000
        operation.qualityOfService = .userInteractive
        operation.recordFetchedBlock = { (record) in
            self.items.append(record)
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
        operation.queryCompletionBlock = { (queryCursor, error) in
            DispatchQueue.main.async {
                self.loading.stopAnimating()
            }
        }
        myData.add(operation)
    }

My CollectionViewCell:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "productCell", for: indexPath)
        let img = UIImageView(frame: CGRect(x: 1, y: 1, width: w - 2, height: h - 2))
        img.contentMode = .scaleAspectFill
        img.image = UIImage(contentsOfFile: (self.items[indexPath.item]["productImage"] as! CKAsset).fileURL.path)
        cell.contentView.addSubview(img)

        return cell
    }


问:
Loop code with different worksheet names
I am running below code. The worksheet named "fast" contains names such as cycle, run, walk, jog, etc. The code currently searches for the word "cycle" in a particular row and if found it copies the whole column and pastes it in a worksheet called "cycle". At the moment I am just repeating the script and changing "Cycle" for names like "run" "walk" etc. Is there I can make this shorter and more efficient by not simply just repeating the same script over and over. </p>

```<code>Sub Cycle()

Dim C As Range
Dim col As Long, lastCol As Long

With Worksheets("fast")
    lastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
    col = 1
    For Each C In .Range(.Cells(2, 1), .Cells(2, lastCol))
        If C.value = "Cycle" Then
            C.EntireColumn.Copy Destination:=Sheets("Cycle").Columns(col)
            C.EntireColumn.Copy
            Sheets("Cycle").Columns(col).PasteSpecial xlPasteValues
            col = col + 1
        End If
    Next C
End With
Worksheets("Cycle").Activate

End Sub
</code>```

答:
Try the code below, let me know if that's what you meant:</p>

```<code>Option Explicit

Sub Cycle()

Dim C               As Range
Dim StringsArr      As Variant
Dim col As Long, lastCol As Long

StringsArr = Array("cycle", "run", "walk", "jog")

With Worksheets("fast")
    lastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
    For Each C In .Range(.Cells(2, 1), .Cells(2, lastCol))
        ' check per cell if value is one of the values in StringsArr array
        If Not IsError(Application.Match(C.value, StringsArr, 0)) Then
            col = Sheets(C.value).Cells(2, Sheets(C.value).Columns.Count).End(xlToLeft).Column + 1 ' find first empty column in relevant sheet
            C.EntireColumn.Copy
            Sheets(C.value).Columns(col).PasteSpecial xlPasteValues
        End If
    Next C
End With

End Sub
</code>```

Body:
I am running below code. The worksheet named "fast" contains names such as cycle, run, walk, jog, etc. The code currently searches for the word "cycle" in a particular row and if found it copies the whole column and pastes it in a worksheet called "cycle". At the moment I am just repeating the script and changing "Cycle" for names like "run" "walk" etc. Is there I can make this shorter and more efficient by not simply just repeating the same script over and over.

Sub Cycle()

Dim C As Range
Dim col As Long, lastCol As Long

With Worksheets("fast")
    lastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
    col = 1
    For Each C In .Range(.Cells(2, 1), .Cells(2, lastCol))
        If C.value = "Cycle" Then
            C.EntireColumn.Copy Destination:=Sheets("Cycle").Columns(col)
            C.EntireColumn.Copy
            Sheets("Cycle").Columns(col).PasteSpecial xlPasteValues
            col = col + 1
        End If
    Next C
End With
Worksheets("Cycle").Activate

End Sub

Body:
Try the code below, let me know if that's what you meant:

Option Explicit

Sub Cycle()

Dim C               As Range
Dim StringsArr      As Variant
Dim col As Long, lastCol As Long

StringsArr = Array("cycle", "run", "walk", "jog")

With Worksheets("fast")
    lastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
    For Each C In .Range(.Cells(2, 1), .Cells(2, lastCol))
        ' check per cell if value is one of the values in StringsArr array
        If Not IsError(Application.Match(C.value, StringsArr, 0)) Then
            col = Sheets(C.value).Cells(2, Sheets(C.value).Columns.Count).End(xlToLeft).Column + 1 ' find first empty column in relevant sheet
            C.EntireColumn.Copy
            Sheets(C.value).Columns(col).PasteSpecial xlPasteValues
        End If
    Next C
End With

End Sub


问:
Parsing command line arguments in a python script (getopt woes)
Can anyone spot why the following script is not printing the passed arguments?

```<code>import sys, getopt

def usage():
    print 'Unknown arguments'

def main(argv):
    try:
        opts, args = getopt.getopt(argv,'fdmse:d',['files=','data-source=','mode=','start','end'])

    except getopt.GetoptError:
        usage()
        sys.exit(999)

    for opt, arg in opts:
        # print opt,arg
        if opt in('-f','--files'):
            print 'files: ', arg  #

if __name__ == "__main__":
    main(sys.argv[1:])
</code>```

When I run the script at the command line and pass the arguments -f=dummy.csv, usage() seems to be invoked instead - WHY?

BTW, I find the logic of the program flow a bit weird (I copied it from here). Normally, I would have thought that the logic will be implemented in the try branch, and then AFTER that comes the exception handler.

Is this (as pasted in the code above) the 'Pythonic' way to write try/catch blocks?

答:
Did you get your answers?

One way to debug python exceptions is to move (or copy temporarily for debugging) the code out of the try block.  You'll get a full trace.

And of course another way is to reduce the test case.  Here I've reduced the problems to three lines, and tried the solution hinted at by @s.lott (using 'f:' in the getopts call), and also show at the end how calling with some different test data behaves:

```<code>$ cat x1.py
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:],'fdmse:d',['files=','data-source=','mode=','start','end'])
print "opts=", opts, "args=", args

$ python x1.py -f=dummy.csv argblah
Traceback (most recent call last):
  File "x1.py", line 2, in <module>
    opts, args = getopt.getopt(sys.argv[1:],'fdmse:d',['files=','data-source=','mode=','start','end'])
  File "/usr/lib/python2.6/getopt.py", line 91, in getopt
    opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
  File "/usr/lib/python2.6/getopt.py", line 191, in do_shorts
    if short_has_arg(opt, shortopts):
  File "/usr/lib/python2.6/getopt.py", line 207, in short_has_arg
    raise GetoptError('option -%s not recognized' % opt, opt)
getopt.GetoptError: option -= not recognized

$ sed 's/fdm/f:dm/' <x1.py >x2.py

$ diff x1.py x2.py
2c2
< opts, args = getopt.getopt(sys.argv[1:],'fdmse:d',['files=','data-source=','mode=','start','end'])
---
> opts, args = getopt.getopt(sys.argv[1:],'f:dmse:d',['files=','data-source=','mode=','start','end'])

$ python x2.py -f=dummy.csv argblah
opts= [('-f', '=dummy.csv')] args= ['argblah']

$ python x1.py -f dummy.csv argblah
opts= [('-f', '')] args= ['dummy.csv', 'argblah']
</code>```

Body:
Can anyone spot why the following script is not printing the passed arguments?

import sys, getopt

def usage():
    print 'Unknown arguments'

def main(argv):
    try:
        opts, args = getopt.getopt(argv,'fdmse:d',['files=','data-source=','mode=','start','end'])

    except getopt.GetoptError:
        usage()
        sys.exit(999)

    for opt, arg in opts:
        # print opt,arg
        if opt in('-f','--files'):
            print 'files: ', arg  #

if __name__ == "__main__":
    main(sys.argv[1:])

When I run the script at the command line and pass the arguments -f=dummy.csv, usage() seems to be invoked instead - WHY?

BTW, I find the logic of the program flow a bit weird (I copied it from here). Normally, I would have thought that the logic will be implemented in the try branch, and then AFTER that comes the exception handler.

Is this (as pasted in the code above) the 'Pythonic' way to write try/catch blocks?

Body:
Did you get your answers?

One way to debug python exceptions is to move (or copy temporarily for debugging) the code out of the try block.  You'll get a full trace.

And of course another way is to reduce the test case.  Here I've reduced the problems to three lines, and tried the solution hinted at by @s.lott (using 'f:' in the getopts call), and also show at the end how calling with some different test data behaves:

$ cat x1.py
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:],'fdmse:d',['files=','data-source=','mode=','start','end'])
print "opts=", opts, "args=", args

$ python x1.py -f=dummy.csv argblah
Traceback (most recent call last):
  File "x1.py", line 2, in <module>
    opts, args = getopt.getopt(sys.argv[1:],'fdmse:d',['files=','data-source=','mode=','start','end'])
  File "/usr/lib/python2.6/getopt.py", line 91, in getopt
    opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
  File "/usr/lib/python2.6/getopt.py", line 191, in do_shorts
    if short_has_arg(opt, shortopts):
  File "/usr/lib/python2.6/getopt.py", line 207, in short_has_arg
    raise GetoptError('option -%s not recognized' % opt, opt)
getopt.GetoptError: option -= not recognized

$ sed 's/fdm/f:dm/' <x1.py >x2.py

$ diff x1.py x2.py
2c2
< opts, args = getopt.getopt(sys.argv[1:],'fdmse:d',['files=','data-source=','mode=','start','end'])
---
> opts, args = getopt.getopt(sys.argv[1:],'f:dmse:d',['files=','data-source=','mode=','start','end'])

$ python x2.py -f=dummy.csv argblah
opts= [('-f', '=dummy.csv')] args= ['argblah']

$ python x1.py -f dummy.csv argblah
opts= [('-f', '')] args= ['dummy.csv', 'argblah']


问:
Invalid salt Error in autentication process in nodejs
Am new to javascript and nodejs, I wrote a code to do authentication of the user from the password and salt present in database, Below is the code in nodejs were i receive a usercode and password and i retrieve the data from database and compare the password and salt present in DB with the received password.

The salt stored in DB is generated by base64 format.

```<code>var Bcrypt = require('bcrypt');
var pg = require('pg');
var usercode = 'tarun';
var clientid='214057357158656';
var password='tarun';
var connectionString = "postgres://dbusername:password@localhost:5432/USCProduction";
console.log('connectin to DB');
var client = new pg.Client(connectionString);
client.connect(function(err) {

    if(err) {
        console.log(err);
      }
    var Query ='select password, salt from muser, mclient where usercode='+"'"+usercode+"'"+' and muser.clientid='+clientid+' and muser.clientid=mclient.clientid and mclient.status=1';
    console.log('executing query',Query);
    client.query(Query, function(err, result) {

   if(err){
       console.log('Error in executing Query');
       client.end();
   } else {
       console.log(result.rows);
       var passinDB=result.rows[0].password;
       var saltinDB=result.rows[0].salt;
       console.log('passwordinDB : ',passinDB);
       console.log('saltinDB : ',saltinDB);
 client.end();
    Bcrypt.hash(passinDB, saltinDB, function(err, hash) {
        if(err) {
                return console.error(err);
        }
        console.log(hash);
    Bcrypt.compare(password, hash, function(err, isMatch) {
        if(err) {
                return console.error(err);
        }
        console.log('do they match?', isMatch);
    });

});
   }
    });
});
</code>```

Am facing the following error while ececuting the code

```<code>passwordinDB :  StAxL1r3bb/5k/6D6+BulwxhXFs=
saltinDB :  FOhs8crXyO8=
    [Error: Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue]
</code>```

its unable to find number of rounds of the salt or any other i may be missing in the code ,how to over come this error.

Thank You..!!

答:
In this line,

Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue]

$Vers is bcrypt_id

$log2(NumRounds) is a parameter that tells it how many times to execute that internal hash function.

So you need to generate salt and has password in this way:

var bcrypt = require('bcryptjs');
bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash("any_password", salt, function(err, hash) {
        // Store hash in your password DB.
    });
});```

Read more here

Body:
Am new to javascript and nodejs, I wrote a code to do authentication of the user from the password and salt present in database, Below is the code in nodejs were i receive a usercode and password and i retrieve the data from database and compare the password and salt present in DB with the received password.

The salt stored in DB is generated by base64 format.

var Bcrypt = require('bcrypt');
var pg = require('pg');
var usercode = 'tarun';
var clientid='214057357158656';
var password='tarun';
var connectionString = "postgres://dbusername:password@localhost:5432/USCProduction";
console.log('connectin to DB');
var client = new pg.Client(connectionString);
client.connect(function(err) {

    if(err) {
        console.log(err);
      }
    var Query ='select password, salt from muser, mclient where usercode='+"'"+usercode+"'"+' and muser.clientid='+clientid+' and muser.clientid=mclient.clientid and mclient.status=1';
    console.log('executing query',Query);
    client.query(Query, function(err, result) {

   if(err){
       console.log('Error in executing Query');
       client.end();
   } else {
       console.log(result.rows);
       var passinDB=result.rows[0].password;
       var saltinDB=result.rows[0].salt;
       console.log('passwordinDB : ',passinDB);
       console.log('saltinDB : ',saltinDB);
 client.end();
    Bcrypt.hash(passinDB, saltinDB, function(err, hash) {
        if(err) {
                return console.error(err);
        }
        console.log(hash);
    Bcrypt.compare(password, hash, function(err, isMatch) {
        if(err) {
                return console.error(err);
        }
        console.log('do they match?', isMatch);
    });

});
   }
    });
});

Am facing the following error while ececuting the code

passwordinDB :  StAxL1r3bb/5k/6D6+BulwxhXFs=
saltinDB :  FOhs8crXyO8=
    [Error: Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue]

its unable to find number of rounds of the salt or any other i may be missing in the code ,how to over come this error.

Thank You..!!

Body:
In this line,

Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue]

$Vers is bcrypt_id

$log2(NumRounds) is a parameter that tells it how many times to execute that internal hash function.

So you need to generate salt and has password in this way:

var bcrypt = require('bcryptjs');
bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash("any_password", salt, function(err, hash) {
        // Store hash in your password DB.
    });
});

Read more here

ContentLicense: CC BY-SA 4.0


问:
SignalR won't use Websocket protocol even though I have the protocol installed in windows 8
I'm using signalr to do some real-time events in my web application. I'm trying to force signalr to use the new websocket protocol but it won't, even if I specify it.

```<code>$.connection.hub.start({ transport: 'webSockets' })
</code>```

I definitely have the web socket protocol installed and I am running Windows 8 with IIS 8.

What else do I need to do to enable web sockets support in signalr?

答: If you are already using framework 4.5 but still no luck, add an HTTPS binding to your IIS website and access the website over HTTPS.</p>

Body:
I'm using signalr to do some real-time events in my web application. I'm trying to force signalr to use the new websocket protocol but it won't, even if I specify it.

$.connection.hub.start({ transport: 'webSockets' })

I definitely have the web socket protocol installed and I am running Windows 8 with IIS 8.

What else do I need to do to enable web sockets support in signalr?


问:
Getting error at console jQuery : not a function
In MVC I am getting following error :

jQuery.Deferred exception: $(...).parents(...).andSelf is not a function

I just Installed the latest version of jQuery via NUGET. I'm getting stuck because of the above mentioned error.

答:
Sir, the andSelf() is deprecated in version 1.8 and removed from 3.0. that's why the above error is occurred.
Here is some description: https://api.jquery.com/andself/


问:
Swift - UIButton with two lines of text
I was wondering if it is possible to create a UIButton with two lines of text.  I need each line to have a different font size.  The first line will be 17 point and the second will be 11 point.  I've tried messing with putting two labels inside of a UIButton, but I can't get them to stay inside the bounds of the button.

I'm attempting to do all of this in the ui builder, and not programmatically.

Thanks

答:
I have notice an issue in most of the solutions which is while making line break mode to "Character Wrap" the second line will be left aligned to the first line

To make all the lines centered.
just change the title From Plain to Attributed and then you can make each line centered

Title: Swift - UIButton with two lines of text


问:
Update facebook page status from that page itself
I'm trying to update the status of my page (from my page). I have been successful in posting to the wall of the page with the following code:

```<code>require_once 'facebook-php-sdk/src/facebook.php';

// Create our Application instance.
$facebook = new Facebook(array(
  'appId'  => '...',
  'secret' => '...'
));

$attachment = array(
'access_token' => "...",
'message'=> "Hello World"
);

$facebook->api('/pageId/feed','POST', $attachment);
</code>```

But the post shows that I posted to the page from my account(ie: Joe Blogs) where I want it to show that it was posted by the page itself (ie: Page Name).

Or am I going about it the wrong way? Should I be trying to change the Status of the page (if possible)?

Any help would be greatly appreciated.

答:
You need to add the UID of your fan page to your api call.

I believe it should be something like:

```<code>$uid = 'your page id';
$facebook->api('/pageId/feed', 'POST', $attachment, $uid);
</code>```

If no UID is provided in the call, it defaults to the session user.

Body:
I'm trying to update the status of my page (from my page). I have been successful in posting to the wall of the page with the following code:

require_once 'facebook-php-sdk/src/facebook.php';

// Create our Application instance.
$facebook = new Facebook(array(
  'appId'  => '...',
  'secret' => '...'
));

$attachment = array(
'access_token' => "...",
'message'=> "Hello World"
);

$facebook->api('/pageId/feed','POST', $attachment);

But the post shows that I posted to the page from my account(ie: Joe Blogs) where I want it to show that it was posted by the page itself (ie: Page Name).

Or am I going about it the wrong way? Should I be trying to change the Status of the page (if possible)?

Any help would be greatly appreciated.

Body:
You need to add the UID of your fan page to your api call.

I believe it should be something like:

$uid = 'your page id';
$facebook->api('/pageId/feed', 'POST', $attachment, $uid);

If no UID is provided in the call, it defaults to the session user.


问:
Bash PATH is not a valid identifier
I'm on a Mac, when I open my shell, it displays the following:

```<code>-bash: export: `/Users/jasoncollis/torch/install/bin/torch-activate:/usr/local/bin:/Users/jasoncollis/Library/Enthought/Canopy_64bit/User/bin:/Users/jasoncollis/anaconda/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin': not a valid identifier
</code>```

This is my #.bash_profile# file:

```<code># Setting PATH for Python 3.5
# The original version is saved in .bash_profile.pysave
PATH=":/Library/Frameworks/Python.framework/Versions/3.5/bin:${PATH}"
export PATH

# added by Anaconda3 4.2.0 installer
export PATH=":/Users/jasoncollis/anaconda/bin:$PATH"

# Added by Canopy installer on 2016-11-10
# VIRTUAL_ENV_DISABLE_PROMPT can be set to '' to make the bash prompt show that Canopy is active, otherwise 1
alias activate_canopy="source '/Users/jasoncollis/Library/Enthought/Canopy_64bit/User/bin/activate'"
VIRTUAL_ENV_DISABLE_PROMPT=1 source '/Users/jasoncollis/Library/Enthought/Canopy_64bit/User/bin/activate'
export PATH=":/usr/local/bin:$PATH"

export LC_CTYPE=en_US.UTF-8

export PATH=":/Users/jasoncollis/torch/install/bin/torch-activate:$PATH"

export PATH=":/Users/jasoncollis/torch/install/bin:$PATH"
</code>```

I've been trying to search for a solution but nothing I've tried has worked so far. Would be really grateful for any help!

答: Make sure that you edit the right file. For login shells Bash executes .bash_profile and not #.bash_profile#. The later looks like a backup file created by a text editor or script.

Title: Bash PATH is not a valid identifier

Body:
I'm on a Mac, when I open my shell, it displays the following:

-bash: export: `/Users/jasoncollis/torch/install/bin/torch-activate:/usr/local/bin:/Users/jasoncollis/Library/Enthought/Canopy_64bit/User/bin:/Users/jasoncollis/anaconda/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin': not a valid identifier

This is my #.bash_profile# file:

# Setting PATH for Python 3.5
# The original version is saved in .bash_profile.pysave
PATH=":/Library/Frameworks/Python.framework/Versions/3.5/bin:${PATH}"
export PATH

# added by Anaconda3 4.2.0 installer
export PATH=":/Users/jasoncollis/anaconda/bin:$PATH"

# Added by Canopy installer on 2016-11-10
# VIRTUAL_ENV_DISABLE_PROMPT can be set to '' to make the bash prompt show that Canopy is active, otherwise 1
alias activate_canopy="source '/Users/jasoncollis/Library/Enthought/Canopy_64bit/User/bin/activate'"
VIRTUAL_ENV_DISABLE_PROMPT=1 source '/Users/jasoncollis/Library/Enthought/Canopy_64bit/User/bin/activate'
export PATH=":/usr/local/bin:$PATH"

export LC_CTYPE=en_US.UTF-8

export PATH=":/Users/jasoncollis/torch/install/bin/torch-activate:$PATH"

export PATH=":/Users/jasoncollis/torch/install/bin:$PATH"

I've been trying to search for a solution but nothing I've tried has worked so far. Would be really grateful for any help!


问:
How do I get TinyMCE 4.x to work with dynamically added DIVs?
I need to use TinyMCE 4.x to edit contents in multiple DIVs. This works well, except when I dynamically add more DIVs by clicking a button (jquery).

The new DIV shows below the others, but it is not editable at once. After saving the file and reloading it, the new DIV is also editable.

I see that all existing DIVs has a id="mce_nn" where nn is a unique number. This seams to be added by TinyMCE itself.

When I dynamically add new DIVs they do not have a id added. However after saving the file and then reloading the page it has a id added.

Is there a way I can get TinyMCE to dynamically to allow me to edit new DIVs?  (All new DIVs had a common class. )

This is my current TinyMCE init:

```<code><script type="text/javascript">
tinymce.init({
    selector: "div.mydivsclass",
    inline: true,
 theme: "modern",
    width: "100%",
    height: 300,
</code>```

I appreciate all help :-)

答:
I did this by calling ActivateTinyMCE() function onclick of DIV, but then inline tinymce toolbar was not working for me. Tinymce editor instance was getting initialized but toolbar was not getting visible. I have resolved this issue by firing focus event when tinymce gets initialized as shown below.

```<code><script type="text/javascript">
function ActivateTinyMCE() {
    tinymce.init({
         selector: "div.myclass",
         inline: true,
         ...,
         setup : function(editor) {
            editor.on('init', function() {
                editor._eventDispatcher.fire("focus");
         });
        }
    });
}
</code>```

```<code><div class="myclass" onclick="ActivateTinyMCE()"/>
</code>```

Body:
I did this by calling ActivateTinyMCE() function onclick of DIV, but then inline tinymce toolbar was not working for me. Tinymce editor instance was getting initialized but toolbar was not getting visible. I have resolved this issue by firing focus event when tinymce gets initialized as shown below.

<script type="text/javascript">
function ActivateTinyMCE() {
    tinymce.init({
         selector: "div.myclass",
         inline: true,
         ...,
         setup : function(editor) {
            editor.on('init', function() {
                editor._eventDispatcher.fire("focus");
         });
        }
    });
}

<div class="myclass" onclick="ActivateTinyMCE()"/>


问:
PHP Session Variable not showing prior to unset being called
Basically I have the following code which is currently working fine as expected:

```<code>if ( isset($_SESSION['message']) )
    {
    echo '<p class="user_message">'.$_SESSION['message'].'</p>';

    //unset( $_SESSION['message'] );
    }
</code>```

As you can see the unset()  has been commented out. What I want to do is unset the session message after it has echo'd out. However when I run this code without the comments, the session variable is not echo'd out at all?

Many thanks in advance.

EDIT:

Thanks for responding, however this solution does not work and returns the same result as my original attempt. Here is the code which defines the session message:

```<code>$_SESSION['message'] = "";

// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {

$_SESSION['message'] = $_SESSION['message'].'User with this email already         exists!<br />';

 }
// Validate email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

$_SESSION['message'] = $_SESSION['message'].'Email address is invalid, please try again!<br />';

}
// Validate Referral code
if ( $refby != "" ) {
if ( (count_digit($refby) > 0 && count_digit($refby) < 6) || count_digit($refby) > 6 ) {
        $_SESSION['message'] = $_SESSION['message'].'Referral code is invalid!<br />';
} elseif ( !is_numeric($refby) ) {
        $_SESSION['message'] = $_SESSION['message'].'Referral code is invalid!<br />';
}
</code>```

}

```<code> // Validate password length
if ( count_digit($_POST['password']) < 6 ) {

$_SESSION['message'] = $_SESSION['message'].'Password invalid, must be more than 6 characters!<br />';
</code>```

}

```<code>// Validate password confirmed
if ( $_POST['password'] != $_POST['confirm_password'] ) {

$_SESSION['message'] = $_SESSION['message'].'Your passwords do not match!<br     />';
</code>```

}

```<code> if ( count_digit($num1)>2 || count_digit($num2)>2 || count_digit($num3)>2 ||       count_digit($num4)>2 || count_digit($num5)>2 ) {

$_SESSION['message'] = $_SESSION['message'].'Please select your lucky    numbers!<br />';
 }

if ( $_SESSION['message'] != "" ) {
header("location: #register_content");
</code>```

however, I dont understand how the code works perfectly prior to unsetting the session variable? even though the contents are echo'd prior to the session variable being unset?

Many thanks

答:
You can use the following approach:

```<code>if ( isset($_SESSION['message']) )
{
    $message = $_SESSION['message'];
    echo '<p class="user_message">'.$message.'</p>';
    unset( $_SESSION['message'] );
}
</code>```

It will print the data as well as unset it later.

also remember to call session_start() at the beginning of your script.

Body:
Basically I have the following code which is currently working fine as expected:

if ( isset($_SESSION['message']) )
    {
    echo '
'.$_SESSION['message'].'
';

    //unset( $_SESSION['message'] );
    }

As you can see the unset()  has been commented out. What I want to do is unset the session message after it has echo'd out. However when I run this code without the comments, the session variable is not echo'd out at all?

Many thanks in advance.

EDIT:

Thanks for responding, however this solution does not work and returns the same result as my original attempt. Here is the code which defines the session message:

$_SESSION['message'] = "";

// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {

$_SESSION['message'] = $_SESSION['message'].'User with this email already         exists!
';

 }
// Validate email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

$_SESSION['message'] = $_SESSION['message'].'Email address is invalid, please try again!
';

}
// Validate Referral code
if ( $refby != "" ) {
if ( (count_digit($refby) > 0 && count_digit($refby) < 6) || count_digit($refby) > 6 ) {
        $_SESSION['message'] = $_SESSION['message'].'Referral code is invalid!
';
} elseif ( !is_numeric($refby) ) {
        $_SESSION['message'] = $_SESSION['message'].'Referral code is invalid!
';
}

}

 // Validate password length
if ( count_digit($_POST['password']) < 6 ) {

$_SESSION['message'] = $_SESSION['message'].'Password invalid, must be more than 6 characters!
';

}

// Validate password confirmed
if ( $_POST['password'] != $_POST['confirm_password'] ) {

$_SESSION['message'] = $_SESSION['message'].'Your passwords do not match!
';

}

 if ( count_digit($num1)>2 || count_digit($num2)>2 || count_digit($num3)>2 ||       count_digit($num4)>2 || count_digit($num5)>2 ) {

$_SESSION['message'] = $_SESSION['message'].'Please select your lucky    numbers!
';
 }

if ( $_SESSION['message'] != "" ) {
header("location: #register_content");

however, I dont understand how the code works perfectly prior to unsetting the session variable? even though the contents are echo'd prior to the session variable being unset?

Many thanks

Body:
You can use the following approach:

if ( isset($_SESSION['message']) )
{
    $message = $_SESSION['message'];
    echo '<p class="user_message">'.$message.'</p>';
    unset( $_SESSION['message'] );
}

It will print the data as well as unset it later.

also remember to call session_start() at the beginning of your script.


问:
Edittext password is always showing the password
I have an EditText to enter the password and i set inputType as "textPassword". But when i run it in app or emulator the password is visible. Why it is showing password instead of dots?

```<code><EditText
 android:id="@+id/etPassword"
 android:layout_width="match_parent"
 android:inputType="textPassword"
 android:layout_height="wrap_content"
 android:hint="@string/Password"
 android:layout_marginBottom="10dp"
 android:maxLength="15"
 android:background="@drawable/ss"/>
</code>```

drawable file ss:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="10dp"/>
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<solid android:color="#ffffffff"/>
<stroke android:width="1dp" android:color="#CCCCCC" />
</code>```

Complete Layout:

```<code>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:background="#ffffffff"
        android:gravity="center_vertical" >

        <ImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/foodstall"
         android:layout_gravity="center"
         android:layout_marginBottom="10dp"/>

        <LinearLayout
         android:layout_width="match_parent"
         android:orientation="vertical"
         android:layout_height="wrap_content"
         android:background="#ffffffff">

        <EditText
        android:id="@+id/etUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/Username"
        android:maxLength="15"
        android:background="@drawable/ss"
        android:layout_marginBottom="10dp"/>

        <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:inputType="textPassword"
        android:layout_height="wrap_content"                                                     android:hint="@string/Password"
        android:layout_marginBottom="10dp"
        android:maxLength="15"
        android:background="@drawable/ss"
                android:text="askdjhkashdjasdksakdkaskdhkashkdhkashdkjhakshdkjhaskhdkj"/>

        <Button
        android:id="@+id/bLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/title_activity_login"
        android:background="@color/button"
        android:textColor="#ffffffff"
        android:layout_weight="1" />

        </LinearLayout>

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearlayout"
        android:background="@drawable/ss"
        android:layout_marginTop="10dp">

        <TextView
        android:id="@+id/tvRegisterLink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/Newuser"
        android:gravity="center"
        android:layout_weight="1"
        android:textStyle="bold"/>

        <TextView
        android:id="@+id/fpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/title_activity_forgotpass"
        android:layout_weight="1"
        android:gravity="center"
        android:textStyle="bold"/>

        </LinearLayout>

        </LinearLayout>
</code>```

答:
Try adding android:password="true" in EditText. It should work.</p>

```<code>    <EditText
      android:id="@+id/etPassword"
      android:layout_width="match_parent"
      android:inputType="textPassword"
      android:password="true"
      android:layout_height="wrap_content"
      android:hint="@string/Password"
      android:layout_marginBottom="10dp"
      android:maxLength="15"
      android:background="@drawable/ss"/>
</code>```

Body:
I have an EditText to enter the password and i set inputType as "textPassword". But when i run it in app or emulator the password is visible. Why it is showing password instead of dots?

<EditText
 android:id="@+id/etPassword"
 android:layout_width="match_parent"
 android:inputType="textPassword"
 android:layout_height="wrap_content"
 android:hint="@string/Password"
 android:layout_marginBottom="10dp"
 android:maxLength="15"
 android:background="@drawable/ss"/>

drawable file ss:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="10dp"/>
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<solid android:color="#ffffffff"/>
<stroke android:width="1dp" android:color="#CCCCCC" />

Complete Layout:

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:background="#ffffffff"
        android:gravity="center_vertical" >

        <ImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/foodstall"
         android:layout_gravity="center"
         android:layout_marginBottom="10dp"/>

        <LinearLayout
         android:layout_width="match_parent"
         android:orientation="vertical"
         android:layout_height="wrap_content"
         android:background="#ffffffff">

        <EditText
        android:id="@+id/etUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/Username"
        android:maxLength="15"
        android:background="@drawable/ss"
        android:layout_marginBottom="10dp"/>

        <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:inputType="textPassword"
        android:layout_height="wrap_content"                                                     android:hint="@string/Password"
        android:layout_marginBottom="10dp"
        android:maxLength="15"
        android:background="@drawable/ss"
                android:text="askdjhkashdjasdksakdkaskdhkashkdhkashdkjhakshdkjhaskhdkj"/>

        <Button
        android:id="@+id/bLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/title_activity_login"
        android:background="@color/button"
        android:textColor="#ffffffff"
        android:layout_weight="1" />

        </LinearLayout>

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearlayout"
        android:background="@drawable/ss"
        android:layout_marginTop="10dp">

        <TextView
        android:id="@+id/tvRegisterLink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/Newuser"
        android:gravity="center"
        android:layout_weight="1"
        android:textStyle="bold"/>

        <TextView
        android:id="@+id/fpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/title_activity_forgotpass"
        android:layout_weight="1"
        android:gravity="center"
        android:textStyle="bold"/>

        </LinearLayout>

        </LinearLayout>

Body:
Try adding android:password="true" in EditText. It should work.

    <EditText
      android:id="@+id/etPassword"
      android:layout_width="match_parent"
      android:inputType="textPassword"
      android:password="true"
      android:layout_height="wrap_content"
      android:hint="@string/Password"
      android:layout_marginBottom="10dp"
      android:maxLength="15"
      android:background="@drawable/ss"/>


问:
SAS Retain statement - how to retain previous non missing values into new column for comparison
I am simply looking to create a new column retaining the value of a specific column within the previous record, so that I can compare the existing column against the new column. Further down the line I want to be able to output records whereby the values in both columns are different and lose the records where the values are the same

Essentially I want my dataset to look like this, where the first idr has the retained date set to null:

```<code>Idr Date1           Date2
1   20/01/2016  .
1   20/01/2016  20/01/2016
1   18/10/2016  20/01/2016
2   07/03/2016  .
2   18/05/2016  07/03/2016
2   21/10/2016  18/05/2016
3   29/01/2016  .
3   04/02/2016  29/01/2016
3   04/02/2016  04/02/2016
</code>```

I have used code along the following lines in the past whereby I have created a temporary variable referencing the data I want to retain:

```<code>date_temp=date1;
    data example2;
    set example1;
    by idr date1;
    date_temp=date1;
retain date_temp ;
    if first.idr then do;
        date_temp=date1;
    end;else do;
        date2=date_temp;
    end;
 run;
</code>```

I have searched the highs and lows of google - Any help would be greatly appreciated

答:
To achieve your final outcome (remove records where the idr and date are the same as the previous row), you can easily achieve this without creating the extra column.  Providing the data is sorted by idr and date1, then just use first.date1 to keep the required records.

```<code>data have;
input Idr Date1 :ddmmyy10.;
format date1 ddmmyy10.;
datalines;
1   20/01/2016
1   20/01/2016
1   18/10/2016
2   07/03/2016
2   18/05/2016
2   21/10/2016
3   29/01/2016
3   04/02/2016
3   04/02/2016
;
run;

data want;
set have;
by idr date1;
if first.date1 then output;
run;
</code>```

Body:
I am simply looking to create a new column retaining the value of a specific column within the previous record, so that I can compare the existing column against the new column. Further down the line I want to be able to output records whereby the values in both columns are different and lose the records where the values are the same

Essentially I want my dataset to look like this, where the first idr has the retained date set to null:

Idr Date1           Date2
1   20/01/2016  .
1   20/01/2016  20/01/2016
1   18/10/2016  20/01/2016
2   07/03/2016  .
2   18/05/2016  07/03/2016
2   21/10/2016  18/05/2016
3   29/01/2016  .
3   04/02/2016  29/01/2016
3   04/02/2016  04/02/2016

I have used code along the following lines in the past whereby I have created a temporary variable referencing the data I want to retain:

date_temp=date1;
    data example2;
    set example1;
    by idr date1;
    date_temp=date1;
retain date_temp ;
    if first.idr then do;
        date_temp=date1;
    end;else do;
        date2=date_temp;
    end;
 run;

I have searched the highs and lows of google - Any help would be greatly appreciated

Body:
To achieve your final outcome (remove records where the idr and date are the same as the previous row), you can easily achieve this without creating the extra column.  Providing the data is sorted by idr and date1, then just use first.date1 to keep the required records.

data have;
input Idr Date1 :ddmmyy10.;
format date1 ddmmyy10.;
datalines;
1   20/01/2016
1   20/01/2016
1   18/10/2016
2   07/03/2016
2   18/05/2016
2   21/10/2016
3   29/01/2016
3   04/02/2016
3   04/02/2016
;
run;

data want;
set have;
by idr date1;
if first.date1 then output;
run;


问:
Structure JSOUP content to JSON
I extract some data from a http site and now I want to format this using JSON . I watched some examples but i don't understand how to do that exactly .I want something like that :

```<code>{
  Product name:"Samsung..."
    { review 1:"..."
      review 2:"..."
   }
}
</code>```

Also my code don't iterate over all reviews, it stops at page 1 ,and there is 10 more pages and i want to get like 20-30 reviews at least. There is what i did until now :

```<code>import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JsoupMain {

private static int nr = 1;

public static void main(String[] args) {

    Document document = null;
    try {
        document = Jsoup.connect("http://www.emag.ro/telefon-mobil-samsung- galaxy-j5-2016-dual-sim-16gb-4g-gold-sm-j510fzdurom/pd/DQD3B7BBM/").get();

        String title = document.title();
        System.out.println("Title: " + title);

        Elements review = document.select("div.product-review-body");

        for (Element rev : review) {
            System.out.println("Review : " + nr + " :" + rev.text() + "\n");
            nr++;
        }

    } catch (IOException e) {

        e.printStackTrace();
    }

}

}
</code>```

答:
Replace your code from  Elements review = document.select("div.product-review-body");... to   ... System.out.println(mainObject); with the following code snippet.

```<code>            Elements review = document.select("div[class=product-review-body]");
            JSONObject parent = new JSONObject();
            parent.put("Product name", title);
            JSONArray reviews = new JSONArray();
            int i = 1;
            for (Element rev : review) {
                reviews.put(new JSONObject().put("review" + i, rev.text()));
                i++;
            }
            parent.put("Reviews", reviews);
            System.out.println(parent);
</code>```

Hope this helps.

Title: Structure JSOUP content to JSON

Body:
I extract some data from a http site and now I want to format this using JSON . I watched some examples but i don't understand how to do that exactly .I want something like that :

{
  Product name:"Samsung..."
    { review 1:"..."
      review 2:"..."
   }
}

Also my code don't iterate over all reviews, it stops at page 1 ,and there is 10 more pages and i want to get like 20-30 reviews at least. There is what i did until now :

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JsoupMain {

private static int nr = 1;

public static void main(String[] args) {

    Document document = null;
    try {
        document = Jsoup.connect("http://www.emag.ro/telefon-mobil-samsung- galaxy-j5-2016-dual-sim-16gb-4g-gold-sm-j510fzdurom/pd/DQD3B7BBM/").get();

        String title = document.title();
        System.out.println("Title: " + title);

        Elements review = document.select("div.product-review-body");

        for (Element rev : review) {
            System.out.println("Review : " + nr + " :" + rev.text() + "\n");
            nr++;
        }

    } catch (IOException e) {

        e.printStackTrace();
    }

}

}

Body:
Replace your code from  Elements review = document.select("div.product-review-body");... to   ... System.out.println(mainObject); with the following code snippet.

            Elements review = document.select("div[class=product-review-body]");
            JSONObject parent = new JSONObject();
            parent.put("Product name", title);
            JSONArray reviews = new JSONArray();
            int i = 1;
            for (Element rev : review) {
                reviews.put(new JSONObject().put("review" + i, rev.text()));
                i++;
            }
            parent.put("Reviews", reviews);
            System.out.println(parent);

Hope this helps.


问:
How to access device settings programmatically?
Is there any way to access device settings programmatically?

For Example: Settings > Developer Options > USB debugging > True/False

Thanks in advance.

Edit: USB debugging is just an example. Can I access every settings which is exist in Settings in device.

答:
If you app is System app then you Simply do this to enable/disable USB Debugging

Settings.Secure.putInt(getActivity().getContentResolver(),Settings.Secure.ADB_ENABLED,
  1);

You also need root access to do this.
I have rooted device and I just simply execute SU to enable/disable Usb Debugging.

Process proc = Runtime.getRuntime().exec(new String [] { "su", "-c",
  "setprop", "persist.service.adb.enable", "0"});

proc.waitFor();

Process proc2 = Runtime.getRuntime().exec(new String [] { "su", "-c",
  "stop", "adbd"});

proc2.waitFor();

Good thing is you don't need to place your application in (/system/priv-app/)
Your simple app i.e. (/data/app) can do this.


问:
PowerShell receive vs. get verbs
I've seen quite a few discussions on which verbs to use in your own PowerShell functions, but I haven't seen a clarification on using Receive vs. Get. They mean roughly the same thing to me, but Receive is supposed to be used specifically in situations involving communications (just type Get-Verb to see this).  Get, however, is in the Common group, so I'm really not sure which one to use.

I have a function that basically wraps a RESTful API and gets data from it (I use parameter sets for the different methods of the service). Right now the function is called Get-FooData. However, I'm thinking that I should possibly rename it to Receive-FooData since it is doing some communication.

I think I'm being too literal here in wanting to use Receive. My personal feeling is that Get sounds better, but I think that's just because I'm used to using it. What are your thoughts?

答:
Although I'm proficient at PowerShell at only the amateur level, for me, "get" implies a much more forceful and in-charge type of code.  Meaning my code is going to initiate the action, and the other software will humbly respond to my request.

"Receive" sounds more docile, meaning the other software is really in charge.  So I might use Receive if the other software was for example putting out temperatures once a minute.  I'm going to receive the data, but the other software is doing its thing even if I wasn't there to receive it.

"Get" is shorter and most of the time I like to feel like my code is in charge.  Go with Get.

Title: PowerShell receive vs. get verbs


问:
Highlighting textview with color like Adobe PDF
I'm trying to add menu to focus textview to highlight a word or phrase.
Currently my code has issues
1. highlights more than one word if the word appears more than once
2. Highlighted color disappears on app exit.</p>

```<code>    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        getMenuInflater().inflate(R.menu.h_menu, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.highlight:
                    setTextBG();
                    return true;
                default:
                    break;
            }
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {

        }
    });
}
private void setTextBG() {
    String selectedText = "";
    if (textView.isFocused()) {
        final int textStartIndex = textView.getSelectionStart();
        final int textEndIndex = textView.getSelectionEnd();

        int min = 0;
        int max = textView.getText().length();

        min = Math.max(0, Math.min(textStartIndex, textEndIndex));
        max = Math.max(0, Math.max(textStartIndex, textEndIndex));
        selectedText = textView.getText().subSequence(min, max).toString().trim();
    }
    int txt = textView.getText().toString().indexOf(selectedText, 0);

    Spannable mywords = new SpannableString(textView.getText().toString());
    for (int i = 0; i < textView.getText().toString().length() && whateva != -1;
            i = whateva+1) {
        txt = textView.getText().toString().indexOf(selectedText, i);
        if (txt == -1) break;
        else {
            mywords.setSpan(new BackgroundColorSpan(Color.YELLOW), txt, txt+selectedText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            textView.setText(mywords, TextView.BufferType.SPANNABLE);
        }
    }
    Toast.makeText(getApplicationContext(), selectedText, Toast.LENGTH_SHORT).show();
}
</code>```

答:
Please find below example for highlighting more than one word in content.

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    private TextView textContent;

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

        textContent = (TextView) findViewById(R.id.txtContent);

        highlightWords();

    }

    private void highlightWords() {
        String content = "This is just a demo of how to highlight more than one word in Android";
        textContent.setText(getSpannableWord(content));
    }

    private Spannable getSpannableWord(String content) {
        Spannable spannableString = new SpannableString(content);

        // Create list of highlighted word and add to list every time user highlights
        ArrayList<HighlightedWord> words = new ArrayList<>();

        //1st highlighted word
        HighlightedWord highlightedWord1 = new HighlightedWord("demo", 15);
        words.add(highlightedWord1);

        //2nd highlighted word
        HighlightedWord highlightedWord2 = new HighlightedWord("highlight", 30);
        words.add(highlightedWord2);

        for (HighlightedWord highlightedWord : words) {
            spannableString.setSpan(new BackgroundColorSpan(Color.YELLOW), highlightedWord.getStartIndex(),
                    highlightedWord.getStartIndex()+ highlightedWord.getWord().length(), Spannable
                            .SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }
}
</code>```

Thanks!

Body:
I'm trying to add menu to focus textview to highlight a word or phrase.
Currently my code has issues
1. highlights more than one word if the word appears more than once
2. Highlighted color disappears on app exit.

    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        getMenuInflater().inflate(R.menu.h_menu, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.highlight:
                    setTextBG();
                    return true;
                default:
                    break;
            }
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {

        }
    });
}
private void setTextBG() {
    String selectedText = "";
    if (textView.isFocused()) {
        final int textStartIndex = textView.getSelectionStart();
        final int textEndIndex = textView.getSelectionEnd();

        int min = 0;
        int max = textView.getText().length();

        min = Math.max(0, Math.min(textStartIndex, textEndIndex));
        max = Math.max(0, Math.max(textStartIndex, textEndIndex));
        selectedText = textView.getText().subSequence(min, max).toString().trim();
    }
    int txt = textView.getText().toString().indexOf(selectedText, 0);

    Spannable mywords = new SpannableString(textView.getText().toString());
    for (int i = 0; i < textView.getText().toString().length() && whateva != -1;
            i = whateva+1) {
        txt = textView.getText().toString().indexOf(selectedText, i);
        if (txt == -1) break;
        else {
            mywords.setSpan(new BackgroundColorSpan(Color.YELLOW), txt, txt+selectedText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            textView.setText(mywords, TextView.BufferType.SPANNABLE);
        }
    }
    Toast.makeText(getApplicationContext(), selectedText, Toast.LENGTH_SHORT).show();
}

Body:
Please find below example for highlighting more than one word in content.

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private TextView textContent;

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

        textContent = (TextView) findViewById(R.id.txtContent);

        highlightWords();

    }

    private void highlightWords() {
        String content = "This is just a demo of how to highlight more than one word in Android";
        textContent.setText(getSpannableWord(content));
    }

    private Spannable getSpannableWord(String content) {
        Spannable spannableString = new SpannableString(content);

        // Create list of highlighted word and add to list every time user highlights
        ArrayList<HighlightedWord> words = new ArrayList<>();

        //1st highlighted word
        HighlightedWord highlightedWord1 = new HighlightedWord("demo", 15);
        words.add(highlightedWord1);

        //2nd highlighted word
        HighlightedWord highlightedWord2 = new HighlightedWord("highlight", 30);
        words.add(highlightedWord2);

        for (HighlightedWord highlightedWord : words) {
            spannableString.setSpan(new BackgroundColorSpan(Color.YELLOW), highlightedWord.getStartIndex(),
                    highlightedWord.getStartIndex()+ highlightedWord.getWord().length(), Spannable
                            .SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }
}

Thanks!


问:
JS Promises: is there a neat way to resolve multiple promises as object properties?
I wrote the below code then realised it was resolving early (logging before all promises resolve):

```<code>readDirPromise
.then(categoriseFiles)
.then(({movies, series}) => ({
  movies: Promise.all(movies.map(movieTasks)),
  series: Promise.all(series.map(seriesTasks))
}))
.then((res) => {
  console.log(' done!', res)
})
</code>```

I've managed to rewrite it to resolve in the correct order:

```<code>readDirPromise
.then(categoriseFiles)
.then((cats) => Promise.all(cats.movies.map(movieTasks)).then((movies) => {
  cats.movies = movies
  return cats
}))
.then((cats) => Promise.all(cats.series.map(seriesTasks)).then((series) => {
  cats.series = series
  return cats
}))
.then((res) => {
  console.log(' done!', res)
})
</code>```

but I can't help but think... is there a neater, more extensible way?

答:
You can make the series step run independently of the movies step (rather than blocking one after the other) by wrapping both of them in another layer of Promise.all, coming back as a tuple which you may then destructure and restructure into the object you want:

```<code>readDirPromise
.then(categoriseFiles)
.then(({movies, series}) => Promise.all([
  Promise.all(movies.map(movieTasks)),
  Promise.all(series.map(seriesTasks))])
.then(([movies, series]) => ({movies, series}))
.then((res) => {
  console.log(' done!', res)
})
</code>```

Body:
I wrote the below code then realised it was resolving early (logging before all promises resolve):

readDirPromise
.then(categoriseFiles)
.then(({movies, series}) => ({
  movies: Promise.all(movies.map(movieTasks)),
  series: Promise.all(series.map(seriesTasks))
}))
.then((res) => {
  console.log(' done!', res)
})

I've managed to rewrite it to resolve in the correct order:

readDirPromise
.then(categoriseFiles)
.then((cats) => Promise.all(cats.movies.map(movieTasks)).then((movies) => {
  cats.movies = movies
  return cats
}))
.then((cats) => Promise.all(cats.series.map(seriesTasks)).then((series) => {
  cats.series = series
  return cats
}))
.then((res) => {
  console.log(' done!', res)
})

but I can't help but think... is there a neater, more extensible way?

Body:
You can make the series step run independently of the movies step (rather than blocking one after the other) by wrapping both of them in another layer of Promise.all, coming back as a tuple which you may then destructure and restructure into the object you want:

readDirPromise
.then(categoriseFiles)
.then(({movies, series}) => Promise.all([
  Promise.all(movies.map(movieTasks)),
  Promise.all(series.map(seriesTasks))])
.then(([movies, series]) => ({movies, series}))
.then((res) => {
  console.log(' done!', res)
})


问:
infoWindow and center on click outside map
I have been playing around with Google Maps, and would like to center on a marker and open the appropriate infoWindow when I click on an element outside the map.
For example I have;

```<code><div id="map"></div>
Store A
Opening Hours: 10-10

Store B
Opening Hours: 10-4

Store C
Opening Hours: 9-9

Store D.
Opening Hours: 8-9
</code>```

I would like it to work, when I click on one of the stores in the list (outside of the map), it call the appropriate marker, centres on it and opens the attached infoWindow.
The infoWindow is working on marker click.

function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {
lat: -33.800426,
lng: 142.038494
}
  });
  setMarkers(map);
}

// Data for the markers consisting of a name, a LatLng and a zIndex for     the
// order in which these markers should display on top of each other.

var stores = [
          ['A', -33.771624, 142.888128, 1],
          ['B', -33.843956, 142.994875, 2],
          ['C', -33.818086, 142.995699, 3],
          ['C', -33.812697, 143.229200, 4],
          ];

function setMarkers(map) {
  // Adds markers to the map.
  for (var i = 0; i < stores.length; ++i) {
    var store = stores[i];
    const marker = new google.maps.Marker({
      position: {
        lat: store[1],
        lng: store[2]
      },
      map: map,
      animation: google.maps.Animation.DROP,
      title: store[0],
      zIndex: store[3],
    });
    attachStoreTitle(marker);
  }
}

// Attaches an info window to a marker with the provided message. When         the
// marker is clicked, the info window will open with message.
function attachStoreTitle(marker) {
  var infowindow = new google.maps.InfoWindow({
    content: marker.title
});
marker.addListener('click', function() {
infowindow.open(marker.get('map'), marker);
});
}
initMap()
```

答:
Completed fiddle at https://jsfiddle.net/00e58pba/8/

Attach event listener to markers and then open correct infoWindow -

```<code>  google.maps.event.addListener(marker, 'click', (function(marker, i) {
  return function() {

    // Close all other infoboxes
    for (var j = 0; j < markers.length; j++) {
      markers[j].infobox.close(map);
    }

    // Open correct info box
    markers[i].infobox.open(map, markers[i]);
  }
})(marker, i));
</code>```

Body:
I have been playing around with Google Maps, and would like to center on a marker and open the appropriate infoWindow when I click on an element outside the map.
For example I have;

Store A
Opening Hours: 10-10

Store B
Opening Hours: 10-4

Store C
Opening Hours: 9-9

Store D.
Opening Hours: 8-9

I would like it to work, when I click on one of the stores in the list (outside of the map), it call the appropriate marker, centres on it and opens the attached infoWindow.
The infoWindow is working on marker click.

function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {
lat: -33.800426,
lng: 142.038494
}
  });
  setMarkers(map);
}

// Data for the markers consisting of a name, a LatLng and a zIndex for     the
// order in which these markers should display on top of each other.

var stores = [
          ['A', -33.771624, 142.888128, 1],
          ['B', -33.843956, 142.994875, 2],
          ['C', -33.818086, 142.995699, 3],
          ['C', -33.812697, 143.229200, 4],
          ];

function setMarkers(map) {
  // Adds markers to the map.
  for (var i = 0; i < stores.length; ++i) {
    var store = stores[i];
    const marker = new google.maps.Marker({
      position: {
        lat: store[1],
        lng: store[2]
      },
      map: map,
      animation: google.maps.Animation.DROP,
      title: store[0],
      zIndex: store[3],
    });
    attachStoreTitle(marker);
  }
}

// Attaches an info window to a marker with the provided message. When         the
// marker is clicked, the info window will open with message.
function attachStoreTitle(marker) {
  var infowindow = new google.maps.InfoWindow({
    content: marker.title
});
marker.addListener('click', function() {
infowindow.open(marker.get('map'), marker);
});
}
initMap()

Body:
Completed fiddle at https://jsfiddle.net/00e58pba/8/

Attach event listener to markers and then open correct infoWindow -

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
  return function() {

    // Close all other infoboxes
    for (var j = 0; j < markers.length; j++) {
      markers[j].infobox.close(map);
    }

    // Open correct info box
    markers[i].infobox.open(map, markers[i]);
  }
})(marker, i));


问:
Fatal error: Call to undefined method MongoCursor::toArray()
I want to convert a cursor to array so i see cursor result, for this when i used toArray of mongodb then this error shown

"Fatal error: Call to undefined method MongoCursor::toArray()"

Here is my code:

```<code>$getting_started_collection = $this->getServiceLocator()->get('Common\Collection\ResourcesGettingStarted');
$criteria = array(
    '$or' => array(
        array('affiliate_type' => 'cpl_cpm'),
        array('affiliate_type' => 'cpl')
    )
);
$columns = array(
    '_id' => true,
    'title' => true,
    'description' => true,
    'logo' => true,
    'pdf' => true
);
$cursor = $getting_started_collection->fetchAll($criteria, $columns, true);
$data_array = $cursor->toArray();
echo("```");
print_r($data_array);
die();
```

how i used https://docs.mongodb.com/manual/reference/method/cursor.toArray/ ?

答:
That's because MongoCursor class does not have method called toArray. Here is a list of all available methods- MongoCursor.

You should use iterator_to_array() as in Example #1 in manual:

```<code><?php

$cursor = $collection->find();
var_dump(iterator_to_array($cursor));

?>
</code>```

Source: http://php.net/manual/en/class.mongocursor.php

In your example:

```<code>$cursor = $getting_started_collection->fetchAll($criteria, $columns, true);
$data_array = iterator_to_array($cursor);
echo("```");
print_r($data_array);
die();
```

Body:
I want to convert a cursor to array so i see cursor result, for this when i used toArray of mongodb then this error shown

"Fatal error: Call to undefined method MongoCursor::toArray()"

Here is my code:

$getting_started_collection = $this->getServiceLocator()->get('Common\Collection\ResourcesGettingStarted');
$criteria = array(
    '$or' => array(
        array('affiliate_type' => 'cpl_cpm'),
        array('affiliate_type' => 'cpl')
    )
);
$columns = array(
    '_id' => true,
    'title' => true,
    'description' => true,
    'logo' => true,
    'pdf' => true
);
$cursor = $getting_started_collection->fetchAll($criteria, $columns, true);
$data_array = $cursor->toArray();
echo("
");
print_r($data_array);
die();

how i used https://docs.mongodb.com/manual/reference/method/cursor.toArray/ ?

Body:
That's because MongoCursor class does not have method called toArray. Here is a list of all available methods- MongoCursor.

You should use iterator_to_array() as in Example #1 in manual:

<?php

$cursor = $collection->find();
var_dump(iterator_to_array($cursor));

?>

Source: http://php.net/manual/en/class.mongocursor.php

In your example:

$cursor = $getting_started_collection->fetchAll($criteria, $columns, true);
$data_array = iterator_to_array($cursor);
echo("<pre>");
print_r($data_array);
die();