问:
Change rectangle Fill color on mouse over WPF
I am new to WPF. This is my code for a rectangle :

```<code>  <Rectangle x:Name="rect1" Grid.Column="1" Fill="#FF505F75" HorizontalAlignment="Left" Height="50" Margin="36,171,0,0" StrokeThickness="2" VerticalAlignment="Top" Width="358" RadiusX="30" RadiusY="50">

    </Rectangle>
</code>```

And this is the code to animate a button's color-change on mouseOver :

```<code>    <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Trigger.EnterActions>
                            <BeginStoryboard>
                                <Storyboard x:Name="DisabledAnimation">
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop1"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource IsNotEnabledBackgroundColor1}"
                                                    Duration="0" />
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop2"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource IsNotEnabledBackgroundColor2}"
                                                    Duration="0" />
                                </Storyboard>
                            </BeginStoryboard>
                        </Trigger.EnterActions>
                        <Trigger.ExitActions>
                            <BeginStoryboard>
                                <Storyboard x:Name="EnabledAnimation">
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop1"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource BackgroundColor1}"
                                                    Duration="0" />
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop2"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource BackgroundColor2}"
                                                    Duration="0" />
                                </Storyboard>
                            </BeginStoryboard>
                        </Trigger.ExitActions>
                    </Trigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsEnabled" Value="True" />
                            <Condition Property="IsMouseOver" Value="True" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.EnterActions>
                            <BeginStoryboard>
                                <Storyboard x:Name="MouseOverAnimation">
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop1"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource MouseOverBackgroundColor1}"
                                                    Duration="0:0:0:1" />
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop2"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource MouseOverBackgroundColor2}"
                                                    Duration="0:0:0:1" />
                                </Storyboard>
                            </BeginStoryboard>
                        </MultiTrigger.EnterActions>
                        <MultiTrigger.ExitActions>
                            <BeginStoryboard>
                                <Storyboard x:Name="MouseOutAnimation" FillBehavior="Stop">
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop1"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource BackgroundColor1}"
                                                    Duration="0:0:0:1" />
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop2"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource BackgroundColor2}"
                                                    Duration="0:0:0:1" />
                                </Storyboard>
                            </BeginStoryboard>
                        </MultiTrigger.ExitActions>
                    </MultiTrigger>
</code>```

My question is, how can use it for the rectangle ??
Or how do i change the Fill color of a rectangle on mouse over?? Not just changing the color, but fading in the color...is it possible?

答:
Fixed it myself :</p>

```<code>  <Rectangle.Style>
            <Style TargetType="Rectangle">
                <Style.Triggers>
                    <EventTrigger RoutedEvent="Rectangle.MouseEnter">
                        <BeginStoryboard>
                            <Storyboard>
                                <ParallelTimeline  >
                                    <ColorAnimation Storyboard.TargetProperty="Fill.Color" To="#FF767C84" />
                                </ParallelTimeline>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                    <EventTrigger RoutedEvent="Rectangle.MouseLeave">
                        <BeginStoryboard>
                            <Storyboard>
                                <ParallelTimeline  >
                                    <ColorAnimation Storyboard.TargetProperty="Fill.Color" To="#FF5C626C" />
                                </ParallelTimeline>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
        </Rectangle.Style>
</code>```

Body:
I am new to WPF. This is my code for a rectangle :

  <Rectangle x:Name="rect1" Grid.Column="1" Fill="#FF505F75" HorizontalAlignment="Left" Height="50" Margin="36,171,0,0" StrokeThickness="2" VerticalAlignment="Top" Width="358" RadiusX="30" RadiusY="50">

    </Rectangle>

And this is the code to animate a button's color-change on mouseOver :

    <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Trigger.EnterActions>
                            <BeginStoryboard>
                                <Storyboard x:Name="DisabledAnimation">
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop1"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource IsNotEnabledBackgroundColor1}"
                                                    Duration="0" />
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop2"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource IsNotEnabledBackgroundColor2}"
                                                    Duration="0" />
                                </Storyboard>
                            </BeginStoryboard>
                        </Trigger.EnterActions>
                        <Trigger.ExitActions>
                            <BeginStoryboard>
                                <Storyboard x:Name="EnabledAnimation">
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop1"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource BackgroundColor1}"
                                                    Duration="0" />
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop2"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource BackgroundColor2}"
                                                    Duration="0" />
                                </Storyboard>
                            </BeginStoryboard>
                        </Trigger.ExitActions>
                    </Trigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsEnabled" Value="True" />
                            <Condition Property="IsMouseOver" Value="True" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.EnterActions>
                            <BeginStoryboard>
                                <Storyboard x:Name="MouseOverAnimation">
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop1"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource MouseOverBackgroundColor1}"
                                                    Duration="0:0:0:1" />
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop2"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource MouseOverBackgroundColor2}"
                                                    Duration="0:0:0:1" />
                                </Storyboard>
                            </BeginStoryboard>
                        </MultiTrigger.EnterActions>
                        <MultiTrigger.ExitActions>
                            <BeginStoryboard>
                                <Storyboard x:Name="MouseOutAnimation" FillBehavior="Stop">
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop1"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource BackgroundColor1}"
                                                    Duration="0:0:0:1" />
                                    <ColorAnimation Storyboard.TargetName="BackgroundGradientStop2"
                                                    Storyboard.TargetProperty="Color"
                                                    To="{StaticResource BackgroundColor2}"
                                                    Duration="0:0:0:1" />
                                </Storyboard>
                            </BeginStoryboard>
                        </MultiTrigger.ExitActions>
                    </MultiTrigger>

My question is, how can use it for the rectangle ??
Or how do i change the Fill color of a rectangle on mouse over?? Not just changing the color, but fading in the color...is it possible?

Body:
Fixed it myself :

  <Rectangle.Style>
            <Style TargetType="Rectangle">
                <Style.Triggers>
                    <EventTrigger RoutedEvent="Rectangle.MouseEnter">
                        <BeginStoryboard>
                            <Storyboard>
                                <ParallelTimeline  >
                                    <ColorAnimation Storyboard.TargetProperty="Fill.Color" To="#FF767C84" />
                                </ParallelTimeline>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                    <EventTrigger RoutedEvent="Rectangle.MouseLeave">
                        <BeginStoryboard>
                            <Storyboard>
                                <ParallelTimeline  >
                                    <ColorAnimation Storyboard.TargetProperty="Fill.Color" To="#FF5C626C" />
                                </ParallelTimeline>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
        </Rectangle.Style>


来源: stackexchange

问:
Call function in shared library but not declaration in header files
I am doing some implementation about calling function of shared library via Java to JNI.
And JNI is implemented by C code.
Here is my question.
There is a function named ABC() in shared library.
This function is not be declared in header files.
BUT with NDK build, it can be successful and this function also can work fine.

It's very confusing.
Why? why can it be built by NDK and why can it be called without any exception?
Thank you for answering:)

答:
There are two possibilities here.

The file using the function may contain its own declaration of the function. (Declarations are not required to be only in header files.)

If you use a function without declaring it, the compiler may provide a default declaration. This is not part of modern C, but compilers may use old standards or be unduly lax in this regard. The default declaration is a function of the type int SomeName(). Such implicit declarations automatically have external linkage, which means the name will be matched to the definition of the function when the library is linked in.

If the latter is the case, you would be well advised to enable additional switches to tell the compiler to issue more warning messages and to use a modern language standard (such as C 2011), at least when developing new code.

Using a routine that is in a shared library but is not declared in its header is inadvisable. Such routines are often intended only for internal use of the library, and they may change or vanish in future versions of the library. So code using them would break; it would not be compatible with the new versions of the library.

ContentLicense: CC BY-SA 3.0


问:
.remove does not work out - jQuery
I am trying to remove an id, and .live is necessary, the code is below

```<code>$('.TS').live('click',function() {
    ("#"+$(this).attr('id')).remove();
});
</code>```

The error got from chrome

Uncaught TypeError: Object #first has no method 'remove'

I tried removeId, but the above error message.

Appreciate all help

Thanks
Jean

答:
Try this, although it is an indirect way but it works - </p>

```<code>$('.TS').live('click',function() {
    $(this).attr('id','');
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: .remove does not work out - jQuery

Body:
I am trying to remove an id, and .live is necessary, the code is below

$('.TS').live('click',function() {
    ("#"+$(this).attr('id')).remove();
});

The error got from chrome

Uncaught TypeError: Object #first has no method 'remove'

I tried removeId, but the above error message.

Appreciate all help

Thanks
Jean

Body:
Try this, although it is an indirect way but it works -

$('.TS').live('click',function() {
    $(this).attr('id','');
});


问:
how to get the first day of the first month of the current year in RPGLE

dcl-s today date inz(*Sys) is  the current sytem date
 How do i get the first day of the first month of the current year in this format 2017/01/01</p>

答:
You may want to look into the %SUBST built-in function.</p>

```<code>date = d'1999-02-17';
time = t'01.23.45';
timestamp = z'1999-02-17-01.23.45.98765';

num = %subdt(date:*YEARS);
// num = 1999

num = %subdt(time:*MN);
// num = 23
</code>```

Body:
You may want to look into the %SUBST built-in function.

date = d'1999-02-17';
time = t'01.23.45';
timestamp = z'1999-02-17-01.23.45.98765';

num = %subdt(date:*YEARS);
// num = 1999

num = %subdt(time:*MN);
// num = 23


问:
Unable to post FormData via Ajax with Laravel (405 Error)
Straight to the point: The end goal here is to be able to submit multiple forms with one button in Laravel. One of the forms contains a file upload field.

When attempting to make the Ajax Call, i'm receiving a 405 Method Not Allowed error. Looking through several Stack Overflow questions, I have managed to narrow it down to two options (processData, contentType) in the Ajax Call below.

My issue is, If I remove both of these I then receive an Illegal Invocation error on the new Formdata($this). So, how would I submit a file upload whilst still keeping it an Ajax Call?

The Ajax Call

```<code>// Submit all forms

        $.each(forms, function(form){
            formData = new FormData(form);

            $.ajax({
                type: "POST",
                processData: false,
                contentType: false,
                url: $(this).attr('action'),
                data: formData,
                success: function(data){
                    console.log('Form submitted');
                },
                error: function(x, h, r){
                    console.log(x, h, r);
                }
            })
        });
</code>```

The route function that the forms are targetting

```<code>public function update(Request $request, $id)
{
    // Save clinic initially
    $clinic = Clinic::find($id);
    $clinic->update($request->all());

    // If image is present, save it and update it in the database table
    if ($request->file('clinic_logo')) {
        $file = $request->file('clinic_logo');
        $fileExtension = $file->getClientOriginalExtension();
        $filePath = '/img/profile_images/' . $request->get('clinic_name') . "." . $fileExtension;

        // Save Image
        $file->move(
            base_path() . '/public/img/profile_images/', $request->get('clinic_name') . "." . $fileExtension
        );

        // Update database table
        $clinic->logo = $filePath;
        $clinic->save();
    }

    $data = [
        'clinic' => $clinic,
        'categories' => Category::where('approved', 1)->pluck('name', 'id')
    ];

    $request->session()->flash('alert-success', 'Clinic has been successfully edited.');

    return redirect()->back();
}
</code>```

Screenshot of my Chrome Console with Options

Screenshot of my Chrome Console without options

Update 1

The actual routing works fine. If I remove both of those Ajax options, the forms post and the data updates correctly, just without the file upload. If I use a regular submit button in the form, everything works fine - including upload data. Route is a resource controller as below;

```<code>Route::resource('clinics', 'ClinicController');
</code>```

Update 2

So now at least, I know why i'm getting the 405 method not allowed errors. Setting processData: false screws up the request data resulting in Laravel not understanding both the csrf_token and the _method field - resulting in Method not allowed. Still not sure how to fix this, just thought the extra info might help.

Update 3

Routes list, as requested.

```<code>|        | POST      | clinics                           | clinics.store         | App\Http\Controllers\ClinicController@store                            | web          |
|        | GET|HEAD  | clinics                           | clinics.index         | App\Http\Controllers\ClinicController@index                            | web          |
|        | PUT       | clinics/approve/{id}              | clinics.approve       | App\Http\Controllers\ClinicController@approve                          | web          |
|        | GET|HEAD  | clinics/create                    | clinics.create        | App\Http\Controllers\ClinicController@create                           | web          |
|        | GET|HEAD  | clinics/request                   |                       | App\Http\Controllers\ClinicController@request                          | web          |
|        | PUT|PATCH | clinics/{clinic}                  | clinics.update        | App\Http\Controllers\ClinicController@update                           | web          |
|        | GET|HEAD  | clinics/{clinic}                  | clinics.show          | App\Http\Controllers\ClinicController@show                             | web          |
|        | DELETE    | clinics/{clinic}                  | clinics.destroy       | App\Http\Controllers\ClinicController@destroy                          | web          |
|        | GET|HEAD  | clinics/{clinic}/edit             | clinics.edit          | App\Http\Controllers\ClinicController@edit                             | web          |
</code>```

The forms are pretty big, but they're built using the form model binding pattern found here.

```<code>{!! Form::model($clinic, ['route' => ['clinics.update', $clinic], 'method' => 'PUT', 'files' => true, 'class' => 'multi-part-form']) !!}
</code>```

答:
When dealing with ajax with attachment. Implying the FormData() function in your javascript will not easily bind your file attachments. you need to separately bind your attachments into something like this.

```<code>formData = new FormData(form);
formData.append('image', $('input[type=file]')[0].files[0]);
</code>```

i hope this will help you

Body:
Straight to the point: The end goal here is to be able to submit multiple forms with one button in Laravel. One of the forms contains a file upload field.

When attempting to make the Ajax Call, i'm receiving a 405 Method Not Allowed error. Looking through several Stack Overflow questions, I have managed to narrow it down to two options (processData, contentType) in the Ajax Call below.

My issue is, If I remove both of these I then receive an Illegal Invocation error on the new Formdata($this). So, how would I submit a file upload whilst still keeping it an Ajax Call?

The Ajax Call

// Submit all forms

        $.each(forms, function(form){
            formData = new FormData(form);

            $.ajax({
                type: "POST",
                processData: false,
                contentType: false,
                url: $(this).attr('action'),
                data: formData,
                success: function(data){
                    console.log('Form submitted');
                },
                error: function(x, h, r){
                    console.log(x, h, r);
                }
            })
        });

The route function that the forms are targetting

public function update(Request $request, $id)
{
    // Save clinic initially
    $clinic = Clinic::find($id);
    $clinic->update($request->all());

    // If image is present, save it and update it in the database table
    if ($request->file('clinic_logo')) {
        $file = $request->file('clinic_logo');
        $fileExtension = $file->getClientOriginalExtension();
        $filePath = '/img/profile_images/' . $request->get('clinic_name') . "." . $fileExtension;

        // Save Image
        $file->move(
            base_path() . '/public/img/profile_images/', $request->get('clinic_name') . "." . $fileExtension
        );

        // Update database table
        $clinic->logo = $filePath;
        $clinic->save();
    }

    $data = [
        'clinic' => $clinic,
        'categories' => Category::where('approved', 1)->pluck('name', 'id')
    ];

    $request->session()->flash('alert-success', 'Clinic has been successfully edited.');

    return redirect()->back();
}

Screenshot of my Chrome Console with Options

Screenshot of my Chrome Console without options

Update 1

The actual routing works fine. If I remove both of those Ajax options, the forms post and the data updates correctly, just without the file upload. If I use a regular submit button in the form, everything works fine - including upload data. Route is a resource controller as below;

Route::resource('clinics', 'ClinicController');

Update 2

So now at least, I know why i'm getting the 405 method not allowed errors. Setting processData: false screws up the request data resulting in Laravel not understanding both the csrf_token and the _method field - resulting in Method not allowed. Still not sure how to fix this, just thought the extra info might help.

Update 3

Routes list, as requested.

|        | POST      | clinics                           | clinics.store         | App\Http\Controllers\ClinicController@store                            | web          |
|        | GET|HEAD  | clinics                           | clinics.index         | App\Http\Controllers\ClinicController@index                            | web          |
|        | PUT       | clinics/approve/{id}              | clinics.approve       | App\Http\Controllers\ClinicController@approve                          | web          |
|        | GET|HEAD  | clinics/create                    | clinics.create        | App\Http\Controllers\ClinicController@create                           | web          |
|        | GET|HEAD  | clinics/request                   |                       | App\Http\Controllers\ClinicController@request                          | web          |
|        | PUT|PATCH | clinics/{clinic}                  | clinics.update        | App\Http\Controllers\ClinicController@update                           | web          |
|        | GET|HEAD  | clinics/{clinic}                  | clinics.show          | App\Http\Controllers\ClinicController@show                             | web          |
|        | DELETE    | clinics/{clinic}                  | clinics.destroy       | App\Http\Controllers\ClinicController@destroy                          | web          |
|        | GET|HEAD  | clinics/{clinic}/edit             | clinics.edit          | App\Http\Controllers\ClinicController@edit                             | web          |

The forms are pretty big, but they're built using the form model binding pattern found here.

{!! Form::model($clinic, ['route' => ['clinics.update', $clinic], 'method' => 'PUT', 'files' => true, 'class' => 'multi-part-form']) !!}

Body:
When dealing with ajax with attachment. Implying the FormData() function in your javascript will not easily bind your file attachments. you need to separately bind your attachments into something like this.

formData = new FormData(form);
formData.append('image', $('input[type=file]')[0].files[0]);

i hope this will help you


问:
How do I do a raw query using Nest with object initializer syntax?
I am trying to do a search in ElasticSearch using Nest.  I want to use the object initializer syntax because I need to build the parts of the search dynamically.  I have figured out how to build much of the request, but am not clear how I would initialize a Raw Query.  The OIS doesn't seem to have QueryRaw as a parameter to the request.

Code that I have now:

```<code>var searchResults = client.Search<dynamic>(s => s
    .Index("myIndex"),
    .Type("myType),
    .Aggregations(a => a
        .DateHistogram("my_date_histogram", h => h
            .Field("DateField")
            .Interval("day")
         )
     )
     .QueryRaw(queryText)
)
</code>```

Code that I am trying to create:

```<code>var request = new SearchRequest<dynamic>
{
    Index = "MyIndex",
    Type = "MyType",
    QueryRaw = <doesn't exist>
};
</code>```

答:
Here's how to do raw queries using the new object structure:</p>

```<code>var response = client.Search<dynamic>(s => s
    .Query(qry => qry
        .Raw(yourRawQueryStringHere)
    )
);
</code>```

Body:
I am trying to do a search in ElasticSearch using Nest.  I want to use the object initializer syntax because I need to build the parts of the search dynamically.  I have figured out how to build much of the request, but am not clear how I would initialize a Raw Query.  The OIS doesn't seem to have QueryRaw as a parameter to the request.

Code that I have now:

var searchResults = client.Search<dynamic>(s => s
    .Index("myIndex"),
    .Type("myType),
    .Aggregations(a => a
        .DateHistogram("my_date_histogram", h => h
            .Field("DateField")
            .Interval("day")
         )
     )
     .QueryRaw(queryText)
)

Code that I am trying to create:

var request = new SearchRequest<dynamic>
{
    Index = "MyIndex",
    Type = "MyType",
    QueryRaw = <doesn't exist>
};

Body:
Here's how to do raw queries using the new object structure:

var response = client.Search<dynamic>(s => s
    .Query(qry => qry
        .Raw(yourRawQueryStringHere)
    )
);


问:
Move the PDF's from folders to a "not to be sent folder" in SSIS
I have about a dozen folders with up to 2500 PDF's. I need to move out 163 of the PDF's from t-SQL statement into a "not to be sent" folder in SSIS.. I already have the for each loop container and file system task.. How can I only search/select the files from my T-SQL statement to be moved?

Note: I already have the filenames that need to be moved in my T-SQL statement

答:
In your foreach loop container, which I assume is enumerating through the files, put a script task in front of your file system task.

The script task will check the current file name against your T-SQL results, either by running the query, or checking it against a variable that contains the results.

Then it will set a boolean variable to either true or false if the file should be moved, and in the precedence constraint leading to the file system task, you check the value of the boolean variable.


问:
Call Jssor Slider Transition during onclick event
I am new to this jssor slider animation.I am trying to update the jssor slider transition from one effect to other during button click. Ex. if the slider transition effect is fade-in , then after button click it should be fade-out.

I have tried few options like SetCaptionTransitions(), setSlideshowTransitions(), changing the slider options. but i did not work out. I need help on this.

Regards,
Neji

答:
```<code>jssor_slider1.$SetSlideshowTransitions([{ $Duration: 800, x: 0.3, $During: { $Left: [0.3, 0.7] }, $Easing: { $Left: $Jease$.$InCubic, $Opacity: $Jease$.$Linear }, $Opacity: 2 }]]);
</code>```

on button click

```<code>jssor_slider1.$SetSlideshowTransitions([{ $Duration: 800, x: 0.3, $SlideOut: true, $Easing: { $Left: $Jease$.$InCubic, $Opacity: $Jease$.$Linear }, $Opacity: 2 }]]);
</code>```

See example here
https://www.jssor.com/slideshow/x-fade.html

view-source:https://www.jssor.com/slideshow/x-fade.html

Body:
jssor_slider1.$SetSlideshowTransitions([{ $Duration: 800, x: 0.3, $During: { $Left: [0.3, 0.7] }, $Easing: { $Left: $Jease$.$InCubic, $Opacity: $Jease$.$Linear }, $Opacity: 2 }]]);

on button click

jssor_slider1.$SetSlideshowTransitions([{ $Duration: 800, x: 0.3, $SlideOut: true, $Easing: { $Left: $Jease$.$InCubic, $Opacity: $Jease$.$Linear }, $Opacity: 2 }]]);

See example here
https://www.jssor.com/slideshow/x-fade.html

view-source:https://www.jssor.com/slideshow/x-fade.html


问:
List operations using Angular 5
I'm making a simple mean stack app with Angular 5.
I know my code is not that performant and don't use best practices.
This code is my Typescript file for a product list. I only want my products to show where the field 'user' in the collection products is equal to the loggedinUser.

At the moment it's showing all my products no matter which user is logged in. I don't work with models or Mongoose.

The for loop doesn't work. It's says that 'this.products' is empty.
Can someone explain to me why it is empty and how I can solve this issue?

```<code>import { Component, OnInit } from '@angular/core';

// Import the DataService
import { DataService } from '../../data.service';
import { UserService } from '../../user.service';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
  products: Array<any>;
  productsCU : Array<any>;
  ngOnInit() {
  }

  constructor(private _dataService: DataService , private userService: UserService) {
        this._dataService.getInventory()
        .subscribe(res => this.products = res);

         for(var i = 0;i < this.products.length;i++){
                    if(this.products[i].user== userService.getNameUserLoggedIn()){
                        this.productsCU.push(this.products[i]);
                    }
                }

  }
</code>```

答:
Try this, if there is a data problem with the console.log then its to do with ur services getInventoy() function and where ever that gets the data from.

```<code>this._dataService.getInventory().subscribe((res) => {
   this.products = res;
   console.log(this.products);

   for()...

});
</code>```

I don't reccomend the approach you are doing here to get ALL products then filter by ID. As you've mentioned its not "performant". You should query that specifically in your backend to get products where user id is "123".

Having said that a array.filter seems appropriate use case here instead of a long winded for loop.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

```<code>let userProducts = this.products.filter(p => p.user == userService.getNameUserLoggedIn())
</code>```

where "p" is each product within this.products Array

Title: List operations using Angular 5

Body:
I'm making a simple mean stack app with Angular 5.
I know my code is not that performant and don't use best practices.
This code is my Typescript file for a product list. I only want my products to show where the field 'user' in the collection products is equal to the loggedinUser.

At the moment it's showing all my products no matter which user is logged in. I don't work with models or Mongoose.

The for loop doesn't work. It's says that 'this.products' is empty.
Can someone explain to me why it is empty and how I can solve this issue?

import { Component, OnInit } from '@angular/core';

// Import the DataService
import { DataService } from '../../data.service';
import { UserService } from '../../user.service';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
  products: Array<any>;
  productsCU : Array<any>;
  ngOnInit() {
  }

  constructor(private _dataService: DataService , private userService: UserService) {
        this._dataService.getInventory()
        .subscribe(res => this.products = res);

         for(var i = 0;i < this.products.length;i++){
                    if(this.products[i].user== userService.getNameUserLoggedIn()){
                        this.productsCU.push(this.products[i]);
                    }
                }

  }

Body:
Try this, if there is a data problem with the console.log then its to do with ur services getInventoy() function and where ever that gets the data from.

this._dataService.getInventory().subscribe((res) => {
   this.products = res;
   console.log(this.products);

   for()...

});

I don't reccomend the approach you are doing here to get ALL products then filter by ID. As you've mentioned its not "performant". You should query that specifically in your backend to get products where user id is "123".

Having said that a array.filter seems appropriate use case here instead of a long winded for loop.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

let userProducts = this.products.filter(p => p.user == userService.getNameUserLoggedIn())

where "p" is each product within this.products Array


问:
Install Docker on Windows Server 2008
How does one install docker for Windows Server 2008?

I only see support for Windows Server 2016:
https://www.docker.com/docker-windows-server

答:
Docker for Windows https://www.docker.com/docker-windows only works on Windows 10 Pro/2016.

For all other windows versions you must use Docker Toolbox
 https://docs.docker.com/toolbox/toolbox_install_windows/. A subtle but important difference.

Docker Toolbox comes with the ominous warning:

Legacy desktop solution. Docker Toolbox is for older Mac and Windows systems that do not meet the requirements of Docker for Mac
  and Docker for Windows. We recommend updating to the newer
  applications, if possible.

So I guess this is not getting maintained anymore and may disappear.

Title: Install Docker on Windows Server 2008


问:
Fastest way to subtract pointer array by a constant
I have a very large array of type (short*). How do I subtract all values by a constant in the fastest manner? </p>

答:
If you don't need to recalculate the actual values, you can calculate it ad hoc on usage:

```<code>#include <iostream>
using namespace std;

struct OffsetShort {
    short value;
    static short offset;
    operator short() const { return value - offset; }
};
short OffsetShort::offset = 0;
int main() {
    OffsetShort *vals[] = {new OffsetShort{1},new OffsetShort{2},new OffsetShort{3}};
    for (auto f : vals) {
        cout << *f;
    }
    OffsetShort::offset = 10;
    for (auto f : vals) {
        cout << *f;
    }
    return 0;
}
</code>```

this prints

```<code>123
-9-8-7
</code>```

Body:
If you don't need to recalculate the actual values, you can calculate it ad hoc on usage:

#include <iostream>
using namespace std;

struct OffsetShort {
    short value;
    static short offset;
    operator short() const { return value - offset; }
};
short OffsetShort::offset = 0;
int main() {
    OffsetShort *vals[] = {new OffsetShort{1},new OffsetShort{2},new OffsetShort{3}};
    for (auto f : vals) {
        cout << *f;
    }
    OffsetShort::offset = 10;
    for (auto f : vals) {
        cout << *f;
    }
    return 0;
}

this prints

123
-9-8-7


问:
How to define own WebElement in JDI test framework
I need to define own UI WebElement in JDI test automation framework. For example I need the following elements:

table with Sortable columns

table with pagination

Dropdown with items filtering

How to define them using JDI style and approach?

答:
See examples here

https://github.com/epam/JDI/tree/master/Java/Tests/jdi-uitest-tutorialtests/src/main/java/com/epam/jdi/site/epam/CustomElements

Generally you just extends existing element e.g. dropdown and add your actions or override actions that have new behavior
If you have more details on it. Fill free to ask


问:
grunt auto insert your javascript files
I am just getting to grips with usemin and wiredep. I have this in my index.html file:

```<code><!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<!-- build:css(.) styles/vendor.css -->
<!-- bower:css -->
<!-- endbower -->
<!-- build:css(.tmp) styles/core.css -->
<link rel="stylesheet" href="styles/core.css">
<!-- endbuild -->
</code>```

If I run grunt build, the index.html is modified to this:

```<code><!-- build:css(.) styles/vendor.css -->
<!-- bower:css -->
<link rel="stylesheet" href="bower_components/angular-loading-bar/build/loading-bar.css" />
<link rel="stylesheet" href="bower_components/angular-ui-select/dist/select.css" />
<link rel="stylesheet" href="bower_components/ng-notify/src/styles/ng-notify.css" />
<link rel="stylesheet" href="bower_components/components-font-awesome/css/font-awesome.css" />
<!-- endbower -->
<!-- endbuild -->
<!-- build:css(.tmp) styles/core.css -->
<link rel="stylesheet" href="styles/core.css">
<!-- endbuild -->
</code>```

This is great, but it only happens for the bower:css files (which I believe is done with wiredep. Further down my page I have similar to JavaScript files and that works also.
I would like to do it for my own JavaScript files. Currently I have about 100 and i have manually put the into my src/index.html. When my application is built, usemin replaces my scripts with the concatinated, uglified version which is great. But when I build, I would like the src/index.html to get all the scripts from by src/app directory and inject them into my html file.

Can this be done?

答:
I managed to figure this out using grunt-injector.
I configured my Gruntfile to use grunt-injector like this:

```<code>// Automatically inject my components into index.html
injector: {
  options: {
    template: '<%= yeoman.app %>/index.html'
  },
  html: {
    options: {
      transform: function (filePath) {
          return '<script type="text/ng-template" src="' + filePath.replace('/src/', '') + '"></script>';
      }
    },
    files: {
      '<%= yeoman.app %>/index.html': [
        '<%= yeoman.app %>/app/**/*.html'
      ]
    }
  },
  scripts: {
    options: {
      transform: function (filePath) {
          return '<script src="' + filePath.replace('/src/', '') + '"></script>';
      }
    },
    files: {
      '<%= yeoman.app %>/index.html': [
        '<%= yeoman.app %>/app/**/*.module.js',
        '<%= yeoman.app %>/app/**/*.js'
      ]
    }
  },
  styles: {
    options: {
      transform: function (filePath) {
          var media = filePath.indexOf('print') > -1 ? 'print' : 'screen';
          return '<link rel="stylesheet" media="' + media + '" href="' + filePath.replace('/.tmp/', '') + '" />';
      }
    },
    files: {
      '<%= yeoman.app %>/index.html': [
        '.tmp/styles/**/*.css'
      ]
    }
  }
},
</code>```

And then in my index.html, I just put the injector comments like this:

```<code>  <!-- injector:css -->
  <!-- endinjector -->
</code>```

Which were converted to this:

```<code>  <!-- injector:css -->
  <link rel="stylesheet" media="screen" href="styles/core.css" />
  <link rel="stylesheet" media="print" href="styles/print.css" />
  <!-- endinjector -->
</code>```

And that was it.

Title: grunt auto insert your javascript files

Body:
I am just getting to grips with usemin and wiredep. I have this in my index.html file:

<link rel="stylesheet" href="styles/core.css">

If I run grunt build, the index.html is modified to this:

<link rel="stylesheet" href="bower_components/angular-loading-bar/build/loading-bar.css" />
<link rel="stylesheet" href="bower_components/angular-ui-select/dist/select.css" />
<link rel="stylesheet" href="bower_components/ng-notify/src/styles/ng-notify.css" />
<link rel="stylesheet" href="bower_components/components-font-awesome/css/font-awesome.css" />

<link rel="stylesheet" href="styles/core.css">

This is great, but it only happens for the bower:css files (which I believe is done with wiredep. Further down my page I have similar to JavaScript files and that works also.
I would like to do it for my own JavaScript files. Currently I have about 100 and i have manually put the into my src/index.html. When my application is built, usemin replaces my scripts with the concatinated, uglified version which is great. But when I build, I would like the src/index.html to get all the scripts from by src/app directory and inject them into my html file.

Can this be done?

Body:
I managed to figure this out using grunt-injector.
I configured my Gruntfile to use grunt-injector like this:

// Automatically inject my components into index.html
injector: {
  options: {
    template: '<%= yeoman.app %>/index.html'
  },
  html: {
    options: {
      transform: function (filePath) {
          return '<script type="text/ng-template" src="' + filePath.replace('/src/', '') + '"></script>';
      }
    },
    files: {
      '<%= yeoman.app %>/index.html': [
        '<%= yeoman.app %>/app/**/*.html'
      ]
    }
  },
  scripts: {
    options: {
      transform: function (filePath) {
          return '<script src="' + filePath.replace('/src/', '') + '"></script>';
      }
    },
    files: {
      '<%= yeoman.app %>/index.html': [
        '<%= yeoman.app %>/app/**/*.module.js',
        '<%= yeoman.app %>/app/**/*.js'
      ]
    }
  },
  styles: {
    options: {
      transform: function (filePath) {
          var media = filePath.indexOf('print') > -1 ? 'print' : 'screen';
          return '<link rel="stylesheet" media="' + media + '" href="' + filePath.replace('/.tmp/', '') + '" />';
      }
    },
    files: {
      '<%= yeoman.app %>/index.html': [
        '.tmp/styles/**/*.css'
      ]
    }
  }
},

And then in my index.html, I just put the injector comments like this:

  <!-- injector:css -->
  <!-- endinjector -->

Which were converted to this:

  <!-- injector:css -->
  <link rel="stylesheet" media="screen" href="styles/core.css" />
  <link rel="stylesheet" media="print" href="styles/print.css" />
  <!-- endinjector -->

And that was it.


问:
Error 500 internal server error when posting long forms content
I created a long form with multiple fields that post the typed data to a Mariadb database.

The types are all set to TEXT as the field will contain long text.

The max_allowed_packet = 1073741824

The net_buffer_length = 1048576

The PHP post_max_size = 500M

The memory_limit = 550M

All this seems suficiant for very long text posting to database.
But apparently not, as it gives me a 500 error when I exceed 99100 characters :/ and works fine when I keep the posted text under that amount of characters.
What am I doing wrong ?

The error log shows : Code:500
Message:Code:500 Message: POST /login/resident/updateresident/7 HTTP/1.1

Thank you in advance!

答:
Thanks for the reply !
Actually none of that worked....went through all php and apache and all the conf files that controls the upload ans post max .....
A brilliant guy sent me this link :
 https://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-20.html
It was a Mysql 5.6 bug !!!
Just updated it to 5.7 and pufff !! It worked !
GOD ! lost 3 days of my life because of this bug !</p>


问:
multiple recyclerviews?
I want to make my homepage with two row  with recyclerview
with data of books and  the events which are display independent of each other how can i accomplish it I want to add event to the my code how can i do it?

MoviesAdapter.java

```<code>public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

private List<Movie> moviesList;
public Context context;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title;
    public ImageView thumbnail;

    public MyViewHolder(View view) {
        super(view);
        title = (TextView) view.findViewById(R.id.title);
        thumbnail = (ImageView) view.findViewById(R.id.book);

    }
}//End of MyViewHolder class

public MoviesAdapter(List<Movie> moviesList) {
    this.moviesList = moviesList;
}

//display different items in the data set
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.movie_list_row, parent, false);

    return new MyViewHolder(itemView);
}

//display data at specified location
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

    holder.title.setText(moviesList.get(position).getTitle());

    holder.thumbnail.setImageResource(moviesList.get(position).getImage());
}

@Override
public int getItemCount() {
    return moviesList.size();
}
}
</code>```

I want to make my page like this

答: It should be fine to use a LinearLayout with 3 RecyclerViews in it and create an Adapter for each of them. Nested RecyclerViews would only make sense if you had a lot of categories.</p>

Title: multiple recyclerviews?

Body:
I want to make my homepage with two row  with recyclerview
with data of books and  the events which are display independent of each other how can i accomplish it I want to add event to the my code how can i do it?

MoviesAdapter.java

public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

private List<Movie> moviesList;
public Context context;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title;
    public ImageView thumbnail;

    public MyViewHolder(View view) {
        super(view);
        title = (TextView) view.findViewById(R.id.title);
        thumbnail = (ImageView) view.findViewById(R.id.book);

    }
}//End of MyViewHolder class

public MoviesAdapter(List<Movie> moviesList) {
    this.moviesList = moviesList;
}

//display different items in the data set
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.movie_list_row, parent, false);

    return new MyViewHolder(itemView);
}

//display data at specified location
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

    holder.title.setText(moviesList.get(position).getTitle());

    holder.thumbnail.setImageResource(moviesList.get(position).getImage());
}

@Override
public int getItemCount() {
    return moviesList.size();
}
}

I want to make my page like this


问:
How to make good looking custom ui in mobile and tablet devices?
I'm looking for an intro into designing and making a custom and dynamic UI on mobile specific platforms. As I understand Nokia(Qt), Android, and iOS all use OpenGL ES (2.0?). I haven't looked into Windows phone 7 yet so not sure what that uses. So I think OpenGL would be a pretty good place to start. While OpenGL is mostly about 3D, I'm also open to 2d ways of creating dynamic UI.

I've never really been big on designing interfaces or coming up with cool concepts but now I have an idea for a mobile app that really needs a good looking user-interface. It's sort of a half app, half game type of thing. It really targets people in the gaming community who I think are used to a bit more polish and advanced UI. I could still probably get away with a simple UI(simple not being a bad thing) but I think I at least should learn some design techniques for future reference.

Of course I realise that excessive eye candy which hurts usability, like bloated graphics that slow down the mobile, are of no use at all. I'm trying to make a sleek UI that while looking good allows the user to interact well with the app effectively.

Any suggestions, resources, experience you can share would be most helpful.

EDIT: While I'm looking for ways to use 3D graphics, I'm more concerned with how to come up with a sleek UI in a mobile. I come from a mostly web developer background, with some experience in Photoshop(CSS is the furthest I've gone in designing). I have never really had to design a dynamic interface that reacted to touch and moved all around the screen with some laws of physics attached. There are lots of such effects, such as the carousal effect, which gives the user an enhanced experience. I have no idea how to incorporate these effects into a mobile device. For example, one of the things I need this app to do is take a glassy circular object(a button) that moves around, then turn it into a sort of convex glass lens so it's sort of zooming in on the image underneath to make it look like its actually a magnifying glass. I looked around and this effect is created by a "grid warp" or a "mesh warp". Suffice it to say I have no idea how to do it.

答:
I have been searching since yesterday and thought I'd add some links for anyone interested.
Although I'm dividing them up by the platform the articles refer to, with some elbow grease the ideas should be cross-platform compatible.

Qt

Carousal animation in Qt

Shadow effect Qt

Qt Kinetic Scrolling describes kinetic scrolling algorithm in Qt(self descriptive really)

Qt OpenGL Nehe tutorials converted to the Qt environment

Iphone

OpenGL from the ground up - expansive list

Flow Cover tutorial.

Android

Android 3d Tutorial

Another Android OpenGL tutorial

Yet another Android OpenGl ES tutorial, seems people have gone open-source mad.

Custom UI on Android

One finger zoom tutorial at Sony Ericsson Developer World

3D list at Sony Ericsson Developer World

OpenGl/ES

OpenGl tutorials at NeHe, there are tons, I read through the first one (on light) and it was really informative.

TheRedBook intro to OpenGl

Books

Books list at Design4Mobile, these do not cover the technical side rather covers the things to keep in mind when designing mobiles, I think the O'Rielly one should be pretty good.

Inspiration

10 beautifully designed Iphone Apps - for a touch of inspiration

All rounder

Mobile TutsPlus sort of a gathering of tutorials for android and iPhone

That's I found in the last four or five hours, as I find more I'll add it on. I've also made this a community Wiki so others can correct any mistakes I've made here, or to add anything they feel relevant.


问:
Why use dotenv library instead of parsing ini file?
Within PHP, *.ini files can be read by using parse_ini_file(). However, various frameworks (Laravel included) opt to, instead, bring in a separate library to parse an environment file.

What is the reasoning behind using this "dotenv" solution instead of ini files and the built-in PHP function?

答:
It worked for me using Laravel .env</p>

```<code><?php
var_dump(parse_ini_file('.env', false, INI_SCANNER_RAW));
</code>```

Body:
It worked for me using Laravel .env

<?php
var_dump(parse_ini_file('.env', false, INI_SCANNER_RAW));


问:
Regex match alphabetic/numeric that is not x
Assume I want to extract all strings starting in either ftp or ftpk (example made up).

I currently have a solution:

Get all the strings starting with ftp but not those starting in
  ftpx or ftpc.

I wonder how I can make it more general (because right now I'm listing the exceptions which can become tedious), something like:

Get all the strings starting with ftp but not those starting in
  ftpX where X is any alphabetic/numeric that is not k.

```<code># Data:
vec <- c("ftp:ladpmxqgvt", "ftpx:xfiwyoloqu", "ftpk:yol.qdsrehn",
         "ftpc:krjqdzsuhb", "ftpk:yolo.taxukj", "ftp:qvxarpkjid",
         "ebutlngqkr", "yolx.vhznja")

# Current solution (desired output)
grep("^ftp[^xc]", vec, value = TRUE)
"ftp:ladpmxqgvt"   "ftpk:yol.qdsrehn" "ftpk:yolo.taxukj" "ftp:qvxarpkjid"
</code>```

答:
I think this solution most closely mimics the sentence:

Get all the strings starting with ftp but not those starting in ftpX where X is any alphabetic/numeric that is not k.

```<code>grep("ftp(?!k)[[:alnum:]](*SKIP)(*FAIL)|ftp", vec, value = TRUE, perl = TRUE)
</code>```

or

```<code>grep("ftp(?!(?!k)[[:alnum:]])", vec, value = TRUE, perl = TRUE)
</code>```

Result:

```<code>[1] "ftp:ladpmxqgvt"   "ftpk:yol.qdsrehn" "ftpk:yolo.taxukj" "ftp:qvxarpkjid"
</code>```

Note:

The first solution uses the (*SKIP)(*FAIL) trick to avoid matching particular patterns. In this case, I am using it to avoid matching ftp followed by an alphanumeric character except k, and matching any ftp that was not avoided.

The second solution is similar, but uses negative lookahead. (?!k)[[:alnum:]] matches all alphanumerics except k, while ftp(?!(?!k)[[:alnum:]]) matches ftp not immediately followed by any alphanumerics except k.

The advantage of these two solutions is that one can add to the things to avoid. Just add them to (?!k)[[:alnum:]] or (?!(?!k)[[:alnum:]]).

ContentLicense: CC BY-SA 4.0

Body:
Assume I want to extract all strings starting in either ftp or ftpk (example made up).

I currently have a solution:

Get all the strings starting with ftp but not those starting in
  ftpx or ftpc.

I wonder how I can make it more general (because right now I'm listing the exceptions which can become tedious), something like:

Get all the strings starting with ftp but not those starting in
  ftpX where X is any alphabetic/numeric that is not k.

# Data:
vec <- c("ftp:ladpmxqgvt", "ftpx:xfiwyoloqu", "ftpk:yol.qdsrehn",
         "ftpc:krjqdzsuhb", "ftpk:yolo.taxukj", "ftp:qvxarpkjid",
         "ebutlngqkr", "yolx.vhznja")

# Current solution (desired output)
grep("^ftp[^xc]", vec, value = TRUE)
"ftp:ladpmxqgvt"   "ftpk:yol.qdsrehn" "ftpk:yolo.taxukj" "ftp:qvxarpkjid"

Body:
I think this solution most closely mimics the sentence:

Get all the strings starting with ftp but not those starting in ftpX where X is any alphabetic/numeric that is not k.

grep("ftp(?!k)[[:alnum:]](*SKIP)(*FAIL)|ftp", vec, value = TRUE, perl = TRUE)

or

grep("ftp(?!(?!k)[[:alnum:]])", vec, value = TRUE, perl = TRUE)

Result:

[1] "ftp:ladpmxqgvt"   "ftpk:yol.qdsrehn" "ftpk:yolo.taxukj" "ftp:qvxarpkjid"

Note:

The first solution uses the (*SKIP)(*FAIL) trick to avoid matching particular patterns. In this case, I am using it to avoid matching ftp followed by an alphanumeric character except k, and matching any ftp that was not avoided.

The second solution is similar, but uses negative lookahead. (?!k)[[:alnum:]] matches all alphanumerics except k, while ftp(?!(?!k)[[:alnum:]]) matches ftp not immediately followed by any alphanumerics except k.

The advantage of these two solutions is that one can add to the things to avoid. Just add them to (?!k)[[:alnum:]] or (?!(?!k)[[:alnum:]]).


问:
Applying multiple functions (Mean., STD etc ) across columns in Python
I have this data of 4 columns and 8 rows...

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

       time  A  B  C
    0     1  2  3  7
    1     2  8  6  8
    2     3  2  3  7
    3     4  4  6  8
    4     5  2  3  7
    5     6  1  6  8
    6     7  8  3  7
    7     8  9  6  8
</code>```

I want to take mean and STD of column A and C, across columns not rows. e.g Mean and STD of 2 and 7 is "" (mean) and "3.535533906" (STD) respectively as following.

I want my result to look like this...

```<code>      Mean  STD
    0 4.7   3.535533906
    1 8     0
    2 .     .
    3 .     .
    . .     .
    . .     .
</code>```

However, when I try to do

df= df.loc[(df.time>=2) & (df.time<=7),['A','C']],(['mean','std'])

I get the following error...

AttributeError: 'DataFrame' object has no attribute 'time'

I've tried to find solutions by doing this as well but in vain :

```<code>df= df.loc[(df.time>=2) & (df.time<=7),['A','C']].agg(['mean','std'])
</code>```

but it gives me result of all rows mean and STD.

```<code>                 A         C
    mean  4.166667  7.500000
    std   3.125167  0.547723
</code>```

How do I fix it?

Body:
I have this data of 4 columns and 8 rows...

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

       time  A  B  C
    0     1  2  3  7
    1     2  8  6  8
    2     3  2  3  7
    3     4  4  6  8
    4     5  2  3  7
    5     6  1  6  8
    6     7  8  3  7
    7     8  9  6  8

I want to take mean and STD of column A and C, across columns not rows. e.g Mean and STD of 2 and 7 is "" (mean) and "3.535533906" (STD) respectively as following.

I want my result to look like this...

      Mean  STD
    0 4.7   3.535533906
    1 8     0
    2 .     .
    3 .     .
    . .     .
    . .     .

However, when I try to do

df= df.loc[(df.time>=2) & (df.time<=7),['A','C']],(['mean','std'])

I get the following error...

AttributeError: 'DataFrame' object has no attribute 'time'

I've tried to find solutions by doing this as well but in vain :

df= df.loc[(df.time>=2) & (df.time<=7),['A','C']].agg(['mean','std'])

but it gives me result of all rows mean and STD.

                 A         C
    mean  4.166667  7.500000
    std   3.125167  0.547723

How do I fix it?

Body:
You can use describe

df[['A','C']].T.describe().T[['mean','std']]
Out[865]:
   mean       std
0   4.5  3.535534
1   8.0  0.000000
2   4.5  3.535534
3   6.0  2.828427
4   4.5  3.535534
5   4.5  4.949747
6   7.5  0.707107
7   8.5  0.707107


问:
Angular 5 percent pipe digitInfo not working as expected
If I do this in an Angular 5 template:

```<code>{{0.7 | percent:'1.2-5'}}
</code>```

I get this as expected: 70.00%

However, when I do this:

```<code>{{0.07 | percent:'1.2-5'}}
</code>```

I get 7.00000% instead of what the expected 7.00%

Am I just doing something wrong or is this a bug in Angular?

答:
Seems like a bug with DecimalPipe because PercentPipe uses it for formatting. Simple removal of maxFractionDigits which is the maximum number of digits after fraction (default is 3) will get you the desired result:

```<code>{{0.7 | percent:'1.2'}} --> 70.00%
{{0.07 | percent:'1.2'}} --> 7.00%
</code>```

Body:
If I do this in an Angular 5 template:

{{0.7 | percent:'1.2-5'}}

I get this as expected: 70.00%

However, when I do this:

{{0.07 | percent:'1.2-5'}}

I get 7.00000% instead of what the expected 7.00%

Am I just doing something wrong or is this a bug in Angular?

Body:
Seems like a bug with DecimalPipe because PercentPipe uses it for formatting. Simple removal of maxFractionDigits which is the maximum number of digits after fraction (default is 3) will get you the desired result:

{{0.7 | percent:'1.2'}} --> 70.00%
{{0.07 | percent:'1.2'}} --> 7.00%


问:
Setting extraFields in rest api yii2
```<code>public function fields()
{
    return [
        'field' => 'field',
    ];
}

public function extraFields()
{
    return [
        'users',
    ];
}
</code>```

return:

```<code>{ "field": "field", "users": { "id": 1, "name": "user" } }
</code>```

how to exclude id?

```<code>public function extraFields()
{
    return [
        'users' => function($model){
            return [
                'name' => $model->users->name,
            ];
        }
    ];
}
</code>```

return:

```<code>{ "field": "field", "users": { "name": null } }
</code>```

how to fill in the name field correctly or how to customize field output filtering?

答:
Option can be overwrite field() method in User model:</p>

```<code>public function fields()
{
    $fields = parent::fields();
    if ($something) {
        unset($fields['id']);
    }

    return $fields;
}
</code>```

Title: Setting extraFields in rest api yii2

Body:
public function fields()
{
    return [
        'field' => 'field',
    ];
}

public function extraFields()
{
    return [
        'users',
    ];
}

return:

{ "field": "field", "users": { "id": 1, "name": "user" } }

how to exclude id?

public function extraFields()
{
    return [
        'users' => function($model){
            return [
                'name' => $model->users->name,
            ];
        }
    ];
}

return:

{ "field": "field", "users": { "name": null } }

how to fill in the name field correctly or how to customize field output filtering?

Body:
Option can be overwrite field() method in User model:

public function fields()
{
    $fields = parent::fields();
    if ($something) {
        unset($fields['id']);
    }

    return $fields;
}


问:
Get in a Json child with a String
I wan't to get the value of a String called symbolString. I don't know how to do this. This is what i got so far. I tried first to get in the Data child and then go to the symbolString to get the ImageUrl Value. It doesn't seem to work. Please help!

```<code>final let urlString = "https://www.cryptocompare.com/api/data/coinlist/"

        func downloadJsonWithURL() {
            let url = NSURL(string: urlString)

            URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
                if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                    if let DataArray = jsonObj!.value(forKey: "Data") as? NSArray {
                        print(DataArray)
                        for Data in DataArray{
                            if let DataDict = Data as? NSDictionary {
                                if let nameURL = DataDict.value(forKey: "\(self.symbolString)") as? NSDictionary {
                                    if let name = nameURL.value(forKey: "ImageUrl") {
                                        self.imageString.append(name as! String)
                                        print(self.imageString)
                                    }
                                }
                            }
                        }
                    }
                }
            }).resume()
        }
</code>```

答:
You can try with the below code. Its working for me.</p>

```<code> func downloadJsonWithURL() {
    let url = "https://www.cryptocompare.com/api/data/coinlist/"
    var urlRequest = URLRequest(url: URL(string: url)!)
    let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in

        guard let unwrappedDAta = data else {
            print("Error unwrapping data")
            return
        }

        do {
            let responseJSON = try JSONSerialization.jsonObject(with: unwrappedDAta, options: []) as? NSDictionary

            if let dataDict = responseJSON!["Data"] as? NSDictionary {
                for (key, _) in dataDict {
                    if let keyDict = dataDict[key] as? NSDictionary {
                        if let imageURL = keyDict["ImageUrl"] as? String {
                            self.imageString.append(imageURL)
                        }
                        print(self.imageString)
                    }
                }
            }
        } catch {
            print("Could not get API data. \(error))")
        }
    }
    task.resume()
}
</code>```

Title: Get in a Json child with a String

Body:
I wan't to get the value of a String called symbolString. I don't know how to do this. This is what i got so far. I tried first to get in the Data child and then go to the symbolString to get the ImageUrl Value. It doesn't seem to work. Please help!

final let urlString = "https://www.cryptocompare.com/api/data/coinlist/"

        func downloadJsonWithURL() {
            let url = NSURL(string: urlString)

            URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
                if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                    if let DataArray = jsonObj!.value(forKey: "Data") as? NSArray {
                        print(DataArray)
                        for Data in DataArray{
                            if let DataDict = Data as? NSDictionary {
                                if let nameURL = DataDict.value(forKey: "\(self.symbolString)") as? NSDictionary {
                                    if let name = nameURL.value(forKey: "ImageUrl") {
                                        self.imageString.append(name as! String)
                                        print(self.imageString)
                                    }
                                }
                            }
                        }
                    }
                }
            }).resume()
        }

Body:
You can try with the below code. Its working for me.

 func downloadJsonWithURL() {
    let url = "https://www.cryptocompare.com/api/data/coinlist/"
    var urlRequest = URLRequest(url: URL(string: url)!)
    let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in

        guard let unwrappedDAta = data else {
            print("Error unwrapping data")
            return
        }

        do {
            let responseJSON = try JSONSerialization.jsonObject(with: unwrappedDAta, options: []) as? NSDictionary

            if let dataDict = responseJSON!["Data"] as? NSDictionary {
                for (key, _) in dataDict {
                    if let keyDict = dataDict[key] as? NSDictionary {
                        if let imageURL = keyDict["ImageUrl"] as? String {
                            self.imageString.append(imageURL)
                        }
                        print(self.imageString)
                    }
                }
            }
        } catch {
            print("Could not get API data. \(error))")
        }
    }
    task.resume()
}


问:
Getting started with the facebook c# SDK
This is my second post and I am going slightly mad. I have read all the posts on this forum an spent the best part of every night this week hitting my head against a brick wall. I am an experienced coder but I cannot for the life of me get my "facebook connect" to work.

What I think I want to do is;

I have a c# asp.net solution which is a webforms solution which I develop on visual studio 2010. I want a simple page which gets my information from facebook and shows me my name. The simplest of simple.

How far have I got? I have a facebook app with my "Site Domain" set to englandkorfball.co.uk. I have the "Site URL" set to http://www.englandkorfball.co.uk/test.aspx?app=1

I have downloaded and referenced the 3.5 framework SDK dlls from codeplex.

I have put on test.aspx, the simplest of code which I do no know how to show you here

Q1. Can I show you my code in an easy format? I cannot work out the formatting on the site.

it is from all the web examples involving FB.init, the meta declaration and the fb:login-button. This part works fine. I log out of facebook, click on the button and I get asked to log in. I remove the app and it asks me fine. All this is fine.

It is the server side bit which I cannot for the life of me work out. I have used

```<code>Authorizer authorizer = new CanvasAuthorizer(fbApp);
if (authorizer.IsAuthorized())
</code>```

and

```<code>Authorizer authorizer = new Authorizer(fbApp);
if (authorizer.IsAuthorized())
</code>```

and

```<code>if (fbApp.IsAuthenticated) {
</code>```

but nothing will induce a positive authenticated result.

Have I got the wrong end of the stick. How do I check if I am logged in server side?

Thanks, I have run out of ideas and patience for something which could be so good.

答:
Here is a step by step buide on how you create a Facebook Application with ASP.NET, if you follow this throughly step by step, you will have a working app in no time. You have to be sure that the web.config part is exactly what it should be, here's an explanation of it:

appId – Application ID

appSecret - Application Secret

baseDomain – Site Domain

cookieSupport –“false”

maxRetries – “2” (or the number of times you want the SDK to retry an action)

retryDelay – “1” (or how long do you want it to wait before retrying

Samples from Facebook C# SDK

ASP.NET MVC Sample

WebForms iFrame Sample

Body:
This is my second post and I am going slightly mad. I have read all the posts on this forum an spent the best part of every night this week hitting my head against a brick wall. I am an experienced coder but I cannot for the life of me get my "facebook connect" to work.

What I think I want to do is;

I have a c# asp.net solution which is a webforms solution which I develop on visual studio 2010. I want a simple page which gets my information from facebook and shows me my name. The simplest of simple.

How far have I got? I have a facebook app with my "Site Domain" set to englandkorfball.co.uk. I have the "Site URL" set to http://www.englandkorfball.co.uk/test.aspx?app=1

I have downloaded and referenced the 3.5 framework SDK dlls from codeplex.

I have put on test.aspx, the simplest of code which I do no know how to show you here

Q1. Can I show you my code in an easy format? I cannot work out the formatting on the site.

it is from all the web examples involving FB.init, the meta declaration and the fb:login-button. This part works fine. I log out of facebook, click on the button and I get asked to log in. I remove the app and it asks me fine. All this is fine.

It is the server side bit which I cannot for the life of me work out. I have used

Authorizer authorizer = new CanvasAuthorizer(fbApp);
if (authorizer.IsAuthorized())

and

Authorizer authorizer = new Authorizer(fbApp);
if (authorizer.IsAuthorized())

and

if (fbApp.IsAuthenticated) {

but nothing will induce a positive authenticated result.

Have I got the wrong end of the stick. How do I check if I am logged in server side?

Thanks, I have run out of ideas and patience for something which could be so good.


问:
JavaScript: Dynamically generated object key
```<code>const cars = [
  {
    'id': 'truck',
    'defaultCategory': 'vehicle'
  }
]

const output = []

Object.keys(cars).map((car) => {
  output.push({
      foo: cars[car].defaultCategory
  })
})

console.log(output)
</code>```

This work fine, however what I want to achieve is so that the newly crated object has structure of 'truck': 'vehicle'.

So if I replace push argument with

```<code>${cars[car].id}`: cars[car].defaultCategory
</code>```

I get SyntaxError: Unexpected template string

What am I doing wrong?

答:
You should use .map() over your cars array and not Object.keys(cars):, we don't use Object.keys() with arrays.

This is how should be your code:

```<code>var output = cars.map(function(car) {
  return {
    [car.id]: car.defaultCategory
  };
});
</code>```

var cars = [{
  'id': 'truck',
  'defaultCategory': 'vehicle'
}];

var output = cars.map(function(car) {
  return {
    [car.id]: car.defaultCategory
  };
});

console.log(output);```

Body:
const cars = [
  {
    'id': 'truck',
    'defaultCategory': 'vehicle'
  }
]

const output = []

Object.keys(cars).map((car) => {
  output.push({
      foo: cars[car].defaultCategory
  })
})

console.log(output)

This work fine, however what I want to achieve is so that the newly crated object has structure of 'truck': 'vehicle'.

So if I replace push argument with

${cars[car].id}`: cars[car].defaultCategory

I get SyntaxError: Unexpected template string

What am I doing wrong?

Body:
You should use .map() over your cars array and not Object.keys(cars):, we don't use Object.keys() with arrays.

This is how should be your code:

var output = cars.map(function(car) {
  return {
    [car.id]: car.defaultCategory
  };
});

var cars = [{
  'id': 'truck',
  'defaultCategory': 'vehicle'
}];

var output = cars.map(function(car) {
  return {
    [car.id]: car.defaultCategory
  };
});

console.log(output);


问:
start learn iphone objective-c application where from?
to all
i'm new-be in iphone sector i didn't decide to where from i start to learn and build application for iphone </p>

答: Just a quick response - here are some recommendations from someone who has been there. But (as suggested in the comment) see the longer responses here.</p>


问:
Multiple attachment with single callback_id: slack interactive component
Is it possible to have multiple menu attachment and allow users to select each menu before sending back the collated response?

```<code> return Promise.resolve({
  text: `Rate each game`,
  attachments: [
    ...games.map(game => ({
      color: "#5A352D",
      title: game,
      callback_id: "game:done",
      actions: [
        {
          name: "done",
          text: "Select a score",
          type: "select",
          value: "game:done",
          options: [
            { text: 1, value: 1 },
            { text: 2, value: 2 }
          ]
        }
      ]
    }))
  ]
});
</code>```

This images shows how it renders
But, I need to call the callback only when the user has finished scoring each game.

Perhaps, I can provide an additional button for that, but how can I handle callback for these menu actions

答: Choosing a menu option will always fire a request to your app. But you could replace the former message and recreate the menu list each time and show the remaining menus to the user until all are chosen. Technically it will be a new message each time, but by replacing the old message the user will not notice.</p>

Body:
Is it possible to have multiple menu attachment and allow users to select each menu before sending back the collated response?

 return Promise.resolve({
  text: `Rate each game`,
  attachments: [
    ...games.map(game => ({
      color: "#5A352D",
      title: game,
      callback_id: "game:done",
      actions: [
        {
          name: "done",
          text: "Select a score",
          type: "select",
          value: "game:done",
          options: [
            { text: 1, value: 1 },
            { text: 2, value: 2 }
          ]
        }
      ]
    }))
  ]
});

This images shows how it renders
But, I need to call the callback only when the user has finished scoring each game.

Perhaps, I can provide an additional button for that, but how can I handle callback for these menu actions


问:
Visual Studio Mac open open F# solution as file
After I update VS-Mac to 7.3 my F# Solution is opened as a plain text file (it is not loaded).

I create a empty solution and it load.

I could build the solution with MSBUILD from the command line.

```<code>Visual Studio Community 2017 for Mac
Version 7.3 (build 797)
Runtime:
    Mono 5.4.1.7 (2017-06/e66d9abbb27) (64-bit)
    GTK+ 2.24.23 (Raleigh theme)

    Package version: 504010007

NuGet
Versión: 4.3.1.4445

.NET Core
Runtime: /usr/local/share/dotnet/dotnet
Versión de tiempo de ejecución: 2.0.0
SDK: /usr/local/share/dotnet/sdk/2.0.0/Sdks
Versión del SDK: 2.0.0
SDK de MSBuild: /Library/Frameworks/Mono.framework/Versions/5.4.1/lib/mono/msbuild/15.0/bin/Sdks

Xamarin.Profiler
Versión: 1.6.0
Ubicación: /Applications/Xamarin Profiler.app/Contents/MacOS/Xamarin Profiler

Xamarin.Android
Versión: 8.1.0.24 (Visual Studio Community)
Android SDK: /Users/mamcx/Library/Developer/Xamarin/android-sdk-macosx
    Versiones de Android admitidas:
        7.1 (nivel de API 25)

Versión de las herramientas del SDK: 25.2.5
Versión de las herramientas de plataforma del SDK: 25.0.5
Versión de las herramientas de compilación del SDK: 25.0.3

Java SDK: /usr
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

El código EPL de Android Designer está disponible EPL:
https://github.com/xamarin/AndroidDesigner.EPL

Apple Developer Tools
Xcode 9.1 (13532)
Build 9B55

Xamarin.Mac
Version: 4.0.0.214 (Visual Studio Community)

Xamarin Inspector
Version: 1.3.2
Hash: 461f09a
Branch: 1.3-release
Build date: Tue, 03 Oct 2017 18:26:57 GMT
Client compatibility: 1

Xamarin.iOS
Version: 11.4.0.214 (Visual Studio Community)
Hash: c4240f3f
Branch: d15-5
Build date: 2017-11-08 17:28:18-0500

Build Information
Release ID: 703000797
Git revision: ff055b3ecaaeb4229434d0ca871c7d67c62f6388
Build date: 2017-11-30 14:34:51-05
Xamarin addins: 351fc12d4f2367490f8fc2a66b14690d825bb7f1
Build lane: monodevelop-lion-d15-5

Operating System
Mac OS X 10.12.6
Darwin 16.7.0 Darwin Kernel Version 16.7.0
    Wed Oct  4 00:17:00 PDT 2017
    root:xnu-3789.71.6~1/RELEASE_X86_64 x86_64

Enabled user installed addins
Internet of Things (IoT) development (Preview) 7.1
</code>```

BTW: When try to load the update for "Visual Studio Updater 1.7" it download and when try to apply I get error "No updates Found".

答: Make sure that your F# Language Binding extension is Enabled

Body:
After I update VS-Mac to 7.3 my F# Solution is opened as a plain text file (it is not loaded).

I create a empty solution and it load.

I could build the solution with MSBUILD from the command line.

Visual Studio Community 2017 for Mac
Version 7.3 (build 797)
Runtime:
    Mono 5.4.1.7 (2017-06/e66d9abbb27) (64-bit)
    GTK+ 2.24.23 (Raleigh theme)

    Package version: 504010007

NuGet
Versión: 4.3.1.4445

.NET Core
Runtime: /usr/local/share/dotnet/dotnet
Versión de tiempo de ejecución: 2.0.0
SDK: /usr/local/share/dotnet/sdk/2.0.0/Sdks
Versión del SDK: 2.0.0
SDK de MSBuild: /Library/Frameworks/Mono.framework/Versions/5.4.1/lib/mono/msbuild/15.0/bin/Sdks

Xamarin.Profiler
Versión: 1.6.0
Ubicación: /Applications/Xamarin Profiler.app/Contents/MacOS/Xamarin Profiler

Xamarin.Android
Versión: 8.1.0.24 (Visual Studio Community)
Android SDK: /Users/mamcx/Library/Developer/Xamarin/android-sdk-macosx
    Versiones de Android admitidas:
        7.1 (nivel de API 25)

Versión de las herramientas del SDK: 25.2.5
Versión de las herramientas de plataforma del SDK: 25.0.5
Versión de las herramientas de compilación del SDK: 25.0.3

Java SDK: /usr
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

El código EPL de Android Designer está disponible EPL:
https://github.com/xamarin/AndroidDesigner.EPL

Apple Developer Tools
Xcode 9.1 (13532)
Build 9B55

Xamarin.Mac
Version: 4.0.0.214 (Visual Studio Community)

Xamarin Inspector
Version: 1.3.2
Hash: 461f09a
Branch: 1.3-release
Build date: Tue, 03 Oct 2017 18:26:57 GMT
Client compatibility: 1

Xamarin.iOS
Version: 11.4.0.214 (Visual Studio Community)
Hash: c4240f3f
Branch: d15-5
Build date: 2017-11-08 17:28:18-0500

Build Information
Release ID: 703000797
Git revision: ff055b3ecaaeb4229434d0ca871c7d67c62f6388
Build date: 2017-11-30 14:34:51-05
Xamarin addins: 351fc12d4f2367490f8fc2a66b14690d825bb7f1
Build lane: monodevelop-lion-d15-5

Operating System
Mac OS X 10.12.6
Darwin 16.7.0 Darwin Kernel Version 16.7.0
    Wed Oct  4 00:17:00 PDT 2017
    root:xnu-3789.71.6~1/RELEASE_X86_64 x86_64

Enabled user installed addins
Internet of Things (IoT) development (Preview) 7.1

BTW: When try to load the update for "Visual Studio Updater 1.7" it download and when try to apply I get error "No updates Found".


问:
Inserting test data which references another table without hard coding the foreign key values
I'm trying to write a SQL query that will insert test data into two tables, one of which references the other.

Tables are created from something like the following:

```<code>CREATE TABLE address (
  address_id INTEGER IDENTITY PRIMARY KEY,
  ...[irrelevant columns]
);

CREATE TABLE member (
  ...[irrelevant columns],
  address INTEGER,
  FOREIGN KEY(address) REFERENCES address(address_id)
);
</code>```

I want ids in both tables to auto increment, so that I can easily insert new rows later without having to look into the table for ids.

I need to insert some test data into both tables, about 25 rows in each. Hardcoding ids for the insert causes issues with inserting new rows later, as the automatic values for the id columns try and start with 1 (which is already in the database). So I need to let the ids be automatically generated, but I also need to know which ids are in the database for inserting test data into the member database - I don't believe the autogenerated ones are guaranteed to be consecutive, so can't assume I can safely hardcode those.

This is test data - I don't care which record I link each member row I am inserting to, only that there is an address record in the address table with that id.

My thoughts for how to do this so far include:

Insert addresses individually, returning the id, then use that to insert an individual member (cons: potentially messy, not sure of the syntax, harder to see expected sets of addresses/members in the test data)

Do the member insert with a SELECT address_id FROM address WHERE [some condition that will only give one row] for the address column (cons: also a bit messy, involves a quite long statement for something I don't care about)

Is there a neater way around this problem?

I particularly wonder if there is a way to either:

Let the auto increment controlling functions be aware of manually inserted id values, or

Get the list of inserted ids from the address table into a variable which I can use values from in turn to insert members.

Ideally, I'd like this to work with as many (irritatingly slightly different) database engines as possible, but I need to support at least postgresql and sqlite - ideally in a single query, although I could have two separate ones. (I have separate ones for creating the tables, the sole difference being INTEGER GENEREATED BY DEFAULT AS IDENTITY instead of just IDENTITY.)

答:
https://www.postgresql.org/docs/8.1/static/functions-sequence.html

Sounds like LASTVAL() is what you're looking for.  It was also work in the real world to maintain transactional consistency between multiple selects, as it's scoped to your sessions last insert.

Body:
I'm trying to write a SQL query that will insert test data into two tables, one of which references the other.

Tables are created from something like the following:

CREATE TABLE address (
  address_id INTEGER IDENTITY PRIMARY KEY,
  ...[irrelevant columns]
);

CREATE TABLE member (
  ...[irrelevant columns],
  address INTEGER,
  FOREIGN KEY(address) REFERENCES address(address_id)
);

I want ids in both tables to auto increment, so that I can easily insert new rows later without having to look into the table for ids.

I need to insert some test data into both tables, about 25 rows in each. Hardcoding ids for the insert causes issues with inserting new rows later, as the automatic values for the id columns try and start with 1 (which is already in the database). So I need to let the ids be automatically generated, but I also need to know which ids are in the database for inserting test data into the member database - I don't believe the autogenerated ones are guaranteed to be consecutive, so can't assume I can safely hardcode those.

This is test data - I don't care which record I link each member row I am inserting to, only that there is an address record in the address table with that id.

My thoughts for how to do this so far include:

Insert addresses individually, returning the id, then use that to insert an individual member (cons: potentially messy, not sure of the syntax, harder to see expected sets of addresses/members in the test data)

Do the member insert with a SELECT address_id FROM address WHERE [some condition that will only give one row] for the address column (cons: also a bit messy, involves a quite long statement for something I don't care about)

Is there a neater way around this problem?

I particularly wonder if there is a way to either:

Let the auto increment controlling functions be aware of manually inserted id values, or

Get the list of inserted ids from the address table into a variable which I can use values from in turn to insert members.

Ideally, I'd like this to work with as many (irritatingly slightly different) database engines as possible, but I need to support at least postgresql and sqlite - ideally in a single query, although I could have two separate ones. (I have separate ones for creating the tables, the sole difference being INTEGER GENEREATED BY DEFAULT AS IDENTITY instead of just IDENTITY.)


问:
Google Chrome developer tools works very slow
Sinсe Google Chrome was updated to 50.x version, it become impossible to work with DevTools. This issue reproduced mostly in "Network" tab. Every time when you click on "request" it takes about 30-40 sec. after that chrome can crash. Tried to delete all extensions, clear cache, and reinstall, but didn't help. Does anybody know how to fix this issue?

I'm running Chrome 50.0.2661.87 m

UPD: The problem may be occurs because of long headers. Try to close response and request headers.

答:
Make devtools snappy again by deactivating all breakpoints:

Go to the Sources tab, show the debugger (may be hidden) and hit Deactivate breakpoints.

(Chrome v62.0 on Windows 10)


问:
System.identityHashCode() behavior on primitives
In jvm imgui, I was using

System.identityHashCode(i++)

where

var i = 0

to generate for each frame always a constant id for a given object (and so being

able to track it)

However, one user case just showed me that this is valid only for values in [0, 125]

Trying to debug and find the bug, I ended testing this short snippet of code:

```<code>    var i = 0
    val A = Array(256, { System.identityHashCode(i++) })
    i = 0
    val B = Array(256, { System.identityHashCode(i++) })
    repeat(256) {
        if (A[it] != B[it])
            println("[$it] different, A ${A[it]}, B ${B[it]}")
    }
</code>```

also with:

bytes (fully working, A == B for all the 256 values)

shorts (not working from 128)

ints (not working from 128)

longs (not working from 128)

floats (not working at all)

doubles (not working at all)

Why is that?

And am I safe assuming this behavior will be the coherent also on other platforms?

答:
However, one user case just showed me that this is valid only for values in [0, 125]

System.identityHashCode(Object) takes an Object not a primitive which means that your i++ is auto-boxed to be an Integer (or Long or ...).  The only time that the objects will have the same identity hashcode will most likely (but not always) be when they are the same object.  As it happens, the JVM caches a small number of Integers for optimization purposes meaning that the identity hashcodes of the 0 to 127 values are be the same.

When autoboxing happens the compiler generates a call to Integer.valueOf(int).  If we look at the code for `valueOf(...) we see:

```<code>if (i >= IntegerCache.low && i <= IntegerCache.high)
    return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
</code>```

So there is a low and high cache range from which you will get a cached constant object that are generated when the JVM starts up.  There are JVM arguments that affect the size of the number caches.  So 127 must be within the cache range for your JVM while 128 and above are not.

```<code>// both of the 100 values gets auto-boxed to the same Integer object
System.identityHashCode(100) == System.identityHashCode(100)
</code>```

This is basically equivalent to comparing the hashcodes of the same object:

```<code>Integer i = new Integer(100);
System.identityHashCode(i) == System.identityHashCode(i)
</code>```

Once you are past the initial cached set of Integer values and larger ints are specified, new Integer objects will be created when they are auto-boxed and so the identity hashcodes are (most likely) no longer equal.

```<code>// by default, each of these 1000000 values gets auto-boxed to a different object
System.identityHashCode(1000000) != System.identityHashCode(1000000)
</code>```

This is basically equivalent to instantiating 2 different integers and expecting their hashcodes to be the same:

```<code>Integer i1 = new Integer(1000000);
Integer i2 = new Integer(1000000);
System.identityHashCode(i1) != System.identityHashCode(i2)
</code>```

Note that System.identityHashCode(...) does not return unique values so it is possible (albeit unlikely) that they will generate the same value if when looking at different objects.

Body:
In jvm imgui, I was using

System.identityHashCode(i++)

where

var i = 0

to generate for each frame always a constant id for a given object (and so being

able to track it)

However, one user case just showed me that this is valid only for values in [0, 125]

Trying to debug and find the bug, I ended testing this short snippet of code:

    var i = 0
    val A = Array(256, { System.identityHashCode(i++) })
    i = 0
    val B = Array(256, { System.identityHashCode(i++) })
    repeat(256) {
        if (A[it] != B[it])
            println("[$it] different, A ${A[it]}, B ${B[it]}")
    }

also with:

bytes (fully working, A == B for all the 256 values)

shorts (not working from 128)

ints (not working from 128)

longs (not working from 128)

floats (not working at all)

doubles (not working at all)

Why is that?

And am I safe assuming this behavior will be the coherent also on other platforms?

Body:
However, one user case just showed me that this is valid only for values in [0, 125]

System.identityHashCode(Object) takes an Object not a primitive which means that your i++ is auto-boxed to be an Integer (or Long or ...).  The only time that the objects will have the same identity hashcode will most likely (but not always) be when they are the same object.  As it happens, the JVM caches a small number of Integers for optimization purposes meaning that the identity hashcodes of the 0 to 127 values are be the same.

When autoboxing happens the compiler generates a call to Integer.valueOf(int).  If we look at the code for `valueOf(...) we see:

if (i >= IntegerCache.low && i <= IntegerCache.high)
    return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);

So there is a low and high cache range from which you will get a cached constant object that are generated when the JVM starts up.  There are JVM arguments that affect the size of the number caches.  So 127 must be within the cache range for your JVM while 128 and above are not.

// both of the 100 values gets auto-boxed to the same Integer object
System.identityHashCode(100) == System.identityHashCode(100)

This is basically equivalent to comparing the hashcodes of the same object:

Integer i = new Integer(100);
System.identityHashCode(i) == System.identityHashCode(i)

Once you are past the initial cached set of Integer values and larger ints are specified, new Integer objects will be created when they are auto-boxed and so the identity hashcodes are (most likely) no longer equal.

// by default, each of these 1000000 values gets auto-boxed to a different object
System.identityHashCode(1000000) != System.identityHashCode(1000000)

This is basically equivalent to instantiating 2 different integers and expecting their hashcodes to be the same:

Integer i1 = new Integer(1000000);
Integer i2 = new Integer(1000000);
System.identityHashCode(i1) != System.identityHashCode(i2)

Note that System.identityHashCode(...) does not return unique values so it is possible (albeit unlikely) that they will generate the same value if when looking at different objects.


问:
becomeFirstResponder sometimes does not open the keyboard on ios 10
I'm creating an native touch id alert with code:

```<code>    let context = LAContext()

    guard deviceCanUseTouchId(context: context) else {
        return
    }

    presentingAlert = true
    [context.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: "touch_id_auth_message".localized(), reply: { [unowned self] success, error -> Void in
        self.presentingAlert = false
        self.canPresentAlert = true

        dispatch_async(dispatch_get_main_queue()) {
            completionHandler?(success)
        }
    })]
</code>```

button handler that calls the native Touch ID alert looks like this:

```<code>@IBAction func touchUpInsideUseTouchIdButton(sender: AnyObject) {
    ACTouchId.sharedManager.authenticateWithTouchId(completionHandler: { [weak self] in
        self?.handleTouchIdAuthentication(granted: $0)
        })

    view.endEditing(true)
}
</code>```

and this is the code of handleTouchIdAuthentication:

```<code>private func handleTouchIdAuthentication(granted granted: Bool) {
    if granted {
        //...
    } else {
        passcodeDigitTextField1.becomeFirstResponder()
    }
}
</code>```

The problem is, that most of the time, when I cancel the Touch ID native dialog, the alert dismiss correctly and becomeFirstResponder() works OK.

However at around 1 in 10 times, becomeFirstResponder() returns true, passcodeDigitTextField1 gets focus, but the keyboard does not appear. Moreover keyboard will not show itself even if I change the focus to other text field by tapping them.

Strangly, this works fine for ios 9 and 8. The issue happens only on iOS 10.

答:
It might sound really stupid but... in my case once it helped to restart the whole device. Just that. It was also iOS 10 only.
;) Maybe there is someone with a similar problem out there and did not try that before checking stack overflow since it seems kind of weird to just restart the device for an error like this.</p>

Body:
I'm creating an native touch id alert with code:

    let context = LAContext()

    guard deviceCanUseTouchId(context: context) else {
        return
    }

    presentingAlert = true
    [context.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: "touch_id_auth_message".localized(), reply: { [unowned self] success, error -> Void in
        self.presentingAlert = false
        self.canPresentAlert = true

        dispatch_async(dispatch_get_main_queue()) {
            completionHandler?(success)
        }
    })]

button handler that calls the native Touch ID alert looks like this:

@IBAction func touchUpInsideUseTouchIdButton(sender: AnyObject) {
    ACTouchId.sharedManager.authenticateWithTouchId(completionHandler: { [weak self] in
        self?.handleTouchIdAuthentication(granted: $0)
        })

    view.endEditing(true)
}

and this is the code of handleTouchIdAuthentication:

private func handleTouchIdAuthentication(granted granted: Bool) {
    if granted {
        //...
    } else {
        passcodeDigitTextField1.becomeFirstResponder()
    }
}

The problem is, that most of the time, when I cancel the Touch ID native dialog, the alert dismiss correctly and becomeFirstResponder() works OK.

However at around 1 in 10 times, becomeFirstResponder() returns true, passcodeDigitTextField1 gets focus, but the keyboard does not appear. Moreover keyboard will not show itself even if I change the focus to other text field by tapping them.

Strangly, this works fine for ios 9 and 8. The issue happens only on iOS 10.


问:
Redirect / Rewrite with .htaccess of an url containing :
I'm trying to redirect from /index.php?option=com_k2&view=itemlist&task=category&id=44:pinco to google.it

Note the special char :

But it doesn't seem to work.

This is one of the tests I've tried. Where am I wrong?

```<code>redirect 301 /?option=com_k2&view=item&id=44:pinco http://www.google.it
</code>```

答:
You can not redirect Query String using Redirect directive. You need to check Query String using ℅{QUERY_STRING} variable.

```<code>RewriteEngine on

RewriteCond ℅{QUERY_STRING} ^option=com_k2&view=itemlist&task=category&id=44:pinco$
RewriteRule ^index\.php$ http://google.it? [L,R]
</code>```

Body:
I'm trying to redirect from /index.php?option=com_k2&view=itemlist&task=category&id=44:pinco to google.it

Note the special char :

But it doesn't seem to work.

This is one of the tests I've tried. Where am I wrong?

redirect 301 /?option=com_k2&view=item&id=44:pinco http://www.google.it

Body:
You can not redirect Query String using Redirect directive. You need to check Query String using ℅{QUERY_STRING} variable.

RewriteEngine on

RewriteCond ℅{QUERY_STRING} ^option=com_k2&view=itemlist&task=category&id=44:pinco$
RewriteRule ^index\.php$ http://google.it? [L,R]