问:
It's showing unreachable statement error
I'm trying to make a toast on item selected but it's showing unreachable statement error.

My code is:

```<code>btn=(Button)findViewById(R.id.button);
    btn.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  btn.performLongClick();
                }
            }
    );
    registerForContextMenu(btn);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("For Optimum Results");
    menu.add(0,v.getId(),0,"Hi");
    menu.add(0,v.getId(),0,"Hello");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    return super.onContextItemSelected(item);
    if(item.getTitle()=="Hi"){
        Toast.makeText(this,"hi",Toast.LENGTH_SHORT).show();

    }
return true;
}
</code>```

答:
you have two type of error:

1)return super (return super.onContextItemSelected(item)) , it means that you return your method at first line so lines below not execute.

2)wrong comparing String (item.getTitle()=="Hi")

correct code should be like this:

```<code>@Override
public boolean onContextItemSelected(MenuItem item) {
   //return super.onContextItemSelected(item);//remove this line
   if(item.getTitle().equal("Hi")){// also maybe you want to check not null for item.getTitle()
       Toast.makeText(this,"hi",Toast.LENGTH_SHORT).show();
   }
   return true;
}
</code>```

Body:
I'm trying to make a toast on item selected but it's showing unreachable statement error.

My code is:

btn=(Button)findViewById(R.id.button);
    btn.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  btn.performLongClick();
                }
            }
    );
    registerForContextMenu(btn);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("For Optimum Results");
    menu.add(0,v.getId(),0,"Hi");
    menu.add(0,v.getId(),0,"Hello");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    return super.onContextItemSelected(item);
    if(item.getTitle()=="Hi"){
        Toast.makeText(this,"hi",Toast.LENGTH_SHORT).show();

    }
return true;
}

Body:
you have two type of error:

1)return super (return super.onContextItemSelected(item)) , it means that you return your method at first line so lines below not execute.

2)wrong comparing String (item.getTitle()=="Hi")

correct code should be like this:

@Override
public boolean onContextItemSelected(MenuItem item) {
   //return super.onContextItemSelected(item);//remove this line
   if(item.getTitle().equal("Hi")){// also maybe you want to check not null for item.getTitle()
       Toast.makeText(this,"hi",Toast.LENGTH_SHORT).show();
   }
   return true;
}


来源: stackexchange

问:
React Native dynamically require(images)
I'm programming an App similar to coinmarketcap.com.
A giant list of up to 700 coins and icons etc in a SectionList. But in my App, you can choose which coins you wanna track.

Is there a way to not require ALL 700 icons but just selected ones ?
Right now I have an objects.js file with:

```<code>export const IMAGES = {
  'btc-usd': require('../icons/bitcoin.png'), //statically analyzed
  'eth-usd': require('../icons/ether.png'),
   ...
</code>```

But I'm worried about memory and performance. Does React load them all in RAM ? Or just when it renders ?
Thanks a lot for helping

Found this solution but not sure if it is technically more efficient:

A simple solution I found was creating a very minimalistic
  package.json inside the top-most folder you want to absolutely import
  from. That package.json should look like this: { "name": "src" },
  where "src" is the name of that folder.

The you can simply do import X from 'src/X.js' just as you would
  normally do.

Source

Thanks a lot for helping!

答: Have you tried using a FlatList? It will only render items in view as well as a few items ahead. It should give you the performance boost you seek. As for lazily requiring/loading images, maybe use a package like react-native-lazyload.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm programming an App similar to coinmarketcap.com.
A giant list of up to 700 coins and icons etc in a SectionList. But in my App, you can choose which coins you wanna track.

Is there a way to not require ALL 700 icons but just selected ones ?
Right now I have an objects.js file with:

export const IMAGES = {
  'btc-usd': require('../icons/bitcoin.png'), //statically analyzed
  'eth-usd': require('../icons/ether.png'),
   ...

But I'm worried about memory and performance. Does React load them all in RAM ? Or just when it renders ?
Thanks a lot for helping

Found this solution but not sure if it is technically more efficient:

A simple solution I found was creating a very minimalistic
  package.json inside the top-most folder you want to absolutely import
  from. That package.json should look like this: { "name": "src" },
  where "src" is the name of that folder.

The you can simply do import X from 'src/X.js' just as you would
  normally do.

Source

Thanks a lot for helping!


问:
Open PDF file on certain page iOS
Is it possible to open PDF file on certain page with UIDocumentInteractionController?

I'm trying to append #page=3 at the end of the file address string but it is not working when I try to do:

```<code>NSString* pdf = [fileName stringByAppendingString:@"#page=3"];

NSURL *URL = [[NSURL alloc] initFileURLWithPath:pdf];
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];
</code>```

Maybe there is another way to do this?

答:
Now, with Swift 4 and PDFKit we can do the following:</p>

```<code>var pdfView: PDFView!

override func viewDidLoad() {
    super.viewDidLoad()

    pdfView = PDFView()
    // You might want to constraint pdfView here

    // Load pdf from bundle or url
    let url = Bundle.main.url(forResource: "test", withExtension: "pdf")!
    let document = PDFDocument(url: url)
    pdfView.document = document

    // Grab 10th page, returns optional if out of bounds
    if let page10 = document?.page(at: 10) {
        pdfView.go(to: page10)
    }

}
</code>```

Title: Open PDF file on certain page iOS

Body:
Is it possible to open PDF file on certain page with UIDocumentInteractionController?

I'm trying to append #page=3 at the end of the file address string but it is not working when I try to do:

NSString* pdf = [fileName stringByAppendingString:@"#page=3"];

NSURL *URL = [[NSURL alloc] initFileURLWithPath:pdf];
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];

Maybe there is another way to do this?

Body:
Now, with Swift 4 and PDFKit we can do the following:

var pdfView: PDFView!

override func viewDidLoad() {
    super.viewDidLoad()

    pdfView = PDFView()
    // You might want to constraint pdfView here

    // Load pdf from bundle or url
    let url = Bundle.main.url(forResource: "test", withExtension: "pdf")!
    let document = PDFDocument(url: url)
    pdfView.document = document

    // Grab 10th page, returns optional if out of bounds
    if let page10 = document?.page(at: 10) {
        pdfView.go(to: page10)
    }

}


问:
Call a SQL Server stored proc with parameters in PHP
Based on this :

how to execute sql server stored procedure on php?

Tried the following :

```<code>$odbc = odbc_connect($DB1_ODBC,$DB1_USER,$DB1_PWD);  // proven to be fully functionnal
$result = odbc_exec($odbc,"CALL importClient( @name = 'hello',@number = 457)");
</code>```

It does not call the stored procedure, i can't see any error code.

I replaced "CALL by "EXEC but it's not working in either cases.

Otherwise, the stored procedure can be run by using the same credentials to connect to the database, and using this SQL statement :

```<code>EXECUTE [dbo].[importClient] @name = 'hello',@number = 457
</code>```

I couldn't find anything helpful, neither think of another way, and I definitely need the parameters.

答:
It finally worked with :

```<code>$result = odbc_exec($odbc,"EXECUTE importClient @name = 'hello', @number = 457");
</code>```

But this isn't protected against SQL injections, so it might not be the best answer

Body:
Based on this :

how to execute sql server stored procedure on php?

Tried the following :

$odbc = odbc_connect($DB1_ODBC,$DB1_USER,$DB1_PWD);  // proven to be fully functionnal
$result = odbc_exec($odbc,"CALL importClient( @name = 'hello',@number = 457)");

It does not call the stored procedure, i can't see any error code.

I replaced "CALL by "EXEC but it's not working in either cases.

Otherwise, the stored procedure can be run by using the same credentials to connect to the database, and using this SQL statement :

EXECUTE [dbo].[importClient] @name = 'hello',@number = 457

I couldn't find anything helpful, neither think of another way, and I definitely need the parameters.

Body:
It finally worked with :

$result = odbc_exec($odbc,"EXECUTE importClient @name = 'hello', @number = 457");

But this isn't protected against SQL injections, so it might not be the best answer


答:
I can also do this by creating the dataframe as a temp view and then do select case statement. Like this,

```<code>df1.createTempView("df1")
df2.createTempView("df2")
df3.createTempView("df3")

select case when df1.val1=df2.val1 and df1.val1<>df3.val1 then df3.val1 end
</code>```

This is much faster.

Title: spark scala dataframe merge multiple dataframes

Body:
I have three files coming in,

## +---+----+----+---+
## |pk1|pk2|val1|val2|
## +---+----+----+---+
## |  1| aa|  ab|  ac|
## |  2| bb|  bc|  bd|
## +---+----+----+---+

## +---+----+----+---+
## |pk1|pk2|val1|val2|
## +---+----+----+---+
## |  1| aa|  ab|  ad|
## |  2| bb|  bb|  bd|
## +---+----+----+---+

## +---+----+----+---+
## |pk1|pk2|val1|val2|
## +---+----+----+---+
## |  1| aa|  ac|  ad|
## |  2| bb|  bc|  bd|
## +---+----+----+---+

I need to compare the first two files (which I'm reading as dataframe) and identify only the changes and then merge with the third file, so my output should be,

## +---+----+----+---+
## |pk1|pk2|val1|val2|
## +---+----+----+---+
## |  1| aa|  ac|  ad|
## |  2| bb|  bb|  bd|
## +---+----+----+---+

How to pick only the changed columns? and update another dataframe?

Body:
I can also do this by creating the dataframe as a temp view and then do select case statement. Like this,

df1.createTempView("df1")
df2.createTempView("df2")
df3.createTempView("df3")

select case when df1.val1=df2.val1 and df1.val1<>df3.val1 then df3.val1 end

This is much faster.


问:
Execute internal server script in grafana
I would like to know how to execute a script in response to an alert in Grafana.

I want to execute the script in a shell when the temperature is greater than 25C. The script connects to an ESX server and turns off all VM's.

I've created the script that connects to the ESX server, but I'm not sure how to call it from Grafana.

答:
Use the Alert Webhook notifier. It sends a json document to the webhook url every time an alert is triggered.

You will need to build some sort of backend service (in any language/web framework) that can listen to HTTP requests. This service would take in the JSON document, parse it and then shell out to execute your script.


问:
How to use java bean in ReactJS to handle run time values and events inside the bean?Is it possible?
Please let me know if there is anyway of using a java bean inside react js. I wish to handle all the events and valuechange listeners inside the bean.Also the data model to store the values of the components in the JS.</p>

答: There is no point to implementing java beans in React, there is no actual notion of privacy in javascript. Java beans is only a concept for data control within classes, specifically in Java.</p>


问:
Recieving cookie in angular from php response
I've been trying to retrieve cookie from php for awhile.

from php I have this method:

```<code>public function created()
{
  $datetime = date_create()->format('Y-m-d H:i:s');
  $json =file_get_contents('php://input');
  var_dump($json);
  $decoded = json_decode($json, true);
  $cookie="";
  $obj=new \stdClass();

  if($decoded['cookie']==""){
    $cookie=$random = rand(1,1000);
    setcookie( "cookie", "$cookie", time() + (10 * 365 * 24 * 60 * 60), "/", "http://localhost" );
  }
  else{
    $cookie=$decoded['cookie'];
  }

        $user=[
            'name'=>$decoded['name'],
            'surname'=>$decoded['surname'],
            'email'=>$decoded['email'],
            'review'=>$decoded['review'],
            'time'=>$datetime,
            'cookie'=>$cookie,
        ];
  $obj->cookie=$cookie;
  DatabaseModel::newuser($user);
  //return response()->json($cookie);
}
</code>```

which creates cookie if none exists and I see it in my response headers. (Don't pay attention to how I create cookie for now, I now rand() function is not the right way, it's just for testing)

In my angular side I have :

```<code>function PostReview(JSONObject) {
        if (JSONObject != null) {
            debugger;

            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json"

                },

            })
                .then(function (data) {

                    console.log(data.headers('Set-cookie'));

                }, function (data) {
                    console.log(data.headers('Set-cookie'));
                });
        }

    }
</code>```

I would like to post my JSON object and recieve cookie with response. However I am quite stuck. I tried with .success() but it's deprecated, so I am using .then() , but then I print console.log(data.headers('Set-cookie')); I get null result. Does anybody ever had similar problem?

I also tried:

```<code>.then(function (data, status, headers, config) {

                    console.log(headers('Set-cookie'));

                }, function (data, status, headers, config) {
                    console.log(headers('Set-cookie'));
                });
</code>```

and:

```<code>.then(function(response) {
                    if (response.data == 'ok') {
                        $cookies['X-AUTH-TOKEN']=response.headers('X-AUTH-TOKEN');
                        // below put,put,putObject Cookies value is valid for Angular version >= 1.4
                       var $cookie= $cookies.putObject('X-AUTH-TOKEN',response.headers('X-AUTH-TOKEN'));
                        console.log($cookie);
                        debugger;

                    }

                });
</code>```

but none of them worked. What problem could it be?

My client side:

```<code>function PostReview(JSONObject) {
        if (JSONObject != null) {
            debugger;

            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json"
                }

            })
        }
    }
</code>```

in my controllers:

```<code>$scope.Cookie = $cookies.get('cookie');
    $scope.$watch('Cookie', function() {
        $scope.Cookie = $cookies.get('cookie');
    });
</code>```

WHhat about cross-domain cookies?

答:
I found a way to my problem, it may be not the best way to solve it, but if anyone runs into the same problem it will probably help.

```<code>function PostReview(JSONObject) {
        if (JSONObject != null) {
            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json",
                    "crossDomain": true,
                    "withCredentials": true
                }

            }).then(function (response) {
            if(response.data.cookie_value===undefined){
                var info = JSON.parse(JSONObject);
                console.log(info.cookie);
                $cookies.put('userCookie', info.cookie);

            }
            else{
                console.log(response.data.cookie_value);
                $cookies.put('userCookie', response.data.cookie_value);
            }
            $rootScope.savedInfo=JSON.parse(JSONObject);
        });
        }
    }
</code>```

I set cookie from response method if none exists, if it exists, then I use value from my json object.

In php side I check if cookie which I sent is empty, if it is, then I create cookie. Doesn't seem that hard, but I spent so much time on this.

```<code>public function created()
{
    $date = new DateTime();
    $date->setTimeZone(new DateTimeZone("Europe/Vilnius"));
    $get_datetime = $date->format('d.m.Y H:i:s');

  $datetime = date_create()->format('Y-m-d H:i:s');
  $json =file_get_contents('php://input');
  $decoded = json_decode($json, true);
  $cookie="";
  $obj=new \stdClass();

  if($decoded['cookie']==" "){
    $cookie_name = "user";
    $cookie_value =$random = md5(rand(1,1000));
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
    $_COOKIE[$cookie_name]=$cookie_value;
    $obj->cookie_value=$cookie_value;
  }
  else{
   $cookie_value=$decoded['cookie'];
  }

        $user=[
            'name'=>$decoded['name'],
            'surname'=>$decoded['surname'],
            'email'=>$decoded['email'],
            'review'=>$decoded['review'],
            'time'=>$datetime,
            'cookie'=>$cookie_value,
        ];
//  $obj->cookie=$cookie;
  DatabaseModel::newuser($user);

     return response()->json( $obj);
}
</code>```

Body:
I've been trying to retrieve cookie from php for awhile.

from php I have this method:

public function created()
{
  $datetime = date_create()->format('Y-m-d H:i:s');
  $json =file_get_contents('php://input');
  var_dump($json);
  $decoded = json_decode($json, true);
  $cookie="";
  $obj=new \stdClass();

  if($decoded['cookie']==""){
    $cookie=$random = rand(1,1000);
    setcookie( "cookie", "$cookie", time() + (10 * 365 * 24 * 60 * 60), "/", "http://localhost" );
  }
  else{
    $cookie=$decoded['cookie'];
  }

        $user=[
            'name'=>$decoded['name'],
            'surname'=>$decoded['surname'],
            'email'=>$decoded['email'],
            'review'=>$decoded['review'],
            'time'=>$datetime,
            'cookie'=>$cookie,
        ];
  $obj->cookie=$cookie;
  DatabaseModel::newuser($user);
  //return response()->json($cookie);
}

which creates cookie if none exists and I see it in my response headers. (Don't pay attention to how I create cookie for now, I now rand() function is not the right way, it's just for testing)

In my angular side I have :

function PostReview(JSONObject) {
        if (JSONObject != null) {
            debugger;

            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json"

                },

            })
                .then(function (data) {

                    console.log(data.headers('Set-cookie'));

                }, function (data) {
                    console.log(data.headers('Set-cookie'));
                });
        }

    }

I would like to post my JSON object and recieve cookie with response. However I am quite stuck. I tried with .success() but it's deprecated, so I am using .then() , but then I print console.log(data.headers('Set-cookie')); I get null result. Does anybody ever had similar problem?

I also tried:

.then(function (data, status, headers, config) {

                    console.log(headers('Set-cookie'));

                }, function (data, status, headers, config) {
                    console.log(headers('Set-cookie'));
                });

and:

.then(function(response) {
                    if (response.data == 'ok') {
                        $cookies['X-AUTH-TOKEN']=response.headers('X-AUTH-TOKEN');
                        // below put,put,putObject Cookies value is valid for Angular version >= 1.4
                       var $cookie= $cookies.putObject('X-AUTH-TOKEN',response.headers('X-AUTH-TOKEN'));
                        console.log($cookie);
                        debugger;

                    }

                });

but none of them worked. What problem could it be?

My client side:

function PostReview(JSONObject) {
        if (JSONObject != null) {
            debugger;

            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json"
                }

            })
        }
    }

in my controllers:

$scope.Cookie = $cookies.get('cookie');
    $scope.$watch('Cookie', function() {
        $scope.Cookie = $cookies.get('cookie');
    });

WHhat about cross-domain cookies?

Body:
I found a way to my problem, it may be not the best way to solve it, but if anyone runs into the same problem it will probably help.

function PostReview(JSONObject) {
        if (JSONObject != null) {
            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json",
                    "crossDomain": true,
                    "withCredentials": true
                }

            }).then(function (response) {
            if(response.data.cookie_value===undefined){
                var info = JSON.parse(JSONObject);
                console.log(info.cookie);
                $cookies.put('userCookie', info.cookie);

            }
            else{
                console.log(response.data.cookie_value);
                $cookies.put('userCookie', response.data.cookie_value);
            }
            $rootScope.savedInfo=JSON.parse(JSONObject);
        });
        }
    }

I set cookie from response method if none exists, if it exists, then I use value from my json object.

In php side I check if cookie which I sent is empty, if it is, then I create cookie. Doesn't seem that hard, but I spent so much time on this.

public function created()
{
    $date = new DateTime();
    $date->setTimeZone(new DateTimeZone("Europe/Vilnius"));
    $get_datetime = $date->format('d.m.Y H:i:s');

  $datetime = date_create()->format('Y-m-d H:i:s');
  $json =file_get_contents('php://input');
  $decoded = json_decode($json, true);
  $cookie="";
  $obj=new \stdClass();

  if($decoded['cookie']==" "){
    $cookie_name = "user";
    $cookie_value =$random = md5(rand(1,1000));
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
    $_COOKIE[$cookie_name]=$cookie_value;
    $obj->cookie_value=$cookie_value;
  }
  else{
   $cookie_value=$decoded['cookie'];
  }

        $user=[
            'name'=>$decoded['name'],
            'surname'=>$decoded['surname'],
            'email'=>$decoded['email'],
            'review'=>$decoded['review'],
            'time'=>$datetime,
            'cookie'=>$cookie_value,
        ];
//  $obj->cookie=$cookie;
  DatabaseModel::newuser($user);

     return response()->json( $obj);
}


问:
CSS: Help with position relative/absolute
I have a main menu bar at the top of my page. Now my #LinkToMenu fails at resizing and such, even if there's an position: relative. But it work fine if I set a specific width on the #mainmenu style, which I don't want it to. I even tried width: auto, with no luck.

```<code><div id="mainmenu" style="position: relative;">

<div id="LinkToMenu" style="position: absolute; right: 130px; top: 10px;">
  <a href="home.php">Home</a>
</div>

<img src="images/mainmenu_logo3.png" style="position: absolute; top: 2px; left: 210px; ">
</code>```

What's the problem? How can I solve this?

The image with nearly same settings works fine at resizing and so, but not the barlinks?

答: #mainmenu effectively has no content - it's two children are position:absolute,  so are removed from the normal flow.  As is,  a DIV element is a block,  so should expand to the full width of the container,  although won't have any height.

ContentLicense: CC BY-SA 2.5

Body:
I have a main menu bar at the top of my page. Now my #LinkToMenu fails at resizing and such, even if there's an position: relative. But it work fine if I set a specific width on the #mainmenu style, which I don't want it to. I even tried width: auto, with no luck.

  Home

What's the problem? How can I solve this?

The image with nearly same settings works fine at resizing and so, but not the barlinks?


问:
How to switch between pages with Xamarin.Forms.INavigation.InsertPageBefore
I'm using Xamarin Forms and I'm having an issue use InsertPageBefore() method with existing objects of Pages.

Here is my view code:

```<code>private FirstPage firstPage;
private SecondPage secondPage = new SecondPage();
private ThirdPage thirdPage = new ThirdPage();
private async void ItemSelectedMethod()
{
        var root = App.NavigationPage.Navigation.NavigationStack[0];
        if (SelectedItem == Items[0])
        {
            if (!IsFirstChoose)
            {
                App.NavigationPage.Navigation.InsertPageBefore(firstPage, root);
                await App.NavigationPage.PopToRootAsync(false);
            }
        }
        if (SelectedItem == Items[1])
        {
            App.NavigationPage.Navigation.InsertPageBefore(secondPage, root);
            await App.NavigationPage.PopToRootAsync(false);
        }
        if (SelectedItem == Items[2])
        {
            App.NavigationPage.Navigation.InsertPageBefore(thirdPage, root);
            await App.NavigationPage.PopToRootAsync(false);
        }

        IsFirstChoose = false;
        rootPageViewModel.IsPresented = false;
}
</code>```

It's throw exception "System.ArgumentException: 'Cannot insert page which is already in the navigation stack'". How to switch between existing objects of pages? I don't want create new object in InsertPageBefore(). I tried use it code, before call InsertPageBefore():

```<code>foreach (var item in App.NavigationPage.Navigation.NavigationStack.ToList())
                App.NavigationPage.Navigation.RemovePage(item);
</code>```

But it's not working... Can anyone help me?

答:
It didn't work with UWP. Here is agly workaround for you but you really need to read how to work with Master-Detail pages.

```<code>public partial class App : Application
    {
        public static RootPage RootPage { get; private set; } //DON'T DO THIS,
                                                              //FIND A BETTER WAY
        public App()
        {
            InitializeComponent();

            RootPage = new RootPage();
            MenuPage menuPage = new MenuPage(RootPage.vm);

            RootPage.Master = menuPage;
            RootPage.Detail = new NavigationPage(new MainPage());// NavigationPage;
            MainPage = RootPage;
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
</code>```

Then

```<code>private async void ItemSelectedMethod()
        {

            if (SelectedItem == Items[0])
            {
                App.RootPage.Detail = new NavigationPage(mainPage);
            }
            if (SelectedItem == Items[1])
            {
                App.RootPage.Detail = new NavigationPage(secondPage);
            }
            if (SelectedItem == Items[2])
            {
                App.RootPage.Detail = new NavigationPage(thirdPage);
            }
            rootPageViewModel.IsPresented = false;
        }
</code>```

Body:
I'm using Xamarin Forms and I'm having an issue use InsertPageBefore() method with existing objects of Pages.

Here is my view code:

private FirstPage firstPage;
private SecondPage secondPage = new SecondPage();
private ThirdPage thirdPage = new ThirdPage();
private async void ItemSelectedMethod()
{
        var root = App.NavigationPage.Navigation.NavigationStack[0];
        if (SelectedItem == Items[0])
        {
            if (!IsFirstChoose)
            {
                App.NavigationPage.Navigation.InsertPageBefore(firstPage, root);
                await App.NavigationPage.PopToRootAsync(false);
            }
        }
        if (SelectedItem == Items[1])
        {
            App.NavigationPage.Navigation.InsertPageBefore(secondPage, root);
            await App.NavigationPage.PopToRootAsync(false);
        }
        if (SelectedItem == Items[2])
        {
            App.NavigationPage.Navigation.InsertPageBefore(thirdPage, root);
            await App.NavigationPage.PopToRootAsync(false);
        }

        IsFirstChoose = false;
        rootPageViewModel.IsPresented = false;
}

It's throw exception "System.ArgumentException: 'Cannot insert page which is already in the navigation stack'". How to switch between existing objects of pages? I don't want create new object in InsertPageBefore(). I tried use it code, before call InsertPageBefore():

foreach (var item in App.NavigationPage.Navigation.NavigationStack.ToList())
                App.NavigationPage.Navigation.RemovePage(item);

But it's not working... Can anyone help me?

Body:
It didn't work with UWP. Here is agly workaround for you but you really need to read how to work with Master-Detail pages.

public partial class App : Application
    {
        public static RootPage RootPage { get; private set; } //DON'T DO THIS,
                                                              //FIND A BETTER WAY
        public App()
        {
            InitializeComponent();

            RootPage = new RootPage();
            MenuPage menuPage = new MenuPage(RootPage.vm);

            RootPage.Master = menuPage;
            RootPage.Detail = new NavigationPage(new MainPage());// NavigationPage;
            MainPage = RootPage;
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }

Then

private async void ItemSelectedMethod()
        {

            if (SelectedItem == Items[0])
            {
                App.RootPage.Detail = new NavigationPage(mainPage);
            }
            if (SelectedItem == Items[1])
            {
                App.RootPage.Detail = new NavigationPage(secondPage);
            }
            if (SelectedItem == Items[2])
            {
                App.RootPage.Detail = new NavigationPage(thirdPage);
            }
            rootPageViewModel.IsPresented = false;
        }


问:
Bootstrap: Centering col-md-5?
I feel like this is a very weird question but I couldn't seem to find a solution online.

If I have a col-md-5, I can't seem to center it.
As far as I understood the grid system, if I choose a column size (1-12), in order to control the position of the column I use col-##-offset-#.

So if I have a col-md-4, I would use col-md-offset-4 to push it 4 columns from the left, and then it will be centered. The idea is that, to center a column, there must be the same amount of columns within the grid from the left of it and from the right of it.

Now, what if I have a, let's say, col-md-5? How can I center it?
Doing something like col-md-4 will leave 3 from the right. I tried several things but no success.

Thanks in advance.

答:
```<code><div class="col-md-10 col-md-offset-1">
    <div class="col-md-6 col-md-offset-3">
    </div>
</div>
</code>```

Title: Bootstrap: Centering col-md-5?


问:
How to delete a record in the polymorphic association in rails?
I have been following a polymorphic association example at this website
https://www.richonrails.com/articles/polymorphic-associations-in-rails#comments

unfortunately, the author did not provide a example of how to delete a interaction under either people model or business model.

I have interactions_controller.rb

```<code>def destroy
  @context = context
  @interaction = @context.interactions.find(params[:id])
  @interaction.destroy
end
</code>```

in routes.rb

```<code>resources :business do
  resources :interaction
end
</code>```

in businesses/1, show.html.erb, it has a list all interactions.

```<code><% link_to 'delete', business_interaction_path([@business, interaction]), method: :delete, data: {confirm: 'Are you sure?'} %>
</code>```

I tried to use this to delete an individual interaction, the error message told me that it could find the business.id number, but cannot find interaction.id number.

This is both polymorphic association and nested resources so I got confused.

Can you tell me what I did wrong? Please you must understand this tutorial first before answering? Thanks!

答:
```<code><% link_to 'delete', business_interaction_path(@business, interaction), method: :delete, data: {confirm: 'Are you sure?'} %>

def destroy
  @context = context
  @interaction = @context.interactions.find(params[:id])
  @interaction.destroy
  redirect_to context_url(context)
end
</code>```

I forgot to redirect_to correct page after deleting. This is why it keeps giving me a error message.

Body:
I have been following a polymorphic association example at this website
https://www.richonrails.com/articles/polymorphic-associations-in-rails#comments

unfortunately, the author did not provide a example of how to delete a interaction under either people model or business model.

I have interactions_controller.rb

def destroy
  @context = context
  @interaction = @context.interactions.find(params[:id])
  @interaction.destroy
end

in routes.rb

resources :business do
  resources :interaction
end

in businesses/1, show.html.erb, it has a list all interactions.

<% link_to 'delete', business_interaction_path([@business, interaction]), method: :delete, data: {confirm: 'Are you sure?'} %>

I tried to use this to delete an individual interaction, the error message told me that it could find the business.id number, but cannot find interaction.id number.

This is both polymorphic association and nested resources so I got confused.

Can you tell me what I did wrong? Please you must understand this tutorial first before answering? Thanks!

Body:
<% link_to 'delete', business_interaction_path(@business, interaction), method: :delete, data: {confirm: 'Are you sure?'} %>

def destroy
  @context = context
  @interaction = @context.interactions.find(params[:id])
  @interaction.destroy
  redirect_to context_url(context)
end

I forgot to redirect_to correct page after deleting. This is why it keeps giving me a error message.


问:
Best way to route method calling from List in Java
What's definitely the best way to call a different method of a class according to a different object type in a List?

common example:

```<code>public class Dog extends Animals{
  ...
  public void say(){
    System.out("i'm a dog");
}

public class Cat extends Animals{
  ...
  public void say(){
    System.out("i'm a cat");
}

public class OtherClass {
  public void route(){
    List<Animals> aList = new ArrayList<>();
    a.add(new Dog());
    a.add(new Cat());
    for(Animals a:aList)
     methodOverloaded(a); ---> that's the point <---
  }
  public methodOverloaded(Dog d){
    d.say();
  }

  public methodOverloaded(Cat c){
    c.say();
 }
}
</code>```

Of course, the metaphorical goal is print I'm a dog on the first iteration and I'm a cat on second running methodOverloaded().

I tried

Visitor Pattern

instanceOf()

but I'm looking for better solution.

edit : I stricrtly want to call the overloaded methods of example's OtherClass.

答:
You can do it like this:

```<code>for(Animals a:aList){
    if(a instanceof Dog){
        methodOverloaded((Dog) a);
    }else if(a instanceof Cat){
        methodOverloaded((Cat) a);
    }
}
</code>```

But according to the scenario you have described in the question, @J-Alex answer is a good way to go.

Body:
What's definitely the best way to call a different method of a class according to a different object type in a List?

common example:

public class Dog extends Animals{
  ...
  public void say(){
    System.out("i'm a dog");
}

public class Cat extends Animals{
  ...
  public void say(){
    System.out("i'm a cat");
}

public class OtherClass {
  public void route(){
    List<Animals> aList = new ArrayList<>();
    a.add(new Dog());
    a.add(new Cat());
    for(Animals a:aList)
     methodOverloaded(a); ---> that's the point <---
  }
  public methodOverloaded(Dog d){
    d.say();
  }

  public methodOverloaded(Cat c){
    c.say();
 }
}

Of course, the metaphorical goal is print I'm a dog on the first iteration and I'm a cat on second running methodOverloaded().

I tried

Visitor Pattern

instanceOf()

but I'm looking for better solution.

edit : I stricrtly want to call the overloaded methods of example's OtherClass.

Body:
You can do it like this:

for(Animals a:aList){
    if(a instanceof Dog){
        methodOverloaded((Dog) a);
    }else if(a instanceof Cat){
        methodOverloaded((Cat) a);
    }
}

But according to the scenario you have described in the question, @J-Alex answer is a good way to go.


问:
Uncaught PDOException: SQLSTATE[HY093] with UPDATE
I'm trying to create a function to change a users password:

```<code>    public function ChangePassword($password)
    {
        $query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
        $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
        $query->bindParam("password", $hash, PDO::PARAM_STR);
        $query->execute();
        return true;
    }
</code>```

but it shows me the "Uncaught PDOException: SQLSTATE[HY093]". When I use

```<code>$query = $this->db->prepare("INSERT INTO users(password) VALUES (:password)");
</code>```

instead of

```<code>$query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
</code>```

it works, means I get an additional row with a password entry. I didn't find a documentation showing the proper use of UPDATE.

答:
Check the full error message, that gives quite a hint! SQLSTATE[HY093] means "Invalid parameter number"

The parameter user_id is missing.

```<code>public function ChangePassword($password, $userId)
{
    $query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
    $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
    $query->bindParam("password", $hash, PDO::PARAM_STR);
    $query->bindParam("user_id", $userId, PDO::PARAM_STR);
    $query->execute();
    return true;
}
</code>```

Body:
I'm trying to create a function to change a users password:

    public function ChangePassword($password)
    {
        $query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
        $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
        $query->bindParam("password", $hash, PDO::PARAM_STR);
        $query->execute();
        return true;
    }

but it shows me the "Uncaught PDOException: SQLSTATE[HY093]". When I use

$query = $this->db->prepare("INSERT INTO users(password) VALUES (:password)");

instead of

$query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");

it works, means I get an additional row with a password entry. I didn't find a documentation showing the proper use of UPDATE.

Body:
Check the full error message, that gives quite a hint! SQLSTATE[HY093] means "Invalid parameter number"

The parameter user_id is missing.

public function ChangePassword($password, $userId)
{
    $query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
    $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
    $query->bindParam("password", $hash, PDO::PARAM_STR);
    $query->bindParam("user_id", $userId, PDO::PARAM_STR);
    $query->execute();
    return true;
}


问:
Is there any way to change char* value at any index?
As I know, if we declare char* in our program then it gives memory from read-only area, so we are not able to change a char at any position in the array.

```<code>char *ch = "sitaram";
ch[2] = 'y';
</code>```

The above code will not run properly, as we are changing read-only memory.

One approach is we can declare our char array as

```<code>char ch[] = "sitaram";
</code>```

and then we can change a value at an index.

Is there any way where I can change a char value at any index in a char*?

答:
Use the modern C++ approach for mutable string values

```<code>std::string str{"sitaram"};
str[2] = 'y';
</code>```

String literals (i.e. values enclosed in "") are by default of type const char[n] (where n is the length of the string literal +1 for the null character)  in C++ and because of that they are immutable, any attempt to modify them results in undefined behavior.

Body:
As I know, if we declare char* in our program then it gives memory from read-only area, so we are not able to change a char at any position in the array.

char *ch = "sitaram";
ch[2] = 'y';

The above code will not run properly, as we are changing read-only memory.

One approach is we can declare our char array as

char ch[] = "sitaram";

and then we can change a value at an index.

Is there any way where I can change a char value at any index in a char*?

Body:
Use the modern C++ approach for mutable string values

std::string str{"sitaram"};
str[2] = 'y';

String literals (i.e. values enclosed in "") are by default of type const char[n] (where n is the length of the string literal +1 for the null character)  in C++ and because of that they are immutable, any attempt to modify them results in undefined behavior.


问:
Adjust DataGridView's columns to fill available space if the grid is smaller and use scroll in case the grid bigger than the space available
I want to adjust all columns of a DataGridView according to the required space to show all its data completely. If the space required is smaller than the available space i want the grid to fill this exceeding space, but if the available is space is not enough to display properly all columns i want to DataGridView create automatically a scroll. Is there an easy way to do this?</p>

答: Go to DataGridView Property select "AutoSizeColumnsMode". Set "Fill".</p>


问:
Are there algorithms that are only feasible in a recursive manner?
Are there algorithms that are only feasible in a recursive manner? If yes, how can one identify these algorithms?

Consider the following as a case study.

In order to approximate a exponential, one can use.

ef ≈ 1 + f(1 + f/2(1 + f/3(1 + f/4)))

Here is a function that computes this approximation at a level of n steps using recursion.

```<code>exp_approximation = function(f, n, i = 2)
{
    if (n == 1)
    {
        return( 1 + f/i )
    } else
    {
        1 + f/i * exp_approximation(f,n=n-1,i=i+1)
    }

}
</code>```

Is it possible to write the same algorithm using iteration instead of recursion?

I wrote my code in R but I welcome solution in pseudo code other some other commonly used language such as C, C++, Java, Python, ...

答: Yes, technically it's possible. See, for example, this question for a generic conversion method. That said, many algorithms are much more intuitive in the recursive form (and might be more efficient in functional languages but not in imperative ones). That's especially true for math-related problems involving recurrences, where recursion is in fact a representation of a recurrence relation. </p>

Body:
Are there algorithms that are only feasible in a recursive manner? If yes, how can one identify these algorithms?

Consider the following as a case study.

In order to approximate a exponential, one can use.

ef ≈ 1 + f(1 + f/2(1 + f/3(1 + f/4)))

Here is a function that computes this approximation at a level of n steps using recursion.

exp_approximation = function(f, n, i = 2)
{
    if (n == 1)
    {
        return( 1 + f/i )
    } else
    {
        1 + f/i * exp_approximation(f,n=n-1,i=i+1)
    }

}

Is it possible to write the same algorithm using iteration instead of recursion?

I wrote my code in R but I welcome solution in pseudo code other some other commonly used language such as C, C++, Java, Python, ...


问:
Jquery Dialog issue
In order to use jquery UI dialog module with use of $.extend() method , I wrote this:

```<code>User.confirmationDialog = function(options)
{
  if(undefined === options.selector)
  {
      return false;
  }

  this.close = function()
  {
    modal.dialog('close');
  }

  this.forward = function()
  {
    if(undefined !== trigger.attr('href'))
    {
      document.location.href = trigger.attr('href');
    }
  }

  var modalButtons = {};
  if(undefined !== options.buttons)
  {
    for(var buttonTitle in options.buttons)
    {
      modalButtons[buttonTitle] = (function(e, f)
      {
        return function() {
          e.call(f);
        }
      })(options.buttons[buttonTitle], this);
    }
    delete options.buttons;
  }

  var modalHtmlElementId = 'confirmDialog';
  if(undefined !== options.id)
  {
    modalHtmlElementId = options.id;
    delete options.id;
  }

  var modalOptions = jQuery.extend({
    autoOpen: false,
    width: 410,
    height: 'auto',
    minHeight: false,
    dialogClass: 'modalDefault',
    modal: true,
    resizable: false,
    draggable: false,
    close: function()
    {
      bindTriggers();
    },
    open: function()
    {
      unbindTriggers();
    },
    buttons: modalButtons
  }, options || {});

  var modal = jQuery('<div />', {'id': modalHtmlElementId});
  if(undefined !== options.text)
  {
    modal.html(options.text);
  }
  modal.dialog(modalOptions);

  var trigger = null;
  var onTriggerClick = function(e)
  {
    e.preventDefault();
    trigger = jQuery(e.target);
    if(undefined !== options.beforeOpen)
    {
      options.beforeOpen.call(trigger, modal, e);
    }
    modal.dialog('open');
  };

  //bind custom event to current options.selector elements
  var bindTriggers = function()
  {
    jQuery(options.selector).live('click', onTriggerClick);
  }

  //unbind custom event to current options.selector elements
  var unbindTriggers = function()
  {
    jQuery(options.selector).die('click', onTriggerClick);
  }

  //First init: bind custom event listener on option.selector
  bindTriggers();
}

/*
*
* @required User.confirmationDialog
*/
User.singleBtnDialog = function (options)
{
  if(undefined === options.selector) return false;

  var text= options.text,
      ok = options.okBtnTxt,
      dialogButton = {};

  dialogButton[ok] = function()
  {
    this.forward();
  };

  var modalOptions = jQuery.extend({
    selector: options.selector,
    text : text,
    closeOnEscape: false,
    open: function(event, ui)
    {
      jQuery(".ui-dialog-titlebar-close").hide()
    },
    buttons: dialogButton
  }, options || {});
  User.confirmationDialog(modalOptions);
}

User.twoBtnDialog = function(options)
{
  if(undefined === options.selector) return false;

  var text= options.text,
      ok = options.okBtnTxt,
      cancel = options.cancelBtnTxt,
      dialogButtons = {};

  dialogButtons[ok] = function()
  {
    forward();
  };
  dialogButtons[cancel] = function()
  {
    close();
  };

  var modalOptions = jQuery.extend({
    selector: options.selector,
    text: text,
    buttons: dialogButtons
  }, options || {});
  User.confirmationDialog(modalOptions);
};

User.ajaxContentDialog = function(options)
{
  if(undefined === options.selector) return false;

  var modalOptions = jQuery.extend({
    selector: options.selector,
    beforeOpen: function(modal, e)
    {
      e.stopPropagation();
      jQuery.ajax({
         async: false,
         type: 'GET',
         url: this.attr('href'),
         success: function(data, textStatus, XMLHttpRequest)
         {
          modal.html(data);
         }
      });
    }
  }, options || {});
  User.confirmationDialog(modalOptions);
};
</code>```

Frontend, i'm actually binding any of the 3 methods (singbutton, 2buttons, or ajax) this way :

```<code> [User.singleBtnDialog, {
      okBtnTxt: 'Ok',
      text: 'blablablablabl',
      selector: '.addToFav'}],

    [User.twoBtnDialog, {
      okBtnTxt: 'Ok',
      cancelBtnTxt: 'Ablehnen',
      text: 'blablablablabl',
      selector: '.topicOpenClose'}],
</code>```

My issue is quite simple, yet I cannot seem to resolve it easily :
event is well binded on each of my selectors, buttons are created properly, yet, when clicking on the 'ok' button, I get a

```<code>trigger is null
[Break On This Error] if(undefined !== trigger.attr('href'))
</code>```

error. I suspect some scope misunderstanding, but can't seem to find the correct solution.

Thanks for the help, greatly appreciated.

答:
Yes, this is a scope issue. Try to call it using User.confirmationDialog.forward(); Ifthis does not work make the function public available.

EDIT: You should make your functions into objects with functions and call those functions only.

```<code>User.confirmationDialog = {

 recent_function: function(options){
   // do ...
 }

 close: function()
  {
    alert('close');
  }
  ...
}
</code>```

Calling User.confirmationDialog.recent_function will run the former function confirmationDialog.
You may acces close now using User.confirmationDialog.close();

Title: Jquery Dialog issue

Body:
In order to use jquery UI dialog module with use of $.extend() method , I wrote this:

User.confirmationDialog = function(options)
{
  if(undefined === options.selector)
  {
      return false;
  }

  this.close = function()
  {
    modal.dialog('close');
  }

  this.forward = function()
  {
    if(undefined !== trigger.attr('href'))
    {
      document.location.href = trigger.attr('href');
    }
  }

  var modalButtons = {};
  if(undefined !== options.buttons)
  {
    for(var buttonTitle in options.buttons)
    {
      modalButtons[buttonTitle] = (function(e, f)
      {
        return function() {
          e.call(f);
        }
      })(options.buttons[buttonTitle], this);
    }
    delete options.buttons;
  }

  var modalHtmlElementId = 'confirmDialog';
  if(undefined !== options.id)
  {
    modalHtmlElementId = options.id;
    delete options.id;
  }

  var modalOptions = jQuery.extend({
    autoOpen: false,
    width: 410,
    height: 'auto',
    minHeight: false,
    dialogClass: 'modalDefault',
    modal: true,
    resizable: false,
    draggable: false,
    close: function()
    {
      bindTriggers();
    },
    open: function()
    {
      unbindTriggers();
    },
    buttons: modalButtons
  }, options || {});

  var modal = jQuery('
', {'id': modalHtmlElementId});
  if(undefined !== options.text)
  {
    modal.html(options.text);
  }
  modal.dialog(modalOptions);

  var trigger = null;
  var onTriggerClick = function(e)
  {
    e.preventDefault();
    trigger = jQuery(e.target);
    if(undefined !== options.beforeOpen)
    {
      options.beforeOpen.call(trigger, modal, e);
    }
    modal.dialog('open');
  };

  //bind custom event to current options.selector elements
  var bindTriggers = function()
  {
    jQuery(options.selector).live('click', onTriggerClick);
  }

  //unbind custom event to current options.selector elements
  var unbindTriggers = function()
  {
    jQuery(options.selector).die('click', onTriggerClick);
  }

  //First init: bind custom event listener on option.selector
  bindTriggers();
}

/*
*
* @required User.confirmationDialog
*/
User.singleBtnDialog = function (options)
{
  if(undefined === options.selector) return false;

  var text= options.text,
      ok = options.okBtnTxt,
      dialogButton = {};

  dialogButton[ok] = function()
  {
    this.forward();
  };

  var modalOptions = jQuery.extend({
    selector: options.selector,
    text : text,
    closeOnEscape: false,
    open: function(event, ui)
    {
      jQuery(".ui-dialog-titlebar-close").hide()
    },
    buttons: dialogButton
  }, options || {});
  User.confirmationDialog(modalOptions);
}

User.twoBtnDialog = function(options)
{
  if(undefined === options.selector) return false;

  var text= options.text,
      ok = options.okBtnTxt,
      cancel = options.cancelBtnTxt,
      dialogButtons = {};

  dialogButtons[ok] = function()
  {
    forward();
  };
  dialogButtons[cancel] = function()
  {
    close();
  };

  var modalOptions = jQuery.extend({
    selector: options.selector,
    text: text,
    buttons: dialogButtons
  }, options || {});
  User.confirmationDialog(modalOptions);
};

User.ajaxContentDialog = function(options)
{
  if(undefined === options.selector) return false;

  var modalOptions = jQuery.extend({
    selector: options.selector,
    beforeOpen: function(modal, e)
    {
      e.stopPropagation();
      jQuery.ajax({
         async: false,
         type: 'GET',
         url: this.attr('href'),
         success: function(data, textStatus, XMLHttpRequest)
         {
          modal.html(data);
         }
      });
    }
  }, options || {});
  User.confirmationDialog(modalOptions);
};

Frontend, i'm actually binding any of the 3 methods (singbutton, 2buttons, or ajax) this way :

 [User.singleBtnDialog, {
      okBtnTxt: 'Ok',
      text: 'blablablablabl',
      selector: '.addToFav'}],

    [User.twoBtnDialog, {
      okBtnTxt: 'Ok',
      cancelBtnTxt: 'Ablehnen',
      text: 'blablablablabl',
      selector: '.topicOpenClose'}],

My issue is quite simple, yet I cannot seem to resolve it easily :
event is well binded on each of my selectors, buttons are created properly, yet, when clicking on the 'ok' button, I get a

trigger is null
[Break On This Error] if(undefined !== trigger.attr('href'))

error. I suspect some scope misunderstanding, but can't seem to find the correct solution.

Thanks for the help, greatly appreciated.

Body:
Yes, this is a scope issue. Try to call it using User.confirmationDialog.forward(); Ifthis does not work make the function public available.

EDIT: You should make your functions into objects with functions and call those functions only.

User.confirmationDialog = {

 recent_function: function(options){
   // do ...
 }

 close: function()
  {
    alert('close');
  }
  ...
}

Calling User.confirmationDialog.recent_function will run the former function confirmationDialog.
You may acces close now using User.confirmationDialog.close();


问:
Getting started with Keras for machine learning
I'm getting started with machine learning tools and I'd like to learn more about what the heck I'm doing. For instance, the script:

```<code>from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, BatchNormalization
from keras.initializers import RandomUniform
import numpy

numpy.random.seed(13)
RandomUniform(seed=13)

model = Sequential()

model.add(Dense(6, input_dim=6))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(Dropout(0.01))

model.add(Dense(11))
model.add(Activation('tanh'))
model.add(Dropout(0.01))

model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(optimizer='sgd', loss='mean_absolute_error', metrics=['accuracy'])

data = numpy.loadtxt('train', delimiter=' ')
X = data[:, 0:6]
Y = data[:, 6]

model.fit(X, Y, batch_size=1, epochs=1000)

data = numpy.loadtxt('test', delimiter=' ')
X = data[:, 0:6]
Y = data[:, 6]

score = model.evaluate(X, Y, verbose=1)
print ('\n\nThe error is:\n', score, "\n")

print('\n\nPrediction:\n')
Y = model.predict(X, batch_size=1, verbose=1)
print('\nResult:\n', Y, '\n')
</code>```

It's a Frankenstein I made from some examples I found on the internet and I have many unanswered questions about it:

The file train has 60 rows. Is 1000 epochs too little? Is it too much? Can I get an Underfit/Overfit?

What does the result I get from model.evaluate() mean? I know it's the loss but, if I get a [7.0506157875061035, 0.0], does it mean that my model has a 7% error?

And last, I'm getting a prediction of 0.99875391, 0.99875391, 0.9362126, 0.99875391, 0.99875391, 0.99875391, 0.93571019 when the expected values were anything close to 7.86, 3.57, 8.93, 6.57, 11.7, 8.53, 9.06, which means it's a real bad prediction. Clearly there's a lot of things I'm doing wrong. Could you guys give me a few pointers?

I know it all depends on the type of data I'm using, but is there anything I shouldn't do at all? Or maybe something I should be doing?

答:
1

There is never a ready answer for how many epochs is a good number. It varies wildly depending on the size of your data, your model, and what you want to achieve. Normally, small models require less epochs, bigger models require more. Yours seem small enough and 1000 epochs seems way too much.

It also depends on the learning rate, a parameter given to the optimizer that defines how long are the steps your model takes to update its weights. Bigger learning rates mean less epochs, but there is a chance that you simply never find a good point because you're adjusting weights beyond what is good. Smaller learning rates mean more epochs and better learning.

Normally, if the loss reaches a limit, you're approaching a point where training is not useful anymore. (Of course, there may be problems with the model too, there is really no simple answer for this one).

To detect overfitting, you need besides the training data (X and Y), another group with test data (say Xtest and Ytest, for instance).

Then you use it in model.fit(X,Y, validation_data=(Xtest,Ytest), ...)

Test data is not given for training, it's kept separate just to see if your model can predict good things from data it has never seen in training.

If the training loss goes down, but the validation loss doesn't, you're overfitting (roughly, your model is capable of memorizing the training data without really understanding it).

An underfit, on the contrary, happens when you never achieve the accuracy you expect (of course we always expect a 100% accuracy, no mistakes, but good models get around the 90's, some applicatoins go better 99%, some worse, again, it's very subjective).

2

model.evaluate() gives you the losses and the metrics you added in the compile method.

The loss value is something your model will always try to decrease during training. It roughly means how distant your model is from the exact values. There is no rule for what the loss value means, it could even be negative (but usually keras uses positive losses). The point is: it must decrease during training, that means your model is evolving.

The accuracy value means how many right predictions your model outputs compared to the true values (Y). It seems your accuracy is 0%, your model is getting everything wrong. (You can see that from the values you typed).

3

In your model, you used activation functions. These normalize the results so they don't get too big. This avoids overflowing problems, numeric errors propagating, etc.

It's very very usual to work with values within such bounds.

tanh - outputs values between -1 and 1

sigmoid - outputs values between 0 and 1

Well, if you used a sigmoid activation in the last layer, your model will never output 3 for instance. It tries, but the maximum value is 1.

What you should do is prepare your data (Y), so it's contained between 0 and 1. (This is the best to do in classification problems, often done with images too)

But if you actually want numerical values, then you should just remove the activation and let the output be free to reach higher values.  (It all depends on what you want to achieve with your model)

Body:
I'm getting started with machine learning tools and I'd like to learn more about what the heck I'm doing. For instance, the script:

from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, BatchNormalization
from keras.initializers import RandomUniform
import numpy

numpy.random.seed(13)
RandomUniform(seed=13)

model = Sequential()

model.add(Dense(6, input_dim=6))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(Dropout(0.01))

model.add(Dense(11))
model.add(Activation('tanh'))
model.add(Dropout(0.01))

model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(optimizer='sgd', loss='mean_absolute_error', metrics=['accuracy'])

data = numpy.loadtxt('train', delimiter=' ')
X = data[:, 0:6]
Y = data[:, 6]

model.fit(X, Y, batch_size=1, epochs=1000)

data = numpy.loadtxt('test', delimiter=' ')
X = data[:, 0:6]
Y = data[:, 6]

score = model.evaluate(X, Y, verbose=1)
print ('\n\nThe error is:\n', score, "\n")

print('\n\nPrediction:\n')
Y = model.predict(X, batch_size=1, verbose=1)
print('\nResult:\n', Y, '\n')

It's a Frankenstein I made from some examples I found on the internet and I have many unanswered questions about it:

The file train has 60 rows. Is 1000 epochs too little? Is it too much? Can I get an Underfit/Overfit?

What does the result I get from model.evaluate() mean? I know it's the loss but, if I get a [7.0506157875061035, 0.0], does it mean that my model has a 7% error?

And last, I'm getting a prediction of 0.99875391, 0.99875391, 0.9362126, 0.99875391, 0.99875391, 0.99875391, 0.93571019 when the expected values were anything close to 7.86, 3.57, 8.93, 6.57, 11.7, 8.53, 9.06, which means it's a real bad prediction. Clearly there's a lot of things I'm doing wrong. Could you guys give me a few pointers?

I know it all depends on the type of data I'm using, but is there anything I shouldn't do at all? Or maybe something I should be doing?


问:
matplotlib split title on two lines with non ascii and LaTeX char
I need to split a figure title to two lines using matplotlib.pyplot with non ascii characters in it.

Here's what I've tried so far:

```<code>plt.title(u"Some very long string with non ascii chara éèàéüöëêâûô\n"
"and the next line should be here, with maybe some LaTeX symbols like greek letters in addition éèàéüöëêâûô")

plt.title(r"Some very long string with non ascii chara éèàéüöëêâûô\n"
"and the next line should be here, with maybe some LaTeX symbols like greek letters in addition éèàéüöëêâûô")
</code>```

Both statement versions returned me some errors.

答:
Just don't end the line with ":

```<code>plt.title(u"Some very long string with non ascii chara éèàéüöëêâûô\n and the next line should be here, with maybe some LaTeX symbols like greek letters in addition éèàéüöëêâûô")
</code>```

Or try:

```<code>plt.title(u"""Some very long string with non ascii chara éèàéüöëêâûô
and the next line should be here, with maybe some LaTeX symbols like greek letters in addition éèàéüöëêâûô""")
</code>```

Body:
I need to split a figure title to two lines using matplotlib.pyplot with non ascii characters in it.

Here's what I've tried so far:

plt.title(u"Some very long string with non ascii chara éèàéüöëêâûô\n"
"and the next line should be here, with maybe some LaTeX symbols like greek letters in addition éèàéüöëêâûô")

plt.title(r"Some very long string with non ascii chara éèàéüöëêâûô\n"
"and the next line should be here, with maybe some LaTeX symbols like greek letters in addition éèàéüöëêâûô")

Both statement versions returned me some errors.

Body:
Just don't end the line with ":

plt.title(u"Some very long string with non ascii chara éèàéüöëêâûô\n and the next line should be here, with maybe some LaTeX symbols like greek letters in addition éèàéüöëêâûô")

Or try:

plt.title(u"""Some very long string with non ascii chara éèàéüöëêâûô
and the next line should be here, with maybe some LaTeX symbols like greek letters in addition éèàéüöëêâûô""")


问:
Why am I getting "undefined is not an object (evaluating PropTypes.shape)"?
Whenever I try to run my iOS simulator, I'm getting that error. All modules are installed, file path to my picture is correct, no errors being thrown within my IDE except for the one that's appearing in my simulator. Picture below of error.

Here's Login.js:

```<code>import React, {Component} from 'react';
import {StyleSheet, TextInput, Text, TouchableOpacity, KeyboardAvoidingView} from 'react-native';

class Login extends Component {
    onButtonPress() {
        this.props.navigator.push({
            id: 'CreateAccount'
        });
    }

    render() {
        return(
            <KeyboardAvoidingView behavior={"padding"} style={styles.container}>
                    <TextInput
                        style={styles.input}
                        returnKeyType={"next"}
                        keyboardType={"email-address"}
                        autoCorrect={false}
                        placeholder={"Email"}
                    />

                    <TextInput
                        style={styles.input}
                        returnKeyType={"go"}
                        placeholder={"Password"}
                        secureTextEntry
                    />

                    <TouchableOpacity>
                        <Text style={styles.loginAndCA}>Login</Text>
                    </TouchableOpacity>

                    <TouchableOpacity onPress={this.onButtonPress.bind(this)}>
                        <Text style={styles.loginAndCA}>Create Account</Text>
                    </TouchableOpacity>
            </KeyboardAvoidingView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        padding: 20 // Length of text input boxes.
    },

    input: {
        backgroundColor: '#DAE5FF',
        padding: 20,
        paddingHorizontal: 15,
        marginBottom: 10,
        borderRadius: 15
    },

    loginAndCA: {
        fontSize: 40,
        textAlign: 'center',
        color: 'white',
        fontFamily: 'Bodoni 72 Smallcaps',
        paddingHorizontal: 10
    }
});

export default Login;
</code>```

Here's BackGround.js:

```<code>import React, {Component} from 'react';
import {StyleSheet, Image, View, Text} from 'react-native';
import Login from './Login';

class BackGround extends Component {
    render() {
        return(
            <View style={styles.first}>
                <Image style={styles.container} source={require('../pictures/smoke.jpg')}>
                    <View style={styles.second}>
                         <View>
                            <Text style={styles.title}>My App</Text>
                         </View>
                        <Login/>
                    </View>
                </Image>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        width: null,
        height: null,
        backgroundColor: 'rgba(0,0,0,0)'
    },

    first: {
        flex: 1
    },

    second: {
       paddingTop: 290 // Moves both <TextInput> boxes down.
    },

    title: {
        fontSize: 34,
        textAlign: 'center',
        justifyContent: 'center',
        flexDirection: 'row',
        fontFamily: 'Bodoni 72'
    }

    // movementTitle: {
    //     paddingBottom: 34
    // }
});

export default BackGround;
</code>```

Here's CreateAccount.js:

```<code>import React, {Component} from 'react';
import {Text} from 'react-native';

class CreateAccount extends Component {
    render() {
        return(
            <Text>Must get to this page</Text>
        );
    }
}

export default CreateAccount;
</code>```

Here's index.ios.js:

```<code>import React, {Component} from 'react';
import {View, StyleSheet, AppRegistry} from 'react-native';
import {Navigator} from 'react-native-deprecated-custom-components';
import BackGround from './components/BackGround';
import Login from "./components/Login";
import CreateAccount from "./components/CreateAccount";

export default class App extends Component {
    render() {
        return(
            <View style={styles.back}>
              <BackGround/>
              <Navigator
                  initialRoute={{id: 'Login'}}
                  renderScene={this.navigatorRenderScene}
              />
            </View>
        );
    }

    navigatorRenderScene() {
        _navigator = navigator;
        switch(route.id) {
            case 'Login':
                return (<Login navigator={navigator} title="Login"/>);
            case 'CreateAccount':
                return (<CreateAccount navigator={navigator} title="Create Account" />);
        }
    }
}

const styles = StyleSheet.create({
    back: {
        flex: 1
    }
});

AppRegistry.registerComponent('dendroApp', () => dendroApp);
</code>```

答:
React recently removed PropTypes from their core library as of React 15.5.

Add the line

```<code>import PropTypes from 'prop-types';
</code>```

And call your proptypes directly from that.

Body:
Whenever I try to run my iOS simulator, I'm getting that error. All modules are installed, file path to my picture is correct, no errors being thrown within my IDE except for the one that's appearing in my simulator. Picture below of error.

Here's Login.js:

import React, {Component} from 'react';
import {StyleSheet, TextInput, Text, TouchableOpacity, KeyboardAvoidingView} from 'react-native';

class Login extends Component {
    onButtonPress() {
        this.props.navigator.push({
            id: 'CreateAccount'
        });
    }

    render() {
        return(
            <KeyboardAvoidingView behavior={"padding"} style={styles.container}>
                    <TextInput
                        style={styles.input}
                        returnKeyType={"next"}
                        keyboardType={"email-address"}
                        autoCorrect={false}
                        placeholder={"Email"}
                    />

                    <TextInput
                        style={styles.input}
                        returnKeyType={"go"}
                        placeholder={"Password"}
                        secureTextEntry
                    />

                    <TouchableOpacity>
                        <Text style={styles.loginAndCA}>Login</Text>
                    </TouchableOpacity>

                    <TouchableOpacity onPress={this.onButtonPress.bind(this)}>
                        <Text style={styles.loginAndCA}>Create Account</Text>
                    </TouchableOpacity>
            </KeyboardAvoidingView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        padding: 20 // Length of text input boxes.
    },

    input: {
        backgroundColor: '#DAE5FF',
        padding: 20,
        paddingHorizontal: 15,
        marginBottom: 10,
        borderRadius: 15
    },

    loginAndCA: {
        fontSize: 40,
        textAlign: 'center',
        color: 'white',
        fontFamily: 'Bodoni 72 Smallcaps',
        paddingHorizontal: 10
    }
});

export default Login;

Here's BackGround.js:

import React, {Component} from 'react';
import {StyleSheet, Image, View, Text} from 'react-native';
import Login from './Login';

class BackGround extends Component {
    render() {
        return(
            <View style={styles.first}>
                <Image style={styles.container} source={require('../pictures/smoke.jpg')}>
                    <View style={styles.second}>
                         <View>
                            <Text style={styles.title}>My App</Text>
                         </View>
                        <Login/>
                    </View>
                </Image>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        width: null,
        height: null,
        backgroundColor: 'rgba(0,0,0,0)'
    },

    first: {
        flex: 1
    },

    second: {
       paddingTop: 290 // Moves both <TextInput> boxes down.
    },

    title: {
        fontSize: 34,
        textAlign: 'center',
        justifyContent: 'center',
        flexDirection: 'row',
        fontFamily: 'Bodoni 72'
    }

    // movementTitle: {
    //     paddingBottom: 34
    // }
});

export default BackGround;

Here's CreateAccount.js:

import React, {Component} from 'react';
import {Text} from 'react-native';

class CreateAccount extends Component {
    render() {
        return(
            <Text>Must get to this page</Text>
        );
    }
}

export default CreateAccount;

Here's index.ios.js:

import React, {Component} from 'react';
import {View, StyleSheet, AppRegistry} from 'react-native';
import {Navigator} from 'react-native-deprecated-custom-components';
import BackGround from './components/BackGround';
import Login from "./components/Login";
import CreateAccount from "./components/CreateAccount";

export default class App extends Component {
    render() {
        return(
            <View style={styles.back}>
              <BackGround/>
              <Navigator
                  initialRoute={{id: 'Login'}}
                  renderScene={this.navigatorRenderScene}
              />
            </View>
        );
    }

    navigatorRenderScene() {
        _navigator = navigator;
        switch(route.id) {
            case 'Login':
                return (<Login navigator={navigator} title="Login"/>);
            case 'CreateAccount':
                return (<CreateAccount navigator={navigator} title="Create Account" />);
        }
    }
}

const styles = StyleSheet.create({
    back: {
        flex: 1
    }
});

AppRegistry.registerComponent('dendroApp', () => dendroApp);

Body:
React recently removed PropTypes from their core library as of React 15.5.

Add the line

import PropTypes from 'prop-types';

And call your proptypes directly from that.


问:
Cannot install matplotlib on Intel Edison
I am trying to install matplotlib on my Intel Edison board but I am taking errors. I installed Numpy and Spicy successfully but could not manage to install matplotlib.

I am getting this error

```<code>root@edisonwbl:~# pip install matplotlib
Collecting matplotlib
/usr/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/usr/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
  Downloading matplotlib-2.0.2.tar.gz (53.9MB)
    99% |############################### | 53.9MB 623kB/s eta 0:00:01Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 324, in run
    requirement_set.prepare_files(finder)
  File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 620, in _prepare_file
    session=self.session, hashes=hashes)
  File "/usr/lib/python2.7/site-packages/pip/download.py", line 821, in unpack_url
    hashes=hashes
  File "/usr/lib/python2.7/site-packages/pip/download.py", line 659, in unpack_http_url
    hashes)
  File "/usr/lib/python2.7/site-packages/pip/download.py", line 882, in _download_http_url
    _download_url(resp, link, content_file, hashes)
  File "/usr/lib/python2.7/site-packages/pip/download.py", line 603, in _download_url
    hashes.check_against_chunks(downloaded_chunks)
  File "/usr/lib/python2.7/site-packages/pip/utils/hashes.py", line 46, in check_against_chunks
    for chunk in chunks:
  File "/usr/lib/python2.7/site-packages/pip/download.py", line 571, in written_chunks
    for chunk in chunks:
  File "/usr/lib/python2.7/site-packages/pip/utils/ui.py", line 139, in iter
    for x in it:
  File "/usr/lib/python2.7/site-packages/pip/download.py", line 560, in resp_read
    decode_content=False):
  File "/usr/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 357, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/usr/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 314, in read
    data = self._fp.read(amt)
  File "/usr/lib/python2.7/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 63, in read
    self._close()
  File "/usr/lib/python2.7/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 50, in _close
    self.__callback(self.__buf.getvalue())
  File "/usr/lib/python2.7/site-packages/pip/_vendor/cachecontrol/controller.py", line 275, in cache_response
    self.serializer.dumps(request, response, body=body),
  File "/usr/lib/python2.7/site-packages/pip/_vendor/cachecontrol/serialize.py", line 87, in dumps
    ).encode("utf8"),
MemoryError
</code>```

I have Yocto on Edison and firmware version is 201606061707

Can anyone help me?

Thanks in advance!

--- Edit ---

I found the solution. freetype2 and libpng packages cannot be installed so I installed them manually and problem was solved!

答:
I will suggest you to uninstall python and install Anaconda2 for python 2.7. It comes with all necessary module, including matplolib, numpy, pandas all.

follow this link: https://www.continuum.io/downloads

Body:
I am trying to install matplotlib on my Intel Edison board but I am taking errors. I installed Numpy and Spicy successfully but could not manage to install matplotlib.

I am getting this error

root@edisonwbl:~# pip install matplotlib
Collecting matplotlib
/usr/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/usr/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
  Downloading matplotlib-2.0.2.tar.gz (53.9MB)
    99% |############################### | 53.9MB 623kB/s eta 0:00:01Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 324, in run
    requirement_set.prepare_files(finder)
  File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 620, in _prepare_file
    session=self.session, hashes=hashes)
  File "/usr/lib/python2.7/site-packages/pip/download.py", line 821, in unpack_url
    hashes=hashes
  File "/usr/lib/python2.7/site-packages/pip/download.py", line 659, in unpack_http_url
    hashes)
  File "/usr/lib/python2.7/site-packages/pip/download.py", line 882, in _download_http_url
    _download_url(resp, link, content_file, hashes)
  File "/usr/lib/python2.7/site-packages/pip/download.py", line 603, in _download_url
    hashes.check_against_chunks(downloaded_chunks)
  File "/usr/lib/python2.7/site-packages/pip/utils/hashes.py", line 46, in check_against_chunks
    for chunk in chunks:
  File "/usr/lib/python2.7/site-packages/pip/download.py", line 571, in written_chunks
    for chunk in chunks:
  File "/usr/lib/python2.7/site-packages/pip/utils/ui.py", line 139, in iter
    for x in it:
  File "/usr/lib/python2.7/site-packages/pip/download.py", line 560, in resp_read
    decode_content=False):
  File "/usr/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 357, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/usr/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 314, in read
    data = self._fp.read(amt)
  File "/usr/lib/python2.7/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 63, in read
    self._close()
  File "/usr/lib/python2.7/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 50, in _close
    self.__callback(self.__buf.getvalue())
  File "/usr/lib/python2.7/site-packages/pip/_vendor/cachecontrol/controller.py", line 275, in cache_response
    self.serializer.dumps(request, response, body=body),
  File "/usr/lib/python2.7/site-packages/pip/_vendor/cachecontrol/serialize.py", line 87, in dumps
    ).encode("utf8"),
MemoryError

I have Yocto on Edison and firmware version is 201606061707

Can anyone help me?

Thanks in advance!

--- Edit ---

I found the solution. freetype2 and libpng packages cannot be installed so I installed them manually and problem was solved!


问:
Galois field computations on Linux
Is there any software available on Linux for Galois field calculus?</p>

答:
I did a little bit of searching, and found a couple of options:

Sage

Sage can be used to study elementary and advanced, pure and applied mathematics. This includes a huge range of mathematics, including basic algebra, calculus, elementary to very advanced number theory, cryptography, numerical computation, commutative algebra, group theory, combinatorics, graph theory, exact linear algebra and much more.

Here's part of the tutorial on polynomials.

Octave

A high-level language, primarily intended for numerical computations. It provides a convenient command line interface for solving linear and nonlinear problems numerically, and for performing other numerical experiments using a language that is mostly compatible with Matlab.

Singular

A computer algebra system for polynomial computations, with special emphasis on commutative and non-commutative algebra, algebraic geometry, and singularity theory.

Note that I have not used the software listed above, and am merely trying to provide some helpful links. Asking this question on the Mathematics SE site will likely provide some more in-depth answers. Hope this helps.

Title: Galois field computations on Linux


问:
How to store list in python dataframe
I'm trying to create a dataframe where one column is a list of the values of other columns, something like:

```<code>   a             b  MA2  MA4
0  1   [1,NaN,NaN]  NaN  Nan
1  2   [2,1.5,NaN]  1.5  NaN
2  3   [3,2.5,NaN]  2.5  NaN
3  4   [4,3.5,2.5]  3.5  2.5
...
</code>```

but I can't figure out how to make the values in column b a list.

My test code is:

```<code>df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8,9]})

df["b"] = list(df["a"])

for days in [2,4]:
    labelMA  = "MA" + str(days)

    df[labelMA]   = df["a"].rolling(window =  days, center = False).mean()
    df["b"] += list(df[labelMA])
</code>```

but this (and other variations I've tried) produce a single-valued b column.

答:
Use tolist() to convert the values you need to store in column b to a list of lists, and then assign directly; this should be more efficient than creating column b on the go:

```<code>df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8,9]})

for days in [2,4]:
    labelMA  = "MA" + str(days)
    df[labelMA] = df["a"].rolling(window =  days, center = False).mean()
</code>```

```<code>df['b'] = df.values.tolist()

df
#   a   MA2 MA4               b
#0  1   NaN NaN [1.0, nan, nan]
#1  2   1.5 NaN [2.0, 1.5, nan]
#2  3   2.5 NaN [3.0, 2.5, nan]
#3  4   3.5 2.5 [4.0, 3.5, 2.5]
</code>```

Title: How to store list in python dataframe

Body:
I'm trying to create a dataframe where one column is a list of the values of other columns, something like:

   a             b  MA2  MA4
0  1   [1,NaN,NaN]  NaN  Nan
1  2   [2,1.5,NaN]  1.5  NaN
2  3   [3,2.5,NaN]  2.5  NaN
3  4   [4,3.5,2.5]  3.5  2.5
...

but I can't figure out how to make the values in column b a list.

My test code is:

df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8,9]})

df["b"] = list(df["a"])

for days in [2,4]:
    labelMA  = "MA" + str(days)

    df[labelMA]   = df["a"].rolling(window =  days, center = False).mean()
    df["b"] += list(df[labelMA])

but this (and other variations I've tried) produce a single-valued b column.

Body:
Use tolist() to convert the values you need to store in column b to a list of lists, and then assign directly; this should be more efficient than creating column b on the go:

df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8,9]})

for days in [2,4]:
    labelMA  = "MA" + str(days)
    df[labelMA] = df["a"].rolling(window =  days, center = False).mean()

df['b'] = df.values.tolist()

df
#   a   MA2 MA4               b
#0  1   NaN NaN [1.0, nan, nan]
#1  2   1.5 NaN [2.0, 1.5, nan]
#2  3   2.5 NaN [3.0, 2.5, nan]
#3  4   3.5 2.5 [4.0, 3.5, 2.5]


问:
Node.JS with Express and SASS - Compiled CSS file not applied
I'm new to NodeJS and I'm using Express to serve my pug files/view. Furthermore I'm using "express-sass-middleware" to compile and serve the scss/css files. Everything works very well but unfortunately, the CSS are not applied.

My app.js files looks like:

```<code>var express = require('express');
var sassMiddleware = require('express-sass-middleware');
var app = express();
app.set('view engine', 'pug');

app.get('/css/bootstrap.css', sassMiddleware({
  file: 'css/bootstrap.scss', // the location of the entry point,
                                     // this can also be a directory

  precompile: true,                   // should it be compiled on server start
                                     // or deferred to the first request
                                     //  - defaults to false
}));

app.get('/', function (req, res) {
    res.render('index', {
        varTitle: 'Hello World'
    });
});

app.listen(3000, function() {
    console.log('Example app listening on port 3000!');
});
</code>```

And my simple css file looks like:

```<code>// $icon-font-path: /3rdparty/fonts;

// @import 'bootstrap/bootstrap';
// @import './node_modules/bootstrap-sass/assets/stylesheets/bootstrap/variables';

body
{
    background-color: green;
    font-size: 100px;
}
</code>```

My index.pug file is:

```<code>doctype html
html(lang='en')
  head
    title= varTitle
    link(ref='stylesheet' type='text/css' href='/css/bootstrap.css')
  body
    h1= varTitle
</code>```

Now, when I start my webserver using "node app.js", accessing http://localhost:3000, I see "Hello World" but unfortunately the body background isn't green and the text is also not 100px. That means that the css file is not applied. But when I access http://localhost:3000/css/bootstrap.css, I see the valid, css file.

Anyone know what I'm missing here? I'm a bit confused that I see the CSS source when accessing it directly but the browser doesn't apply the css styling. I already tried different browsers without any success. None of them applying the css file.

答:
You have typing error in index.pug file for loading css file. You had mentioned ref whereas it should be rel.

```<code>link(rel='stylesheet' type='text/css' href='/css/bootstrap.css')
</code>```

Happy to help you.

Body:
I'm new to NodeJS and I'm using Express to serve my pug files/view. Furthermore I'm using "express-sass-middleware" to compile and serve the scss/css files. Everything works very well but unfortunately, the CSS are not applied.

My app.js files looks like:

var express = require('express');
var sassMiddleware = require('express-sass-middleware');
var app = express();
app.set('view engine', 'pug');

app.get('/css/bootstrap.css', sassMiddleware({
  file: 'css/bootstrap.scss', // the location of the entry point,
                                     // this can also be a directory

  precompile: true,                   // should it be compiled on server start
                                     // or deferred to the first request
                                     //  - defaults to false
}));

app.get('/', function (req, res) {
    res.render('index', {
        varTitle: 'Hello World'
    });
});

app.listen(3000, function() {
    console.log('Example app listening on port 3000!');
});

And my simple css file looks like:

// $icon-font-path: /3rdparty/fonts;

// @import 'bootstrap/bootstrap';
// @import './node_modules/bootstrap-sass/assets/stylesheets/bootstrap/variables';

body
{
    background-color: green;
    font-size: 100px;
}

My index.pug file is:

doctype html
html(lang='en')
  head
    title= varTitle
    link(ref='stylesheet' type='text/css' href='/css/bootstrap.css')
  body
    h1= varTitle

Now, when I start my webserver using "node app.js", accessing http://localhost:3000, I see "Hello World" but unfortunately the body background isn't green and the text is also not 100px. That means that the css file is not applied. But when I access http://localhost:3000/css/bootstrap.css, I see the valid, css file.

Anyone know what I'm missing here? I'm a bit confused that I see the CSS source when accessing it directly but the browser doesn't apply the css styling. I already tried different browsers without any success. None of them applying the css file.

Body:
You have typing error in index.pug file for loading css file. You had mentioned ref whereas it should be rel.

link(rel='stylesheet' type='text/css' href='/css/bootstrap.css')

Happy to help you.


问:
SyntaxError: name 'cows' is assigned to before global declaration in Python3.6
I am trying to edit the global variables cows and bulls inside a loop but getting this error "SyntaxError: name 'cows' is assigned to before global declaration"

```<code>import random

random_no = random.sample(range(0, 10), 4)
cows = 0
bulls = 0
#random_num = ','.join(map(str, random_no))
print(random_no)
user_input = input("Guess the no: ")
for index, num in enumerate(random_no):
    global cows, bulls
    print(index, num)
    if user_input[index] == num:
        cows += 1
    elif user_input[index] in random_no:
        bulls += 1

print(f'{cows} cows and {bulls} bulls')
</code>```

答:
You give cows a value before you declare it as global. You should declare your global scope first

Btw you dont need the global declarations. Just remove this line.

Body:
I am trying to edit the global variables cows and bulls inside a loop but getting this error "SyntaxError: name 'cows' is assigned to before global declaration"

import random

random_no = random.sample(range(0, 10), 4)
cows = 0
bulls = 0
#random_num = ','.join(map(str, random_no))
print(random_no)
user_input = input("Guess the no: ")
for index, num in enumerate(random_no):
    global cows, bulls
    print(index, num)
    if user_input[index] == num:
        cows += 1
    elif user_input[index] in random_no:
        bulls += 1

print(f'{cows} cows and {bulls} bulls')


问:
change color of flash component?
Sorry if this question is kind of newbie I'm really new with flash but I'm using this dice on my site http://www.flashvalley.com/fv_components/dice/ and I managed to chage the color but I was wondering if it was possible to change the dots color to white as well?

Thanks in advance!

答:
You need to target the movieclips/sprites and do a color transform on them

Lets say you have called each of the movieclips you want to transform "dot_mc"

```<code>var c:ColorTransform = new ColorTransform(); // instantiate a color transform
c.color = 0xFFFFFF; // set the color of the transform to white
dot_mc.transform.colorTransform = c; //Apply the color transform
</code>```

So if you had many of these dots you would put them in an array and loop through the array and apply whatever color to these dots

```<code>var arr:Array = new Array();
arr.push(dot1_mc);
arr.push(dot2_mc);
arr.push(dot3_mc);
//
var c:ColorTransform = new ColorTransform();
c.color = 0xFFFFFF;
//
for (var i:int=0; i<arr.length;i++){
    var mc:MovieClip = arr[i];
    mc.transform.colorTransform = c;
}
</code>```

You could put the above in a function and call it whenever you want, passing whichever color to it and transforming the dots when necessary.

```<code>function changeDotColor($color_num:Number):void {
    ...
    var c:ColorTransform = new ColorTransform();
    c.color = $color_num;
    ...
}
</code>```

You know or pass an array of movieclips to it with the associated color. and change other MovieClips/Sprites rather than the dot movieclip.

i.e

```<code>function changeDotColor($color_num:Number,$mc_arr:Array):void{
</code>```

Hope this helps

Title: change color of flash component?

Body:
You need to target the movieclips/sprites and do a color transform on them

Lets say you have called each of the movieclips you want to transform "dot_mc"

var c:ColorTransform = new ColorTransform(); // instantiate a color transform
c.color = 0xFFFFFF; // set the color of the transform to white
dot_mc.transform.colorTransform = c; //Apply the color transform

So if you had many of these dots you would put them in an array and loop through the array and apply whatever color to these dots

var arr:Array = new Array();
arr.push(dot1_mc);
arr.push(dot2_mc);
arr.push(dot3_mc);
//
var c:ColorTransform = new ColorTransform();
c.color = 0xFFFFFF;
//
for (var i:int=0; i<arr.length;i++){
    var mc:MovieClip = arr[i];
    mc.transform.colorTransform = c;
}

You could put the above in a function and call it whenever you want, passing whichever color to it and transforming the dots when necessary.

function changeDotColor($color_num:Number):void {
    ...
    var c:ColorTransform = new ColorTransform();
    c.color = $color_num;
    ...
}

You know or pass an array of movieclips to it with the associated color. and change other MovieClips/Sprites rather than the dot movieclip.

i.e

function changeDotColor($color_num:Number,$mc_arr:Array):void{

Hope this helps


问:
Laravel 'with' and nested relation
I am retrieving some relationship:

```<code>$requirements = Requirement::with([
            'countryMatch',
            'applier',
            'doc' ])->get();
</code>```

and my model Requirements contains:

```<code>public function doc()
{
    return $this->belongsTo(Doc::class);
}
</code>```

Right now all fine.

Since my Doc model has its own relationship:

```<code>public function translation($language = null)
{
    if ($language == null) {
        $language = /*App::getLocale()*/'en';
    }
    return $this->hasMany('App\DocTranslation')->where('language', '=', $language);
}
</code>```

I would like to retrieve this relationship direct in the first 'with' statement, something like this:

```<code>$requirements = Requirement::with([
        'countryMatch',
        'applier',
        'doc->translation()' ])->get();
</code>```

but I receive error:

```<code>Call to undefined relationship [doc->translation()] on model [App\Requirement].
</code>```

That's because relation translation is in Doc model not in Requirement.

答: Nested with() calls use dot notation, not object notation. Change it to 'doc.translation' instead. Do note though that I'm not sure if you can eager load relations that contain application logic.

Title: Laravel 'with' and nested relation

Body:
I am retrieving some relationship:

$requirements = Requirement::with([
            'countryMatch',
            'applier',
            'doc' ])->get();

and my model Requirements contains:

public function doc()
{
    return $this->belongsTo(Doc::class);
}

Right now all fine.

Since my Doc model has its own relationship:

public function translation($language = null)
{
    if ($language == null) {
        $language = /*App::getLocale()*/'en';
    }
    return $this->hasMany('App\DocTranslation')->where('language', '=', $language);
}

I would like to retrieve this relationship direct in the first 'with' statement, something like this:

$requirements = Requirement::with([
        'countryMatch',
        'applier',
        'doc->translation()' ])->get();

but I receive error:

Call to undefined relationship [doc->translation()] on model [App\Requirement].

That's because relation translation is in Doc model not in Requirement.


答:
Epoch is a single pass through the full training set. I my mind it seems a lot, but you'd have to check for overfitting and evaluate the predictions. There are many ways of checking and controlling for overfitting in a model. If you understand the methods of doing so from here, coding them in Keras should be no problem.

According to the documentation .evaluate returns:

Scalar test loss (if the model has no metrics) or list of scalars (if the model computes other metrics)

so these are the evaluation metrics of your model, they tell you how good your model is given some notion of good. Those metrics depend on the model and type of data that you've used. Some explanation on those can be found here and here. As mentioned in the documentation,

The attribute  model.metrics_names will give you the display labels for the scalar outputs.

So you can know what metric you are looking at. It is easier to do that interactively through the console (ipython, bpython) or Jupyter notebook.

I can't see your data, but a if you are doing a classification problem as suggested by metrics=['accuracy'], the loss=mean_absolute_error doesn't make sense, since it is made for regression problems. To learn more about those I refer you to here and here which discuss classification and regression problems with Keras.

PS: question 3 is not related to software per se, but to the theoretical construct supporting the software. In such cases, I'd recommend asking them at Cross Validated.

Title: Getting started with Keras for machine learning