问:
FCM showing duplicate notification when app is in background
I implemented FCM in my project. Push notification is working as expected, onMessageReceived is called when a notification is received. This is true when app is in the foreground.

However, when the app is in the background, the system tray always display a duplicate notification when one arrives (e.g. when Notification A is received, system tray display 2 Notification A)

How to fix this?

EDIT: added code

I extended FirebaseMessagingService class and have this in the onMessageReceived method

This is the only part in the project where I used NotificationManager.

Also, I tried to add a log on this method. onMessageReceived is called when app is in foreground. It doesn't get called when app is in background

```<code>@Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
    RemoteMessage.Notification notification = remoteMessage.getNotification();

        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String title = notification.getTitle();
        String message = notification.getBody();

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
}
</code>```

答:
Same problem. I modified AndroidManifest.xml because i was requesting permissions to old GCM like this...

```<code><uses-permission android:name="mypackage.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<permission
    android:name="mypackage.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
</code>```

So, removing it from manifest and uninstalling and reinstalling the app my problem was solved.

Body:
I implemented FCM in my project. Push notification is working as expected, onMessageReceived is called when a notification is received. This is true when app is in the foreground.

However, when the app is in the background, the system tray always display a duplicate notification when one arrives (e.g. when Notification A is received, system tray display 2 Notification A)

How to fix this?

EDIT: added code

I extended FirebaseMessagingService class and have this in the onMessageReceived method

This is the only part in the project where I used NotificationManager.

Also, I tried to add a log on this method. onMessageReceived is called when app is in foreground. It doesn't get called when app is in background

@Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
    RemoteMessage.Notification notification = remoteMessage.getNotification();

        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String title = notification.getTitle();
        String message = notification.getBody();

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
}

Body:
Same problem. I modified AndroidManifest.xml because i was requesting permissions to old GCM like this...

<uses-permission android:name="mypackage.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<permission
    android:name="mypackage.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

So, removing it from manifest and uninstalling and reinstalling the app my problem was solved.


来源: stackexchange

问:
oracle regular expression with number matching
I have a table which contains a column 'col1' having values like

```<code>    0.23
    0.0123
   90.013
   23.31
    0.87
  100.013
</code>```

How to get the records whole values matching with any number followed by 0.01 followed by any number in Oracle? I.e.

```<code>  0.0123
 90.013
100.013
</code>```

答:
If you want a number containing 0.01 (zero units, zero tenths and one hundredth) then you do not need regular expressions:

```<code>SELECT *
FROM   your_table
WHERE  INSTR( TO_CHAR( col1, '99999999999999990.00' ), '0.01' ) > 0
</code>```

If you want a number containing .01 (zero tenths and one hundredth) then:

```<code>SELECT *
FROM   your_table
WHERE  INSTR( TO_CHAR( col1, '99999999999999990.00' ), '.01' ) > 0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a table which contains a column 'col1' having values like

    0.23
    0.0123
   90.013
   23.31
    0.87
  100.013

How to get the records whole values matching with any number followed by 0.01 followed by any number in Oracle? I.e.

  0.0123
 90.013
100.013

Body:
If you want a number containing 0.01 (zero units, zero tenths and one hundredth) then you do not need regular expressions:

SELECT *
FROM   your_table
WHERE  INSTR( TO_CHAR( col1, '99999999999999990.00' ), '0.01' ) > 0

If you want a number containing .01 (zero tenths and one hundredth) then:

SELECT *
FROM   your_table
WHERE  INSTR( TO_CHAR( col1, '99999999999999990.00' ), '.01' ) > 0


问:
What's causing this delay when importing libraries?
I'm seeing an issue where the execution of my python script can sometimes take longer to import libraries. This happens if I have not executed the script recently or if I run the script from a different server. After the first delay, the import times become much faster. I was wondering what is causing this slow import and if there is any way to prevent it?

```<code>import time
s_time = time.time()
import sys,re,os,logging,signal
from argparse  import ArgumentParser
print('Internal Import Time: {}'.format(time.time() - s_time))
s_time = time.time()
from backtrace import Backtrace,BacktraceSet
from report    import Report
from core      import Core
from burtapi   import BurtAPI
print('External Import Time: {}'.format(time.time() - s_time))
</code>```

In this example backtrace,report,core, and burtapi are libraries I created.

```<code>[name@server1 tool]$ ./tool --python
Internal Import Time: 2.8281359672546387
External Import Time: 13.053943157196045
Enter/Paste your content. Ctrl-D to save it.
^CYou pressed Ctrl+C!
[name@server1 tool]$ ./tool --python
Internal Import Time: 0.12279081344604492
External Import Time: 0.6948020458221436
Enter/Paste your content. Ctrl-D to save it.
^CYou pressed Ctrl+C!

ssh to different server (with same storage mount)

[name@server2 tool]$ ./tool --python
Internal Import Time: 3.0217390060424805
External Import Time: 13.151482105255127
Enter/Paste your content. Ctrl-D to save it.
^CYou pressed Ctrl+C!
[name@server2 tool]$
</code>```

./tool is a bash script that calls python3 /path/to/script.py

答:
There are more factors here but there are three major ones:

First - importing a module requires finding the modules on your system, which requires reading data from your disk.

Second - with that, if there are any changes done inside those modules, the interpreter would need to bite-compile them.

Last, but not least, when the interpreter starts importing them, the modules themselves might contain instructions/code that needs to be executed which could be performing a lot of operations. Say imagine one of those modules connects to a database or has to filter through a large hashtable...

Edit: I should point out that those are assumptions and it's hard to say what exactly is happening in your case but in most cases this is what's happening.

Body:
I'm seeing an issue where the execution of my python script can sometimes take longer to import libraries. This happens if I have not executed the script recently or if I run the script from a different server. After the first delay, the import times become much faster. I was wondering what is causing this slow import and if there is any way to prevent it?

import time
s_time = time.time()
import sys,re,os,logging,signal
from argparse  import ArgumentParser
print('Internal Import Time: {}'.format(time.time() - s_time))
s_time = time.time()
from backtrace import Backtrace,BacktraceSet
from report    import Report
from core      import Core
from burtapi   import BurtAPI
print('External Import Time: {}'.format(time.time() - s_time))

In this example backtrace,report,core, and burtapi are libraries I created.

[name@server1 tool]$ ./tool --python
Internal Import Time: 2.8281359672546387
External Import Time: 13.053943157196045
Enter/Paste your content. Ctrl-D to save it.
^CYou pressed Ctrl+C!
[name@server1 tool]$ ./tool --python
Internal Import Time: 0.12279081344604492
External Import Time: 0.6948020458221436
Enter/Paste your content. Ctrl-D to save it.
^CYou pressed Ctrl+C!

ssh to different server (with same storage mount)

[name@server2 tool]$ ./tool --python
Internal Import Time: 3.0217390060424805
External Import Time: 13.151482105255127
Enter/Paste your content. Ctrl-D to save it.
^CYou pressed Ctrl+C!
[name@server2 tool]$

./tool is a bash script that calls python3 /path/to/script.py


问:
Update/Replace with a substring - triple backslashes
I have a column full of duplicate filepaths:

```<code>\\C:\298788\DOC1\SUB1\\\C:\298788\DOC1\SUB1\FILE.txt
\\C:\298788\DOC1\SUB1\\\C:\298788\DOC1\SUB1\FILE.txt
\\C:\298788\DOC1\SUB1\\\C:\298788\DOC1\SUB1\FILE.txt
</code>```

I need only the second part of the string ie. C:\298788\DOC1\SUB1\FILE.txt

How do I replace up to the triple backslashes with nothing. I have tried:

```<code>UPDATE [TABLE].[dbo].[ColumnName]
SET [ColumnName] = REPLACE([ColumnName], '%\\\', '');
</code>```

It says all rows updated however nothing has changed. Assuming its something to do with the backslashes.

Using SQL SERVER 2012.

Body:
I have a column full of duplicate filepaths:

\\C:\298788\DOC1\SUB1\\\C:\298788\DOC1\SUB1\FILE.txt
\\C:\298788\DOC1\SUB1\\\C:\298788\DOC1\SUB1\FILE.txt
\\C:\298788\DOC1\SUB1\\\C:\298788\DOC1\SUB1\FILE.txt

I need only the second part of the string ie. C:\298788\DOC1\SUB1\FILE.txt

How do I replace up to the triple backslashes with nothing. I have tried:

UPDATE [TABLE].[dbo].[ColumnName]
SET [ColumnName] = REPLACE([ColumnName], '%\\\', '');

It says all rows updated however nothing has changed. Assuming its something to do with the backslashes.

Using SQL SERVER 2012.

Body:
Using stuff()

select col = stuff(col,1,charindex('\\\',col,2)+2,'')
from tbl

rextester demo: http://rextester.com/QRKWP8606

returns:

+------------------------------+
|             col              |
+------------------------------+
| C:\298788\DOC1\SUB1\FILE.txt |
| C:\298788\DOC1\SUB1\FILE.txt |
| C:\298788\DOC1\SUB1\FILE.txt |
+------------------------------+

as an update:

update tbl
  set col = stuff(col,1,charindex('\\\',col,2)+2,'')
where charindex('\\\',col,2)>0


问:
How to get data from API using curl?
(I am new to curl and also apigee)

I am trying to get the Body data from API

"https://staging.api.pearson.com/content/scapi/urn:pearson:manifestation:014f333d-ceda-476f-81f2-d3d6c89ace42"

using curl with following command but unable to get any data than fault string

curl "https://staging.api.pearson.com/content/scapi/urn:pearson:manifestation:014f333d-ceda-476f-81f2-d3d6c89ace42"

Error that I am getting is :

```<code>{"fault":{"faultstring":"Failed to resolve API Key variable request.header.x-api key","detail":"errorcode":"steps.oauth.v2.FailedToResolveAPIKey"}}}
</code>```

but when accessing the URL multiple times in Browser, I can able to get JSON data as desired

CURL woking code

```<code>curl "https://staging.api.pearson.com/content/scapi/urn:pearson:manifestation:014f333d-ceda-476f-81f2-d3d6c89ace42" -H "Accept:application/json"  -H "Accept-Encoding:gzip, deflate, sdch, br" -H "Accept-Language:en-US,en;q=0.8 " -H "Connection:keep-alive" -H "Host:staging.api.pearson.com" -H "X-ApiKey:7ij8zrLkCNR9DtAXx3KJ6yutoYnk4SAx" -H "X-PearsonSSOSession:AQIC5wM2LY4Sfczr6fmuhzvfN4dwnpK3c9K8tyduHkwg7sA.*AAJTSQACMDIAAlNLABQtNTk5Nzg3OTI1MTgxNTYxNjE3MAACUzEAAjAx*"
</code>```

Kindly somebody suggest to get JSON data

Sorry I am new to curl and also apigee

Thanks

答:
```<code>curl "URL" \
 -H "Accept: application/json" \
 -H "x-apikey: {need to pass your API key here}" \
 -H "Content-Type: application/octet-stream"
</code>```

Put your x-apikey in {need to pass your API key here}

Title: How to get data from API using curl?

Body:
(I am new to curl and also apigee)

I am trying to get the Body data from API

"https://staging.api.pearson.com/content/scapi/urn:pearson:manifestation:014f333d-ceda-476f-81f2-d3d6c89ace42"

using curl with following command but unable to get any data than fault string

curl "https://staging.api.pearson.com/content/scapi/urn:pearson:manifestation:014f333d-ceda-476f-81f2-d3d6c89ace42"

Error that I am getting is :

{"fault":{"faultstring":"Failed to resolve API Key variable request.header.x-api key","detail":"errorcode":"steps.oauth.v2.FailedToResolveAPIKey"}}}

but when accessing the URL multiple times in Browser, I can able to get JSON data as desired

CURL woking code

curl "https://staging.api.pearson.com/content/scapi/urn:pearson:manifestation:014f333d-ceda-476f-81f2-d3d6c89ace42" -H "Accept:application/json"  -H "Accept-Encoding:gzip, deflate, sdch, br" -H "Accept-Language:en-US,en;q=0.8 " -H "Connection:keep-alive" -H "Host:staging.api.pearson.com" -H "X-ApiKey:7ij8zrLkCNR9DtAXx3KJ6yutoYnk4SAx" -H "X-PearsonSSOSession:AQIC5wM2LY4Sfczr6fmuhzvfN4dwnpK3c9K8tyduHkwg7sA.*AAJTSQACMDIAAlNLABQtNTk5Nzg3OTI1MTgxNTYxNjE3MAACUzEAAjAx*"

Kindly somebody suggest to get JSON data

Sorry I am new to curl and also apigee

Thanks

Body:
curl "URL" \
 -H "Accept: application/json" \
 -H "x-apikey: {need to pass your API key here}" \
 -H "Content-Type: application/octet-stream"

Put your x-apikey in {need to pass your API key here}


问:
catching button clicks in javascript without server interaction
I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.

Currently my JavaScript code for this is as follows:

```<code>    function toggleShowPassword() {
        var button = $get('PASSWORD_TEXTBOX_ID');
        var password;
        if (button)
        {
            password = button.value;
            alert(password);
            button.value = password;
        }
   }
</code>```

The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.

My questions are:

Why does the password field keep getting reset with each button click?

How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text?

答:
I would assume that the browser has some issue with the script attempting to set the value of a password field:

```<code>button.value = password;
</code>```

This line of code has no real purpose. password.value is not affected in the previous lines where you are reading the value and using it in the alert().

This should be a simpler version of your code:

```<code>function toggleShowPassword() {
    var button = $get('PASSWORD_TEXTBOX_ID');
    if (button)
    {
        alert(button.value);
    }
</code>```

}

edit: actually I just did a quick test, and Firefox has no problem setting the password field's value with code such as button.value = "blah". So it doesn't seem like this would be the case ... I would check if your ASP.NET code is causing a postback as others have suggested.

OwnerDisplayName: eviljack

Body:
I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.

Currently my JavaScript code for this is as follows:

    function toggleShowPassword() {
        var button = $get('PASSWORD_TEXTBOX_ID');
        var password;
        if (button)
        {
            password = button.value;
            alert(password);
            button.value = password;
        }
   }

The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.

My questions are:

Why does the password field keep getting reset with each button click?

How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text?

Body:
I would assume that the browser has some issue with the script attempting to set the value of a password field:

button.value = password;

This line of code has no real purpose. password.value is not affected in the previous lines where you are reading the value and using it in the alert().

This should be a simpler version of your code:

function toggleShowPassword() {
    var button = $get('PASSWORD_TEXTBOX_ID');
    if (button)
    {
        alert(button.value);
    }

}

edit: actually I just did a quick test, and Firefox has no problem setting the password field's value with code such as button.value = "blah". So it doesn't seem like this would be the case ... I would check if your ASP.NET code is causing a postback as others have suggested.

OwnerDisplayName: matt b

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: matt b


问:
How to store a list in a db column
I would like to store an object FOO in a database.
Lets say FOO contains three integers and a list of "Fruits".

The list can have any length, the only thing I know is that the all the fruits allowed are stored in another table.

Can I store the fruit list in a column?

答:
If you're quite sure of what you're doing (ie. you won't need to look up the list's values, for example), you could also serialize your object, or just the list object, and store it in a binary column.

Just character-separating the values may be fine too, and cheaper in terms of saving and loading, but be careful your data doesn't contain the separator character, or escape it (and handle the escapes accordingly while loading, etc... Your language of choice may do a better job at this than you, though. ;) )

However, for a "proper" solution, do what Mehrdad described above.

OwnerDisplayName: Stumproot

Title: How to store a list in a db column

OwnerDisplayName: AKX


问:
BGP status UP/DOWN counter SNMP Monitoring
I have cisco 6509 for BGP with upstream providers, also have SNMP Monitoring server Solarwinds in my network.

I need to monitor BGP Up/Down counter, like if BGP status Up/Down timer is less then or equal to 5 Minutes SNMP server trigger an alert

Like in below, one of my peer was down and restored after an intermittent flap, interfaces are already in monitoring but due to high CPU during route receiving/learning SNMP goes timeout.

Neighbor V       AS MsgRcvd MsgSent   TblVer  InQ OutQ Up/Down  State/PfxRcd

2.2.2.1  4       22222 2129685 2077555   107685    0    0 3w5d            0

3.3.3.1  4       33333 12052862  229372   107685    0    0 00:11:45     3045

So, let router do what he is doing at time of flap, i need my SNMP server to send alert when he get BGP UP/DOWN timer <=5,  and i am unable to find OID for this attribute.

Please help

Thanks

答:
You can try two approaches, both based on CISCO-BGP4-MIB:

If your Solarwinds server can receive snmp traps and alert on them, than configure router to send snmp notifications (snmp traps) to Solarwind server on BGP state changes. For bgp monitoring these traps may work for you: cbgpFsmStateChange, cbgpBackwardTransition, cbgpPeer2EstablishedNotification, cbgpPeer2BackwardTransNotification, cbgpPeer2FsmStateChange, cbgpPeer2BackwardTransition (see detailed description in MIB, supported traps may depend on IOS version on router).

Configure Solarwinds to do snmp poll of OIDs from CISCO-BGP4-MIB::cbgpPeer2Table, in particular, cbgpPeer2State, cbgpPeer2PrevState,cbgpPeer2FsmEstablishedTransitions, cbgpPeer2FsmEstablishedTime and alert appropriately.

Similar OIDs for polling and traps for notifications can also be found in BGP4-MIB.


问:
Broblem in ACTION_CALL code in android studio m
my program stopped when i click on callbutton what is the problem

```<code>public void callbutton(View v) {  try{
             intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:111*"+phone+"#"));
            startActivity(intent);
            }catch (ActivityNotFoundException e){
                Toast.makeText(data.this, "noooo", Toast.LENGTH_SHORT).show();

            }}
</code>```

**i Wrote the permission in manifests   **

```<code><uses-permission android:name="android.permission.CALL_PHONE" />
</code>```

答:
On API 23 or higher: you most use this code:

```<code>public void calling(String phoneNumber) {
    Intent intent = new Intent(Intent.ACTION_CALL);
    intent.setData(Uri.parse(phoneNumber));
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}
</code>```

OR::

```<code>public void callind(String phone) {
    Intent callIntent = new Intent(Intent.ACTION_CALL); //use ACTION_CALL class
    callIntent.setData(Uri.parse(phone));    //this is the phone number calling
    //check permission
    //If the device is running Android 6.0 (API level 23) and the app's targetSdkVersion is 23 or higher,
    //the system asks the user to grant approval.
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        //request permission from user if the app hasn't got the required permission
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CALL_PHONE},   //request specific permission from user
                10);
        return;
    }else {     //have got permission
        try{
            startActivity(callIntent);  //call activity and make phone call
        }
        catch (android.content.ActivityNotFoundException ex){
            Toast.makeText(getApplicationContext(), "did not work", Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

On API 23 and less: you can use this code:

```<code>public void callind(String phoneNumber) {
    Intent intent = new Intent(Intent.ACTION_CALL);
    intent.setData(Uri.parse(phoneNumber));
        startActivity(intent);
    }
}
</code>```

in tow ways you have to  add manifests permission:

```<code><uses-permission android:name="android.permission.CALL_PHONE" />
</code>```

Body:
my program stopped when i click on callbutton what is the problem

public void callbutton(View v) {  try{
             intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:111*"+phone+"#"));
            startActivity(intent);
            }catch (ActivityNotFoundException e){
                Toast.makeText(data.this, "noooo", Toast.LENGTH_SHORT).show();

            }}

**i Wrote the permission in manifests   **

<uses-permission android:name="android.permission.CALL_PHONE" />

Body:
On API 23 or higher: you most use this code:

public void calling(String phoneNumber) {
    Intent intent = new Intent(Intent.ACTION_CALL);
    intent.setData(Uri.parse(phoneNumber));
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

OR::

public void callind(String phone) {
    Intent callIntent = new Intent(Intent.ACTION_CALL); //use ACTION_CALL class
    callIntent.setData(Uri.parse(phone));    //this is the phone number calling
    //check permission
    //If the device is running Android 6.0 (API level 23) and the app's targetSdkVersion is 23 or higher,
    //the system asks the user to grant approval.
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        //request permission from user if the app hasn't got the required permission
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CALL_PHONE},   //request specific permission from user
                10);
        return;
    }else {     //have got permission
        try{
            startActivity(callIntent);  //call activity and make phone call
        }
        catch (android.content.ActivityNotFoundException ex){
            Toast.makeText(getApplicationContext(), "did not work", Toast.LENGTH_SHORT).show();
        }
    }
}

On API 23 and less: you can use this code:

public void callind(String phoneNumber) {
    Intent intent = new Intent(Intent.ACTION_CALL);
    intent.setData(Uri.parse(phoneNumber));
        startActivity(intent);
    }
}

in tow ways you have to  add manifests permission:

<uses-permission android:name="android.permission.CALL_PHONE" />


问:
Open third party extension with TYPO3 extension builder
There is a custom TYPO3 extension in our installation which was obviously bootstrapped using the TYPO3 extension builder. But I cant access it using the "load" button.

Where do I tell the extension builder that he is in charge of this extension?

The original developer of the extension is no longer available.

答: The ExtensionBuilder search for an ExtensionBuilder.json file in the extension directory. Here are all settings for the extension and models defined. Without this file the ExtensionBuilder doesn't know how the extension was created and which domain models and their fields exist or are defined. So you can't edit an Extension without this file in the ExtensionBuilder


问:
How can i change Kendo UI for angular default styles
I want to change the styles from the default datepicker to something like the second image. Is there a way to acomplish that?

答: You can biuld your own theme and check out what telerik already done at kendo-ui theme builder</p>


问:
Liquibase config file content?
I am trying to integrate Liquibase for my current project. I have read the Quick Start Guide and the Documentation pages. I want to use it via it's API. When i run it like they say on the site, it complains about a missing config file. So i have created the liquibaseConfig.yml. But the system still complains the file does not exist, but it is there. What content should the config file have? Here is how i call the liquibase API:</p>

```<code>Database database = DatabaseFactory.getInstance()
        .findCorrectDatabaseImplementation(new JdbcConnection(connection));

  Liquibase liquibase = new liquibase.Liquibase(DEFAULT_LIQUIBASE_CONFIGFILE, new ClassLoaderResourceAccessor(),
        database);

  liquibase.update(new Contexts(), new LabelExpression());
</code>```

答:
To answer my own question the solution lies in the RessourceAccessor type. I changed it to FileSystemResourceAccessor and it works.</p>

```<code>Liquibase liquibase = new liquibase.Liquibase(DEFAULT_LIQUIBASE_CONFIGFILE, new FileSystemResourceAccessor(),
        database);
</code>```

Title: Liquibase config file content?

Body:
I am trying to integrate Liquibase for my current project. I have read the Quick Start Guide and the Documentation pages. I want to use it via it's API. When i run it like they say on the site, it complains about a missing config file. So i have created the liquibaseConfig.yml. But the system still complains the file does not exist, but it is there. What content should the config file have? Here is how i call the liquibase API:

Database database = DatabaseFactory.getInstance()
        .findCorrectDatabaseImplementation(new JdbcConnection(connection));

  Liquibase liquibase = new liquibase.Liquibase(DEFAULT_LIQUIBASE_CONFIGFILE, new ClassLoaderResourceAccessor(),
        database);

  liquibase.update(new Contexts(), new LabelExpression());

Body:
To answer my own question the solution lies in the RessourceAccessor type. I changed it to FileSystemResourceAccessor and it works.

Liquibase liquibase = new liquibase.Liquibase(DEFAULT_LIQUIBASE_CONFIGFILE, new FileSystemResourceAccessor(),
        database);


问:
Are there specific consequences of modifying a parent Array from a child component?
It is possible to modify parents properties from within a child component when the props are an Array:

Vue.component('search-box', {
  template: '#search-box-template',
  props: ['who']
})
var vm = new Vue({
  el: '#root',
  data: {
    who: ['a', 'b']
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>

<div id="root">
  who as seen by the parent: {{who}}
  <search-box v-bind:who="who"></search-box>
</div>

<template id="search-box-template">
    <div>
        who as seen by the child: {{who}}
    <button v-on:click="who.push('x')">modify who from within the child</button>
    </div>
</template></code>```

Beside the intended action to modify the parent from a child (which may be, style wise, a bad thing to do) - are there collateral consequences of doing so, ones which would break Vue.js?

答:
You will not "break Vue" by breaking encapsulation, and that's what updating a component's data items from outside the component is. The docs say

it is also very important to keep the parent and the child as
decoupled as possible via a clearly-defined interface. This ensures
each component’s code can be written and reasoned about in relative
isolation, thus making them more maintainable and potentially easier
to reuse.

That is the rationale: it's good programming, not a matter of being something Vue cannot handle.

Body:
It is possible to modify parents properties from within a child component when the props are an Array:

Vue.component('search-box', {
  template: '#search-box-template',
  props: ['who']
})
var vm = new Vue({
  el: '#root',
  data: {
    who: ['a', 'b']
  }
})

  who as seen by the parent: {{who}}
  <search-box v-bind:who="who"></search-box>

<template id="search-box-template">

        who as seen by the child: {{who}}
    <button v-on:click="who.push('x')">modify who from within the child</button>

</template>

Beside the intended action to modify the parent from a child (which may be, style wise, a bad thing to do) - are there collateral consequences of doing so, ones which would break Vue.js?

ContentLicense: CC BY-SA 4.0


问:
Unable to connect to a remote server using JMX connection in visualvm from Docker
I am using visualvm tool and trying to connect to my remote server ubuntu(14.04). In ubuntu my application is running on Docker. The Dockerfile looks like-

```<code>FROM anapsix/alpine-java:8_jdk
MAINTAINER user
ENV OFFLINE_DB_USERNAME abc123
ENV OFFLINE_DB_URL jdbc:mysql://x.x.x.x:xxxx/%s?useLegacyDatetimeCode=false&useTimezone=true&serverTimezone=UTC
ENV OFFLINE_DB_SERVER_URL jdbc:mysql://x.x.x.x:xxxx/offlineserver?useLegacyDatetimeCode=false&useTimezone=true&serverTimezone=UTC
ENV OFFLINE_DB_PASSWORD password123
CMD ["java", "-Dcom.sun.management.jmxremote","-Dcom.sun.management.jmxremote.port=9990", "-Dcom.sun.management.jmxremote.rmi.port=9991" "-Dcom.sun.management.jmxremote.local.only=false", "-Dcom.sun.management.jmxremote.authenticate=false","-Dcom.sun.management.jmxremote.ssl=false", "-Djava.rmi.server.hostname=x.x.x.x"
COPY sampleproject.jar /home/ubuntu/test/sampleproject.jar
CMD ["java","-jar","/home/ubuntu/test/sampleproject.jar"]
Expose 9990
</code>```

I executed the below command to check whether port:9990 is listening or not. It showed following output-

```<code>$ netstat -lp | grep 9990
tcp6       0      0 [::]:9990               [::]:*                  LISTEN      1666/docker-proxy
</code>```

But on trying to connect to a remote server with hostname:port(x.x.x.x:9990) i am getting the error as -Cannot connect to x.x.x.x:9990 using service:jmx:rmi:///jndi/rmi://x.x.x.x:9990/jmxrmi.

答:
It matters how you create a container from Docker image.

If you want to expose port for connecting from outside of container then you need to pass next to your docker run command:

```<code>-p 9990:9990
</code>```

Body:
I am using visualvm tool and trying to connect to my remote server ubuntu(14.04). In ubuntu my application is running on Docker. The Dockerfile looks like-

FROM anapsix/alpine-java:8_jdk
MAINTAINER user
ENV OFFLINE_DB_USERNAME abc123
ENV OFFLINE_DB_URL jdbc:mysql://x.x.x.x:xxxx/%s?useLegacyDatetimeCode=false&useTimezone=true&serverTimezone=UTC
ENV OFFLINE_DB_SERVER_URL jdbc:mysql://x.x.x.x:xxxx/offlineserver?useLegacyDatetimeCode=false&useTimezone=true&serverTimezone=UTC
ENV OFFLINE_DB_PASSWORD password123
CMD ["java", "-Dcom.sun.management.jmxremote","-Dcom.sun.management.jmxremote.port=9990", "-Dcom.sun.management.jmxremote.rmi.port=9991" "-Dcom.sun.management.jmxremote.local.only=false", "-Dcom.sun.management.jmxremote.authenticate=false","-Dcom.sun.management.jmxremote.ssl=false", "-Djava.rmi.server.hostname=x.x.x.x"
COPY sampleproject.jar /home/ubuntu/test/sampleproject.jar
CMD ["java","-jar","/home/ubuntu/test/sampleproject.jar"]
Expose 9990

I executed the below command to check whether port:9990 is listening or not. It showed following output-

$ netstat -lp | grep 9990
tcp6       0      0 [::]:9990               [::]:*                  LISTEN      1666/docker-proxy

But on trying to connect to a remote server with hostname:port(x.x.x.x:9990) i am getting the error as -Cannot connect to x.x.x.x:9990 using service:jmx:rmi:///jndi/rmi://x.x.x.x:9990/jmxrmi.

Body:
It matters how you create a container from Docker image.

If you want to expose port for connecting from outside of container then you need to pass next to your docker run command:

-p 9990:9990


问:
searching a 2d array in python - best method + indentation error
I have created the following 2d array (list of lists) in Python:

```<code>#creating a 2d array (3 rows by 7 columns) and populating it with numbers
matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
rows=len(matrix) #finding the max number of rows in the matrix, in this case 3
columns=len(matrix[0]) #finding the max number of columns in each row, 7 in this case
</code>```

I am trying to search for a specific element in the array (say the number 9), and then print "found", if found, and "not found", if not in the array, with the following code:

```<code>number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
else:
  print("not found")
</code>```

The output however, is erroneous:

```<code>>>What number are you looking for? 9
>>Found it!
>>not found
</code>```

I have two questions: 1. could someone please explain identatation clearly, with reference to this problem and why the second "not found" always is output.
2. Is there a better more efficient way to do this, without the use of numpy

*note, this is not a duplicate, as I have searched the other entries and they don't quite deal with what I am explicitly asking.

repl.it here:
https://repl.it/IcJ3/3

Someone just suggested an answer as below: (I had already tried this)

https://repl.it/IcJ3/5
Note, it doesn't work at all either:

```<code>number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
        else:
          print("not found")
</code>```

Erroneous output, still!

```<code>What number are you looking for? 9
not found
not found
not found
not found
not found
not found
not found
not found
Found it!
not found
not found
not found
not found
not found
not found
not found
</code>```

答:
This should do what you require!

```<code>matrix=[[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]]
x = 93
bool_value = [True if x in mat else False for mat in matrix]
print('Found' if any(bool_value) else 'Not found')
</code>```

Note: any() returns True if atleast one value in the list is true.
Also in python indentations act as block seperators
For example in c/c++

```<code>if(condition){
 do a thing
}
else{
do something else
}
</code>```

But in python indentations act as block seperators

```<code>if (condition):
    do a thing
else:
    do something else
</code>```

where four whitespaces or a tab acts as block seperators. So if I were to represent the whitespaces with + (This is just for understanding purposes)

```<code>if (condition):
++++do a thing
else:
++++if (another_condition):
++++++++do_stuff
++++else:
++++++++do_some_other_stuff
print("Exited from nested if/else loops")
</code>```

You get the idea right? And indentation isn't proper in your code that's why every time not found is printed.

EDIT: As mentioned in comments [True if x in mat else False for mat in matrix] can be written as [x in mat for mat in matrix] But i will leave it as it is for your understanding since you are new to python.

Body:
I have created the following 2d array (list of lists) in Python:

#creating a 2d array (3 rows by 7 columns) and populating it with numbers
matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
rows=len(matrix) #finding the max number of rows in the matrix, in this case 3
columns=len(matrix[0]) #finding the max number of columns in each row, 7 in this case

I am trying to search for a specific element in the array (say the number 9), and then print "found", if found, and "not found", if not in the array, with the following code:

number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
else:
  print("not found")

The output however, is erroneous:

>>What number are you looking for? 9
>>Found it!
>>not found

I have two questions: 1. could someone please explain identatation clearly, with reference to this problem and why the second "not found" always is output.
2. Is there a better more efficient way to do this, without the use of numpy

*note, this is not a duplicate, as I have searched the other entries and they don't quite deal with what I am explicitly asking.

repl.it here:
https://repl.it/IcJ3/3

Someone just suggested an answer as below: (I had already tried this)

https://repl.it/IcJ3/5
Note, it doesn't work at all either:

number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
        else:
          print("not found")

Erroneous output, still!

What number are you looking for? 9
not found
not found
not found
not found
not found
not found
not found
not found
Found it!
not found
not found
not found
not found
not found
not found
not found

Body:
This should do what you require!

matrix=[[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]]
x = 93
bool_value = [True if x in mat else False for mat in matrix]
print('Found' if any(bool_value) else 'Not found')

Note: any() returns True if atleast one value in the list is true.
Also in python indentations act as block seperators
For example in c/c++

if(condition){
 do a thing
}
else{
do something else
}

But in python indentations act as block seperators

if (condition):
    do a thing
else:
    do something else

where four whitespaces or a tab acts as block seperators. So if I were to represent the whitespaces with + (This is just for understanding purposes)

if (condition):
++++do a thing
else:
++++if (another_condition):
++++++++do_stuff
++++else:
++++++++do_some_other_stuff
print("Exited from nested if/else loops")

You get the idea right? And indentation isn't proper in your code that's why every time not found is printed.

EDIT: As mentioned in comments [True if x in mat else False for mat in matrix] can be written as [x in mat for mat in matrix] But i will leave it as it is for your understanding since you are new to python.


问:
replace part of href between 2 words jquery
This is simple and I have done it before but can't make it work right now.

I need to change the name of the image in below href

var href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg"

$('.share, .share-2').prop('href', function () {
    $(this).replace(/(picture=).*?(&)/,'$1' + imgNew + '$2');
});
```

答:
Since the href string is a URL, you can take advantage of the URL object.

var imgNew = 'http://example.com/img.png';
var href = "https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg";
var url = new URL(href);
url.searchParams.set('picture', imgNew);
console.log(url.href);```

Note that not all browsers are supported at this time, so you can use a polyfill.

Body:
Since the href string is a URL, you can take advantage of the URL object.

var imgNew = 'http://example.com/img.png';
var href = "https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg";
var url = new URL(href);
url.searchParams.set('picture', imgNew);
console.log(url.href);

Note that not all browsers are supported at this time, so you can use a polyfill.


问:
Sql server Query to Select Isolated rows
hi i am using Sql server Query to Select Isolated rows,
I am giving TicketEsclationID and TicketEsclationSubcategoryID and i want to select connected UserInfoUserID and SeniorUserInfoUserID.

For example if i give UserInfoUserID as 2020 the rest rows should populated

below is the screen shot of same

答:
If i understand correctly you are trying to do this?</p>

```<code>Select top (1) with ties * from yourtable
    order by row_number() over(partition by TicketEsclationId, TicketEsclationSubCategoryId order by SeniorUserInfoUserId desc)
</code>```

Body:
If i understand correctly you are trying to do this?

Select top (1) with ties * from yourtable
    order by row_number() over(partition by TicketEsclationId, TicketEsclationSubCategoryId order by SeniorUserInfoUserId desc)


问:
After changing the url in .htaccess php is not working
I changed this url
 http://localhost/rozgar/job.php?search=Testing%201&id=43
 to this
http://localhost/rozgar/job/Testing%201/43
by using .htaccess

```<code>RewriteRule ^job/([A-Za-z]+) job.php?id=$1&search=$2
</code>```

Link is working fine but php is not loading data from database it's showing me error..

```<code>    <?php
include "inc/db.php";
$id = @$_GET['id'];
$search = @$_GET['search'];
session_start();
$email = @$_SESSION['email'];

  $id=@$_GET['id'];
  $query="select * from company,jobs where company.id = jobs.company_id AND jobs.id = '$id'";
$run=mysqli_query($db,$query);

while ($row = mysqli_fetch_assoc($run)) {
}
</code>```

答:
Just create .htaccess like this </p>

```<code>RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/]+)/?$ $1.php [L]

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ job.php?id=$1&search=$2 [L,QSA]
</code>```

<p>And Now get the get variable in job.php </p>

Body:
I changed this url
 http://localhost/rozgar/job.php?search=Testing%201&id=43
 to this
http://localhost/rozgar/job/Testing%201/43
by using .htaccess

RewriteRule ^job/([A-Za-z]+) job.php?id=$1&search=$2

Link is working fine but php is not loading data from database it's showing me error..

    <?php
include "inc/db.php";
$id = @$_GET['id'];
$search = @$_GET['search'];
session_start();
$email = @$_SESSION['email'];

  $id=@$_GET['id'];
  $query="select * from company,jobs where company.id = jobs.company_id AND jobs.id = '$id'";
$run=mysqli_query($db,$query);

while ($row = mysqli_fetch_assoc($run)) {
}

Body:
Just create .htaccess like this

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/]+)/?$ $1.php [L]

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ job.php?id=$1&search=$2 [L,QSA]

And Now get the get variable in job.php


问:
What is the gold standard for creating a main() loop that waits for a Thread in Java
I was tasked to write a small server application. It is supposed to be started via the console and then run in the background, processing some network traffic and calculating stuff locally until it receives a shutdown signal. I am pretty sure i can handle all of that - except the very basic application architecture. I am super unsure how to bring my main loop to wait for the application to finish. So here is my current code, cleaned up and omitting unnecessary parts.

```<code>public class TestServer {

public static Logger logger;
private static Boolean abortStartup = false;
private static ServerModule server;

public static void main(String[] args) {
    System.out.println("Starting Server...");
        initializeServer(); //this function reads config file, and initializes all variables and stuff. If anything goes wrong, abortStartup is set to true

        if (!abortStartup) {
            runMainLoop();
        }

        if (!abortStartup) {
            cleanup(); //clean up all initialized variables and objects
        }

    System.out.println("Goodbye.");
}

private static void runMainLoop() {
    //This is the main loop. Run this until application terminates.
    logger.log(null, "Starting main loop...", Logger.LOGLEVEL_NOTE);
        server.run();
        while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }
        }
    logger.log(null, "Done.", Logger.LOGLEVEL_NOTE);
}
</code>```

ServerModule looks like this:

```<code>public class ServerModule{

public Boolean shutdown = false;
private Boolean stayAlive = true;

public ServerModule(){
    //setup everything
}

public void run() {
    //initalize timers, instantiate objects etc.. add listeners and everything. At some point, a network message will set stayAlive to false;
}

public Boolean isAlive() {
    return stayAlive;
}
</code>```

Now for the actual question: is there a more elegant or more efficient way to go about this? i am talking about this part specifically:

```<code>while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }
</code>```

Is thread.sleep okay here? Could or should i even omit it? I want to wait here at this very point of my code, so i can clean up after execution stops.

答:
It depends on how you're managing your threads.

At the lowest level Java thread API, your main thread can wait for the server thread to complete with:

```<code>serverThread.join();
</code>```

Look at the Thread API for more options, such as putting a timeout on the join() (so you can take increasingly drastic measures to make it end).

Higher level threading abstractions such as Executor, Future, ForkJoinTask etc. give you the same ability with different APIs. A thorough exploration of these is beyond the scope of a SO answer -- Oracle has tutorials on concurrency, or there are books.

Body:
I was tasked to write a small server application. It is supposed to be started via the console and then run in the background, processing some network traffic and calculating stuff locally until it receives a shutdown signal. I am pretty sure i can handle all of that - except the very basic application architecture. I am super unsure how to bring my main loop to wait for the application to finish. So here is my current code, cleaned up and omitting unnecessary parts.

public class TestServer {

public static Logger logger;
private static Boolean abortStartup = false;
private static ServerModule server;

public static void main(String[] args) {
    System.out.println("Starting Server...");
        initializeServer(); //this function reads config file, and initializes all variables and stuff. If anything goes wrong, abortStartup is set to true

        if (!abortStartup) {
            runMainLoop();
        }

        if (!abortStartup) {
            cleanup(); //clean up all initialized variables and objects
        }

    System.out.println("Goodbye.");
}

private static void runMainLoop() {
    //This is the main loop. Run this until application terminates.
    logger.log(null, "Starting main loop...", Logger.LOGLEVEL_NOTE);
        server.run();
        while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }
        }
    logger.log(null, "Done.", Logger.LOGLEVEL_NOTE);
}

ServerModule looks like this:

public class ServerModule{

public Boolean shutdown = false;
private Boolean stayAlive = true;

public ServerModule(){
    //setup everything
}

public void run() {
    //initalize timers, instantiate objects etc.. add listeners and everything. At some point, a network message will set stayAlive to false;
}

public Boolean isAlive() {
    return stayAlive;
}

Now for the actual question: is there a more elegant or more efficient way to go about this? i am talking about this part specifically:

while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }

Is thread.sleep okay here? Could or should i even omit it? I want to wait here at this very point of my code, so i can clean up after execution stops.

Body:
It depends on how you're managing your threads.

At the lowest level Java thread API, your main thread can wait for the server thread to complete with:

serverThread.join();

Look at the Thread API for more options, such as putting a timeout on the join() (so you can take increasingly drastic measures to make it end).

Higher level threading abstractions such as Executor, Future, ForkJoinTask etc. give you the same ability with different APIs. A thorough exploration of these is beyond the scope of a SO answer -- Oracle has tutorials on concurrency, or there are books.


问:
Sitecore compare items version programmatically
Lets suppose I have an Item with 5 versions. (I am not talking about language versions).

I would like to compare all the versions to identify the differencies. Is there some thing available out of box from Sitecore to do this task? Or I have have to loop over all the versions and then all the fields to find the differences.

答:
No, there is nothing like that out of the box. You will have to compare fields one by one.

Remember that some of the fields should be ignored (like __Updated, __ValidFrom, __Workflow State, etc).

Remember that it's not easy to display what was changed in Blob fields.

And here is a code for you to start with:

FieldCollection fields = version1.Fields;
fields.ReadAll();
fields.Sort();
foreach (Field field1 in fields)
{
    if (field1.ShouldBeTranslated)
    {
        Field field2 = version2.Fields[field1.ID];
        var value1 = field1.Value;
        var value2 = field2.Value;
        ... // whatever you need here
```

Make sure you add all the necessary null checks! I skipped them for the clarity.

Body:
No, there is nothing like that out of the box. You will have to compare fields one by one.

Remember that some of the fields should be ignored (like __Updated, __ValidFrom, __Workflow State, etc).

Remember that it's not easy to display what was changed in Blob fields.

And here is a code for you to start with:

FieldCollection fields = version1.Fields;
fields.ReadAll();
fields.Sort();
foreach (Field field1 in fields)
{
    if (field1.ShouldBeTranslated)
    {
        Field field2 = version2.Fields[field1.ID];
        var value1 = field1.Value;
        var value2 = field2.Value;
        ... // whatever you need here

Make sure you add all the necessary null checks! I skipped them for the clarity.


问:
Processing alternate element in for loop without using index value
I have list of elements with dictionary, for simplicity I have written them as strings:

```<code>ls = ['element1', 'element2', 'element3', 'element4', 'element5', 'element6', 'element7', 'element8', 'element9', 'element10']
</code>```

I am trying to process pair of element from list as follow:

```<code>#m1. Step for loop by size two with if condition
for x in ls:
    if ls.index(x)%2 == 0:
        # my code to be process
        print(x) # for simplicity I just printed element

#m2. tried another way like below:
for x in range(0, len(ls), 2):
    # this way give me output of alternate element from list
    print(ls[x])
</code>```

Is there any way to get only alternate elements while iterating the list items in m1 just like m2?

答:
You can use itertools.islice with a step of 2:

```<code>import itertools

for item in itertools.islice(ls, None, None, 2):  # start and stop None, step 2
    print(item)
</code>```

Which prints:

```<code>element1
element3
element5
element7
element9
</code>```

The islice won't create a new list, so it's more memory-efficient than l[::2] but at the cost of performance (it will be a bit slower).

Timing comparison:

(NB: I use IPythons %%timeit to measure the execution time.)

For short sequences [::2] is faster:

```<code>ls = list(range(100))

%%timeit

for item in itertools.islice(ls, None, None, 2):
    pass
</code>```

3.81 µs ± 90 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

```<code>%%timeit

for item in ls[::2]:
    pass
</code>```

3.16 µs ± 82 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

But for long sequences islice will be faster and require less memory:

```<code>import itertools

ls = list(range(100000))

%%timeit

for item in itertools.islice(ls, None, None, 2):
    pass
</code>```

3.14 ms ± 53.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

```<code>%%timeit

for item in ls[::2]:
    pass
</code>```

4.82 ms ± 132 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

One exception: If you want the result as list then slicing [::2] will always be faster but in case you want to iterate over it then islice should be the preferred option.

Body:
I have list of elements with dictionary, for simplicity I have written them as strings:

ls = ['element1', 'element2', 'element3', 'element4', 'element5', 'element6', 'element7', 'element8', 'element9', 'element10']

I am trying to process pair of element from list as follow:

#m1. Step for loop by size two with if condition
for x in ls:
    if ls.index(x)%2 == 0:
        # my code to be process
        print(x) # for simplicity I just printed element

#m2. tried another way like below:
for x in range(0, len(ls), 2):
    # this way give me output of alternate element from list
    print(ls[x])

Is there any way to get only alternate elements while iterating the list items in m1 just like m2?

Body:
You can use itertools.islice with a step of 2:

import itertools

for item in itertools.islice(ls, None, None, 2):  # start and stop None, step 2
    print(item)

Which prints:

element1
element3
element5
element7
element9

The islice won't create a new list, so it's more memory-efficient than l[::2] but at the cost of performance (it will be a bit slower).

Timing comparison:

(NB: I use IPythons %%timeit to measure the execution time.)

For short sequences [::2] is faster:

ls = list(range(100))

%%timeit

for item in itertools.islice(ls, None, None, 2):
    pass

3.81 µs ± 90 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%%timeit

for item in ls[::2]:
    pass

3.16 µs ± 82 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

But for long sequences islice will be faster and require less memory:

import itertools

ls = list(range(100000))

%%timeit

for item in itertools.islice(ls, None, None, 2):
    pass

3.14 ms ± 53.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit

for item in ls[::2]:
    pass

4.82 ms ± 132 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

One exception: If you want the result as list then slicing [::2] will always be faster but in case you want to iterate over it then islice should be the preferred option.


问:
Prevent safari loading from cache when back button is clicked
Got an issue with safari loading old youtube videos when back button is clicked. I have tried adding onunload="" (mentioned here Preventing cache on back-button in Safari 5) to the body tag but it doesn't work in this case.

Is there any way to prevent safari loading from cache on a certain page?

答:
Yes the Safari browser does not handle back/foreward button cache the same like Firefox and Chrome does. Specially iframes like vimeo or youtube videos are cached hardly although there is a new iframe.src.

I found three ways to handle this. Choose the best for your case.
Solutions tested on Firefox 53 and Safari 10.1

1. Detect if user is using the back/foreward button, then reload whole page  or reload only the cached iframes by replacing the src

```<code>if (!!window.performance && window.performance.navigation.type === 2) {
            // value 2 means "The page was accessed by navigating into the history"
            console.log('Reloading');
            //window.location.reload(); // reload whole page
            $('iframe').attr('src', function (i, val) { return val; }); // reload only iframes
        }
</code>```

2. reload whole page if page is cached

```<code>window.onpageshow = function (event) {
        if (event.persisted) {
            window.location.reload();
        }
    };
</code>```

3. remove the page from history so users can't visit the page again by back/forward buttons

```<code>$(function () {
            //replace() does not keep the originating page in the session history,
            document.location.replace("/Exercises#nocache"); // clear the last entry in the history and redirect to new url
        });
</code>```

Body:
Yes the Safari browser does not handle back/foreward button cache the same like Firefox and Chrome does. Specially iframes like vimeo or youtube videos are cached hardly although there is a new iframe.src.

I found three ways to handle this. Choose the best for your case.
Solutions tested on Firefox 53 and Safari 10.1

1. Detect if user is using the back/foreward button, then reload whole page  or reload only the cached iframes by replacing the src

if (!!window.performance && window.performance.navigation.type === 2) {
            // value 2 means "The page was accessed by navigating into the history"
            console.log('Reloading');
            //window.location.reload(); // reload whole page
            $('iframe').attr('src', function (i, val) { return val; }); // reload only iframes
        }

2. reload whole page if page is cached

window.onpageshow = function (event) {
        if (event.persisted) {
            window.location.reload();
        }
    };

3. remove the page from history so users can't visit the page again by back/forward buttons

$(function () {
            //replace() does not keep the originating page in the session history,
            document.location.replace("/Exercises#nocache"); // clear the last entry in the history and redirect to new url
        });


问:
Forcing the app to work as LTR
I currently own Galaxy Note 4 with RTL in my language, and whenever I run my app it works from right to left while the app is English.

I need to some kind of "force" the app to be LTR in all kind of devices, RTL and LTR.

How I can force it?

答:
Add in styles.xml in your Base App theme style:

```<code><item name="android:layoutDirection">ltr</item>
</code>```

Exemple:

```<code>  <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorPrimary</item>
    <item name="android:screenOrientation">portrait</item>
    <item name="android:layoutDirection">ltr</item>
</style>
</code>```

Title: Forcing the app to work as LTR

Body:
Add in styles.xml in your Base App theme style:

<item name="android:layoutDirection">ltr</item>

Exemple:

  <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorPrimary</item>
    <item name="android:screenOrientation">portrait</item>
    <item name="android:layoutDirection">ltr</item>
</style>


问:
Highlight a form select element if its value is empty
I have a form where people sign up for a shift. There are multiple shifts on the page, and I have an onchange event that sends the sign-up via Ajax.

```<code><select name="user" class="assign_user" id="user1">
   <option value="user1234" selected="selected">Joe Bloggs</option>
   <option value="">No-one</option>
   <option value="user1235">Jane Mahon</option>
   <option value="user1236">Ahmed Kitab</option>
   <option value="user1237">Dave Smew</option>
</select>
</code>```

If  <option value="">No-one</option> is selected, I want to highlight the select element in yellow.

I cannot think of a way to do this with just CSS. I tried

```<code>select[value=''] {
   background-color:lightyellow;
}
</code>```

but the attribute filter in the square brackets doesn't accept empty values, as far as I know.

EDIT: just to be clear, empty select elements should be highlighted when the page loads, as well as when the element changes

答:
CSS

```<code>.empty {
    background-color: lightyellow;
}
</code>```

Javascript

```<code>function userChanged(select) {
    select = $(select);
    if (select.val() === "") select.addClass("empty");
    else select.removeClass("empty");
}

// UPDATED: Initialization
$(function() {
    var user1 = $("#user1");
    user1.change(function() { userChanged(user1); });

    // Highlights select when page loads.
    userChanged(user1);
});
</code>```

UPDATE: Future solution uses CSS only. From: Is there a CSS parent selector?

```<code>select:has(option:checked[value='']) {
    background-color: lightyellow;
}
</code>```

Body:
I have a form where people sign up for a shift. There are multiple shifts on the page, and I have an onchange event that sends the sign-up via Ajax.

<select name="user" class="assign_user" id="user1">
   <option value="user1234" selected="selected">Joe Bloggs</option>
   <option value="">No-one</option>
   <option value="user1235">Jane Mahon</option>
   <option value="user1236">Ahmed Kitab</option>
   <option value="user1237">Dave Smew</option>
</select>

If  <option value="">No-one</option> is selected, I want to highlight the select element in yellow.

I cannot think of a way to do this with just CSS. I tried

select[value=''] {
   background-color:lightyellow;
}

but the attribute filter in the square brackets doesn't accept empty values, as far as I know.

EDIT: just to be clear, empty select elements should be highlighted when the page loads, as well as when the element changes

Body:
CSS

.empty {
    background-color: lightyellow;
}

Javascript

function userChanged(select) {
    select = $(select);
    if (select.val() === "") select.addClass("empty");
    else select.removeClass("empty");
}

// UPDATED: Initialization
$(function() {
    var user1 = $("#user1");
    user1.change(function() { userChanged(user1); });

    // Highlights select when page loads.
    userChanged(user1);
});

UPDATE: Future solution uses CSS only. From: Is there a CSS parent selector?

select:has(option:checked[value='']) {
    background-color: lightyellow;
}


问:
How can I mimic reading multiple RFID readers through Softwareserial library in a loop?
I am working on a project that requires reading from six ID-12LA RFID readers simultaneously.

I’ve tried setting up readings from six channels through the Sparkfun Analog/Digital MUX Breakout board (CD74HC4067), but without luck. I don’t know if it is capable of serial communication, even though I read that on Bildr.org.

However, I am now trying to emulate reading from multiple serial ports through the SoftwareSerial library. I have read that it is not capable of reading simultaneously, but maybe a loop can simulate simultaneous listening. I have tried to do so by listening to the the first serial, then initializing readTag(), and then after that function has finished, begin listening to the second serial and then initialize the second function.

The readTag() function is capable of reading on its own, when only on RFID reader is connected, so that is not the problem.

Below is the code.

What would be the correct way to go about and simulate simultaneous reading through the loop function?

void setup() {
  Serial.begin(9600);
  ourSerial1.begin(9600);
  ourSerial2.begin(9600);

  pinMode(RFIDResetPin, OUTPUT);
  digitalWrite(RFIDResetPin, HIGH);
}

void loop() {

  ourSerial1.listen();
  readTag1();
  ourSerial2.listen();
  readTag2(); // Only this function works right now, because it is the last serial that was initiated in setup.

}

void readTag1() {

  char tagString[13];
  int index = 0;
  boolean reading = false;

  while (ourSerial1.available()) {

    int readByte = ourSerial1.read();

    if (readByte == 2) reading = true; // Beginning of tag
    if (readByte == 3) reading = false; // End of tag

    if (reading && readByte != 2 && readByte != 10 && readByte != 13) {
      //store the tag
      tagString[index] = readByte;
      index ++;
    }
  }

  checkTag(tagString); // Check if it is a match
  clearTag(tagString); // Clear the char of all value
  resetReader(); // Reset the RFID reader
}

void readTag2() {

  char tagString[13];
  int index = 0;
  boolean reading = false;

  while (ourSerial2.available()) {

    int readByte = ourSerial2.read();

    if (readByte == 2) reading = true; // Beginning of tag
    if (readByte == 3) reading = false; // End of tag

    if (reading && readByte != 2 && readByte != 10 && readByte != 13) {
      //store the tag
      tagString[index] = readByte;
      index ++;
    }
  }

  checkTag2(tagString); // Check if it is a match
  clearTag(tagString); // Clear the char of all value
  resetReader(); // Reset the RFID reader
}
```

答:
Am I correct that you just want to mock/mimic communication from RFID?
You want to have simultaneous reads to 2-6 serial RFID readers?

What you should do is not use the ourSerial1.listen(); routine.
This can indeed not listen on 2 ports at the same time. Make your own subroutines, that poll the individual ports (if needed, switch your MUX inbetween):

create a for loop that checks xx times (depending your setup, during 100ms?)

```<code>for (int i = 0, i < 1000, i++) //first part of loop
{
    if (Serial.available())
    {
      // do your decoding of port 1 here
    }
}
for (int i = 0, i < 1000, i++) //second part of loop
{
    if (Serial1.available()) //other port
    {
      // do your decoding of port 1 here
    }
}
</code>```

Body:
Am I correct that you just want to mock/mimic communication from RFID?
You want to have simultaneous reads to 2-6 serial RFID readers?

What you should do is not use the ourSerial1.listen(); routine.
This can indeed not listen on 2 ports at the same time. Make your own subroutines, that poll the individual ports (if needed, switch your MUX inbetween):

create a for loop that checks xx times (depending your setup, during 100ms?)

for (int i = 0, i < 1000, i++) //first part of loop
{
    if (Serial.available())
    {
      // do your decoding of port 1 here
    }
}
for (int i = 0, i < 1000, i++) //second part of loop
{
    if (Serial1.available()) //other port
    {
      // do your decoding of port 1 here
    }
}


问:
Why doesn't my OpenMP simd directive have any use?
I have tried these codes to test SIMD directive in OpenMP.

#include <iostream>
#include <sys/time.h>
#include <cmath>
#define N 4096
#define M 1000
using namespace std;

int main()
{
    timeval start,end;
    float a[N],b[N];
    for(int i=0;i<N;i++)
        b[i]=i;
    gettimeofday(&start,NULL);
    for(int j=0;j<M;j++)
    {
    #pragma omp simd
        for(int i=0;i<N;i++)
            a[i]=pow(b[i],2.1);
    }
    gettimeofday(&end,NULL);
    int time_used=1000000*(end.tv_sec-start.tv_sec)+(end.tv_usec-start.tv_usec);
    cout<<"time_used="<<time_used<<endl;
    return 1;
}
```

<p>But either I compiled it by</p>

```g++ -fopenmp simd.cpp
```

<p>or</p>

```g++ simd.cpp
```

<p>their reports for "time_used" are almost the same.It looks like the SIMD directive I used doesn't have any use?
Thanks!</p>

<p>Additional questions:
I replaced</p>

```a[i]=pow(b[i],2.1);
```

<p>by</p>

```a[i]=b[i]+2.1;
```

<p>and when I compile them by</p>

```g++ -fopenmp simd.cpp
```

<p>the output of "time_used" is about 12000.
When I compile them by</p>

```g++ simd.cpp
```

the output of "time_used" is about 12000,almost the same as before.

My computer: Haswell i5,8g RAM,ubuntu kylin 16.04,gcc 5.4.0

答:
The compiler can't auto-vectorize function calls. It can only vectorize specific arithmetic operations that can be done using SIMD instructions.

Therefore, you need a vector math library that implements the pow function using SIMD instructions. Intel provides one. I'm not sure if pow is one of the functions that it offers with vector optimizations, but I imagine it is. You should also beware that Intel's math library may not be optimal on AMD processors.

You claim that you tried changing the pow function call to a simple addition, but didn't see any improvement in the results. I'm not quite sure how that is possible, because if you change the inner loop from:

```<code>a[i]=pow(b[i],2.1);
</code>```

to, say:

```<code>a[i] += b[i];
</code>```

or:

```<code>a[i] += (b[i] * 2);
</code>```

then GCC, with optimizations enabled, notices that you never use the result and elides the entire thing. It was unable to perform this optimization with the pow function call, because it didn't know whether the function had any other side-effects. However, with code that is visible to the optimizer, it can…well, optimize it. In some cases, it might be able to vectorize it. In this case, it was able to remove it entirely.

If you tried code where the optimizer removed this loop entirely, and you still didn't see an improvement on your benchmark scores, then clearly this is not a bottleneck in your code and you needn't worry about trying to vectorize it.

Body:
I have tried these codes to test SIMD directive in OpenMP.

#include <iostream>
#include <sys/time.h>
#include <cmath>
#define N 4096
#define M 1000
using namespace std;

int main()
{
    timeval start,end;
    float a[N],b[N];
    for(int i=0;i<N;i++)
        b[i]=i;
    gettimeofday(&start,NULL);
    for(int j=0;j<M;j++)
    {
    #pragma omp simd
        for(int i=0;i<N;i++)
            a[i]=pow(b[i],2.1);
    }
    gettimeofday(&end,NULL);
    int time_used=1000000*(end.tv_sec-start.tv_sec)+(end.tv_usec-start.tv_usec);
    cout<<"time_used="<<time_used<<endl;
    return 1;
}

But either I compiled it by

g++ -fopenmp simd.cpp

or

g++ simd.cpp

their reports for "time_used" are almost the same.It looks like the SIMD directive I used doesn't have any use?
Thanks!

Additional questions:
I replaced

a[i]=pow(b[i],2.1);

by

a[i]=b[i]+2.1;

and when I compile them by

g++ -fopenmp simd.cpp

the output of "time_used" is about 12000.
When I compile them by

g++ simd.cpp

the output of "time_used" is about 12000,almost the same as before.

My computer: Haswell i5,8g RAM,ubuntu kylin 16.04,gcc 5.4.0

Body:
The compiler can't auto-vectorize function calls. It can only vectorize specific arithmetic operations that can be done using SIMD instructions.

Therefore, you need a vector math library that implements the pow function using SIMD instructions. Intel provides one. I'm not sure if pow is one of the functions that it offers with vector optimizations, but I imagine it is. You should also beware that Intel's math library may not be optimal on AMD processors.

You claim that you tried changing the pow function call to a simple addition, but didn't see any improvement in the results. I'm not quite sure how that is possible, because if you change the inner loop from:

a[i]=pow(b[i],2.1);

to, say:

a[i] += b[i];

or:

a[i] += (b[i] * 2);

then <a href="https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:'%23include+%3Ciostream%3E%0A%23include+%3Csys/time.h%3E%0A%23include+%3Ccmath%3E%0A%23define+N+4096%0A%23define+M+1000%0Ausing+namespace+std%3B%0A%0Aint+main()%0A%7B%0A++++timeval+start,end%3B%0A++++float+a%5BN%5D,b%5BN%5D%3B%0A++++for(int+i%3D0%3Bi%3CN%3Bi%2B%2B)%0A++++++++b%5Bi%5D%3Di%3B%0A++++gettimeofday(%26start,NULL)%3B%0A++++for(int+j%3D0%3Bj%3CM%3Bj%2B%2B)%0A++++%7B%0A++++%23pragma+omp+simd+%0A++++++++for(int+i%3D0%3Bi%3CN%3Bi%2B%2B)%0A++++++++++++a%5Bi%5D+%2B%3D+(b%5Bi%5D+*+2)%3B%0A++++%7D%0A++++gettimeofday(%26end,NULL)%3B%0A++++int+time_used%3D1000000*(end.tv_sec-start.tv_sec)%2B(end.tv_usec-start.tv_usec)%3B%0A++++cout%3C%3C%22time_used%3D%22%3C%3Ctime_used%3C%3Cendl%3B%0A++++return+1%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:46.96823110303906,l:'4',m:100,n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g71,filters:(b:'0',commentOnly:'0',directives:'0',intel:'0'),options:'-m64+-O3+-fopenmp',source:1),l:'5',n:'0',o:'x86-64+gcc+7.1+(Editor+%231,+Compiler+%231)',t:'0')),header:(),k:53.031768896960955,l:'4',m:100,n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">GCC, with optimizations enabled, notices that you never use the result and elides the entire thing. It was unable to perform this optimization with the pow function call, because it didn't know whether the function had any other side-effects. However, with code that is visible to the optimizer, it can…well, optimize it. In some cases, it might be able to vectorize it. In this case, it was able to remove it entirely.

If you tried code where the optimizer removed this loop entirely, and you still didn't see an improvement on your benchmark scores, then clearly this is not a bottleneck in your code and you needn't worry about trying to vectorize it.


问:
C++ / Qt: track filesystem changes
I'm currently trying to implement a c++ program which monitors a folder on the filesystem. On initalizing the application, it scans the Directory and saves some meta information about it.

when something is chenged while the program is active, i can read changes to the folder (for examlpe changing the name of a folder or a file). But i can't track changes to the Directory while the program isn't running. Upon startup i would get

```<code>Removed folder X
Added folder Y
</code>```

instead of

```<code>Renamed folder X to Y
</code>```

is it possible to identify a directory in another way than it's path/name?
if yes, how would i gather that information in C++ / Qt ?

答:
Like TheDarkNight said, you need to use QFileSystemWatcher to avoid portability and so other problem.
But if you want to continue your approach:

In GNU/Linux land, you can check this with inode struct of directory (take care of symbolic link issue).
inode struct have an index for example you can get it on shell with:

```<code>ls -id /path/to/your/folder
</code>```

There is an API to access inode. You can google inode struct linux for it.

In Windows garden, you can get file id when accessing handle in the struct BY_HANDLE_FILE_INFORMATION:

nFileIndexHigh
      The high-order part of a unique identifier that is associated with a file.
      For more information, see nFileIndexLow.
      nFileIndexLow
      The low-order part of a unique identifier that is associated with a file.

Title: C++ / Qt: track filesystem changes

Body:
I'm currently trying to implement a c++ program which monitors a folder on the filesystem. On initalizing the application, it scans the Directory and saves some meta information about it.

when something is chenged while the program is active, i can read changes to the folder (for examlpe changing the name of a folder or a file). But i can't track changes to the Directory while the program isn't running. Upon startup i would get

Removed folder X
Added folder Y

instead of

Renamed folder X to Y

is it possible to identify a directory in another way than it's path/name?
if yes, how would i gather that information in C++ / Qt ?

Body:
Like TheDarkNight said, you need to use QFileSystemWatcher to avoid portability and so other problem.
But if you want to continue your approach:

In GNU/Linux land, you can check this with inode struct of directory (take care of symbolic link issue).
inode struct have an index for example you can get it on shell with:

ls -id /path/to/your/folder

There is an API to access inode. You can google inode struct linux for it.

In Windows garden, you can get file id when accessing handle in the struct BY_HANDLE_FILE_INFORMATION:

nFileIndexHigh
      The high-order part of a unique identifier that is associated with a file.
      For more information, see nFileIndexLow.
      nFileIndexLow
      The low-order part of a unique identifier that is associated with a file.


问:
How to disable days before tomorrow in jquery UI datepicker
I want to disable days before tomorrow and set tomorrow as the default  but I cant.my code shows today as the default and disabled days before today.

view:

```<code>   <input id="date_modified" type="text" class="form-control" value="">
</code>```

jquery:

```<code> $('#date_modified').persianDatepicker({
            observer: true,
            format: 'YYYY/MM/DD',
            maxDate: new Date(),

        })

                .pDatepicker('setDate');

    });
</code>```

答:
 <!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

Date: <input type="text" id="datepicker">

```

Body:
I want to disable days before tomorrow and set tomorrow as the default  but I cant.my code shows today as the default and disabled days before today.

view:

   <input id="date_modified" type="text" class="form-control" value="">

jquery:

 $('#date_modified').persianDatepicker({
            observer: true,
            format: 'YYYY/MM/DD',
            maxDate: new Date(),

        })

                .pDatepicker('setDate');

    });

Body:
 <!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
  var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    //Following line of code is to set the default and minDate of datepicker.
    $( "#datepicker" ).datepicker({minDate: tomorrow,defaultDate:tomorrow});
    //Following line of code is to set value of default date on text box.
    $("#datepicker").val($.datepicker.formatDate('mm/dd/yy', tomorrow));
  } );
  </script>
</head>
<body>

<p>Date: <input type="text" id="datepicker"></p>

</body>
</html>


问:
What's the difference between traveling salesman and chinese traveling?
What's the difference between travelling salesman problem (TSP) and Chinese postman problem (CPP)?

For me, both wants go to a destination, and then back.

答: Graphs are made of edges and vertices. CPP requires a visit to all edges. TSP requires a visit to all vertices.</p>


问:
Cell reuse bug in collectionView
Hello to all dear friends. I'm experiencing a problem with cell reuse. In practice I select multiple cells. In the "didSelected" method, I modify a property, called "isSelectedCell", to true and add a green border (to indicate the selection); While in the "didDeselect" method I carry it to false and remove the color of the border. But when I scroll down some cells, never selected, appear to be selected and the property is true. Because? How do I prevent this. It seems that when a cell is reused, the properties take on old ones and not their own.</p>

答:
Cells are for reuse means they are only fixed number of views which are used again. You have to update cells for every item to be displayed in that cell in collectionView cellForItemAtIndexPath method. You've to put it inside data source like array of objects to return correct value for every item. Hence it will remember to display which property on item.
Reusable cells are necesary to not bloat up the device memory and reuse same views.

Title: Cell reuse bug in collectionView


答:
The main problem here is that break only exits the innermost loop. So, if an element is found, break will skip checking other elements in the same column, but still the outer loop will advance to next row. What you really want is either this:

```<code>found = False
for row in matrix:
    for element in row:
        if element == number:
            found = True
            break
    if found:
        break
if found:
    print("Found")
else:
    print("Not found")
</code>```

(notice the other break)
or, possibly, a more readable solution using a function:

```<code>def searchfor(matrix, number):
    for row in matrix:
        for element in row:
            if element == number:
                return True
    return False

if searchfor(matrix, number):
    print("Found")
else:
    print("Not found")
</code>```

Edit: It just occured to me that it is possible to write it without either a flag variable or a function, but it is not a particularly elegant way. Still, for completeness, here you are:

```<code>for row in matrix:
    for element in row:
        if element == number:
            break
    else:
        continue
    break

if element == number:
    print("Found")
else:
    print("Not found")
</code>```

The continue statement will execute only if the inner loop was not exited by break, and it will advance the outer loop to the next row; otherwise the second break will end the outer loop.

Title: searching a 2d array in python - best method + indentation error

Body:
I have created the following 2d array (list of lists) in Python:

#creating a 2d array (3 rows by 7 columns) and populating it with numbers
matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
rows=len(matrix) #finding the max number of rows in the matrix, in this case 3
columns=len(matrix[0]) #finding the max number of columns in each row, 7 in this case

I am trying to search for a specific element in the array (say the number 9), and then print "found", if found, and "not found", if not in the array, with the following code:

number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
else:
  print("not found")

The output however, is erroneous:

>>What number are you looking for? 9
>>Found it!
>>not found

I have two questions: 1. could someone please explain identatation clearly, with reference to this problem and why the second "not found" always is output.
2. Is there a better more efficient way to do this, without the use of numpy

*note, this is not a duplicate, as I have searched the other entries and they don't quite deal with what I am explicitly asking.

repl.it here:
https://repl.it/IcJ3/3

Someone just suggested an answer as below: (I had already tried this)

https://repl.it/IcJ3/5
Note, it doesn't work at all either:

number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
        else:
          print("not found")

Erroneous output, still!

What number are you looking for? 9
not found
not found
not found
not found
not found
not found
not found
not found
Found it!
not found
not found
not found
not found
not found
not found
not found

Body:
The main problem here is that break only exits the innermost loop. So, if an element is found, break will skip checking other elements in the same column, but still the outer loop will advance to next row. What you really want is either this:

found = False
for row in matrix:
    for element in row:
        if element == number:
            found = True
            break
    if found:
        break
if found:
    print("Found")
else:
    print("Not found")

(notice the other break)
or, possibly, a more readable solution using a function:

def searchfor(matrix, number):
    for row in matrix:
        for element in row:
            if element == number:
                return True
    return False

if searchfor(matrix, number):
    print("Found")
else:
    print("Not found")

Edit: It just occured to me that it is possible to write it without either a flag variable or a function, but it is not a particularly elegant way. Still, for completeness, here you are:

for row in matrix:
    for element in row:
        if element == number:
            break
    else:
        continue
    break

if element == number:
    print("Found")
else:
    print("Not found")

The continue statement will execute only if the inner loop was not exited by break, and it will advance the outer loop to the next row; otherwise the second break will end the outer loop.


问:
Text that changes with the date
I have been searching for a while and need help figuring out how to make text change depending on the date. I am traveling and people want to know where I am when, so I was going to post a "where am i now" section on my website.

For example, today I need it to say Dominican Republic, tomorrow Haiti, etc. for the next few weeks.

This is what I have so far but I have no idea if I'm doing it right. Not experienced at all with this!

```<code><html>
<head>
<p>
Where am I now?
</p>

<div id="first">Dominican Republic</div>
<div id="second">Haiti</div>
<div id="third">Jamaica</div>

<style>
#first,#second,#third {
    display:none;
}
</style>

<script type="text/javascript">
var date=new Date();
var year=date.getFullYear();
var month=date.getMonth();
var day=date.getDate(); // fixed

function SetDivContent() {

    if (year==2017 && month==6) {
        if (day==8) {
            $("#first").css("display","block");
        }
        else if (day==9) {
            $("#second").css("display","block");
        }
        else if (day==10) {
            $("#third").css("display","block");
        }
    }
</script>
</head>
</html>
</code>```

Thank you for your help!

答:
getMonth() is 0 based, yo you need to add +1 to get current month;

var date=new Date();
var year=date.getFullYear();
var month=date.getMonth() + 1;
var day=date.getDate(); // fixed
(function SetDivContent() {

    if (year == 2017 && month == 6) {
        if (day == 8) {
            $("#first").css("display","block");
        }
        else if (day==9) {
            $("#second").css("display","block");
        }
        else if (day==10) {
            $("#third").css("display","block");
        }
    }
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#first,#second,#third {
    display:none;
}</code>```

Where am I now?

Dominican Republic

Haiti

Jamaica
```

Title: Text that changes with the date

Body:
I have been searching for a while and need help figuring out how to make text change depending on the date. I am traveling and people want to know where I am when, so I was going to post a "where am i now" section on my website.

For example, today I need it to say Dominican Republic, tomorrow Haiti, etc. for the next few weeks.

This is what I have so far but I have no idea if I'm doing it right. Not experienced at all with this!

Where am I now?

Dominican Republic

Haiti

Jamaica

Thank you for your help!

Body:
getMonth() is 0 based, yo you need to add +1 to get current month;

var date=new Date();
var year=date.getFullYear();
var month=date.getMonth() + 1;
var day=date.getDate(); // fixed
(function SetDivContent() {

    if (year == 2017 && month == 6) {
        if (day == 8) {
            $("#first").css("display","block");
        }
        else if (day==9) {
            $("#second").css("display","block");
        }
        else if (day==10) {
            $("#third").css("display","block");
        }
    }
})();

#first,#second,#third {
    display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Where am I now?
</p>

<div id="first">Dominican Republic</div>
<div id="second">Haiti</div>
<div id="third">Jamaica</div>


问:
Firebase cloud messaging duplicate notifications
We are using Firebase cloud messaging.
Sometimes when Android or iOS app is in sleep mode the cell phone receives same (duplicates) notifications messages.
For device identifications the FIRInstanceID token is used. An external server on node.js is used for sending notifications to Firebase service.
No duplications in our server log file are presented.</p>

答:
check this answer, That worked for me... https://stackoverflow.com/a/44435980/1533285

I was requesting permissions to GCM too so Systray showed two notifications.


答:
I'm not certain I understand correctly, but I think this query should be very close to what you're trying to do:

```<code>select name,
max(LNr1) as LNr1,
max(LNr2) as LNr2,
...
max(LNr10) as LNr10
from
(
    select name,
    if(LNr = 1, LID, null) as LNr1,
    if(LNr = 2, LID, null) as LNr2,
    ...
    if(LNr = 10, LID, null) as LNr10
    from klz
) res
group by name
</code>```

The inner part will split your rows in different "LNr" columns and give you what I like to call a "stairway" resultset. All we have to do now is flatten it, which is what the outer query does by selecting max(LNr) for each row and grouping by name. It works because by default an actual value is always bigger than null, so selecting the max for each column will get rid of the null values and give you the actual value.

Title: Putting more than one MySQL Row in a column

Body:
the problem that i've is, that I have a Table in my Database and want to fetch some of the rows of this table in one column.

For example I've this table names klz:

|-------+-----------+-----+-----|
| ID    | Name      | LNr | LID |
|-------+-----------+-----+-----|
| 1     | 0000_01   | 1   | 16  |
| 2     | 0000_01   | 2   | 35  |
| 3     | 0000_02   | 1   | 16  |
| 4     | 0000_02   | 2   | 35  |
| 5     | 0000_10   | 1   | 18  |
| ..    | ..        | ..  | ..  |
| 297   | 0214_01   | 1   | 23  |
| 298   | 0214_01   | 1   | 66  |
| 299   | 0214_01   | 2   | 24  |
| 300   | 0214_01   | 2   | 67  |
| 301   | 0214_01   | 3   | 26  |
| 302   | 0214_01   | 4   | 28  |
| 303   | 0214_01   | 4   | 69  |
| 304   | 0214_01   | 5   | 30  |
| 305   | 0214_01   | 5   | 70  |
| 306   | 0214_01   | 6   | 31  |
| 307   | 0214_01   | 6   | 71  |
|-------+-----------+-----+-----|

If I fetch this table with a while-loop in PHP I would get the same table.

So what I want to have is a table like this:

|-----------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------|
| Name      | LNr1    | LNr2    | LNr3    | LNr4    | LNr5    | LNr6    | LNr7    | LNr8    | LNr9    | LNr10   |
|-----------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------|
| 0000_01   | 16      | 35      |         |         |         |         |         |         |         |         |
| 0000_02   | 16      | 35      |         |         |         |         |         |         |         |         |
| 0000_10   | 18      |         |         |         |         |         |         |         |         |         |
| 0214_01   | 23 - 66 | 24      | 26 - 68 | 28 - 69 | 30 - 70 | 31 - 71 |         |         |         |         |
|-----------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------|

This table have the column Name and an enumeration of the possible LNr from 1 to 10 as columns. The data inside the LNr columns arethe LIDs from the table above.

My Question is, how can I put in dependency of the Name and the LNr, the LIDs in the right columns?
In this table you have listed all Names once and set for all LNr the right LID.

Here is the Code I'm trying to do this with... Until now it works only for the first LNr column, to write the LID in:

<?php
  include "dbconnect.php";

  $klz = mysqli_query($db, "SELECT      *
                            FROM        klz;");

?>

           Name
           Leitungsnr 1
           Leitungsnr 2
           Leitungsnr 3
           Leitungsnr 4
           Leitungsnr 5
           Leitungsnr 6
           Leitungsnr 7
           Leitungsnr 8
           Leitungsnr 9
           Leitungsnr 10

<?php
  $name_old = "";
  $lnr_old  = "";
  $name     = [];
  $lnr      = [];
  $lid      = [];

  while($row = mysqli_fetch_array($klz, MYSQL_ASSOC)){
    $name[] = $row['Name'];
    $lnr[] = $row['LNr'];
    $lid[] = $row['LID'];
  }

  for($i=0; $i <= sizeof($name)-1; $i++){

    if($name[$i] != $name_old){

      echo "
";
        echo "". $name[$i] . "	 \n";

        if($lnr[$i] != $lnr_old){
          echo "". $lid[$i] . "	 \n";

          $lnr_old != $lnr[$i];
        }

      echo "
";

      $name_old = $name[$i];
    }
  }
?>

<?php
  mysqli_close($db);
?>

I hope you know what I mean and trying to do. If not feel free to ask please.
Thank you

Body:
I'm not certain I understand correctly, but I think this query should be very close to what you're trying to do:

select name,
max(LNr1) as LNr1,
max(LNr2) as LNr2,
...
max(LNr10) as LNr10
from
(
    select name,
    if(LNr = 1, LID, null) as LNr1,
    if(LNr = 2, LID, null) as LNr2,
    ...
    if(LNr = 10, LID, null) as LNr10
    from klz
) res
group by name

The inner part will split your rows in different "LNr" columns and give you what I like to call a "stairway" resultset. All we have to do now is flatten it, which is what the outer query does by selecting max(LNr) for each row and grouping by name. It works because by default an actual value is always bigger than null, so selecting the max for each column will get rid of the null values and give you the actual value.


问:
Use CodeCeption assertion in conditional (if) statement
I'm totally new with CodeCeption.

I want to do an action/assertion depending on another assertion result, like this:

```<code>if ($I->see('message')){

    $I->click('button_close');

}
</code>```

Is something like that possible? I tried, but doesn't work.
Probably the assertion result doesn't apply to IF, but is there any alternative?

Thanks in advance!

IMPORTANT UPDATE:

Finally Codeception now has the function performOn!!
http://codeception.com/docs/modules/WebDriver#performOn

答:
100% working solution !! Thanx me later ;)

In tests/_support/AcceptanceHelper.php add additional method

```<code>public function seePageHasElement($element)
{
    try {
        $this->getModule('WebDriver')->_findElements($element);
    } catch (\PHPUnit_Framework_AssertionFailedError $f) {
        return false;
    }
    return true;
}
</code>```

Then to test in your acceptance test use:

```<code>if ($I->seePageHasElement($element)) {
    $I->fillField($element);
}
</code>```

The 'seeElement' function of WebDriver doesnot work on this case so needs little modified function as i have used one '_findElements' .Please donot forget to build your actors after any changes done.

Body:
I'm totally new with CodeCeption.

I want to do an action/assertion depending on another assertion result, like this:

if ($I->see('message')){

    $I->click('button_close');

}

Is something like that possible? I tried, but doesn't work.
Probably the assertion result doesn't apply to IF, but is there any alternative?

Thanks in advance!

IMPORTANT UPDATE:

Finally Codeception now has the function performOn!!
http://codeception.com/docs/modules/WebDriver#performOn

Body:
100% working solution !! Thanx me later ;)

In tests/_support/AcceptanceHelper.php add additional method

public function seePageHasElement($element)
{
    try {
        $this->getModule('WebDriver')->_findElements($element);
    } catch (\PHPUnit_Framework_AssertionFailedError $f) {
        return false;
    }
    return true;
}

Then to test in your acceptance test use:

if ($I->seePageHasElement($element)) {
    $I->fillField($element);
}

The 'seeElement' function of WebDriver doesnot work on this case so needs little modified function as i have used one '_findElements' .Please donot forget to build your actors after any changes done.


问:
Discover if a variable is a number
Is there a Way To compare nan with a variable?I need this To understand if a variable is a number or Not without using javascript's functions.</p>

答:
Im not sure why would you want to avoid calling a function for that, but here is a quick hack:

```<code>var myNumber = NaN;
typeof myNumber === "number" && myNumber + "" !== "NaN"
</code>```

this way you get true if its a number and not NaN, if its only a number, it will return true if its nan or a non number, it will return false/

again, it is recommended to use the isNaN function

Title: Discover if a variable is a number

Body:
Im not sure why would you want to avoid calling a function for that, but here is a quick hack:

var myNumber = NaN;
typeof myNumber === "number" && myNumber + "" !== "NaN"

this way you get true if its a number and not NaN, if its only a number, it will return true if its nan or a non number, it will return false/

again, it is recommended to use the isNaN function