问:
Twig Join, display 0 value
I have an array of integers I am rendering with join in a twig template. If the value is zero, however, it is not displaying. Wondering if there is a way to resolve this easily?

Thanks

```<code><b>Snow Last 24 Hours:</b> {{ report.snowLast24Hours|join(' - ') }} in
</code>```

答:
You can try this (with join and replace):

```<code>{{ (snowLast24Hours|join()|replace({'0':''}) is empty) ? '' : snowLast24Hours|join(' - ') }}
</code>```

Or with join and trim:

```<code>{{ (snowLast24Hours|join()|trim('0') is empty) ? '' : snowLast24Hours|join(' - ') }}
</code>```

Title: Twig Join, display 0 value

Body:
I have an array of integers I am rendering with join in a twig template. If the value is zero, however, it is not displaying. Wondering if there is a way to resolve this easily?

Thanks

Snow Last 24 Hours: {{ report.snowLast24Hours|join(' - ') }} in

Body:
You can try this (with join and replace):

{{ (snowLast24Hours|join()|replace({'0':''}) is empty) ? '' : snowLast24Hours|join(' - ') }}

Or with join and trim:

{{ (snowLast24Hours|join()|trim('0') is empty) ? '' : snowLast24Hours|join(' - ') }}


来源: stackexchange

问:
.NET's GUID structure
http://msdn.microsoft.com/en-us/library/system.guid.aspx

How does it work? How does it guarantee unique ID? Does it only rely on probability or is there another trick? Can I always trust it to give unique id or what are cases where I should avoid guid?

答: A Guid doesn't guarantee a unique ID, it just has a very low probability of generating a duplicate one.

ContentLicense: CC BY-SA 2.5

Title: .NET's GUID structure


问:
Python- if statement evaluation pattern
what the heck is the if statement doing?

```<code>>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> for i in xrange(len(list)):
...   if i / 2:
...     del(list[0])
</code>```

and this will result in ['e', 'f']

I dont know that the if is doing.

答:
Update your code like this to know for each iteration what happens with your list.

```<code>list = ['a', 'b', 'c', 'd', 'e', 'f']
for i in xrange(len(list)):
    print (i)
    print list
    if (i / 2):
        del(list[0])

print list
</code>```

for 1st,2nd iteration when i=0 or i=1 then statement if i/2: evaluates to zero i.e False hence code under if statement does not executes.

for Further iterations from i=2 to i=5 then statement if i/2: evaluates to some value i.e. considered True hence code under if statement executes and deletes the first element of list.

Hope this helps.

ContentLicense: CC BY-SA 3.0

Title: Python- if statement evaluation pattern

Body:
what the heck is the if statement doing?

>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> for i in xrange(len(list)):
...   if i / 2:
...     del(list[0])

and this will result in ['e', 'f']

I dont know that the if is doing.

Body:
Update your code like this to know for each iteration what happens with your list.

list = ['a', 'b', 'c', 'd', 'e', 'f']
for i in xrange(len(list)):
    print (i)
    print list
    if (i / 2):
        del(list[0])

print list

for 1st,2nd iteration when i=0 or i=1 then statement if i/2: evaluates to zero i.e False hence code under if statement does not executes.

for Further iterations from i=2 to i=5 then statement if i/2: evaluates to some value i.e. considered True hence code under if statement executes and deletes the first element of list.

Hope this helps.


问:
Is it possible to use position:fixed or an alternative to this and have it remain in the natural flow?
I have a fixed sidebar:

```<code>#sidebar {
    background-color: #eaeaea;
    width: 18.5vw;
    height: 100vh;
    position: fixed;
    align-items: stretch;
}
</code>```

Since it's position: fixed; it is not in the natural flow, meaning that if I don't give the main content a width relative to the sidebar and float/position it right, then the main content will appear in front of/behind it, like this: (http://picpaste.com/pics/screenshot-PiBDmenN.1490873729.png).

This is hard to do with this content as it's a Wordpress plugin template that contains more templates which contain more templates and no actual content, and any containers I try to add to the main template don't show up (in the case of this particular page, at least). It did work with a different page and template: (http://picpaste.com/pics/screenshot1-BPi0QsIX.1490873805.png).

My question is if it's possible to fix the sidebar in position without it leaving the natural flow, so that i don't have to give all the main content a relative width - the main content isn't always grouped together and I end up having to target many individual elements to do this which could be problematic in the future if new elements are introduced.

Here is the beginning of the code of the template that doesn't see the container (called .match-wrapper):

```<code><?php
/**
 * The Template for displaying job details
 *
 * Override this template by copying it to yourtheme/simple_job_board/single-jobpost.php
 *
 * @author      PressTigers
 * @package     Simple_Job_Board
 * @subpackage  Simple_Job_Board/Templates
 * @version     1.1.0
 * @since       2.2.0
 * @since       2.2.3   Enqueued Front Styles & Revised the HTML structure.
 * @since       2.2.4   Enqueued Front end Scripts.
 * @since       2.3.0   Added "sjb_archive_template" filter.
 */
get_header(); ?>

<img src = '<?php bloginfo('template_directory'); ?>/images/nieuwspagina-header.png' class="not-front-page-header" />

<div class="match-wrapper">

<?php
ob_start();
global $post;

/**
 * Enqueue Frontend Scripts.
 *
 * @since   2.2.4
 */
do_action('sjb_enqueue_scripts');

/*code continues....
</code>```

Many thanks.

答:
yes... flex box is one way - this question is similar to yours

Flexbox responsive layout with multiple sidebars

Body:
I have a fixed sidebar:

#sidebar {
    background-color: #eaeaea;
    width: 18.5vw;
    height: 100vh;
    position: fixed;
    align-items: stretch;
}

Since it's position: fixed; it is not in the natural flow, meaning that if I don't give the main content a width relative to the sidebar and float/position it right, then the main content will appear in front of/behind it, like this: (http://picpaste.com/pics/screenshot-PiBDmenN.1490873729.png).

This is hard to do with this content as it's a Wordpress plugin template that contains more templates which contain more templates and no actual content, and any containers I try to add to the main template don't show up (in the case of this particular page, at least). It did work with a different page and template: (http://picpaste.com/pics/screenshot1-BPi0QsIX.1490873805.png).

My question is if it's possible to fix the sidebar in position without it leaving the natural flow, so that i don't have to give all the main content a relative width - the main content isn't always grouped together and I end up having to target many individual elements to do this which could be problematic in the future if new elements are introduced.

Here is the beginning of the code of the template that doesn't see the container (called .match-wrapper):

<?php
/**
 * The Template for displaying job details
 *
 * Override this template by copying it to yourtheme/simple_job_board/single-jobpost.php
 *
 * @author      PressTigers
 * @package     Simple_Job_Board
 * @subpackage  Simple_Job_Board/Templates
 * @version     1.1.0
 * @since       2.2.0
 * @since       2.2.3   Enqueued Front Styles & Revised the HTML structure.
 * @since       2.2.4   Enqueued Front end Scripts.
 * @since       2.3.0   Added "sjb_archive_template" filter.
 */
get_header(); ?>

<img src = '<?php bloginfo('template_directory'); ?>/images/nieuwspagina-header.png' class="not-front-page-header" />

<?php
ob_start();
global $post;

/**
 * Enqueue Frontend Scripts.
 *
 * @since   2.2.4
 */
do_action('sjb_enqueue_scripts');

/*code continues....

Many thanks.


问:
make null value as X sql server
i have problem.., i want to display the null value as 'X'
i has been using the case statement but still failed,
i already using Isnull and failed too.

```<code>DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @X AS NVARCHAR(MAX)

SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(code)
FROM (SELECT DISTINCT code FROM edrsDB..tbl_users where area='west' ) AS status

SET @DynamicPivotQuery =
N'SELECT date, '+ @ColumnName +'
FROM (
SELECT DISTINCT userid, status , DATEPART(dd, [date]) as Date
FROM edrsDB..tbl_status
WHERE DatePart(MM, [Date]) = 3
 And DATEPART(YYYY, [Date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[date]) as Date
FROM edrsDB..tbl_public_holiday
WHERE DatePart(MM, [Date]) = 3
And DATEPART(YYYY, [Date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[Date]) as Date
FROM edrsDB..tbl_station_weekend
WHERE DatePart(MM, [Date]) = 3
And DATEPART(YYYY, [Date]) = 2017
And date IS NOT NULL
 ) AS x
 PIVOT
 (
max(status)
FOR userid IN (' + @ColumnName + ')
) AS PVTTable'
 EXEC sp_executesql @DynamicPivotQuery
</code>```

this is ouput.. , i want null to be display as 'X'

output

答:
You can use isnull() or coalesce() in sql server.

```<code>select isnull(col,'X')
</code>```

or

```<code>select coalesce(col,'X')
</code>```

The main difference between the two is that coalesce() can support more than 2 parameters, and it selects the first one that is not null. More differences between the two are answered here.

```<code>select coalesce(col,col2,'X')
</code>```

coalesce() is also standard ANSI sql, so you will find it in most RDBMS. isnull() is specific to sql server.

Reference:

isnull() - msdn

coalesce() - msdn

Title: make null value as X sql server

Body:
i have problem.., i want to display the null value as 'X'
i has been using the case statement but still failed,
i already using Isnull and failed too.

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @X AS NVARCHAR(MAX)

SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(code)
FROM (SELECT DISTINCT code FROM edrsDB..tbl_users where area='west' ) AS status

SET @DynamicPivotQuery =
N'SELECT date, '+ @ColumnName +'
FROM (
SELECT DISTINCT userid, status , DATEPART(dd, [date]) as Date
FROM edrsDB..tbl_status
WHERE DatePart(MM, [Date]) = 3
 And DATEPART(YYYY, [Date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[date]) as Date
FROM edrsDB..tbl_public_holiday
WHERE DatePart(MM, [Date]) = 3
And DATEPART(YYYY, [Date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[Date]) as Date
FROM edrsDB..tbl_station_weekend
WHERE DatePart(MM, [Date]) = 3
And DATEPART(YYYY, [Date]) = 2017
And date IS NOT NULL
 ) AS x
 PIVOT
 (
max(status)
FOR userid IN (' + @ColumnName + ')
) AS PVTTable'
 EXEC sp_executesql @DynamicPivotQuery

this is ouput.. , i want null to be display as 'X'

output

Body:
You can use isnull() or coalesce() in sql server.

select isnull(col,'X')

or

select coalesce(col,'X')

The main difference between the two is that coalesce() can support more than 2 parameters, and it selects the first one that is not null. More differences between the two are answered here.

select coalesce(col,col2,'X')

coalesce() is also standard ANSI sql, so you will find it in most RDBMS. isnull() is specific to sql server.

Reference:

isnull() - msdn

coalesce() - msdn


问:
Find if value exists in multiple list and get names of it
I found similar question, but I'm not able to convert answer to match my needs.
(Find if value exists in multiple lists)

So, basicly, I have multiple lists, and I want to list all of them, which contain current user username.

```<code>import getpass

value = getpass.getuser()
rep_WOHTEL = ['user1','user2','user3']
rep_REPDAY = ['user4','user1','user3']
rep_ZARKGL = ['user3','user1','user2']
rep_WOHOPL = ['user3','user2','user5']

#No idea how code below works
w = next(n for n,v in filter(lambda t: isinstance(t[1],list) and t[0].startswith('rep_'), globals().items()) if value in v)
print(w)
</code>```

If current user is user1, I want it to print rep_WOHTEL, rep_REPDAY and rep_ZARKGL. Code above print only ony of them.

How should I change this part of script, to print all I want?

答:
Like I commented in the linked question, iterating through all of globals() or locals() is a bad idea. Store your lists together in a single dictionary or list, and iterate through that instead.

```<code>value = "user1"
named_lists = {
    "WOHTEL": ['user1','user2','user3'],
    "REPDAY": ['user4','user1','user3'],
    "ZARKGL": ['user3','user1','user2'],
    "WOHOPL": ['user3','user2','user5']
}

names = [name for name, seq in named_lists.items() if value in seq]
print(names)
</code>```

Result:

```<code>['REPDAY', 'ZARKGL', 'WOHTEL']
</code>```

Body:
I found similar question, but I'm not able to convert answer to match my needs.
(Find if value exists in multiple lists)

So, basicly, I have multiple lists, and I want to list all of them, which contain current user username.

import getpass

value = getpass.getuser()
rep_WOHTEL = ['user1','user2','user3']
rep_REPDAY = ['user4','user1','user3']
rep_ZARKGL = ['user3','user1','user2']
rep_WOHOPL = ['user3','user2','user5']

#No idea how code below works
w = next(n for n,v in filter(lambda t: isinstance(t[1],list) and t[0].startswith('rep_'), globals().items()) if value in v)
print(w)

If current user is user1, I want it to print rep_WOHTEL, rep_REPDAY and rep_ZARKGL. Code above print only ony of them.

How should I change this part of script, to print all I want?

Body:
Like I commented in the linked question, iterating through all of globals() or locals() is a bad idea. Store your lists together in a single dictionary or list, and iterate through that instead.

value = "user1"
named_lists = {
    "WOHTEL": ['user1','user2','user3'],
    "REPDAY": ['user4','user1','user3'],
    "ZARKGL": ['user3','user1','user2'],
    "WOHOPL": ['user3','user2','user5']
}

names = [name for name, seq in named_lists.items() if value in seq]
print(names)

Result:

['REPDAY', 'ZARKGL', 'WOHTEL']


问:
WPF selection of a TreeView item as context menu is called
This problem relates mainly to context menus, but in my specific case it's about a TreeView control.

The TreeView item contains a StackPanel, and on that StackPanel is a ContextMenu property, which I have assigned to a StaticResource (which is a ContextMenu of course). Said ContextMenu leads to an ICommand and, thus, does its thing.

At present (and this is the default behaviour I believe), right clicking on an item in the TreeView does not select that item. This is common in Windows, but doesn't happen here. I would like it to happen (but I don't know how).

A little follow up information: I do have a selected item in the TreeView and this changes with a mouse left click. It's not a left click event, though, rather the event is 'SelectedItemChanged'. This leads to a method whereby I set the 'SelectedItem' in my data context (view model) to the SelectedItem. It has to be done this way because a TreeView's selected item is 'read only'.

That code is here, although I'm not sure how useful it is to the issue at hand:

```<code>private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        if (this.ScenesTreeView01 == null)
            return;

        if (this.ScenesTreeView01.DataContext == null)
            return;

        var DataContext = this.ScenesTreeView01.DataContext as ScenesViewModel;

        if (e.NewValue is SceneViewModel)
        {
            DataContext.SelectedScene = (SceneViewModel)e.NewValue;
        }

        if (e.NewValue is CharacterViewModel)
        {

            DataContext.SelectedCharacter = (CharacterViewModel)e.NewValue;
        }
    }
</code>```

Since there doesn't seem to be a place where it says 'okay you left clicked and so here is the selected item', I don't know what to do to tell it to assign the selected item on a right click (as well as a left click).

How can I do this?

Edit: I am using MVVM so when we have a method like SelectedItemChanged with a parameter which is RoutedPropertyChangedEventArgs e, e.Source refers me back to my view model, not to a TreeViewItem.

答:
You can use a behavior for it:

```<code>using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

public class SelectOnRMBBehavior : Behavior<FrameworkElement>
{
    public static readonly DependencyProperty CurrentItemProperty = DependencyProperty.Register("CurrentItem", typeof(TreeViewItem), typeof(SelectOnRMBBehavior), new PropertyMetadata(null));

    public TreeViewItem CurrentItem
    {
        get
        {
            return (TreeViewItem)GetValue(CurrentItemProperty);
        }
        set
        {
            SetValue(CurrentItemProperty, value);
        }
    }

    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.PreviewMouseRightButtonDown += AssociatedObject_PreviewMouseRightButtonDown;
    }

    private void AssociatedObject_PreviewMouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (CurrentItem!=null)
        {
            CurrentItem.IsSelected = true;
        }
    }

    protected override void OnDetaching()
    {
        AssociatedObject.PreviewMouseRightButtonDown -= AssociatedObject_PreviewMouseRightButtonDown;

        base.OnDetaching();
    }
}
</code>```

and then just put your behavior to the element which will be clicked(I suppose a container in DataTemplate):

```<code><StackPanel>
    <i:Interaction.Behaviors>
        <b:SelectOnRMBBehavior CurrentItem="{Binding RelativeSource={RelativeSource AncestorType=TreeViewItem}}"/>
    </i:Interaction.Behaviors>
</StackPanel>
</code>```

Body:
This problem relates mainly to context menus, but in my specific case it's about a TreeView control.

The TreeView item contains a StackPanel, and on that StackPanel is a ContextMenu property, which I have assigned to a StaticResource (which is a ContextMenu of course). Said ContextMenu leads to an ICommand and, thus, does its thing.

At present (and this is the default behaviour I believe), right clicking on an item in the TreeView does not select that item. This is common in Windows, but doesn't happen here. I would like it to happen (but I don't know how).

A little follow up information: I do have a selected item in the TreeView and this changes with a mouse left click. It's not a left click event, though, rather the event is 'SelectedItemChanged'. This leads to a method whereby I set the 'SelectedItem' in my data context (view model) to the SelectedItem. It has to be done this way because a TreeView's selected item is 'read only'.

That code is here, although I'm not sure how useful it is to the issue at hand:

private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        if (this.ScenesTreeView01 == null)
            return;

        if (this.ScenesTreeView01.DataContext == null)
            return;

        var DataContext = this.ScenesTreeView01.DataContext as ScenesViewModel;

        if (e.NewValue is SceneViewModel)
        {
            DataContext.SelectedScene = (SceneViewModel)e.NewValue;
        }

        if (e.NewValue is CharacterViewModel)
        {

            DataContext.SelectedCharacter = (CharacterViewModel)e.NewValue;
        }
    }

Since there doesn't seem to be a place where it says 'okay you left clicked and so here is the selected item', I don't know what to do to tell it to assign the selected item on a right click (as well as a left click).

How can I do this?

Edit: I am using MVVM so when we have a method like SelectedItemChanged with a parameter which is RoutedPropertyChangedEventArgs e, e.Source refers me back to my view model, not to a TreeViewItem.

Body:
You can use a behavior for it:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

public class SelectOnRMBBehavior : Behavior<FrameworkElement>
{
    public static readonly DependencyProperty CurrentItemProperty = DependencyProperty.Register("CurrentItem", typeof(TreeViewItem), typeof(SelectOnRMBBehavior), new PropertyMetadata(null));

    public TreeViewItem CurrentItem
    {
        get
        {
            return (TreeViewItem)GetValue(CurrentItemProperty);
        }
        set
        {
            SetValue(CurrentItemProperty, value);
        }
    }

    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.PreviewMouseRightButtonDown += AssociatedObject_PreviewMouseRightButtonDown;
    }

    private void AssociatedObject_PreviewMouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (CurrentItem!=null)
        {
            CurrentItem.IsSelected = true;
        }
    }

    protected override void OnDetaching()
    {
        AssociatedObject.PreviewMouseRightButtonDown -= AssociatedObject_PreviewMouseRightButtonDown;

        base.OnDetaching();
    }
}

and then just put your behavior to the element which will be clicked(I suppose a container in DataTemplate):

<StackPanel>
    <i:Interaction.Behaviors>
        <b:SelectOnRMBBehavior CurrentItem="{Binding RelativeSource={RelativeSource AncestorType=TreeViewItem}}"/>
    </i:Interaction.Behaviors>
</StackPanel>


问:
GCM cannot receive message
My app use GCM that send notification message, my question is :

My app can receive notification message when app is foreground, but when app is background or killed my app can't receive notification message .

i want to custom a notification view, i do't want that gcm send notification.

答:
Use Service to handle your code in background even with closed app.

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

 static Activity activity;

public void SendNotification(String message) {

   Intent  resultIntent = new Intent(this, YourActivity.class); //Display activity when user click notification
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), resultIntent, 0);

    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_lancher)
            .setContentTitle("title")
            .setContentText(message)
            .setSound(alarmSound)
            .setContentIntent(pIntent);

    NotificationManager mNotificationManager =
            (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
}

@Override
public void onCreate() {
    super.onCreate();

    // Start GCM code here
    // or
    SendNotification("hi!);
 }
}
</code>```

in AndroidManifest.xml

```<code> <service
        android:name=".MyService"
        android:exported="false" />
</code>```

to start Service

```<code>Intent serviceIntent = new Intent(YourActivity.this, MyService.class);
startService(serviceIntent);
</code>```

Title: GCM cannot receive message

Body:
Use Service to handle your code in background even with closed app.

public class MyService extends Service {

 static Activity activity;

public void SendNotification(String message) {

   Intent  resultIntent = new Intent(this, YourActivity.class); //Display activity when user click notification
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), resultIntent, 0);

    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_lancher)
            .setContentTitle("title")
            .setContentText(message)
            .setSound(alarmSound)
            .setContentIntent(pIntent);

    NotificationManager mNotificationManager =
            (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
}

@Override
public void onCreate() {
    super.onCreate();

    // Start GCM code here
    // or
    SendNotification("hi!);
 }
}

in AndroidManifest.xml

 <service
        android:name=".MyService"
        android:exported="false" />

to start Service

Intent serviceIntent = new Intent(YourActivity.this, MyService.class);
startService(serviceIntent);


问:
How to write update query for updating multiple rows into single sql query in ios
I want to write update query for updating multiple rows into single SQL query in Objective-C.

Does anyone knows how i can achieve that ? Please help.

Here is my update query:-

```<code>UPDATE chatDetailTable SET threadId = '584140258203930624', createdByFirstName = 'Poonam', createdByLastName = 'Deshpande', createdById = '201', createdByImgUrl = '', createdByRole = 'teacher', msgType = 'text/plain', msgText = '1111', canEdit = '1', deliverOn = '2017-03-30T12:23:20.73Z', thumbUrl = '', isOwned = '1', replies = '0', mediaPath = '', isFailed = '', read = '1', isSeen = '0', key = '', gmid = '', contact_id = '2', recipientFirstName = 'Indrajit', recipientLastName = 'Joshi', recipientId = '2', recipientImgUrl = '', recipientRole = 'user', isGroup = '0', threadStatus = 'open', mediaUrl = '(null)', status = 'pendingApproval', reviewedById = '0', broadcastId = '584140258136821760' WHERE msgId = '584140258203930625';UPDATE chatDetailTable SET threadId = '584140258266845184', createdByFirstName = 'Poonam', createdByLastName = 'Deshpande', createdById = '201', createdByImgUrl = '', createdByRole = 'teacher', msgType = 'text/plain', msgText = '1111', canEdit = '1', deliverOn = '2017-03-30T12:23:20.73Z', thumbUrl = '', isOwned = '1', replies = '0', mediaPath = '', isFailed = '', read = '1', isSeen = '0', key = '', gmid = '', contact_id = '4', recipientFirstName = 'Hrusikesh', recipientLastName = 'Desai', recipientId = '4', recipientImgUrl = '', recipientRole = 'user', isGroup = '0', threadStatus = 'open', mediaUrl = '(null)', status = 'pendingApproval', reviewedById = '0', broadcastId = '584140258136821760' WHERE msgId = '584140258266845185';UPDATE chatDetailTable SET threadId = '584140258266845186', createdByFirstName = 'Poonam', createdByLastName = 'Deshpande', createdById = '201', createdByImgUrl = '', createdByRole = 'teacher', msgType = 'text/plain', msgText = '1111', canEdit = '1', deliverOn = '2017-03-30T12:23:20.73Z', thumbUrl = '', isOwned = '1', replies = '0', mediaPath = '', isFailed = '', read = '1', isSeen = '0', key = '', gmid = '', contact_id = '1002', recipientFirstName = 'Pramod', recipientLastName = 'Agarwal', recipientId = '1002', recipientImgUrl = '', recipientRole = 'branchAdmin', isGroup = '0', threadStatus = 'open', mediaUrl = '(null)', status = 'pendingApproval', reviewedById = '0', broadcastId = '584140258136821760' WHERE msgId = '584140258333954048';
</code>```

答:
Based on your query you have to set all values with column name and update without any WHERE condition so it will update all row available in your table with provided new value.

```<code>UPDATE chatDetailTable SET threadId = '584140258203930624', createdByFirstName = 'Poonam',
</code>```

Not include column which you don't want to update.

If you want different different value on every row so based on your API response you need to loop your data and update it by primary_key condition.

```<code>NSMutableArray *serverResponse;

for (NSDictionary *dictObject in serverResponse) {

    NSString *strUpdateQry = [NSString stringWithFormat:@"UPDATE chatDetailTable SET threadId = %@, createdByFirstName = %@ Where id = %@",dictObject[@"threadId"],dictObject[@"FirstName"],<PRIMARY_KEY>];
    //Execute Update qry with database classes.
}
</code>```

In above code you need to pass your data dynamically and generate UPDATE query with some primary key and execute it with your DB classes.

Syntax : The basic syntax of UPDATE query with WHERE clause is as follows: UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition]; You can combine N number of conditions using AND or OR operators.

Hope this will helps to update your table.

Body:
I want to write update query for updating multiple rows into single SQL query in Objective-C.

Does anyone knows how i can achieve that ? Please help.

Here is my update query:-

UPDATE chatDetailTable SET threadId = '584140258203930624', createdByFirstName = 'Poonam', createdByLastName = 'Deshpande', createdById = '201', createdByImgUrl = '', createdByRole = 'teacher', msgType = 'text/plain', msgText = '1111', canEdit = '1', deliverOn = '2017-03-30T12:23:20.73Z', thumbUrl = '', isOwned = '1', replies = '0', mediaPath = '', isFailed = '', read = '1', isSeen = '0', key = '', gmid = '', contact_id = '2', recipientFirstName = 'Indrajit', recipientLastName = 'Joshi', recipientId = '2', recipientImgUrl = '', recipientRole = 'user', isGroup = '0', threadStatus = 'open', mediaUrl = '(null)', status = 'pendingApproval', reviewedById = '0', broadcastId = '584140258136821760' WHERE msgId = '584140258203930625';UPDATE chatDetailTable SET threadId = '584140258266845184', createdByFirstName = 'Poonam', createdByLastName = 'Deshpande', createdById = '201', createdByImgUrl = '', createdByRole = 'teacher', msgType = 'text/plain', msgText = '1111', canEdit = '1', deliverOn = '2017-03-30T12:23:20.73Z', thumbUrl = '', isOwned = '1', replies = '0', mediaPath = '', isFailed = '', read = '1', isSeen = '0', key = '', gmid = '', contact_id = '4', recipientFirstName = 'Hrusikesh', recipientLastName = 'Desai', recipientId = '4', recipientImgUrl = '', recipientRole = 'user', isGroup = '0', threadStatus = 'open', mediaUrl = '(null)', status = 'pendingApproval', reviewedById = '0', broadcastId = '584140258136821760' WHERE msgId = '584140258266845185';UPDATE chatDetailTable SET threadId = '584140258266845186', createdByFirstName = 'Poonam', createdByLastName = 'Deshpande', createdById = '201', createdByImgUrl = '', createdByRole = 'teacher', msgType = 'text/plain', msgText = '1111', canEdit = '1', deliverOn = '2017-03-30T12:23:20.73Z', thumbUrl = '', isOwned = '1', replies = '0', mediaPath = '', isFailed = '', read = '1', isSeen = '0', key = '', gmid = '', contact_id = '1002', recipientFirstName = 'Pramod', recipientLastName = 'Agarwal', recipientId = '1002', recipientImgUrl = '', recipientRole = 'branchAdmin', isGroup = '0', threadStatus = 'open', mediaUrl = '(null)', status = 'pendingApproval', reviewedById = '0', broadcastId = '584140258136821760' WHERE msgId = '584140258333954048';

Body:
Based on your query you have to set all values with column name and update without any WHERE condition so it will update all row available in your table with provided new value.

UPDATE chatDetailTable SET threadId = '584140258203930624', createdByFirstName = 'Poonam',

Not include column which you don't want to update.

If you want different different value on every row so based on your API response you need to loop your data and update it by primary_key condition.

NSMutableArray *serverResponse;

for (NSDictionary *dictObject in serverResponse) {

    NSString *strUpdateQry = [NSString stringWithFormat:@"UPDATE chatDetailTable SET threadId = %@, createdByFirstName = %@ Where id = %@",dictObject[@"threadId"],dictObject[@"FirstName"],<PRIMARY_KEY>];
    //Execute Update qry with database classes.
}

In above code you need to pass your data dynamically and generate UPDATE query with some primary key and execute it with your DB classes.

Syntax : The basic syntax of UPDATE query with WHERE clause is as follows: UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition]; You can combine N number of conditions using AND or OR operators.

Hope this will helps to update your table.


问:
Using jQuery "click" function on an element echoed by php
I'm making a forum and I want the user panel to change whenever a user is logged in. So by default it says "Sign in or register." But when a user is logged in it says their name and an option to log out.

The idea is that when they click sign out jQuery will ask for a confirm and if its true they will be redirected to ?logout=true where php handles the rest.

The problem is that jQuery just won't work on the element echoed by php.

Here is the PHP:

```<code><div id="userbar">
    <span id="userPanel">User Panel</span>
    <?php
        if (isset($_SESSION['signedIn'])) {
            echo '
                <a href="#" class="logout">Sign Out</a>
                <span id="welcome">
                    Hello, <b><a href="#" class="sessName">' . $_SESSION["username"] . '
                </b></a></span>
            ';
        } else {
            echo '
                <a href="signin.php" class="signIn">Sign In</a>
                <a href="signup.php" class="register">Register</a>
            ';
        }
    ?>
</div>
</code>```

And here is the jQuery:

```<code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

<script type="text/javascript">

    $(".logout").click(function(){
        var exit = confirm("Are you sure you would like to sing out?");

        if (exit == true) {
            window.location("header.php?logout=true");
        }

        return false;
    });

</script>
</code>```

答:
As the element is not already created in the DOM, you need to use a delegated event for it to work.

See Understanding delegated events

So you would do like that, but you can attach to another container if you wish :

```<code>$(document).on('click', '.logout',

function() {
// Do your things
})
</code>```

EDIT : I misleaded, everything is already in the DOM with PHP echo

Body:
I'm making a forum and I want the user panel to change whenever a user is logged in. So by default it says "Sign in or register." But when a user is logged in it says their name and an option to log out.

The idea is that when they click sign out jQuery will ask for a confirm and if its true they will be redirected to ?logout=true where php handles the rest.

The problem is that jQuery just won't work on the element echoed by php.

Here is the PHP:

    User Panel
    <?php
        if (isset($_SESSION['signedIn'])) {
            echo '
                Sign Out

                    Hello, ' . $_SESSION["username"] . '

            ';
        } else {
            echo '
                Sign In
                Register
            ';
        }
    ?>

And here is the jQuery:

Body:
As the element is not already created in the DOM, you need to use a delegated event for it to work.

See Understanding delegated events

So you would do like that, but you can attach to another container if you wish :

$(document).on('click', '.logout',

function() {
// Do your things
})

EDIT : I misleaded, everything is already in the DOM with PHP echo


问:
Use One HTML Slider to Move Handle on Another Slider Without Using JQuery UI
Very simply I'm trying to make multiple HTML 5 sliders that change their values based on the position of other sliders. A simple but illustrative example is when I have two range inputs that should always equal a total value. One starts at value 1 and the other starts at value 10.

```<code><input id='slider1' type='range' min='1' max='10' value='1'/>
<input id='slider2' type='range' min='1' max='10' value='10'/>
</code>```

Making the total 11. So, for example, if I move slider1 to 2, then slider2 should move down to 9 in order to maintain a total value of 11.

I am able to use an event listener to change the displayed value on the range input using the .prop() function:

```<code>$(document).ready(function() {
    var max_total = 11;
    $("#slider1").on("change", function(){
        var slider1 = this.value;
        $("#slider2").prop("value", max_total - slider1);
    });
});
</code>```

However, this doesn't update the position of the handle on the range input. From the research I've done here it seems that everyone says this solution should work, but I'm not sure why it won't work for me. I'm trying to accomplish this without using JQueryUI, by the way.

Here's a JSFiddle of the code I'm using: https://jsfiddle.net/zkdwr784/

答:
Calling change on slider 2 seems to work -</p>

```<code>$(document).ready(function() {
    var max_total = 11;
    $("#slider1").on("change", function(){
        var slider1 = this.value;
        $("#slider2").prop("value", max_total - slider1);
        $("#slider2").change();
    });
});
</code>```

Body:
Very simply I'm trying to make multiple HTML 5 sliders that change their values based on the position of other sliders. A simple but illustrative example is when I have two range inputs that should always equal a total value. One starts at value 1 and the other starts at value 10.

<input id='slider1' type='range' min='1' max='10' value='1'/>
<input id='slider2' type='range' min='1' max='10' value='10'/>

Making the total 11. So, for example, if I move slider1 to 2, then slider2 should move down to 9 in order to maintain a total value of 11.

I am able to use an event listener to change the displayed value on the range input using the .prop() function:

$(document).ready(function() {
    var max_total = 11;
    $("#slider1").on("change", function(){
        var slider1 = this.value;
        $("#slider2").prop("value", max_total - slider1);
    });
});

However, this doesn't update the position of the handle on the range input. From the research I've done here it seems that everyone says this solution should work, but I'm not sure why it won't work for me. I'm trying to accomplish this without using JQueryUI, by the way.

Here's a JSFiddle of the code I'm using: https://jsfiddle.net/zkdwr784/

Body:
Calling change on slider 2 seems to work -

$(document).ready(function() {
    var max_total = 11;
    $("#slider1").on("change", function(){
        var slider1 = this.value;
        $("#slider2").prop("value", max_total - slider1);
        $("#slider2").change();
    });
});


问:
Project Euler with C++ - compiler won't process after 100 x 101
I've started working with C++ and was fiddling around with some problems on projecteuler.net.

I'm on question #4 and here's my code:

algorithm to check whether the number is a palindrome:

```<code>bool forwardCheck(long posPal){
long n = posPal;
long rev = 0;
long dig;

    while (posPal > 0){
        dig = posPal % 10;
        rev = rev * 10 + dig;
        posPal = posPal % 10;
    }

    return n == rev;
}
</code>```

main program:

```<code>int main(){
long palindrome;

cout << "We are finding the largest palindrome made from two 3-digit numbers.\n"
     << "Calculating...\nCalculating...\nDone!\n";

for (long i = 100; i < 1000; i++){
    for (long j = 100; j < 1000; j++){
        long mult = i * j;
            if (forwardCheck(mult)){
                palindrome = mult;
                //testing function above
                cout << mult << " is a palindrome!\n";
            } else
                //testing function above
                cout << mult << " is not a palindrome...\n";
    }
}

cout << "The largest palindrome composed of two 3 digit numbers is: " << palindrome
     << endl;

return 0;
}
</code>```

I'm using X11 on OS X as my compiler with g++ and my problem is that, using the code above, the numbers get to 101,000 as the multiple and then stops and stalls after that.  My question is:

Why is it doing this?  Am I approaching this inefficiently?

I realize that an alternative is to start from long = 999 and iterate downwards but I've coded but it gets stuck after the "Done!" statement (yes, I know it's a bit ambitious to program that in before the algorithm has run but I like to be optimistic. :)

By stuck and stalls, I mean that the CPU usage spikes but nothing is written to the console.

As a general side note:

Is there a way I can debug through the console, i.e. have it tell me what it's doing similar to echo in windows command prompt?  I'm new to OS X too...

答:
Have a look at this code:

```<code>  while (posPal > 0){
    dig = posPal % 10;
    rev = rev * 10 + dig;
    posPal = posPal % 10;
  }
</code>```

I think you are miscalculating posPal at the bottom of the loop.

Try replacing with posPal = posPal / 10.

Body:
I've started working with C++ and was fiddling around with some problems on projecteuler.net.

I'm on question #4 and here's my code:

algorithm to check whether the number is a palindrome:

bool forwardCheck(long posPal){
long n = posPal;
long rev = 0;
long dig;

    while (posPal > 0){
        dig = posPal % 10;
        rev = rev * 10 + dig;
        posPal = posPal % 10;
    }

    return n == rev;
}

main program:

int main(){
long palindrome;

cout << "We are finding the largest palindrome made from two 3-digit numbers.\n"
     << "Calculating...\nCalculating...\nDone!\n";

for (long i = 100; i < 1000; i++){
    for (long j = 100; j < 1000; j++){
        long mult = i * j;
            if (forwardCheck(mult)){
                palindrome = mult;
                //testing function above
                cout << mult << " is a palindrome!\n";
            } else
                //testing function above
                cout << mult << " is not a palindrome...\n";
    }
}

cout << "The largest palindrome composed of two 3 digit numbers is: " << palindrome
     << endl;

return 0;
}

I'm using X11 on OS X as my compiler with g++ and my problem is that, using the code above, the numbers get to 101,000 as the multiple and then stops and stalls after that.  My question is:

Why is it doing this?  Am I approaching this inefficiently?

I realize that an alternative is to start from long = 999 and iterate downwards but I've coded but it gets stuck after the "Done!" statement (yes, I know it's a bit ambitious to program that in before the algorithm has run but I like to be optimistic. :)

By stuck and stalls, I mean that the CPU usage spikes but nothing is written to the console.

As a general side note:

Is there a way I can debug through the console, i.e. have it tell me what it's doing similar to echo in windows command prompt?  I'm new to OS X too...

Body:
Have a look at this code:

  while (posPal > 0){
    dig = posPal % 10;
    rev = rev * 10 + dig;
    posPal = posPal % 10;
  }

I think you are miscalculating posPal at the bottom of the loop.

Try replacing with posPal = posPal / 10.


问:
Angular 2 date format string
I have an c# API that need to accept DateTime variable from several angular 2 apps. Problem is, every app sends parameter in different format.

How can i get current format string for DateTime variable in Angular 2, so i could pass that to my API and unify it on server?

答: You could treat date passed to your API as string at first and work from there (try parsing with different formats, e.g. using custom model binder). But the whole process should obvoiusly work the other way around - API should enforce certain date format on Angular apps.</p>

Title: Angular 2 date format string


问:
Element positioned higher because of flexbox
I have two identical divs and one of them is nested inside an extra
. In display, both of the squares sit besides to their peer paragraph, but the first square is higher compared to the second one to their respective paragraph. What effect of flexbox creates the difference?

p {
  margin-top: 1rem;
  line-height: 1.85rem;
}

.flexbox {
  display: flex;
}

.square {
  float: left;
  margin-top: 1rem;
  background-color: #cfc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexbox">
  <div>
    <div id="first" class="square">A square</div>
    <p>A paragraph sits aside to the square.</p>
  </div>
</div>

<div>
  <div id="second" class="square">A square</div>
  <p>A paragraph sits aside to the square.</p>
</div></code>```

Without the line-height and margin-top, the square inside the flexbox is still higher, and I'd like to demolish that side-effect of flexbox.

答:
Because your div#first.square doesn't have the same line-height as
 sitting right next to it.

p {
  margin-top: 1rem;
  line-height: 1.85rem;
}

.flexbox {
  display: flex;
}

.square {
  float: left;
  margin-top: 1rem;
  line-height: 1.85rem;
  background-color: #cfc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexbox">
  <div>
    <div id="first" class="square">A square</div>
    <p>A paragraph sits aside to the square.</p>
  </div>
</div>

<div>
  <div id="second" class="square">A square</div>
  <p>A paragraph sits aside to the square.</p>
</div></code>```

BTW you should use dev tools. It makes debug a lot of other things much easier.

Body:
I have two identical divs and one of them is nested inside an extra
. In display, both of the squares sit besides to their peer paragraph, but the first square is higher compared to the second one to their respective paragraph. What effect of flexbox creates the difference?

p {
  margin-top: 1rem;
  line-height: 1.85rem;
}

.flexbox {
  display: flex;
}

.square {
  float: left;
  margin-top: 1rem;
  background-color: #cfc;
}

A square

A paragraph sits aside to the square.

A square

A paragraph sits aside to the square.

Without the line-height and margin-top, the square inside the flexbox is still higher, and I'd like to demolish that side-effect of flexbox.

Body:
Because your div#first.square doesn't have the same line-height as <p> sitting right next to it.

p {
  margin-top: 1rem;
  line-height: 1.85rem;
}

.flexbox {
  display: flex;
}

.square {
  float: left;
  margin-top: 1rem;
  line-height: 1.85rem;
  background-color: #cfc;
}

<div class="flexbox">
  <div>
    <div id="first" class="square">A square</div>
    <p>A paragraph sits aside to the square.</p>
  </div>
</div>

<div>
  <div id="second" class="square">A square</div>
  <p>A paragraph sits aside to the square.</p>
</div>

BTW you should use dev tools. It makes debug a lot of other things much easier.


问:
Java 1.8 is compatible for BO4.0 SP9?
Is Java 1.8 is compatible with BO4.0 SP9? When I am trying to open the BI launchpad - "Cannot launch Java report panel, please make sure you have installed Java Virtual Machine" error is displaying,
In BO server jre1.8_111 and JDK 1.8_111 are installed

Please advice

答:
According to the PAM, BI4.0 is supported with JRE 6-8.

Few things to note:

The version of the JRE/JDK on the server is irrelevant.  A JRE must be installed on the client in order to use the WebI Java panel.

The bitness of the JRE must match the browser.  If you are using 64-bit IE, then you will need a 64-bit JRE.

Newer versions of Chrome and (I believe) Firefox do not support Java at all.

Title: Java 1.8 is compatible for BO4.0 SP9?


问:
How to include multiple file extensions with 'glob.sync' in NodeJS?
Can anyone please suggest how to add multiple file extensions with the glob.sync method.

Something like:

```<code>const glob = require('glob');
let files = glob.sync(path + '**/*.(html|xhtml)');
</code>```

Thank you :)

答:
You can use this (which most shells support as well):

```<code>glob.sync(path + '**/*.{html,xhtml}')
</code>```

Or this one:

```<code>glob.sync(path + '**/*.@(html|xhtml)')
</code>```

EDIT: I initially also suggested this pattern:

```<code>glob.sync(path + '**/*.+(html|xhtml)')
</code>```

However, this will also match files that have .htmlhtml as extension (plus any other combination of html and xhtml, in single or multiple occurrences), which is incorrect.

Body:
Can anyone please suggest how to add multiple file extensions with the glob.sync method.

Something like:

const glob = require('glob');
let files = glob.sync(path + '**/*.(html|xhtml)');

Thank you :)

Body:
You can use this (which most shells support as well):

glob.sync(path + '**/*.{html,xhtml}')

Or this one:

glob.sync(path + '**/*.@(html|xhtml)')

EDIT: I initially also suggested this pattern:

glob.sync(path + '**/*.+(html|xhtml)')

However, this will also match files that have .htmlhtml as extension (plus any other combination of html and xhtml, in single or multiple occurrences), which is incorrect.

ContentLicense: CC BY-SA 4.0


问:
Angular 2 - Bindings cannot contain assignments
I need to give a class to a
 if a property of item has the same value as a property from an object in an array.

Here's the code I currently have:

```<code><tr *ngFor="let item of closingDayGroupsList" [class.inactive]="definitionDetails.Groups.filter(i => i.AbsenceReservationGroupID === item.ID).length > 0">
</code>```

however now I receive the error:

```<code>Bindings cannot contain assignments
</code>```

I'm not sure if what I'm doing is bad practice, or if I'm just making syntax errors.

This is the only way I know to achieve what I want, but it's not working

答:
Its a bad practice to use expressions in angular bindings

Move the class expression into controller.

```<code>export class AppComponent {
    title = 'Groups';

    getClass(item): void {

      // add filter logic here
      return this.definitionDetails.Groups.filter(i => i.AbsenceReservationGroupID === item.ID).length > 0

    }
}
</code>```

The tr will be something like,

```<code><tr *ngFor="let item of closingDayGroupsList" [class.inactive]="getClass(item)">
</code>```

Body:
I need to give a class to a
 if a property of item has the same value as a property from an object in an array.

Here's the code I currently have:

 i.AbsenceReservationGroupID === item.ID).length > 0">

however now I receive the error:

Bindings cannot contain assignments

I'm not sure if what I'm doing is bad practice, or if I'm just making syntax errors.

This is the only way I know to achieve what I want, but it's not working

Body:
Its a bad practice to use expressions in angular bindings

Move the class expression into controller.

export class AppComponent {
    title = 'Groups';

    getClass(item): void {

      // add filter logic here
      return this.definitionDetails.Groups.filter(i => i.AbsenceReservationGroupID === item.ID).length > 0

    }
}

The tr will be something like,

<tr *ngFor="let item of closingDayGroupsList" [class.inactive]="getClass(item)">


问:
Handled exception in Controller can not call error function in ajax
If I handle A exception In Controller how ajax will Know that Exception Is Occured So That I Can Call Error Function in Ajax To Solve My Problem.</p>

答:
You will need to return an error status code.

You could allow the framework to do it for you by simply rethrowing the exception:

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

Another option is for your response to include an error status code.

That will trigger the error function in your ajax call.

Body:
You will need to return an error status code.

You could allow the framework to do it for you by simply rethrowing the exception:

try
{
 //
}
catch (Exception e)
{
   throw;
}

Another option is for your response to include an error status code.

That will trigger the error function in your ajax call.


问:
How to get the screen & height width using c?
Just learned that there is no pre-defined graphics library for C. I want to get the resolution of the current monitor screen.</p>

答:
That is simply not possible to answer as a "pure C" question; there is no "screen" in C, i.e. the language and its standard library never assumes that there is any kind of screen-like output device available.

You need to settle for a suitable library for a portable solution, or figure out how to talk directly to your target environment.


问:
A question about delegates
I am trying to read some code that I did not write. In the main body of the class, there is the following 2 lines.

```<code>// RenderingService callbacks
protected RenderingServiceResponsesDelegate renderingServiceResponsesDelegate;
public delegate void RenderingServiceResponsesDelegate(Collection<RenderingServiceResponse> responses);
</code>```

Now, I have never used delegates before in C#, but read that there is three steps (declaration, instantiation and invocation). The 2nd lines looks like the declaration and the 1st line looks like the first step in instantiation. Inside the constructor of the class, there is the following line:

```<code>//Inside the constructor
this.renderingServiceResponsesDelegate = renderingServiceResponsesDelegate;
</code>```

where renderingServiceResponsesDelegate is the parameter passed by the constructor. So that would be the second part of the instantiation. Is this correctly understood? I was confused by the order of things. Is is possible to instantiate it like that in c# before it has been declared?

答:
The second line is the declaration of the type RenderingServiceResponsesDelegate.

The first line is the declaration of a variable with that type. It is not the instantiation.

The line inside the constructor assigns a value to the variable - but in your example this value is received from elsewhere. Instantiation means creating an instance, which is often done with the new keyword. In your example you haven't provided the code where the instantiation is performed.

Title: A question about delegates

Body:
I am trying to read some code that I did not write. In the main body of the class, there is the following 2 lines.

// RenderingService callbacks
protected RenderingServiceResponsesDelegate renderingServiceResponsesDelegate;
public delegate void RenderingServiceResponsesDelegate(Collection<RenderingServiceResponse> responses);

Now, I have never used delegates before in C#, but read that there is three steps (declaration, instantiation and invocation). The 2nd lines looks like the declaration and the 1st line looks like the first step in instantiation. Inside the constructor of the class, there is the following line:

//Inside the constructor
this.renderingServiceResponsesDelegate = renderingServiceResponsesDelegate;

where renderingServiceResponsesDelegate is the parameter passed by the constructor. So that would be the second part of the instantiation. Is this correctly understood? I was confused by the order of things. Is is possible to instantiate it like that in c# before it has been declared?


问:
Want to get content of a span on amazon.de
I will get a the text of a span on https://www.amazon.de/

I tried like that

```<code>$('.a-spacing-top-extra-large:first').text();
</code>```

and much other things, but every time i get this error.

```<code>VM186:211 Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '.a-spacing-top-extra-large:first' is not a valid selector.(…)
</code>```

I tried much things, with jquery or javascript but all the time same error.
On other sites this code works

I know that there are other guys who have a worked code but i dont find a way...

I want to get it with jquery or javascript

答:
If you use this,

```<code>$('.a-spacing-top-extra-large:first-child').text();
</code>```

you should get the value you want.

You are nearly there with your selector, but it should be :first-child

Body:
I will get a the text of a span on https://www.amazon.de/

I tried like that

$('.a-spacing-top-extra-large:first').text();

and much other things, but every time i get this error.

VM186:211 Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '.a-spacing-top-extra-large:first' is not a valid selector.(…)

I tried much things, with jquery or javascript but all the time same error.
On other sites this code works

I know that there are other guys who have a worked code but i dont find a way...

I want to get it with jquery or javascript

Body:
If you use this,

$('.a-spacing-top-extra-large:first-child').text();

you should get the value you want.

You are nearly there with your selector, but it should be :first-child


问:
android.hardware.Camera fails to open every second time

Problem background

I am developing a VR Project on Unreal Engine 4, and the project requires the usage of Android's native camera. Since there are no built-in functions in UE4 to iteract with Android's native methods, I customized this plugin under my need.

The original plugin uses the JNI interface to iteract with C++ code. It calls camera.open() and camera.startPreview() on UE4's EventBeginPlay, and calls camera.stopPreview() and camera.Release() on UE4's EventEndPlay. Since it is a known issue that EventEndPlay never fires up on Android platform, I decided to manipulate the camera in onResume() and onPause() methods. Here is the code:

```<code><gameActivityClassAdditions>
<insert>
  /* Unrelevant code goes here */
    ...
    ...
  /* End of unrelevant code */

  public void AndroidThunkJava_startCamera()
  {
    surfaceTexture = new SurfaceTexture(10);
    surfaceTexture.setDefaultBufferSize(preferredWidth, preferredHeight);

    if (camera == null){
      try {
        camera = Camera.open();
      } catch (RuntimeException exc) {
        return;
      }
    }

    try {
      camera.setPreviewTexture(surfaceTexture);
    } catch (IOException t) {
      return;
    }

    Parameters cameraParam = camera.getParameters();

    cameraParam.setPreviewFormat(ImageFormat.NV21);
    cameraParam.setPreviewSize(preferredWidth, preferredHeight);
    cameraParam.setPreviewFpsRange(preferredFPS, preferredFPS);
    cameraParam.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);
    if (cameraParam.isVideoStabilizationSupported()) {
      cameraParam.setVideoStabilization(false);
    }
    if (cameraParam.isAutoWhiteBalanceLockSupported()) {
      cameraParam.setAutoWhiteBalanceLock(false);
    }

    camera.setParameters(cameraParam);

    camera.setPreviewCallback(new PreviewCallback() {
      @Override
      public void onPreviewFrame(byte[] data, Camera camera) {
        int Height = camera.getParameters().getPreviewSize().height;
        int Width = camera.getParameters().getPreviewSize().width;

        // calling C++ function via JNI interface
        processFrameData(Width, Height, data);
      }
    });

    camera.startPreview();
  }

  public void AndroidThunkJava_stopCamera()
  {
    if (camera != null)
    {
      camera.stopPreview();
      camera.release();
      camera = null;
    }
  }
</insert>
</gameActivityClassAdditions>

<gameActivityOnPauseAdditions>
<insert>
  AndroidThunkJava_stopCamera();
</insert>
</gameActivityOnPauseAdditions>

<gameActivityOnResumeAdditions>
<insert>
  AndroidThunkJava_startCamera();
</insert>
</gameActivityOnResumeAdditions>
</code>```

The problem

The camera works fine every second time. That means:

I open the app, camera is working. I pushed the home button (which triggers onPause() method), then switch back to the app (triggers onResume() method). Pushed the home button again, and then switched back - camera works.  And so on, the camera works every second time.

Anybody have any idea about this issue? Is that connected to the fact that android.hardware.Camera is deprecated? I'm using API version 19, so it is not possible to use newer android.hardware.camera2.

答:
Here is my onStop and onResume methods. I'm not using onPause. And it works perfectly:

```<code>  @Override
    protected void onResume() {
        super.onResume();
        if (mCamera == null) {
            restartPreview();
        }
    }
    @Override
    public void onStop() {

        // stop the preview
        if (mCamera != null) {
            stopCameraPreview();
            mCamera.release();
            mCamera = null;
        }

        super.onStop();
    }

 private void restartPreview() {
        if (mCamera != null) {
            stopCameraPreview();
            mCamera.release();
            mCamera = null;
        }

            getCamera(mCameraID);
            startCameraPreview();
        }

private void startCameraPreview() {

        try {
            mCamera.setPreviewDisplay(mSurfaceHolder);
            mCamera.startPreview();

            setSafeToTakePhoto(true);
            setCameraFocusReady(true);
        } catch (IOException e) {
            Log.d("st", "Can't start camera preview due to IOException " + e);
            e.printStackTrace();
        }
    }

 private void stopCameraPreview() {
        setSafeToTakePhoto(false);
        setCameraFocusReady(false);

        // Nulls out callbacks, stops face detection
        mCamera.stopPreview();
        mPreviewView.setCamera(null);
    }
</code>```

maybe some implementations not equals yours but i think it is help you.

Body:
Problem background

I am developing a VR Project on Unreal Engine 4, and the project requires the usage of Android's native camera. Since there are no built-in functions in UE4 to iteract with Android's native methods, I customized this plugin under my need.

The original plugin uses the JNI interface to iteract with C++ code. It calls camera.open() and camera.startPreview() on UE4's EventBeginPlay, and calls camera.stopPreview() and camera.Release() on UE4's EventEndPlay. Since it is a known issue that EventEndPlay never fires up on Android platform, I decided to manipulate the camera in onResume() and onPause() methods. Here is the code:

<gameActivityClassAdditions>
<insert>
  /* Unrelevant code goes here */
    ...
    ...
  /* End of unrelevant code */

  public void AndroidThunkJava_startCamera()
  {
    surfaceTexture = new SurfaceTexture(10);
    surfaceTexture.setDefaultBufferSize(preferredWidth, preferredHeight);

    if (camera == null){
      try {
        camera = Camera.open();
      } catch (RuntimeException exc) {
        return;
      }
    }

    try {
      camera.setPreviewTexture(surfaceTexture);
    } catch (IOException t) {
      return;
    }

    Parameters cameraParam = camera.getParameters();

    cameraParam.setPreviewFormat(ImageFormat.NV21);
    cameraParam.setPreviewSize(preferredWidth, preferredHeight);
    cameraParam.setPreviewFpsRange(preferredFPS, preferredFPS);
    cameraParam.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);
    if (cameraParam.isVideoStabilizationSupported()) {
      cameraParam.setVideoStabilization(false);
    }
    if (cameraParam.isAutoWhiteBalanceLockSupported()) {
      cameraParam.setAutoWhiteBalanceLock(false);
    }

    camera.setParameters(cameraParam);

    camera.setPreviewCallback(new PreviewCallback() {
      @Override
      public void onPreviewFrame(byte[] data, Camera camera) {
        int Height = camera.getParameters().getPreviewSize().height;
        int Width = camera.getParameters().getPreviewSize().width;

        // calling C++ function via JNI interface
        processFrameData(Width, Height, data);
      }
    });

    camera.startPreview();
  }

  public void AndroidThunkJava_stopCamera()
  {
    if (camera != null)
    {
      camera.stopPreview();
      camera.release();
      camera = null;
    }
  }
</insert>
</gameActivityClassAdditions>

<gameActivityOnPauseAdditions>
<insert>
  AndroidThunkJava_stopCamera();
</insert>
</gameActivityOnPauseAdditions>

<gameActivityOnResumeAdditions>
<insert>
  AndroidThunkJava_startCamera();
</insert>
</gameActivityOnResumeAdditions>

The problem

The camera works fine every second time. That means:

I open the app, camera is working. I pushed the home button (which triggers onPause() method), then switch back to the app (triggers onResume() method). Pushed the home button again, and then switched back - camera works.  And so on, the camera works every second time.

Anybody have any idea about this issue? Is that connected to the fact that android.hardware.Camera is deprecated? I'm using API version 19, so it is not possible to use newer android.hardware.camera2.

Body:
Here is my onStop and onResume methods. I'm not using onPause. And it works perfectly:

  @Override
    protected void onResume() {
        super.onResume();
        if (mCamera == null) {
            restartPreview();
        }
    }
    @Override
    public void onStop() {

        // stop the preview
        if (mCamera != null) {
            stopCameraPreview();
            mCamera.release();
            mCamera = null;
        }

        super.onStop();
    }

 private void restartPreview() {
        if (mCamera != null) {
            stopCameraPreview();
            mCamera.release();
            mCamera = null;
        }

            getCamera(mCameraID);
            startCameraPreview();
        }

private void startCameraPreview() {

        try {
            mCamera.setPreviewDisplay(mSurfaceHolder);
            mCamera.startPreview();

            setSafeToTakePhoto(true);
            setCameraFocusReady(true);
        } catch (IOException e) {
            Log.d("st", "Can't start camera preview due to IOException " + e);
            e.printStackTrace();
        }
    }

 private void stopCameraPreview() {
        setSafeToTakePhoto(false);
        setCameraFocusReady(false);

        // Nulls out callbacks, stops face detection
        mCamera.stopPreview();
        mPreviewView.setCamera(null);
    }

maybe some implementations not equals yours but i think it is help you.


问:
Thread Safety in Concurrent Queue C#
I have a MessagesManager thread to which different threads may send messages and then this  MessagesManager thread is responsible to publish these messages inside SendMessageToTcpIP() (start point of MessagesManager thread ).

```<code>class MessagesManager : IMessageNotifier
{
    //private
    private readonly AutoResetEvent _waitTillMessageQueueEmptyARE = new AutoResetEvent(false);
    private ConcurrentQueue<string> MessagesQueue = new ConcurrentQueue<string>();

    public void PublishMessage(string Message)
    {
        MessagesQueue.Enqueue(Message);
        _waitTillMessageQueueEmptyARE.Set();
    }

    public void SendMessageToTcpIP()
    {
        //keep waiting till a new message comes
        while (MessagesQueue.Count() == 0)
        {
            _waitTillMessageQueueEmptyARE.WaitOne();
        }

        //Copy the Concurrent Queue into a local queue - keep dequeuing the item once it is inserts into the local Queue
        Queue<string> localMessagesQueue = new Queue<string>();

        while (!MessagesQueue.IsEmpty)
        {
            string message;
            bool isRemoved = MessagesQueue.TryDequeue(out message);
            if (isRemoved)
                localMessagesQueue.Enqueue(message);
        }

        //Use the Local Queue for further processing
        while (localMessagesQueue.Count() != 0)
        {
            TcpIpMessageSenderClient.ConnectAndSendMessage(localMessagesQueue.Dequeue().PadRight(80, ' '));
            Thread.Sleep(2000);
        }
    }
}
</code>```

The different threads (3-4) send their message by calling the PublishMessage(string Message) (using same object to MessageManager). Once the message comes, I push that message into a concurrent queue and notifies the  SendMessageToTcpIP() by setting _waitTillMessageQueueEmptyARE.Set();. Inside SendMessageToTcpIP(), I am copying the message from the concurrent queue inside a local queue and then publish one by one.

QUESTIONS: Is it thread safe to do enqueuing and dequeuing in this way? Could there be some strange effects due to it?

答:
The code is thread safe since both ConcurrentQueue and AutoResetEvent are thread safe. your strings are anyway being read and never being written to, so this code is thread safe.

However, You have to make sure you call SendMessageToTcpIP in some sort of a loop.

otherwise , you have a dangerous race condition - some messages may get lost:

```<code>while (!MessagesQueue.IsEmpty)
        {
            string message;
            bool isRemoved = MessagesQueue.TryDequeue(out message);
            if (isRemoved)
                localMessagesQueue.Enqueue(message);
        }

        //<<--- what happens if another thread enqueues a message here?

        while (localMessagesQueue.Count() != 0)
        {
            TcpIpMessageSenderClient.ConnectAndSendMessage(localMessagesQueue.Dequeue().PadRight(80, ' '));
            Thread.Sleep(2000);
        }
</code>```

Other than that, AutoResetEvent is extremely heavy object. it uses a kernel object to synchronize threads. every call is a system call which may be costly. consider using user mode synchronization object (doesn't .net provides some sort of condition variable?)

Title: Thread Safety in Concurrent Queue C#

Body:
I have a MessagesManager thread to which different threads may send messages and then this  MessagesManager thread is responsible to publish these messages inside SendMessageToTcpIP() (start point of MessagesManager thread ).

class MessagesManager : IMessageNotifier
{
    //private
    private readonly AutoResetEvent _waitTillMessageQueueEmptyARE = new AutoResetEvent(false);
    private ConcurrentQueue<string> MessagesQueue = new ConcurrentQueue<string>();

    public void PublishMessage(string Message)
    {
        MessagesQueue.Enqueue(Message);
        _waitTillMessageQueueEmptyARE.Set();
    }

    public void SendMessageToTcpIP()
    {
        //keep waiting till a new message comes
        while (MessagesQueue.Count() == 0)
        {
            _waitTillMessageQueueEmptyARE.WaitOne();
        }

        //Copy the Concurrent Queue into a local queue - keep dequeuing the item once it is inserts into the local Queue
        Queue<string> localMessagesQueue = new Queue<string>();

        while (!MessagesQueue.IsEmpty)
        {
            string message;
            bool isRemoved = MessagesQueue.TryDequeue(out message);
            if (isRemoved)
                localMessagesQueue.Enqueue(message);
        }

        //Use the Local Queue for further processing
        while (localMessagesQueue.Count() != 0)
        {
            TcpIpMessageSenderClient.ConnectAndSendMessage(localMessagesQueue.Dequeue().PadRight(80, ' '));
            Thread.Sleep(2000);
        }
    }
}

The different threads (3-4) send their message by calling the PublishMessage(string Message) (using same object to MessageManager). Once the message comes, I push that message into a concurrent queue and notifies the  SendMessageToTcpIP() by setting _waitTillMessageQueueEmptyARE.Set();. Inside SendMessageToTcpIP(), I am copying the message from the concurrent queue inside a local queue and then publish one by one.

QUESTIONS: Is it thread safe to do enqueuing and dequeuing in this way? Could there be some strange effects due to it?

Body:
The code is thread safe since both ConcurrentQueue and AutoResetEvent are thread safe. your strings are anyway being read and never being written to, so this code is thread safe.

However, You have to make sure you call SendMessageToTcpIP in some sort of a loop.

otherwise , you have a dangerous race condition - some messages may get lost:

while (!MessagesQueue.IsEmpty)
        {
            string message;
            bool isRemoved = MessagesQueue.TryDequeue(out message);
            if (isRemoved)
                localMessagesQueue.Enqueue(message);
        }

        //<<--- what happens if another thread enqueues a message here?

        while (localMessagesQueue.Count() != 0)
        {
            TcpIpMessageSenderClient.ConnectAndSendMessage(localMessagesQueue.Dequeue().PadRight(80, ' '));
            Thread.Sleep(2000);
        }

Other than that, AutoResetEvent is extremely heavy object. it uses a kernel object to synchronize threads. every call is a system call which may be costly. consider using user mode synchronization object (doesn't .net provides some sort of condition variable?)


问:
js find Elements with same innerHTML
I have a button that has some text and I get that text by innerHTML

```<code>var helpName = helpButton.parentElement.querySelector('span').innerHTML;
</code>```

Then I have a few other buttons that trigger accordion boxes

```<code>var helpAccordions = modal.getElementsByClassName('accordion');
</code>```

I would like to select one element from helpAccordions that matches helpName and set it as a var.

```<code>    <div class="modal-content">
        <span class="close">×</span>
        <h3 class="modal-title">Help</h3>

        <button class="accordion">Key Partners</button>
    </div>

    <div class="section-header">
        <span>Key Partners</span>
        <div class="help-icon"></div>
    </div>
</code>```

答:
Simply use with jquery contains()

$(document).ready(function (){
$('button').click(function(){
var a = $('span:Contains('+$(this).text()+')').parent();
//result varible is a
console.log(a.attr('class'))
})

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="modal-content">
        <span class="close">×</span>
        <h3 class="modal-title">Help</h3>

        <button class="accordion">Key Partners</button>
    </div>

    <div class="section-header">
        <span>Key Partners</span>
        <div class="help-icon"></div>
    </div></code>```

Title: js find Elements with same innerHTML

Body:
I have a button that has some text and I get that text by innerHTML

var helpName = helpButton.parentElement.querySelector('span').innerHTML;

Then I have a few other buttons that trigger accordion boxes

var helpAccordions = modal.getElementsByClassName('accordion');

I would like to select one element from helpAccordions that matches helpName and set it as a var.

        ×

Help

        <button class="accordion">Key Partners</button>

        Key Partners

Body:
Simply use with jquery contains()

$(document).ready(function (){
$('button').click(function(){
var a = $('span:Contains('+$(this).text()+')').parent();
//result varible is a
console.log(a.attr('class'))
})

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="modal-content">
        <span class="close">&times;</span>
        <h3 class="modal-title">Help</h3>

        <button class="accordion">Key Partners</button>
    </div>

    <div class="section-header">
        <span>Key Partners</span>
        <div class="help-icon"></div>
    </div>


问:
How to set ProgressBar at the center screen in frame layout?
I am using following code, but my progress bar is not displaying in the center of frame layout. I want to avoid padding to my progressbar.Can any one please explain? It is perfectly working if i am using "Linear Layout"</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|center_horizontal">

    <ProgressBar android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView android:id="@+id/gallery_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

 </FrameLayout>
</code>```

答:
In the layout xml for your progressBar set the android:layout_gravity (instead of android:gravity) to "center"

```<code>android:layout_gravity = "center"
</code>```

Body:
I am using following code, but my progress bar is not displaying in the center of frame layout. I want to avoid padding to my progressbar.Can any one please explain? It is perfectly working if i am using "Linear Layout"

<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|center_horizontal">

    <ProgressBar android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView android:id="@+id/gallery_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

 </FrameLayout>

Body:
In the layout xml for your progressBar set the android:layout_gravity (instead of android:gravity) to "center"

android:layout_gravity = "center"


问:
Django Regular expression many slugs
I have the regular expression in my url that accepts pass one slug to my view, exemple:

127.0.0.1/cart/product_slug1

But I need a regex that accept pass one or more slugs, example:

127.0.0.1/cart/product_slug1/product_slug2/product_slug3/.../product_slugN

urls.py

```<code>from django.conf.urls import url

from . import views

urlpatterns = [
url(
    r'^cart/add/(?P<slug>[\w_-]+)/$', views.create_cartitem,
    name='create_cartitem'
),
</code>```

It's possible send many slugs?

答:
[UPDATE]: It seems that you cannot do that. Instead, you can place a catch all pattern and capture the whole url. Then inside your views you can split it by / and get the parameters you want. Something like this:

```<code> urlpatterns = [
    url(
        r'^cart/add/(?P<slugs>[\w_/-]+)/$', views.create_cartitem, name='create_cartitem'
    ),
</code>```

And then in your views, do this:

```<code>def my_view(request, slugs):
    slugs = slugs.split('/')
    # now slugs is a list of strings
</code>```

Note, however, that this is error prone since both cart/add/h/e/l/l/o and cart/add/hell//o//to/you are valid.

-- OLD ANSWER --

Sure you can, but you cannot use both named captured parameters with unnamed ones.

So, change your urls.py to this:

```<code>urlpatterns = [
    url(
        r'^cart/add/([\w_-]+)/([\w_-]+/)*$', views.create_cartitem, name='create_cartitem'
    ),
</code>```

And inside your views.py, instead of kwargs (like slug you already have) you must use args (positional arguments, now you're gonna have a list of slugs). Like this:

```<code>def my_view(request, *args):
    for arg in args:
        print(arg)
</code>```

Now if you type 127.0.0.1:8000/cart/add/argv/argvv/argvvv/, inside your views you get them as a list ['argv', 'argvv', 'argvvv'].

Title: Django Regular expression many slugs

Body:
I have the regular expression in my url that accepts pass one slug to my view, exemple:

127.0.0.1/cart/product_slug1

But I need a regex that accept pass one or more slugs, example:

127.0.0.1/cart/product_slug1/product_slug2/product_slug3/.../product_slugN

urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
url(
    r'^cart/add/(?P<slug>[\w_-]+)/$', views.create_cartitem,
    name='create_cartitem'
),

It's possible send many slugs?

Body:
[UPDATE]: It seems that you cannot do that. Instead, you can place a catch all pattern and capture the whole url. Then inside your views you can split it by / and get the parameters you want. Something like this:

 urlpatterns = [
    url(
        r'^cart/add/(?P<slugs>[\w_/-]+)/$', views.create_cartitem, name='create_cartitem'
    ),

And then in your views, do this:

def my_view(request, slugs):
    slugs = slugs.split('/')
    # now slugs is a list of strings

Note, however, that this is error prone since both cart/add/h/e/l/l/o and cart/add/hell//o//to/you are valid.

-- OLD ANSWER --

Sure you can, but you cannot use both named captured parameters with unnamed ones.

So, change your urls.py to this:

urlpatterns = [
    url(
        r'^cart/add/([\w_-]+)/([\w_-]+/)*$', views.create_cartitem, name='create_cartitem'
    ),

And inside your views.py, instead of kwargs (like slug you already have) you must use args (positional arguments, now you're gonna have a list of slugs). Like this:

def my_view(request, *args):
    for arg in args:
        print(arg)

Now if you type 127.0.0.1:8000/cart/add/argv/argvv/argvvv/, inside your views you get them as a list ['argv', 'argvv', 'argvvv'].


问:
Stata doesn't save output file
I'm having difficulties to save the output of my regression. Stata is supposed to save the file as "output.dta" in the defined directory, however the file is not saved in this folder (and also nowhere else on my PC). Here is the final piece of code, where I want it to be saved:

```<code>if (`counter'==1) {
  save "C:\Users\Milla\Code\output", replace
  local counter = `counter' + 1
}
if (`counter'!=1) {
cap append using "C:\Users\Milla\Code\output"
duplicates drop *, force
cap save "C:\Users\Milla\Code\output", replace
}
</code>```

Does anyone have an idea why could this happen? The code runs well and throws no errors or warnings. But it also doesn't say "output.dta is saved" as it normally does, when one saves anything in Stata.

Thanks ahead and best regards,
Milla

答:
try</p>

```<code> save "C:\Users\Milla\Code\output.dta", r
</code>```

Title: Stata doesn't save output file

Body:
I'm having difficulties to save the output of my regression. Stata is supposed to save the file as "output.dta" in the defined directory, however the file is not saved in this folder (and also nowhere else on my PC). Here is the final piece of code, where I want it to be saved:

if (`counter'==1) {
  save "C:\Users\Milla\Code\output", replace
  local counter = `counter' + 1
}
if (`counter'!=1) {
cap append using "C:\Users\Milla\Code\output"
duplicates drop *, force
cap save "C:\Users\Milla\Code\output", replace
}

Does anyone have an idea why could this happen? The code runs well and throws no errors or warnings. But it also doesn't say "output.dta is saved" as it normally does, when one saves anything in Stata.

Thanks ahead and best regards,
Milla

Body:
try

 save "C:\Users\Milla\Code\output.dta", r


问:
React native get API endpoint always 400 without body
I have a CURL request which is working properly:

```<code>curl -v -X POST https://auth.domain.com/v1/oauth/tokens -u test:test -d "grant_type=authorization_code" -d "code=d9a473a4-e417-4dd7-9151-83e9c1cb9ca6" -d "redirect_uri=app://authorize"
</code>```

I tryed to implement it in my React Native app but I always get 400 error. Firstly I used axios:

```<code>var url = `https://auth.domain.com/v1/oauth/tokens`
axios.post(url, {
  "grant_type": 'authorization_code',
  "code": code,
  "redirect_uri": 'app://authorize',
},{
  auth: {
    username: 'test',
    password: 'test'
  }
}).then(response => {
  console.log(response);
}).catch(function(error) {
  console.log('There has been a problem with your fetch operation: ' + error.message);
  throw error
});
</code>```

But I got 400 error:

```<code>Possible Unhandled Promise Rejection (id: 0):
Request failed with status code 400
Error: Request failed with status code 400
</code>```

I tryed it with fetch either:

```<code>fetch(url, {
  method: 'post',
  headers: {
    'Authorization': 'Basic '+btoa('test:test'),
  },
    body: JSON.stringify({
      "grant_type": 'authorization_code',
      "code": code,
      "redirect_uri": 'app://authorize',
    })
  }).then(response => {
    console.log('Request core...');
    console.log(response);
  })
</code>```

I got 400 error with the same empty body. For the CURL request I got 200 OK and the response from the server. What am I doing wrong in the JS side?

答:
As Yury Tarabanko mentoined the problem was "You are sending urlencoded data using curl. Other examples send json. "

Solution:

```<code>var url = `https://auth.domain.com/v1/oauth/tokens`
axios.post(url,
  querystring.stringify({
    "grant_type": 'authorization_code',
    "code": code,
    "redirect_uri": 'app://authorize',
  }),{
    auth: {
      username: 'test',
      password: 'test'
    },
    headers: {
      'Content-type': 'application/x-www-form-urlencoded'
    }
  }).then(response => {
    console.log('Request core...');
    console.log(response);
  }).catch(function(error) {
    console.log('There has been a problem with your fetch operation: ' + error.message);
    console.log(error);
    throw error;
});
</code>```

Body:
I have a CURL request which is working properly:

curl -v -X POST https://auth.domain.com/v1/oauth/tokens -u test:test -d "grant_type=authorization_code" -d "code=d9a473a4-e417-4dd7-9151-83e9c1cb9ca6" -d "redirect_uri=app://authorize"

I tryed to implement it in my React Native app but I always get 400 error. Firstly I used axios:

var url = `https://auth.domain.com/v1/oauth/tokens`
axios.post(url, {
  "grant_type": 'authorization_code',
  "code": code,
  "redirect_uri": 'app://authorize',
},{
  auth: {
    username: 'test',
    password: 'test'
  }
}).then(response => {
  console.log(response);
}).catch(function(error) {
  console.log('There has been a problem with your fetch operation: ' + error.message);
  throw error
});

But I got 400 error:

Possible Unhandled Promise Rejection (id: 0):
Request failed with status code 400
Error: Request failed with status code 400

I tryed it with fetch either:

fetch(url, {
  method: 'post',
  headers: {
    'Authorization': 'Basic '+btoa('test:test'),
  },
    body: JSON.stringify({
      "grant_type": 'authorization_code',
      "code": code,
      "redirect_uri": 'app://authorize',
    })
  }).then(response => {
    console.log('Request core...');
    console.log(response);
  })

I got 400 error with the same empty body. For the CURL request I got 200 OK and the response from the server. What am I doing wrong in the JS side?

Body:
As Yury Tarabanko mentoined the problem was "You are sending urlencoded data using curl. Other examples send json. "

Solution:

var url = `https://auth.domain.com/v1/oauth/tokens`
axios.post(url,
  querystring.stringify({
    "grant_type": 'authorization_code',
    "code": code,
    "redirect_uri": 'app://authorize',
  }),{
    auth: {
      username: 'test',
      password: 'test'
    },
    headers: {
      'Content-type': 'application/x-www-form-urlencoded'
    }
  }).then(response => {
    console.log('Request core...');
    console.log(response);
  }).catch(function(error) {
    console.log('There has been a problem with your fetch operation: ' + error.message);
    console.log(error);
    throw error;
});