问:
Mysql join tables with or without a condition
I have a problem i've been having quite a lot recently and it would be great to find a solution for it.
Let's say we have two tables Table1 and Table2. Is there a way to make a join on these tables with or without a condition?

e.g:

```<code>Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in (v1,v2,v3) and ...;

Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in ('') and ....;
</code>```

So in these two cases i wanna be able to do a join, if I point a condition on the t2 column then it would show me results related to that otherwise show everything.

At the moment if I put the in('') it wouldn't show anything.

Thanks in advance.

答:
Your requirements as mentioned call for use of an inner join.
A left join will fetch all records from left table and matching records from the right one. If you want to apply filter on the intersection of two tables, use inner join.

A graphical explanation is available here: https://www.w3schools.com/sql/sql_join.asp

Body:
I have a problem i've been having quite a lot recently and it would be great to find a solution for it.
Let's say we have two tables Table1 and Table2. Is there a way to make a join on these tables with or without a condition?

e.g:

Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in (v1,v2,v3) and ...;

Select * from Table1 t1 left join Table2 t2 on t1.column = t2.column where t2.anothercolumn in ('') and ....;

So in these two cases i wanna be able to do a join, if I point a condition on the t2 column then it would show me results related to that otherwise show everything.

At the moment if I put the in('') it wouldn't show anything.

Thanks in advance.


来源: stackexchange

问:
wpf datagrid total row
I want to make a total row in a wpf datagrid like
this one.
I don't know how to create such a row in xaml. It should be frozen when I scroll through the other rows.

Someone said it is possible to add a total item to the data source and create a special template for that item. But this seems a bit weird.

I found no working solution for that. Has someone an idea how to do that?

答:
You could bind your TextBlock.Text to your value. To do this for all of your columns you could change the ContentTemplate for your DataGrid Header like this

```<code><DataGrid ...>
   <DataGrid.Resources>
      <Style TargetType="{x:Type DataGridColumnHeader}">
         <Setter Property="ContentTemplate">
            <Setter.Value>
               <DataTemplate>
                  <TextBlock Text="{Binding}" TextWrapping="Wrap"/>
               </DataTemplate>
            </Setter.Value>
         </Setter>
      </Style>
   </DataGrid.Resources>
   <DataGrid.Columns>
      <DataGridTextColumn Binding="{Binding Name}" Header="Header Text">
   </DataGrid.Columns>
</DataGrid>
</code>```

Alternatively, to do it for each column you could change TextBlock.Text in your Header template to use a binding

```<code><TextBlock Text="{Binding}" TextWrapping="Wrap"/>
</code>```

and then your column would look like this

```<code><DataGridTextColumn
    Binding="{Binding Name}"
    HeaderTemplate="{StaticResource ColumnHeaderTemplate}"
    Header="Header Text"/>
</code>```

ContentLicense: CC BY-SA 3.0

Title: wpf datagrid total row

Body:
You could bind your TextBlock.Text to your value. To do this for all of your columns you could change the ContentTemplate for your DataGrid Header like this

<DataGrid ...>
   <DataGrid.Resources>
      <Style TargetType="{x:Type DataGridColumnHeader}">
         <Setter Property="ContentTemplate">
            <Setter.Value>
               <DataTemplate>
                  <TextBlock Text="{Binding}" TextWrapping="Wrap"/>
               </DataTemplate>
            </Setter.Value>
         </Setter>
      </Style>
   </DataGrid.Resources>
   <DataGrid.Columns>
      <DataGridTextColumn Binding="{Binding Name}" Header="Header Text">
   </DataGrid.Columns>
</DataGrid>

Alternatively, to do it for each column you could change TextBlock.Text in your Header template to use a binding

<TextBlock Text="{Binding}" TextWrapping="Wrap"/>

and then your column would look like this

<DataGridTextColumn
    Binding="{Binding Name}"
    HeaderTemplate="{StaticResource ColumnHeaderTemplate}"
    Header="Header Text"/>


问:
Create a New Laravel Project Using Homestead
I have already setup Laravel using homestead before, and I have an existing project that already works. However, i want to add another new project.

I have added a new folder and mapped it in the homestead.yaml file. But I want to know how to setup the project itself because the folder is empty and all the documentation I found is on the new site mapping. How about the new site configuration and files.

Please assist me in this as i am very new to Laravel. I am using Windows by the way

答:
You can install Laravel using composer:

```<code>composer create-project --prefer-dist laravel/laravel blog
</code>```

Alternative:

```<code>composer global require "laravel/installer"
</code>```

and then laravel new blog
(make sure composer is in your path)

Body:
You can install Laravel using composer:

composer create-project --prefer-dist laravel/laravel blog

Alternative:

composer global require "laravel/installer"

and then laravel new blog
(make sure composer is in your path)


问:
how to connecting a variable to .caption in VB.NET
i want to make a variable can be used in .caption, so i can get the value and used it to make something.

last experiment, i use it in foxpro and it can work pretty well.
like this.

foxpro code mix variable with system

tmbl = "command"+alltrim(str(i)) set order to no_room seek
  (thisform.pageframe1.page1.&tmbl..caption

see the &tmbl.?? im using it as a connector to .caption

now im trying to do it in VB.NET. it can not work. i don't know what kind connector must be use in VB.NET. so can somebody please tell what must to use in VB.NET?

答:
You can simply use controls collection to find the control you want (and even in VFP it is the way to go, instead of abusing the & operator). Say you want to do this for a label, in C# it looks like:

```<code>var label = this.Controls.OfType<Label>()
      .SingleOrDefault(c => c.Name == "command" + i);

if (label != null)
{
   label.Text = "Whatever";
}
</code>```

Telerik code converter converts this to VB.Net as:

```<code>Dim label = Me.Controls.OfType(Of Label)().SingleOrDefault(Function(c) c.Name = "command" + i)

If label IsNot Nothing Then
    label.Text = "Whatever"
End If
</code>```

Body:
You can simply use controls collection to find the control you want (and even in VFP it is the way to go, instead of abusing the & operator). Say you want to do this for a label, in C# it looks like:

var label = this.Controls.OfType<Label>()
      .SingleOrDefault(c => c.Name == "command" + i);

if (label != null)
{
   label.Text = "Whatever";
}

Telerik code converter converts this to VB.Net as:

Dim label = Me.Controls.OfType(Of Label)().SingleOrDefault(Function(c) c.Name = "command" + i)

If label IsNot Nothing Then
    label.Text = "Whatever"
End If


问:
Change ContentControl Content from Content ViewModel programmatically
MainWindow.xaml

```<code><Window.Resources>
    <DataTemplate DataType="{x:Type local2:StartPageViewModel}">
        <local1:StartPage/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type local2:SecondPageViewModel}">
        <local1:SecondPage/>
    </DataTemplate>
</Window.Resources>
<DockPanel>
    <StackPanel DockPanel.Dock="Left">
        <Label Content="[res][per]" />
        <Button Command="{Binding CommandStartView}">
            First
        </Button>
        <Button Command="{Binding CommandSecondView}">
            Second
        </Button>
    </StackPanel>
    <ContentControl x:Name="Pages" DockPanel.Dock="Right" Content="{Binding SelectedViewModel}"/>
</DockPanel>
</code>```

MainWindowViewModel.cs

```<code>class MainWindowViewModel : BaseViewModel
{

    private object selectedViewModel;

    public object SelectedViewModel
    {
        get { return selectedViewModel; }
        set { selectedViewModel = value; OnPropertyChanged("SelectedViewModel"); }
    }

    public ICommand CommandStartView { get; set; }
    public ICommand CommandSecondView { get; set; }

    public MainWindowViewModel()
    {

        CommandStartView = new RelayCommand(openStartView);
        CommandSecondView = new RelayCommand(openSecondView);

    }

    private void openStartView(object obj)
    {
        SelectedViewModel = new StartPageViewModel();
    }

    private void openSecondView(object obj)
    {
        SelectedViewModel = new SecondPageViewModel();
    }

}
</code>```

StartPage.xaml

```<code><StackPanel>
    <Label Content="First Page" />
    <Button Content="Second" Command="{Binding Path=DataContext.CommandSecondView, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
    <Button Content="Do Something" Command="{Binding CommandDoBeforeSecondView}"/>
</StackPanel>
</code>```

StartPageViewModel.cs

```<code>class StartPageViewModel : BaseViewModel
{
    public ICommand CommandDoBeforeSecondView { get; set; }

    public StartPageViewModel()
    {

        CommandDoBeforeSecondView = new RelayCommand(openSecondView);
    }

    private void openSecondView(object obj)
    {
        Console.WriteLine("DO SOME CODE");

        //Then change Content programmatically

    }
 }
</code>```

Question:
How can I change the Content from the MainWindow ContentControl using the second button in the StartPage? I want to execute some code and then change the content.

In relation of the first comment I think I have to add a reference the MainWindowViewModel in my StartPageViewModel, how i make this?

EDIT

My working Solution:

MainWindowViewModel.cs

```<code>private void openStartView(object obj)
{
    SelectedViewModel = new StartPageViewModel(this);
}
</code>```

StartPageViewModel.cs

```<code>class StartPageViewModel : BaseViewModel
{
    private MainWindowViewModel mainWindow;
    public ICommand CommandDoBeforeSecondView { get; set; }

    public StartPageViewModel(MainWindowViewModel _mainWindow)
    {
        mainWindow = _mainWindow;
        CommandDoBeforeSecondView = new RelayCommand(openSecondView);
    }

    private void openSecondView(object obj)
    {
        Console.WriteLine("DO SOME CODE");
        mainWindow.SelectedViewModel = new SecondPageViewModel();

    }
}
</code>```

答:
My working Solution:

MainWindowViewModel.cs

```<code>private void openStartView(object obj)
{
    SelectedViewModel = new StartPageViewModel(this);
}
</code>```

StartPageViewModel.cs

```<code>class StartPageViewModel : BaseViewModel
{
    private MainWindowViewModel mainWindow;
    public ICommand CommandDoBeforeSecondView { get; set; }

    public StartPageViewModel(MainWindowViewModel _mainWindow)
    {
        mainWindow = _mainWindow;
        CommandDoBeforeSecondView = new RelayCommand(openSecondView);
    }

    private void openSecondView(object obj)
    {
        Console.WriteLine("DO SOME CODE");
        mainWindow.SelectedViewModel = new SecondPageViewModel();

    }
}
</code>```

Thx to Peter Duniho he answered it the comments above:

you should just pass this when creating StartPageViewModel in the MainWindowViewModel, then the StartPageViewModel will have the reference (you'll have to add the parameter to the constructor of course)

Body:
MainWindow.xaml

<Window.Resources>
    <DataTemplate DataType="{x:Type local2:StartPageViewModel}">
        <local1:StartPage/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type local2:SecondPageViewModel}">
        <local1:SecondPage/>
    </DataTemplate>
</Window.Resources>
<DockPanel>
    <StackPanel DockPanel.Dock="Left">

        <Button Command="{Binding CommandStartView}">
            First
        </Button>
        <Button Command="{Binding CommandSecondView}">
            Second
        </Button>
    </StackPanel>
    <ContentControl x:Name="Pages" DockPanel.Dock="Right" Content="{Binding SelectedViewModel}"/>
</DockPanel>

MainWindowViewModel.cs

class MainWindowViewModel : BaseViewModel
{

    private object selectedViewModel;

    public object SelectedViewModel
    {
        get { return selectedViewModel; }
        set { selectedViewModel = value; OnPropertyChanged("SelectedViewModel"); }
    }

    public ICommand CommandStartView { get; set; }
    public ICommand CommandSecondView { get; set; }

    public MainWindowViewModel()
    {

        CommandStartView = new RelayCommand(openStartView);
        CommandSecondView = new RelayCommand(openSecondView);

    }

    private void openStartView(object obj)
    {
        SelectedViewModel = new StartPageViewModel();
    }

    private void openSecondView(object obj)
    {
        SelectedViewModel = new SecondPageViewModel();
    }

}

StartPage.xaml

<StackPanel>

    <Button Content="Second" Command="{Binding Path=DataContext.CommandSecondView, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
    <Button Content="Do Something" Command="{Binding CommandDoBeforeSecondView}"/>
</StackPanel>

StartPageViewModel.cs

class StartPageViewModel : BaseViewModel
{
    public ICommand CommandDoBeforeSecondView { get; set; }

    public StartPageViewModel()
    {

        CommandDoBeforeSecondView = new RelayCommand(openSecondView);
    }

    private void openSecondView(object obj)
    {
        Console.WriteLine("DO SOME CODE");

        //Then change Content programmatically

    }
 }

Question:
How can I change the Content from the MainWindow ContentControl using the second button in the StartPage? I want to execute some code and then change the content.

In relation of the first comment I think I have to add a reference the MainWindowViewModel in my StartPageViewModel, how i make this?

EDIT

My working Solution:

MainWindowViewModel.cs

private void openStartView(object obj)
{
    SelectedViewModel = new StartPageViewModel(this);
}

StartPageViewModel.cs

class StartPageViewModel : BaseViewModel
{
    private MainWindowViewModel mainWindow;
    public ICommand CommandDoBeforeSecondView { get; set; }

    public StartPageViewModel(MainWindowViewModel _mainWindow)
    {
        mainWindow = _mainWindow;
        CommandDoBeforeSecondView = new RelayCommand(openSecondView);
    }

    private void openSecondView(object obj)
    {
        Console.WriteLine("DO SOME CODE");
        mainWindow.SelectedViewModel = new SecondPageViewModel();

    }
}

Body:
My working Solution:

MainWindowViewModel.cs

private void openStartView(object obj)
{
    SelectedViewModel = new StartPageViewModel(this);
}

StartPageViewModel.cs

class StartPageViewModel : BaseViewModel
{
    private MainWindowViewModel mainWindow;
    public ICommand CommandDoBeforeSecondView { get; set; }

    public StartPageViewModel(MainWindowViewModel _mainWindow)
    {
        mainWindow = _mainWindow;
        CommandDoBeforeSecondView = new RelayCommand(openSecondView);
    }

    private void openSecondView(object obj)
    {
        Console.WriteLine("DO SOME CODE");
        mainWindow.SelectedViewModel = new SecondPageViewModel();

    }
}

Thx to Peter Duniho he answered it the comments above:

you should just pass this when creating StartPageViewModel in the MainWindowViewModel, then the StartPageViewModel will have the reference (you'll have to add the parameter to the constructor of course)


问:
how to create html table in php
I have the following snippet of code that basically uses explode to split out these values:

```<code><?php
$data=array();
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line){
   $pieces = explode(";", $line);
   echo $pieces[0];
   echo $pieces[1];
   echo $pieces[2];
   echo $pieces[3];
//print_r($line);
}
?>
</code>```

Data: (prod.txt)

```<code>PREFIX=abc;PART=null;FILE=/myprojects/school/out/data/feed_abc_2010120810.gz2
PREFIX=efg;PART=sdsu;FILE=mail_efg.dat.2010120810.gz2
</code>```

Can someone show me how to put this in an HTML table dynamically, like this?? Is there an easy way to do this? Thanks.

```<code>PREFIX  PART   FILE
abc     null   /myprojects/school/out/data/feed_abc_2010120810.gz2
efg     sdsu   mail_efg.dat.2010120810.gz2
</code>```

答:
This should be flexible enough and won't require any hard-coded pair names:</p>

```<code><?php

$lines = preg_split('~\s*[\r\n]+\s*~', file_get_contents('prod.txt'));

foreach($lines as $i => $line) {
    $pairs = explode(';', $line);
    foreach($pairs as $pair) {
        list($column, $value) = explode('=', $pair, 2);
        $columns[$column] = true;
        $rows[$i][$column] = $value;
    }
}

$columns = array_keys($columns);

echo '<table><thead><tr>';

foreach($columns as $column) {
    echo '<th>'.$column.'</th>';
}

echo '</tr></thead><tbody>';

foreach($rows as $row) {
    echo '<tr>';
    foreach($columns as $column) {
        echo '<td>'.$row[$column].'</td>';
    }
    echo '</tr>';
}
echo '</tbody></table>';

?>
</code>```

ContentLicense: CC BY-SA 2.5

Title: how to create html table in php

Body:
I have the following snippet of code that basically uses explode to split out these values:

<?php
$data=array();
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line){
   $pieces = explode(";", $line);
   echo $pieces[0];
   echo $pieces[1];
   echo $pieces[2];
   echo $pieces[3];
//print_r($line);
}
?>

Data: (prod.txt)

PREFIX=abc;PART=null;FILE=/myprojects/school/out/data/feed_abc_2010120810.gz2
PREFIX=efg;PART=sdsu;FILE=mail_efg.dat.2010120810.gz2

Can someone show me how to put this in an HTML table dynamically, like this?? Is there an easy way to do this? Thanks.

PREFIX  PART   FILE
abc     null   /myprojects/school/out/data/feed_abc_2010120810.gz2
efg     sdsu   mail_efg.dat.2010120810.gz2

Body:
This should be flexible enough and won't require any hard-coded pair names:

<?php

$lines = preg_split('~\s*[\r\n]+\s*~', file_get_contents('prod.txt'));

foreach($lines as $i => $line) {
    $pairs = explode(';', $line);
    foreach($pairs as $pair) {
        list($column, $value) = explode('=', $pair, 2);
        $columns[$column] = true;
        $rows[$i][$column] = $value;
    }
}

$columns = array_keys($columns);

echo '<table><thead><tr>';

foreach($columns as $column) {
    echo '<th>'.$column.'</th>';
}

echo '</tr></thead><tbody>';

foreach($rows as $row) {
    echo '<tr>';
    foreach($columns as $column) {
        echo '<td>'.$row[$column].'</td>';
    }
    echo '</tr>';
}
echo '</tbody></table>';

?>


问:
ExpressionChangedAfterItHasBeenCheckedError when passing the width of an element to my own directive.
I created my own directive for table header (thead tag). That makes that header of table is "sticky" (has fixed position and is visible during scroll table). It looks like that:

sticky.directive.ts

```<code>const NAVBAR_HEIGHT = 55;

@Directive({
    selector: '[sticky]',
})
export class StickyDirective implements AfterViewInit {

    @Input()
    @HostBinding('style.width.px')
    stickyWidth: string;

    topPosition: number;

    constructor(private _element: ElementRef, private _window: WindowRef) { }

    ngAfterViewInit() {
        let boundingClientRect = this._element.nativeElement.getBoundingClientRect();
        this.topPosition = boundingClientRect.top - NAVBAR_HEIGHT;
    }

    @HostListener('window:scroll', ['$event'])
    handleScrollEvent(e) {
        if (this._window.nativeWindow.pageYOffset > (this.topPosition) ) {
            this._element.nativeElement.classList.add('stick');
        } else {
            this._element.nativeElement.classList.remove('stick');
        }
    }
}
</code>```

And is called in this way:

```<code><div class="card-block" >
   <table #table class="table table-bordered">
      <thead sticky [stickyWidth]="table.offsetWidth">
</code>```

It's work fine, but in console I got error:

```<code>ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '1632'. Current value: '1615'.
    at viewDebugError (core.es5.js:8633)
    at expressionChangedAfterItHasBeenCheckedError (core.es5.js:8611)
    at checkBindingNoChanges (core.es5.js:8775)
    at checkNoChangesNodeInline (core.es5.js:12329)
    at checkNoChangesNode (core.es5.js:12303)
    at debugCheckNoChangesNode (core.es5.js:12922)
    at debugCheckDirectivesFn (core.es5.js:12824)
    at Object.View_PageListComponent_0.co [as updateDirectives] (PageListComponent.html:23)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:12806)
    at checkNoChangesView (core.es5.js:12123)
    at callViewAction (core.es5.js:12487)
</code>```

Anyone can explain me what I did wrong? How can I secure my app against this exception or what is the correct way creating similar directive? Thanks in advance

答:
the moment you're updating table.offsetWidth is happening after Angular has finished it's changeDetection cycle .

It would be better to share the code, but without seeing it, here is what you possibly need to do :

Move that update in better and proper timing, and make sure the process of changing that is a one way flow.

Use detectorRef.detectChanges() after your update

Put the update inside a setTimeout

Any of them would work, but best is the first one, the others are your last resort

Body:
I created my own directive for table header (thead tag). That makes that header of table is "sticky" (has fixed position and is visible during scroll table). It looks like that:

sticky.directive.ts

const NAVBAR_HEIGHT = 55;

@Directive({
    selector: '[sticky]',
})
export class StickyDirective implements AfterViewInit {

    @Input()
    @HostBinding('style.width.px')
    stickyWidth: string;

    topPosition: number;

    constructor(private _element: ElementRef, private _window: WindowRef) { }

    ngAfterViewInit() {
        let boundingClientRect = this._element.nativeElement.getBoundingClientRect();
        this.topPosition = boundingClientRect.top - NAVBAR_HEIGHT;
    }

    @HostListener('window:scroll', ['$event'])
    handleScrollEvent(e) {
        if (this._window.nativeWindow.pageYOffset > (this.topPosition) ) {
            this._element.nativeElement.classList.add('stick');
        } else {
            this._element.nativeElement.classList.remove('stick');
        }
    }
}

And is called in this way:

It's work fine, but in console I got error:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '1632'. Current value: '1615'.
    at viewDebugError (core.es5.js:8633)
    at expressionChangedAfterItHasBeenCheckedError (core.es5.js:8611)
    at checkBindingNoChanges (core.es5.js:8775)
    at checkNoChangesNodeInline (core.es5.js:12329)
    at checkNoChangesNode (core.es5.js:12303)
    at debugCheckNoChangesNode (core.es5.js:12922)
    at debugCheckDirectivesFn (core.es5.js:12824)
    at Object.View_PageListComponent_0.co [as updateDirectives] (PageListComponent.html:23)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:12806)
    at checkNoChangesView (core.es5.js:12123)
    at callViewAction (core.es5.js:12487)

Anyone can explain me what I did wrong? How can I secure my app against this exception or what is the correct way creating similar directive? Thanks in advance


问:
Issue in pagination angularjs
I am having an issue with pagination :
This is my html

```<code>    <div class="panel panel-info" ng-repeat="item in filteredTodos | orderBy: 'Date' : true | filter : search">
     {{item.Name}}
    </div>
<div data-pagination="" data-num-pages="numPages()"
      data-current-page="currentPage" data-max-size="maxSize"
      data-boundary-links="true"></div>
</code>```

and this is my controller :

```<code>$scope.filteredTodos = []
  $scope.currentPage = 1
  $scope.numPerPage = 4
  $scope.maxSize = 5

  $scope.makeTodos = function() {
    $scope.Offre = [];
    $http({
                header: 'content-type:application/json',
                method: 'GET',
                url: '/GetOffre',
            }).success(function (messages) {
            $scope.Offre =messages  ;
      });

  };
  $scope.makeTodos();

  $scope.numPages = function () {
    return Math.ceil($scope.Offre.length / $scope.numPerPage);
  };

  $scope.$watch('currentPage + numPerPage', function() {
    var begin = (($scope.currentPage - 1) * $scope.numPerPage)
    , end = begin + $scope.numPerPage;

    $scope.filteredTodos = $scope.Offre.slice(begin, end);
  });
</code>```

so the problem is when i want to show my result
result

i tried to change the currentPage = 0 so in view i can click in 1 and i can see the result only when i click on 1... and when i refresh the page the same issue is repeated

答:
You can do this easily in the template by using the built-in limitTo filter.

```<code><div class="panel panel-info" ng-repeat="item in Offre | limitTo : maxSize : (currentPage * maxSize - maxSize)">
    <!-- print your item details here -->
</div>
</code>```

Then you can add buttons (previous, next, atd.) which would change the currentPage variable and thus changing the content displayed.

Title: Issue in pagination angularjs

Body:
I am having an issue with pagination :
This is my html

     {{item.Name}}

and this is my controller :

$scope.filteredTodos = []
  $scope.currentPage = 1
  $scope.numPerPage = 4
  $scope.maxSize = 5

  $scope.makeTodos = function() {
    $scope.Offre = [];
    $http({
                header: 'content-type:application/json',
                method: 'GET',
                url: '/GetOffre',
            }).success(function (messages) {
            $scope.Offre =messages  ;
      });

  };
  $scope.makeTodos();

  $scope.numPages = function () {
    return Math.ceil($scope.Offre.length / $scope.numPerPage);
  };

  $scope.$watch('currentPage + numPerPage', function() {
    var begin = (($scope.currentPage - 1) * $scope.numPerPage)
    , end = begin + $scope.numPerPage;

    $scope.filteredTodos = $scope.Offre.slice(begin, end);
  });

so the problem is when i want to show my result
result

i tried to change the currentPage = 0 so in view i can click in 1 and i can see the result only when i click on 1... and when i refresh the page the same issue is repeated

Body:
You can do this easily in the template by using the built-in limitTo filter.

<div class="panel panel-info" ng-repeat="item in Offre | limitTo : maxSize : (currentPage * maxSize - maxSize)">
    <!-- print your item details here -->
</div>

Then you can add buttons (previous, next, atd.) which would change the currentPage variable and thus changing the content displayed.


问:
pull property object as parent object
I have this set of data which I have no control (it's hosted API somewhere, I have no access)

```<code>let x = [
    {name: "james", age: 10, school: {id:1, name:"London"}},
    {name: "james_2", age: 11, school: {id:1, name:"London"}},
    {name: "john", age: 12, school: {id:2, name:"India"}},
    {name: "johnny", age: 56, school: {id:3, name:"USA"}}
]
</code>```

How can I group school first? I need the format to be like this

```<code>[{
    id:1,
    name: "London",
    data: [{
        name: "james", age: 10, school: {id:1, name:"London"
    },{name: "james_2", age: 11, school: {id:1, name:"London"}}]
}]
</code>```

答:
let x = [
    {name: "james", age: 10, school: {id:1, name:"London"}},
    {name: "james_2", age: 11, school: {id:1, name:"London"}},
    {name: "john", age: 12, school: {id:2, name:"India"}},
    {name: "johnny", age: 56, school: {id:3, name:"USA"}}
];

let result = [];
for(var i = 0; i < x.length; i++) {
  var person = x[i];
  var school = result.find(s => s.id === person.school.id);
  if(!school) {
    school = {
      id: person.school.id,
      name: person.school.name,
      data: []
    };
    result.push(school);
  }
  school.data.push(person);
}

console.log(result);```

Title: pull property object as parent object

Body:
I have this set of data which I have no control (it's hosted API somewhere, I have no access)

let x = [
    {name: "james", age: 10, school: {id:1, name:"London"}},
    {name: "james_2", age: 11, school: {id:1, name:"London"}},
    {name: "john", age: 12, school: {id:2, name:"India"}},
    {name: "johnny", age: 56, school: {id:3, name:"USA"}}
]

How can I group school first? I need the format to be like this

[{
    id:1,
    name: "London",
    data: [{
        name: "james", age: 10, school: {id:1, name:"London"
    },{name: "james_2", age: 11, school: {id:1, name:"London"}}]
}]


问:
How do you launch Safari browser from within an iPad app?

Possible Duplicate:

  launch safari from iphone app

How do you launch Safari browser from within an iPad app?

答:
```<code>NSURL *someHTTP_or_HTTPS_URL;
if ( [[UIApplication sharedApplication] openURL: someHTTP_or_HTTPS_URL] ) {
    // success
} else {
    // failure
}
</code>```


问:
React - need for { } to call JS
In the following code (it's a button that changes the color when you click), I don't understand why I need curly braces {} on line9 and 14 but not on line13.

On line 13, we affect state colorGreen to the state color and curly braces are required to read colorYellow variable so we use JS. Am I correct ?
On line 14 it is the same.
On line 13, it is the same, we use colorGreen and color Yellow variable but we don't need curly brace ? Why ?

Thank you

```<code>var React = require('react');
var ReactDOM = require('react-dom');

var colorGreen = '#39D1B0';
var colorYellow = '#FFD710';

var Switch = React.createClass({
  getInitialState: function () {
    return { color: colorGreen }; //line9
  },

  changeColor: function () {
    var changeColor = this.state.color == colorGreen ? colorYellow : colorGreen; //line13
    this.setState({ color: changeColor }); //line14
  }
});
</code>```

答:
They're just plain object literals of JavaScript, not any special syntax of React.

You can create an object in JavaScript by:

```<code>var obj = {
  foo: 'bar'
}
</code>```

and in your code:

```<code>return {
  color: colorGreen
}
</code>```

means create an object and return it immediately.

Please see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer

Title: React - need for { } to call JS

Body:
In the following code (it's a button that changes the color when you click), I don't understand why I need curly braces {} on line9 and 14 but not on line13.

On line 13, we affect state colorGreen to the state color and curly braces are required to read colorYellow variable so we use JS. Am I correct ?
On line 14 it is the same.
On line 13, it is the same, we use colorGreen and color Yellow variable but we don't need curly brace ? Why ?

Thank you

var React = require('react');
var ReactDOM = require('react-dom');

var colorGreen = '#39D1B0';
var colorYellow = '#FFD710';

var Switch = React.createClass({
  getInitialState: function () {
    return { color: colorGreen }; //line9
  },

  changeColor: function () {
    var changeColor = this.state.color == colorGreen ? colorYellow : colorGreen; //line13
    this.setState({ color: changeColor }); //line14
  }
});

Body:
They're just plain object literals of JavaScript, not any special syntax of React.

You can create an object in JavaScript by:

var obj = {
  foo: 'bar'
}

and in your code:

return {
  color: colorGreen
}

means create an object and return it immediately.

Please see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer


问:
Is it possible to configure Nvidia GPU for caffe job only and embed intel GPU for xorg and others respectively?
My laptop has a Nvidia VC with 2G VRAM, and an embedded Intel VC, and the Nvidia VC is activated for using. The problem is that xorg and compiz use too much VRAM (900+ MB), and this causes caffe jobs are being out of memory frequently.

How would it be possible to activate two VCs at same time, but configure Nvidia VC for caffe job, and Intel VC for other jobs like Xorg, Compiz?

答: It turns out that switching to intel gpu in Nivida X server settings will give what I want.</p>

ContentLicense: CC BY-SA 4.0


问:
sw-precache with angularJs application not caching
I am newbie to service worker concept so forgive me if I am overlooking something from documentation. I have an angular application already running in production and I am trying to introduce service worker using sw-precache.
To start with I am trying to precache all images/fonts and couple of js files and see if it works, so my precache config is like this -

```<code>{
  "cacheId": "static-cache",
  "importScripts": [
    "sw-toolbox.js"
  ],
  "stripPrefix": "dist/",
  "verbose": true,
  "staticFileGlobs": [
    "dist/img/**.*",
    "dist/javascripts/require.js",
    "dist/stylesheets/**.*",
    "dist/webfonts/**.{ttf, eot, woff}",
    "sw-toolbox.js",
    "service-worker.js"
  ]
}
</code>```

Now I can see service worker registered and installed properly and cache storage shows all the urls with _sw-precache hashes.

But when I load the application and see in network tab all static content are still served from memory/disk, not from service worker and I am unable to debug why is it so. Am I missing something here -

UPDATE:
More information: I had wrong configurations since I have dynamic url and server side rendered html. Server side it's test.jsp which is giving me initial shell.
For now I have removed all other static files from cache and kept only show.css

So update config now is -

```<code>{
  "importScripts": [
    "sw-toolbox.js"
  ],
  "stripPrefix": "dist/",
  "verbose": true,
  "staticFileGlobs": [
    "dist/stylesheets/show.css"
  ],

  "dynamicUrlToDependencies": {
    "/developers": ["dist/stylesheets/show.css"]
  },

  "navigateFallback": "/developers"
}
</code>```

Web root folder is named differently and it is -

- dashboard
 -- img
 -- javascripts
 -- service-worker.js
 -- sw-toolbox.js
- test.jsp

And I see /developers url as an entry in storage cache, but still it's not served from service worker for next refresh. I have tried all my energy to fix this, but I desperately need some clue here, what's missing in here. TIA.
Let me know if need more info.

答:
It seems that whitespaces in your file extension list are not allowed. Your definition for webfonts should be:

```<code>"dist/webfonts/**.{ttf,eot,woff}",
</code>```

I cloned the sw-precache repo and added a unit test where I compared two generated files with two diffrent staticFileGlobs, one with whitespace and one without.

```<code>it('should handle multiple file extensions', function(done) {
var config = {
  logger: NOOP,
  staticFileGlobs: [
    'test/data/one/*.{txt,rmd}'
  ],
  stripPrefix: 'test'
};

var configPrime = {
  logger: NOOP,
  staticFileGlobs: [
    'test/data/one/*.{txt, rmd}'
  ],
};

generate(config, function(error, responseString) {
  assert.ifError(error);
  generate(configPrime, function(error, responseStringPrime) {
    assert.ifError(error);
    console.log('responseStringPrime',responseString);
    assert.strictEqual(responseString, responseStringPrime);
    done();
  });
});
</code>```

});

and it failed. The second config didn't include the .rmd file:

```<code>  -var precacheConfig = [["/data/one/a.rmd","0cc175b9c0f1b6a831c399e269772661"],["/data/one/a.txt","933222b19ff3e7ea5f65517ea1f7d57e"],["/data/one/c.txt","fa1f726044eed39debea9998ab700388"]];
</code>```

versus

```<code>  +var precacheConfig = [["test/data/one/a.txt","933222b19ff3e7ea5f65517ea1f7d57e"],["test/data/one/c.txt","fa1f726044eed39debea9998ab700388"]];
</code>```

Body:
I am newbie to service worker concept so forgive me if I am overlooking something from documentation. I have an angular application already running in production and I am trying to introduce service worker using sw-precache.
To start with I am trying to precache all images/fonts and couple of js files and see if it works, so my precache config is like this -

{
  "cacheId": "static-cache",
  "importScripts": [
    "sw-toolbox.js"
  ],
  "stripPrefix": "dist/",
  "verbose": true,
  "staticFileGlobs": [
    "dist/img/**.*",
    "dist/javascripts/require.js",
    "dist/stylesheets/**.*",
    "dist/webfonts/**.{ttf, eot, woff}",
    "sw-toolbox.js",
    "service-worker.js"
  ]
}

Now I can see service worker registered and installed properly and cache storage shows all the urls with _sw-precache hashes.

But when I load the application and see in network tab all static content are still served from memory/disk, not from service worker and I am unable to debug why is it so. Am I missing something here -

UPDATE:
More information: I had wrong configurations since I have dynamic url and server side rendered html. Server side it's test.jsp which is giving me initial shell.
For now I have removed all other static files from cache and kept only show.css

So update config now is -

{
  "importScripts": [
    "sw-toolbox.js"
  ],
  "stripPrefix": "dist/",
  "verbose": true,
  "staticFileGlobs": [
    "dist/stylesheets/show.css"
  ],

  "dynamicUrlToDependencies": {
    "/developers": ["dist/stylesheets/show.css"]
  },

  "navigateFallback": "/developers"
}

Web root folder is named differently and it is -

- dashboard
 -- img
 -- javascripts
 -- service-worker.js
 -- sw-toolbox.js
- test.jsp

And I see /developers url as an entry in storage cache, but still it's not served from service worker for next refresh. I have tried all my energy to fix this, but I desperately need some clue here, what's missing in here. TIA.
Let me know if need more info.

Body:
It seems that whitespaces in your file extension list are not allowed. Your definition for webfonts should be:

"dist/webfonts/**.{ttf,eot,woff}",

I cloned the sw-precache repo and added a unit test where I compared two generated files with two diffrent staticFileGlobs, one with whitespace and one without.

it('should handle multiple file extensions', function(done) {
var config = {
  logger: NOOP,
  staticFileGlobs: [
    'test/data/one/*.{txt,rmd}'
  ],
  stripPrefix: 'test'
};

var configPrime = {
  logger: NOOP,
  staticFileGlobs: [
    'test/data/one/*.{txt, rmd}'
  ],
};

generate(config, function(error, responseString) {
  assert.ifError(error);
  generate(configPrime, function(error, responseStringPrime) {
    assert.ifError(error);
    console.log('responseStringPrime',responseString);
    assert.strictEqual(responseString, responseStringPrime);
    done();
  });
});

});

and it failed. The second config didn't include the .rmd file:

  -var precacheConfig = [["/data/one/a.rmd","0cc175b9c0f1b6a831c399e269772661"],["/data/one/a.txt","933222b19ff3e7ea5f65517ea1f7d57e"],["/data/one/c.txt","fa1f726044eed39debea9998ab700388"]];

versus

  +var precacheConfig = [["test/data/one/a.txt","933222b19ff3e7ea5f65517ea1f7d57e"],["test/data/one/c.txt","fa1f726044eed39debea9998ab700388"]];


问:
Does dereferencing a pointer make a copy of it?
Does dereferencing a pointer and passing that to a function which takes its argument by reference create a copy of the object?</p>

答: No. A reference is more or less just like a pointer with different notation and the restriction that there is no null reference. But like a pointer it contains just the address of an object.</p>


问:
How do I remove space between flexbox vertically centred rows?
I have two rows, with a heading in the top row, and 2 columns in the bottom row, all vertically centred within a fullscreen wrap. For some reason, I cannot get rid of the extra vertical space that the fullscreen wrap adds in between the two rows, despite adding:

```<code>align-content:centre
</code>```

as well as display: flex to both parent divs (.wrap and .row)

What am I doing wrong?

jsfiddle: https://jsfiddle.net/ar4Ltoke/2/

.wrap {
  width: 1280px;
  min-height: 100vh;
  border-style: solid;
}

.row {
  width: 100%;
  align-items: flex-start;
  margin: auto;
  border: 1;
  border-style: solid;
}

.column_left {
  flex-basis: 60%;
  border: 1;
}

.column_right {
  flex-basis: 30%;
}

@media (min-width:640px) {
  .row {
    display: flex;
    justify-content: space-between;
  }
  .wrap {
    display: flex;
    align-content: center;
    flex-direction: column;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="row">
    <p class="blue">About me</p>
  </div>
  <div class="row">
    <div class="column_left">
      <p class="leadpara">Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec ullamcorper nulla non metus auctor fringilla. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Fusce dapibus, tellus ac cursus
        commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec ullamcorper nulla non metus auctor fringilla. Duis mollis, est non commodo luctus, nisi
        erat porttitor ligula, eget lacinia odio sem nec elit. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.
      </p>
    </div>
    <div class="column_right">
      <p class="leadpara">
        Email
        <br> Add me on Linkedin
        <br> Tweet at @fsd
      </p>
    </div>
  </div>
</div></code>```

答:
Because you are using
 to change the line due to which extra spaces are created using something else to change the line. You can use a list instead if you want to show them pointwise with list-style-type as none. Please let me know if my answer is not clear. I will send the code if required.

Body:
I have two rows, with a heading in the top row, and 2 columns in the bottom row, all vertically centred within a fullscreen wrap. For some reason, I cannot get rid of the extra vertical space that the fullscreen wrap adds in between the two rows, despite adding:

align-content:centre

as well as display: flex to both parent divs (.wrap and .row)

What am I doing wrong?

jsfiddle: https://jsfiddle.net/ar4Ltoke/2/

.wrap {
  width: 1280px;
  min-height: 100vh;
  border-style: solid;
}

.row {
  width: 100%;
  align-items: flex-start;
  margin: auto;
  border: 1;
  border-style: solid;
}

.column_left {
  flex-basis: 60%;
  border: 1;
}

.column_right {
  flex-basis: 30%;
}

@media (min-width:640px) {
  .row {
    display: flex;
    justify-content: space-between;
  }
  .wrap {
    display: flex;
    align-content: center;
    flex-direction: column;
  }
}

About me

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec ullamcorper nulla non metus auctor fringilla. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Fusce dapibus, tellus ac cursus
        commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec ullamcorper nulla non metus auctor fringilla. Duis mollis, est non commodo luctus, nisi
        erat porttitor ligula, eget lacinia odio sem nec elit. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.

        Email

 Add me on Linkedin

 Tweet at @fsd

Body: Because you are using <br> to change the line due to which extra spaces are created using something else to change the line. You can use a list instead if you want to show them pointwise with list-style-type as none. Please let me know if my answer is not clear. I will send the code if required.


问:
i am trying to send from one controller to other contoller in angularjs but is not working
```<code>/*service */
 app.service('sharedProperties', function () {
        var property = 'First';

        return {
            getProperty: function () {
                return property;
            },
            setProperty: function(value) {
                property = value;
            }
        };
    });

/*first contoller */
app.controller('loginCtrl',function($scope,$location,$http,$window,sharedProperties){
    $scope.submit =function(){
        var username=$scope.username;
        var pass=$scope.password;
      sharedProperties.setProperty(username);

 $location.path('/userdashboard');
 $window.location.reload();
            });
        }
    });

/*second controller*/
app.controller('empController', function($route,$scope,$http,$routeParams,sharedProperties){

    $scope.getEmployees = function(){

        alert( sharedProperties.getProperty());

     };
   };
</code>```

答:
You can assign members to $rootScope, which will store data globally for your app.  Just inject $rootScope to each controller.

For instance...

```<code> /*first controller */
app.controller('loginCtrl',function($scope,$rootScope,$location,$http,$window,sharedProperties){
            $scope.submit =function(){
                var username=$scope.username;
                var pass=$scope.password;
                $rootScope.username = username;

                $location.path('/userdashboard');
                $window.location.reload();
            });
        }
    });
</code>```

This will make 'username' available to any controller that injects and consumes $rootScope.

```<code>/*second controller*/
app.controller('empController', function($route,$scope,$rootScope,$http,$routeParams,sharedProperties){

    $scope.getEmployees = function(){
        alert($rootScope.username);
     };
   };
</code>```

Body:
You can assign members to $rootScope, which will store data globally for your app.  Just inject $rootScope to each controller.

For instance...

 /*first controller */
app.controller('loginCtrl',function($scope,$rootScope,$location,$http,$window,sharedProperties){
            $scope.submit =function(){
                var username=$scope.username;
                var pass=$scope.password;
                $rootScope.username = username;

                $location.path('/userdashboard');
                $window.location.reload();
            });
        }
    });

This will make 'username' available to any controller that injects and consumes $rootScope.

/*second controller*/
app.controller('empController', function($route,$scope,$rootScope,$http,$routeParams,sharedProperties){

    $scope.getEmployees = function(){
        alert($rootScope.username);
     };
   };


问:
UIImagePickerController Use Photo / Retake buttons don't work
I use default UIImagePickerController for taking photos / choosing them from a library. At some point, I present other ViewController over UIImagePickerController for customization of chosen photo. If a user selects Cancel option, I want to get him back to image choosing screen - in a case of camera source to screen with Use Photo / Retake buttons. After dismissing ViewController with customization buttons don't work (they work before).

I would rather not use AVFoundation here.

Here is some related code:

```<code>let storyBuilder = StoryBuilderViewController.storyboardController()

storyBuilder.delegate = self

photoPickerController.present(storyBuilder, animated: true)
</code>```

This way I'm presenting my customization screen.

```<code>func resetButtonTapped(_ storyBuilder: StoryBuilderViewController) {
    storyBuilder.dismiss(animated: true)
}
</code>```

This code runs after dismissing.

So, nothing special, but buttons stop working

View Hierarchy looks like this:

So, there is nothing over this screen. Buttons properties isEnabled set to true. UIImagePickerController isn't nil. isUserInteractionEnabled is true

I've created a simple project with this error. It doesn't work either.
Also, I've just had a case, when camera stops work entirely, even after app restart, with logs full of errors. Only restart of my phone helps.

More description

I have a start screen - RootViewController. I need to present UIImagePickerController with a camera over it. After a user makes a photo I need to present another controller - EditViewController (not dismissing UIImagePickerController, so if a user wants to take another photo - he just goes back). I do it like this:

```<code>picker(editController, animated: true) //picker - UIImagePickerController, editController - edit controller
</code>```

As I said before, my user can go back - and here is a problem - if I dismiss editController, buttons on UIImagePickerController don't work.

Please, ask some questions, I don't understand, why is it hard to get my issue correctly.

答:
I had Checked your demo code and make certain changes to make it work as you wants it.
1) Please check ViewController class code.

```<code>class ViewController: UIViewController {
    fileprivate var photoPickerController = UIImagePickerController()
    let notificationIdentifier: String = "StartCamera"

    override func viewDidLoad() {
        // Register to receive notification
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.cameraSetUp), name: NSNotification.Name(rawValue: notificationIdentifier), object: nil)
    }

    func cameraSetUp(){
        photoPickerController.sourceType = .camera
        photoPickerController.cameraDevice = .front
        photoPickerController.delegate = self
        present(photoPickerController, animated: true)

    }
    @IBAction func showCamera(_ sender: Any) {
        cameraSetUp()
    }
}

extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard let storyboard = storyboard else {return}
        let viewController = storyboard.instantiateViewController(withIdentifier: "EditingViewController")
        picker.dismiss(animated: true)
        present(viewController, animated: true)
    }

    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
}
</code>```

2) EditingViewController class code

```<code>class EditingViewController: UIViewController {
    let notificationIdentifier: String = "StartCamera"

    @IBAction func dismissButtonTapped(_ sender: Any) {
        // Post a notification
        dismiss(animated: true)
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: notificationIdentifier), object: nil)
    }
}
</code>```

Body:
I use default UIImagePickerController for taking photos / choosing them from a library. At some point, I present other ViewController over UIImagePickerController for customization of chosen photo. If a user selects Cancel option, I want to get him back to image choosing screen - in a case of camera source to screen with Use Photo / Retake buttons. After dismissing ViewController with customization buttons don't work (they work before).

I would rather not use AVFoundation here.

Here is some related code:

let storyBuilder = StoryBuilderViewController.storyboardController()

storyBuilder.delegate = self

photoPickerController.present(storyBuilder, animated: true)

This way I'm presenting my customization screen.

func resetButtonTapped(_ storyBuilder: StoryBuilderViewController) {
    storyBuilder.dismiss(animated: true)
}

This code runs after dismissing.

So, nothing special, but buttons stop working

View Hierarchy looks like this:

So, there is nothing over this screen. Buttons properties isEnabled set to true. UIImagePickerController isn't nil. isUserInteractionEnabled is true

I've created a simple project with this error. It doesn't work either.
Also, I've just had a case, when camera stops work entirely, even after app restart, with logs full of errors. Only restart of my phone helps.

More description

I have a start screen - RootViewController. I need to present UIImagePickerController with a camera over it. After a user makes a photo I need to present another controller - EditViewController (not dismissing UIImagePickerController, so if a user wants to take another photo - he just goes back). I do it like this:

picker(editController, animated: true) //picker - UIImagePickerController, editController - edit controller

As I said before, my user can go back - and here is a problem - if I dismiss editController, buttons on UIImagePickerController don't work.

Please, ask some questions, I don't understand, why is it hard to get my issue correctly.

Body:
I had Checked your demo code and make certain changes to make it work as you wants it.
1) Please check ViewController class code.

class ViewController: UIViewController {
    fileprivate var photoPickerController = UIImagePickerController()
    let notificationIdentifier: String = "StartCamera"

    override func viewDidLoad() {
        // Register to receive notification
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.cameraSetUp), name: NSNotification.Name(rawValue: notificationIdentifier), object: nil)
    }

    func cameraSetUp(){
        photoPickerController.sourceType = .camera
        photoPickerController.cameraDevice = .front
        photoPickerController.delegate = self
        present(photoPickerController, animated: true)

    }
    @IBAction func showCamera(_ sender: Any) {
        cameraSetUp()
    }
}

extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard let storyboard = storyboard else {return}
        let viewController = storyboard.instantiateViewController(withIdentifier: "EditingViewController")
        picker.dismiss(animated: true)
        present(viewController, animated: true)
    }

    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
}

2) EditingViewController class code

class EditingViewController: UIViewController {
    let notificationIdentifier: String = "StartCamera"

    @IBAction func dismissButtonTapped(_ sender: Any) {
        // Post a notification
        dismiss(animated: true)
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: notificationIdentifier), object: nil)
    }
}


问:
Load and manipulate on my page elements from different domain
I am trying to load in a div from my page the content of a different domain page.
I've tried to use <object> or , the content is loaded but I am not allowed to manipulate it with jQuery.
Also, I had the same error:

XMLHttpRequest cannot load 'URL'. No 'Access-Control-Allow-Origin'
  header is present on the requested resource. Origin
  'http://localhost:15297' is therefore not allowed access

, when I tried

```<code>$.get("URL", function (data) {
    $("#divID").append(data);
}
</code>```

Is there any work around to load and manipulate content from different domain page with jQuery?

答:
You need to organise connection between child and parent page using postMessage.

Seems like this lib could help you https://github.com/travist/seamless.js

Body:
I am trying to load in a div from my page the content of a different domain page.
I've tried to use <object> or , the content is loaded but I am not allowed to manipulate it with jQuery.
Also, I had the same error:

XMLHttpRequest cannot load 'URL'. No 'Access-Control-Allow-Origin'
  header is present on the requested resource. Origin
  'http://localhost:15297' is therefore not allowed access

, when I tried

$.get("URL", function (data) {
    $("#divID").append(data);
}

Is there any work around to load and manipulate content from different domain page with jQuery?


问:
How to check if a class has a specific base class in Matlab
I define in Matlab a class that's a subclass of another one, like this:

```<code>classdef SpecificLimit < BaseLimit

  % Private properties section
  properties (SetAccess = private, GetAccess = private)
    options;
  end

  % Public section
  methods (Access = public)
    % ...
  end
end
</code>```

Now I've a variable named r and I want to check if this variable is a class instance that has BaseLimit as base class (I've a lot of them). Is there an easy way to do that? I've read about meta.class but I didn't find a way to perform this check.

I'm using Matlab r2014a.

答:
You should use isa which determines if an object is either a BaseLimit instance or is derived from BaseLimit.

```<code>isa(r, 'BaseLimit')
</code>```

Body:
I define in Matlab a class that's a subclass of another one, like this:

classdef SpecificLimit < BaseLimit

  % Private properties section
  properties (SetAccess = private, GetAccess = private)
    options;
  end

  % Public section
  methods (Access = public)
    % ...
  end
end

Now I've a variable named r and I want to check if this variable is a class instance that has BaseLimit as base class (I've a lot of them). Is there an easy way to do that? I've read about meta.class but I didn't find a way to perform this check.

I'm using Matlab r2014a.

Body:
You should use isa which determines if an object is either a BaseLimit instance or is derived from BaseLimit.

isa(r, 'BaseLimit')


问:
Goodness-of-fit indices "NA"
I'm running a non-recursive model with Lavaan. However, 2 things happened that I didn't quite understand. First, gooodness-of-fit indices and some standard errors were "NA". Second, the two coefficients between two variables of different directions were not consistent (non-recursive part: ResidentialMobility--Author): one was positive, and another one was negative (at least they should be in the same direction; otherwise, how to explain?). Can someone help me out? Please let me know if you want me to clarify it more. Thanks!

```<code>model01<-'ResidentialMobility~a*Coun
SavingMotherPercentage~e*Affect
SavingMotherPercentage~f*Author
SavingMotherPercentage~g*Recipro

Affect~b*ResidentialMobility
Author~c*ResidentialMobility
Recipro~d*ResidentialMobility

ResidentialMobility~h*Affect
ResidentialMobility~i*Author
ResidentialMobility~j*Recipro

Affect~~Author+Recipro+ResidentialMobility
Author~~Recipro+ResidentialMobility
Recipro~~ResidentialMobility

Coun~SavingMotherPercentage

ab:=a*b
ac:=a*c
ad:=a*d

be:=b*e
cf:=c*f
dg:=d*g
'

fit <- cfa(model01, estimator = "MLR", data = data01, missing = "FIML")
summary(fit, standardized = TRUE, fit.measures = TRUE)
</code>```

Output:

lavaan (0.5-21) converged normally after  93 iterations

```<code>                                                  Used       Total
  Number of observations                           502         506

  Number of missing patterns                         4

  Estimator                                         ML      Robust
  Minimum Function Test Statistic                   NA          NA
  Degrees of freedom                                -2          -2
  Minimum Function Value               0.0005232772506
  Scaling correction factor
    for the Yuan-Bentler correction

User model versus baseline model:

  Comparative Fit Index (CFI)                       NA          NA
  Tucker-Lewis Index (TLI)                          NA          NA

Loglikelihood and Information Criteria:

  Loglikelihood user model (H0)              -5057.346   -5057.346
  Loglikelihood unrestricted model (H1)      -5057.084   -5057.084

  Number of free parameters                         29          29
  Akaike (AIC)                               10172.693   10172.693
  Bayesian (BIC)                             10295.032   10295.032
  Sample-size adjusted Bayesian (BIC)        10202.984   10202.984

Root Mean Square Error of Approximation:

  RMSEA                                             NA          NA
  90 Percent Confidence Interval             NA     NA          NA     NA
  P-value RMSEA <= 0.05                             NA          NA

Standardized Root Mean Square Residual:

  SRMR                                           0.006       0.006

Parameter Estimates:

  Information                                 Observed
  Standard Errors                   Robust.huber.white

Regressions:
                           Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
  ResidentialMobility ~
    Coun       (a)           -1.543    0.255   -6.052    0.000   -1.543   -0.540
  SavingMotherPercentage ~
    Affect     (e)            3.093    1.684    1.837    0.066    3.093    0.122
    Author     (f)            2.618    0.923    2.835    0.005    2.618    0.145
    Recipro    (g)            0.061    1.344    0.046    0.964    0.061    0.003
  Affect ~
    RsdntlMblt (b)           -0.311    0.075   -4.125    0.000   -0.311   -0.570
  Author ~
    RsdntlMblt (c)           -0.901    0.119   -7.567    0.000   -0.901   -1.180
  Recipro ~
    RsdntlMblt (d)           -0.313    0.082   -3.841    0.000   -0.313   -0.512
  ResidentialMobility ~
    Affect     (h)           -0.209    0.193   -1.082    0.279   -0.209   -0.114
    Author     (i)            0.475    0.192    2.474    0.013    0.475    0.363
    Recipro    (j)            0.178    0.346    0.514    0.607    0.178    0.109
  Coun ~
SvngMthrPr                0.003    0.001    2.225    0.026    0.003    0.108

Covariances:
                         Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
 .Affect ~~
   .Author                  0.667    0.171    3.893    0.000    0.667    0.534
   .Recipro                 0.669    0.119    5.623    0.000    0.669    0.773
 .ResidentialMobility ~~
   .Affect                  0.624    0.144    4.347    0.000    0.624    0.474
 .Author ~~
   .Recipro                 0.565    0.173    3.267    0.001    0.565    0.416
 .ResidentialMobility ~~
   .Author                  1.029    0.288    3.572    0.000    1.029    0.499
   .Recipro                 0.564    0.304    1.851    0.064    0.564    0.395

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
   .ResidentlMblty    1.813       NA                      1.813    1.270
   .SvngMthrPrcntg   29.591    7.347    4.027    0.000   29.591    1.499
   .Affect            5.701    0.169   33.797    0.000    5.701    7.320
   .Author            5.569    0.275   20.259    0.000    5.569    5.109
   .Recipro           5.149    0.186   27.642    0.000    5.149    5.889
   .Coun              0.367    0.069    5.336    0.000    0.367    0.735

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
   .ResidentlMblty    2.169    0.259    8.378    0.000    2.169    1.064
   .SvngMthrPrcntg  363.792   23.428   15.528    0.000  363.792    0.934
   .Affect            0.797    0.129    6.153    0.000    0.797    1.314
   .Author            1.957    0.343    5.713    0.000    1.957    1.647
   .Recipro           0.941    0.126    7.439    0.000    0.941    1.231
   .Coun              0.242    0.004   54.431    0.000    0.242    0.969

Defined Parameters:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
    ab                0.480    0.120    3.991    0.000    0.480    0.308
    ac                1.390    0.261    5.328    0.000    1.390    0.637
    ad                0.483    0.133    3.640    0.000    0.483    0.276
    be               -0.962    0.548   -1.757    0.079   -0.962   -0.070
    cf               -2.359    0.851   -2.771    0.006   -2.359   -0.171
    dg               -0.019    0.421   -0.046    0.964   -0.019   -0.001
</code>```

答: Why you get NA I think is because you have specified a model with -2 in degrees of freedom. You should specify the model differently so that you get a positive number of degrees of freedom.  </p>

Title: Goodness-of-fit indices "NA"

Body:
I'm running a non-recursive model with Lavaan. However, 2 things happened that I didn't quite understand. First, gooodness-of-fit indices and some standard errors were "NA". Second, the two coefficients between two variables of different directions were not consistent (non-recursive part: ResidentialMobility--Author): one was positive, and another one was negative (at least they should be in the same direction; otherwise, how to explain?). Can someone help me out? Please let me know if you want me to clarify it more. Thanks!

model01<-'ResidentialMobility~a*Coun
SavingMotherPercentage~e*Affect
SavingMotherPercentage~f*Author
SavingMotherPercentage~g*Recipro

Affect~b*ResidentialMobility
Author~c*ResidentialMobility
Recipro~d*ResidentialMobility

ResidentialMobility~h*Affect
ResidentialMobility~i*Author
ResidentialMobility~j*Recipro

Affect~~Author+Recipro+ResidentialMobility
Author~~Recipro+ResidentialMobility
Recipro~~ResidentialMobility

Coun~SavingMotherPercentage

ab:=a*b
ac:=a*c
ad:=a*d

be:=b*e
cf:=c*f
dg:=d*g
'

fit <- cfa(model01, estimator = "MLR", data = data01, missing = "FIML")
summary(fit, standardized = TRUE, fit.measures = TRUE)

Output:

lavaan (0.5-21) converged normally after  93 iterations

                                                  Used       Total
  Number of observations                           502         506

  Number of missing patterns                         4

  Estimator                                         ML      Robust
  Minimum Function Test Statistic                   NA          NA
  Degrees of freedom                                -2          -2
  Minimum Function Value               0.0005232772506
  Scaling correction factor
    for the Yuan-Bentler correction

User model versus baseline model:

  Comparative Fit Index (CFI)                       NA          NA
  Tucker-Lewis Index (TLI)                          NA          NA

Loglikelihood and Information Criteria:

  Loglikelihood user model (H0)              -5057.346   -5057.346
  Loglikelihood unrestricted model (H1)      -5057.084   -5057.084

  Number of free parameters                         29          29
  Akaike (AIC)                               10172.693   10172.693
  Bayesian (BIC)                             10295.032   10295.032
  Sample-size adjusted Bayesian (BIC)        10202.984   10202.984

Root Mean Square Error of Approximation:

  RMSEA                                             NA          NA
  90 Percent Confidence Interval             NA     NA          NA     NA
  P-value RMSEA <= 0.05                             NA          NA

Standardized Root Mean Square Residual:

  SRMR                                           0.006       0.006

Parameter Estimates:

  Information                                 Observed
  Standard Errors                   Robust.huber.white

Regressions:
                           Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
  ResidentialMobility ~
    Coun       (a)           -1.543    0.255   -6.052    0.000   -1.543   -0.540
  SavingMotherPercentage ~
    Affect     (e)            3.093    1.684    1.837    0.066    3.093    0.122
    Author     (f)            2.618    0.923    2.835    0.005    2.618    0.145
    Recipro    (g)            0.061    1.344    0.046    0.964    0.061    0.003
  Affect ~
    RsdntlMblt (b)           -0.311    0.075   -4.125    0.000   -0.311   -0.570
  Author ~
    RsdntlMblt (c)           -0.901    0.119   -7.567    0.000   -0.901   -1.180
  Recipro ~
    RsdntlMblt (d)           -0.313    0.082   -3.841    0.000   -0.313   -0.512
  ResidentialMobility ~
    Affect     (h)           -0.209    0.193   -1.082    0.279   -0.209   -0.114
    Author     (i)            0.475    0.192    2.474    0.013    0.475    0.363
    Recipro    (j)            0.178    0.346    0.514    0.607    0.178    0.109
  Coun ~
SvngMthrPr                0.003    0.001    2.225    0.026    0.003    0.108

Covariances:
                         Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
 .Affect ~~
   .Author                  0.667    0.171    3.893    0.000    0.667    0.534
   .Recipro                 0.669    0.119    5.623    0.000    0.669    0.773
 .ResidentialMobility ~~
   .Affect                  0.624    0.144    4.347    0.000    0.624    0.474
 .Author ~~
   .Recipro                 0.565    0.173    3.267    0.001    0.565    0.416
 .ResidentialMobility ~~
   .Author                  1.029    0.288    3.572    0.000    1.029    0.499
   .Recipro                 0.564    0.304    1.851    0.064    0.564    0.395

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
   .ResidentlMblty    1.813       NA                      1.813    1.270
   .SvngMthrPrcntg   29.591    7.347    4.027    0.000   29.591    1.499
   .Affect            5.701    0.169   33.797    0.000    5.701    7.320
   .Author            5.569    0.275   20.259    0.000    5.569    5.109
   .Recipro           5.149    0.186   27.642    0.000    5.149    5.889
   .Coun              0.367    0.069    5.336    0.000    0.367    0.735

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
   .ResidentlMblty    2.169    0.259    8.378    0.000    2.169    1.064
   .SvngMthrPrcntg  363.792   23.428   15.528    0.000  363.792    0.934
   .Affect            0.797    0.129    6.153    0.000    0.797    1.314
   .Author            1.957    0.343    5.713    0.000    1.957    1.647
   .Recipro           0.941    0.126    7.439    0.000    0.941    1.231
   .Coun              0.242    0.004   54.431    0.000    0.242    0.969

Defined Parameters:
                   Estimate  Std.Err  z-value  P(>|z|)   Std.lv  Std.all
    ab                0.480    0.120    3.991    0.000    0.480    0.308
    ac                1.390    0.261    5.328    0.000    1.390    0.637
    ad                0.483    0.133    3.640    0.000    0.483    0.276
    be               -0.962    0.548   -1.757    0.079   -0.962   -0.070
    cf               -2.359    0.851   -2.771    0.006   -2.359   -0.171
    dg               -0.019    0.421   -0.046    0.964   -0.019   -0.001


问:
query that will duplicate records based on quantity
I am using SQL Server 2008 and looking for a query that will duplicate records based on quantity

Table has QTY and PartNumber Columns. Need to add an additional record for each QTY.
So say a part number has a qty of 3. I need three rows with that partnumber.

Any Help would be greatly appreciated. Thank You.

答:
I wanted to do the same, and to make the function more useful, I created a table function based on the code example:

```<code>CREATE FUNCTION dbo.tfn_all_ints(@max_val integer)
RETURNS @retTable TABLE
 (
  val INT
 )
BEGIN
/* returns @max_val rows with Vals 1 to @max_val */
/* limited to 99 because of the recursion limit  */
WITH CTE (Vals)
AS (
    SELECT 1
    UNION ALL
    SELECT 1 + Vals
    FROM CTE WHERE Vals < 99
   )

INSERT INTO @retTable(val)
SELECT Vals
FROM CTE C
WHERE Vals <= @max_val

RETURN
END
</code>```

call example:
    SELECT * FROM tfn_all_ints(2)

Body:
I wanted to do the same, and to make the function more useful, I created a table function based on the code example:

CREATE FUNCTION dbo.tfn_all_ints(@max_val integer)
RETURNS @retTable TABLE
 (
  val INT
 )
BEGIN
/* returns @max_val rows with Vals 1 to @max_val */
/* limited to 99 because of the recursion limit  */
WITH CTE (Vals)
AS (
    SELECT 1
    UNION ALL
    SELECT 1 + Vals
    FROM CTE WHERE Vals < 99
   )

INSERT INTO @retTable(val)
SELECT Vals
FROM CTE C
WHERE Vals <= @max_val

RETURN
END

call example:
    SELECT * FROM tfn_all_ints(2)


问:
Disable closeButton in 2nd ViewController
Im trying to disable the closeButton in my second ViewController "OptionsVC"

Here's what I tried:

```<code>self.view.window!.standardWindowButton(NSWindowButton.closeButton)!.isHidden = true
</code>```

Did that, got this:
EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0

Also tried

```<code>var button = view.window?.standardWindowButton(NSWindowButton.ZoomButton)
button?.isEnabled = false
</code>```

No changes

答: In order to disable a button, it should be initialized. Therefore, you will face problems disabling the button from another view controller. Try adding a boolean and on viewDidLoad() check the boolean and decide either to enable or disable the button.</p>

Body:
Im trying to disable the closeButton in my second ViewController "OptionsVC"

Here's what I tried:

self.view.window!.standardWindowButton(NSWindowButton.closeButton)!.isHidden = true

Did that, got this:
EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0

Also tried

var button = view.window?.standardWindowButton(NSWindowButton.ZoomButton)
button?.isEnabled = false

No changes


问:
Bootstrap tooltip for dynamically created element coming on second time
I am dynamically adding an image to a span with below jQuery.

I want to show bootstrap tooltip on image's mouse enter, tooltip coming but from second time.

```<code>   $('span').append('<img src="Edited-Message.png" data-toggle="tooltip" data-placement="right" class="EditedChat" title="Removed />');
</code>```

I am using following jQuery to add tooltip :-

```<code>$("body").on("mouseenter", "img.EditedChat", function () {
    $(this).tooltip();
});
</code>```

TIA.

答:
Bind on the image to reposition the tooltip when it has finished loading : </p>

```<code>$(img).load(function(){ $element.tooltipster('reposition') })
</code>```

Body:
I am dynamically adding an image to a span with below jQuery.

I want to show bootstrap tooltip on image's mouse enter, tooltip coming but from second time.

   $('span').append('');

I am using following jQuery to add tooltip :-

$("body").on("mouseenter", "img.EditedChat", function () {
    $(this).tooltip();
});

TIA.

Body:
Bind on the image to reposition the tooltip when it has finished loading :

$(img).load(function(){ $element.tooltipster('reposition') })


问:
Center navigation bar title vertically
I have a simple storyboard containing a navigation controller with a static table view controller. I have added a view controller and connected it to one of the cells via a push segue. One thing I have noticed is that the navigation bar title doesn't center properly vertically with the back button and UIBarButtonItem.
Here is an image of what it looks now.

Notice that it is all aligned to the bottom. What I want is, is a way to either move the title down or move the buttons up. If the buttons were moved up, the back button arrow should be moved as well, and allow to return to the main table view.

Here is the code I'm using to set the UIBarButtonItem font in the view controller (If it helps) :

[clearButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"ChalkboardSE-Regular" size:15], NSFontAttributeName, [UIColor whiteColor], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];

And here is what I'm using to set the font for the back button in the app delegate, didFinishLaunchingWithOptions::

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont fontWithName:@"ChalkboardSE-Regular" size:15]}forState:UIControlStateNormal];

答:
To move title down :

```<code>self.navigationController!.navigationBar.setTitleVerticalPositionAdjustmen(+Value, forBarMetrics: .Default)
</code>```

To move title up:

```<code>self.navigationController!.navigationBar.setTitleVerticalPositionAdjustmen(-Value, forBarMetrics: .Default)
</code>```

Title: Center navigation bar title vertically

Body:
To move title down :

self.navigationController!.navigationBar.setTitleVerticalPositionAdjustmen(+Value, forBarMetrics: .Default)

To move title up:

self.navigationController!.navigationBar.setTitleVerticalPositionAdjustmen(-Value, forBarMetrics: .Default)


问:
C# How to convert irregular date and time String into DateTime?
I have a program which converts a irregular date and time string into a system DateTime.

However as the system does not recognize irregular strings, the method .ParseExact, toDateTime and TryParse has not worked.

There are only 2 types of date time strings that the program needs to convert:

```<code> Thu Dec  9 05:12:42 2010
 Mon Dec 13 06:45:58 2010
</code>```

Please note that the single date has a double spacing which I have used the .replace method to convert the single date to Thu Dec 09 05:12:42 2010.

May someone please advise on the codes? Thanks!

The codes:

```<code>        String rb = re.Replace("  ", " 0");

        DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture);

        Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
</code>```

答:
I would really avoid regex and use what's already built-in .NET (TryParseExact method and date formats):</p>

```<code>DateTime result;
string dateToParse = "Thu Dec  9 05:12:42 2010";
string format = "ddd MMM d HH:mm:ss yyyy";

if (DateTime.TryParseExact(
    dateToParse,
    format,
    CultureInfo.InvariantCulture,
    DateTimeStyles.AllowWhiteSpaces,
    out result)
)
{
    // The date was successfully parsed => use the result here
}
</code>```

Body:
I have a program which converts a irregular date and time string into a system DateTime.

However as the system does not recognize irregular strings, the method .ParseExact, toDateTime and TryParse has not worked.

There are only 2 types of date time strings that the program needs to convert:

 Thu Dec  9 05:12:42 2010
 Mon Dec 13 06:45:58 2010

Please note that the single date has a double spacing which I have used the .replace method to convert the single date to Thu Dec 09 05:12:42 2010.

May someone please advise on the codes? Thanks!

The codes:

        String rb = re.Replace("  ", " 0");

        DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture);

        Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));

Body:
I would really avoid regex and use what's already built-in .NET (TryParseExact method and date formats):

DateTime result;
string dateToParse = "Thu Dec  9 05:12:42 2010";
string format = "ddd MMM d HH:mm:ss yyyy";

if (DateTime.TryParseExact(
    dateToParse,
    format,
    CultureInfo.InvariantCulture,
    DateTimeStyles.AllowWhiteSpaces,
    out result)
)
{
    // The date was successfully parsed => use the result here
}


问:
How to use page.php?id={id} routes on laravel
I'm rewriting an website in laravel, and for the sake of the SEO, I have to create some routes that will do a 301 redirect in case the visitor get to access the old style links of the website:

Using Laravel 5.4 + PHP 7.0

For example:

Old links: www.website.com/category.php?category={id}

will redirect to:

New Link: www.website.com/category/{category-name}

But when I create a route like this on laravel, it doesn't work:

```<code>Route::get('/category.php?category={id}', function ($id) {
 // Old route style, search new route and do the redirect.
});
</code>```

If I remove the "?" it kinda works, but then it won't target my old links, cause there's no "?" in the url.

Is this supported on laravel ?

If it isn't, what would be a good way to achieve this?

答:
make your route like this and pass the category id. for example I have taken that 10.

```<code><a href="www.website.com/category.php?category=10">button</a>
</code>```

and take id from the request object.

```<code>Route::get('/category.php', function (\Illuminate\Http\Request $request) {
    $id = $request->category;
    // Old route style, search new route and do the redirect.
});
</code>```

Body:
I'm rewriting an website in laravel, and for the sake of the SEO, I have to create some routes that will do a 301 redirect in case the visitor get to access the old style links of the website:

Using Laravel 5.4 + PHP 7.0

For example:

Old links: www.website.com/category.php?category={id}

will redirect to:

New Link: www.website.com/category/{category-name}

But when I create a route like this on laravel, it doesn't work:

Route::get('/category.php?category={id}', function ($id) {
 // Old route style, search new route and do the redirect.
});

If I remove the "?" it kinda works, but then it won't target my old links, cause there's no "?" in the url.

Is this supported on laravel ?

If it isn't, what would be a good way to achieve this?

Body:
make your route like this and pass the category id. for example I have taken that 10.

<a href="www.website.com/category.php?category=10">button</a>

and take id from the request object.

Route::get('/category.php', function (\Illuminate\Http\Request $request) {
    $id = $request->category;
    // Old route style, search new route and do the redirect.
});


问:
ReactJS not rerendering after setState
I have a simple ReactJS application that loads a list of users and shows a record for each user.

This is the component handling the loading of the users and showing them in a list, while the UserCard component will visualize the user information and allow for edits.

```<code>export default class UserManager extends React.Component {
constructor() {
    super();

    this.state = {
        users:[]
    };
};

componentDidMount() {
    this.loadUsers();
};

loadUsers() {
    $.getJSON('/api/users').then((data) => {
        this.setState({ users: data.items });
    });
};

render() {
    return (
        <div className="animated fadeIn">
            <div className="row">
                <div className="col-sm-8 col-md-10">
                    <div id="userslist" className="userlist" >
                        {
                            this.state.users.map((user) => {
                                <UserCard user={user} />
                            })
                        }
                    </div>
                </div>
            </div>
        </div>
    )
}
</code>```

}

I load the users on componentDidMount, and the api call returns successfully with all user data. The rendering of the users is however not triggered. The list will remain empty.

Am I missing something here? Do I have to trigger the rendering manually again?

答:
Return the UserCard component from map body, if you don't return anything then, it will return undefined by default:

```<code><div id="userslist" className="userlist" >
    {
        this.state.users.map((user) => {
            return  <UserCard user={user} />
        })
    }
</div>
</code>```

Or write it like this without using {} because, you just want to return a component without any calculation or condition so {} is not required:

```<code><div id="userslist" className="userlist" >
    {
        this.state.users.map((user,i) => <UserCard key={i} user={user} /> )
    }
</div>
</code>```

Assign the unique key to each UserCard.

Title: ReactJS not rerendering after setState

Body:
I have a simple ReactJS application that loads a list of users and shows a record for each user.

This is the component handling the loading of the users and showing them in a list, while the UserCard component will visualize the user information and allow for edits.

export default class UserManager extends React.Component {
constructor() {
    super();

    this.state = {
        users:[]
    };
};

componentDidMount() {
    this.loadUsers();
};

loadUsers() {
    $.getJSON('/api/users').then((data) => {
        this.setState({ users: data.items });
    });
};

render() {
    return (

                        {
                            this.state.users.map((user) => {
                                <UserCard user={user} />
                            })
                        }

    )
}

}

I load the users on componentDidMount, and the api call returns successfully with all user data. The rendering of the users is however not triggered. The list will remain empty.

Am I missing something here? Do I have to trigger the rendering manually again?

Body:
Return the UserCard component from map body, if you don't return anything then, it will return undefined by default:

<div id="userslist" className="userlist" >
    {
        this.state.users.map((user) => {
            return  <UserCard user={user} />
        })
    }
</div>

Or write it like this without using {} because, you just want to return a component without any calculation or condition so {} is not required:

<div id="userslist" className="userlist" >
    {
        this.state.users.map((user,i) => <UserCard key={i} user={user} /> )
    }
</div>

Assign the unique key to each UserCard.


问:
How to call a method from another method in the same class (java)
I've been trying to understand how to call a method from inside another method of the same class by reading "Java how to program early objects".

I'm totally lost at the moment, the analogy used in the book makes it easy to visualise whats going on. However, translating that into code is challenging.

I have tried many times to figure this out and have gotten this far:
P.S. for the sake of simplicity I have excluded code that I think is not important for my question...

```<code>import java.util.Scanner;

public class BuyAHouseInc
{
    private int housePrice;
    private int amountOfHouses;
    private int houseCounter;

    // method to enter the amount of houses on sale
    public void setAmountOfHouses()
    {
        // do stuff etc.
    }

    // method that sets the house price
    public void setHousePrice()
    {
        // do stuff etc.

        calculateFees(this.housePrice); // this is where I'm not sure...
    }

    //method to calculate fees and taxes
    public void calculateFees(int housePrice) // does this receive this.housePrice?
    {
      // do some stuff
    }
</code>```

Tester code:

```<code>public class BuyAHouseIncTester
{
    public static void main(String[] args)
    {
        BuyAHouseInc client1 = new BuyAHouseInc("John","Doyle","15 Newton Drive\nDublin 5\n", 550000) // Create object
        // set amount of houses on sale to client 1
        client1.setAmountOfHouses();

        // set house price for each of the houses added to database
        client1.setHousePrice();
    }
}
</code>```

What is the code to call a method inside another method? Do the values of each individual house price get called?

答:
Please correct me if I'm wrong but is this a possible solution:

```<code>public void setHousePrice(int price)
{

    calculateFees(price);
}

public void calculateFees(int housePrice)
{
  // stuff with housePrice
}
</code>```

then do

```<code>variable.setHousePrice(variable.getHousePrice);
</code>```

Body:
I've been trying to understand how to call a method from inside another method of the same class by reading "Java how to program early objects".

I'm totally lost at the moment, the analogy used in the book makes it easy to visualise whats going on. However, translating that into code is challenging.

I have tried many times to figure this out and have gotten this far:
P.S. for the sake of simplicity I have excluded code that I think is not important for my question...

import java.util.Scanner;

public class BuyAHouseInc
{
    private int housePrice;
    private int amountOfHouses;
    private int houseCounter;

    // method to enter the amount of houses on sale
    public void setAmountOfHouses()
    {
        // do stuff etc.
    }

    // method that sets the house price
    public void setHousePrice()
    {
        // do stuff etc.

        calculateFees(this.housePrice); // this is where I'm not sure...
    }

    //method to calculate fees and taxes
    public void calculateFees(int housePrice) // does this receive this.housePrice?
    {
      // do some stuff
    }

Tester code:

public class BuyAHouseIncTester
{
    public static void main(String[] args)
    {
        BuyAHouseInc client1 = new BuyAHouseInc("John","Doyle","15 Newton Drive\nDublin 5\n", 550000) // Create object
        // set amount of houses on sale to client 1
        client1.setAmountOfHouses();

        // set house price for each of the houses added to database
        client1.setHousePrice();
    }
}

What is the code to call a method inside another method? Do the values of each individual house price get called?

Body:
Please correct me if I'm wrong but is this a possible solution:

public void setHousePrice(int price)
{

    calculateFees(price);
}

public void calculateFees(int housePrice)
{
  // stuff with housePrice
}

then do

variable.setHousePrice(variable.getHousePrice);


问:
Reusing Task<T> in .NET core/.NET Standard
Is it possible to reuse the same Task<T> created with Task.FromResult for instant returning methods (as it is completed already anyway)?

My reasoning behind the question is to reduce garbage produced by implementations of async interfaces that complete instantly (Task<bool> would be a great example for it, as it only has two possible values).

Base on this article about disposing of tasks, it should be possible, if .NET Core behaves the same (does it?).

答:
Yes, and this is actually strongly recommended in cases where you have a small set of likely results that might be known synchronously (from cache, etc). Likewise, in the case of Task (not Task<T>), Task.CompletedTask can be used.

Note that if most of your calls complete synchronously but you do not have a small domain of likely results, you might want to consider ValueTask<T>, which is optimized for this case.

Everything here applies equally to both .NET and .NET Core.