问:
Why can't configure Azure diagnostics to use Azure Table Storage via new Azure Portal?
I am developing a web api which will be hosted in Azure. I would like to use Azure diagnostics to log errors to Azure table storage.
In the Classic portal, I can configure the logs to go to Azure table storage.

Classic Portal Diagnostic Settings

However in the new Azure portal, the only storage option I have is to use Blob storage:

New Azure Portal Settings

It seems that if I was to make use of a web role, I could configure the data store for diagnostics but as I am developing a web api, I don't want to create a separate web role for every api just so that I can log to an azure table.

Is there a way to programmatically configure azure diagnostics to propagate log messages to a specific data store without using a web role? Is there any reason why the new Azure portal only has diagnostic settings for blob storage and not table storage?

I can currently work around the problem by using the classic portal but I am worried that table storage for diagnostics will eventually become deprecated since it hasn't been included in the diagnostic settings for the new portal.

答:
(I'll do some necromancy on this question as this was the most relevant StackOverflow question I found while searching for a solution to this as it is no longer possible to do this through the classic portal)

Disclaimer: Microsoft has seemingly removed support for logging to Table in the Azure Portal, so I don't know if this is deprecated or will soon be deprecated, but I have a solution that will work now (31.03.2017):

There are specific settings determining logging, I first found out information on this from an issue in the Azure Powershell github: https://github.com/Azure/azure-powershell/issues/317

The specific settings we need are (from github):

AzureTableTraceEnabled = True, & AppSettings has:
  DIAGNOSTICS_AZURETABLESASURL

Using the excellent resource explorer (https://resources.azure.com) under (GUI navigation):

/subscriptions/{subscriptionName}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/config/logs

I was able to find the Setting AzureTableTraceEnabled in the Properties.

The property AzureTableTraceEnabled has Level and sasURL. In my experience updating these two values (Level="Verbose",sasUrl="someSASurl") will work, as updating the sasURL sets DIAGNOSTICS_AZURETABLESASURL in appsettings.

How do we change this? I did it in Powershell. I first tried the cmdlet Get-AzureRmWebApp, but could not find what i wanted - the old Get-AzureWebSite does display AzureTableTraceEnabled, but I could not get it to update (perhaps someone with more powershell\azure experience can come with input on how to use the ASM cmdlets to do this).

The solution that worked for me was setting the property through the Set-AzureRmResource command, with the following settings:

```<code>Set-AzureRmResource -PropertyObject $PropertiesObject -ResourceGroupName "$ResourceGroupName" -ResourceType Microsoft.Web/sites/config -ResourceName "$ResourceName/logs" -ApiVersion 2015-08-01 -Force
</code>```

Where the $PropertiesObject looks like this:

```<code>$PropertiesObject = @{applicationLogs=@{azureTableStorage=@{level="$Level";sasUrl="$SASUrl"}}}
</code>```

The Level corresponds to "Error", "Warning", "Information", "Verbose" and "Off".

It is also possible to do this in the ARM Template (important bits is in properties on the logs resource in the site):

```<code>        {
            "apiVersion": "2015-08-01",
            "name": "[variables('webSiteName')]",
            "type": "Microsoft.Web/sites",
            "location": "[resourceGroup().location]",
            "tags": {
                "displayName": "WebApp"
            },
            "dependsOn": [
                "[resourceId('Microsoft.Web/serverfarms/', variables('hostingPlanName'))]"
            ],
            "properties": {
                "name": "[variables('webSiteName')]",
                "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]"
            },
            "resources": [
            {
                "name": "logs",
                "type": "config",
                "apiVersion": "2015-08-01",
                "dependsOn": [
                    "[resourceId('Microsoft.Web/sites/', variables('webSiteName'))]"
                ],
                "tags": {
                    "displayName": "LogSettings"
                },
                "properties": {
                    "azureTableStorage": {
                        "level": "Verbose",
                        "sasUrl": "SASURL"
                    }
                }
            }
        }
</code>```

The issue with doing it in ARM is that I've yet to find a way to generate the correct SAS, it is possible to fetch out Azure Storage Account keys (from: ARM - How can I get the access key from a storage account to use in AppSettings later in the template?):

```<code>"properties": {
    "type": "AzureStorage",
        "typeProperties": {
            "connectionString": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storageAccountName'),';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName')), providers('Microsoft.Storage', 'storageAccounts').apiVersions[0]).keys[0].value)]"
    }
}
</code>```

There are also some clever ways of generating them using linked templates (from: http://wp.sjkp.dk/service-bus-arm-templates/).

The current solution I went for (time constraints) was a custom Powershell script that looks something like this:

```<code>...
$SASUrl = New-AzureStorageTableSASToken -Name $LogTable -Permission $Permissions -Context $StorageContext -StartTime $StartTime -ExpiryTime $ExpiryTime -FullUri
$PropertiesObject = @{applicationLogs=@{azureTableStorage=@{level="$Level";sasUrl="$SASUrl"}}}
Set-AzureRmResource -PropertyObject $PropertiesObject -ResourceGroupName "$ResourceGroupName" -ResourceType Microsoft.Web/sites/config -ResourceName "$ResourceName/logs" -ApiVersion 2015-08-01 -Force
...
</code>```

This is quite an ugly solution, as it is something extra you need to maintain in addition to the ARM template - but it is easy, fast and it works while we wait for updates to the ARM Templates (or for someone cleverer than I to come and enlighten us).

Body:
(I'll do some necromancy on this question as this was the most relevant StackOverflow question I found while searching for a solution to this as it is no longer possible to do this through the classic portal)

Disclaimer: Microsoft has seemingly removed support for logging to Table in the Azure Portal, so I don't know if this is deprecated or will soon be deprecated, but I have a solution that will work now (31.03.2017):

There are specific settings determining logging, I first found out information on this from an issue in the Azure Powershell github: https://github.com/Azure/azure-powershell/issues/317

The specific settings we need are (from github):

AzureTableTraceEnabled = True, & AppSettings has:
  DIAGNOSTICS_AZURETABLESASURL

Using the excellent resource explorer (https://resources.azure.com) under (GUI navigation):

/subscriptions/{subscriptionName}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/config/logs

I was able to find the Setting AzureTableTraceEnabled in the Properties.

The property AzureTableTraceEnabled has Level and sasURL. In my experience updating these two values (Level="Verbose",sasUrl="someSASurl") will work, as updating the sasURL sets DIAGNOSTICS_AZURETABLESASURL in appsettings.

How do we change this? I did it in Powershell. I first tried the cmdlet Get-AzureRmWebApp, but could not find what i wanted - the old Get-AzureWebSite does display AzureTableTraceEnabled, but I could not get it to update (perhaps someone with more powershell\azure experience can come with input on how to use the ASM cmdlets to do this).

The solution that worked for me was setting the property through the Set-AzureRmResource command, with the following settings:

Set-AzureRmResource -PropertyObject $PropertiesObject -ResourceGroupName "$ResourceGroupName" -ResourceType Microsoft.Web/sites/config -ResourceName "$ResourceName/logs" -ApiVersion 2015-08-01 -Force

Where the $PropertiesObject looks like this:

$PropertiesObject = @{applicationLogs=@{azureTableStorage=@{level="$Level";sasUrl="$SASUrl"}}}

The Level corresponds to "Error", "Warning", "Information", "Verbose" and "Off".

It is also possible to do this in the ARM Template (important bits is in properties on the logs resource in the site):

        {
            "apiVersion": "2015-08-01",
            "name": "[variables('webSiteName')]",
            "type": "Microsoft.Web/sites",
            "location": "[resourceGroup().location]",
            "tags": {
                "displayName": "WebApp"
            },
            "dependsOn": [
                "[resourceId('Microsoft.Web/serverfarms/', variables('hostingPlanName'))]"
            ],
            "properties": {
                "name": "[variables('webSiteName')]",
                "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]"
            },
            "resources": [
            {
                "name": "logs",
                "type": "config",
                "apiVersion": "2015-08-01",
                "dependsOn": [
                    "[resourceId('Microsoft.Web/sites/', variables('webSiteName'))]"
                ],
                "tags": {
                    "displayName": "LogSettings"
                },
                "properties": {
                    "azureTableStorage": {
                        "level": "Verbose",
                        "sasUrl": "SASURL"
                    }
                }
            }
        }

The issue with doing it in ARM is that I've yet to find a way to generate the correct SAS, it is possible to fetch out Azure Storage Account keys (from: ARM - How can I get the access key from a storage account to use in AppSettings later in the template?):

"properties": {
    "type": "AzureStorage",
        "typeProperties": {
            "connectionString": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storageAccountName'),';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName')), providers('Microsoft.Storage', 'storageAccounts').apiVersions[0]).keys[0].value)]"
    }
}

There are also some clever ways of generating them using linked templates (from: http://wp.sjkp.dk/service-bus-arm-templates/).

The current solution I went for (time constraints) was a custom Powershell script that looks something like this:

...
$SASUrl = New-AzureStorageTableSASToken -Name $LogTable -Permission $Permissions -Context $StorageContext -StartTime $StartTime -ExpiryTime $ExpiryTime -FullUri
$PropertiesObject = @{applicationLogs=@{azureTableStorage=@{level="$Level";sasUrl="$SASUrl"}}}
Set-AzureRmResource -PropertyObject $PropertiesObject -ResourceGroupName "$ResourceGroupName" -ResourceType Microsoft.Web/sites/config -ResourceName "$ResourceName/logs" -ApiVersion 2015-08-01 -Force
...

This is quite an ugly solution, as it is something extra you need to maintain in addition to the ARM template - but it is easy, fast and it works while we wait for updates to the ARM Templates (or for someone cleverer than I to come and enlighten us).


来源: stackexchange

问:
1gravity contacts picker library for android
Has anyone used 1GravityContactsPicker Library for android.

I just found this yesterday and decided to use this in my app due to its good features. I did everything as mentioned in the steps but when i am starting the activity I am getting a Toast message saying

Attribute undefined; "cp_textColorPrimary". Did you apply the correct
  theme

i have checked the documentation of library and heres what i did
1) Added dependency to gradle
2) Added activity file to manifest
3) Enabled contacts permission
4) below is the code

```<code> Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ContactPickerActivity.class)
                        .putExtra(ContactPickerActivity.EXTRA_THEME, R.style.ContactPicker_Theme_Dark)

                        .putExtra(ContactPickerActivity.EXTRA_CONTACT_BADGE_TYPE,
                                ContactPictureType.ROUND.name())

                        .putExtra(ContactPickerActivity.EXTRA_CONTACT_DESCRIPTION,
                                ContactDescription.ADDRESS.name())
                        .putExtra(ContactPickerActivity.EXTRA_SHOW_CHECK_ALL, true)
                        .putExtra(ContactPickerActivity.EXTRA_SELECT_CONTACTS_LIMIT, 0)
                        .putExtra(ContactPickerActivity.EXTRA_ONLY_CONTACTS_WITH_PHONE, false)

                        .putExtra(ContactPickerActivity.EXTRA_CONTACT_DESCRIPTION_TYPE,
                                ContactsContract.CommonDataKinds.Email.TYPE_WORK)

                        .putExtra(ContactPickerActivity.EXTRA_CONTACT_SORT_ORDER,
                                ContactSortOrder.AUTOMATIC.name());

                startActivityForResult(intent, REQUEST_CONTACT);
            }
        });
</code>```

can anyone please help me out with this

答:
I have the same issue.
it's because in his Actvity he test the AppThem directly and if your Application themes does not implement Picker style the check is all time false.

```<code>// check if all custom attributes are defined
    if (! checkTheming()) {
        finish();
        return;
    }
</code>```

For fix it, i've juste add new themes in styles.xml

```<code>    <!-- LIGHT Theme -->
<style name="Theme_Light_Base" parent="@style/ContactPicker_Theme_Light">
    <!-- ActionBarCompat -->
    <item name="colorPrimary">@color/colorPrimary_light</item>
    <item name="colorAccent">@color/colorAccent_light</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark_light</item>

    <item name="backgroundColor">@color/background_light</item>
    <!--<item name="icTheme">@drawable/ic_palette_black_36dp</item>-->
    <!--<item name="icPickContact">@drawable/ic_person_add_black_36dp</item>-->
</style>

<style name="Theme_Light_picker" parent="@style/Theme_Light_Base"/>

<!-- DARK Theme -->
<style name="Theme_Dark_Base" parent="@style/ContactPicker_Theme_Dark">
    <!-- ActionBarCompat -->
    <item name="colorPrimary">@color/colorPrimary_dark</item>
    <item name="colorAccent">@color/colorAccent_dark</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark_dark</item>

    <item name="backgroundColor">@color/background_dark</item>
    <!--<item name="icTheme">@drawable/ic_palette_white_36dp</item>-->
    <!--<item name="icPickContact">@drawable/ic_person_add_white_36dp</item>-->
</style>
</code>```

and after apply directly on the ActivityPicker in AndroidManifest.xml :

```<code>    <activity
        android:name="com.onegravity.contactpicker.core.ContactPickerActivity"
        android:enabled="true"
        android:exported="false"
        android:theme="@style/Theme_Light_picker">

        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>
    </activity>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Has anyone used 1GravityContactsPicker Library for android.

I just found this yesterday and decided to use this in my app due to its good features. I did everything as mentioned in the steps but when i am starting the activity I am getting a Toast message saying

Attribute undefined; "cp_textColorPrimary". Did you apply the correct
  theme

i have checked the documentation of library and heres what i did
1) Added dependency to gradle
2) Added activity file to manifest
3) Enabled contacts permission
4) below is the code

 Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ContactPickerActivity.class)
                        .putExtra(ContactPickerActivity.EXTRA_THEME, R.style.ContactPicker_Theme_Dark)

                        .putExtra(ContactPickerActivity.EXTRA_CONTACT_BADGE_TYPE,
                                ContactPictureType.ROUND.name())

                        .putExtra(ContactPickerActivity.EXTRA_CONTACT_DESCRIPTION,
                                ContactDescription.ADDRESS.name())
                        .putExtra(ContactPickerActivity.EXTRA_SHOW_CHECK_ALL, true)
                        .putExtra(ContactPickerActivity.EXTRA_SELECT_CONTACTS_LIMIT, 0)
                        .putExtra(ContactPickerActivity.EXTRA_ONLY_CONTACTS_WITH_PHONE, false)

                        .putExtra(ContactPickerActivity.EXTRA_CONTACT_DESCRIPTION_TYPE,
                                ContactsContract.CommonDataKinds.Email.TYPE_WORK)

                        .putExtra(ContactPickerActivity.EXTRA_CONTACT_SORT_ORDER,
                                ContactSortOrder.AUTOMATIC.name());

                startActivityForResult(intent, REQUEST_CONTACT);
            }
        });

can anyone please help me out with this

Body:
I have the same issue.
it's because in his Actvity he test the AppThem directly and if your Application themes does not implement Picker style the check is all time false.

// check if all custom attributes are defined
    if (! checkTheming()) {
        finish();
        return;
    }

For fix it, i've juste add new themes in styles.xml

    <!-- LIGHT Theme -->
<style name="Theme_Light_Base" parent="@style/ContactPicker_Theme_Light">
    <!-- ActionBarCompat -->
    <item name="colorPrimary">@color/colorPrimary_light</item>
    <item name="colorAccent">@color/colorAccent_light</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark_light</item>

    <item name="backgroundColor">@color/background_light</item>
    <!--<item name="icTheme">@drawable/ic_palette_black_36dp</item>-->
    <!--<item name="icPickContact">@drawable/ic_person_add_black_36dp</item>-->
</style>

<style name="Theme_Light_picker" parent="@style/Theme_Light_Base"/>

<!-- DARK Theme -->
<style name="Theme_Dark_Base" parent="@style/ContactPicker_Theme_Dark">
    <!-- ActionBarCompat -->
    <item name="colorPrimary">@color/colorPrimary_dark</item>
    <item name="colorAccent">@color/colorAccent_dark</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark_dark</item>

    <item name="backgroundColor">@color/background_dark</item>
    <!--<item name="icTheme">@drawable/ic_palette_white_36dp</item>-->
    <!--<item name="icPickContact">@drawable/ic_person_add_white_36dp</item>-->
</style>

and after apply directly on the ActivityPicker in AndroidManifest.xml :

    <activity
        android:name="com.onegravity.contactpicker.core.ContactPickerActivity"
        android:enabled="true"
        android:exported="false"
        android:theme="@style/Theme_Light_picker">

        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>
    </activity>


问:
How do I know when the current system scrollbar width changed?
I need to move controls around when the scrollbar's size change (System.Windows.Forms.SystemInformation.VerticalScrollBarWidth).

I'm creating a control with custom scrollbars that go over the normal ones. This implies creating a new UserControl (not inheriting a built-in control) and playing around with panels so as to hide the normal scrollbars.

The custom control must have one "outer" panel at the right size, this one containing an "inner" panel larger than the outer panel, so the scrollbars do not appear. How much larger depends on System.Windows.Forms.SystemInformation.VerticalScrollBarWidth and HorizontalScrollBarHeight as was already answered. But then I must know if that changes when my app is running, as improbable as it seems.

This question is related to:
How do I know the current width of system scrollbar?

答:
One must listen to Microsoft.Win32.SystemEvents.UserPreferenceChanged.
As takrl mentioned, OnSystemColorsChanged gets called, but only once for me (Windows7, Framework 3.5)

ContentLicense: CC BY-SA 2.5


问:
Reversing single linked list
I tried to revert single linkied list as follows:

```<code>public class MutableLst<T> {
    public T current;
    public MutableLst<T> next;

    private MutableLst(T current){
        this.current = current;
    }

    public static <T> MutableLst<T> create(T current){
        return new MutableLst<T>(current);
    }

    public void reverse(){
        MutableLst<T> newNext = null;
        MutableLst<T> nxt = next;
        next = newNext;
        while(nxt != null) {
            newNext = this;  //<------- cycle is here
            current = nxt.current;
            next = newNext;
            nxt = nxt.next;
        }
    }
</code>```

But this implementation does not work. When I assign to this I got a cycle. How to fix it?

答:
I would use recursion, like this:

```<code>public void reverse(MutableLst<T> previous){
    if (this.current.next !== null) {
        this.next.reverse(this);
    }
    this.next = previous;
}

public void reverse() {
    reverse(null);
}
</code>```

You will need to call reverse to the head of your list. As about your concrete problem, you are changing the next before you get a chance to use it. You might want to do something like this instead:

```<code>public void reverse(){
    MutableLst<T> previous = null;
    MutableLst<T> currentItem = this;
    MutableLst<T> nxt = null;
    while(currentItem != null) {
        nxt = currentItem.next;
        currentItem.next = previous;
        previous = currentItem;
        currentItem = nxt;
    }
}
</code>```

Title: Reversing single linked list

Body:
I tried to revert single linkied list as follows:

public class MutableLst<T> {
    public T current;
    public MutableLst<T> next;

    private MutableLst(T current){
        this.current = current;
    }

    public static <T> MutableLst<T> create(T current){
        return new MutableLst<T>(current);
    }

    public void reverse(){
        MutableLst<T> newNext = null;
        MutableLst<T> nxt = next;
        next = newNext;
        while(nxt != null) {
            newNext = this;  //<------- cycle is here
            current = nxt.current;
            next = newNext;
            nxt = nxt.next;
        }
    }

But this implementation does not work. When I assign to this I got a cycle. How to fix it?

Body:
I would use recursion, like this:

public void reverse(MutableLst<T> previous){
    if (this.current.next !== null) {
        this.next.reverse(this);
    }
    this.next = previous;
}

public void reverse() {
    reverse(null);
}

You will need to call reverse to the head of your list. As about your concrete problem, you are changing the next before you get a chance to use it. You might want to do something like this instead:

public void reverse(){
    MutableLst<T> previous = null;
    MutableLst<T> currentItem = this;
    MutableLst<T> nxt = null;
    while(currentItem != null) {
        nxt = currentItem.next;
        currentItem.next = previous;
        previous = currentItem;
        currentItem = nxt;
    }
}


问:
How to select a single cell in a pandas dataframe by condition
I have a dataframe like the following:

```<code>df = pd.DataFrame([[2,[4,6,8]],[3,[6,9]],[5,[10]],[7,[]]],columns = ['A','B'])
    A   B
0   2   [4, 6, 8]
1   3   [6, 9]
2   5   [10]
3   7   []
</code>```

And I would like to append the lists using a condition on the first column. For instance adding 12 in the cell df.ix[1,'B']. For this the following works:

```<code>df.ix[1,'b'].append(12)
</code>```

But now I don't know the index of the row, just a condition on the value in the A column. Using slicing yields a dataframe instead of the cell, therefore I can't append the value of the cell like before. (Note that the velues in A are unique, no duplicates)

```<code>df.ix[df.A == 3,'B'].append(12)

TypeError: cannot concatenate a non-NDFrame object
</code>```

So my question is the following:
How can I append the list in this cell using a condition on the A column value?

答:
You can leverage that pandas will use the + operator as it's defined for the underlying objects.  In this case [10] + [12] is [10, 12].  The conditional I used was just to illustrate that it isn't required to be for just one row.

```<code>df.loc[df.A > 4, 'B'] += [12]
print(df)

   A          B
0  2  [4, 6, 8]
1  3     [6, 9]
2  5   [10, 12]
3  7       [12]
</code>```

If by chance some your B column are not lists, we can make them so with a function.

```<code>def listify(x):
    try:
        return list(x)
    except:
        return [x]

df.B = df.B.apply(listify)
</code>```

Example

Consider the dataframe df

```<code>df = pd.DataFrame(
    [[2,[4,6,8]],[3,[6,9]],[5,[10]],[7,[]], [9, 1]],
    columns = ['A','B'])

print(df)

   A          B
0  2  [4, 6, 8]
1  3     [6, 9]
2  5       [10]
3  7         []
4  9          1
</code>```

If we try my suggestion, we get

>
    TypeError: unsupported operand type(s) for +: 'int' and 'list'

Once we listify

```<code>df.B = df.B.apply(listify)
print(df)

   A          B
0  2  [4, 6, 8]
1  3     [6, 9]
2  5       [10]
3  7         []
4  9        [1]
</code>```

Now we can

```<code>df.loc[df.A > 4, 'B'] += [12]
print(df)

   A          B
0  2  [4, 6, 8]
1  3     [6, 9]
2  5   [10, 12]
3  7       [12]
4  9    [1, 12]
</code>```

Body:
I have a dataframe like the following:

df = pd.DataFrame([[2,[4,6,8]],[3,[6,9]],[5,[10]],[7,[]]],columns = ['A','B'])
    A   B
0   2   [4, 6, 8]
1   3   [6, 9]
2   5   [10]
3   7   []

And I would like to append the lists using a condition on the first column. For instance adding 12 in the cell df.ix[1,'B']. For this the following works:

df.ix[1,'b'].append(12)

But now I don't know the index of the row, just a condition on the value in the A column. Using slicing yields a dataframe instead of the cell, therefore I can't append the value of the cell like before. (Note that the velues in A are unique, no duplicates)

df.ix[df.A == 3,'B'].append(12)

TypeError: cannot concatenate a non-NDFrame object

So my question is the following:
How can I append the list in this cell using a condition on the A column value?

Body:
You can leverage that pandas will use the + operator as it's defined for the underlying objects.  In this case [10] + [12] is [10, 12].  The conditional I used was just to illustrate that it isn't required to be for just one row.

df.loc[df.A > 4, 'B'] += [12]
print(df)

   A          B
0  2  [4, 6, 8]
1  3     [6, 9]
2  5   [10, 12]
3  7       [12]

If by chance some your B column are not lists, we can make them so with a function.

def listify(x):
    try:
        return list(x)
    except:
        return [x]

df.B = df.B.apply(listify)

Example

Consider the dataframe df

df = pd.DataFrame(
    [[2,[4,6,8]],[3,[6,9]],[5,[10]],[7,[]], [9, 1]],
    columns = ['A','B'])

print(df)

   A          B
0  2  [4, 6, 8]
1  3     [6, 9]
2  5       [10]
3  7         []
4  9          1

If we try my suggestion, we get

>
    TypeError: unsupported operand type(s) for +: 'int' and 'list'

Once we listify

df.B = df.B.apply(listify)
print(df)

   A          B
0  2  [4, 6, 8]
1  3     [6, 9]
2  5       [10]
3  7         []
4  9        [1]

Now we can

df.loc[df.A > 4, 'B'] += [12]
print(df)

   A          B
0  2  [4, 6, 8]
1  3     [6, 9]
2  5   [10, 12]
3  7       [12]
4  9    [1, 12]


问:
XSD 1.1 structure to enforce unique IDs (if necessary)?
Do I need XSD 1.1 to enforce ID uniqueness in a single XML file with a file/record structure like this:

```<code><?xml version="1.1" encoding="UTF-8"?>

<file>

<record id="1" status="ok">
    <info1></info1>
    <info2></info2>
    <!-- etc... -->
</record>

<record id="2" status="ok">
    <info1></info1>
    <info2></info2>
    <!-- etc... -->
</record>

<record id="1" status="duplicate_deprecated">
    <info1></info1>
    <info2></info2>
    <!-- etc... -->
</record>
</code>```

I'd like to also allow certain duplicated IDs under the condition that they are combined with e.g. an attribute meaning "remove / stop using this version of the record, replace this (now) deprecated duplicate by the other record with the same ID" (in the example, record 1).

Is this possible with XML schema 1.0 or does it need XSD 1.1 assertions (etc.)?

What kind of general XML instance structure is needed to make this assertion work? I know that XSD 1.1 asserts need to be on closely related elements / attributes.

Possibly related:

Asserting element Id uniqueness globally with XML 1.1 schema

XSD unique elements and attributes

答:
Yes, this needs XSD 1.1. Unfortunately the XPath expressions you can use on xs:unique / xs:key don't include predicates (even in XSD 1.1) so this can only be done with assertions.

The typical way of asserting uniqueness is

```<code>test="count(PATH) = count(distinct-values(PATH))"
</code>```

Unfortunately this doesn't give any diagnostics about what the offending duplicates are. Some processors might give you better diagnostics with

```<code>test="every $M in PATH, $N in PATH satisfies ($M is $N or $M ne $N)"
</code>```

but this is likely to be much less efficient.

The assertion should be specified on the innermost element that contains all the values to be tested for uniqueness.

Body:
Do I need XSD 1.1 to enforce ID uniqueness in a single XML file with a file/record structure like this:

<?xml version="1.1" encoding="UTF-8"?>

<file>

<record id="1" status="ok">
    <info1></info1>
    <info2></info2>

</record>

<record id="2" status="ok">
    <info1></info1>
    <info2></info2>

</record>

<record id="1" status="duplicate_deprecated">
    <info1></info1>
    <info2></info2>

</record>

I'd like to also allow certain duplicated IDs under the condition that they are combined with e.g. an attribute meaning "remove / stop using this version of the record, replace this (now) deprecated duplicate by the other record with the same ID" (in the example, record 1).

Is this possible with XML schema 1.0 or does it need XSD 1.1 assertions (etc.)?

What kind of general XML instance structure is needed to make this assertion work? I know that XSD 1.1 asserts need to be on closely related elements / attributes.

Possibly related:

Asserting element Id uniqueness globally with XML 1.1 schema

XSD unique elements and attributes

Body:
Yes, this needs XSD 1.1. Unfortunately the XPath expressions you can use on xs:unique / xs:key don't include predicates (even in XSD 1.1) so this can only be done with assertions.

The typical way of asserting uniqueness is

test="count(PATH) = count(distinct-values(PATH))"

Unfortunately this doesn't give any diagnostics about what the offending duplicates are. Some processors might give you better diagnostics with

test="every $M in PATH, $N in PATH satisfies ($M is $N or $M ne $N)"

but this is likely to be much less efficient.

The assertion should be specified on the innermost element that contains all the values to be tested for uniqueness.


问:
ES6 (Webpack) single file for each module - How to make variables globally available without using window.VARIABLE
I'm using React and one thing I didn't figure out yet is how to share variables with multiple components/modules. Right now I use window.VARIABLE = ... As this makes developers cringe, I wonder if there's a better way to do this without writing allot of boilerplate code and without bringing in Redux.</p>

答:
Webpack is just a tool that will bundle multiple files into a single one.
His job is not to connect react components.

Using global variables can be a way to share data between 2 components React but the best thing you can do is to give the variable as component properties (if you don't have to manipulate it).
If you need to share a state (a variable that can be manipulated), you need to use a tool like redux.


问:
Is there any structure to programmatically access indices of a String array in Java?
I'm creating a content provider for an Android app in Java and have a String array of constants and separate names for the index of each string in this array, as follows:

```<code>private static final String[] FILM_PROJECTION = {
    FilmContract.FilmEntry.COLUMN_FILM_ID,
    FilmContract.FilmEntry.COLUMN_TITLE,
    FilmContract.FilmEntry.COLUMN_POSTER_URL,
    FilmContract.FilmEntry.COLUMN_OVERVIEW,
    FilmContract.FilmEntry.COLUMN_RATING,
    FilmContract.FilmEntry.COLUMN_DATE,
    FilmContract.FilmEntry.COLUMN_POPULARITY,
    FilmContract.FilmEntry.COLUMN_VIDEOS,
    FilmContract.FilmEntry.COLUMN_REVIEWS
};

private static final int COLUMN_FILM_ID_INDEX    = 0;
private static final int COLUMN_TITLE_INDEX      = 1;
private static final int COLUMN_POSTER_URL_INDEX = 2;
private static final int COLUMN_OVERVIEW_INDEX   = 3;
private static final int COLUMN_RATING_INDEX     = 4;
private static final int COLUMN_DATE_INDEX       = 5;
private static final int COLUMN_POPULARITY_INDEX = 6;
private static final int COLUMN_VIDEOS_INDEX     = 7;
private static final int COLUMN_REVIEWS_INDEX    = 8;
</code>```

I'm thinking there's surely a better way to do this, and I tried it with enum e.g:

```<code>private enum FILM_PROJECTION_INDICES {
    FILM_PROJECTION
}
</code>```

But Java doesn't unpack the String array so that doesn't work (despite all the values being constant). What I'm asking for is something like this:

```<code>index = FILM_PROJECTION.getIndexOf(FilmContract.FilmEntry.COLUMN_TITLE);
</code>```

Is there any way to do this?

答:
```<code>public enum FilmType {

    FilmContract.FilmEntry.COLUMN_FILM_ID(0),
    ...
   ;

    private final int code;

    FilmType(int code) {
        this.index = index;
    }

    public Integer getIndex() {
        return index;
    }
}

index = FilmType.FilmContract.FilmEntry.COLUMN_FILM_ID.getIndex()
</code>```

Body:
I'm creating a content provider for an Android app in Java and have a String array of constants and separate names for the index of each string in this array, as follows:

private static final String[] FILM_PROJECTION = {
    FilmContract.FilmEntry.COLUMN_FILM_ID,
    FilmContract.FilmEntry.COLUMN_TITLE,
    FilmContract.FilmEntry.COLUMN_POSTER_URL,
    FilmContract.FilmEntry.COLUMN_OVERVIEW,
    FilmContract.FilmEntry.COLUMN_RATING,
    FilmContract.FilmEntry.COLUMN_DATE,
    FilmContract.FilmEntry.COLUMN_POPULARITY,
    FilmContract.FilmEntry.COLUMN_VIDEOS,
    FilmContract.FilmEntry.COLUMN_REVIEWS
};

private static final int COLUMN_FILM_ID_INDEX    = 0;
private static final int COLUMN_TITLE_INDEX      = 1;
private static final int COLUMN_POSTER_URL_INDEX = 2;
private static final int COLUMN_OVERVIEW_INDEX   = 3;
private static final int COLUMN_RATING_INDEX     = 4;
private static final int COLUMN_DATE_INDEX       = 5;
private static final int COLUMN_POPULARITY_INDEX = 6;
private static final int COLUMN_VIDEOS_INDEX     = 7;
private static final int COLUMN_REVIEWS_INDEX    = 8;

I'm thinking there's surely a better way to do this, and I tried it with enum e.g:

private enum FILM_PROJECTION_INDICES {
    FILM_PROJECTION
}

But Java doesn't unpack the String array so that doesn't work (despite all the values being constant). What I'm asking for is something like this:

index = FILM_PROJECTION.getIndexOf(FilmContract.FilmEntry.COLUMN_TITLE);

Is there any way to do this?


问:
Are the terms Type and Class used interchangeably - Scala
I have been studying scala quite a bit now. However, I have a simple question in regards to few terms used on many learning materials I find.

Are the term Type used interchangeably with Class?

Could a Type be replaced by a Class? and vice versa?

Ex. a Scala programmer would/could call the following case class a Type

```<code>type ProductId = String
type Quantity = Int

case class ShoppingCart(items: Map[ProductId, Quantity])
</code>```

So, is ShoppingCart a Type, a class, or both, or depends on the paradigm ?

Also, does it have anything to do with Type Classes?

Thanks in advance.

答:
In short no, Scala offers a great variety of types, classes are one of the possible representations of type. A type refers to a natural language construct of defining a "template" of properties that can categorise a construct.

So we define a set of objects via a unifying set of characteristics, and we called the logical set of objects that "fit the template" a type, because all instances of that type share the properties.

So a class always has a type, but a type is not always a class.

Just for the sake of argument:

trait T is a type, it can have abstract methods, normal fully implemented methods, inherited methods, fields, type members, etc.

```<code>class A {
  type B
}
</code>```

Both A and B have a type.

```<code>case class Bla
</code>```

Also has a type.

object C also automatically generates the C.type definition, so C has type C.type.

```<code>def test(a: { def close: Unit() = println("closed")}
</code>```

Is also a structural type, that can be exposed via a type lambda.

There are many more possible representations of a type. Just about the
only thing you wouldn't call a type is your first example, depending on how it's defined:

```<code>type A = String
</code>```

We refer to that as a type alias, because it's not in essence a new type. It can be if you define type A as a type member with no particular implementation on a trait and then an implementor specifies a concrete type.

```<code>trait Holder {
  type Repr
}
</code>```

And then override the type member like this:

```<code>trait StringHolder extends Holder {
  type Repr = String
}
</code>```

Body:
I have been studying scala quite a bit now. However, I have a simple question in regards to few terms used on many learning materials I find.

Are the term Type used interchangeably with Class?

Could a Type be replaced by a Class? and vice versa?

Ex. a Scala programmer would/could call the following case class a Type

type ProductId = String
type Quantity = Int

case class ShoppingCart(items: Map[ProductId, Quantity])

So, is ShoppingCart a Type, a class, or both, or depends on the paradigm ?

Also, does it have anything to do with Type Classes?

Thanks in advance.

Body:
In short no, Scala offers a great variety of types, classes are one of the possible representations of type. A type refers to a natural language construct of defining a "template" of properties that can categorise a construct.

So we define a set of objects via a unifying set of characteristics, and we called the logical set of objects that "fit the template" a type, because all instances of that type share the properties.

So a class always has a type, but a type is not always a class.

Just for the sake of argument:

trait T is a type, it can have abstract methods, normal fully implemented methods, inherited methods, fields, type members, etc.

class A {
  type B
}

Both A and B have a type.

case class Bla

Also has a type.

object C also automatically generates the C.type definition, so C has type C.type.

def test(a: { def close: Unit() = println("closed")}

Is also a structural type, that can be exposed via a type lambda.

There are many more possible representations of a type. Just about the
only thing you wouldn't call a type is your first example, depending on how it's defined:

type A = String

We refer to that as a type alias, because it's not in essence a new type. It can be if you define type A as a type member with no particular implementation on a trait and then an implementor specifies a concrete type.

trait Holder {
  type Repr
}

And then override the type member like this:

trait StringHolder extends Holder {
  type Repr = String
}


问:
how do i remove and add value in dynamic created dropdown using JQuery?
My requirements are:

1 - If I select any option from drop down then it should not show up in any other drop down except current one.

2 - If I change the above selected option to something else then the previous selected option should show up(added) again in all drop downs & new one should be removed from all other dropdowns.

HTML

```<code><table class="table table-bordered centeredContent multiSelectFunctionality" id="table">
  <tbody>
    <tr>
      <td>
        <button type="button" class="btn btn-plus custom-icon glyphicon glyphicon-plus" onclick="cloneRow();" title="Add Row"></button>
      </td>
      <td>
        <select class="selectedItem form-control" name="selectedItem" id="selectedItem_1">
          <option value="entityName">Entity Name</option>
          <option value="transmitter_mac">Tag Mac</option>
          <option value="tag_number">Tag Number</option>
          <option value="sub_category">Sub Category</option>
          <option value="name">Department Name</option>
          <option value="in_time">In Time</option>
          <option value="out_time">Out Time</option>
        </select>
      </td>
      <td>
        <input class="form-control searchItem" placeholder="Enter Search item" name="searchItem" />
        <!-- <input type="hidden" name="counterValue" id="counterValue" value=""> -->
      </td>
    </tr>
  </tbody>
</table>
</code>```

JavaScript

```<code>function cloneRow() {
  counter++;
  if (counter >= 7) {
    return;
  } else {
    var a = $("table#table").find("tbody");
    var b = a.find("tr:first");
    $trLast1 = a.find("tr:last");
    $trNew = b.clone();
    $trNew.find("button#dltbtn").remove().end();
    $trNew.find("td:first").append('<button type="button" class="btn btn-plus custom-icon glyphicon glyphicon-minus" onclick="deleteRow(this);" title="Remove Row"></button>');
    $trLast1.after($trNew);
  }
}

function deleteRow(a) {
  $(a).closest("tr").remove();
  counter--;
}
</code>```

答:
```<code>        var rowCount = 1;
    function cloneRow(self) {
        if(rowCount==7){
            $(".glyphicon-plus").attr("disabled", true);
            return;
        }
        else{
        var a = $("table#table").find("tbody");
        var b = a.find("tr:first");
        $trLast1 = a.find("tr:last");
        $trNew = b.clone();
        $trNew.find("button#dltbtn").remove().end();
        $trNew.find("td:first").append('<button type="button" class="btn btn-plus custom-icon glyphicon glyphicon-minus" onclick="deleteRow(this);" title="Remove Row"></button>');
        $trLast1.after($trNew);
        rowCount = $('table#table tr:last').index() + 1;
        manage_opns();
        }
     }

    $(document).on('change', '.selectedItem', function(e, el){
        manage_opns();
    });

    function manage_opns(){
        $("select.selectedItem option").attr('disabled',false);
        $("select.selectedItem").each(function(i, el){
            var cur_val = $(el).val();
            if(cur_val != ''){
                $("select.selectedItem option[value='"+cur_val+"']").attr('disabled',true);
                $(el).find("option[value='"+cur_val+"']").attr('disabled',false);
            }
        });
    }

    function deleteRow(a) {
        $(a).closest("tr").remove();
        rowCount = $('table#table tr:last').index() + 1;
        if(rowCount <= 7){
            $(".glyphicon-plus").attr("disabled", false);
        }
        manage_opns();
    }
</code>```

HTML Code

```<code><table class="table table-bordered centeredContent" id="table">
                         <tbody>
                           <tr>
                             <td><button type="button" class="btn btn-plus custom-icon glyphicon glyphicon-plus" onclick="cloneRow(this);" title="Add Row"></button>
                             </td>
                             <td>
                             <select class="selectedItem  required-report input-normal input-width-45" name="selectedItem">
                                    <option value="entityName">Entity Name</option>
                                    <option value="transmitter_mac">Tag Mac</option>
                                    <option value="tag_number">Tag Number</option>
                                    <option value="sub_category">Sub Category</option>
                                    <option value="name">Department Name</option>
                                    <option value="in_time">In Time</option>
                                    <option value="out_time">Out Time</option>
                             </select>
                                </td>
                             <td>
                                <input class="searchItem input-normal input-width-45 required-report" placeholder="Enter Search item"  name="searchItem"/>

                             </td>
                           </tr>
                         </tbody>
                   </table>
</code>```

Now you can see the functionality

Body:
My requirements are:

1 - If I select any option from drop down then it should not show up in any other drop down except current one.

2 - If I change the above selected option to something else then the previous selected option should show up(added) again in all drop downs & new one should be removed from all other dropdowns.

HTML

        <button type="button" class="btn btn-plus custom-icon glyphicon glyphicon-plus" onclick="cloneRow();" title="Add Row"></button>

        <select class="selectedItem form-control" name="selectedItem" id="selectedItem_1">
          <option value="entityName">Entity Name</option>
          <option value="transmitter_mac">Tag Mac</option>
          <option value="tag_number">Tag Number</option>
          <option value="sub_category">Sub Category</option>
          <option value="name">Department Name</option>
          <option value="in_time">In Time</option>
          <option value="out_time">Out Time</option>
        </select>

        <input class="form-control searchItem" placeholder="Enter Search item" name="searchItem" />

JavaScript

function cloneRow() {
  counter++;
  if (counter >= 7) {
    return;
  } else {
    var a = $("table#table").find("tbody");
    var b = a.find("tr:first");
    $trLast1 = a.find("tr:last");
    $trNew = b.clone();
    $trNew.find("button#dltbtn").remove().end();
    $trNew.find("td:first").append('<button type="button" class="btn btn-plus custom-icon glyphicon glyphicon-minus" onclick="deleteRow(this);" title="Remove Row"></button>');
    $trLast1.after($trNew);
  }
}

function deleteRow(a) {
  $(a).closest("tr").remove();
  counter--;
}

Body:
        var rowCount = 1;
    function cloneRow(self) {
        if(rowCount==7){
            $(".glyphicon-plus").attr("disabled", true);
            return;
        }
        else{
        var a = $("table#table").find("tbody");
        var b = a.find("tr:first");
        $trLast1 = a.find("tr:last");
        $trNew = b.clone();
        $trNew.find("button#dltbtn").remove().end();
        $trNew.find("td:first").append('<button type="button" class="btn btn-plus custom-icon glyphicon glyphicon-minus" onclick="deleteRow(this);" title="Remove Row"></button>');
        $trLast1.after($trNew);
        rowCount = $('table#table tr:last').index() + 1;
        manage_opns();
        }
     }

    $(document).on('change', '.selectedItem', function(e, el){
        manage_opns();
    });

    function manage_opns(){
        $("select.selectedItem option").attr('disabled',false);
        $("select.selectedItem").each(function(i, el){
            var cur_val = $(el).val();
            if(cur_val != ''){
                $("select.selectedItem option[value='"+cur_val+"']").attr('disabled',true);
                $(el).find("option[value='"+cur_val+"']").attr('disabled',false);
            }
        });
    }

    function deleteRow(a) {
        $(a).closest("tr").remove();
        rowCount = $('table#table tr:last').index() + 1;
        if(rowCount <= 7){
            $(".glyphicon-plus").attr("disabled", false);
        }
        manage_opns();
    }

HTML Code

<table class="table table-bordered centeredContent" id="table">
                         <tbody>
                           <tr>
                             <td><button type="button" class="btn btn-plus custom-icon glyphicon glyphicon-plus" onclick="cloneRow(this);" title="Add Row"></button>
                             </td>
                             <td>
                             <select class="selectedItem  required-report input-normal input-width-45" name="selectedItem">
                                    <option value="entityName">Entity Name</option>
                                    <option value="transmitter_mac">Tag Mac</option>
                                    <option value="tag_number">Tag Number</option>
                                    <option value="sub_category">Sub Category</option>
                                    <option value="name">Department Name</option>
                                    <option value="in_time">In Time</option>
                                    <option value="out_time">Out Time</option>
                             </select>
                                </td>
                             <td>
                                <input class="searchItem input-normal input-width-45 required-report" placeholder="Enter Search item"  name="searchItem"/>

                             </td>
                           </tr>
                         </tbody>
                   </table>

Now you can see the functionality


问:
HttpUrlConnection for delete method was not accepting any Arguments?
Http url connection for DELETE method was not passing any value  in this request request.putOpt("Username", userid).I am getting proper cartid value in log but that cart id value is not passing while sending request and hereby i am attaching my code for httpclientconnection for delete method and my request too.Please give me some good solutions.Thanks in advance.

```<code>private static JSONObject delete(String sUrl, String body) {

    HttpURLConnection connection = null;

    String authentication = "dem" + ":" + "dem123";
    String encodedAuthentication = Base64
        .encodeToString(authentication.getBytes(), Base64.NO_WRAP);

    try {
        URL url = new URL(sUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("DELETE");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization",
            "Basic " + encodedAuthentication);
        connection.setRequestProperty("Accept-Charset", "utf-8,*");
        OutputStreamWriter streamWriter = new OutputStreamWriter(
            connection.getOutputStream());

        streamWriter.write(body);
        streamWriter.flush();
        StringBuilder stringBuilder = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStreamReader streamReader = new InputStreamReader(
                connection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(
                streamReader);
            String response = null;
            while ((response = bufferedReader.readLine()) != null) {
                stringBuilder.append(response + "\n");
            }
            bufferedReader.close();

            return new JSONObject(stringBuilder.toString());
        } else {
            Log.d("Put-Error", connection.getResponseMessage());
            return null;
        }
    } catch (Exception exception) {
        Log.e("Put-Exception", exception.toString());
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

 public static JSONObject ClearcartItems(Context ctx, String sUrl,
                                        String userid) throws   JSONException, IOException {
    JSONObject request = new JSONObject();
    Log.e("userid",""+userid);//I am getting cartid value here
    request.putOpt("Username", userid);
    sUrl = sUrl + "clear-all-cart-items";
    Log.e("del", "" + sUrl);
    return delete(sUrl, request.toString());
}
</code>```

答: RequestMethod "DELETE" doesn't support RequestBody </p>

Body:
Http url connection for DELETE method was not passing any value  in this request request.putOpt("Username", userid).I am getting proper cartid value in log but that cart id value is not passing while sending request and hereby i am attaching my code for httpclientconnection for delete method and my request too.Please give me some good solutions.Thanks in advance.

private static JSONObject delete(String sUrl, String body) {

    HttpURLConnection connection = null;

    String authentication = "dem" + ":" + "dem123";
    String encodedAuthentication = Base64
        .encodeToString(authentication.getBytes(), Base64.NO_WRAP);

    try {
        URL url = new URL(sUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("DELETE");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization",
            "Basic " + encodedAuthentication);
        connection.setRequestProperty("Accept-Charset", "utf-8,*");
        OutputStreamWriter streamWriter = new OutputStreamWriter(
            connection.getOutputStream());

        streamWriter.write(body);
        streamWriter.flush();
        StringBuilder stringBuilder = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStreamReader streamReader = new InputStreamReader(
                connection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(
                streamReader);
            String response = null;
            while ((response = bufferedReader.readLine()) != null) {
                stringBuilder.append(response + "\n");
            }
            bufferedReader.close();

            return new JSONObject(stringBuilder.toString());
        } else {
            Log.d("Put-Error", connection.getResponseMessage());
            return null;
        }
    } catch (Exception exception) {
        Log.e("Put-Exception", exception.toString());
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

 public static JSONObject ClearcartItems(Context ctx, String sUrl,
                                        String userid) throws   JSONException, IOException {
    JSONObject request = new JSONObject();
    Log.e("userid",""+userid);//I am getting cartid value here
    request.putOpt("Username", userid);
    sUrl = sUrl + "clear-all-cart-items";
    Log.e("del", "" + sUrl);
    return delete(sUrl, request.toString());
}


答:
This is not normal operation to store lists in a df, but here you need the index label of the Series so you can then append:

```<code>In [68]:
idx = df.loc[df['A'] == 3,'B'].index[0]
df.loc[df['A'] == 3,'B'][idx].append(12)
df

Out[68]:
   A           B
0  2   [4, 6, 8]
1  3  [6, 9, 12]
2  5        [10]
3  7          []
</code>```

Here df.loc[df['A'] == 3, 'B'] returns a Series:

```<code>In [70]:
df.loc[df['A'] == 3,'B']

Out[70]:
1    [6, 9]
Name: B, dtype: object
</code>```

The element stored here needs to be dereferenced using the index label:

```<code>In [71]:
df.loc[df['A'] == 3,'B'][1]

Out[71]:
[6, 9]
</code>```

So you need to figure out the index label:

```<code>In [72]:
df.loc[df['A'] == 3,'B'].index[0]

Out[72]:
1
</code>```

So you can then dereference the list and append

Title: How to select a single cell in a pandas dataframe by condition

Body:
This is not normal operation to store lists in a df, but here you need the index label of the Series so you can then append:

In [68]:
idx = df.loc[df['A'] == 3,'B'].index[0]
df.loc[df['A'] == 3,'B'][idx].append(12)
df

Out[68]:
   A           B
0  2   [4, 6, 8]
1  3  [6, 9, 12]
2  5        [10]
3  7          []

Here df.loc[df['A'] == 3, 'B'] returns a Series:

In [70]:
df.loc[df['A'] == 3,'B']

Out[70]:
1    [6, 9]
Name: B, dtype: object

The element stored here needs to be dereferenced using the index label:

In [71]:
df.loc[df['A'] == 3,'B'][1]

Out[71]:
[6, 9]

So you need to figure out the index label:

In [72]:
df.loc[df['A'] == 3,'B'].index[0]

Out[72]:
1

So you can then dereference the list and append


问:
Why should a Java programmer care about year 2038 bug?
Year 2038 Bug is all over the web, But this seems to be a unix issue. How will this affect java Date ?</p>

答: I don't believe it will impact the Java Date class as for as the programmer is concerned.  It's already using 64-bit values.  I can see it being a problem if you're using a data store that still uses 32-bit values.  I don't expect to see too many 32-bit OSes around in 27 years.</p>


问:
.innerHTML not changing value on maths quiz
As part of a school project I have to make a full randomised maths quiz (with three operators) using HTML, CSS, Javascript and JQuery, if necessairy. It also has to include css styling i.e. it has to look good as well.

I've hit a road block where my question doesn't appear in the assigned div of 'questions'. I understand I've made plenty of mistakes, this is my first time using javascript, any help would be appriciated and if you need the full code, just ask. Thanks.

```<code>function getNumber(){
    var oplist = ["=","-","*"];
    num1 = Math.floor((Math.random() * 10) + 1);
    num2 = Math.floor((Math.random() * 10) + 1);
    op = oplist [Math.floor(Math.random()* oplist.length)];
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
}

document.getElementById("questions").innerHTML = num1 + op + num2;
</code>```

答:
Apply inside the function return  num1 + op + num2+'='+ans;

var num1,num2,op
var ans =0;
function getNumber(){
    var oplist = ["=","-","*"];
    num1 = Math.floor((Math.random() * 10) + 1);
    num2 = Math.floor((Math.random() * 10) + 1);
    op = oplist [Math.floor(Math.random()* oplist.length)];
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
    return  num1 + op + num2+'='+ans;
}

document.getElementById("questions").innerHTML = getNumber();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="questions"></p></code>```

Body:
As part of a school project I have to make a full randomised maths quiz (with three operators) using HTML, CSS, Javascript and JQuery, if necessairy. It also has to include css styling i.e. it has to look good as well.

I've hit a road block where my question doesn't appear in the assigned div of 'questions'. I understand I've made plenty of mistakes, this is my first time using javascript, any help would be appriciated and if you need the full code, just ask. Thanks.

function getNumber(){
    var oplist = ["=","-","*"];
    num1 = Math.floor((Math.random() * 10) + 1);
    num2 = Math.floor((Math.random() * 10) + 1);
    op = oplist [Math.floor(Math.random()* oplist.length)];
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
}

document.getElementById("questions").innerHTML = num1 + op + num2;

Body:
Apply inside the function return  num1 + op + num2+'='+ans;

var num1,num2,op
var ans =0;
function getNumber(){
    var oplist = ["=","-","*"];
    num1 = Math.floor((Math.random() * 10) + 1);
    num2 = Math.floor((Math.random() * 10) + 1);
    op = oplist [Math.floor(Math.random()* oplist.length)];
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
    return  num1 + op + num2+'='+ans;
}

document.getElementById("questions").innerHTML = getNumber();

<p id="questions"></p>


问:
Plugins that can do the same something like wedding video
Does anyone know is there any plugins out there that can do something similar like those photo montage in video form for wedding? But it's in HTML5 or jQuery plugins.

Thanks in advance guys!

答:
check this one :

https://tympanus.net/Development/PhotoDesk/

if not what you are looking for, can you plz provide a screenshot or a link?


问:
Disable dynamically generated buttons in jquery
Each time a user selects a checkbox within a row of a table, and clicks save, it will generate a container which will hold the data in a specific format for that selected row.

Note: The data is coming in the table from JSON.

Similarly, the user will also have an option to add the data manually to the same container through a form.

Now, I all these containers or data holders will be appended to a parent container in the dom.

I need to swap each of these data containers, which I've achieved so far.
However, the buttons are not getting disabled or hidden for the first container and the last one.

Here's my script

```<code><script>
    function getData(){
        $('input[name="articles"]:checked').map(function() {
            var content =  JSON.parse(decodeURIComponent(this.value));
            content+= '<div class="container parent><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Name:</label><div class="col-md-8 article-data">'+name+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove">Delete  <span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';
            $('.box').html(content);
        });
        $('.remove').click(function(){
            $(this).parents('.parent').remove();
        });
        resetEvents();
    }
function addName(){
    var name= $("#articleTitle").val();
    content +='<div class="container parent><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Name:</label><div class="col-md-8 article-data">'+Count+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove">Delete  <span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';
        $('.box').html(content);
        $('.removeArticle').click(function(){
        $(this).parents('.parent').remove();
    });

}
function handleEvents() {
    $(".top-btn, .down-btn").prop("disabled", false).show();
    $(".parent:first").find(".top-btn").prop("disabled", true).hide();
    $(".parent:last").find(".down-btn").prop("disabled", true).hide();
}
function resetEvents() {
    $(".top-btn, .down-btn").unbind('click');
    handleEvents();
    $('.down-btn').click(function() {
        var toMove1 = $(this).parents('.article-box');
        $(toMove1).insertAfter($(toMove1).next());
        handleEvents();
    });
    $('.top-btn').click(function() {
        var toMove1 = $(this).parents('.article-box');
        $(toMove1).insertBefore($(toMove1).prev());
        handleEvents();
    });
}
</script>
</code>```

The first data holder will not have a top one to swap with. Hence, the top button should be disabled or hidden.

Similarly, the last data holder will not have a down one to swap with. Hence, the down button should be disabled or hidden.

I'm not able to understand what's wrong with what I wrote?

Note: This works perfectly fine if I use hard-coded data holders rather than generating it on runtime.

答:
You need to add a delegated listener.</p>

```<code>$('NearestParentElementThatAppearsOnPageLoad').on('event', 'ElementToApplyListenerTo', function() {
  // Do something
});
</code>```

Body:
Each time a user selects a checkbox within a row of a table, and clicks save, it will generate a container which will hold the data in a specific format for that selected row.

Note: The data is coming in the table from JSON.

Similarly, the user will also have an option to add the data manually to the same container through a form.

Now, I all these containers or data holders will be appended to a parent container in the dom.

I need to swap each of these data containers, which I've achieved so far.
However, the buttons are not getting disabled or hidden for the first container and the last one.

Here's my script

The first data holder will not have a top one to swap with. Hence, the top button should be disabled or hidden.

Similarly, the last data holder will not have a down one to swap with. Hence, the down button should be disabled or hidden.

I'm not able to understand what's wrong with what I wrote?

Note: This works perfectly fine if I use hard-coded data holders rather than generating it on runtime.

Body:
You need to add a delegated listener.

$('NearestParentElementThatAppearsOnPageLoad').on('event', 'ElementToApplyListenerTo', function() {
  // Do something
});


问:
Using dictionary mapping to call functions from Keyboard Input
I have several pre-defined functions in a dictionary:

```<code>dict = {
   'test1':test1(),
    'test2':test2(),
    'test3':test3()
}
</code>```

At this point I already have a question: after creating the dictionary these functions run automatically - why is that and how can I avoid it?

Ultimately, my goal is to type in e.g. "test2" and get the function executed (just the one in a controlled manner, not everything at once like above). First I wanted to use eval, but everyone advised against it, which I understand now. But what is the alternative? I tried

```<code>def select_function():
    try:
        return dict[input("Type in function ")]
    except KeyError:
        raise ValueError('Invalid input!')
select_function()
</code>```

as well as just

```<code>dict.get(input("Type in function "), 'Invalid input!')
</code>```

But both return an empty line if I type in the correct function. If I type in a wrong one I get my error message, therefore my command should work in general. I also know my functions work because, as I said, they get executed after I create the dictionary and they only print a greeting (a different one for each function for testing).

Did I do something wrong? Is there some other way to call functions without eval()?Thanks in advance.

答:
Do it like

```<code>dict = {
   'test1':test1,
    'test2':test2,
    'test3':test3
}
</code>```

Then

```<code>return dict[input("Type in function")]
</code>```

If you want to call that function, Just

```<code>return dict[input("Type in function")]()
</code>```

Body:
I have several pre-defined functions in a dictionary:

dict = {
   'test1':test1(),
    'test2':test2(),
    'test3':test3()
}

At this point I already have a question: after creating the dictionary these functions run automatically - why is that and how can I avoid it?

Ultimately, my goal is to type in e.g. "test2" and get the function executed (just the one in a controlled manner, not everything at once like above). First I wanted to use eval, but everyone advised against it, which I understand now. But what is the alternative? I tried

def select_function():
    try:
        return dict[input("Type in function ")]
    except KeyError:
        raise ValueError('Invalid input!')
select_function()

as well as just

dict.get(input("Type in function "), 'Invalid input!')

But both return an empty line if I type in the correct function. If I type in a wrong one I get my error message, therefore my command should work in general. I also know my functions work because, as I said, they get executed after I create the dictionary and they only print a greeting (a different one for each function for testing).

Did I do something wrong? Is there some other way to call functions without eval()?Thanks in advance.

Body:
Do it like

dict = {
   'test1':test1,
    'test2':test2,
    'test3':test3
}

Then

return dict[input("Type in function")]

If you want to call that function, Just

return dict[input("Type in function")]()


问:
Put a Linearlayout under the ListView
I'm facing problem to put a linearlayout under the listview like what is shown in this image link:

I want the layout with the Add icon and text:"Add New Members" to be displayed under the listview. What am I doing wrong? Pls help me to solve the problem. Thank you very much.

This is the xml file for the layout

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.thomasbrown.myapplication.MemberActivity"
android:background="@android:color/white">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/groupID"
    android:textSize="20sp"
    android:layout_marginBottom="15dp" />

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/white"
        android:layout_weight="1" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            app:srcCompat="@drawable/add"
            android:id="@+id/imageView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="80dp"
            android:layout_height="60dp"
            android:layout_weight="1" />

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/addMember"
                android:text="Add New Members"
                android:textSize="18sp"
                android:textColor="@android:color/holo_red_dark"
            android:layout_weight="1"
            android:layout_gravity="center_vertical" />
    </LinearLayout>

</LinearLayout>

<Button
    android:text="Leave this group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/leaveGroupButton"
    android:background="@color/colorPrimary"
    android:layout_gravity="bottom|end" />

</LinearLayout>
</code>```

答:
Try RelativeLayout and use android:layout_above as shown below:</p>

```<code>    <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <ListView
                android:id="@+id/your_listview"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_above="@+id/your_layout_with_buttons" />

            <LinearLayout
                android:layout_alignParentBottom="true"
                android:id="@+id/your_layout_with_buttons"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >

//your buttons come here

            </LinearLayout>
        </RelativeLayout>
</code>```

Title: Put a Linearlayout under the ListView

Body:
I'm facing problem to put a linearlayout under the listview like what is shown in this image link:

I want the layout with the Add icon and text:"Add New Members" to be displayed under the listview. What am I doing wrong? Pls help me to solve the problem. Thank you very much.

This is the xml file for the layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.thomasbrown.myapplication.MemberActivity"
android:background="@android:color/white">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/groupID"
    android:textSize="20sp"
    android:layout_marginBottom="15dp" />

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/white"
        android:layout_weight="1" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            app:srcCompat="@drawable/add"
            android:id="@+id/imageView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="80dp"
            android:layout_height="60dp"
            android:layout_weight="1" />

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/addMember"
                android:text="Add New Members"
                android:textSize="18sp"
                android:textColor="@android:color/holo_red_dark"
            android:layout_weight="1"
            android:layout_gravity="center_vertical" />
    </LinearLayout>

</LinearLayout>

<Button
    android:text="Leave this group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/leaveGroupButton"
    android:background="@color/colorPrimary"
    android:layout_gravity="bottom|end" />

</LinearLayout>

Body:
Try RelativeLayout and use android:layout_above as shown below:

    <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <ListView
                android:id="@+id/your_listview"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_above="@+id/your_layout_with_buttons" />

            <LinearLayout
                android:layout_alignParentBottom="true"
                android:id="@+id/your_layout_with_buttons"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >

//your buttons come here

            </LinearLayout>
        </RelativeLayout>


问:
How do i find the selected id and name of radiobutton list
How do I find the selected id of radiobutton in list.

Here is the radiobutton:

```<code><input name="1" id="1" type="radio">
</code>```

Radiobutton are dynamics.

Here is the dynamic radio button list.

```<code><div class="row">
  <div class="form-group">
      <div class="col-md-12">
          <label>1. Here is the question??</label>
          <div class="icheck-list">
              <label class="icheck-list" id="1">

                  <input name="1" id="1" type="radio">Strongly Disagree
                  <span></span>
              </label>
          </div>
          <div class="icheck-list">
              <label class="icheck-list" id="2">
                  <input name="1" id="2" type="radio">Disagree
                  <span></span>
              </label>
          </div>
          <div class="icheck-list">
              <label class="icheck-list" id="3">
                  <input name="1" id="3" type="radio">Neither Agree or Disagree
                  <span></span>
              </label>
          </div>
          <div class="icheck-list">
              <label class="icheck-list" id="4">
                  <input name="1" id="4" type="radio">Agree
                  <span></span>
              </label>
          </div>
          <div class="icheck-list">
              <label class="icheck-list" id="5">
                  <input name="1" id="5" type="radio">Strongly Agree
                  <span></span>
              </label>
          </div>
      </div>
  </div>
</div>
</code>```

There is 5 possible answers for a question.

I am using mvc 4.

For next question the i.e. for question 2.

The answer radiobutton is just like

```<code><input name="2" id="11" type="radio">Strongly Disagree
</code>```

So how do I find the selected radio button id and name???

here is the html i am using in view page.

```<code>        <div class="tab-pane active" id="tab1">

                                        @foreach (var items in Model.ParentList)
                                        {
                                            <div class="row">

                                                <div class="form-group">

                                                    <div class="col-md-12">

                                                        <label>@items.QuestionText</label>

                                                        @foreach (var ch in Model.ChildList)
                                                        {
                                                            if (items.QuestionId == ch.QuestionId)
                                                            {

                                                                <div class="icheck-list">
                                                                    <label class="icheck-list" id="@ch.AnswerId">
                                                                        @*<input type="checkbox"> @Html.DisplayFor(model => model.Answers[j].AnswerText)*@
                                                                        <input name="@ch.QuestionId" id="@ch.AnswerId" type="radio">@ch.AnswerText
                                                                        <span></span>
                                                                    </label> </div>
 }

                                                        }
 </div>
</div>
 }
</div>
</code>```

there is total 10 questions and each questions having 5 multiple choice answers.
so Model.ParentList i got total 10 questions with id
in Model.ChildList i got 50 answers.
so how do i bind and got the selected radio button value??

答:
First attach an event listener which detects the change in selection.

```<code>jQuery( "input[name='1']" ).on( "click", function() {
  var id = jQuery(this).attr("id");
  var name = jQuery(this).attr("name");
  alert("Id:"+ id);
  alert("Name: "+name);

});
</code>```

A similar method can be used where input[name='2']

Body:
How do I find the selected id of radiobutton in list.

Here is the radiobutton:

<input name="1" id="1" type="radio">

Radiobutton are dynamics.

Here is the dynamic radio button list.

          1. Here is the question??

                  <input name="1" id="1" type="radio">Strongly Disagree

                  <input name="1" id="2" type="radio">Disagree

                  <input name="1" id="3" type="radio">Neither Agree or Disagree

                  <input name="1" id="4" type="radio">Agree

                  <input name="1" id="5" type="radio">Strongly Agree

There is 5 possible answers for a question.

I am using mvc 4.

For next question the i.e. for question 2.

The answer radiobutton is just like

<input name="2" id="11" type="radio">Strongly Disagree

So how do I find the selected radio button id and name???

here is the html i am using in view page.

                                        @foreach (var items in Model.ParentList)
                                        {

                                                        @items.QuestionText

                                                        @foreach (var ch in Model.ChildList)
                                                        {
                                                            if (items.QuestionId == ch.QuestionId)
                                                            {

                                                                        @*<input type="checkbox"> @Html.DisplayFor(model => model.Answers[j].AnswerText)*@
                                                                        <input name="@ch.QuestionId" id="@ch.AnswerId" type="radio">@ch.AnswerText

 }

                                                        }

 }

there is total 10 questions and each questions having 5 multiple choice answers.
so Model.ParentList i got total 10 questions with id
in Model.ChildList i got 50 answers.
so how do i bind and got the selected radio button value??

Body:
First attach an event listener which detects the change in selection.

jQuery( "input[name='1']" ).on( "click", function() {
  var id = jQuery(this).attr("id");
  var name = jQuery(this).attr("name");
  alert("Id:"+ id);
  alert("Name: "+name);

});

A similar method can be used where input[name='2']


问:
FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri()) return null on Facebook
I've developed an mvc 5 application using nopcommerce and i use facebook login using External callback it was working but now it is not working and i can't find out actual problem. And using this below code

this.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

and it's returning me always null and authentication status failed i searched on web an do every thing and followed that steps but still i can't login with facebook.

My code is like this in FacebookProviderAuthorizer.cs

```<code>private AuthorizeState VerifyAuthentication(string returnUrl)
{
   var authResult = DotNetOpenAuth.AspNet.Clients.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

   if (authResult.IsSuccessful)
   {
   }
}
</code>```

And then write Call back method

```<code>private Uri GenerateLocalCallbackUri()
{
    string url = string.Format("{0}plugins/externalauthFacebook/logincallback/", _webHelper.GetStoreLocation());
    return new Uri(url);
}
</code>```

Then generate service login url

```<code>private Uri GenerateServiceLoginUrl()
{
   //code copied from DotNetOpenAuth.AspNet.Clients.FacebookClient file
   var builder = new UriBuilder("https://www.facebook.com/dialog/oauth");
   var args = new Dictionary<string, string>();
   args.Add("client_id", _facebookExternalAuthSettings.ClientKeyIdentifier);
   args.Add("redirect_uri", GenerateLocalCallbackUri().AbsoluteUri);
   args.Add("response_type", "token");
   args.Add("scope", "email");
   AppendQueryArgs(builder, args);
   return builder.Uri;
}
</code>```

答:
As suggested by @SteveTerry We need to update QueryAccessToken function in FacebookClient class. unfortunately "FacebookClient" is sealed class so we cannot inherit and override. So whichever way you choose is up to you. Here is what end result should look like:

Old code of this function was:

```<code>protected override string QueryAccessToken(Uri returnUrl, string authorizationCode) {
// Note: Facebook doesn't like us to url-encode the redirect_uri value
var builder = new UriBuilder(TokenEndpoint);
builder.AppendQueryArgs(
    new Dictionary<string, string> {
        { "client_id", this.appId },
        { "redirect_uri", NormalizeHexEncoding(returnUrl.AbsoluteUri) },
        { "client_secret", this.appSecret },
        { "code", authorizationCode },
        { "scope", "email" },
    });

using (webclient client = new webclient()) {
    string data = client.downloadstring(builder.uri);
    if (string.isnullorempty(data)) {
        return null;
    }

    var parsedquerystring = httputility.parsequerystring(data);
    return parsedquerystring["access_token"];
}
</code>```

}

And to support new version of fb api it should be like this:

```<code>/// <summary>
/// Contains access_token of a Facebook user.
/// </summary>
[DataContract]
[EditorBrowsable(EditorBrowsableState.Never)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Facebook", Justification = "Brand name")]
public class FacebookAccessTokenData
{
    #region Public Properties

    /// <summary>
    ///
    /// </summary>
    [DataMember(Name = "access_token")]
    public string AccessToken { get; set; }

    /// <summary>
    ///
    /// </summary>
    [DataMember(Name = "token_type")]
    public string TokenType { get; set; }

    /// <summary>
    ///
    /// </summary>
    [DataMember(Name = "expires_in")]
    public string ExpiresIn { get; set; }

    #endregion
}

/// <summary>
/// Obtains an access token given an authorization code and callback URL.
/// </summary>
/// <param name="returnUrl">
/// The return url.
/// </param>
/// <param name="authorizationCode">
/// The authorization code.
/// </param>
/// <returns>
/// The access token.
/// </returns>
protected override string QueryAccessToken(Uri returnUrl, string authorizationCode) {
    // Note: Facebook doesn't like us to url-encode the redirect_uri value
    var builder = new UriBuilder(TokenEndpoint);
    builder.AppendQueryArgs(
        new Dictionary<string, string> {
            { "client_id", this.appId },
            { "redirect_uri", NormalizeHexEncoding(returnUrl.AbsoluteUri) },
            { "client_secret", this.appSecret },
            { "code", authorizationCode },
            { "scope", "email" },
        });

    FacebookAccessTokenData graphData;
    var request = WebRequest.Create(builder.Uri);
    using (var response = request.GetResponse())
    {
        using (var responseStream = response.GetResponseStream())
        {
            graphData = JsonHelper.Deserialize<FacebookAccessTokenData>(responseStream);
        }
    }

    return graphData.AccessToken;
}
</code>```

Body:
I've developed an mvc 5 application using nopcommerce and i use facebook login using External callback it was working but now it is not working and i can't find out actual problem. And using this below code

this.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

and it's returning me always null and authentication status failed i searched on web an do every thing and followed that steps but still i can't login with facebook.

My code is like this in FacebookProviderAuthorizer.cs

private AuthorizeState VerifyAuthentication(string returnUrl)
{
   var authResult = DotNetOpenAuth.AspNet.Clients.FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri());

   if (authResult.IsSuccessful)
   {
   }
}

And then write Call back method

private Uri GenerateLocalCallbackUri()
{
    string url = string.Format("{0}plugins/externalauthFacebook/logincallback/", _webHelper.GetStoreLocation());
    return new Uri(url);
}

Then generate service login url

private Uri GenerateServiceLoginUrl()
{
   //code copied from DotNetOpenAuth.AspNet.Clients.FacebookClient file
   var builder = new UriBuilder("https://www.facebook.com/dialog/oauth");
   var args = new Dictionary<string, string>();
   args.Add("client_id", _facebookExternalAuthSettings.ClientKeyIdentifier);
   args.Add("redirect_uri", GenerateLocalCallbackUri().AbsoluteUri);
   args.Add("response_type", "token");
   args.Add("scope", "email");
   AppendQueryArgs(builder, args);
   return builder.Uri;
}

Body:
As suggested by @SteveTerry We need to update QueryAccessToken function in FacebookClient class. unfortunately "FacebookClient" is sealed class so we cannot inherit and override. So whichever way you choose is up to you. Here is what end result should look like:

Old code of this function was:

protected override string QueryAccessToken(Uri returnUrl, string authorizationCode) {
// Note: Facebook doesn't like us to url-encode the redirect_uri value
var builder = new UriBuilder(TokenEndpoint);
builder.AppendQueryArgs(
    new Dictionary<string, string> {
        { "client_id", this.appId },
        { "redirect_uri", NormalizeHexEncoding(returnUrl.AbsoluteUri) },
        { "client_secret", this.appSecret },
        { "code", authorizationCode },
        { "scope", "email" },
    });

using (webclient client = new webclient()) {
    string data = client.downloadstring(builder.uri);
    if (string.isnullorempty(data)) {
        return null;
    }

    var parsedquerystring = httputility.parsequerystring(data);
    return parsedquerystring["access_token"];
}

}

And to support new version of fb api it should be like this:

/// <summary>
/// Contains access_token of a Facebook user.
/// </summary>
[DataContract]
[EditorBrowsable(EditorBrowsableState.Never)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Facebook", Justification = "Brand name")]
public class FacebookAccessTokenData
{
    #region Public Properties

    /// <summary>
    ///
    /// </summary>
    [DataMember(Name = "access_token")]
    public string AccessToken { get; set; }

    /// <summary>
    ///
    /// </summary>
    [DataMember(Name = "token_type")]
    public string TokenType { get; set; }

    /// <summary>
    ///
    /// </summary>
    [DataMember(Name = "expires_in")]
    public string ExpiresIn { get; set; }

    #endregion
}

/// <summary>
/// Obtains an access token given an authorization code and callback URL.
/// </summary>
/// <param name="returnUrl">
/// The return url.
/// </param>
/// <param name="authorizationCode">
/// The authorization code.
/// </param>
/// <returns>
/// The access token.
/// </returns>
protected override string QueryAccessToken(Uri returnUrl, string authorizationCode) {
    // Note: Facebook doesn't like us to url-encode the redirect_uri value
    var builder = new UriBuilder(TokenEndpoint);
    builder.AppendQueryArgs(
        new Dictionary<string, string> {
            { "client_id", this.appId },
            { "redirect_uri", NormalizeHexEncoding(returnUrl.AbsoluteUri) },
            { "client_secret", this.appSecret },
            { "code", authorizationCode },
            { "scope", "email" },
        });

    FacebookAccessTokenData graphData;
    var request = WebRequest.Create(builder.Uri);
    using (var response = request.GetResponse())
    {
        using (var responseStream = response.GetResponseStream())
        {
            graphData = JsonHelper.Deserialize<FacebookAccessTokenData>(responseStream);
        }
    }

    return graphData.AccessToken;
}


问:
How to get RTF contents from UIPasteboard after UIWebView copy?
I have a UIWebView showing some custom HTML content. If I tap and hold, then select some text and tap the Copy option, the text gets added to UIPasteboard with the key "com.apple.rtfd". My problem now is that I can't find any way of extracting the actual textual contents of what I just copied. If I use this code:

```<code>NSString *contents = [NSString stringWithUTF8String:[data bytes]];
</code>```

it returns the literal string "rtfd", regardless of what text I actually copied from the UIWebView. If I use this code:

```<code>NSString *contents = [[NSString alloc] initWithData:data
    encoding:NSUTF8StringEncoding];
</code>```

I get a blank string. How can I get the actual text contents of what I just copied into the pasteboard?

答:
A correct Swift solution for extract rft text content what copied from Safari:</p>

```<code>guard let rtf = textItem["public.rtf"] as? String,
        let rtfData = rtf.data(using: .utf8) else {
            return
    }
    do {
        let attr = try NSAttributedString(data: rtfData,
                                          options: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType],
                                          documentAttributes: nil)

        //DO SOMETHING ...
    }
    catch (let exc) {
        print(exc.localizedDescription)
    }
</code>```

Body:
I have a UIWebView showing some custom HTML content. If I tap and hold, then select some text and tap the Copy option, the text gets added to UIPasteboard with the key "com.apple.rtfd". My problem now is that I can't find any way of extracting the actual textual contents of what I just copied. If I use this code:

NSString *contents = [NSString stringWithUTF8String:[data bytes]];

it returns the literal string "rtfd", regardless of what text I actually copied from the UIWebView. If I use this code:

NSString *contents = [[NSString alloc] initWithData:data
    encoding:NSUTF8StringEncoding];

I get a blank string. How can I get the actual text contents of what I just copied into the pasteboard?

Body:
A correct Swift solution for extract rft text content what copied from Safari:

guard let rtf = textItem["public.rtf"] as? String,
        let rtfData = rtf.data(using: .utf8) else {
            return
    }
    do {
        let attr = try NSAttributedString(data: rtfData,
                                          options: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType],
                                          documentAttributes: nil)

        //DO SOMETHING ...
    }
    catch (let exc) {
        print(exc.localizedDescription)
    }


问:
Using GROUP BY in mysql giving syntax error
I have this query:

```<code>select * FROM `posters` p
INNER JOIN `poster_logs` pl ON pl.`pos_id`= p.`id`
WHERE pl.`log` = 'Accepted' AND p.`book`='book1' AND
p.`category`='category1'
ORDER BY p.`category`, p.`id`
</code>```

That returns to me a poster_logs.pos_id several times and I dont want this so I tried to add "group by pl.pos_id" in this way:

```<code>select * FROM `posters` p
INNER JOIN `poster_logs` pl ON pl.`pos_id`= p.`id`
WHERE pl.`log` = 'Accepted' AND p.`book`='book1' AND
p.`category`='category1'
group by pl.`pos_id`
ORDER BY p.`category`, p.`id`
</code>```

But that gives me a syntax error and I dont know what I'm doing wrong. I'm really beginner with SQL.

答:
What version of MySQL are you using?

Your current query:-

```<code>SELECT *
FROM `posters` p
INNER JOIN `poster_logs` pl ON pl.`pos_id`= p.`id`
WHERE pl.`log` = 'Accepted'
AND p.`book`='book1'
AND p.`category`='category1'
GROUP BY pl.`pos_id`
ORDER BY p.`category`, p.`id`
</code>```

is not using any aggregate fields (but as you have used SELECT *, not a clue which fields it is returning).

Older versions of MySQL do support this , although it is against SQL standards except in certain limited circumstances.

Newer versions of SQL have support for this turned off by default, although you can set an option to enable it:-

https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them. (Before 5.7.5, MySQL does not detect functional dependency and ONLY_FULL_GROUP_BY is not enabled by default. For a description of pre-5.7.5 behavior, see the MySQL 5.6 Reference Manual.)

With your current query, if it worked then it would bring back 1 row per pos_id, but which row the other columns come from is not defined. Normally you would want a specific row (maybe the first, maybe the last).

Body:
I have this query:

select * FROM `posters` p
INNER JOIN `poster_logs` pl ON pl.`pos_id`= p.`id`
WHERE pl.`log` = 'Accepted' AND p.`book`='book1' AND
p.`category`='category1'
ORDER BY p.`category`, p.`id`

That returns to me a poster_logs.pos_id several times and I dont want this so I tried to add "group by pl.pos_id" in this way:

select * FROM `posters` p
INNER JOIN `poster_logs` pl ON pl.`pos_id`= p.`id`
WHERE pl.`log` = 'Accepted' AND p.`book`='book1' AND
p.`category`='category1'
group by pl.`pos_id`
ORDER BY p.`category`, p.`id`

But that gives me a syntax error and I dont know what I'm doing wrong. I'm really beginner with SQL.

Body:
What version of MySQL are you using?

Your current query:-

SELECT *
FROM `posters` p
INNER JOIN `poster_logs` pl ON pl.`pos_id`= p.`id`
WHERE pl.`log` = 'Accepted'
AND p.`book`='book1'
AND p.`category`='category1'
GROUP BY pl.`pos_id`
ORDER BY p.`category`, p.`id`

is not using any aggregate fields (but as you have used SELECT *, not a clue which fields it is returning).

Older versions of MySQL do support this , although it is against SQL standards except in certain limited circumstances.

Newer versions of SQL have support for this turned off by default, although you can set an option to enable it:-

https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them. (Before 5.7.5, MySQL does not detect functional dependency and ONLY_FULL_GROUP_BY is not enabled by default. For a description of pre-5.7.5 behavior, see the MySQL 5.6 Reference Manual.)

With your current query, if it worked then it would bring back 1 row per pos_id, but which row the other columns come from is not defined. Normally you would want a specific row (maybe the first, maybe the last).