问:
Xamarin: Visual State Manager and custom properties
I am trying to set a custom property on a custom control using the Visual State Manager but I'm not having any luck so far. My custom control is just a label with an additional bindable property on it.

```<code>public class SelectableLabel : Label
{
    public static readonly BindableProperty IsSelectedProperty = BindableProperty.Create("IsSelected", typeof(bool), typeof(SelectableLabel), false);

    public bool IsSelected
    {
        get { return (bool)GetValue(IsSelectedProperty); }
        set
        {
            Console.WriteLine($"MDO: {Text}.IsSelected_set={value}");
            SetValue(IsSelectedProperty, value);
        }
    }
</code>```

I use this control inside a CollectionView to toggle the IsSelected property when the control enters the Selected visual state.

```<code>    <CollectionView
        x:Name="cv"
        ItemsSource="{Binding Names}"
        SelectionMode="Multiple"
        SelectedItems="{Binding SelectedNames, Mode=TwoWay}"
        VerticalOptions="Fill">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <local:SelectableLabel
                    x:Name="lblName"
                    Text="{Binding First}">
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup
                            x:Name="CommonStates">
                            <VisualState
                                x:Name="Normal">
                                <VisualState.Setters>
                                    <Setter
                                        Property="IsSelected"
                                        Value="False" />
                                </VisualState.Setters>
                            </VisualState>
                            <VisualState
                                x:Name="Selected">
                                <VisualState.Setters>
                                    <Setter
                                        Property="IsSelected"
                                        Value="True" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                </local:SelectableLabel>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</code>```

When I run this on an iOS simulator, I'm not seeing the setter being fired when the visual state changes to Selected. If I change the property in the setter to BackgroundColor or Text, I'm seeing the expected behavior. The problem seems specific to the custom property. I looked at the documentation for the Setter.Property and it states that the Setter can be applied to a BindableProperty which IsSelected is. Am I doing something wrong or does the VSM not support this functionality?

Edit: The CollectionView part of this example is irrelevant. The same issue happens with this code.

```<code>    public class SelectableEntry : Entry
    {
        public static readonly BindableProperty IsSelectedProperty = BindableProperty.Create("IsSelected", typeof(bool), typeof(SelectableEntry), false);

        public bool IsSelected
        {
            get { return (bool)GetValue(IsSelectedProperty); }
            set
            {
                Console.WriteLine($"MDO: {Text}.IsSelected_set={value}");
                var color = value ? Color.LightBlue : Color.LightPink;
                SetValue(IsSelectedProperty, value);
                SetValue(BackgroundColorProperty, color);
            }
        }
    }
</code>```

Here is the corresponding XAML. The background color changes when the first custom Entry control receives focus while the second does not. I also don't see my WriteLine statement in the console.

```<code>        <local:SelectableEntry Text="First">
            <VisualStateManager.VisualStateGroups>
                <VisualStateGroup
                    x:Name="CommonStates">
                    <VisualState
                        x:Name="Normal">
                        <VisualState.Setters>
                            <Setter
                                Property="BackgroundColor"
                                Value="LightBlue" />
                        </VisualState.Setters>
                    </VisualState>

                    <VisualState
                        x:Name="Focused">
                        <VisualState.Setters>
                            <Setter
                                Property="BackgroundColor"
                                Value="LightPink" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateManager.VisualStateGroups>
        </local:SelectableEntry>
        <local:SelectableEntry Text="Second">
            <VisualStateManager.VisualStateGroups>
                <VisualStateGroup
                    x:Name="CommonStates">

                    <VisualState
                        x:Name="Normal">
                        <VisualState.Setters>
                            <Setter
                                Property="IsSelected"
                                Value="False" />
                        </VisualState.Setters>
                    </VisualState>

                    <VisualState
                        x:Name="Focused">
                        <VisualState.Setters>
                            <Setter
                                Property="IsSelected"
                                Value="True" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateManager.VisualStateGroups>
        </local:SelectableEntry>
</code>```

答:
I have tried with Bindable Property to check whether property be invoked in VisualStateManager . That's regrettable, it can not be invoked even in propertyChanged method . I think maybe bindable property can not work in VisualStateManager.

Custom Entry Code as follow :

```<code>public class SelectableEntry : Entry
{
    public static readonly BindableProperty IsSelectedProperty = BindableProperty.Create("IsSelected", typeof(bool), typeof(SelectableEntry), false ,propertyChanged:changedMethod);

    private static void changedMethod(BindableObject bindable, object oldValue, object newValue)
    {
        Console.WriteLine($"MDO: {oldValue}.IsSelected_set={newValue}");
    }

    public bool IsSelected
    {
        get { return (bool)GetValue(IsSelectedProperty); }
        set
        {
            Console.WriteLine($"MDO: {Text}.IsSelected_set={value}");
            var color = value ? Color.LightBlue : Color.LightPink;
            SetValue(IsSelectedProperty, value);
            SetValue(BackgroundColorProperty, color);
        }
    }
}
</code>```

Solution:

However , there is a Attached Properties that can be used in Style.Setters. Then you can also have a try with it in VisualState.Setters .It also will work .

Attached property class Code as follow :

```<code>public class SelectableEntryStyle
{
    public static readonly BindableProperty IsSelectedProperty =  BindableProperty.CreateAttached("IsSelected", typeof(bool), typeof(SelectableEntryStyle), false,propertyChanged:onChangedMethod);

    private static void onChangedMethod(BindableObject bindable, object oldValue, object newValue)
    {
        Console.WriteLine($"MDO:IsSelected_set={newValue}");
        var color = (bool)newValue ? Color.LightBlue : Color.LightPink;
        var entry = bindable as Entry;
        entry.SetValue(Entry.BackgroundColorProperty, color);
    }

    public static bool GetIsSelected(BindableObject view)
    {
        return (bool)view.GetValue(IsSelectedProperty);
    }

    public static void SetIsSelected(BindableObject view, bool value)
    {
        view.SetValue(IsSelectedProperty, value);
    }

}
</code>```

The code of Xaml as follow :

```<code><local:SelectableEntry FontSize="18" Placeholder="Bindable Property">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="CommonStates">
            <VisualState x:Name="Normal">
                <VisualState.Setters>
                    <Setter Property="IsSelected"
                            Value="False" />
                </VisualState.Setters>
            </VisualState>

            <VisualState x:Name="Disabled">
                <VisualState.Setters>
                    <Setter Property="IsSelected"
                            Value="True" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</local:SelectableEntry>
<Entry Placeholder="Attached Property">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="CommonStates">

            <VisualState x:Name="Normal">
                <VisualState.Setters>
                    <Setter Property="local:SelectableEntryStyle.IsSelected"
                            Value="False" />
                </VisualState.Setters>
            </VisualState>

            <VisualState x:Name="Focused">
                <VisualState.Setters>
                    <Setter Property="local:SelectableEntryStyle.IsSelected"
                            Value="True" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</Entry>
</code>```

Then console can print log when Entry is Normal or Focused .

02-18 14:26:27.360 I/mono-stdout(26014): MDO:IsSelected_set=True

02-18 14:26:28.675 I/mono-stdout(26014): MDO:IsSelected_set=False

The effects :

Body:
I am trying to set a custom property on a custom control using the Visual State Manager but I'm not having any luck so far. My custom control is just a label with an additional bindable property on it.

public class SelectableLabel : Label
{
    public static readonly BindableProperty IsSelectedProperty = BindableProperty.Create("IsSelected", typeof(bool), typeof(SelectableLabel), false);

    public bool IsSelected
    {
        get { return (bool)GetValue(IsSelectedProperty); }
        set
        {
            Console.WriteLine($"MDO: {Text}.IsSelected_set={value}");
            SetValue(IsSelectedProperty, value);
        }
    }

I use this control inside a CollectionView to toggle the IsSelected property when the control enters the Selected visual state.

    <CollectionView
        x:Name="cv"
        ItemsSource="{Binding Names}"
        SelectionMode="Multiple"
        SelectedItems="{Binding SelectedNames, Mode=TwoWay}"
        VerticalOptions="Fill">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <local:SelectableLabel
                    x:Name="lblName"
                    Text="{Binding First}">
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup
                            x:Name="CommonStates">
                            <VisualState
                                x:Name="Normal">
                                <VisualState.Setters>
                                    <Setter
                                        Property="IsSelected"
                                        Value="False" />
                                </VisualState.Setters>
                            </VisualState>
                            <VisualState
                                x:Name="Selected">
                                <VisualState.Setters>
                                    <Setter
                                        Property="IsSelected"
                                        Value="True" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                </local:SelectableLabel>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>

When I run this on an iOS simulator, I'm not seeing the setter being fired when the visual state changes to Selected. If I change the property in the setter to BackgroundColor or Text, I'm seeing the expected behavior. The problem seems specific to the custom property. I looked at the documentation for the Setter.Property and it states that the Setter can be applied to a BindableProperty which IsSelected is. Am I doing something wrong or does the VSM not support this functionality?

Edit: The CollectionView part of this example is irrelevant. The same issue happens with this code.

    public class SelectableEntry : Entry
    {
        public static readonly BindableProperty IsSelectedProperty = BindableProperty.Create("IsSelected", typeof(bool), typeof(SelectableEntry), false);

        public bool IsSelected
        {
            get { return (bool)GetValue(IsSelectedProperty); }
            set
            {
                Console.WriteLine($"MDO: {Text}.IsSelected_set={value}");
                var color = value ? Color.LightBlue : Color.LightPink;
                SetValue(IsSelectedProperty, value);
                SetValue(BackgroundColorProperty, color);
            }
        }
    }

Here is the corresponding XAML. The background color changes when the first custom Entry control receives focus while the second does not. I also don't see my WriteLine statement in the console.

        <local:SelectableEntry Text="First">
            <VisualStateManager.VisualStateGroups>
                <VisualStateGroup
                    x:Name="CommonStates">
                    <VisualState
                        x:Name="Normal">
                        <VisualState.Setters>
                            <Setter
                                Property="BackgroundColor"
                                Value="LightBlue" />
                        </VisualState.Setters>
                    </VisualState>

                    <VisualState
                        x:Name="Focused">
                        <VisualState.Setters>
                            <Setter
                                Property="BackgroundColor"
                                Value="LightPink" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateManager.VisualStateGroups>
        </local:SelectableEntry>
        <local:SelectableEntry Text="Second">
            <VisualStateManager.VisualStateGroups>
                <VisualStateGroup
                    x:Name="CommonStates">

                    <VisualState
                        x:Name="Normal">
                        <VisualState.Setters>
                            <Setter
                                Property="IsSelected"
                                Value="False" />
                        </VisualState.Setters>
                    </VisualState>

                    <VisualState
                        x:Name="Focused">
                        <VisualState.Setters>
                            <Setter
                                Property="IsSelected"
                                Value="True" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateManager.VisualStateGroups>
        </local:SelectableEntry>

Body:
I have tried with Bindable Property to check whether property be invoked in VisualStateManager . That's regrettable, it can not be invoked even in propertyChanged method . I think maybe bindable property can not work in VisualStateManager.

Custom Entry Code as follow :

public class SelectableEntry : Entry
{
    public static readonly BindableProperty IsSelectedProperty = BindableProperty.Create("IsSelected", typeof(bool), typeof(SelectableEntry), false ,propertyChanged:changedMethod);

    private static void changedMethod(BindableObject bindable, object oldValue, object newValue)
    {
        Console.WriteLine($"MDO: {oldValue}.IsSelected_set={newValue}");
    }

    public bool IsSelected
    {
        get { return (bool)GetValue(IsSelectedProperty); }
        set
        {
            Console.WriteLine($"MDO: {Text}.IsSelected_set={value}");
            var color = value ? Color.LightBlue : Color.LightPink;
            SetValue(IsSelectedProperty, value);
            SetValue(BackgroundColorProperty, color);
        }
    }
}

Solution:

However , there is a Attached Properties that can be used in Style.Setters. Then you can also have a try with it in VisualState.Setters .It also will work .

Attached property class Code as follow :

public class SelectableEntryStyle
{
    public static readonly BindableProperty IsSelectedProperty =  BindableProperty.CreateAttached("IsSelected", typeof(bool), typeof(SelectableEntryStyle), false,propertyChanged:onChangedMethod);

    private static void onChangedMethod(BindableObject bindable, object oldValue, object newValue)
    {
        Console.WriteLine($"MDO:IsSelected_set={newValue}");
        var color = (bool)newValue ? Color.LightBlue : Color.LightPink;
        var entry = bindable as Entry;
        entry.SetValue(Entry.BackgroundColorProperty, color);
    }

    public static bool GetIsSelected(BindableObject view)
    {
        return (bool)view.GetValue(IsSelectedProperty);
    }

    public static void SetIsSelected(BindableObject view, bool value)
    {
        view.SetValue(IsSelectedProperty, value);
    }

}

The code of Xaml as follow :

<local:SelectableEntry FontSize="18" Placeholder="Bindable Property">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="CommonStates">
            <VisualState x:Name="Normal">
                <VisualState.Setters>
                    <Setter Property="IsSelected"
                            Value="False" />
                </VisualState.Setters>
            </VisualState>

            <VisualState x:Name="Disabled">
                <VisualState.Setters>
                    <Setter Property="IsSelected"
                            Value="True" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</local:SelectableEntry>
<Entry Placeholder="Attached Property">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="CommonStates">

            <VisualState x:Name="Normal">
                <VisualState.Setters>
                    <Setter Property="local:SelectableEntryStyle.IsSelected"
                            Value="False" />
                </VisualState.Setters>
            </VisualState>

            <VisualState x:Name="Focused">
                <VisualState.Setters>
                    <Setter Property="local:SelectableEntryStyle.IsSelected"
                            Value="True" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</Entry>

Then console can print log when Entry is Normal or Focused .

02-18 14:26:27.360 I/mono-stdout(26014): MDO:IsSelected_set=True

02-18 14:26:28.675 I/mono-stdout(26014): MDO:IsSelected_set=False

The effects :


来源: stackexchange

问:
What are some good rigid body dynamics references?
I'm not a math guy in the least but I'm interested in learning about rigid body physics (for the purpose of implementing a basic 3d physics engine).  In school I only took Maths through Algebra II, but I've done 3d dev for years so I have a fairly decent understanding of vectors, quaternions, matrices, etc.  My real problem is reading complex formulas and such, so I'm looking for some decent rigid body dynamics references that will make some sense.

Anyone have any good references?

答:
Physics for Game Programmers I think is better than Physics for Game Developers.

If you want something thick in your bookshelf (like I do), Eberly's 3D Game Engine Design and Erleben's Physics-Based Animation can accompany the above.

OwnerDisplayName: Cody Brocious

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Cody Brocious


问:
How to show the output of 'l' in python pdb after every command entered
I would like to have the output of the python pdb 'l' command printed to the screen after every command I enter in an interactive debugging session.

Is there a way to setup python pdb to do this?

答:
One way to do this is to alias your favourite commands to run the command and then l.

e.g.

```<code>(Pdb) alias s step ;; l
(Pdb) s
> /usr/lib/python2.5/distutils/core.py(14)<module>()
-> from types import *
 9      # This module should be kept compatible with Python 2.1.
10
11      __revision__ = "$Id: core.py 38672 2005-03-20 22:19:47Z fdrake $"
12
13      import sys, os
14  ->  from types import *
15
16      from distutils.debug import DEBUG
17      from distutils.errors import *
18      from distutils.util import grok_environment_error
19
</code>```

In your ~/.pdbrc you can add the aliases so you have them every time:

```<code>alias s step ;; l
</code>```

OwnerDisplayName: Paul D. Eden

Body:
One way to do this is to alias your favourite commands to run the command and then l.

e.g.

(Pdb) alias s step ;; l
(Pdb) s
> /usr/lib/python2.5/distutils/core.py(14)<module>()
-> from types import *
 9      # This module should be kept compatible with Python 2.1.
10
11      __revision__ = "$Id: core.py 38672 2005-03-20 22:19:47Z fdrake $"
12
13      import sys, os
14  ->  from types import *
15
16      from distutils.debug import DEBUG
17      from distutils.errors import *
18      from distutils.util import grok_environment_error
19

In your ~/.pdbrc you can add the aliases so you have them every time:

alias s step ;; l

OwnerDisplayName: Michael Twomey


问:
How to update database record in Laravel
i use this rout ==> Route::put('update/{id}','testcontroller@update');

And i use this function

```<code>public function update(Request $request, $id)
   {

    $input=[
        'name' => $request->name,
        'email' => $request->email,
        'password' => $request->password,
    ];
    $update = DB::table('users')->where('id', $id)->update($input);
    if ($update) {
        dd('updated');
    }
    else{
        dd('error');

   }
}
</code>```

but i see a error.

答:
Your code looks fine.

But I think you are updating the same values. If you try to update with the same values, it will return 0. otherwise 1.

So I suggest you to check if this is the case.

ContentLicense: CC BY-SA 4.0

Body:
i use this rout ==> Route::put('update/{id}','testcontroller@update');

And i use this function

public function update(Request $request, $id)
   {

    $input=[
        'name' => $request->name,
        'email' => $request->email,
        'password' => $request->password,
    ];
    $update = DB::table('users')->where('id', $id)->update($input);
    if ($update) {
        dd('updated');
    }
    else{
        dd('error');

   }
}

but i see a error.


问:
Chopper using MVP Architecture in flutter
Im using Chopper for calling api and i want to get result json,
this is the API i want to call
[https://api.jsonbin.io/b/5e1219328d761771cc8b9394]

I would like to ask how to resolve this kind of problem,

Unhandled Exception: NoSuchMethodError: The method
  'inheritFromWidgetOfExactType' was called on null.

my class is

```<code>part 'APIService.chopper.dart';
@ChopperApi(baseUrl:"/b/")
abstract class ApiService extends ChopperService {

  @Get(path: "5e1219328d761771cc8b9394")
  Future<Response> getPost();

  static ApiService create() {
    final client = ChopperClient(
        baseUrl: "https://api.jsonbin.io/",
        services: [_$ApiService(),],
        converter: JsonConverter());
    return _$ApiService(client);
  }
}
</code>```

and then I'm calling this function to test the Chooper

```<code> void testAPI() async
  {
    final response  = await Provider.of<ApiService>(context).getPost();
    print(response.body);
  }
</code>```

But i having a problem and i cannot call testAPI
can you help me ?

Thank you in advance, sorry for the grammar BTW,

答:
```<code>void testAPI() async
  {
    final response  = await ApiService.create().getPost();
    print(response.body);
  }
</code>```

This is correct answer for my questions

Body:
Im using Chopper for calling api and i want to get result json,
this is the API i want to call
[https://api.jsonbin.io/b/5e1219328d761771cc8b9394]

I would like to ask how to resolve this kind of problem,

Unhandled Exception: NoSuchMethodError: The method
  'inheritFromWidgetOfExactType' was called on null.

my class is

part 'APIService.chopper.dart';
@ChopperApi(baseUrl:"/b/")
abstract class ApiService extends ChopperService {

  @Get(path: "5e1219328d761771cc8b9394")
  Future<Response> getPost();

  static ApiService create() {
    final client = ChopperClient(
        baseUrl: "https://api.jsonbin.io/",
        services: [_$ApiService(),],
        converter: JsonConverter());
    return _$ApiService(client);
  }
}

and then I'm calling this function to test the Chooper

 void testAPI() async
  {
    final response  = await Provider.of<ApiService>(context).getPost();
    print(response.body);
  }

But i having a problem and i cannot call testAPI
can you help me ?

Thank you in advance, sorry for the grammar BTW,

Body:
void testAPI() async
  {
    final response  = await ApiService.create().getPost();
    print(response.body);
  }

This is correct answer for my questions


问:
Laravel: Email not sending
I try to send email to user using templates. So,before the email sent it should check that the user received email on that day or not. It's like One user should received one mail only in a day so i add if statement which is

if (EmailSave::where('user_id',$user_id)->whereDate('created_at', Carbon::today())->exists()) {
```

<p>after i add this line the mail is not sending can anyone help me on this. Im new to laravel. </p>

<pre class="lang-php prettyprint-override"><code>    foreach ($users as $user) {
        foreach($auto_email_templates as $mail) {

                $email_id = $mail->id;
                $user_id = $user->id;

                if( $user->created_at < Carbon::now()->subDays($mail->days)){  //check when the acc create

                    if (EmailSave::where('user_id',$user_id)->whereDate('created_at', Carbon::today())->exists()) {

                        if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->count()< 1){  //sent email one time only

                            if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->whereDate('created_at', '>', Carbon::now()->addDays(30))) { //mail sent again after 30 days

                                $mails = new EmailSave;
                                $mails->user_id = $user->id;
                                $mails->email_id =$mail->id;
                                Mail::to($user->email)->send(new Automail($mail));
                                $mails->save();

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

答:
Wondering if you have already setup your email credential at .env, if not you can try to use mailtrap.io for email sandbox.

Register your mailtrap account at https://mailtrap.io/ , then go to SMTP Setting tab to get your username and password.

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=25
MAIL_USERNAME=ENTER_YOUR_MAILTRAP_USERNAME_AT_SMTP_SETTING_PAGE(should be 14 characters long)
MAIL_PASSWORD=ENTER_YOUR_MAILTRAP_PASSWORD_AT_SMTP_SETTING_PAGE(should be 14 characters long)
</code>```

There is a logic error to correct, try this kind of codes if this meets your requirement.

```<code>foreach ($users as $user) {
            foreach($auto_email_templates as $mail) {

                $email_id = $mail->id;
                $user_id = $user->id;

                if( $user->created_at < Carbon::now()->subDays($mail->days)){  //check when the acc create

                    $ableToSendMail = false;
                    if (!EmailSave::where('user_id',$user_id)->whereDate('created_at', Carbon::today())->exists()) {

                        // looks like this logic need to break down into two separate checking cause the requirement is different
                        // one is email to send one time only when there is everyday checking
                        // another one will breach first checking, which see the created_at date which more than 30 days

//                        if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->count()< 1){  //sent email one time only
//
//                            if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->whereDate('created_at', '>', Carbon::now()->addDays(30))) { //mail sent again after 30 days
//
//                                $mails = new EmailSave;
//                                $mails->user_id = $user->id;
//                                $mails->email_id =$mail->id;
//                                Mail::to($user->email)->send(new Automail($mail));
//                                $mails->save();
//
//                            }
//                        }

                        // Email does not sent before, proceed to email send
                        if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->count()< 1){  //sent email one time only
                            $ableToSendMail = true;
                        }

                        if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->whereDate('created_at', '>', Carbon::now()->addDays(30))) { //mail sent again after 30 days
                            $ableToSendMail = true;
                        }
                    }

                    if ($ableToSendMail) {
                        $mails = new EmailSave;
                        $mails->user_id = $user->id;
                        $mails->email_id =$mail->id;
                        Mail::to($user->email)->send(new Automail($mail));
                        $mails->save();
                    }
                }
            }
        }
</code>```

Title: Laravel: Email not sending

Body:
I try to send email to user using templates. So,before the email sent it should check that the user received email on that day or not. It's like One user should received one mail only in a day so i add if statement which is

if (EmailSave::where('user_id',$user_id)->whereDate('created_at', Carbon::today())->exists()) {

after i add this line the mail is not sending can anyone help me on this. Im new to laravel.

    foreach ($users as $user) {
        foreach($auto_email_templates as $mail) {

                $email_id = $mail->id;
                $user_id = $user->id;

                if( $user->created_at < Carbon::now()->subDays($mail->days)){  //check when the acc create

                    if (EmailSave::where('user_id',$user_id)->whereDate('created_at', Carbon::today())->exists()) {

                        if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->count()< 1){  //sent email one time only

                            if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->whereDate('created_at', '>', Carbon::now()->addDays(30))) { //mail sent again after 30 days

                                $mails = new EmailSave;
                                $mails->user_id = $user->id;
                                $mails->email_id =$mail->id;
                                Mail::to($user->email)->send(new Automail($mail));
                                $mails->save();

                            }
                        }
                    }
                }
            }
          }

Body:
Wondering if you have already setup your email credential at .env, if not you can try to use mailtrap.io for email sandbox.

Register your mailtrap account at https://mailtrap.io/ , then go to SMTP Setting tab to get your username and password.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=25
MAIL_USERNAME=ENTER_YOUR_MAILTRAP_USERNAME_AT_SMTP_SETTING_PAGE(should be 14 characters long)
MAIL_PASSWORD=ENTER_YOUR_MAILTRAP_PASSWORD_AT_SMTP_SETTING_PAGE(should be 14 characters long)

There is a logic error to correct, try this kind of codes if this meets your requirement.

foreach ($users as $user) {
            foreach($auto_email_templates as $mail) {

                $email_id = $mail->id;
                $user_id = $user->id;

                if( $user->created_at < Carbon::now()->subDays($mail->days)){  //check when the acc create

                    $ableToSendMail = false;
                    if (!EmailSave::where('user_id',$user_id)->whereDate('created_at', Carbon::today())->exists()) {

                        // looks like this logic need to break down into two separate checking cause the requirement is different
                        // one is email to send one time only when there is everyday checking
                        // another one will breach first checking, which see the created_at date which more than 30 days

//                        if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->count()< 1){  //sent email one time only
//
//                            if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->whereDate('created_at', '>', Carbon::now()->addDays(30))) { //mail sent again after 30 days
//
//                                $mails = new EmailSave;
//                                $mails->user_id = $user->id;
//                                $mails->email_id =$mail->id;
//                                Mail::to($user->email)->send(new Automail($mail));
//                                $mails->save();
//
//                            }
//                        }

                        // Email does not sent before, proceed to email send
                        if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->count()< 1){  //sent email one time only
                            $ableToSendMail = true;
                        }

                        if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->whereDate('created_at', '>', Carbon::now()->addDays(30))) { //mail sent again after 30 days
                            $ableToSendMail = true;
                        }
                    }

                    if ($ableToSendMail) {
                        $mails = new EmailSave;
                        $mails->user_id = $user->id;
                        $mails->email_id =$mail->id;
                        Mail::to($user->email)->send(new Automail($mail));
                        $mails->save();
                    }
                }
            }
        }


问:
Go to definition and back to reference in Visual Studio Code
I'm currently using VSCode and am trying to use the F12 shortcut which takes me to a definition of an object/function. When I want to go back to the reference, I can't seem to find the right way to do it. With VS community I used Shift + F12.

I've try different combinations, such as Alt + F12 or Shift + F12 but all I get is a peek definition of the element which is not useful at all; it's just a popup showing the same element in the same file I'm at. I've seen answers to this question but pertaining to VS 2010 which are no longer applicable or doesn't work with VSCode.

Question: What is the shortcut to Go Back once you've used F12 to Go to the definition?

答:
ALT + Left Arrow and ALT + Right Arrow worked for me. VS code listed all shortcuts in pdf keyboard-shortcuts-windows.pdf.
To see all keyboard shortcuts go to menu bar Help->Keyboard Shortcuts Reference. It will open pdf that contains all shortcuts.


问:
Extjs 4: Create an iFrame Window
I am in need of creating an iFrame Window in Extjs. Previously in ExtJS 3.x I would do this:

```<code>bodyCfg: {
    tag: 'iframe'
}
</code>```

But the Window Class of ExtJS 4 seems not to have a bodyCfg.

Any ideas on how to make an iFrame ExtJS 4 Window?

答:
I think autoEl is what you are looking for...

Some advice from me, in Ext 4.x don't use autoEl as a window config property, it can make your window malformed.. I suggest you to use autoEl in a component (items of your window)

```<code>new Ext.Window({
    title : "iframe",
    width : 300,
    height: 300,
    layout : 'fit',
    items : [{
        xtype : "component",
        autoEl : {
            tag : "iframe",
            src : "http://www.yahoo.com"
        }
    }]
}).show();
</code>```

The code above is better than

```<code>new Ext.Window({
    title : "iframe",
    width : 300,
    height: 300,
    layout : 'fit',
    autoEl : {
       tag : "iframe",
       src : "http://www.yahoo.com"
    }
}).show();
</code>```

Note: currenty you can't load Google and Facebook inside an iframe

ContentLicense: CC BY-SA 3.0

Title: Extjs 4: Create an iFrame Window

Body:
I am in need of creating an iFrame Window in Extjs. Previously in ExtJS 3.x I would do this:

bodyCfg: {
    tag: 'iframe'
}

But the Window Class of ExtJS 4 seems not to have a bodyCfg.

Any ideas on how to make an iFrame ExtJS 4 Window?

Body:
I think autoEl is what you are looking for...

Some advice from me, in Ext 4.x don't use autoEl as a window config property, it can make your window malformed.. I suggest you to use autoEl in a component (items of your window)

new Ext.Window({
    title : "iframe",
    width : 300,
    height: 300,
    layout : 'fit',
    items : [{
        xtype : "component",
        autoEl : {
            tag : "iframe",
            src : "http://www.yahoo.com"
        }
    }]
}).show();

The code above is better than

new Ext.Window({
    title : "iframe",
    width : 300,
    height: 300,
    layout : 'fit',
    autoEl : {
       tag : "iframe",
       src : "http://www.yahoo.com"
    }
}).show();

Note: currenty you can't load Google and Facebook inside an iframe


问:
Logic App Using Filter Query in Get Entities Action
I am new to logic app and try to build and logic app to check the records in Azure table. The PartitionKey is a string type of DateTime.utcNow().Ticks. I want to write a filter query to filter the records whose PartitionKey is less than or equals to current DateTime. My effort is shown in the screenshot:

It keeps telling me the expression is invalid. Can anyone give me some hints to write the correct query for my purpose? Many thanks. I am not sure why this expression is invalid.

答:
Firstly your filter query expression, the format should be Timestamp le datetime'2019-03-18T06:07Z'.

Second the expression doesn't need the ticks function, if use it the query expression will be like the below pic hows.

So actually the right query expression should be Timestamp le datetime '@{utcNow()}', if you get the warning, go the code view mode change the expression and don't forget the single quote.

And here is my test result, hope this could help you, if you still have other problem please feel free to let me know.


问:
React Native: Unable to center Text in View component
I am unable to center a Text component in a View component in React Native both on android as well as ios.

As you can see the + sign in not centred in the white circle.

This is my component:

```<code>
<TouchableOpacity
    style={styles.blueButton}
>
    <View style={styles.addButton}>
        <Text style={styles.plus}>+</Text>
    </View>
</TouchableOpacity>
</code>```

This is my stylesheet:

```<code>blueButton: {
    height: 40,
    width: 40,
    borderRadius: 3,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#3498DB',
},
addButton: {
    width: 15,
    height: 15,
    borderRadius: 30,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
},
plus: {
    color: '#3498DB',
    fontSize: 20,
},
</code>```

答:
The extra font padding in android might be the culprit here. Try adding includeFontPadding: false to the text style.

more info here - https://facebook.github.io/react-native/docs/text#style

includeFontPadding: bool (Android)

Set to false to remove extra font padding intended to make space for
certain ascenders / descenders. With some fonts, this padding can make
text look slightly misaligned when centered vertically. For best
results also set textAlignVertical to center. Default is true.

Body:
I am unable to center a Text component in a View component in React Native both on android as well as ios.

As you can see the + sign in not centred in the white circle.

This is my component:

<TouchableOpacity
    style={styles.blueButton}
>
    <View style={styles.addButton}>
        <Text style={styles.plus}>+</Text>
    </View>
</TouchableOpacity>

This is my stylesheet:

blueButton: {
    height: 40,
    width: 40,
    borderRadius: 3,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#3498DB',
},
addButton: {
    width: 15,
    height: 15,
    borderRadius: 30,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
},
plus: {
    color: '#3498DB',
    fontSize: 20,
},


问:
MySQL adding longtext column making query extremely slow - any performance tip?
I have this table called stories that currently has 12 million records, on production.

```<code>CREATE TABLE `stories` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `headline` varchar(255) DEFAULT NULL,
  `author_id` int(11) DEFAULT NULL,
  `body` longtext NOT NULL,
  `published_at` datetime DEFAULT NULL,
  `type_id` int(11) NOT NULL DEFAULT '0',
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `aasm_state` varchar(255) NOT NULL,
  `deleted` tinyint(1) DEFAULT '0',
  `word_count` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `index_stories_on_cms_story_id` (`cms_story_id`),
  KEY `typeid` (`type_id`),
  KEY `index_stories_on_published_at` (`published_at`),
  KEY `index_stories_on_updated_at` (`updated_at`),
  KEY `index_stories_on_aasm_state_and_published_at_and_deleted` (`aasm_state`,`published_at`,`deleted`),
  KEY `idx_author_id` (`author_id`)
) ENGINE=InnoDB AUTO_INCREMENT=511625276 DEFAULT CHARSET=utf8;
</code>```

And I am performing the following queries: (just fetching the id runs fine)

```<code>SELECT  `stories`.id
  FROM `stories`
 WHERE `stories`.`aasm_state` = 'scheduled'
   AND `stories`.`deleted` = 0
   AND (`stories`.`published_at` <= '2020-01-14 06:16:04')
   AND (`stories`.`id` > 519492608)
 ORDER
    BY `stories`.`id` ASC
  LIMIT 1000;
...
1000 rows in set (0.59 sec)
</code>```

However, when I add the longtext column to it, I get:

```<code>mysql> SELECT  `stories`.id
, `stories`.body
FROM `stories`
WHERE `stories`.`aasm_state` = 'scheduled'
AND `stories`.`deleted` = 0
AND (`stories`.`published_at` <= '2020-01-14 06:16:04')
AND (`stories`.`id` > 519492608)
ORDER BY `stories`.`id` ASC LIMIT 1000;
...
1000 rows in set (6 min 34.11 sec)
</code>```

Any performance tip on how to deal with this table?

答:
I recommend this order for the index:

```<code>INDEX(`aasm_state`,`deleted`,id)
</code>```

put the = tests first

end with range that matches the ORDER BY; hopefully this will avoid having to gather lots of rows, and sort them before getting to the LIMIT.

This index may help all variants of the query.

Body:
I have this table called stories that currently has 12 million records, on production.

CREATE TABLE `stories` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `headline` varchar(255) DEFAULT NULL,
  `author_id` int(11) DEFAULT NULL,
  `body` longtext NOT NULL,
  `published_at` datetime DEFAULT NULL,
  `type_id` int(11) NOT NULL DEFAULT '0',
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `aasm_state` varchar(255) NOT NULL,
  `deleted` tinyint(1) DEFAULT '0',
  `word_count` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `index_stories_on_cms_story_id` (`cms_story_id`),
  KEY `typeid` (`type_id`),
  KEY `index_stories_on_published_at` (`published_at`),
  KEY `index_stories_on_updated_at` (`updated_at`),
  KEY `index_stories_on_aasm_state_and_published_at_and_deleted` (`aasm_state`,`published_at`,`deleted`),
  KEY `idx_author_id` (`author_id`)
) ENGINE=InnoDB AUTO_INCREMENT=511625276 DEFAULT CHARSET=utf8;

And I am performing the following queries: (just fetching the id runs fine)

SELECT  `stories`.id
  FROM `stories`
 WHERE `stories`.`aasm_state` = 'scheduled'
   AND `stories`.`deleted` = 0
   AND (`stories`.`published_at` <= '2020-01-14 06:16:04')
   AND (`stories`.`id` > 519492608)
 ORDER
    BY `stories`.`id` ASC
  LIMIT 1000;
...
1000 rows in set (0.59 sec)

However, when I add the longtext column to it, I get:

mysql> SELECT  `stories`.id
, `stories`.body
FROM `stories`
WHERE `stories`.`aasm_state` = 'scheduled'
AND `stories`.`deleted` = 0
AND (`stories`.`published_at` <= '2020-01-14 06:16:04')
AND (`stories`.`id` > 519492608)
ORDER BY `stories`.`id` ASC LIMIT 1000;
...
1000 rows in set (6 min 34.11 sec)

Any performance tip on how to deal with this table?

Body:
I recommend this order for the index:

INDEX(`aasm_state`,`deleted`,id)

put the = tests first

end with range that matches the ORDER BY; hopefully this will avoid having to gather lots of rows, and sort them before getting to the LIMIT.

This index may help all variants of the query.


问:
Evaluation order of lambda functions in Racket
Currently working through the Racket Guide at https://docs.racket-lang.org and reading up on lambda functions. The explanation of their usefulness is lucid, but I am not sure I quite grasp the order in which such functions are evaluated. Consider the following example from the Guide:

```<code>(define (twice f v)
  (f (f v)))

(define (make-add-suffix s2)
  (lambda (s) (string-append s s2)))

(twice (make-add-suffix "!") "hello")
</code>```

The function call to twice here is said to evaluate to "hello!!". Here is my guess at what the evaluation process looks like:

```<code>(twice (make-add-suffix "!") "hello")

((make-add-suffix "!") ((make-add-suffix "!") "hello")

((make-add-suffix "!") (string-append "hello" "!"))

(string-append (string-append "hello" "!") "!")

(string-append "hello!" "!")

"hello!!"
</code>```

Is this an accurate assessment, or have I missed something?

答:
Slogan: The outermost and left-most nested expression should be evaluated first.

```<code>(twice (make-add-suffix "!") "hello")

; (define (f x) ...) is short for (define f (lambda (x) ...)) so,
; = { substitute twice with  (lambda (f v) (f (f v)))}

((lambda (f v) (f (f v))) (make-add-suffix "!") "hello")

; = { substition of make-add-suffix with (lambda (s2) (lambda (s) (string-append s s2)))}

((lambda (f v) (f (f v)))
 ((lambda (s2) (lambda (s) (string-append s s2))) "!")
 "hello")
</code>```

Terminology before we move on:

Beta Reduction:
((lambda (x-1 ... x-n) f-body) v-1 ... v-n) == f-body
with all occurrences of x-1 ... x-n
replaced with v-1 ... v-n, respectively.

Call by Value: The arguments of a function call are evaluated before beta reduction.

```<code>; = { beta-reduction of ((lambda (s2) (lambda (s) (string-append s s2))) "!") }

((lambda (f v) (f (f v))) (lambda (s) (string-append s "!")) "hello")

; = { beta-reduction of the whole expression }

((lambda (s) (string-append s "!"))
 ((lambda (s) (string-append s "!")) "hello"))

; = { beta-reduction of the expression in the argument position first }

((lambda (s) (string-append s "!")) (string-append "hello" "!"))

; ... and the rest is easy:
((lambda (s) (string-append s "!")) "hello!")
(string-append "hello!" "!")
"hello!!"
</code>```

Body:
Currently working through the Racket Guide at https://docs.racket-lang.org and reading up on lambda functions. The explanation of their usefulness is lucid, but I am not sure I quite grasp the order in which such functions are evaluated. Consider the following example from the Guide:

(define (twice f v)
  (f (f v)))

(define (make-add-suffix s2)
  (lambda (s) (string-append s s2)))

(twice (make-add-suffix "!") "hello")

The function call to twice here is said to evaluate to "hello!!". Here is my guess at what the evaluation process looks like:

(twice (make-add-suffix "!") "hello")

((make-add-suffix "!") ((make-add-suffix "!") "hello")

((make-add-suffix "!") (string-append "hello" "!"))

(string-append (string-append "hello" "!") "!")

(string-append "hello!" "!")

"hello!!"

Is this an accurate assessment, or have I missed something?

Body:
Slogan: The outermost and left-most nested expression should be evaluated first.

(twice (make-add-suffix "!") "hello")

; (define (f x) ...) is short for (define f (lambda (x) ...)) so,
; = { substitute twice with  (lambda (f v) (f (f v)))}

((lambda (f v) (f (f v))) (make-add-suffix "!") "hello")

; = { substition of make-add-suffix with (lambda (s2) (lambda (s) (string-append s s2)))}

((lambda (f v) (f (f v)))
 ((lambda (s2) (lambda (s) (string-append s s2))) "!")
 "hello")

Terminology before we move on:

Beta Reduction:
((lambda (x-1 ... x-n) f-body) v-1 ... v-n) == f-body
with all occurrences of x-1 ... x-n
replaced with v-1 ... v-n, respectively.

Call by Value: The arguments of a function call are evaluated before beta reduction.

; = { beta-reduction of ((lambda (s2) (lambda (s) (string-append s s2))) "!") }

((lambda (f v) (f (f v))) (lambda (s) (string-append s "!")) "hello")

; = { beta-reduction of the whole expression }

((lambda (s) (string-append s "!"))
 ((lambda (s) (string-append s "!")) "hello"))

; = { beta-reduction of the expression in the argument position first }

((lambda (s) (string-append s "!")) (string-append "hello" "!"))

; ... and the rest is easy:
((lambda (s) (string-append s "!")) "hello!")
(string-append "hello!" "!")
"hello!!"


问:
Help with Undefined index and Undefined variable
Could somebody help me with this problem. I just trasferred my PHP/MYSQL program to another computer (both are running XAMPP and on localhost) and now I got a massive amount of Undefined index and Undefined variable ERRORS. Could somebody explain me why?

All the variables are checked with isset and all the values should be OK, but I can't get anything to work as it is supposed to and then there are the Undefined index and Undefined variable ERRORS.

Please Help!
Thanks

答:
It sounds like your configuration on the first box had a lower error reporting level.

You can set that in php.ini or in your code via ini_set.

php.ini

```<code>error_reporting = E_ALL & ~E_NOTICE
</code>```

php code

```<code>error_reporting(E_ALL ^ E_NOTICE);
</code>```

Body:
It sounds like your configuration on the first box had a lower error reporting level.

You can set that in php.ini or in your code via ini_set.

php.ini

error_reporting = E_ALL & ~E_NOTICE

php code

error_reporting(E_ALL ^ E_NOTICE);


问:
Inheritance in classes in Python3
So the Player class inherits traits from the Entity class but also has unique
traits of its own which are initialized within the Player class.

```<code>class Entity(object):
    def __init__(self, name, health, des):
        self.name = name
        self.health = health
        self.des = des
class Player(Entity):
    def __init__(self, mana):
        self.mana = mana
</code>```

Is this the proper way to do this?

答:
As @juanpa.arrivillaga pointed out, you probably want to call the super-class constructor. The way the __init__ functions work, there is currently no way to pass arguments down through the constructors.

An alternative approach would be:

```<code>class Entity(object):
    def __init__(self, name, health, des):
        self.name = name
        self.health = health
        self.des = des

class Player(Entity):
    def __init__(self, mana, *args):
        super().__init__(*args)
        self.mana = mana
</code>```

That way, when the Player is created you can pass all the arguments in:

```<code>mana = 100
name = "bob"
health = 1000
des = "potato"
player = Player(mana, name, health, des)
</code>```

It does have the odd pattern that new arguments are added to the start.

An alternative is to just use keyword arguments (having the * by itself means any non-keyword arguments will just get swallowed)

```<code>class Entity(object):
    def __init__(self, *, name, health, des):
        self.name = name
        self.health = health
        self.des = des

class Player(Entity):
    def __init__(self, *, mana, **kwargs):
        super().__init__(**kwargs)
        self.mana = mana
</code>```

Then the player can be initialised with:

```<code>mana = 100
name = "bob"
health = 1000
des = "potato"
player = Player(mana=mana, name=name, health=health, des=des)
</code>```

Title: Inheritance in classes in Python3

Body:
So the Player class inherits traits from the Entity class but also has unique
traits of its own which are initialized within the Player class.

class Entity(object):
    def __init__(self, name, health, des):
        self.name = name
        self.health = health
        self.des = des
class Player(Entity):
    def __init__(self, mana):
        self.mana = mana

Is this the proper way to do this?

Body:
As @juanpa.arrivillaga pointed out, you probably want to call the super-class constructor. The way the __init__ functions work, there is currently no way to pass arguments down through the constructors.

An alternative approach would be:

class Entity(object):
    def __init__(self, name, health, des):
        self.name = name
        self.health = health
        self.des = des

class Player(Entity):
    def __init__(self, mana, *args):
        super().__init__(*args)
        self.mana = mana

That way, when the Player is created you can pass all the arguments in:

mana = 100
name = "bob"
health = 1000
des = "potato"
player = Player(mana, name, health, des)

It does have the odd pattern that new arguments are added to the start.

An alternative is to just use keyword arguments (having the * by itself means any non-keyword arguments will just get swallowed)

class Entity(object):
    def __init__(self, *, name, health, des):
        self.name = name
        self.health = health
        self.des = des

class Player(Entity):
    def __init__(self, *, mana, **kwargs):
        super().__init__(**kwargs)
        self.mana = mana

Then the player can be initialised with:

mana = 100
name = "bob"
health = 1000
des = "potato"
player = Player(mana=mana, name=name, health=health, des=des)


问:
Shiny: Join Cells in R
I would like to make this table:

Look like this:

答:
Using dplyr:

```<code>df <- tibble(id = c(1,1,3),
             b = c("foo", "bar", "foo"),
              c = c("x", "y", "z"))
df

# A tibble: 3 x 3
     id b     c
  <dbl> <chr> <chr>
1     1 foo   x
2     1 bar   y
3     3 foo   z

df %>% group_by(id) %>%
  summarize(new = paste(b, collapse = ","),
            new2 = paste(c, collapse = ","))
</code>```

which results in:

```<code># A tibble: 2 x 3
      a new     new2
  <dbl> <chr>   <chr>
1     1 foo,bar x,y
2     3 foo     z

</code>```

Title: Shiny: Join Cells in R

Body:
Using dplyr:

df <- tibble(id = c(1,1,3),
             b = c("foo", "bar", "foo"),
              c = c("x", "y", "z"))
df

# A tibble: 3 x 3
     id b     c
  <dbl> <chr> <chr>
1     1 foo   x
2     1 bar   y
3     3 foo   z

df %>% group_by(id) %>%
  summarize(new = paste(b, collapse = ","),
            new2 = paste(c, collapse = ","))

which results in:

# A tibble: 2 x 3
      a new     new2
  <dbl> <chr>   <chr>
1     1 foo,bar x,y
2     3 foo     z


问:
Unable to get linq query data in the async ActionResult with await and task, Error: await can't be used with async method
How to get the LINQ query data in the Task<IHttpActionResult> return type? I have stored the data in var ponddata variable. How to return the data in the Task<IHttpActionResult> action method? I'm getting this error at return Ok statement:

Error CS1061  'IQueryable<>' does not contain a definition for
  'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting
  a first argument of type 'IQueryable<>' could be found (are
  you missing a using directive or an assembly reference?)

Code:

```<code>public async Task<IHttpActionResult> GetAllData(string user)
{
    using (smartpondEntities entities = new smartpondEntities())
    {
        try
        {
            var ponddata = from pond in entities.ponds
                join customerdevice in entities.CustomerDevices on pond.imei equals customerdevice.imei
                join userdata in entities.Users on customerdevice.CustomerId equals userdata.CustomerId
                where userdata.Username == "user1"
                select new { temperature = pond.temp, Imei = pond.imei, timestamp = pond.timestatmp };
            return Ok(await ponddata);
        }
        catch (Exception Ex)
        {
            return BadRequest("Sorry Error Found!!!");
        }
    }
}
</code>```

答:
The compiler returns the Task for you when you use the async and await pattern, (or more precisely) when you decorate your method with the async keyword

```<code>public async Task<IHttpActionResult> GetAllData(string user)
</code>```

To take advantage of the pattern, you commonly await something in these methods.

Body:
How to get the LINQ query data in the Task<IHttpActionResult> return type? I have stored the data in var ponddata variable. How to return the data in the Task<IHttpActionResult> action method? I'm getting this error at return Ok statement:

Error CS1061  'IQueryable<>' does not contain a definition for
  'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting
  a first argument of type 'IQueryable<>' could be found (are
  you missing a using directive or an assembly reference?)

Code:

public async Task<IHttpActionResult> GetAllData(string user)
{
    using (smartpondEntities entities = new smartpondEntities())
    {
        try
        {
            var ponddata = from pond in entities.ponds
                join customerdevice in entities.CustomerDevices on pond.imei equals customerdevice.imei
                join userdata in entities.Users on customerdevice.CustomerId equals userdata.CustomerId
                where userdata.Username == "user1"
                select new { temperature = pond.temp, Imei = pond.imei, timestamp = pond.timestatmp };
            return Ok(await ponddata);
        }
        catch (Exception Ex)
        {
            return BadRequest("Sorry Error Found!!!");
        }
    }
}

Body:
The compiler returns the Task for you when you use the async and await pattern, (or more precisely) when you decorate your method with the async keyword

public async Task<IHttpActionResult> GetAllData(string user)

To take advantage of the pattern, you commonly await something in these methods.


问:
How should I serialize / reference App Engine users?
This is a follow-up to this question:

How do I correctly reference Users in GQL queries on App Engine?

In my app, I have a Photos db.Model, where each photo has a UserProperty.  I want to display a list of users, where clicking on a user will show all of the user's photos.

What is the best way to reference the user when creating a link to the user's photo page?

I've found two options, both which have their shortcomings.

user.nickname() - this can be used in a GQL query (e.g. Photos.gql("WHERE user = USER(:1)", user.nickname()) ), but it can change, it's not necessarily unique, and sometimes (e.g. for Gmail addresses) user.nickname() truncates at the '@' symbol and can't be used for lookups without appending "@gmail.com".

user.user_id() - this is unique, but I haven't found a way to lookup a user by the user_id()

Is there a better way to do this?  Currently, I'm storing both the user and the user_id() on the Photo model, doing a GQL search by user_id passed in the link, and then referencing the user from the UserProperty on the Photo model.

答:
I think the best way is to pass the user_id as the key_name and use get_or_insert()</p>

```<code>import models
from google.appengine.ext import db
from google.appengine.api import users
class Photo( db.Model ):
    owner = db.UserProperty()
    title = db.StringProperty()

photo = Photo(key_name=users.get_current_user().user_id())
photo.owner=users.get_current_user()
photo.title= 'hai'
photo.put()
user_id = users.get_current_user().user_id()

photo = Photo.get_or_insert(user_id)
</code>```

Body:
I think the best way is to pass the user_id as the key_name and use get_or_insert()

import models
from google.appengine.ext import db
from google.appengine.api import users
class Photo( db.Model ):
    owner = db.UserProperty()
    title = db.StringProperty()

photo = Photo(key_name=users.get_current_user().user_id())
photo.owner=users.get_current_user()
photo.title= 'hai'
photo.put()
user_id = users.get_current_user().user_id()

photo = Photo.get_or_insert(user_id)


问:
What's the alternative to .notifyItemInserted() for multiple items?
I'm using a RecyclerView and .notifyItemInserted only inserts one item into the RecyclerView. How would I do that say, for multiple items? I want to AVOID using .notifyDataSetChanged().

Say I have 25 items, I want to insert another 20, what method would I call?

答:
You can use notifyItemRangeInserted to notify for multiple insertion.

```<code>void notifyItemRangeInserted (int positionStart, int itemCount)
</code>```

According official documentation

Notify any registered observers that the currently reflected itemCount
  items starting at positionStart have been newly inserted. The items
  previously located at positionStart and beyond can now be found
  starting at position positionStart + itemCount.

Body:
You can use notifyItemRangeInserted to notify for multiple insertion.

void notifyItemRangeInserted (int positionStart, int itemCount)

According official documentation

Notify any registered observers that the currently reflected itemCount
  items starting at positionStart have been newly inserted. The items
  previously located at positionStart and beyond can now be found
  starting at position positionStart + itemCount.


问:
Exception in thread "main" java.io.IOException: File already exists. This may lead to undesired behavior. (FragmentClass)
This issue has been a plague on my migration of an application from NativeScript 5.4.0 to NativeScript 6.3.3. I am now using webpack.config.js in combination with nativescript-worker-loader (Workers).

I have performed the required steps in the webpack file and the code that breaks on tns build android works when ran on a device with tns run android.

Error on tns build android:

```<code>         + adding aar plugin dependency: C:\Dev\node_modules\tns-core-modules-widgets\platforms\android\widgets-release.aar
Warning: there already is an extend called com.tns.FragmentClass.
Warning: The static binding generator will generate extend from:vendor.js implementation
Exception in thread "main" java.io.IOException: File already exists. This may lead to undesired behavior.
Please change the name of one of the extended classes.
File:C:\Dev\platforms\android\app\src\main\java\com\tns\FragmentClass.java Class: com.tns.FragmentClass
        at org.nativescript.staticbindinggenerator.Generator.writeBindings(Generator.java:112)
        at org.nativescript.staticbindinggenerator.Main.main(Main.java:50)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:runSbg'.
> Process 'command 'C:\Program Files\Java\jdk1.8.0_211\bin\java.exe'' finished with non-zero exit value 1
</code>```

package.json:

```<code>{
  "description": "xx",
  "license": "SEE LICENSE IN <your-license-filename>",
  "readme": "NativeScript Application",
  "repository": "<fill-your-repository-here>",
  "nativescript": {
    "id": "xx.xx.xx.xx",
    "tns-ios": {
      "version": "6.0.1"
    },
    "tns-android": {
      "version": "6.0.0"
    }
  },
  "dependencies": {
    "@nstudio/nativescript-checkbox": "^1.0.0",
    "@nstudio/nativescript-floatingactionbutton": "^2.0.0",
    "base-64": "^0.1.0",
    "chokidar": "^3.3.1",
    "currency-formatter": "^1.3.2",
    "is-json": "^2.0.1",
    "lodash": "^4.17.15",
    "md5": "^2.2.1",
    "moment": "^2.24.0",
    "nativescript-activity-detection": "^0.1.1",
    "nativescript-android-utils": "^1.0.2",
    "nativescript-bitmap-factory": "^1.7.1",
    "nativescript-camera": "4.5.0",
    "nativescript-couchbase": "^1.0.18",
    "nativescript-dialog": "^0.1.0",
    "nativescript-drawingpad": "^3.0.3",
    "nativescript-drop-down": "^4.0.1",
    "nativescript-exit": "^1.0.1",
    "nativescript-geolocation": "^5.1.0",
    "nativescript-google-maps-sdk": "^2.7.0",
    "nativescript-gradient": "^2.0.1",
    "nativescript-imagepicker": "6.2.0",
    "nativescript-insomnia": "^1.2.2",
    "nativescript-localstorage": "^2.0.0",
    "nativescript-maskedinput": "0.0.3",
    "nativescript-permissions": "^1.3.6",
    "nativescript-phone": "^1.3.1",
    "nativescript-sqlite": "^2.3.3",
    "nativescript-sqlite-commercial": "file:custom_plugins/nativescript-sqlite-commercial-1.3.2-plugin.tgz",
    "nativescript-sqlite-encrypted": "file:custom_plugins/nativescript-sqlite-encrypted-1.4.0-plugin.tgz",
    "nativescript-statusbar": "^3.0.1",
    "nativescript-theme-core": "^1.0.4",
    "nativescript-toast": "^1.4.6",
    "nativescript-ui-autocomplete": "^6.0.0",
    "nativescript-ui-calendar": "^6.0.0",
    "nativescript-ui-chart": "^7.1.1",
    "nativescript-ui-dataform": "^6.0.0",
    "nativescript-ui-gauge": "^6.0.0",
    "nativescript-ui-listview": "7.0.0",
    "nativescript-ui-sidedrawer": "^8.0.0",
    "nativescript-unit-test-runner": "0.7.0",
    "node-stopwatch": "0.0.1",
    "semver": "^5.4.1",
    "stopwatch": "^0.2.0",
    "stopwatch.js": "^1.1.1",
    "timer-stopwatch": "^0.2.0",
    "tns-core-modules": "6.3.0",
    "utf8": "^2.1.2"
  },
  "devDependencies": {
    "add": "^2.0.6",
    "babel-traverse": "6.25.0",
    "babel-types": "6.25.0",
    "babylon": "6.17.4",
    "chai": "^4.1.0",
    "karma": "4.1.0",
    "karma-chai": "^0.1.0",
    "karma-mocha": "^1.3.0",
    "karma-nativescript-launcher": "^0.4.0",
    "karma-webpack": "3.0.5",
    "lazy": "1.0.11",
    "mocha": "^7.0.1",
    "nativescript-dev-webpack": "1.0.1",
    "nativescript-worker-loader": "^0.10.0",
    "serialize-javascript": "^2.1.2",
    "tns-platform-declarations": "6.0.1",
    "typescript": "3.4.5"
  }
}
</code>```

I have deleted and refreshed the node_modules, platforms, hooks many times and the only way I can build is to remove all references to my workers so that they are not included in the bundle.

I have also gone to forums with similar problems Case 1 and Case 2 and more to no avail.

Please let me know if anything else should be included in the question text.
Thanks in advance.

答:
This Answer serves as a temporary one and I will change it once it is official.

This bug has been reported as "a bug in the NativeScript build system" in the latest version of NativeScript.

This should no longer be an error that occurs in newer versions of NativeScript and will be patched soon in a new version.

Body:
This issue has been a plague on my migration of an application from NativeScript 5.4.0 to NativeScript 6.3.3. I am now using webpack.config.js in combination with nativescript-worker-loader (Workers).

I have performed the required steps in the webpack file and the code that breaks on tns build android works when ran on a device with tns run android.

Error on tns build android:

         + adding aar plugin dependency: C:\Dev\node_modules\tns-core-modules-widgets\platforms\android\widgets-release.aar
Warning: there already is an extend called com.tns.FragmentClass.
Warning: The static binding generator will generate extend from:vendor.js implementation
Exception in thread "main" java.io.IOException: File already exists. This may lead to undesired behavior.
Please change the name of one of the extended classes.
File:C:\Dev\platforms\android\app\src\main\java\com\tns\FragmentClass.java Class: com.tns.FragmentClass
        at org.nativescript.staticbindinggenerator.Generator.writeBindings(Generator.java:112)
        at org.nativescript.staticbindinggenerator.Main.main(Main.java:50)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:runSbg'.
> Process 'command 'C:\Program Files\Java\jdk1.8.0_211\bin\java.exe'' finished with non-zero exit value 1

package.json:

{
  "description": "xx",
  "license": "SEE LICENSE IN <your-license-filename>",
  "readme": "NativeScript Application",
  "repository": "<fill-your-repository-here>",
  "nativescript": {
    "id": "xx.xx.xx.xx",
    "tns-ios": {
      "version": "6.0.1"
    },
    "tns-android": {
      "version": "6.0.0"
    }
  },
  "dependencies": {
    "@nstudio/nativescript-checkbox": "^1.0.0",
    "@nstudio/nativescript-floatingactionbutton": "^2.0.0",
    "base-64": "^0.1.0",
    "chokidar": "^3.3.1",
    "currency-formatter": "^1.3.2",
    "is-json": "^2.0.1",
    "lodash": "^4.17.15",
    "md5": "^2.2.1",
    "moment": "^2.24.0",
    "nativescript-activity-detection": "^0.1.1",
    "nativescript-android-utils": "^1.0.2",
    "nativescript-bitmap-factory": "^1.7.1",
    "nativescript-camera": "4.5.0",
    "nativescript-couchbase": "^1.0.18",
    "nativescript-dialog": "^0.1.0",
    "nativescript-drawingpad": "^3.0.3",
    "nativescript-drop-down": "^4.0.1",
    "nativescript-exit": "^1.0.1",
    "nativescript-geolocation": "^5.1.0",
    "nativescript-google-maps-sdk": "^2.7.0",
    "nativescript-gradient": "^2.0.1",
    "nativescript-imagepicker": "6.2.0",
    "nativescript-insomnia": "^1.2.2",
    "nativescript-localstorage": "^2.0.0",
    "nativescript-maskedinput": "0.0.3",
    "nativescript-permissions": "^1.3.6",
    "nativescript-phone": "^1.3.1",
    "nativescript-sqlite": "^2.3.3",
    "nativescript-sqlite-commercial": "file:custom_plugins/nativescript-sqlite-commercial-1.3.2-plugin.tgz",
    "nativescript-sqlite-encrypted": "file:custom_plugins/nativescript-sqlite-encrypted-1.4.0-plugin.tgz",
    "nativescript-statusbar": "^3.0.1",
    "nativescript-theme-core": "^1.0.4",
    "nativescript-toast": "^1.4.6",
    "nativescript-ui-autocomplete": "^6.0.0",
    "nativescript-ui-calendar": "^6.0.0",
    "nativescript-ui-chart": "^7.1.1",
    "nativescript-ui-dataform": "^6.0.0",
    "nativescript-ui-gauge": "^6.0.0",
    "nativescript-ui-listview": "7.0.0",
    "nativescript-ui-sidedrawer": "^8.0.0",
    "nativescript-unit-test-runner": "0.7.0",
    "node-stopwatch": "0.0.1",
    "semver": "^5.4.1",
    "stopwatch": "^0.2.0",
    "stopwatch.js": "^1.1.1",
    "timer-stopwatch": "^0.2.0",
    "tns-core-modules": "6.3.0",
    "utf8": "^2.1.2"
  },
  "devDependencies": {
    "add": "^2.0.6",
    "babel-traverse": "6.25.0",
    "babel-types": "6.25.0",
    "babylon": "6.17.4",
    "chai": "^4.1.0",
    "karma": "4.1.0",
    "karma-chai": "^0.1.0",
    "karma-mocha": "^1.3.0",
    "karma-nativescript-launcher": "^0.4.0",
    "karma-webpack": "3.0.5",
    "lazy": "1.0.11",
    "mocha": "^7.0.1",
    "nativescript-dev-webpack": "1.0.1",
    "nativescript-worker-loader": "^0.10.0",
    "serialize-javascript": "^2.1.2",
    "tns-platform-declarations": "6.0.1",
    "typescript": "3.4.5"
  }
}

I have deleted and refreshed the node_modules, platforms, hooks many times and the only way I can build is to remove all references to my workers so that they are not included in the bundle.

I have also gone to forums with similar problems Case 1 and Case 2 and more to no avail.

Please let me know if anything else should be included in the question text.
Thanks in advance.


问:
How to detect and rotate images in python
I have multiple pdf invoice which i am trying to parse. I convert them to images and use ocr to get text from the images. One of the pdf has 2 out of 3 pages which are rotated by 90 degrees. How do i detect these rotated pages and correctly rotate them for the ocr to return correct information ?</p>

答:
To keep the image intact, you can set the parameter 'expand' to True</p>

```<code>image = image.rotate(270, expand=True)
</code>```

Body:
To keep the image intact, you can set the parameter 'expand' to True

image = image.rotate(270, expand=True)


答:
Take a look here:
error-reporting

You can try something like that (runtime):

```<code><?php
  error_reporting(E_ALL ^ E_NOTICE);
?>
</code>```

Or update php.ini:

```<code>error_reporting = E_ALL & ~E_NOTICE
</code>```

Title: Help with Undefined index and Undefined variable

Body:
Could somebody help me with this problem. I just trasferred my PHP/MYSQL program to another computer (both are running XAMPP and on localhost) and now I got a massive amount of Undefined index and Undefined variable ERRORS. Could somebody explain me why?

All the variables are checked with isset and all the values should be OK, but I can't get anything to work as it is supposed to and then there are the Undefined index and Undefined variable ERRORS.

Please Help!
Thanks

Body:
Take a look here:
error-reporting

You can try something like that (runtime):

<?php
  error_reporting(E_ALL ^ E_NOTICE);
?>

Or update php.ini:

error_reporting = E_ALL & ~E_NOTICE


问:
Is there a way to check when someone's role was added? [Discord.js]
I'm trying to get the date when someone got a role, but I'm not sure how to do it and if there is really any way. I've been searching for this a really long time. I would love some help.

const Discord = require('discord.js');
let Bot = new Discord.Client();

async function GetDate(userid) {
  if (!userid) return message.reply('')
}

Bot.on("message", async(message) => {
    let messageArray = message.content.split(" ");
    let cmd = messageArray[0];
    let args = messageArray.slice(1);

    if(cmd === `!GetDate`) {
      let User = args[0]

      message.reply(`${User} is a member since 2020-02-17`)
    }
});```

I

答:
You can listen the event guildMemberUpdate, then fetch audit log with type memberRoleUpdate and get the audit log entires.

bot.on('guildMemberUpdate', (oldMember, newMember) => {
    if(oldMember.roles.cache.size < newMember.roles.cache.size) {
        const fetchedLogs = await oldMember.guild.fetchAuditLogs({
        limit: 1,
        type: 'MEMBER_ROLE_UPDATE',
    });

        const roleAddLog = fetchedLogs.entries.first();
        if (!roleAddLog ) return;
        const { executor, target, changes} = roleAddLog;
        console.log(`Role ${changes[0].new[0].name} added to <@${target.id}> by <@${executor.id}>`)
    }
});
```
<hr />
<p><strong>V2</strong></p>
<p>Oh, so you can get role by ID and get role <code>createdAdd</code></p>
```client.on('message', message => {
    let targetRole = message.guild.roles.get('PLACEROLEID')
    if(targetRole) console.log(targetRole.createdAt)
});
```

Body:
I'm trying to get the date when someone got a role, but I'm not sure how to do it and if there is really any way. I've been searching for this a really long time. I would love some help.

const Discord = require('discord.js');
let Bot = new Discord.Client();

async function GetDate(userid) {
  if (!userid) return message.reply('')
}

Bot.on("message", async(message) => {
    let messageArray = message.content.split(" ");
    let cmd = messageArray[0];
    let args = messageArray.slice(1);

    if(cmd === `!GetDate`) {
      let User = args[0]

      message.reply(`${User} is a member since 2020-02-17`)
    }
});

I

Body:
You can listen the event guildMemberUpdate, then fetch audit log with type memberRoleUpdate and get the audit log entires.

bot.on('guildMemberUpdate', (oldMember, newMember) => {
    if(oldMember.roles.cache.size < newMember.roles.cache.size) {
        const fetchedLogs = await oldMember.guild.fetchAuditLogs({
        limit: 1,
        type: 'MEMBER_ROLE_UPDATE',
    });

        const roleAddLog = fetchedLogs.entries.first();
        if (!roleAddLog ) return;
        const { executor, target, changes} = roleAddLog;
        console.log(`Role ${changes[0].new[0].name} added to <@${target.id}> by <@${executor.id}>`)
    }
});

V2

Oh, so you can get role by ID and get role createdAdd

client.on('message', message => {
    let targetRole = message.guild.roles.get('PLACEROLEID')
    if(targetRole) console.log(targetRole.createdAt)
});


问:
replace multiple values in a column and keep other values unchanged in pandas dataframe
I have an example dataframe like below:

```<code>df = pd.DataFrame({'name': ['red', 'orange', 'blue'],
                   'value': [22,44,66]})

    name    value
0   red     22
1   orange  44
2   blue    66
</code>```

I need to replace red with 1 and blue with 2, leaving orange as it is, in the column name.

I use map function like below:

```<code>df.name.map({'red': 0, 'blue': 1})
</code>```

I got result like:

```<code>    name    value
0   0.0     22
1   NaN     44
2   1.0     66
</code>```

In the column, orange becomes NaN

What is the best way to replace the values?

I do not want to use df.name.str.replace(..) many times to replace many values. In my real data, there are 10 values to replace in a column.
Thanks.

答:
You can use Series.replace:

```<code>print (df["name"].replace({'red': 0, 'blue': 1}))

0         0
1    orange
2         1
Name: name, dtype: object
</code>```

Body:
I have an example dataframe like below:

df = pd.DataFrame({'name': ['red', 'orange', 'blue'],
                   'value': [22,44,66]})

    name    value
0   red     22
1   orange  44
2   blue    66

I need to replace red with 1 and blue with 2, leaving orange as it is, in the column name.

I use map function like below:

df.name.map({'red': 0, 'blue': 1})

I got result like:

    name    value
0   0.0     22
1   NaN     44
2   1.0     66

In the column, orange becomes NaN

What is the best way to replace the values?

I do not want to use df.name.str.replace(..) many times to replace many values. In my real data, there are 10 values to replace in a column.
Thanks.

Body:
You can use Series.replace:

print (df["name"].replace({'red': 0, 'blue': 1}))

0         0
1    orange
2         1
Name: name, dtype: object


问:
Picked up _JAVA_OPTIONS: -Xmx256M
While running every program i am getting this message Picked up _JAVA_OPTIONS: -Xmx256M on console in eclipse without output.

I already tried related answers but none of them working in my case and I am not using _JAVA_OPTIONS variable in environment variable.
runtime error:

```<code>Picked up _JAVA_OPTIONS: -Xmx256M
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [util.c:840]
</code>```

答:
Go to System Environment Variables
check for JAVA_OPTIONS under variables
delete or update based on your requirement
i got the value as 1024 i modified to 16384
-Xms1024m -Xmx16384m</p>

Title: Picked up _JAVA_OPTIONS: -Xmx256M

Body:
While running every program i am getting this message Picked up _JAVA_OPTIONS: -Xmx256M on console in eclipse without output.

I already tried related answers but none of them working in my case and I am not using _JAVA_OPTIONS variable in environment variable.
runtime error:

Picked up _JAVA_OPTIONS: -Xmx256M
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [util.c:840]


问:
Duplicating each dataframe value n times
I have a data in csv that looks like this: original data

I am trying to rewrite the csv and make my data to look like this:
What I want it to look like

I can't seem to get individual data of the time column.

dataset = pd.read_csv('/data.csv', index_col=False, dtype='unicode')
df = pd.DataFrame(dataset)
timeCol = df['Time']
print(timeCol)
counter = 0
for index, row in timeCol.itertuples():
    if(counter < 2):
        print(row)
        counter +=1
    else:
        counter =0
```

I will have an error at AttributeError: 'Series' object has no attribute 'itertuples'. Why is that so?

My logic seems wrong, is there a better way to do it?

答:
Thanks to ansev</p>

```<code>newdata = df.melt('Time',var_name = 'Shape',value_name = 'Color')
</code>```

Body:
I have a data in csv that looks like this: original data

I am trying to rewrite the csv and make my data to look like this:
What I want it to look like

I can't seem to get individual data of the time column.

dataset = pd.read_csv('/data.csv', index_col=False, dtype='unicode')
df = pd.DataFrame(dataset)
timeCol = df['Time']
print(timeCol)
counter = 0
for index, row in timeCol.itertuples():
    if(counter < 2):
        print(row)
        counter +=1
    else:
        counter =0

I will have an error at AttributeError: 'Series' object has no attribute 'itertuples'. Why is that so?

My logic seems wrong, is there a better way to do it?

Body:
Thanks to ansev

newdata = df.melt('Time',var_name = 'Shape',value_name = 'Color')


问:
How to count AR point cloud number? (Unity AR Foundation 3.0.1)
I have been trying to count the number of all ar point cloud collected in the AR session.

I've tried the following code, but arPointCloud keeps throwing error message:

```<code>Object reference not set to an instance of an object
</code>```

I would be so happy if anyone can help me.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;

public class PointNumberCount : MonoBehaviour
{
 ARSessionOrigin arSessionOrigin;
 ARPointCloud arPointCloud;

 int totalNumber;
 List<Vector3> featurePoints = new List<Vector3>();

 void Start()
 {

     arSessionOrigin = GetComponent<ARSessionOrigin>();

     arPointCloud = arSessionOrigin.trackablesParent.GetComponentInChildren<ARPointCloud>();
 }
 void Update()
 {

         arPointCloud = arSessionOrigin.trackablesParent.GetComponentInChildren<ARPointCloud>();
         featurePoints = new List<Vector3>(arPointCloud.positions);
         totalNumber = featurePoints.Count;

 }
}
}
</code>```

答:
I'm using the unity AR foundation 1.5.0 preview.6 and they have their own script for counting point cloud but in their script, we can't edit anything. So we need to create a custom script for counting point cloud.

Please check all the images.

First, make sure you add you add a reference to point cloud manager.

Then remove Ar point Cloud Particle Visualizer.

Attach a script and Reference.

Script:-

```<code>using System;
using System.Collections.Generic;
using UnityEngine.XR.ARSubsystems;
using UnityEngine.UI;
namespace UnityEngine.XR.ARFoundation
{
   /// <summary>
   /// Renders an <see cref="ARPointCloud"/> as a <c>ParticleSystem</c>.
   /// </summary>
   [RequireComponent(typeof(ARPointCloud))]
   [RequireComponent(typeof(ParticleSystem))]

   public class ARPointCloudParticleVisualizer : MonoBehaviour
   {
    public Text t;
    void OnPointCloudChanged(ARPointCloudUpdatedEventArgs eventArgs)
    {
        var points = s_Vertices;
        points.Clear();
        foreach (var point in m_PointCloud.positions)
            s_Vertices.Add(point);

        int numParticles = points.Count;
        if (m_Particles == null || m_Particles.Length < numParticles)
            m_Particles = new ParticleSystem.Particle[numParticles];

        var color = m_ParticleSystem.main.startColor.color;
        var size = m_ParticleSystem.main.startSize.constant;

        for (int i = 0; i < numParticles; ++i)
        {
            m_Particles[i].startColor = color;
            m_Particles[i].startSize = size;
            m_Particles[i].position = points[i];
            m_Particles[i].remainingLifetime = 1f;
        }

        // Remove any existing particles by setting remainingLifetime
        // to a negative value.
        for (int i = numParticles; i < m_NumParticles; ++i)
        {
            m_Particles[i].remainingLifetime = -1f;
        }

        m_ParticleSystem.SetParticles(m_Particles, Math.Max(numParticles, m_NumParticles));
        m_NumParticles = numParticles;
    }

    void Awake()
    {
        m_PointCloud = GetComponent<ARPointCloud>();
        m_ParticleSystem = GetComponent<ParticleSystem>();
    }

    void OnEnable()
    {
        m_PointCloud.updated += OnPointCloudChanged;
        UpdateVisibility();
    }

    void OnDisable()
    {
        m_PointCloud.updated -= OnPointCloudChanged;
        UpdateVisibility();
    }

    void Update()
    {
        UpdateVisibility();
    }

    void UpdateVisibility()
    {
        var visible =
            enabled &&
            (m_PointCloud.trackingState != TrackingState.None);

        SetVisible(visible);
    }

    void SetVisible(bool visible)
    {
        if (m_ParticleSystem == null)
            return;

        var renderer = m_ParticleSystem.GetComponent<Renderer>();
        t.text = m_NumParticles.ToString();
        if (renderer != null)
            renderer.enabled = visible;
    }

    ARPointCloud m_PointCloud;

    ParticleSystem m_ParticleSystem;

    ParticleSystem.Particle[] m_Particles;

    int m_NumParticles;

    static List<Vector3> s_Vertices = new List<Vector3>();
    }
}
</code>```

This is working for me.

Body:
I have been trying to count the number of all ar point cloud collected in the AR session.

I've tried the following code, but arPointCloud keeps throwing error message:

Object reference not set to an instance of an object

I would be so happy if anyone can help me.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;

public class PointNumberCount : MonoBehaviour
{
 ARSessionOrigin arSessionOrigin;
 ARPointCloud arPointCloud;

 int totalNumber;
 List<Vector3> featurePoints = new List<Vector3>();

 void Start()
 {

     arSessionOrigin = GetComponent<ARSessionOrigin>();

     arPointCloud = arSessionOrigin.trackablesParent.GetComponentInChildren<ARPointCloud>();
 }
 void Update()
 {

         arPointCloud = arSessionOrigin.trackablesParent.GetComponentInChildren<ARPointCloud>();
         featurePoints = new List<Vector3>(arPointCloud.positions);
         totalNumber = featurePoints.Count;

 }
}
}

Body:
I'm using the unity AR foundation 1.5.0 preview.6 and they have their own script for counting point cloud but in their script, we can't edit anything. So we need to create a custom script for counting point cloud.

Please check all the images.

First, make sure you add you add a reference to point cloud manager.

Then remove Ar point Cloud Particle Visualizer.

Attach a script and Reference.

Script:-

using System;
using System.Collections.Generic;
using UnityEngine.XR.ARSubsystems;
using UnityEngine.UI;
namespace UnityEngine.XR.ARFoundation
{
   /// <summary>
   /// Renders an <see cref="ARPointCloud"/> as a <c>ParticleSystem</c>.
   /// </summary>
   [RequireComponent(typeof(ARPointCloud))]
   [RequireComponent(typeof(ParticleSystem))]

   public class ARPointCloudParticleVisualizer : MonoBehaviour
   {
    public Text t;
    void OnPointCloudChanged(ARPointCloudUpdatedEventArgs eventArgs)
    {
        var points = s_Vertices;
        points.Clear();
        foreach (var point in m_PointCloud.positions)
            s_Vertices.Add(point);

        int numParticles = points.Count;
        if (m_Particles == null || m_Particles.Length < numParticles)
            m_Particles = new ParticleSystem.Particle[numParticles];

        var color = m_ParticleSystem.main.startColor.color;
        var size = m_ParticleSystem.main.startSize.constant;

        for (int i = 0; i < numParticles; ++i)
        {
            m_Particles[i].startColor = color;
            m_Particles[i].startSize = size;
            m_Particles[i].position = points[i];
            m_Particles[i].remainingLifetime = 1f;
        }

        // Remove any existing particles by setting remainingLifetime
        // to a negative value.
        for (int i = numParticles; i < m_NumParticles; ++i)
        {
            m_Particles[i].remainingLifetime = -1f;
        }

        m_ParticleSystem.SetParticles(m_Particles, Math.Max(numParticles, m_NumParticles));
        m_NumParticles = numParticles;
    }

    void Awake()
    {
        m_PointCloud = GetComponent<ARPointCloud>();
        m_ParticleSystem = GetComponent<ParticleSystem>();
    }

    void OnEnable()
    {
        m_PointCloud.updated += OnPointCloudChanged;
        UpdateVisibility();
    }

    void OnDisable()
    {
        m_PointCloud.updated -= OnPointCloudChanged;
        UpdateVisibility();
    }

    void Update()
    {
        UpdateVisibility();
    }

    void UpdateVisibility()
    {
        var visible =
            enabled &&
            (m_PointCloud.trackingState != TrackingState.None);

        SetVisible(visible);
    }

    void SetVisible(bool visible)
    {
        if (m_ParticleSystem == null)
            return;

        var renderer = m_ParticleSystem.GetComponent<Renderer>();
        t.text = m_NumParticles.ToString();
        if (renderer != null)
            renderer.enabled = visible;
    }

    ARPointCloud m_PointCloud;

    ParticleSystem m_ParticleSystem;

    ParticleSystem.Particle[] m_Particles;

    int m_NumParticles;

    static List<Vector3> s_Vertices = new List<Vector3>();
    }
}

This is working for me.


问:
Can someone fluent in Javascript explain to me whats going on here SIMPLY
Im taking a course on udemy and I came across this code that changes the background of a window.  The thing is the function randColor loses me.  Id like to know exactly whats going on.

I know a function called randColor is declared, then the function itself RETURNS a function + # but I am trying to understand the logic of how it all happens.  There is a HASH symbol that is added and I believe its also an IIFE correct?

I very much appreciate the help!

```<code>document.querySelector("button").addEventListener("click", function(){
  document.body.style.background = randColor();
})

function randColor(){
  return '#' + (function co(lor){   return (lor +=
    [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'][Math.floor(Math.random()*16)])
    && (lor.length == 6) ?  lor : co(lor); })('');
}
</code>```

答:
i would like to propose a more simplified iterative code instead of the recursion.</p>

```<code>   <script type="text/javascript">
    document.querySelector("button").addEventListener("click", function(){
        // body
        document.body.style.background=randcolor();
    })

    function randcolor(){

        var list=['1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f'];
        var r='#';
        while(r.length<7)
        {
            r+=list[Math.floor(Math.random()*16)];
        }
        return r;
    }

</script>
</code>```

Body:
Im taking a course on udemy and I came across this code that changes the background of a window.  The thing is the function randColor loses me.  Id like to know exactly whats going on.

I know a function called randColor is declared, then the function itself RETURNS a function + # but I am trying to understand the logic of how it all happens.  There is a HASH symbol that is added and I believe its also an IIFE correct?

I very much appreciate the help!

document.querySelector("button").addEventListener("click", function(){
  document.body.style.background = randColor();
})

function randColor(){
  return '#' + (function co(lor){   return (lor +=
    [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'][Math.floor(Math.random()*16)])
    && (lor.length == 6) ?  lor : co(lor); })('');
}

Body:
i would like to propose a more simplified iterative code instead of the recursion.

   <script type="text/javascript">
    document.querySelector("button").addEventListener("click", function(){
        // body
        document.body.style.background=randcolor();
    })

    function randcolor(){

        var list=['1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f'];
        var r='#';
        while(r.length<7)
        {
            r+=list[Math.floor(Math.random()*16)];
        }
        return r;
    }

</script>


问:
The Expo SDK requires Expo to run. i am beginner in react-native?
I am an experienced android developer and started learning react native. I am using ubuntu to make a project. I used code like this one react-native init myprojectand am using visual studio code for code editor.

To run a project on my physical device I run adb devices on the terminal, change directory to project directory then I start localhost like react-native start then I start my project on android by this code react-native run-android. The project works fine on my physical device.

But I am getting an error when I use Expo (** I do not know what is expo is**). I am following the net ninja tutorial series. When I use expo-icons I get no icons. This is the tutorial link : icons

When today I was learning about how to use custom fonts in the react-native I got similar errors like this one shown in this link.

I do not know why does expo is not working on my project. Before following this series, I looked at the book to learn react-native which was saying that now we do not use expo. So how can I get out of this problem?

although i get few answer that clears what is expo and one have also answered the problem of icons in react-native . currently i am not able to use custom fonts in react-native .

答:
so i  got the answer of custom fonts from GitHub Facebook issue .

create react-native.config.js file in your root project folder than paste below code into that file

```<code>module.exports = {
  project: {
    ios: {},
    android: {},
  },
  assets: ["./assets/fonts/"],
};
</code>```

than you can use fonts as fontFamily : 'exact_file_name' after this process you will be able to see changes if you do not see any changes . re run your project via terminal and you should see changes of font in the project .

Thank You all the person who helped me .

Body:
so i  got the answer of custom fonts from GitHub Facebook issue .

create react-native.config.js file in your root project folder than paste below code into that file

module.exports = {
  project: {
    ios: {},
    android: {},
  },
  assets: ["./assets/fonts/"],
};

than you can use fonts as fontFamily : 'exact_file_name' after this process you will be able to see changes if you do not see any changes . re run your project via terminal and you should see changes of font in the project .

Thank You all the person who helped me .


问:
How to convert custom object with map field that includes list of custom object to json?
Let's say, I have an Employee class which looks like this:

```<code>public class Employee{

Map<String, ArrayList<Salary>> salary = new HashMap<String, ArrayList<Salary>>();
String name;
String age;
}

public class Salary{
String amount;
String currency;
}
</code>```

What is the smartest way of convertion to/from Json in Java?

Or;

What if my json should look like that:

```<code>  {
  "name": "Test",
  "age": "12",
  "salary": {
    "first": {
      "41130": {
        "amount": "100",
        "currency": "€"
      },
      "41132": {
        "amount": "100",
        "currency": "€"
      }
    },
    "second": {
      "41129": {
        "amount": "100",
        "currency": "€"
      }
    }
  }
}
</code>```

When i tried to convert this to Employee I am getting error below.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
  Expected BEGIN_ARRAY but was BEGIN_OBJECT

答:
Smartest way, if you plan to use that JSON on a web environment is to use Jackson, JAXB or anything your infraestructure already provides, e.g. Let your preferred REST infrastructure do the job for you.

You will need to provide more context on what is the purpose of your application or the required architecture.

Body:
Let's say, I have an Employee class which looks like this:

public class Employee{

Map<String, ArrayList<Salary>> salary = new HashMap<String, ArrayList<Salary>>();
String name;
String age;
}

public class Salary{
String amount;
String currency;
}

What is the smartest way of convertion to/from Json in Java?

Or;

What if my json should look like that:

  {
  "name": "Test",
  "age": "12",
  "salary": {
    "first": {
      "41130": {
        "amount": "100",
        "currency": "€"
      },
      "41132": {
        "amount": "100",
        "currency": "€"
      }
    },
    "second": {
      "41129": {
        "amount": "100",
        "currency": "€"
      }
    }
  }
}

When i tried to convert this to Employee I am getting error below.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
  Expected BEGIN_ARRAY but was BEGIN_OBJECT


问:
PHP SimpleXML Namespace Problem
I'm trying to get the entry->id and entry->cap:parameter->value for every entry in the RSS feed.... below is the code I'm using.  It is displaying the id correctly however it is not displaying the value field.... please help.

```<code>$url = 'http://alerts.weather.gov/cap/us.php?x=1';
$cap = simplexml_load_file($url);
foreach($cap->entry as $entry){
    echo 'ID: ', $entry->id, "\n";
    echo 'VTEC: ', $entry->children('cap', true)->parameter->value, "\n";
echo "<hr>";
}
</code>```

Thanks for the help in advance.

答:
The <value> element is not in the same namespace as <cap:parameter>:

```<code><cap:parameter>
    <valueName>VTEC</valueName>
    <value>/O.CON.KMPX.FL.W.0012.000000T0000Z-110517T1800Z/</value>
</cap:parameter>
</code>```

So you have to call children() again.

Code (demo)

```<code>$feed = simplexml_load_file('http://alerts.weather.gov/cap/us.php?x=1');
foreach ($feed->entry as $entry){
    printf(
        "ID: %s\nVTEC: %s\n<hr>",
        $entry->id,
        $entry->children('cap', true)->parameter->children()->value
    );
}
</code>```

Title: PHP SimpleXML Namespace Problem

Body:
I'm trying to get the entry->id and entry->cap:parameter->value for every entry in the RSS feed.... below is the code I'm using.  It is displaying the id correctly however it is not displaying the value field.... please help.

$url = 'http://alerts.weather.gov/cap/us.php?x=1';
$cap = simplexml_load_file($url);
foreach($cap->entry as $entry){
    echo 'ID: ', $entry->id, "\n";
    echo 'VTEC: ', $entry->children('cap', true)->parameter->value, "\n";
echo "
";
}

Thanks for the help in advance.

Body:
The <value> element is not in the same namespace as <cap:parameter>:

<cap:parameter>
    <valueName>VTEC</valueName>
    <value>/O.CON.KMPX.FL.W.0012.000000T0000Z-110517T1800Z/</value>
</cap:parameter>

So you have to call children() again.

Code (demo)

$feed = simplexml_load_file('http://alerts.weather.gov/cap/us.php?x=1');
foreach ($feed->entry as $entry){
    printf(
        "ID: %s\nVTEC: %s\n<hr>",
        $entry->id,
        $entry->children('cap', true)->parameter->children()->value
    );
}