问:
External function calling not working
I was working on a script which could automatically import a navigation bar, when I ran into an error which I can't seem to fix.

HTML:

```<code><html>
 <head>
    <script src="//code.jquery.com/jquery.min.js"></script>
    <script scr="http://mySite.nl/navbar.js"></script>
 </head>

 <body onload="onload()">

  <div id="nav-placeholder"></div>

 </body>
</html>
</code>```

Javascript/jQuery:

```<code>function onload() {
 $.get("http://mySite.nl/navbar.html", function(data) {$("#nav-placeholder").replaceWith(data);});
}
</code>```

The navbar HTML file:

```<code><div id="navbar">
    <ul>
        <li><a class="red" href="http://mySite.nl/" id="maintab">Home</a></li>
        <li><a class="red" href="http://mySite.nl/#games" id="subtab">Games</a></li>
        <li><a class="red" href="http://mySite.nl/#movies" id="subtab">Movies</a></li>
        <li><a class="red" href="http://mySite.nl/#about" id="subtab">About</a></li>
        <li><a class="blue" href="http://mySite.nl/apps.html" id="maintab">Apps</a></li>
        <li><a class="yellow" href="http://mySite.nl/forum.html" id="maintab">Forum</a></li>
        <li><a class="yellow" href="http://mySite.nl/forum.html#FAQ" id="subtab">Forum</a></li>
    </ul>
</div>
</code>```

The error that I get, is:

```<code>Uncaught ReferenceError: onload is not defined (index):12
at onload ((index):12)
</code>```

Please help

答:
I am hoping there is no typo here

```<code>         <script scr="http://mySite.nl/navbar.js"></script>
</code>```

it should be

```<code>         <script src="http://mySite.nl/navbar.js"></script>
</code>```

otherwise script file will not load

Title: External function calling not working

Body:
I was working on a script which could automatically import a navigation bar, when I ran into an error which I can't seem to fix.

HTML:

Javascript/jQuery:

function onload() {
 $.get("http://mySite.nl/navbar.html", function(data) {$("#nav-placeholder").replaceWith(data);});
}

The navbar HTML file:

Home

Games

Movies

About

Apps

Forum

Forum

The error that I get, is:

Uncaught ReferenceError: onload is not defined (index):12
at onload ((index):12)

Please help

Body:
I am hoping there is no typo here

         <script scr="http://mySite.nl/navbar.js"></script>

it should be

         <script src="http://mySite.nl/navbar.js"></script>

otherwise script file will not load


来源: stackexchange

问:
Plotting mean as dashed line on histogram with matplotlib
I have a histogram created from a pandas dataframe that I would like to plot a vertical dashed line representing the mean of the dataset. I have reviewed this thread, which is exactly the style I am looking for, however, I cannot figure out how to make it work with my code (below):

```<code>import pandas as pd
import matplotlib.pyplot as plt

#import csv file into pandas dataframe
df = pd.read_csv('/path/to/my/file')

#calculating mean
m = df.mean()
#print(m)

#plotting histogram
df.plot(kind='hist')
#plt.axvline(m, color = 'r', linestyle = 'dashed', linewidth = 2)
</code>```

I end up receiving this error:

```<code> ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

Not sure what that means, any help would be appreciated.

EDIT: My datafile is a csv with one column, first row is a header (string) and all subsequent 107 rows are values ranging from app. 1.0E+11 to 4.0E+11

Fake data (Python 2.7)

```<code>import io
import numpy as np
a = np.linspace(1, 4, num = 20)
s = 'E11\n'.join(map(str, a))
s += 'E11'
#print(s)
df = pd.read_csv(io.BytesIO(s))
</code>```

答:
I think you should use m.all() instead of m. and them use plt.show() for plt to draw your histogram. so the code will look like this:</p>

```<code>#plotting histogram
# df.plot(kind='hist')
plt.axvline(m.all(), color = 'r', linestyle = 'dashed', linewidth = 2)
plt.show()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a histogram created from a pandas dataframe that I would like to plot a vertical dashed line representing the mean of the dataset. I have reviewed this thread, which is exactly the style I am looking for, however, I cannot figure out how to make it work with my code (below):

import pandas as pd
import matplotlib.pyplot as plt

#import csv file into pandas dataframe
df = pd.read_csv('/path/to/my/file')

#calculating mean
m = df.mean()
#print(m)

#plotting histogram
df.plot(kind='hist')
#plt.axvline(m, color = 'r', linestyle = 'dashed', linewidth = 2)

I end up receiving this error:

 ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Not sure what that means, any help would be appreciated.

EDIT: My datafile is a csv with one column, first row is a header (string) and all subsequent 107 rows are values ranging from app. 1.0E+11 to 4.0E+11

Fake data (Python 2.7)

import io
import numpy as np
a = np.linspace(1, 4, num = 20)
s = 'E11\n'.join(map(str, a))
s += 'E11'
#print(s)
df = pd.read_csv(io.BytesIO(s))

Body:
I think you should use m.all() instead of m. and them use plt.show() for plt to draw your histogram. so the code will look like this:

#plotting histogram
# df.plot(kind='hist')
plt.axvline(m.all(), color = 'r', linestyle = 'dashed', linewidth = 2)
plt.show()


问:
c++ function calling function not working
I have 3 functions:

First function takes an int a and prints the that number of dots.

The second function takes an int b and prints that number of stars.

The third function takes a and b and calls the dots function and stars function. When I call it in main, it returns 0 without any output.

Each of the functions work fine on their own - why doesn't the third one work then?

EDIT: Tried initializing i=0, code still compiles with the same result. Again, both functions dots() and stars() work fine when called on their own.

```<code>void dots(int a){
    for(int i; i<a; i++){
        cout << ".";
    }
}
void stars(int a){
    for(int i; i<a; i++){
        cout << "*";
    }
}

//(not working):
void dotsstars(int a, int b){
    dots(a);
    stars(b);
}

int main(){
    dotsstars(5, 6);

    return 0;
}
</code>```

答:
You need to initialize the incrementer i to 0:</p>

```<code>for (int i=0; i<a; i++){
</code>```

Body:
I have 3 functions:

First function takes an int a and prints the that number of dots.

The second function takes an int b and prints that number of stars.

The third function takes a and b and calls the dots function and stars function. When I call it in main, it returns 0 without any output.

Each of the functions work fine on their own - why doesn't the third one work then?

EDIT: Tried initializing i=0, code still compiles with the same result. Again, both functions dots() and stars() work fine when called on their own.

void dots(int a){
    for(int i; i<a; i++){
        cout << ".";
    }
}
void stars(int a){
    for(int i; i<a; i++){
        cout << "*";
    }
}

//(not working):
void dotsstars(int a, int b){
    dots(a);
    stars(b);
}

int main(){
    dotsstars(5, 6);

    return 0;
}

Body:
You need to initialize the incrementer i to 0:

for (int i=0; i<a; i++){


问:
How to assign html table to Variable

I need this table to one variable, so that I can pass this variable as
  String to my email program.

message.setContent(variable, "text/html");

I need this variable as Webemails not supporting scripting executions
  at their front

Is there any way I can pull table information to variable?? is it
  possible??

I'm using angular js and displaying table as

```<code>    <table>
        <tr>

            <th>UserId</th>
            <th>UserName</th>
            <th>Points</th>

        </tr>

        <tr ng-repeat="country in countries.userpointsList| orderBy:'country.uservo.userId' ">

<td> {{ country.uservo.userId }}</td>
<td >{{ country.uservo.userName }}</td>
<td> {{ country.points }}</td>
</code>```

How I can put this table to one variable??

答:
```<code>it works

<html>

<body>

<div id="sasi" >
<table border="1">
<tr><td>sasikar</td><td>sasikar</td></tr>
<tr><td>srikar</td> <td>sasikar</td></tr>
</table>
<script>
var k="";

k=document.getElementById("sasi").innerHTML;
alert(k);
</script>
</html>
</code>```

Title: How to assign html table to Variable

Body:
I need this table to one variable, so that I can pass this variable as
  String to my email program.

message.setContent(variable, "text/html");

I need this variable as Webemails not supporting scripting executions
  at their front

Is there any way I can pull table information to variable?? is it
  possible??

I'm using angular js and displaying table as

            UserId
            UserName
            Points

 {{ country.uservo.userId }}
{{ country.uservo.userName }}
 {{ country.points }}

How I can put this table to one variable??


答:
you are not initializing i that's why it is not printing. i is a local variable so default value for local variable will be garbage value that's why you need to initialize it first.

```<code>#include<iostream>
using namespace std;
void dots(int a){
    for(int i=0; i<a; i++){// i is set to be 0 here
        cout << ".";
        }
    }
void stars(int a){
    for(int i=0; i<a; i++){// i is set to be 0 here
        cout << "*";
        }
    }

//(not working):
void dotsstars(int a, int b){
    dots(a);
    stars(b);
}

int main(){
    dotsstars(5, 6);

    return 0;
}
</code>```

Title: c++ function calling function not working

Body:
you are not initializing i that's why it is not printing. i is a local variable so default value for local variable will be garbage value that's why you need to initialize it first.

#include<iostream>
using namespace std;
void dots(int a){
    for(int i=0; i<a; i++){// i is set to be 0 here
        cout << ".";
        }
    }
void stars(int a){
    for(int i=0; i<a; i++){// i is set to be 0 here
        cout << "*";
        }
    }

//(not working):
void dotsstars(int a, int b){
    dots(a);
    stars(b);
}

int main(){
    dotsstars(5, 6);

    return 0;
}


问:
Change Default Application For Any File
I Want to know if i can change default application for a particular file like if i have set .mp4 files to be open with VLC. Now when I open a .mp4 file via java it should ask me to open with VLC or other relating applications i.e: Windows Media Player.</p>

答:
Changing the default application isn't Java, but the operating system's feat, in your case Windows. You can configure Windows to change this using 'choose default program' option.

If you were just looking to open the file from within your java application, then you could use Desktop.open(fileName) or even a simple Runtime.exec(fileName).

Title: Change Default Application For Any File


问:
Big Oh (Induction Proof)
If f(n) = 15n^3 + 7n^2 + 34 & g(n) = n^4 + 3n^2 + 17. How do I prove f belongs to O(g)? </p>

答:
Well the definition of Big-O notation is as follows:

f is in O(g) <=> there exist c,n0 such that for all n >= n0, |f(n)| <= c|g(n)|

So in this case, you could most easily demonstrate that f is in O(g) by finding appropriate c and n0 satisfying for all n >= n0, |15n^3+7n^2+34| <= c|n^4+3n^2+17|. I guess.

ContentLicense: CC BY-SA 2.5

Title: Big Oh (Induction Proof)


答:
onload is an HTML Event Handler. You shouldn't use it as a function name.

But I think, that you haven't load the function.

Edit: Ahh yes. There is an error in the src-Attribute. Therefore it could not be loaded.

Title: External function calling not working


问:
Indirect using variable range for Worksheet names
I have the following formula:

```<code>=SUMPRODUCT(COUNTIF(INDIRECT("'"&D1:D2&"'!A1"),E2))
</code>```

Took it from here
https://www.extendoffice.com/documents/excel/2541-excel-countif-across-multiple-worksheets.html

Now, i'm making a COUNTA to the D column:

```<code>=COUNTA(D:D)
</code>```

Which will basically result in me having the number of sheets.

Now, i would like to make the first formula use the result of the second one:

```<code>=SUMPRODUCT(COUNTIF(INDIRECT("'"&D1:***COUNTA RESULT***&"'!A1"),E2))
</code>```

What is the correct syntax to perform that? Did not manage to succeed.

答:
Since worksheets typically have alphabetic names and you were attempting a solution with COUNTA not COUNT, use,

```<code>D1:index(D:D, match("zzz", D:D))
</code>```

... to describe your range of worksheet names.

However, if the worksheet names are numeric then,

```<code>D1:index(D:D, match(1e99, D:D))
</code>```

Completed as,

```<code>=SUMPRODUCT(COUNTIF(INDIRECT("'"&D1:index(D:D, match("zzz", D:D))&"'!A1"),E2))
=SUMPRODUCT(COUNTIF(INDIRECT("'"&D1:index(D:D, match(1e99, D:D))&"'!A1"),E2))
</code>```

You could also use OFFSET(D1, 0, 0, COUNTA(D:D), 1). Since you are already using a volatile function with INDIRECT, adding another isn't that big of a deal.

Body:
I have the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D1:D2&"'!A1"),E2))

Took it from here
https://www.extendoffice.com/documents/excel/2541-excel-countif-across-multiple-worksheets.html

Now, i'm making a COUNTA to the D column:

=COUNTA(D:D)

Which will basically result in me having the number of sheets.

Now, i would like to make the first formula use the result of the second one:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D1:***COUNTA RESULT***&"'!A1"),E2))

What is the correct syntax to perform that? Did not manage to succeed.

Body:
Since worksheets typically have alphabetic names and you were attempting a solution with COUNTA not COUNT, use,

D1:index(D:D, match("zzz", D:D))

... to describe your range of worksheet names.

However, if the worksheet names are numeric then,

D1:index(D:D, match(1e99, D:D))

Completed as,

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D1:index(D:D, match("zzz", D:D))&"'!A1"),E2))
=SUMPRODUCT(COUNTIF(INDIRECT("'"&D1:index(D:D, match(1e99, D:D))&"'!A1"),E2))

You could also use OFFSET(D1, 0, 0, COUNTA(D:D), 1). Since you are already using a volatile function with INDIRECT, adding another isn't that big of a deal.


答: You could simply do variable = document.getElementsByTagName("table")[0]. So the variable will contain the entire HTML code of the table

Title: How to assign html table to Variable


问:
in jquery, how to make the right click of the mouse have the same behavior of left click
what i want to realize is : when I right click a link , it also jump to another page like left click. how to do it? thanks very much.</p>

答:
There is a plugin that will handle a lot of this for you: http://abeautifulsite.net/blog/2008/05/jquery-right-click-plugin/

Or if you wanted to roll your own:

Check out the docs for event.which: http://api.jquery.com/event.which/

You can detect which mouse button was clicked:

```<code>$('.clicky').mousedown(function(event) {
switch (event.which) {
    case 1:
    alert('Left mouse button pressed');
    break;
    case 2:
    alert('Middle mouse button pressed');
    break;
    case 3:
    alert('Right mouse button pressed');
       // you would want to prevent default behavior and trigger a click
       event.preventDefault();
       $(this).trigger('click');
    break;
    default:
    alert('You have a strange mouse');
}
});
</code>```

Body:
There is a plugin that will handle a lot of this for you: http://abeautifulsite.net/blog/2008/05/jquery-right-click-plugin/

Or if you wanted to roll your own:

Check out the docs for event.which: http://api.jquery.com/event.which/

You can detect which mouse button was clicked:

$('.clicky').mousedown(function(event) {
switch (event.which) {
    case 1:
    alert('Left mouse button pressed');
    break;
    case 2:
    alert('Middle mouse button pressed');
    break;
    case 3:
    alert('Right mouse button pressed');
       // you would want to prevent default behavior and trigger a click
       event.preventDefault();
       $(this).trigger('click');
    break;
    default:
    alert('You have a strange mouse');
}
});


问:
Getting a Value from a dropdown populated from an SQL database
I have populated a drop down from my MySQL Database successfully. I am now wanting to be able to extracte the value from this dropdown. When ever I extract the value from the dropdown it is only the position value of the value in the list.

Here is the working drop down below:

```<code><?php

include_once("connection.php");

 function fill_name($connect)
 {
      $output = '';
      $sql = "SELECT name, id FROM notes";
      $result = mysqli_query($connect, $sql);
      while($row = mysqli_fetch_array($result))
      {
           $output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
      }
      return $output;
 }

 ?>

 <!DOCTYPE html>
 <html>
      <head>
           <title>Patient Notes View</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
           </script>
      </head>
      <body>
           <br /><br />
           <div class="container">
                <form action="dropdown_selection.php" method="post">
                     <select name="name" id="name">
                          <option value="">Show All Patients</option>
                           <?php echo fill_name($connect); ?>
                     </select>
                     <input type="submit" name="submit" value="Submit" />

                </form>
           </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

      </body>
 </html>
</code>```

And here is the page it then refers to:

```<code><?php
$patient_name = $_POST['name'];
echo $patient_name

?>
</code>```

The output is either 1,2,3,4, but I am wanting it to output what is is selected in the dropdown.

Thnks for your help

答:
You can either change the value of your elements, or remove them. If the element has no value its content will be sent as the value.

The content of this attribute represents the value to be submitted with the form, should this option be selected. If this attribute is omitted, the value is taken from the text content of the option element.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option

So either:

```<code>$output .= '<option value="'.$row["name"].'">'.$row["name"].'</option>';
</code>```

or

```<code>$output .= '<option>'.$row["name"].'</option>';
</code>```

Body:
I have populated a drop down from my MySQL Database successfully. I am now wanting to be able to extracte the value from this dropdown. When ever I extract the value from the dropdown it is only the position value of the value in the list.

Here is the working drop down below:

<?php

include_once("connection.php");

 function fill_name($connect)
 {
      $output = '';
      $sql = "SELECT name, id FROM notes";
      $result = mysqli_query($connect, $sql);
      while($row = mysqli_fetch_array($result))
      {
           $output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
      }
      return $output;
 }

 ?>

 <!DOCTYPE html>

           <title>Patient Notes View</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
           </script>

                <form action="dropdown_selection.php" method="post">
                     <select name="name" id="name">
                          <option value="">Show All Patients</option>
                           <?php echo fill_name($connect); ?>
                     </select>
                     <input type="submit" name="submit" value="Submit" />

                </form>

And here is the page it then refers to:

<?php
$patient_name = $_POST['name'];
echo $patient_name

?>

The output is either 1,2,3,4, but I am wanting it to output what is is selected in the dropdown.

Thnks for your help

Body:
You can either change the value of your elements, or remove them. If the element has no value its content will be sent as the value.

The content of this attribute represents the value to be submitted with the form, should this option be selected. If this attribute is omitted, the value is taken from the text content of the option element.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option

So either:

$output .= '<option value="'.$row["name"].'">'.$row["name"].'</option>';

or

$output .= '<option>'.$row["name"].'</option>';


问:
Google Drive Checksum
Is there a way for me to retrieve Checksums via the Drive API?

This answer goes through doing it via the documentations "Try it" function, which has a horrible interface.

How can I do this via the .NET (C#) Google Drive APIs?
Or, how can I do it using my own post/get requests?

答:
Try the .NET Quickstart since its a basic list files method.

```<code>using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DriveQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/drive-dotnet-quickstart.json
        static string[] Scopes = {  DriveService.Scope.DriveReadonly };
        static string ApplicationName = "Drive API .NET Quickstart";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 10;
            listRequest.Fields = "nextPageToken, files(id, name)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
            Console.WriteLine("Files:");
            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    Console.WriteLine("{0} ({1})", file.Name, file.Id);
                }
            }
            else
            {
                Console.WriteLine("No files found.");
            }
            Console.Read();

        }
    }
}

    }
}
</code>```

edit this line:

```<code>listRequest.Fields = "nextPageToken, files(id, name)";
</code>```

To:

```<code>listRequest.Fields = "nextPageToken, files(id, name, md5Checksum)";
</code>```

The solution from the link above is correct, Try it function will help you familiarize yourself with each method and how the response and request is formed.

Hope this helps.

Title: Google Drive Checksum

Body:
Try the .NET Quickstart since its a basic list files method.

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DriveQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/drive-dotnet-quickstart.json
        static string[] Scopes = {  DriveService.Scope.DriveReadonly };
        static string ApplicationName = "Drive API .NET Quickstart";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 10;
            listRequest.Fields = "nextPageToken, files(id, name)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
            Console.WriteLine("Files:");
            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    Console.WriteLine("{0} ({1})", file.Name, file.Id);
                }
            }
            else
            {
                Console.WriteLine("No files found.");
            }
            Console.Read();

        }
    }
}

    }
}

edit this line:

listRequest.Fields = "nextPageToken, files(id, name)";

To:

listRequest.Fields = "nextPageToken, files(id, name, md5Checksum)";

The solution from the link above is correct, Try it function will help you familiarize yourself with each method and how the response and request is formed.

Hope this helps.


问:
How To Modify Value In Changeset - Elixir?
I am new to phoenix framework,lets say i  have a model like follow with  changeset

```<code>schema "users" do
 field :name, :string
 field :email, :string
 field :countryCode, :string
 field :phone, :string
end

def changeset_user_register(struct, params \\%{}) do
  struct
  |> cast(params, [:name, :email, :countryCode, :phone])
  |> validate_required(:name, [message: "Name Must Not Be Empty"])
  |> validate_required(:countryCode, [message: "countryCode Must Not Be Empty"])
  |> validate_required(:phone, [message: "Phone Number Must Not Be Empty"])
  |> valid_phone_number
end
</code>```

params from form looks like %{name: 'elixir', countryCode: 'IN', phone: '97989*****'}

i am currently using ex_phone_number to validate phone number, my custom validator valid_phone_number looks like follow

```<code>defp valid_phone_number(struct) do
countryCode = get_field(struct, :countryCode) #get_field used to get values from struct
phone = get_field(struct, :phone)
case ExPhoneNumber.parse(phone, countryCode) do
  {:ok, phone_number} ->
    if ExPhoneNumber.is_valid_number?(phone_number) do
      e156_number = ExPhoneNumber.format(phone_number, :e164)
      %{struct | phone: e156_number}
      struct
    else
      add_error(struct, :phone, "Invalid Phone Number")
    end
  {:error, phone_number}->
    struct
 end
end
</code>```

Instead of storing countryCode and phone in differnt column, I am trying to store e164 format number to my database so i modify the number e156_number = ExPhoneNumber.format(phone_number, :e164)in changeset after checking phone number is valid.when i trying to update phone in struct like follow %{struct | phone: e156_number} value is not updating instead it stores value returned from form %{phone: '97989*****'}, what mistake i made here and how can i remove countryCode also in changeset?

答:
To modify a value in a changeset, you should to use Ecto.Changeset.put_change/3. So, your if should look like:

```<code>if ExPhoneNumber.is_valid_number?(phone_number) do
  e156_number = ExPhoneNumber.format(phone_number, :e164)
  put_change(struct, :phone, e156_number)
else
  add_error(struct, :phone, "Invalid Phone Number")
end
</code>```

Sidenote: valid_phone_number here is actually receiving an Ecto.Changeset, not the model Struct (technically the Ecto.Changeset is also an Elixir Struct but it's not your User struct), so changeset would be a better name for that variable.

Body:
I am new to phoenix framework,lets say i  have a model like follow with  changeset

schema "users" do
 field :name, :string
 field :email, :string
 field :countryCode, :string
 field :phone, :string
end

def changeset_user_register(struct, params \\%{}) do
  struct
  |> cast(params, [:name, :email, :countryCode, :phone])
  |> validate_required(:name, [message: "Name Must Not Be Empty"])
  |> validate_required(:countryCode, [message: "countryCode Must Not Be Empty"])
  |> validate_required(:phone, [message: "Phone Number Must Not Be Empty"])
  |> valid_phone_number
end

params from form looks like %{name: 'elixir', countryCode: 'IN', phone: '97989*****'}

i am currently using ex_phone_number to validate phone number, my custom validator valid_phone_number looks like follow

defp valid_phone_number(struct) do
countryCode = get_field(struct, :countryCode) #get_field used to get values from struct
phone = get_field(struct, :phone)
case ExPhoneNumber.parse(phone, countryCode) do
  {:ok, phone_number} ->
    if ExPhoneNumber.is_valid_number?(phone_number) do
      e156_number = ExPhoneNumber.format(phone_number, :e164)
      %{struct | phone: e156_number}
      struct
    else
      add_error(struct, :phone, "Invalid Phone Number")
    end
  {:error, phone_number}->
    struct
 end
end

Instead of storing countryCode and phone in differnt column, I am trying to store e164 format number to my database so i modify the number e156_number = ExPhoneNumber.format(phone_number, :e164)in changeset after checking phone number is valid.when i trying to update phone in struct like follow %{struct | phone: e156_number} value is not updating instead it stores value returned from form %{phone: '97989*****'}, what mistake i made here and how can i remove countryCode also in changeset?

Body:
To modify a value in a changeset, you should to use Ecto.Changeset.put_change/3. So, your if should look like:

if ExPhoneNumber.is_valid_number?(phone_number) do
  e156_number = ExPhoneNumber.format(phone_number, :e164)
  put_change(struct, :phone, e156_number)
else
  add_error(struct, :phone, "Invalid Phone Number")
end

Sidenote: valid_phone_number here is actually receiving an Ecto.Changeset, not the model Struct (technically the Ecto.Changeset is also an Elixir Struct but it's not your User struct), so changeset would be a better name for that variable.


问:
Django: Machine learning model in server side?
I have a Word2Vec model(One of Machine learning model) and could get this pre-trained model by filename :

```<code>model = Word2Vec.load(fname)
</code>```

So, I can get some prediction by using this model:

prediction = model.predict(X)

What I'm trying to do is to get request(including query word) from user and query this data to my pre-trained model and get prediction so that server could send response with this prediction data. This process should occur every time user send queries, so this pre-trained model should always be in memory.

To implement this, I think I have to use Redis, Celery kinda thing, but as I know of, Celery is working asynchronously with Django web application, so it would not be suitable for what I want to do...

How can I implement this function in my Django application?

Thanks.

答:
You don't actually need Redis or celery for this.

Before I post the solution using Django, I should mention that if you only need a web interface for your ML project, that is, you don't need Django's fancy ORM, admin, etc, you should go with Flask. It's perfect for your use case.

Solution using Flask:

It's very easy to store your trained model in memory using Flask:

```<code># ...
# your Flask application code
# ...
# ...

if __name__ == '__main__':
    model = Word2Vec.load(fname)
    app.run()
</code>```

If you're interested, the complete example is here.

Solution using Django:

You can utilise Django's cache framework to store your model. First, activate the local memory cache backend. Instructions are here.

Now, you'll need to store your model in the cache.

```<code>from django.core.cache import cache

model_cache_key = 'model_cache'
# this key is used to `set` and `get`
# your trained model from the cache

model = cache.get(model_cache_key) # get model from cache

if model is None:
    # your model isn't in the cache
    # so `set` it
    model = Word2Vec.load(fname) # load model
    cache.set(model_cache_key, model, None) # save in the cache
    # in above line, None is the timeout parameter. It means cache forever

# now predict
prediction = model.predict(...)
</code>```

You can keep the above code in your views, but I'd rather you create a separate file for that and then import this file in you views.

You can find the full example is on this blog.

Body:
I have a Word2Vec model(One of Machine learning model) and could get this pre-trained model by filename :

model = Word2Vec.load(fname)

So, I can get some prediction by using this model:

prediction = model.predict(X)

What I'm trying to do is to get request(including query word) from user and query this data to my pre-trained model and get prediction so that server could send response with this prediction data. This process should occur every time user send queries, so this pre-trained model should always be in memory.

To implement this, I think I have to use Redis, Celery kinda thing, but as I know of, Celery is working asynchronously with Django web application, so it would not be suitable for what I want to do...

How can I implement this function in my Django application?

Thanks.

Body:
You don't actually need Redis or celery for this.

Before I post the solution using Django, I should mention that if you only need a web interface for your ML project, that is, you don't need Django's fancy ORM, admin, etc, you should go with Flask. It's perfect for your use case.

Solution using Flask:

It's very easy to store your trained model in memory using Flask:

# ...
# your Flask application code
# ...
# ...

if __name__ == '__main__':
    model = Word2Vec.load(fname)
    app.run()

If you're interested, the complete example is here.

Solution using Django:

You can utilise Django's cache framework to store your model. First, activate the local memory cache backend. Instructions are here.

Now, you'll need to store your model in the cache.

from django.core.cache import cache

model_cache_key = 'model_cache'
# this key is used to `set` and `get`
# your trained model from the cache

model = cache.get(model_cache_key) # get model from cache

if model is None:
    # your model isn't in the cache
    # so `set` it
    model = Word2Vec.load(fname) # load model
    cache.set(model_cache_key, model, None) # save in the cache
    # in above line, None is the timeout parameter. It means cache forever

# now predict
prediction = model.predict(...)

You can keep the above code in your views, but I'd rather you create a separate file for that and then import this file in you views.

You can find the full example is on this blog.

ContentLicense: CC BY-SA 4.0


问:
The Point values keep blinking (IsShowPointValues)
I have made a graph and it shows the value every time I move the cursor on any point. I use zedGraphControl1.IsShowPointValues = true; for that.

The problem is the ToolTip that is shown from it is blinking. After looking around on the internet, I found this forum thread:
http://sourceforge.net/p/zedgraph/patches/87/

Is there anyone who knows how to use that patch?
or is there any other solution?

答:
The fix has a flaw. Returning to the same point doesn't display the tool tip. To fix this I replaced every instance in the section of code

```<code>this.pointToolTip.Active = false;
</code>```

with

```<code>{ this.pointToolTip.Active = false; this.pointToolTip.SetToolTip(this, ""); }
</code>```

Body:
The fix has a flaw. Returning to the same point doesn't display the tool tip. To fix this I replaced every instance in the section of code

this.pointToolTip.Active = false;

with

{ this.pointToolTip.Active = false; this.pointToolTip.SetToolTip(this, ""); }


问:
How to find the period of a periodic function using FFT?
Assume I have a smooth function (represented as a vector):

```<code>x=0:0.1:1000;
y=sin(2*x);
</code>```

and I want to find its periodicity - pi (or even its frequency -2 ) .
I have tried the following:

```<code>nfft=1024;
Y=fft(y,nfft);
Y=abs(Y(1:nfft/2));
plot(Y);
</code>```

but obviously it doesn't work (the plot does not give me a peak at "2" ).

Will you please help me find a way to find the value "2"?

Thanks in advance

答:
You have several issues here:

You are computing the fft of x when your actual signal is y

x should be in radians

You need to define a sampling rate and use that to determine the frequency values along the x axis

So once we correct all of these things, we get:

```<code>samplingRate = 1000;   % Samples per period
nPeriods = 10;
nSamples = samplingRate * nPeriods;

x = linspace(0, 2*pi*nPeriods, nSamples);
y = sin(2*x);

F = fft(y);

amplitude = abs(F / nSamples);

f = samplingRate / nSamples*[0:(nSamples/2-1),-nSamples/2:-1];

plot(f, amplitude)
</code>```

Body:
Assume I have a smooth function (represented as a vector):

x=0:0.1:1000;
y=sin(2*x);

and I want to find its periodicity - pi (or even its frequency -2 ) .
I have tried the following:

nfft=1024;
Y=fft(y,nfft);
Y=abs(Y(1:nfft/2));
plot(Y);

but obviously it doesn't work (the plot does not give me a peak at "2" ).

Will you please help me find a way to find the value "2"?

Thanks in advance

Body:
You have several issues here:

You are computing the fft of x when your actual signal is y

x should be in radians

You need to define a sampling rate and use that to determine the frequency values along the x axis

So once we correct all of these things, we get:

samplingRate = 1000;   % Samples per period
nPeriods = 10;
nSamples = samplingRate * nPeriods;

x = linspace(0, 2*pi*nPeriods, nSamples);
y = sin(2*x);

F = fft(y);

amplitude = abs(F / nSamples);

f = samplingRate / nSamples*[0:(nSamples/2-1),-nSamples/2:-1];

plot(f, amplitude)


问:
Where is the Nixos configuration located for the nix image on dockerhub?
According to https://chris-martin.org/2015/installing-nixos there is a /etc/nixos/configuration.nix file present.

I'm using the docker container from https://hub.docker.com/r/nixos/nix/ and running

```<code>find . -name "configuration.nix"
</code>```

within the container returns no results.

Where is this configuration located?

答:
If for some reason it doesn't exist or you cannot find it, you can pass everything you need for building your system as arguments to nixos-rebuild:

```<code>git clone --branch release-17.03 https://github.com/nixos/nixpkgs $HOME/nixpkgs
mkdir -p $HOME/nix-config
nixos-generate-config --dir $HOME/nix-config

nixos-install -I nixos-config=$HOME/nix-config/configuration.nix -I nixpkgs=$HOME/nixpkgs
</code>```

I prefer doing it this way anyway, as it allows me to use my configured nixpkgs and nix-files which I store in a personal git repo.

Body:
According to https://chris-martin.org/2015/installing-nixos there is a /etc/nixos/configuration.nix file present.

I'm using the docker container from https://hub.docker.com/r/nixos/nix/ and running

find . -name "configuration.nix"

within the container returns no results.

Where is this configuration located?

Body:
If for some reason it doesn't exist or you cannot find it, you can pass everything you need for building your system as arguments to nixos-rebuild:

git clone --branch release-17.03 https://github.com/nixos/nixpkgs $HOME/nixpkgs
mkdir -p $HOME/nix-config
nixos-generate-config --dir $HOME/nix-config

nixos-install -I nixos-config=$HOME/nix-config/configuration.nix -I nixpkgs=$HOME/nixpkgs

I prefer doing it this way anyway, as it allows me to use my configured nixpkgs and nix-files which I store in a personal git repo.


问:
removeClass not working
I have a li list and this list working data-project-id

I want to click list_title removeClass e "open" but not working.

tip : toggleClass not working.

```<code><div class="project-side-list scrollbar-inner">
   <ul id="sortable">
      <li data-project-id="1">
         <div class="list-title">Content</div>
           <div class="list-project-detail-content">
           </div>
      </li>
  </ul>
</div>
</code>```

JS:

```<code>$(document.body).on("click", "[data-project-id]", function() {
  var e = $(this),
    list = $(".project-side-list ul li "),
    list_title = $(".project-side-list ul li .list-title");

  if (e.hasClass("open")) {

    $(list_title).click(function() {
      e.removeClass('open');
    });

  } else {
    list.removeClass("open");
    e.addClass("open");
  }
});
</code>```

答:
First of all your html is invalid, you didn't close your
 tag.

Here is working example, if you want to dynamically load your list later on you can use delegate function.

function openToggler() {
  var _this = $(this);

  var element = _this.closest('li[data-project-id]');
  var elementId = element.attr('data-project-id');

  $('.project-side-list li[data-project-id]').not('[data-project-id="' + elementId + '"]').removeClass('open');

  element.toggleClass('open');
}

$('.list-title').click(openToggler);
//$('.project-side-list').delegate('.list-title', 'click', openToggler);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li {
 color: red;
}

li.open {
  color: blue;
}</code>```

Content

Example

Example Content

```

Title: removeClass not working

Body:
I have a li list and this list working data-project-id

I want to click list_title removeClass e "open" but not working.

tip : toggleClass not working.

Content

JS:

$(document.body).on("click", "[data-project-id]", function() {
  var e = $(this),
    list = $(".project-side-list ul li "),
    list_title = $(".project-side-list ul li .list-title");

  if (e.hasClass("open")) {

    $(list_title).click(function() {
      e.removeClass('open');
    });

  } else {
    list.removeClass("open");
    e.addClass("open");
  }
});

Body:
First of all your html is invalid, you didn't close your <li> tag.

Here is working example, if you want to dynamically load your list later on you can use delegate function.

function openToggler() {
  var _this = $(this);

  var element = _this.closest('li[data-project-id]');
  var elementId = element.attr('data-project-id');

  $('.project-side-list li[data-project-id]').not('[data-project-id="' + elementId + '"]').removeClass('open');

  element.toggleClass('open');
}

$('.list-title').click(openToggler);
//$('.project-side-list').delegate('.list-title', 'click', openToggler);

li {
 color: red;
}

li.open {
  color: blue;
}

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<div class="project-side-list scrollbar-inner">
   <ul id="sortable">
      <li data-project-id="1">
         <div class="list-title">Content</div>
           <div class="list-project-detail-content">
           </div>
      </li>
      <li data-project-id="2">
         <div class="list-title">Example</div>
           <div class="list-project-detail-content">
           </div>
      </li>
      <li data-project-id="3">
         <div class="list-title">Example Content</div>
           <div class="list-project-detail-content">
           </div>
      </li>
  </ul>
</div>


问:
Android button link to another page when login is correct
I have the code below that currently has a login of an id and password, when the link is clicked I want it to go to a profile page only if the login is correct, at the minute you can enter whatever you want or nothing at all and click Login and this will take you to the profile page. Can someone show me how I can improve my code so that the Login button will only link to the profile page if the login details are correct, according to what is in the database? I have more code that I can upload if you need it. Thanks

```<code>public class MainActivity extends ActionBarActivity {

EditText doctor_number, password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    doctor_number = (EditText)findViewById(R.id.etDoctorNumber);
    password = (EditText)findViewById(R.id.etPassword);
    final Button btnLogin = (Button) findViewById(R.id.btnLogin);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            OnLogin(v);
            //Intent profileIntent = new Intent(MainActivity.this, Profile.class);
            //MainActivity.this.startActivity(profileIntent);
        }
    });
}

public void OnLogin(View view){
    String str_doctor_number = doctor_number.getText().toString();
    String str_password = password.getText().toString();
    String type = "Login";

    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, str_doctor_number, str_password);
}
}
</code>```

====
BackgroundWorker.java

```<code>public class BackgroundWorker extends AsyncTask<String, Void, String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx){
        context = ctx;
     }

@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String login_url = "";
    String register_url = "";
    if (type.equals("Login")) {
        try {
            String doctorNumber = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("doctor_number", "UTF-8")+"="+URLEncoder.encode(doctorNumber, "utf-8")+"&"
            +URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "utf-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result ="";
            String line ="";
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (type.equals("Register")){
        try {
            String patient_name = params[1];
            String check_in_date = params[2];
            String room_number = params[3];
            String bed_number = params[4];
            String notes = params[5];
            URL url = new URL(register_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("patient_name", "UTF-8")+"="+URLEncoder.encode(patient_name, "utf-8")+"&"
                    + URLEncoder.encode("check_in_date", "UTF-8")+"="+URLEncoder.encode(check_in_date, "utf-8")+"&"
                    + URLEncoder.encode("room_number", "UTF-8")+"="+URLEncoder.encode(room_number, "utf-8")+"&"
                    + URLEncoder.encode("bed_number", "UTF-8")+"="+URLEncoder.encode(bed_number, "utf-8")+"&"
                    + URLEncoder.encode("notes", "UTF-8")+"="+URLEncoder.encode(notes, "utf-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result ="";
            String line ="";
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login status: ");
}

@Override
protected void onPostExecute(String result) {
    if (result.contains("Login Successful")){
        Intent profileIntent = new Intent(context, Profile.class);
        context.startActivity(profileIntent);
    } else {
        alertDialog.setMessage(result);
        alertDialog.show();
    }
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
}
</code>```

答:
Try this:

```<code>btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            OnLogin(v);
        }
    });
</code>```

Now inside BackgroundWorker.java
make following changes:

```<code>@Override
protected void onPostExecute(String result) {
    if(result.equalsIgnoreCase("login successful")){
        Intent profileIntent = new Intent(MainActivity.this, Profile.class);
            MainActivity.this.startActivity(profileIntent);
    } else {
        alertDialog.setMessage(result);
        alertDialog.show();
    }
}
</code>```

Body:
I have the code below that currently has a login of an id and password, when the link is clicked I want it to go to a profile page only if the login is correct, at the minute you can enter whatever you want or nothing at all and click Login and this will take you to the profile page. Can someone show me how I can improve my code so that the Login button will only link to the profile page if the login details are correct, according to what is in the database? I have more code that I can upload if you need it. Thanks

public class MainActivity extends ActionBarActivity {

EditText doctor_number, password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    doctor_number = (EditText)findViewById(R.id.etDoctorNumber);
    password = (EditText)findViewById(R.id.etPassword);
    final Button btnLogin = (Button) findViewById(R.id.btnLogin);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            OnLogin(v);
            //Intent profileIntent = new Intent(MainActivity.this, Profile.class);
            //MainActivity.this.startActivity(profileIntent);
        }
    });
}

public void OnLogin(View view){
    String str_doctor_number = doctor_number.getText().toString();
    String str_password = password.getText().toString();
    String type = "Login";

    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, str_doctor_number, str_password);
}
}

====
BackgroundWorker.java

public class BackgroundWorker extends AsyncTask<String, Void, String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx){
        context = ctx;
     }

@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String login_url = "";
    String register_url = "";
    if (type.equals("Login")) {
        try {
            String doctorNumber = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("doctor_number", "UTF-8")+"="+URLEncoder.encode(doctorNumber, "utf-8")+"&"
            +URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "utf-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result ="";
            String line ="";
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (type.equals("Register")){
        try {
            String patient_name = params[1];
            String check_in_date = params[2];
            String room_number = params[3];
            String bed_number = params[4];
            String notes = params[5];
            URL url = new URL(register_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("patient_name", "UTF-8")+"="+URLEncoder.encode(patient_name, "utf-8")+"&"
                    + URLEncoder.encode("check_in_date", "UTF-8")+"="+URLEncoder.encode(check_in_date, "utf-8")+"&"
                    + URLEncoder.encode("room_number", "UTF-8")+"="+URLEncoder.encode(room_number, "utf-8")+"&"
                    + URLEncoder.encode("bed_number", "UTF-8")+"="+URLEncoder.encode(bed_number, "utf-8")+"&"
                    + URLEncoder.encode("notes", "UTF-8")+"="+URLEncoder.encode(notes, "utf-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result ="";
            String line ="";
            while ((line = bufferedReader.readLine()) != null){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login status: ");
}

@Override
protected void onPostExecute(String result) {
    if (result.contains("Login Successful")){
        Intent profileIntent = new Intent(context, Profile.class);
        context.startActivity(profileIntent);
    } else {
        alertDialog.setMessage(result);
        alertDialog.show();
    }
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
}

Body:
Try this:

btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            OnLogin(v);
        }
    });

Now inside BackgroundWorker.java
make following changes:

@Override
protected void onPostExecute(String result) {
    if(result.equalsIgnoreCase("login successful")){
        Intent profileIntent = new Intent(MainActivity.this, Profile.class);
            MainActivity.this.startActivity(profileIntent);
    } else {
        alertDialog.setMessage(result);
        alertDialog.show();
    }
}


问:
SQL result to JSON as fast as possible
I'm trying to transform the Go built-in sql result to JSON. I'm using goroutines for that but I got problems.

The base problem:

There is a really big database with around 200k user and I have to serve them through tcp sockets in a microservice based system. To get the users from the database spent 20ms but transform this bunch of data to JSON spend 10 seconds with the current solution. This is why I want to use goroutines.

Solution with Goroutines:

```<code>func getJSON(rows *sql.Rows, cnf configure.Config) ([]byte, error) {
    log := logan.Log{
        Cnf: cnf,
    }

    cols, _ := rows.Columns()

    defer rows.Close()

    done := make(chan struct{})
    go func() {
        defer close(done)
        for result := range resultChannel {
            results = append(
                results,
                result,
            )
        }
    }()

    wg.Add(1)
    go func() {
        for rows.Next() {
            wg.Add(1)
            go handleSQLRow(cols, rows)
        }
        wg.Done()
    }()

    go func() {
        wg.Wait()
        defer close(resultChannel)
    }()

    <-done

    s, err := json.Marshal(results)
    results = []resultContainer{}
    if err != nil {
        log.Context(1).Error(err)
    }
    rows.Close()
    return s, nil
}

func handleSQLRow(cols []string, rows *sql.Rows) {
    defer wg.Done()
    result := make(map[string]string, len(cols))
    fmt.Println("asd -> " + strconv.Itoa(counter))
    counter++
    rawResult := make([][]byte, len(cols))
    dest := make([]interface{}, len(cols))

    for i := range rawResult {
        dest[i] = &rawResult[i]
    }
    rows.Scan(dest...) // GET PANIC
    for i, raw := range rawResult {
        if raw == nil {
            result[cols[i]] = ""
        } else {
            fmt.Println(string(raw))
            result[cols[i]] = string(raw)
        }
    }
    resultChannel <- result
}
</code>```

This solution give me a panic with the following message:

```<code>panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x45974c]

goroutine 408 [running]:
panic(0x7ca140, 0xc420010150)
    /usr/lib/golang/src/runtime/panic.go:500 +0x1a1
database/sql.convertAssign(0x793960, 0xc420529210, 0x7a5240, 0x0, 0x0, 0x0)
    /usr/lib/golang/src/database/sql/convert.go:88 +0x1ef1
database/sql.(*Rows).Scan(0xc4203e4060, 0xc42021fb00, 0x44, 0x44, 0x44, 0x44)
    /usr/lib/golang/src/database/sql/sql.go:1850 +0xc2
github.com/PumpkinSeed/zerodb/operations.handleSQLRow(0xc420402000, 0x44, 0x44, 0xc4203e4060)
    /home/loow/gopath/src/github.com/PumpkinSeed/zerodb/operations/operations.go:290 +0x19c
created by github.com/PumpkinSeed/zerodb/operations.getJSON.func2
    /home/loow/gopath/src/github.com/PumpkinSeed/zerodb/operations/operations.go:258 +0x91
exit status 2
</code>```

The current solution which is working but spend too much time:

```<code>func getJSON(rows *sql.Rows, cnf configure.Config) ([]byte, error) {
    log := logan.Log{
        Cnf: cnf,
    }
    var results []resultContainer
    cols, _ := rows.Columns()
    rawResult := make([][]byte, len(cols))
    dest := make([]interface{}, len(cols))

    for i := range rawResult {
        dest[i] = &rawResult[i]
    }

    defer rows.Close()

    for rows.Next() {

        result := make(map[string]string, len(cols))
        rows.Scan(dest...)
        for i, raw := range rawResult {
            if raw == nil {

                result[cols[i]] = ""

            } else {
                result[cols[i]] = string(raw)
            }
        }

        results = append(results, result)
    }
    s, err := json.Marshal(results)
    if err != nil {
        log.Context(1).Error(err)
    }
    rows.Close()
    return s, nil
}
</code>```

Question:

Why the goroutine solution give me an error, where it is not an obvious panic, because the first ~200 goroutine running properly?!

UPDATE

Performance test for the original working solution:

```<code>INFO[0020] setup taken -> 3.149124658s                   file=operations.go func=operations.getJSON line=260 service="Database manager" ts="2017-04-02 19:45:27.132881211 +0100 BST"
INFO[0025] toJSON taken -> 5.317647046s                  file=operations.go func=operations.getJSON line=263 service="Database manager" ts="2017-04-02 19:45:32.450551417 +0100 BST"
</code>```

The sql to map is 3 sec and to json is 5 sec.

答: Go routines won't improve performance on CPU-bound operations like JSON marshaling. What you need is a more efficient JSON marshaler. There are some available, although I haven't used any.  A simple Google search for 'faster JSON marshaling' will turn up many results. A popular one is ffjson.  I suggest starting there.</p>

Title: SQL result to JSON as fast as possible

Body:
I'm trying to transform the Go built-in sql result to JSON. I'm using goroutines for that but I got problems.

The base problem:

There is a really big database with around 200k user and I have to serve them through tcp sockets in a microservice based system. To get the users from the database spent 20ms but transform this bunch of data to JSON spend 10 seconds with the current solution. This is why I want to use goroutines.

Solution with Goroutines:

func getJSON(rows *sql.Rows, cnf configure.Config) ([]byte, error) {
    log := logan.Log{
        Cnf: cnf,
    }

    cols, _ := rows.Columns()

    defer rows.Close()

    done := make(chan struct{})
    go func() {
        defer close(done)
        for result := range resultChannel {
            results = append(
                results,
                result,
            )
        }
    }()

    wg.Add(1)
    go func() {
        for rows.Next() {
            wg.Add(1)
            go handleSQLRow(cols, rows)
        }
        wg.Done()
    }()

    go func() {
        wg.Wait()
        defer close(resultChannel)
    }()

    <-done

    s, err := json.Marshal(results)
    results = []resultContainer{}
    if err != nil {
        log.Context(1).Error(err)
    }
    rows.Close()
    return s, nil
}

func handleSQLRow(cols []string, rows *sql.Rows) {
    defer wg.Done()
    result := make(map[string]string, len(cols))
    fmt.Println("asd -> " + strconv.Itoa(counter))
    counter++
    rawResult := make([][]byte, len(cols))
    dest := make([]interface{}, len(cols))

    for i := range rawResult {
        dest[i] = &rawResult[i]
    }
    rows.Scan(dest...) // GET PANIC
    for i, raw := range rawResult {
        if raw == nil {
            result[cols[i]] = ""
        } else {
            fmt.Println(string(raw))
            result[cols[i]] = string(raw)
        }
    }
    resultChannel <- result
}

This solution give me a panic with the following message:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x45974c]

goroutine 408 [running]:
panic(0x7ca140, 0xc420010150)
    /usr/lib/golang/src/runtime/panic.go:500 +0x1a1
database/sql.convertAssign(0x793960, 0xc420529210, 0x7a5240, 0x0, 0x0, 0x0)
    /usr/lib/golang/src/database/sql/convert.go:88 +0x1ef1
database/sql.(*Rows).Scan(0xc4203e4060, 0xc42021fb00, 0x44, 0x44, 0x44, 0x44)
    /usr/lib/golang/src/database/sql/sql.go:1850 +0xc2
github.com/PumpkinSeed/zerodb/operations.handleSQLRow(0xc420402000, 0x44, 0x44, 0xc4203e4060)
    /home/loow/gopath/src/github.com/PumpkinSeed/zerodb/operations/operations.go:290 +0x19c
created by github.com/PumpkinSeed/zerodb/operations.getJSON.func2
    /home/loow/gopath/src/github.com/PumpkinSeed/zerodb/operations/operations.go:258 +0x91
exit status 2

The current solution which is working but spend too much time:

func getJSON(rows *sql.Rows, cnf configure.Config) ([]byte, error) {
    log := logan.Log{
        Cnf: cnf,
    }
    var results []resultContainer
    cols, _ := rows.Columns()
    rawResult := make([][]byte, len(cols))
    dest := make([]interface{}, len(cols))

    for i := range rawResult {
        dest[i] = &rawResult[i]
    }

    defer rows.Close()

    for rows.Next() {

        result := make(map[string]string, len(cols))
        rows.Scan(dest...)
        for i, raw := range rawResult {
            if raw == nil {

                result[cols[i]] = ""

            } else {
                result[cols[i]] = string(raw)
            }
        }

        results = append(results, result)
    }
    s, err := json.Marshal(results)
    if err != nil {
        log.Context(1).Error(err)
    }
    rows.Close()
    return s, nil
}

Question:

Why the goroutine solution give me an error, where it is not an obvious panic, because the first ~200 goroutine running properly?!

UPDATE

Performance test for the original working solution:

INFO[0020] setup taken -> 3.149124658s                   file=operations.go func=operations.getJSON line=260 service="Database manager" ts="2017-04-02 19:45:27.132881211 +0100 BST"
INFO[0025] toJSON taken -> 5.317647046s                  file=operations.go func=operations.getJSON line=263 service="Database manager" ts="2017-04-02 19:45:32.450551417 +0100 BST"

The sql to map is 3 sec and to json is 5 sec.


问:
How to align tkinter widgets?
How do I align my Radiobuttons? I can add spaces to test4 but that solution doesn't seem proper. Here's what it looks like at the moment—as you can see text111111 has extra chars. I've tried using padx.

My code:

```<code>from tkinter import *

class GUI:
    def __init__(self, master):

        self.iconnum = IntVar()
        self.master = master
        self.master.title('test')
        self.master.resizable(width=False, height=False)
        self.master.maxsize(500, 250)
        self.master.minsize(500, 250)

        self.test1 = Radiobutton(master, text="test11111111", variable=self.iconnum,
                                 value=1, )
        self.test2 = Radiobutton(master, text="test2", variable=0, value=2, )
        self.test3 = Radiobutton(master, text="test3", variable=0, value=3, )
        self.test4 = Radiobutton(master, text="test4", variable=0, value=4)
        self.test1.grid(row=2, columnspan=1)
        self.test2.grid(row=2, columnspan=2)
        self.test3.grid(row=2, column=1)
        self.test4.grid(row=3, columnspan=1)

        self.Checker = Radiobutton(master, text="test5", indicatoron=0, height=1, width=35,
                                   value=0, command=self.icon_switcher) #var=Selection)
        self.Turbo = Radiobutton(master, text="test6", indicatoron=0, height=1, width=35,
                                 value=1, command=self.icon_switcher) #var#=Selection)

        self.Checker.grid(row=1)
        self.Turbo.grid(row=1, column=1,   )

    def icon_switcher(self):
        print("Hello")

root = Tk()
gui = GUI(root)

root.mainloop()
</code>```

答:
You should use the sticky keyword argument in order to align your widgets better when using grid.

```<code>import Tkinter as tk

window = tk.Tk()
radio = tk.Radiobutton(window, text="I'm a radio")
radio.grid(column=0, row=0, sticky=tk.N+tk.S+tk.W+tk.E)

window.mainloop()
</code>```

You can use any combination of the N, S, W and E members of the Tkinter module. This parameter will make your widgets stick to the sides of the cell you have specified, somewhat like justification in text. If your widget is resizable, such as with Button, the widget will also automatically resize to fit the cell if you use all of the N, S, W and E members.

Important to note is that this can only do so much as to make the widgets stick to the edges of the cell. Sometimes it is necessary to actually resize the cell or move your widget to another cell.

In your example image, you have Buttons with a set size that is larger than the default size (the example code you provide is incomplete). This causes the cell, and the whole columns that the cells of these Buttons are in, to become wider. In this case, you might want to use the columnspan keyword argument to divide your column into smaller, resizable, parts, so that your Radiobuttons can be aligned still better.

```<code>import Tkinter as tk

window = tk.Tk()
radio_one = tk.Radiobutton(window, text="I'm a radio")
radio_two = tk.Radiobutton(window, text="I'm another radio")
button = tk.Button(window, text="I am a very long button", width=50)
button.grid(row=0, column=0, columnspan=2, sticky=tk.N+tk.S+tk.W+tk.E)
radio_one.grid(column=0, row=1, sticky=tk.N+tk.W)
radio_two.grid(column=1, row=1, sticky=tk.N+tk.W)

window.mainloop()
</code>```

If you would like more information on what parameters the grid geometry manager can use, I suggest you read this tutorial, I have found it to be very helpful in the past.

As a sidenote, please note that you use the variable keyword argument in the declaration of your Radiobuttons incorrectly. You must pass either a tk.StringVar, tk.IntVar or some other comparable object, as described here.

Title: How to align tkinter widgets?

Body:
How do I align my Radiobuttons? I can add spaces to test4 but that solution doesn't seem proper. Here's what it looks like at the moment—as you can see text111111 has extra chars. I've tried using padx.

My code:

from tkinter import *

class GUI:
    def __init__(self, master):

        self.iconnum = IntVar()
        self.master = master
        self.master.title('test')
        self.master.resizable(width=False, height=False)
        self.master.maxsize(500, 250)
        self.master.minsize(500, 250)

        self.test1 = Radiobutton(master, text="test11111111", variable=self.iconnum,
                                 value=1, )
        self.test2 = Radiobutton(master, text="test2", variable=0, value=2, )
        self.test3 = Radiobutton(master, text="test3", variable=0, value=3, )
        self.test4 = Radiobutton(master, text="test4", variable=0, value=4)
        self.test1.grid(row=2, columnspan=1)
        self.test2.grid(row=2, columnspan=2)
        self.test3.grid(row=2, column=1)
        self.test4.grid(row=3, columnspan=1)

        self.Checker = Radiobutton(master, text="test5", indicatoron=0, height=1, width=35,
                                   value=0, command=self.icon_switcher) #var=Selection)
        self.Turbo = Radiobutton(master, text="test6", indicatoron=0, height=1, width=35,
                                 value=1, command=self.icon_switcher) #var#=Selection)

        self.Checker.grid(row=1)
        self.Turbo.grid(row=1, column=1,   )

    def icon_switcher(self):
        print("Hello")

root = Tk()
gui = GUI(root)

root.mainloop()

Body:
You should use the sticky keyword argument in order to align your widgets better when using grid.

import Tkinter as tk

window = tk.Tk()
radio = tk.Radiobutton(window, text="I'm a radio")
radio.grid(column=0, row=0, sticky=tk.N+tk.S+tk.W+tk.E)

window.mainloop()

You can use any combination of the N, S, W and E members of the Tkinter module. This parameter will make your widgets stick to the sides of the cell you have specified, somewhat like justification in text. If your widget is resizable, such as with Button, the widget will also automatically resize to fit the cell if you use all of the N, S, W and E members.

Important to note is that this can only do so much as to make the widgets stick to the edges of the cell. Sometimes it is necessary to actually resize the cell or move your widget to another cell.

In your example image, you have Buttons with a set size that is larger than the default size (the example code you provide is incomplete). This causes the cell, and the whole columns that the cells of these Buttons are in, to become wider. In this case, you might want to use the columnspan keyword argument to divide your column into smaller, resizable, parts, so that your Radiobuttons can be aligned still better.

import Tkinter as tk

window = tk.Tk()
radio_one = tk.Radiobutton(window, text="I'm a radio")
radio_two = tk.Radiobutton(window, text="I'm another radio")
button = tk.Button(window, text="I am a very long button", width=50)
button.grid(row=0, column=0, columnspan=2, sticky=tk.N+tk.S+tk.W+tk.E)
radio_one.grid(column=0, row=1, sticky=tk.N+tk.W)
radio_two.grid(column=1, row=1, sticky=tk.N+tk.W)

window.mainloop()

If you would like more information on what parameters the grid geometry manager can use, I suggest you read this tutorial, I have found it to be very helpful in the past.

As a sidenote, please note that you use the variable keyword argument in the declaration of your Radiobuttons incorrectly. You must pass either a tk.StringVar, tk.IntVar or some other comparable object, as described here.


问:
No System.Runtime.Caching available?
output type of 'Class Library', and a target framework of '.NET Framework 4'.

According to everything I've read, I should have it available, but all I'm seeing in the System.Runtime namespace is the following:

```<code>CompilerServices
ConstrainedExecution
ExceptionServices
Hosting
InteropServices
Remoting
Serialization
Versioning
</code>```

Any ideas?

答:
To complement Jon Skeets answer, (for those who run into this problem),  if you still get red squiggly lines under Caching after having added reference to System.Runtime.Caching assembly, just restart the Visual Studio, after having saved the solution, and you should be good to go.

Having added the reference, saved the solution and ( if need may be ) restarted Visual Studio, you should be able to use the types within this namespace. In order to get my solution to work, I had to do this very way.

Edit:

While trying to recreate the problem, and solving this way, it seems that we need to set Copy Local to True in System.Runtime.Caching > Properties and then restart Visual Studio for getting it to work. At least, for my case, the problem didn't seem to solve without this. ;)

Title: No System.Runtime.Caching available?

Body:
output type of 'Class Library', and a target framework of '.NET Framework 4'.

According to everything I've read, I should have it available, but all I'm seeing in the System.Runtime namespace is the following:

CompilerServices
ConstrainedExecution
ExceptionServices
Hosting
InteropServices
Remoting
Serialization
Versioning

Any ideas?


问:
Taking dot products of high dimensional numpy arrays
I am trying to take the dot product between three numpy arrays. However, I am struggling with wrapping my head around this.

The problem is as follows:

I have two (4,) shaped numpy arrays a and b respectively, as well as a numpy array with shape (4, 4, 3), c.

```<code>import numpy as np

a = np.array([0, 1, 2, 3])
b = np.array([[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
          [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
          [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],
          [[4, 4, 4], [4, 4, 4], [4, 4, 4], [4, 4, 4]]])
c = np.array([4, 5, 6, 7])
</code>```

I want to compute the dot product in such a way that my result is a 3-tuple. That is, first dot a with b and then dotting with c, taking transposes if needed. In other words, I want to compute the dot product between a, b and c as if c was of shape (4, 4), but I want a 3-tuple as result.

I have tried:

Reshaping a and c, and then computing the dot product:

```<code>a = np.reshape(a, (4, 1))
c = np.reshape(c, (4, 1))

tmp = np.dot(a.T, b) # now has shape (1, 4, 3)
result = np.dot(tmp, c)
</code>```

Ideally, I should now have:

```<code>print(result.shape)
>> (1, 1, 3)
</code>```

but I get the error

ValueError: shapes (1,4,3) and (4,1) not aligned: 3 (dim 2) != 4 (dim 0)

I have also tried using the tensordot function from numpy, but without luck.

答:
The basic dot(A,B) rule is: last axis of A with the 2nd to the last of B

```<code>In [965]: a.shape
Out[965]: (4,)
In [966]: b.shape
Out[966]: (4, 4, 3)
</code>```

a (and c) is 1d.  It's (4,) can dot with the 2nd (4) of b with:

```<code>In [967]: np.dot(a,b).shape
Out[967]: (4, 3)
</code>```

Using c in the same on the output produces a (3,) array

```<code>In [968]: np.dot(c, np.dot(a,b))
Out[968]: array([360, 360, 360])
</code>```

This combination may be clearer with the equivalent einsum:

```<code>In [971]: np.einsum('i,jik,j->k',a,b,c)
Out[971]: array([360, 360, 360])
</code>```

But what if we want a to act on the 1st axis of b?  With einsum that's easy to do:

```<code>In [972]: np.einsum('i,ijk,j->k',a,b,c)
Out[972]: array([440, 440, 440])
</code>```

To do the same with the dot, we could just switch a and c:

```<code>In [973]: np.dot(a, np.dot(c,b))
Out[973]: array([440, 440, 440])
</code>```

Or transpose axes of b:

```<code>In [974]: np.dot(c, np.dot(a,b.transpose(1,0,2)))
Out[974]: array([440, 440, 440])
</code>```

This transposition question would be clearer if a and c had different lengths. e.g. A (2,) and (4,) with a (2,4,3) or (4,2,3).

In

```<code>tmp = np.dot(a.T, b) # now has shape (1, 4, 3)
</code>```

you have a (1,4a) dotted with (4,4a,3). The result is (1,4,3).  I added the a to identify when axes were combined.

To apply the (4,1) c, we have to do the same transpose:

```<code>In [977]: np.dot(c[:,None].T, np.dot(a[:,None].T, b))
Out[977]: array([[[360, 360, 360]]])
In [978]: _.shape
Out[978]: (1, 1, 3)
</code>```

np.dot(c[None,:], np.dot(a[None,:], b)) would do the same without the transposes.

I was hoping numpy would automagically distribute over the last axis. That is, that the dot product would run over the two first axes, if that makes sense.

Given the dot rule that I cited at the start this does not make sense.  But if we transpose b so the (3) axis is first, it can 'carry that along', using the last and 2nd to the last.

```<code>In [986]: b.transpose(2,0,1).shape
Out[986]: (3, 4, 4)
In [987]: np.dot(a, b.transpose(2,0,1)).shape
Out[987]: (3, 4)
In [988]: np.dot(np.dot(a, b.transpose(2,0,1)),c)
Out[988]: array([440, 440, 440])

(4a).(3, 4a, 4c) -> (3, 4c)
(3, 4c). (4c) -> 3
</code>```

Body:
I am trying to take the dot product between three numpy arrays. However, I am struggling with wrapping my head around this.

The problem is as follows:

I have two (4,) shaped numpy arrays a and b respectively, as well as a numpy array with shape (4, 4, 3), c.

import numpy as np

a = np.array([0, 1, 2, 3])
b = np.array([[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
          [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
          [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],
          [[4, 4, 4], [4, 4, 4], [4, 4, 4], [4, 4, 4]]])
c = np.array([4, 5, 6, 7])

I want to compute the dot product in such a way that my result is a 3-tuple. That is, first dot a with b and then dotting with c, taking transposes if needed. In other words, I want to compute the dot product between a, b and c as if c was of shape (4, 4), but I want a 3-tuple as result.

I have tried:

Reshaping a and c, and then computing the dot product:

a = np.reshape(a, (4, 1))
c = np.reshape(c, (4, 1))

tmp = np.dot(a.T, b) # now has shape (1, 4, 3)
result = np.dot(tmp, c)

Ideally, I should now have:

print(result.shape)
>> (1, 1, 3)

but I get the error

ValueError: shapes (1,4,3) and (4,1) not aligned: 3 (dim 2) != 4 (dim 0)

I have also tried using the tensordot function from numpy, but without luck.

Body:
The basic dot(A,B) rule is: last axis of A with the 2nd to the last of B

In [965]: a.shape
Out[965]: (4,)
In [966]: b.shape
Out[966]: (4, 4, 3)

a (and c) is 1d.  It's (4,) can dot with the 2nd (4) of b with:

In [967]: np.dot(a,b).shape
Out[967]: (4, 3)

Using c in the same on the output produces a (3,) array

In [968]: np.dot(c, np.dot(a,b))
Out[968]: array([360, 360, 360])

This combination may be clearer with the equivalent einsum:

In [971]: np.einsum('i,jik,j->k',a,b,c)
Out[971]: array([360, 360, 360])

But what if we want a to act on the 1st axis of b?  With einsum that's easy to do:

In [972]: np.einsum('i,ijk,j->k',a,b,c)
Out[972]: array([440, 440, 440])

To do the same with the dot, we could just switch a and c:

In [973]: np.dot(a, np.dot(c,b))
Out[973]: array([440, 440, 440])

Or transpose axes of b:

In [974]: np.dot(c, np.dot(a,b.transpose(1,0,2)))
Out[974]: array([440, 440, 440])

This transposition question would be clearer if a and c had different lengths. e.g. A (2,) and (4,) with a (2,4,3) or (4,2,3).

In

tmp = np.dot(a.T, b) # now has shape (1, 4, 3)

you have a (1,4a) dotted with (4,4a,3). The result is (1,4,3).  I added the a to identify when axes were combined.

To apply the (4,1) c, we have to do the same transpose:

In [977]: np.dot(c[:,None].T, np.dot(a[:,None].T, b))
Out[977]: array([[[360, 360, 360]]])
In [978]: _.shape
Out[978]: (1, 1, 3)

np.dot(c[None,:], np.dot(a[None,:], b)) would do the same without the transposes.

I was hoping numpy would automagically distribute over the last axis. That is, that the dot product would run over the two first axes, if that makes sense.

Given the dot rule that I cited at the start this does not make sense.  But if we transpose b so the (3) axis is first, it can 'carry that along', using the last and 2nd to the last.

In [986]: b.transpose(2,0,1).shape
Out[986]: (3, 4, 4)
In [987]: np.dot(a, b.transpose(2,0,1)).shape
Out[987]: (3, 4)
In [988]: np.dot(np.dot(a, b.transpose(2,0,1)),c)
Out[988]: array([440, 440, 440])

(4a).(3, 4a, 4c) -> (3, 4c)
(3, 4c). (4c) -> 3


问:
Windows batch: sleep
How do I get a Windows batch script to wait a few seconds?

sleep and wait don't seem to work (unrecognized command).

答:
I don't know why those commands are not working for you, but you can also try timeout</p>

```<code>timeout <delay in seconds>
</code>```

Title: Windows batch: sleep

Body:
I don't know why those commands are not working for you, but you can also try timeout

timeout <delay in seconds>


问:
Html/static files to React Componet /stateless functions?
I am moving a portfolio from Html with bootstrap and vanilla js to React. I am successful in most part since most of it is writing html and bootstrap in jsx which seems to have no issue so far. But  i am running into a problem with specific set of html and js codes that has to do with chart display . I am trying to make these set of codes into a component like I did it with others. i am getting this error "Uncaught TypeError: Cannot read property 'getContext' of null". I try to do componentdid mount will mount , then i get the chart itself is not defined error.  Below is the html and inline js code that work with no problem and  my Stateless function attempt. the chart data itself is from https://github.com/nnnick/Chart.js/blob/master/LICENSE.md  .  if any one want to see the entire code , its here : https://www.dropbox.com/s/552xpfs3ubggrmd/portfolio.rar?dl=0  ps: Testing.html have the entire code, these are the codes I am trying to make it into a component

import React ,{Component} from 'react';
import chart from '../../../assets/js/Chart';
import '../../../assets/css/main.css';

export default class Skills extends Component {

render() {
  var doughnutData1 = [
        {
          value: 55,
          color:"#1abc9c"
        },
        {
          value : 30,
          color : "#ecf0f1"
        }
      ];
  var doughnutData2 = [
          {
            value: 80,
            color:"#1abc9c"
          },
          {
            value : 10,
            color : "#ecf0f1"
          }
        ];
  var doughnutData3 = [
            {
              value: 40,
              color:"#1abc9c"
            },
            {
              value : 35,
              color : "#ecf0f1"
            }
          ];
  var doughnutData4 = [
              {
                value: 95,
                color:"#1abc9c"
              },
              {
                value : 20,
                color : "#ecf0f1"
              }
            ];
  var doughnutData5 = [
                {
                  value: 65,
                  color:"#1abc9c"
                },
                {
                  value : 30,
                  color : "#ecf0f1"
                }
              ];
  var doughnutData6 = [
                  {
                    value: 50,
                    color:"#1abc9c"
                  },
                  {
                    value : 50,
                    color : "#ecf0f1"
                  }
                ];

      let myDoughnut1 = new chart.Chart(document.getElementById("javascript").getContext("2d")).Doughnut(doughnutData1);
      let myDoughnut2 = new chart.Chart(document.getElementById("bootstrap").getContext("2d")).Doughnut(doughnutData2);
      let myDoughnut3 = new chart.Chart(document.getElementById("wordpress").getContext("2d")).Doughnut(doughnutData3);
      let myDoughnut4 = new chart.Chart(document.getElementById("html").getContext("2d")).Doughnut(doughnutData4);
      let myDoughnut5 = new chart.Chart(document.getElementById("photoshop").getContext("2d")).Doughnut(doughnutData5);
      let myDoughnut6 = new chart.Chart(document.getElementById("illustrator").getContext("2d")).Doughnut(doughnutData6);

////////////////////////////////////////////
///////////////////////////////////////////
//////////////////////////////////////////
//////////////////////////////////////////

return (

//start

SKILLS

            <canvas id="javascript" height="130" width="130"></canvas>

Javascript

             {myDoughnut1}

            <canvas id="bootstrap" height="130" width="130"></canvas>

Bootstrap

               {myDoughnut2}

            <canvas id="wordpress" height="130" width="130"></canvas>

jQuery

               {myDoughnut3}

            <canvas id="html" height="130" width="130"></canvas>

HTML/CSS

               {myDoughnut4}

            <canvas id="photoshop" height="130" width="130"></canvas>

Angular Js

               {myDoughnut5}

            <canvas id="illustrator" height="130" width="130"></canvas>

React

               {myDoughnut6}

Other Skills - UNIX Commands, NPM, Gulp, bower packages, Web packs

Other Soft Skills - NOSQL,MYSQL, Node JS

Other Softer Skills - C#, Java, Objective C, MYSQL, PHP, Python

//end

);

};

}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="skillswrap">
  <div class="container">
   <div class="row">
     <div class="col-lg-2 col-lg-offset-1">
      <h5>SKILLS</h5>
     </div>
     <div class="col-lg-3 centered">
      <canvas id="javascript" height="130" width="130"></canvas>
      <p>Javascript</p>
      <br>
      <script>
       var doughnutData = [
         {
          value: 55,
          color:"#1abc9c"
         },
         {
          value : 30,
          color : "#ecf0f1"
         }
        ];
        var myDoughnut = new Chart(document.getElementById("javascript").getContext("2d")).Doughnut(doughnutData);
      </script>
     </div>
     <div class="col-lg-3 centered">
      <canvas id="bootstrap" height="130" width="130"></canvas>
      <p>Bootstrap</p>
      <br>
      <script>
       var doughnutData = [
         {
          value: 80,
          color:"#1abc9c"
         },
         {
          value : 10,
          color : "#ecf0f1"
         }
        ];
        var myDoughnut = new Chart(document.getElementById("bootstrap").getContext("2d")).Doughnut(doughnutData);
      </script>
     </div>
     <div class="col-lg-3 centered">
      <canvas id="wordpress" height="130" width="130"></canvas>
      <p>jQuery</p>
      <br>
      <script>
       var doughnutData = [
         {
          value: 40,
          color:"#1abc9c"
         },
         {
          value : 35,
          color : "#ecf0f1"
         }
        ];
        var myDoughnut = new Chart(document.getElementById("wordpress").getContext("2d")).Doughnut(doughnutData);
      </script>
     </div>

     <div class="col-lg-3 col-lg-offset-3 centered">
      <canvas id="html" height="130" width="130"></canvas>
      <p>HTML/CSS</p>
      <br>
      <script>
       var doughnutData = [
         {
          value: 95,
          color:"#1abc9c"
         },
         {
          value : 20,
          color : "#ecf0f1"
         }
        ];
        var myDoughnut = new Chart(document.getElementById("html").getContext("2d")).Doughnut(doughnutData);
      </script>
     </div>
     <div class="col-lg-3 centered">
      <canvas id="photoshop" height="130" width="130"></canvas>
      <p>Angular Js</p>
      <br>
      <script>
       var doughnutData = [
         {
          value: 65,
          color:"#1abc9c"
         },
         {
          value : 30,
          color : "#ecf0f1"
         }
        ];
        var myDoughnut = new Chart(document.getElementById("photoshop").getContext("2d")).Doughnut(doughnutData);
      </script>
     </div>
     <div class="col-lg-3 centered">
      <canvas id="illustrator" height="130" width="130"></canvas>
      <p>React</p>
      <br>
      <script>
       var doughnutData = [
         {
          value: 50,
          color:"#1abc9c"
         },
         {
          value : 50,
          color : "#ecf0f1"
         }
        ];
        var myDoughnut = new Chart(document.getElementById("illustrator").getContext("2d")).Doughnut(doughnutData);
      </script>
     </div>
<p>Other Skills - UNIX Commands, NPM, Gulp, bower packages, Web packs </p>
<p>Other Soft Skills - NOSQL,MYSQL, Node JS </p>
<p>Other Softer Skills - C#, Java, Objective C, MYSQL, PHP, Python </p>

   </div>
   <br>
  </div>
 </div></code>```

答:
Looks like document.getElementById("...").getContext("2d") failing in render() because element was not mounted to DOM yet.

You should wait componentDidMount and init your Chart module there.

Rough example:

```<code> export default class Skills extends Component {

      componentDidMount() {
           new chart.Chart(this.javascriptEl.getContext("2d")).Doughnut(data);
      }

      render() {
          return (
               <canvas ref={(el) => {this.javascriptEl=el}}></canvas>
          );
      }
 }
</code>```

Body:
I am moving a portfolio from Html with bootstrap and vanilla js to React. I am successful in most part since most of it is writing html and bootstrap in jsx which seems to have no issue so far. But  i am running into a problem with specific set of html and js codes that has to do with chart display . I am trying to make these set of codes into a component like I did it with others. i am getting this error "Uncaught TypeError: Cannot read property 'getContext' of null". I try to do componentdid mount will mount , then i get the chart itself is not defined error.  Below is the html and inline js code that work with no problem and  my Stateless function attempt. the chart data itself is from https://github.com/nnnick/Chart.js/blob/master/LICENSE.md  .  if any one want to see the entire code , its here : https://www.dropbox.com/s/552xpfs3ubggrmd/portfolio.rar?dl=0  ps: Testing.html have the entire code, these are the codes I am trying to make it into a component

import React ,{Component} from 'react';
import chart from '../../../assets/js/Chart';
import '../../../assets/css/main.css';

export default class Skills extends Component {

render() {
  var doughnutData1 = [
        {
          value: 55,
          color:"#1abc9c"
        },
        {
          value : 30,
          color : "#ecf0f1"
        }
      ];
  var doughnutData2 = [
          {
            value: 80,
            color:"#1abc9c"
          },
          {
            value : 10,
            color : "#ecf0f1"
          }
        ];
  var doughnutData3 = [
            {
              value: 40,
              color:"#1abc9c"
            },
            {
              value : 35,
              color : "#ecf0f1"
            }
          ];
  var doughnutData4 = [
              {
                value: 95,
                color:"#1abc9c"
              },
              {
                value : 20,
                color : "#ecf0f1"
              }
            ];
  var doughnutData5 = [
                {
                  value: 65,
                  color:"#1abc9c"
                },
                {
                  value : 30,
                  color : "#ecf0f1"
                }
              ];
  var doughnutData6 = [
                  {
                    value: 50,
                    color:"#1abc9c"
                  },
                  {
                    value : 50,
                    color : "#ecf0f1"
                  }
                ];

      let myDoughnut1 = new chart.Chart(document.getElementById("javascript").getContext("2d")).Doughnut(doughnutData1);
      let myDoughnut2 = new chart.Chart(document.getElementById("bootstrap").getContext("2d")).Doughnut(doughnutData2);
      let myDoughnut3 = new chart.Chart(document.getElementById("wordpress").getContext("2d")).Doughnut(doughnutData3);
      let myDoughnut4 = new chart.Chart(document.getElementById("html").getContext("2d")).Doughnut(doughnutData4);
      let myDoughnut5 = new chart.Chart(document.getElementById("photoshop").getContext("2d")).Doughnut(doughnutData5);
      let myDoughnut6 = new chart.Chart(document.getElementById("illustrator").getContext("2d")).Doughnut(doughnutData6);

////////////////////////////////////////////
///////////////////////////////////////////
//////////////////////////////////////////
//////////////////////////////////////////

return (

//start

SKILLS

            <canvas id="javascript" height="130" width="130"></canvas>

Javascript

             {myDoughnut1}

            <canvas id="bootstrap" height="130" width="130"></canvas>

Bootstrap

               {myDoughnut2}

            <canvas id="wordpress" height="130" width="130"></canvas>

jQuery

               {myDoughnut3}

            <canvas id="html" height="130" width="130"></canvas>

HTML/CSS

               {myDoughnut4}

            <canvas id="photoshop" height="130" width="130"></canvas>

Angular Js

               {myDoughnut5}

            <canvas id="illustrator" height="130" width="130"></canvas>

React

               {myDoughnut6}

Other Skills - UNIX Commands, NPM, Gulp, bower packages, Web packs

Other Soft Skills - NOSQL,MYSQL, Node JS

Other Softer Skills - C#, Java, Objective C, MYSQL, PHP, Python

//end

);

};

}

SKILLS

      <canvas id="javascript" height="130" width="130"></canvas>

Javascript

      <canvas id="bootstrap" height="130" width="130"></canvas>

Bootstrap

      <canvas id="wordpress" height="130" width="130"></canvas>

jQuery

      <canvas id="html" height="130" width="130"></canvas>

HTML/CSS

      <canvas id="photoshop" height="130" width="130"></canvas>

Angular Js

      <canvas id="illustrator" height="130" width="130"></canvas>

React

Other Skills - UNIX Commands, NPM, Gulp, bower packages, Web packs

Other Soft Skills - NOSQL,MYSQL, Node JS

Other Softer Skills - C#, Java, Objective C, MYSQL, PHP, Python

Body:
Looks like document.getElementById("...").getContext("2d") failing in render() because element was not mounted to DOM yet.

You should wait componentDidMount and init your Chart module there.

Rough example:

 export default class Skills extends Component {

      componentDidMount() {
           new chart.Chart(this.javascriptEl.getContext("2d")).Doughnut(data);
      }

      render() {
          return (
               <canvas ref={(el) => {this.javascriptEl=el}}></canvas>
          );
      }
 }