问:
Django MEDIA_URL and MEDIA_ROOT
I'm trying to upload an image via the Django admin and then view that image either in a page on the frontend or just via a URL.

Note this is all on my local machine.

My settings are as follows:

```<code>MEDIA_ROOT = '/home/dan/mysite/media/'

MEDIA_URL = '/media/'
</code>```

I have set the upload_to parameter to 'images' and the file has been correctly uploaded to the directory:

```<code>'/home/dan/mysite/media/images/myimage.png'
</code>```

However, when I try to access the image at the following URL:

```<code>http://127.0.0.1:8000/media/images/myimage.png
</code>```

I get a 404 error.

Do I need to setup specific URLconf patters for uploaded media?

Any advice appreciated.

Thanks.

答:
This if for Django 1.10:  </p>

```<code> if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

Title: Django MEDIA_URL and MEDIA_ROOT

Body:
I'm trying to upload an image via the Django admin and then view that image either in a page on the frontend or just via a URL.

Note this is all on my local machine.

My settings are as follows:

MEDIA_ROOT = '/home/dan/mysite/media/'

MEDIA_URL = '/media/'

I have set the upload_to parameter to 'images' and the file has been correctly uploaded to the directory:

'/home/dan/mysite/media/images/myimage.png'

However, when I try to access the image at the following URL:

http://127.0.0.1:8000/media/images/myimage.png

I get a 404 error.

Do I need to setup specific URLconf patters for uploaded media?

Any advice appreciated.

Thanks.

Body:
This if for Django 1.10:

 if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


来源: stackexchange

问:
How to zip a file while writing to it?
Does anyone know of a way to zip a stream that you are writing to? I'm trying to avoid writing the file to the disk, and was wondering if I can just compress data as you are writing it to the stream.

The use case behind this is that the raw file is going to be very large and we want to avoid having to write the entire thing unzipped onto the disk.

答: I have done this before in a webapp. I got a reference to the servlet OutputStream and then supplied that to the ZipOutputStream. Then I just zipped. The zipped file was served up to the client browser. Easy.

ContentLicense: CC BY-SA 2.5

Title: How to zip a file while writing to it?


问:
Web development transition from MAMP to Docker
I am new to Docker and I am having a hard time applying its core technology to my present web development. Using MAMP, you just need to download the app, put your PHP/HTML files on /htdocs, start servers, then go to http://localhost:8888/ to see your webapp. Now, using docker, I’m wondering how can I do the same. What I’ve done so far is to pull http, php and mysql images from the Docker Hub.

How can I link these three images together to make them work? Or How should I run them simultaneously?

Where should I put the /htdocs or how can I access it?

MAMP has a phpMyAdmin for database access, does Docker has something like this?

I’m working on a Mac OS X Yosemite (10.10.1) with boot2docker v1.4.1 and VirtualBox 4.3.20.

答:
You can now use docker-compose and a docker-compose.yml file to accomplish the same thing as fig.

Finding containers for each service and linking them together isn't the easiest thing. The docker-compose file from The damp github project (pasted below for posterity) is a good start for how to get the apache, php, and mysql services all running with a docker-compose -f docker-compose.yml up command.

```<code>proxy:
    image: jwilder/nginx-proxy
    ports: ['80:80']
    volumes: ['/var/run/docker.sock:/tmp/docker.sock:ro']
    environment: [DEFAULT_HOST=damp.dev]
database:
    image: 'mysql:5.7'
    ports: ['3306:3306']
    environment: [MYSQL_ROOT_PASSWORD=password]
phpmyadmin:
    image: corbinu/docker-phpmyadmin
    links: ['database:mysql']
    environment: [MYSQL_USERNAME=root, MYSQL_ROOT_PASSWORD=password, VIRTUAL_HOST=phpmyadmin.damp.dev]
damp:
    image: httpd
    volumes: ['~/damp/damp:/usr/local/apache2/htdocs']
    environment: [VIRTUAL_HOST=damp.dev]
</code>```

Once you do that _and put an entry for damp.dev 127.0.0.1 in your hosts file, anything you mount in ~/damp/damp (per that second to last line) will be put in the htdocs of the docker container and served up on damp.dev/[whatever].

damp is just the first example I found poking around on how to replicate MAMP with docker. The most important thing to note is that you can use docker-compose instead of fig. Compose is based directly on the Fig codebase and is backwards-compatible with Fig applications.

ContentLicense: CC BY-SA 3.0

Body:
You can now use docker-compose and a docker-compose.yml file to accomplish the same thing as fig.

Finding containers for each service and linking them together isn't the easiest thing. The docker-compose file from The damp github project (pasted below for posterity) is a good start for how to get the apache, php, and mysql services all running with a docker-compose -f docker-compose.yml up command.

proxy:
    image: jwilder/nginx-proxy
    ports: ['80:80']
    volumes: ['/var/run/docker.sock:/tmp/docker.sock:ro']
    environment: [DEFAULT_HOST=damp.dev]
database:
    image: 'mysql:5.7'
    ports: ['3306:3306']
    environment: [MYSQL_ROOT_PASSWORD=password]
phpmyadmin:
    image: corbinu/docker-phpmyadmin
    links: ['database:mysql']
    environment: [MYSQL_USERNAME=root, MYSQL_ROOT_PASSWORD=password, VIRTUAL_HOST=phpmyadmin.damp.dev]
damp:
    image: httpd
    volumes: ['~/damp/damp:/usr/local/apache2/htdocs']
    environment: [VIRTUAL_HOST=damp.dev]

Once you do that _and put an entry for damp.dev 127.0.0.1 in your hosts file, anything you mount in ~/damp/damp (per that second to last line) will be put in the htdocs of the docker container and served up on damp.dev/[whatever].

damp is just the first example I found poking around on how to replicate MAMP with docker. The most important thing to note is that you can use docker-compose instead of fig. Compose is based directly on the Fig codebase and is backwards-compatible with Fig applications.

ContentLicense: CC BY-SA 4.0


问:
difference between node.run_state vs global varibale in a ruby file chef
would like to know the difference and recommended approach to use between global variable vs node.run_state

test.rb

```<code>dbpassword=''

ruby_block "load_databag_secret" do
  block do
    secret_key = Chef::EncryptedDataBagItem.load_secret("/home/test/db_key")
        db_keys = Chef::EncryptedDataBagItem.load("mydatabag", "mydatabagitem", secret_key)
    end
    dbpassword=db_keys['DB_PASSWORD']
node.run_state['password']=db_keys['DB_PASSWORD']
      end
    end

execute "Enable on hosts" do

  command lazy { "echo #{node.run_state['password']} > /home/app/db.txt" }
end

    template "/config/properties" do
            source "properties.erb"
            variables(lazy {
                         :db_password => { node.run_state['password'] },

                      })
</code>```

or using node.run_state['password'] in place of global variable in this .rb file

Now execute command worked fine im able to see the password on the echoed file db.txt where as when i used lazy in template variables it outputed as empty value for db_password in template.

答:
So a few issues, first what you have there isn't a global variable, it's a local variable. Globals in Ruby start with $. Second, you can't assign to a local variable from an enclosing scope like that in Ruby (or, indeed, in most languages). That assignment just creates a second dbpassword local variable scoped to the block. You could, however, use a mutation rather than a variable assignment (e.g. dbpassword << whatever). Third, you can't actually use lazy deeply inside the variables hash like that, it has to be at the top level. Fourth, you can straight up side-step all of this if you're only using the value you once like in that example:

```<code>template "/config/properties" do
  source "properties.erb"
  variables lazy {
    secret_key = Chef::EncryptedDataBagItem.load_secret("/home/test/db_key")
    db_keys = Chef::EncryptedDataBagItem.load("mydatabag", "mydatabagitem", secret_key)
    {db_password: db_keys['DB_PASSWORD']}
  }
end
</code>```

Just for completeness in case others find this via Google, with real global variables the biggest difference is unit testing, the run state is tied to the converge so individual unit tests won't see each other's values which is always nice (though of course you could work around this in your code).

Body:
would like to know the difference and recommended approach to use between global variable vs node.run_state

test.rb

dbpassword=''

ruby_block "load_databag_secret" do
  block do
    secret_key = Chef::EncryptedDataBagItem.load_secret("/home/test/db_key")
        db_keys = Chef::EncryptedDataBagItem.load("mydatabag", "mydatabagitem", secret_key)
    end
    dbpassword=db_keys['DB_PASSWORD']
node.run_state['password']=db_keys['DB_PASSWORD']
      end
    end

execute "Enable on hosts" do

  command lazy { "echo #{node.run_state['password']} > /home/app/db.txt" }
end

    template "/config/properties" do
            source "properties.erb"
            variables(lazy {
                         :db_password => { node.run_state['password'] },

                      })

or using node.run_state['password'] in place of global variable in this .rb file

Now execute command worked fine im able to see the password on the echoed file db.txt where as when i used lazy in template variables it outputed as empty value for db_password in template.

Body:
So a few issues, first what you have there isn't a global variable, it's a local variable. Globals in Ruby start with $. Second, you can't assign to a local variable from an enclosing scope like that in Ruby (or, indeed, in most languages). That assignment just creates a second dbpassword local variable scoped to the block. You could, however, use a mutation rather than a variable assignment (e.g. dbpassword << whatever). Third, you can't actually use lazy deeply inside the variables hash like that, it has to be at the top level. Fourth, you can straight up side-step all of this if you're only using the value you once like in that example:

template "/config/properties" do
  source "properties.erb"
  variables lazy {
    secret_key = Chef::EncryptedDataBagItem.load_secret("/home/test/db_key")
    db_keys = Chef::EncryptedDataBagItem.load("mydatabag", "mydatabagitem", secret_key)
    {db_password: db_keys['DB_PASSWORD']}
  }
end

Just for completeness in case others find this via Google, with real global variables the biggest difference is unit testing, the run state is tied to the converge so individual unit tests won't see each other's values which is always nice (though of course you could work around this in your code).


问:
php mysql query returns many array but need only one
```<code>$connection = db_connect();
$query = mysqli_query($connection, "
SELECT * FROM birouri
WHERE disponibilitate = 'LIBER'
AND locatie_actuala = 'Orhideea'
AND pauza = ''
AND closed_program = ''
AND feedback = ''
LIMIT 1") or die(mysqli_error($connection));
            $row = mysqli_fetch_assoc($query);

            $username = $row['username'];
            $nr_birou = $row['nr_birou'];
            $disponibilitate = $row['disponibilitate'];
            $locatie_actuala = $row['locatie_actuala'];
            $pauza = $row['pauza'];
            $closed_program = $row['closed_program'];
            $feedback = $row['feedback'];
            $inregistrare_clienti = $row['inregistrare_clienti'];

            var_dump($row);
</code>```

In database I have 6 rows that fits with my query criteria.

var_dump($row); returns me 1 array (first row) duplicated 7 times but I need to show only one. Limit 1 is not working.

Help, please.

答:
change this

```<code>$row = mysqli_fetch_assoc($query);

            $username = $row['username'];
            $nr_birou = $row['nr_birou'];
            $disponibilitate = $row['disponibilitate'];
            $locatie_actuala = $row['locatie_actuala'];
            $pauza = $row['pauza'];
            $closed_program = $row['closed_program'];
            $feedback = $row['feedback'];
            $inregistrare_clienti = $row['inregistrare_clienti'];
</code>```

to this and it will work

```<code>while($row = mysqli_fetch_assoc($query)){

            $username = $row['username'];
            $nr_birou = $row['nr_birou'];
            $disponibilitate = $row['disponibilitate'];
            $locatie_actuala = $row['locatie_actuala'];
            $pauza = $row['pauza'];
            $closed_program = $row['closed_program'];
            $feedback = $row['feedback'];
            $inregistrare_clienti = $row['inregistrare_clienti'];
}
</code>```

there are 8 columns so your code runs 8 times but if run while loop it will only run once

Body:
$connection = db_connect();
$query = mysqli_query($connection, "
SELECT * FROM birouri
WHERE disponibilitate = 'LIBER'
AND locatie_actuala = 'Orhideea'
AND pauza = ''
AND closed_program = ''
AND feedback = ''
LIMIT 1") or die(mysqli_error($connection));
            $row = mysqli_fetch_assoc($query);

            $username = $row['username'];
            $nr_birou = $row['nr_birou'];
            $disponibilitate = $row['disponibilitate'];
            $locatie_actuala = $row['locatie_actuala'];
            $pauza = $row['pauza'];
            $closed_program = $row['closed_program'];
            $feedback = $row['feedback'];
            $inregistrare_clienti = $row['inregistrare_clienti'];

            var_dump($row);

In database I have 6 rows that fits with my query criteria.

var_dump($row); returns me 1 array (first row) duplicated 7 times but I need to show only one. Limit 1 is not working.

Help, please.

Body:
change this

$row = mysqli_fetch_assoc($query);

            $username = $row['username'];
            $nr_birou = $row['nr_birou'];
            $disponibilitate = $row['disponibilitate'];
            $locatie_actuala = $row['locatie_actuala'];
            $pauza = $row['pauza'];
            $closed_program = $row['closed_program'];
            $feedback = $row['feedback'];
            $inregistrare_clienti = $row['inregistrare_clienti'];

to this and it will work

while($row = mysqli_fetch_assoc($query)){

            $username = $row['username'];
            $nr_birou = $row['nr_birou'];
            $disponibilitate = $row['disponibilitate'];
            $locatie_actuala = $row['locatie_actuala'];
            $pauza = $row['pauza'];
            $closed_program = $row['closed_program'];
            $feedback = $row['feedback'];
            $inregistrare_clienti = $row['inregistrare_clienti'];
}

there are 8 columns so your code runs 8 times but if run while loop it will only run once


问:
Howto delete every second and third element from an array?
I want to delete every second and third element from an array in Javascript.

My array looks like this:

```<code>var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"];
</code>```

Now I want to delete every second and third element. The result would look like this:

```<code>["Banana", "Orange", "Apple"]
</code>```

I tried to use a for-loop and splice:

```<code>for (var i = 0; fruits.length; i = i+3) {
    fruits.splice(i+1,0);
    fruits.splice(i+2,0);
};
</code>```

Of course this returns an empty array because the elements are removed while the loop is still executed.

How can I do this correctly?

答: Try looping through the array in reverse order</p>

Body:
I want to delete every second and third element from an array in Javascript.

My array looks like this:

var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"];

Now I want to delete every second and third element. The result would look like this:

["Banana", "Orange", "Apple"]

I tried to use a for-loop and splice:

for (var i = 0; fruits.length; i = i+3) {
    fruits.splice(i+1,0);
    fruits.splice(i+2,0);
};

Of course this returns an empty array because the elements are removed while the loop is still executed.

How can I do this correctly?


问:
testing a service that uses a third party library
I have a Service that uses a library called client.

The Client class that I load is stored in the private property client of Service.

For my spec,  I can't inject mockClient in my Service like this

```<code>service = new Service(mockClient)
</code>```

but I can't either do

```<code>service = new Service()
service.client = mockClient
</code>```

since client is private.

What is the right practice to test a service that uses a third party library that is not injected and that you want to mock ?

Edit:
my service uses a third party lib like this

```<code>import { Client } from 'someLib';

Injectable()
export class Service {
  private client: Client;

  constructor() {
    this.client = new Client();
  }
</code>```

答:
The proper practice here is to refactor your code so that your third party library is injected.  First, you should wrap the library in a service or a factory. As a bonus, you may want to only expose the parts of the third party library that you are using. You can validate parameters in your service and transform them so that the call signatures make sense for your app.  So, it may look something like this:

```<code>app.service('theirLibraryFactory', () => {
 return {
   createClientWrapper: () => {
      let client = new Client();
      return {
        op1: (args) => client.doOp1(args),
        op2: (args) => client.doOp2(args)
        ...
      }
 };
}
</code>```

With this client wrapper, you can then inject it into your classes, and then mock it.

ps- I know that angualarjs provides factories as a base type, but I prefer to use services since they do everything that factories do, but more explicitly. YMMV.

Body:
I have a Service that uses a library called client.

The Client class that I load is stored in the private property client of Service.

For my spec,  I can't inject mockClient in my Service like this

service = new Service(mockClient)

but I can't either do

service = new Service()
service.client = mockClient

since client is private.

What is the right practice to test a service that uses a third party library that is not injected and that you want to mock ?

Edit:
my service uses a third party lib like this

import { Client } from 'someLib';

Injectable()
export class Service {
  private client: Client;

  constructor() {
    this.client = new Client();
  }

Body:
The proper practice here is to refactor your code so that your third party library is injected.  First, you should wrap the library in a service or a factory. As a bonus, you may want to only expose the parts of the third party library that you are using. You can validate parameters in your service and transform them so that the call signatures make sense for your app.  So, it may look something like this:

app.service('theirLibraryFactory', () => {
 return {
   createClientWrapper: () => {
      let client = new Client();
      return {
        op1: (args) => client.doOp1(args),
        op2: (args) => client.doOp2(args)
        ...
      }
 };
}

With this client wrapper, you can then inject it into your classes, and then mock it.

ps- I know that angualarjs provides factories as a base type, but I prefer to use services since they do everything that factories do, but more explicitly. YMMV.


问:
IndexOutOfBoundsException Index 0 Size 0
I am writing a program that pretty much is taking a string of numbers and operators, splitting them up, then doing the calculations on it. I have four separate IF statements for each operator inside a For loop. The code compiles, but gives me an IndexOutOfBoundsException Index:0 Size:0 at lines 70 and 28. Does anyone have any suggestions as to why this is happening? Thanks. </p>

```<code>import java.util.*;
import java.io.*;

public class Lab8
{
public static void main( String[] args)
{
    if ( args.length<1) { System.out.println("FATAL ERROR: Missing expression on command line\nexample: java Lab8 3+13/5-16*3\n"); System.exit(0); }

    String expr= args[0];  // i.e. somethinig like "4+5-12/3.5-5.4*3.14";
    System.out.println( "expr: " + expr );
    ArrayList<String> operatorList = new ArrayList<String>();
    ArrayList<String> operandList = new ArrayList<String>();

    StringTokenizer st = new StringTokenizer( expr,"+-*/", true );
    while (st.hasMoreTokens())
    {
        String token = st.nextToken();
        if ("+-/*".contains(token))
            operatorList.add(token);
        else
            operandList.add(token);
        }
    System.out.println("Operators:" + operatorList);
    System.out.println("Operands:" + operandList);

    double result = evaluate( operatorList, operandList );
    System.out.println("The expression: " + expr + " evalutes to " + result + "\n");
} // END MAIN

static double evaluate( ArrayList<String> operatorList, ArrayList<String> operandList)
{
    String operator;
    double result;

    ArrayList<Double> andList = new ArrayList<Double>();

    for( String op : operandList )
    {
        andList.add( Double.parseDouble(op) );
    }

    for(int i=0;i<operatorList.size();++i)
    {
        if(operatorList.get(i).equals("*"))
        {
        operator = operatorList.get(i);
        }
            result = andList.get(i) * andList.get(i+1);
            andList.set(i,result);
        //operandList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

        if(operatorList.get(i).equals("/"))
        {
            operator = operatorList.get(i);
        }
            result = andList.get(i) / andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

        if(operatorList.get(i).equals("+"))
        {
            operator = operatorList.get(i);
        }
            result = andList.get(i) + andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

        if(operatorList.get(i).equals("-"))
        {
            operator = operatorList.get(i);
        }
            result = andList.get(i) - andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

    }

    return andList.get(0);
}
</code>```

<p>} // </p>

答:
Looks like there is something wrong with below code.

```<code>if(operatorList.get(i).equals("*"))
            {
                operator = operatorList.get(i);
            }
            result = andList.get(i) * andList.get(i+1);
            andList.set(i,result);
            //operandList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

            if(operatorList.get(i).equals("/"))
            {
                operator = operatorList.get(i);
            }
            result = andList.get(i) / andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

            if(operatorList.get(i).equals("+"))
            {
                operator = operatorList.get(i);
            }
            result = andList.get(i) + andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

            if(operatorList.get(i).equals("-"))
            {
                operator = operatorList.get(i);
            }
            result = andList.get(i) - andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);
</code>```

All all the if loops you have same set of code

```<code>result = andList.get(i) * andList.get(i+1);
                andList.set(i,result);
                //operandList.set(i,result);
                andList.remove(i+1);
                operatorList.remove(i);
</code>```

which should be probably part of the previous if block. What is happening here is when the code reach to line 70, it has already removed the elements from operatorList in previous operatorList.remove statements. You need to correct it by making sure if the code belongs to if loop .e.g. for first if loop -

```<code>    if(operatorList.get(i).equals("*"))
    {
        operator = operatorList.get(i);
        result = andList.get(i) * andList.get(i+1);
        andList.set(i,result);
        //operandList.set(i,result);
        andList.remove(i+1);
        operatorList.remove(i);
     }
</code>```

Is that the real requirement?

Body:
I am writing a program that pretty much is taking a string of numbers and operators, splitting them up, then doing the calculations on it. I have four separate IF statements for each operator inside a For loop. The code compiles, but gives me an IndexOutOfBoundsException Index:0 Size:0 at lines 70 and 28. Does anyone have any suggestions as to why this is happening? Thanks.

import java.util.*;
import java.io.*;

public class Lab8
{
public static void main( String[] args)
{
    if ( args.length<1) { System.out.println("FATAL ERROR: Missing expression on command line\nexample: java Lab8 3+13/5-16*3\n"); System.exit(0); }

    String expr= args[0];  // i.e. somethinig like "4+5-12/3.5-5.4*3.14";
    System.out.println( "expr: " + expr );
    ArrayList<String> operatorList = new ArrayList<String>();
    ArrayList<String> operandList = new ArrayList<String>();

    StringTokenizer st = new StringTokenizer( expr,"+-*/", true );
    while (st.hasMoreTokens())
    {
        String token = st.nextToken();
        if ("+-/*".contains(token))
            operatorList.add(token);
        else
            operandList.add(token);
        }
    System.out.println("Operators:" + operatorList);
    System.out.println("Operands:" + operandList);

    double result = evaluate( operatorList, operandList );
    System.out.println("The expression: " + expr + " evalutes to " + result + "\n");
} // END MAIN

static double evaluate( ArrayList<String> operatorList, ArrayList<String> operandList)
{
    String operator;
    double result;

    ArrayList<Double> andList = new ArrayList<Double>();

    for( String op : operandList )
    {
        andList.add( Double.parseDouble(op) );
    }

    for(int i=0;i<operatorList.size();++i)
    {
        if(operatorList.get(i).equals("*"))
        {
        operator = operatorList.get(i);
        }
            result = andList.get(i) * andList.get(i+1);
            andList.set(i,result);
        //operandList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

        if(operatorList.get(i).equals("/"))
        {
            operator = operatorList.get(i);
        }
            result = andList.get(i) / andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

        if(operatorList.get(i).equals("+"))
        {
            operator = operatorList.get(i);
        }
            result = andList.get(i) + andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

        if(operatorList.get(i).equals("-"))
        {
            operator = operatorList.get(i);
        }
            result = andList.get(i) - andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

    }

    return andList.get(0);
}

} //

Body:
Looks like there is something wrong with below code.

if(operatorList.get(i).equals("*"))
            {
                operator = operatorList.get(i);
            }
            result = andList.get(i) * andList.get(i+1);
            andList.set(i,result);
            //operandList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

            if(operatorList.get(i).equals("/"))
            {
                operator = operatorList.get(i);
            }
            result = andList.get(i) / andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

            if(operatorList.get(i).equals("+"))
            {
                operator = operatorList.get(i);
            }
            result = andList.get(i) + andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

            if(operatorList.get(i).equals("-"))
            {
                operator = operatorList.get(i);
            }
            result = andList.get(i) - andList.get(i+1);
            andList.set(i,result);
            andList.remove(i+1);
            operatorList.remove(i);

All all the if loops you have same set of code

result = andList.get(i) * andList.get(i+1);
                andList.set(i,result);
                //operandList.set(i,result);
                andList.remove(i+1);
                operatorList.remove(i);

which should be probably part of the previous if block. What is happening here is when the code reach to line 70, it has already removed the elements from operatorList in previous operatorList.remove statements. You need to correct it by making sure if the code belongs to if loop .e.g. for first if loop -

    if(operatorList.get(i).equals("*"))
    {
        operator = operatorList.get(i);
        result = andList.get(i) * andList.get(i+1);
        andList.set(i,result);
        //operandList.set(i,result);
        andList.remove(i+1);
        operatorList.remove(i);
     }

Is that the real requirement?


问:
sigmoidal regression with scipy, numpy, python, etc
I have two variables (x and y) that have a somewhat sigmoidal relationship with each other, and I need to find some sort of prediction equation that will enable me to predict the value of y, given any value of x.  My prediction equation needs to show the somewhat sigmoidal relationship between the two variables.  Therefore, I cannot settle for a linear regression equation that produces a line.  I need to see the gradual, curvilinear change in slope that occurs at both the right and left of the graph of the two variables.

I started using numpy.polyfit after googling curvilinear regression and python, but that gave me the awful results you can see if you run the code below.  Can anyone show me how to re-write the code below to get the type of sigmoidal regression equation that I want?

If you run the code below, you can see that it gives a downward facing parabola, which is not what the relationship between my variables should look like.  Instead, there should be more of a sigmoidal relationship between my two variables, but with a tight fit with the data that I am using in the code below.  The data in the code below are means from a large-sample research study, so they pack more statistical power than their five data points might suggest.  I do not have the actual data from the large-sample research study, but I do have the means below and their standard deviations(which I am not showing).  I would prefer to just plot a simple function with the mean data listed below, but the code could get more complex if complexity would offer substantial improvements.

How can I change my code to show a best fit of a sigmoidal function, preferably using scipy, numpy, and python?  Here is the current version of my code, which needs to be fixed:

```<code>import numpy as np
import matplotlib.pyplot as plt

# Create numpy data arrays
x = np.array([821,576,473,377,326])
y = np.array([255,235,208,166,157])

# Use polyfit and poly1d to create the regression equation
z = np.polyfit(x, y, 3)
p = np.poly1d(z)
xp = np.linspace(100, 1600, 1500)
pxp=p(xp)

# Plot the results
plt.plot(x, y, '.', xp, pxp, '-')
plt.ylim(140,310)
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()
</code>```

EDIT BELOW: (Re-framed the question)

Your response, and its speed, are very impressive.  Thank you, unutbu.
But, in order to produce more valid results, I need to re-frame my data values.  This means re-casting x values as a percentage of the max x value, while re-casting y values as a percentage of the x-values in the original data.  I tried to do this with your code, and came up with the following:

```<code>import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize

# Create numpy data arrays
'''
# Comment out original data
#x = np.array([821,576,473,377,326])
#y = np.array([255,235,208,166,157])
'''

# Re-calculate x values as a percentage of the first (maximum)
# original x value above
x = np.array([1.000,0.702,0.576,0.459,0.397])

# Recalculate y values as a percentage of their respective x values
# from original data above
y = np.array([0.311,0.408,0.440,0.440,0.482])

def sigmoid(p,x):
    x0,y0,c,k=p
    y = c / (1 + np.exp(-k*(x-x0))) + y0
    return y

def residuals(p,x,y):
    return y - sigmoid(p,x)

p_guess=(600,200,100,0.01)
(p,
 cov,
 infodict,
 mesg,
 ier)=scipy.optimize.leastsq(residuals,p_guess,args=(x,y),full_output=1,warning=True)

'''
# comment out original xp to allow for better scaling of
# new values
#xp = np.linspace(100, 1600, 1500)
'''

xp = np.linspace(0, 1.1, 1100)
pxp=sigmoid(p,xp)

x0,y0,c,k=p
print('''\
x0 = {x0}
y0 = {y0}
c = {c}
k = {k}
'''.format(x0=x0,y0=y0,c=c,k=k))

# Plot the results
plt.plot(x, y, '.', xp, pxp, '-')
plt.ylim(0,1)
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()
</code>```

Can you show me how to fix this revised code?

NOTE: By re-casting the data, I have essentially rotated the 2d (x,y) sigmoid about the z-axis by 180 degrees.  Also, the 1.000 is not really a maximum of the x values.  Instead, 1.000 is a mean of the range of values from different test participants in a maximum test condition.

SECOND EDIT BELOW:

Thank you, ubuntu.  I carefully read through your code and looked aspects of it up in the scipy documentation.  Since your name seems to pop up as a writer of the scipy documentation, I am hoping you can answer the following questions:

1.) Does leastsq() call residuals(), which then returns the difference between the input y-vector and the y-vector returned by the sigmoid() function?  If so, how does it account for the difference in the lengths of the input y-vector and the y-vector returned by the sigmoid() function?

2.) It looks like I can call leastsq() for any math equation, as long as I access that math equation through a residuals function, which in turn calls the math function.  Is this true?

3.) Also, I notice that p_guess has the same number of elements as p.  Does this mean that the four elements of p_guess correspond in order, respectively, with the values returned by x0,y0,c, and k?

4.) Is the p that is sent as an argument to the residuals() and sigmoid() functions the same p that will be output by leastsq(), and the leastsq() function is using that p internally before returning it?

5.) Can p and p_guess have any number of elements, depending on the complexity of the equation being used as a model, as long as the number of elements in p is equal to the number of elements in p_guess?

答:
I don't think you're going to get good results with a polynomial fit of any degree -- since
all polynomials go to infinity for sufficiently large and small X, but a sigmoid curve will asymptotically approach some finite value in each direction.

I'm not a Python programmer, so I don't know if numpy has a more general curve fitting
routine.  If you have to roll your own, perhaps this article on Logistic regression will give you some ideas.

Body:
I have two variables (x and y) that have a somewhat sigmoidal relationship with each other, and I need to find some sort of prediction equation that will enable me to predict the value of y, given any value of x.  My prediction equation needs to show the somewhat sigmoidal relationship between the two variables.  Therefore, I cannot settle for a linear regression equation that produces a line.  I need to see the gradual, curvilinear change in slope that occurs at both the right and left of the graph of the two variables.

I started using numpy.polyfit after googling curvilinear regression and python, but that gave me the awful results you can see if you run the code below.  Can anyone show me how to re-write the code below to get the type of sigmoidal regression equation that I want?

If you run the code below, you can see that it gives a downward facing parabola, which is not what the relationship between my variables should look like.  Instead, there should be more of a sigmoidal relationship between my two variables, but with a tight fit with the data that I am using in the code below.  The data in the code below are means from a large-sample research study, so they pack more statistical power than their five data points might suggest.  I do not have the actual data from the large-sample research study, but I do have the means below and their standard deviations(which I am not showing).  I would prefer to just plot a simple function with the mean data listed below, but the code could get more complex if complexity would offer substantial improvements.

How can I change my code to show a best fit of a sigmoidal function, preferably using scipy, numpy, and python?  Here is the current version of my code, which needs to be fixed:

import numpy as np
import matplotlib.pyplot as plt

# Create numpy data arrays
x = np.array([821,576,473,377,326])
y = np.array([255,235,208,166,157])

# Use polyfit and poly1d to create the regression equation
z = np.polyfit(x, y, 3)
p = np.poly1d(z)
xp = np.linspace(100, 1600, 1500)
pxp=p(xp)

# Plot the results
plt.plot(x, y, '.', xp, pxp, '-')
plt.ylim(140,310)
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()

EDIT BELOW: (Re-framed the question)

Your response, and its speed, are very impressive.  Thank you, unutbu.
But, in order to produce more valid results, I need to re-frame my data values.  This means re-casting x values as a percentage of the max x value, while re-casting y values as a percentage of the x-values in the original data.  I tried to do this with your code, and came up with the following:

import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize

# Create numpy data arrays
'''
# Comment out original data
#x = np.array([821,576,473,377,326])
#y = np.array([255,235,208,166,157])
'''

# Re-calculate x values as a percentage of the first (maximum)
# original x value above
x = np.array([1.000,0.702,0.576,0.459,0.397])

# Recalculate y values as a percentage of their respective x values
# from original data above
y = np.array([0.311,0.408,0.440,0.440,0.482])

def sigmoid(p,x):
    x0,y0,c,k=p
    y = c / (1 + np.exp(-k*(x-x0))) + y0
    return y

def residuals(p,x,y):
    return y - sigmoid(p,x)

p_guess=(600,200,100,0.01)
(p,
 cov,
 infodict,
 mesg,
 ier)=scipy.optimize.leastsq(residuals,p_guess,args=(x,y),full_output=1,warning=True)

'''
# comment out original xp to allow for better scaling of
# new values
#xp = np.linspace(100, 1600, 1500)
'''

xp = np.linspace(0, 1.1, 1100)
pxp=sigmoid(p,xp)

x0,y0,c,k=p
print('''\
x0 = {x0}
y0 = {y0}
c = {c}
k = {k}
'''.format(x0=x0,y0=y0,c=c,k=k))

# Plot the results
plt.plot(x, y, '.', xp, pxp, '-')
plt.ylim(0,1)
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()

Can you show me how to fix this revised code?

NOTE: By re-casting the data, I have essentially rotated the 2d (x,y) sigmoid about the z-axis by 180 degrees.  Also, the 1.000 is not really a maximum of the x values.  Instead, 1.000 is a mean of the range of values from different test participants in a maximum test condition.

SECOND EDIT BELOW:

Thank you, ubuntu.  I carefully read through your code and looked aspects of it up in the scipy documentation.  Since your name seems to pop up as a writer of the scipy documentation, I am hoping you can answer the following questions:

1.) Does leastsq() call residuals(), which then returns the difference between the input y-vector and the y-vector returned by the sigmoid() function?  If so, how does it account for the difference in the lengths of the input y-vector and the y-vector returned by the sigmoid() function?

2.) It looks like I can call leastsq() for any math equation, as long as I access that math equation through a residuals function, which in turn calls the math function.  Is this true?

3.) Also, I notice that p_guess has the same number of elements as p.  Does this mean that the four elements of p_guess correspond in order, respectively, with the values returned by x0,y0,c, and k?

4.) Is the p that is sent as an argument to the residuals() and sigmoid() functions the same p that will be output by leastsq(), and the leastsq() function is using that p internally before returning it?

5.) Can p and p_guess have any number of elements, depending on the complexity of the equation being used as a model, as long as the number of elements in p is equal to the number of elements in p_guess?


问:
How to trigger javascript confirm alert to show only once
I created a confirm alert for throwing a message if a particular user's password is about to expired and request them to change their password.

I created a function for this in the header.

If user successfully logs in, they will be directed to the home page (where I call the function - index.jsp).

The confirm alert will show up (as expected) when user successfully login.

Then, each time user clicks the Home menu (index.jsp page), the confirm alert will show up again.

How to make it to show up only once?

I want to make it appear just when user successfully login to the page.

Anyone can help? Would appreciate it so much.

This is in the header.jsp:

```<code>function pwdAlert(){
  <%if(!headerexpDay.equals("") && Integer.parseInt(headerexpDay) <= 10 ){%>
    var expDay = "<%=headerexpDay%>";

    if(confirm("Your login password will be expired in "+expDay+" day(s). Do you want to change password?")){
      document.frmHeader.method = "POST";
      document.frmHeader.action= "<%=request.getContextPath()%>/admin/frmChangePassword.jsp";
      document.frmHeader.target= "_self";
      document.frmHeader.submit();
    }
  <%}%>
}
</code>```

And this is in the index.jsp (home page) where I call the function.

```<code><SCRIPT>
  document.onreadystatechange = function () {
    if (document.readyState === "complete") {
      pwdAlert();
    }
  }
</SCRIPT>
</code>```

答:
Make use of cookies, step can be described like bellow:

Read the cookie variable (name: isIgnored as an example)

If isIgnored === false, run your pwdAlert()

Inside your pwdAlert, change your code of promt

```<code>if(confirm("Your login password will be expired in "+expDay+" day(s). Do you want to change password?")){
    // Your own code here
} else {
    // Set the cookie variable: isIgnored = true
}
</code>```

This show how to use cookies: https://www.w3schools.com/js/js_cookies.asp

Body:
I created a confirm alert for throwing a message if a particular user's password is about to expired and request them to change their password.

I created a function for this in the header.

If user successfully logs in, they will be directed to the home page (where I call the function - index.jsp).

The confirm alert will show up (as expected) when user successfully login.

Then, each time user clicks the Home menu (index.jsp page), the confirm alert will show up again.

How to make it to show up only once?

I want to make it appear just when user successfully login to the page.

Anyone can help? Would appreciate it so much.

This is in the header.jsp:

function pwdAlert(){
  <%if(!headerexpDay.equals("") && Integer.parseInt(headerexpDay) <= 10 ){%>
    var expDay = "<%=headerexpDay%>";

    if(confirm("Your login password will be expired in "+expDay+" day(s). Do you want to change password?")){
      document.frmHeader.method = "POST";
      document.frmHeader.action= "<%=request.getContextPath()%>/admin/frmChangePassword.jsp";
      document.frmHeader.target= "_self";
      document.frmHeader.submit();
    }
  <%}%>
}

And this is in the index.jsp (home page) where I call the function.

Body:
Make use of cookies, step can be described like bellow:

Read the cookie variable (name: isIgnored as an example)

If isIgnored === false, run your pwdAlert()

Inside your pwdAlert, change your code of promt

if(confirm("Your login password will be expired in "+expDay+" day(s). Do you want to change password?")){
    // Your own code here
} else {
    // Set the cookie variable: isIgnored = true
}

This show how to use cookies: https://www.w3schools.com/js/js_cookies.asp


问:
Python3.6/matplotlib: streamplot ignores xlim
The following code generates some figure files. My problem is at the end. Despite the explicit ax.set_xlim(...) command, the figures come out with varying ranges of x. I would like to use these figures as frames in a movie, so the nonuniform ranges displayed are a problem. Thanks PN</p>

```<code>"""
Description: MDantenna.py

Python 3.6
"""

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
plt.close('all')

""" variables
zbar = observer position in units of b, the ring radius
ctbar = observation time, times speed of ligh in units of b
kbar = wavenumber in units of 1/b"""
# parameters
gridsize = 7. # spatial extent of the grid to examine
gridN = 73  # number of gridpoints is 2*gridN**2. Use a big value for final run like 300
numFrames = 3 # how many movie frames
file_name = "{:03d}_movie.jpg"

def Rfun(xbar_, zbar_, alphlist): return np.sqrt(xbar_**2-2*xbar_*np.cos(alphlist)+zbar_**2+1)
def integrand1(alpha, ctbar_, xbar, zbar, kbar_):
    R = Rfun(xbar, zbar, alpha)
    phase = kbar_*(ctbar_ - R)
    return((-np.cos(phase)/R + kbar_*np.sin(phase))/R**2)
def integrand2(alpha, ctbar_, xbar, zbar, kbar_):
    R = Rfun(xbar, zbar, alpha)
    phase = kbar_*(ctbar_ - R)
    return(np.cos(alpha)*(-np.cos(phase)/R + kbar_*np.sin(phase))/R**2)

fig=plt.figure()
kbar = 2.*np.pi/3. #0.0 # 0 gives the static case (kbar=omegabar in these units)
xvals = np.linspace(0.,gridsize,gridN); nX = len(xvals)
zvals = np.linspace(-gridsize, gridsize, 2*gridN); nZ = len(zvals)
Bx = np.zeros((nX,nZ)); Bz = np.zeros((nX,nZ))
X,Z = np.meshgrid(xvals,zvals,indexing='ij')
whichframe=0
for ctbar in np.linspace(0, 2*np.pi/kbar, numFrames):
    whichframe+=1; print(whichframe)
    for ix in range(nX):
        for iz in range(nZ):
            x = X[ix,iz]; z=Z[ix,iz]
            Btmp1, er = quad(integrand1,-np.pi,np.pi,args=(ctbar,x,z,kbar))
            Btmp2, er = quad(integrand2,-np.pi,np.pi,args=(ctbar,x,z,kbar))
            Bx[ix,iz] = -z*Btmp2
            Bz[ix,iz] = -Btmp1 + x*Btmp2
    ax = plt.axes(xlim=(0,gridsize),ylim=(-gridsize,gridsize))
    for xstart in np.arange(.9,.4*gridsize,0.44):
        mystarts=np.array([[xstart + ctbar, 0.]])
        ax.streamplot(xvals,zvals,Bx.T,Bz.T,arrowsize=.4,start_points=mystarts)
        ax.axis('equal');
        ax.set_xlim((0,gridsize))
        ax.set_ylim((-gridsize,gridsize))
    plt.savefig(file_name.format(whichframe))
    plt.cla()
</code>```

答:
There are several things that will help your code, but the main problem is that the line ax.axis('equal'); doesn't work. Replacing it with ax.set_aspect('equal') gives the result you expect.

Beyond that, you are mixing pylab-style commands with the axis object commands. I've commented out some unnecessary lines and changed the remainder to use the pylab style.

This works for Matplotlib 2.0:

```<code>#fig=plt.figure() <- This figure is never used, one will be created for you
kbar = 2.*np.pi/3. #0.0 # 0 gives the static case (kbar=omegabar in these units)
xvals = np.linspace(0.,gridsize,gridN); nX = len(xvals)
zvals = np.linspace(-gridsize, gridsize, 2*gridN); nZ = len(zvals)
Bx = np.zeros((nX,nZ)); Bz = np.zeros((nX,nZ))
X,Z = np.meshgrid(xvals,zvals,indexing='ij')
whichframe=0
for ctbar in np.linspace(0, 2*np.pi/kbar, numFrames):
    whichframe+=1; print(whichframe)
    for ix in range(nX):
        for iz in range(nZ):
            x = X[ix,iz]; z=Z[ix,iz]
            Btmp1, er = quad(integrand1,-np.pi,np.pi,args=(ctbar,x,z,kbar))
            Btmp2, er = quad(integrand2,-np.pi,np.pi,args=(ctbar,x,z,kbar))
            Bx[ix,iz] = -z*Btmp2
            Bz[ix,iz] = -Btmp1 + x*Btmp2
#    ax = plt.axes(xlim=(0,gridsize),ylim=(-gridsize,gridsize)) <- only one axis per plot and limits are set later, so not needed
    for xstart in np.arange(.9,.4*gridsize,0.44):
        mystarts=np.array([[xstart + ctbar, 0.]])
        plt.streamplot(xvals,zvals,Bx.T,Bz.T,arrowsize=.4,start_points=mystarts)
    # These lines only need to be called once before saving the figure, so move them out of the loop
#    plt.axis('equal'); <- this wasn't setting the axes to `equal`
    plt.axes().set_aspect('equal')
    plt.xlim((0,gridsize))
    plt.ylim((-gridsize,gridsize))
    plt.savefig(file_name.format(whichframe))
    plt.clf() # clear the entire figure
</code>```

Body:
The following code generates some figure files. My problem is at the end. Despite the explicit ax.set_xlim(...) command, the figures come out with varying ranges of x. I would like to use these figures as frames in a movie, so the nonuniform ranges displayed are a problem. Thanks PN

"""
Description: MDantenna.py

Python 3.6
"""

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
plt.close('all')

""" variables
zbar = observer position in units of b, the ring radius
ctbar = observation time, times speed of ligh in units of b
kbar = wavenumber in units of 1/b"""
# parameters
gridsize = 7. # spatial extent of the grid to examine
gridN = 73  # number of gridpoints is 2*gridN**2. Use a big value for final run like 300
numFrames = 3 # how many movie frames
file_name = "{:03d}_movie.jpg"

def Rfun(xbar_, zbar_, alphlist): return np.sqrt(xbar_**2-2*xbar_*np.cos(alphlist)+zbar_**2+1)
def integrand1(alpha, ctbar_, xbar, zbar, kbar_):
    R = Rfun(xbar, zbar, alpha)
    phase = kbar_*(ctbar_ - R)
    return((-np.cos(phase)/R + kbar_*np.sin(phase))/R**2)
def integrand2(alpha, ctbar_, xbar, zbar, kbar_):
    R = Rfun(xbar, zbar, alpha)
    phase = kbar_*(ctbar_ - R)
    return(np.cos(alpha)*(-np.cos(phase)/R + kbar_*np.sin(phase))/R**2)

fig=plt.figure()
kbar = 2.*np.pi/3. #0.0 # 0 gives the static case (kbar=omegabar in these units)
xvals = np.linspace(0.,gridsize,gridN); nX = len(xvals)
zvals = np.linspace(-gridsize, gridsize, 2*gridN); nZ = len(zvals)
Bx = np.zeros((nX,nZ)); Bz = np.zeros((nX,nZ))
X,Z = np.meshgrid(xvals,zvals,indexing='ij')
whichframe=0
for ctbar in np.linspace(0, 2*np.pi/kbar, numFrames):
    whichframe+=1; print(whichframe)
    for ix in range(nX):
        for iz in range(nZ):
            x = X[ix,iz]; z=Z[ix,iz]
            Btmp1, er = quad(integrand1,-np.pi,np.pi,args=(ctbar,x,z,kbar))
            Btmp2, er = quad(integrand2,-np.pi,np.pi,args=(ctbar,x,z,kbar))
            Bx[ix,iz] = -z*Btmp2
            Bz[ix,iz] = -Btmp1 + x*Btmp2
    ax = plt.axes(xlim=(0,gridsize),ylim=(-gridsize,gridsize))
    for xstart in np.arange(.9,.4*gridsize,0.44):
        mystarts=np.array([[xstart + ctbar, 0.]])
        ax.streamplot(xvals,zvals,Bx.T,Bz.T,arrowsize=.4,start_points=mystarts)
        ax.axis('equal');
        ax.set_xlim((0,gridsize))
        ax.set_ylim((-gridsize,gridsize))
    plt.savefig(file_name.format(whichframe))
    plt.cla()

Body:
There are several things that will help your code, but the main problem is that the line ax.axis('equal'); doesn't work. Replacing it with ax.set_aspect('equal') gives the result you expect.

Beyond that, you are mixing pylab-style commands with the axis object commands. I've commented out some unnecessary lines and changed the remainder to use the pylab style.

This works for Matplotlib 2.0:

#fig=plt.figure() <- This figure is never used, one will be created for you
kbar = 2.*np.pi/3. #0.0 # 0 gives the static case (kbar=omegabar in these units)
xvals = np.linspace(0.,gridsize,gridN); nX = len(xvals)
zvals = np.linspace(-gridsize, gridsize, 2*gridN); nZ = len(zvals)
Bx = np.zeros((nX,nZ)); Bz = np.zeros((nX,nZ))
X,Z = np.meshgrid(xvals,zvals,indexing='ij')
whichframe=0
for ctbar in np.linspace(0, 2*np.pi/kbar, numFrames):
    whichframe+=1; print(whichframe)
    for ix in range(nX):
        for iz in range(nZ):
            x = X[ix,iz]; z=Z[ix,iz]
            Btmp1, er = quad(integrand1,-np.pi,np.pi,args=(ctbar,x,z,kbar))
            Btmp2, er = quad(integrand2,-np.pi,np.pi,args=(ctbar,x,z,kbar))
            Bx[ix,iz] = -z*Btmp2
            Bz[ix,iz] = -Btmp1 + x*Btmp2
#    ax = plt.axes(xlim=(0,gridsize),ylim=(-gridsize,gridsize)) <- only one axis per plot and limits are set later, so not needed
    for xstart in np.arange(.9,.4*gridsize,0.44):
        mystarts=np.array([[xstart + ctbar, 0.]])
        plt.streamplot(xvals,zvals,Bx.T,Bz.T,arrowsize=.4,start_points=mystarts)
    # These lines only need to be called once before saving the figure, so move them out of the loop
#    plt.axis('equal'); <- this wasn't setting the axes to `equal`
    plt.axes().set_aspect('equal')
    plt.xlim((0,gridsize))
    plt.ylim((-gridsize,gridsize))
    plt.savefig(file_name.format(whichframe))
    plt.clf() # clear the entire figure


问:
Generic Traits dependent on each other in Rust
I have two generic traits that need to be passed to each other as type parameters. The code boils down to this

```<code>pub trait Entity<T: EntityRenderer<Self>>
    where Self: Sized
{
    fn get_renderer(&self) -> &T;
}

pub trait EntityRenderer<T: Entity<Self>>
    where Self: Sized
{
    fn get_animation_frame(&T) -> u32;
}
</code>```

Entity needs to know what type it's EntityRenderer is, and vice versa. Later, I have

```<code>entities: Vec<Box<Entity>>
</code>```

This is an issue, as I can't resolve the type parameter of Entity. I also can't make either of the functions which need the type parameter generic, because Rust's compiler won't let traits with generic methods become trait objects.

Is there any workaround? Or am I violating some sort of memory safety law that I am unaware of?

答:
You can't do this with trait objects, because trait objects erase the real type of the underlying object. The giveaway is that, in order to use Self on the bound for T, you need the bound Self: Sized, yet that very bound disables the ability to use trait objects (like Box<Entity>). And we haven't even addressed the fact that Box<Entity> doesn't even specify a value for the type parameter T on Entity.

It looks like Entity (and maybe EntityRenderer too) should use an associated type instead of a type parameter. However, associated types won't solve your original problem; you'll get essentially the same problem, because you'd still need the Self: Sized bound and because you'd need to specify a value for the associated type on the trait object (Box<Entity<Renderer=???>>).

Body:
I have two generic traits that need to be passed to each other as type parameters. The code boils down to this

pub trait Entity<T: EntityRenderer<Self>>
    where Self: Sized
{
    fn get_renderer(&self) -> &T;
}

pub trait EntityRenderer<T: Entity<Self>>
    where Self: Sized
{
    fn get_animation_frame(&T) -> u32;
}

Entity needs to know what type it's EntityRenderer is, and vice versa. Later, I have

entities: Vec<Box<Entity>>

This is an issue, as I can't resolve the type parameter of Entity. I also can't make either of the functions which need the type parameter generic, because Rust's compiler won't let traits with generic methods become trait objects.

Is there any workaround? Or am I violating some sort of memory safety law that I am unaware of?


问:
How to distinguish int from int pointer in C?
I got a scenario in which I want to distinguish these two types.
It is easy to make it in other language such as python, C++, java. But it is
hard in C. Maybe I am not good at the basics. I have no idea how to achieve this.

Let's say: [1,2,3,[34,45],45]. The internal array exists as an elements in other array. How can I tell them ordinary element from the array.

I just think this is interesting so that I can know more about the property of C.

答:
The other languages you are mentioning are object-oriented, where C is not. C can only manipulate arrays of same-type objects. To be able to have multiple types as elements, you will have to create a union type which can hold either.</p>

```<code>union {
    int integer;
    int *pointer;
} myMixedArray[10] ;
</code>```

Body:
The other languages you are mentioning are object-oriented, where C is not. C can only manipulate arrays of same-type objects. To be able to have multiple types as elements, you will have to create a union type which can hold either.

union {
    int integer;
    int *pointer;
} myMixedArray[10] ;


问:
Android SoundPool doesn't play same sound for second time until playing another sound
Here is my Activity:

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

    private SoundPool soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        final int sound1 = soundPool.load(this, R.raw.whack, 1);
        final int sound2 = soundPool.load(this, R.raw.miss, 1);

        Button b1 = (Button) findViewById(R.id.b1);
        Button b2 = (Button) findViewById(R.id.b2);

        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playSound(sound1);
            }
        });
        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playSound(sound2);
            }
        });
    }

    private void playSound(int soundId) {

        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        float volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        soundPool.play(soundId, volume, volume, 1, 0, 1);
    }
}
</code>```

The problem is when I click on Button1, sound1 is played. Then when I click on Button1 again and again, nothing is played until I click on Button2. When I do that, sound2 is played. Then if I click on Button1, sound1 is played. Same scenario happens when I click on Button2 over and over. So what is the problem here?

答:
Have the same issue with Android version 7.0, you may try to fix it by changing this part of the code:

```<code>float volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
</code>```

into

```<code>float volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) /
               audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
</code>```

Hope this can solve the issue you're facing. :)

Body:
Here is my Activity:

public class MainActivity extends AppCompatActivity {

    private SoundPool soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        final int sound1 = soundPool.load(this, R.raw.whack, 1);
        final int sound2 = soundPool.load(this, R.raw.miss, 1);

        Button b1 = (Button) findViewById(R.id.b1);
        Button b2 = (Button) findViewById(R.id.b2);

        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playSound(sound1);
            }
        });
        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                playSound(sound2);
            }
        });
    }

    private void playSound(int soundId) {

        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        float volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        soundPool.play(soundId, volume, volume, 1, 0, 1);
    }
}

The problem is when I click on Button1, sound1 is played. Then when I click on Button1 again and again, nothing is played until I click on Button2. When I do that, sound2 is played. Then if I click on Button1, sound1 is played. Same scenario happens when I click on Button2 over and over. So what is the problem here?

Body:
Have the same issue with Android version 7.0, you may try to fix it by changing this part of the code:

float volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

into

float volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) /
               audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

Hope this can solve the issue you're facing. :)


问:
How to import jQuery UI using ES6/ES7 syntax?
I am trying to use some jQuery UI functionality in my reactJS/Redux application. I've imported both jQuery and jQuery UI using:

```<code>npm install jquery jquery-ui
</code>```

And then I've tried:

```<code>import $ from 'jquery';
import jQuery from 'query';
import jQuery-ui from 'jquery-ui';
</code>```

However jQuery UI does not seem to be imported when I try to do something like:

```<code>componentDidMount() {
  $('ol#myList').selectable();
}
</code>```

I believe the issue is with jQuery UI. What am I doing wrong? How can I get jQuery UI to work with this stack?

Thank you!

答:
Add a alias in webpack config:

```<code>resolve: {
  alias: {
    'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
  }
}
</code>```

Save them in package.json:

```<code>npm i --save jquery
npm i --save jquery-ui-dist
</code>```

Then

```<code>import $ from 'jquery';
import 'jquery-ui';
</code>```

It work for me with the last jquery(3.2.1) and jquery-ui(1.12.1).

See my blog for detail: http://code.tonytuan.org/2017/03/webpack-import-jquery-ui-in-es6-syntax.html

Body:
I am trying to use some jQuery UI functionality in my reactJS/Redux application. I've imported both jQuery and jQuery UI using:

npm install jquery jquery-ui

And then I've tried:

import $ from 'jquery';
import jQuery from 'query';
import jQuery-ui from 'jquery-ui';

However jQuery UI does not seem to be imported when I try to do something like:

componentDidMount() {
  $('ol#myList').selectable();
}

I believe the issue is with jQuery UI. What am I doing wrong? How can I get jQuery UI to work with this stack?

Thank you!

Body:
Add a alias in webpack config:

resolve: {
  alias: {
    'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
  }
}

Save them in package.json:

npm i --save jquery
npm i --save jquery-ui-dist

Then

import $ from 'jquery';
import 'jquery-ui';

It work for me with the last jquery(3.2.1) and jquery-ui(1.12.1).

See my blog for detail: http://code.tonytuan.org/2017/03/webpack-import-jquery-ui-in-es6-syntax.html


问:
Can you change a path without reloading the controller in AngularJS?
It's been asked before, and from the answers it doesn't look good. I'd like to ask with this sample code in consideration...

My app loads the current item in the service that provides it. There are several controllers that manipulate the item data without the item being reloaded.

My controllers will reload the item if it's not set yet, otherwise, it will use the currently loaded item from the service, between controllers.

Problem: I would like to use different paths for each controller without reloading Item.html.

1) Is that possible?

2) If that is not possible, is there a better approach to having a path per controller vs what I came up with here?

app.js

var app = angular.module('myModule', []).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.
      when('/items', {templateUrl: 'partials/items.html',   controller: ItemsCtrl}).
      when('/items/:itemId/foo', {templateUrl: 'partials/item.html', controller: ItemFooCtrl}).
      when('/items/:itemId/bar', {templateUrl: 'partials/item.html', controller: ItemBarCtrl}).
      otherwise({redirectTo: '/items'});
    }]);
```

<p>Item.html</p>

<pre class="lang-html prettyprint-override"><code><!-- Menu -->
Foo
Bar
<!-- Content -->
<div class="content" ng-include="" src="view.template"></div>
</code>```

controller.js

// Helper function to load $scope.item if refresh or directly linked
function itemCtrlInit($scope, $routeParams, MyService) {
  $scope.item = MyService.currentItem;
  if (!$scope.item) {
    MyService.currentItem = MyService.get({itemId: $routeParams.itemId});
    $scope.item = MyService.currentItem;
  }
}
function itemFooCtrl($scope, $routeParams, MyService) {
  $scope.view = {name: 'foo', template: 'partials/itemFoo.html'};
  itemCtrlInit($scope, $routeParams, MyService);
}
function itemBarCtrl($scope, $routeParams, MyService) {
  $scope.view = {name: 'bar', template: 'partials/itemBar.html'};
  itemCtrlInit($scope, $routeParams, MyService);
}
```

<p><strong>Resolution.</strong></p>

<p><strong>Status</strong>: Using search query as recommended in the accepted answer allowed me to provide different urls without reloading the main controller.</p>

<p>app.js</p>

<pre class="lang-js prettyprint-override"><code>var app = angular.module('myModule', []).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.
      when('/items', {templateUrl: 'partials/items.html',   controller: ItemsCtrl}).
      when('/item/:itemId/', {templateUrl: 'partials/item.html', controller: ItemCtrl, reloadOnSearch: false}).
      otherwise({redirectTo: '/items'});
    }]);
</code>```

Item.html

Foo

Bar

```

<p>controller.js</p>

<pre class="lang-js prettyprint-override"><code>function ItemCtrl($scope, $routeParams, Appts) {
  $scope.views = {
    foo: {name: 'foo', template: 'partials/itemFoo.html'},
    bar: {name: 'bar', template: 'partials/itemBar.html'},
  }
  $scope.view = $scope.views[$routeParams.view];
}
</code>```

directives.js

app.directive('itemTab', function(){
  return function(scope, elem, attrs) {
    scope.$watch(attrs.itemTab, function(val) {
      if (val+'Tab' == attrs.id) {
        elem.addClass('active');
      } else {
        elem.removeClass('active');
      }
    });
  }
});
```

The content inside my partials are wrapped with ng-controller=...

答:
Add following inside head tag

```<code>  <script type="text/javascript">
    angular.element(document.getElementsByTagName('head')).append(angular.element('<base href="' + window.location.pathname + '" />'));
  </script>
</code>```

This will prevent the reload.

Body:
It's been asked before, and from the answers it doesn't look good. I'd like to ask with this sample code in consideration...

My app loads the current item in the service that provides it. There are several controllers that manipulate the item data without the item being reloaded.

My controllers will reload the item if it's not set yet, otherwise, it will use the currently loaded item from the service, between controllers.

Problem: I would like to use different paths for each controller without reloading Item.html.

1) Is that possible?

2) If that is not possible, is there a better approach to having a path per controller vs what I came up with here?

app.js

var app = angular.module('myModule', []).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.
      when('/items', {templateUrl: 'partials/items.html',   controller: ItemsCtrl}).
      when('/items/:itemId/foo', {templateUrl: 'partials/item.html', controller: ItemFooCtrl}).
      when('/items/:itemId/bar', {templateUrl: 'partials/item.html', controller: ItemBarCtrl}).
      otherwise({redirectTo: '/items'});
    }]);

Item.html

Foo
Bar

controller.js

// Helper function to load $scope.item if refresh or directly linked
function itemCtrlInit($scope, $routeParams, MyService) {
  $scope.item = MyService.currentItem;
  if (!$scope.item) {
    MyService.currentItem = MyService.get({itemId: $routeParams.itemId});
    $scope.item = MyService.currentItem;
  }
}
function itemFooCtrl($scope, $routeParams, MyService) {
  $scope.view = {name: 'foo', template: 'partials/itemFoo.html'};
  itemCtrlInit($scope, $routeParams, MyService);
}
function itemBarCtrl($scope, $routeParams, MyService) {
  $scope.view = {name: 'bar', template: 'partials/itemBar.html'};
  itemCtrlInit($scope, $routeParams, MyService);
}

Resolution.

Status: Using search query as recommended in the accepted answer allowed me to provide different urls without reloading the main controller.

app.js

var app = angular.module('myModule', []).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.
      when('/items', {templateUrl: 'partials/items.html',   controller: ItemsCtrl}).
      when('/item/:itemId/', {templateUrl: 'partials/item.html', controller: ItemCtrl, reloadOnSearch: false}).
      otherwise({redirectTo: '/items'});
    }]);

Item.html

Foo

Bar

controller.js

function ItemCtrl($scope, $routeParams, Appts) {
  $scope.views = {
    foo: {name: 'foo', template: 'partials/itemFoo.html'},
    bar: {name: 'bar', template: 'partials/itemBar.html'},
  }
  $scope.view = $scope.views[$routeParams.view];
}

directives.js

app.directive('itemTab', function(){
  return function(scope, elem, attrs) {
    scope.$watch(attrs.itemTab, function(val) {
      if (val+'Tab' == attrs.id) {
        elem.addClass('active');
      } else {
        elem.removeClass('active');
      }
    });
  }
});

The content inside my partials are wrapped with ng-controller=...

Body:
Add following inside head tag

  <script type="text/javascript">
    angular.element(document.getElementsByTagName('head')).append(angular.element('<base href="' + window.location.pathname + '" />'));
  </script>

This will prevent the reload.


问:
How to nest a table within a table?
I've seen a similar topic, but not for my specific situation. I need to nest a table within the table and it will take up several cells, but when I try to nest a table it deletes the surrounding table at the same time. I included a picture of how it should look after my code and my code is how it looks currently. Can someone explain how this is done? Much appreciated.

/*
   CSS for Lounge Project
   Filename: styles.css

   Author:   Justus Self
   Date:     3/21/17
   HTML5 and CSS3 Illustrated Unit I, Lounge Independent Project
*/

/*Reset Styles*/
html, body{
   font-size: 14px;
   width: 100%;
   }
a, body, footer, header, h1, h2, h3, img, li, nav, p, ul, table, tbody, td, tfoot, th, thead, tr{
   border: 0;
   padding: 0;
   margin: 0;
}
img {
   max-width: 100%;
   height: auto;
   width: auto;
}

/*Drink font colors*/

h2.green {
  color: green;
}
h2.blue {
  color: blue;
}
h2.purple {
  color: purple;
}
h2.red {
  color: red;
}
h2.yellow {
  color: gold;
}

/*center and border image*/

img.smlounge {
  display: block;
  margin-left: auto;
  margin-right: auto;
  border: 3px solid;
  border-color: red;
}

/*Table styles*/

td, th {
  border: 1px solid black;
  font-size: 1.3em;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  padding: 0 1em ;
}
table {
  border-collapse: collapse;
  margin: 0 auto;
}
td[colspan="2"] {
  width: 20%;
}
.drink-name {
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Head First Lounge Elixirs</title>

  <!--
   Elixir page for Lounge Project
   Filename: elixir.html

   Author:   Justus Self
   Date:     3/21/17
   HTML5 and CSS3 Illustrated Unit I, Lounge Independent Project
   -->

  <link type="text/css" rel="stylesheet" href="../lounge.css" />
</head>

<body>
  <h1>Our Elixirs</h1>

  <h2 class="green">Green Tea Cooler</h2>
  <p>
    <img src="../images/green.jpg" alt="Green Tea Cooler" /> Chock full of vitamins and minerals, this elixir combines the healthful benefits of green tea with a twist of chamomile blossoms and ginger root.
  </p>
  <hr/>
  <h2 class="blue">Raspberry Ice Concentration</h2>
  <p>
    <img src="../images/lightblue.jpg" alt="Rasberry Ice Concentration" /> Combining raspberry juice with lemon grass, citrus peel and rosehips, this icy drink will make your mind feel clear and crisp.
  </p>
  <hr/>
  <h2 class="purple">Blueberry Bliss Elixir</h2>
  <p>
    <img src="../images/blue.jpg" alt="Blueberry Bliss Elixir" /> Blueberries and cherry essence mixed into a base of elderflower herb tea will put you in a relaxed state of bliss in no time.
  </p>
  <hr/>
  <h2 class="red">Cranberry Antioxidant Blast</h2>
  <p>
    <img src="../images/red.jpg" alt="Cranberry Antioxidant Blast" /> Wake up to the flavors of cranberry and hibiscus in this vitamin C rich elixir.
  </p>
  <hr/>
  <h2 class="yellow">Lemon Breeze</h2>
  <p><img src="../images/yellow.gif" alt="Lemon Breeze Drink" /> The ultimate healthy drink, this elixir combines herbal botanicals, minerals, and vitamins with a twist of lemon into a smooth citrus wonder that will keep your immune system going all day
    and all night.
  </p>
  <hr/>
  <br/>
  <table>
    <thead>
      <tr>
        <th colspan="6">Our Drink Prices</th>
      </tr>
      <tr>
        <th colspan="2">Drink</th>
        <th colspan="2">Size</th>
        <th colspan="2">Price</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td rowspan="2" colspan="2" class="drink-name">Green Tea Cooler</td>
        <td colspan="2">16 oz.</td>
        <td colspan="2">$3.75</td>
      </tr>
      <tr>
        <td colspan="2">24 oz.</td>
        <td colspan="2">$4.75</td>
      </tr>
      <tr>
        <td rowspan="2" colspan="2" class="drink-name">Raspberry Ice Concentration</td>
        <td colspan="2">16 oz.</td>
        <td colspan="2">$3.75</td>
      </tr>
      <tr>
        <td colspan="2">24 oz.</td>
        <td colspan="2">$4.75</td>
      </tr>
      <tr>
        <td colspan="2" class="drink-name">Cranberry Antioxidant Blast</td>
        <td colspan="2">20 oz.</td>
        <td colspan="2">$4.75</td>
      </tr>
      <tr>
        <td rowspan="2" colspan="2" class="drink-name">Lemon Breeze</td>
        <td>Iced</td>
        <td>16 oz.</td>
        <td>$3.75</td>
      </tr>
      <tr>
        <td>Frozen</td>
        <td>20 oz.</td>
        <td>$4.75</td>
      </tr>
    </tbody>
  </table>
  <p>Back to the Lounge</p>

  <footer>
    ©2016, Head First Online Lounge<br /> All trademarks and registered trademarks appearing on this site are the property of their respective owners.
  </footer>
</body>

</html></code>```

How the table should look

答:
You can do something like below and change the CSS as per your need.

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Head First Lounge Elixirs</title>

  <link type="text/css" rel="stylesheet" href="../lounge.css" />

Our Elixirs

Green Tea Cooler

     Chock full of vitamins and minerals, this elixir combines the healthful benefits of green tea with a twist of chamomile blossoms and ginger root.

Raspberry Ice Concentration

     Combining raspberry juice with lemon grass, citrus peel and rosehips, this icy drink will make your mind feel clear and crisp.

Blueberry Bliss Elixir

     Blueberries and cherry essence mixed into a base of elderflower herb tea will put you in a relaxed state of bliss in no time.

Cranberry Antioxidant Blast

     Wake up to the flavors of cranberry and hibiscus in this vitamin C rich elixir.

Lemon Breeze

 The ultimate healthy drink, this elixir combines herbal botanicals, minerals, and vitamins with a twist of lemon into a smooth citrus wonder that will keep your immune system going all day
    and all night.

        Our Drink Prices

        Drink
        Size
        Price

        Green Tea Cooler
        16 oz.
        $3.75

        24 oz.
        $4.75

        Raspberry Ice Concentration
        16 oz.
        $3.75

        24 oz.
        $4.75

        Cranberry Antioxidant Blast
        20 oz.
        $4.75

        Lemon Breeze

              Iced
              16 oz.

              Frozen
              20 oz.

              $3.75

              $4.75

Back to the Lounge

    ©2016, Head First Online Lounge
 All trademarks and registered trademarks appearing on this site are the property of their respective owners.

```

Hope this helps!

Title: How to nest a table within a table?

Body:
I've seen a similar topic, but not for my specific situation. I need to nest a table within the table and it will take up several cells, but when I try to nest a table it deletes the surrounding table at the same time. I included a picture of how it should look after my code and my code is how it looks currently. Can someone explain how this is done? Much appreciated.

/*
   CSS for Lounge Project
   Filename: styles.css

   Author:   Justus Self
   Date:     3/21/17
   HTML5 and CSS3 Illustrated Unit I, Lounge Independent Project
*/

/*Reset Styles*/
html, body{
   font-size: 14px;
   width: 100%;
   }
a, body, footer, header, h1, h2, h3, img, li, nav, p, ul, table, tbody, td, tfoot, th, thead, tr{
   border: 0;
   padding: 0;
   margin: 0;
}
img {
   max-width: 100%;
   height: auto;
   width: auto;
}

/*Drink font colors*/

h2.green {
  color: green;
}
h2.blue {
  color: blue;
}
h2.purple {
  color: purple;
}
h2.red {
  color: red;
}
h2.yellow {
  color: gold;
}

/*center and border image*/

img.smlounge {
  display: block;
  margin-left: auto;
  margin-right: auto;
  border: 3px solid;
  border-color: red;
}

/*Table styles*/

td, th {
  border: 1px solid black;
  font-size: 1.3em;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  padding: 0 1em ;
}
table {
  border-collapse: collapse;
  margin: 0 auto;
}
td[colspan="2"] {
  width: 20%;
}
.drink-name {
  text-align: left;
}

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Head First Lounge Elixirs</title>

  <link type="text/css" rel="stylesheet" href="../lounge.css" />

Our Elixirs

Green Tea Cooler

     Chock full of vitamins and minerals, this elixir combines the healthful benefits of green tea with a twist of chamomile blossoms and ginger root.

Raspberry Ice Concentration

     Combining raspberry juice with lemon grass, citrus peel and rosehips, this icy drink will make your mind feel clear and crisp.

Blueberry Bliss Elixir

     Blueberries and cherry essence mixed into a base of elderflower herb tea will put you in a relaxed state of bliss in no time.

Cranberry Antioxidant Blast

     Wake up to the flavors of cranberry and hibiscus in this vitamin C rich elixir.

Lemon Breeze

 The ultimate healthy drink, this elixir combines herbal botanicals, minerals, and vitamins with a twist of lemon into a smooth citrus wonder that will keep your immune system going all day
    and all night.

        Our Drink Prices

        Drink
        Size
        Price

        Green Tea Cooler
        16 oz.
        $3.75

        24 oz.
        $4.75

        Raspberry Ice Concentration
        16 oz.
        $3.75

        24 oz.
        $4.75

        Cranberry Antioxidant Blast
        20 oz.
        $4.75

        Lemon Breeze
        Iced
        16 oz.
        $3.75

        Frozen
        20 oz.
        $4.75

Back to the Lounge

    ©2016, Head First Online Lounge
 All trademarks and registered trademarks appearing on this site are the property of their respective owners.

How the table should look

Body:
You can do something like below and change the CSS as per your need.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Head First Lounge Elixirs</title>

  <!--
   Elixir page for Lounge Project
   Filename: elixir.html

   Author:   Justus Self
   Date:     3/21/17
   HTML5 and CSS3 Illustrated Unit I, Lounge Independent Project
   -->

  <link type="text/css" rel="stylesheet" href="../lounge.css" />
</head>

<body>
  <h1>Our Elixirs</h1>

  <h2 class="green">Green Tea Cooler</h2>
  <p>
    <img src="../images/green.jpg" alt="Green Tea Cooler" /> Chock full of vitamins and minerals, this elixir combines the healthful benefits of green tea with a twist of chamomile blossoms and ginger root.
  </p>
  <hr/>
  <h2 class="blue">Raspberry Ice Concentration</h2>
  <p>
    <img src="../images/lightblue.jpg" alt="Rasberry Ice Concentration" /> Combining raspberry juice with lemon grass, citrus peel and rosehips, this icy drink will make your mind feel clear and crisp.
  </p>
  <hr/>
  <h2 class="purple">Blueberry Bliss Elixir</h2>
  <p>
    <img src="../images/blue.jpg" alt="Blueberry Bliss Elixir" /> Blueberries and cherry essence mixed into a base of elderflower herb tea will put you in a relaxed state of bliss in no time.
  </p>
  <hr/>
  <h2 class="red">Cranberry Antioxidant Blast</h2>
  <p>
    <img src="../images/red.jpg" alt="Cranberry Antioxidant Blast" /> Wake up to the flavors of cranberry and hibiscus in this vitamin C rich elixir.
  </p>
  <hr/>
  <h2 class="yellow"><a name="Yellow">Lemon Breeze</a></h2>
  <p><img src="../images/yellow.gif" alt="Lemon Breeze Drink" /> The ultimate healthy drink, this elixir combines herbal botanicals, minerals, and vitamins with a twist of lemon into a smooth citrus wonder that will keep your immune system going all day
    and all night.
  </p>
  <hr/>
  <br/>
  <table>
    <thead>
      <tr>
        <th colspan="6">Our Drink Prices</th>
      </tr>
      <tr>
        <th colspan="2">Drink</th>
        <th colspan="2">Size</th>
        <th colspan="2">Price</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td rowspan="2" colspan="2" class="drink-name">Green Tea Cooler</td>
        <td colspan="2">16 oz.</td>
        <td colspan="2">$3.75</td>
      </tr>
      <tr>
        <td colspan="2">24 oz.</td>
        <td colspan="2">$4.75</td>
      </tr>
      <tr>
        <td rowspan="2" colspan="2" class="drink-name">Raspberry Ice Concentration</td>
        <td colspan="2">16 oz.</td>
        <td colspan="2">$3.75</td>
      </tr>
      <tr>
        <td colspan="2">24 oz.</td>
        <td colspan="2">$4.75</td>
      </tr>
      <tr>
        <td colspan="2" class="drink-name">Cranberry Antioxidant Blast</td>
        <td colspan="2">20 oz.</td>
        <td colspan="2">$4.75</td>
      </tr>
      <tr>
        <td rowspan="2" colspan="2" class="drink-name">Lemon Breeze</td>
        <td colspan="2">
          <table>
            <tr>

              <td>Iced</td>
              <td>16 oz.</td>
            </tr>
            <tr>
              <td>Frozen</td>
              <td>20 oz.</td>
            </tr>
          </table>
        </td>
        <td colspan="2">
          <table>
            <tr>
              <td>$3.75</td>
            </tr>
            <tr>
              <td>$4.75</td>
            </tr>
          </table>
        </td>
      </tr>
    </tbody>
  </table>
  <p><a href="../lounge.html">Back to the Lounge</a></p>

  <footer>
    &#169;2016, Head First Online Lounge<br /> All trademarks and registered trademarks appearing on this site are the property of their respective owners.
  </footer>
</body>

</html>

Hope this helps!


问:
Translate java object to soap
I have this (not so cool) web service:

```<code>import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

@WebService()
public class WMCWeb {
}
</code>```

And would like to do something like

```<code>@WebMethod(operationName = "getMyObject")
public MyObject getMyObject(@WebParam(name = "id") String id) {
        ...
        return new myObject;
}
</code>```

But I can't just return an object. I don't really know what I should do to be able to do so. I read something about writing a org.apache.soap.util.Serializer, but it seems like an old solution. How can I make the WebService know how to translate the object to a Soap response?

答:
JAX-WS utilizes JAXB (the actual version of JAXB used depends on the version of JAX-WS) to perform binding between the XML document (the SOAP message on the wire) and the Java types. If you substitute the String parameter with one of type java.lang.Object, then the JAXB runtime is bound to find difficulties during serialization and de-serialization, as no such bindings exist that determine how the runtime should perform such a process.

I suspect that you are attempting to perform type substitution at runtime, using a super class. If that is the case, you should be using JAX-WS 2.1 and the XmlSeeAlso annotation in JAXB 2.1 to this effect; it is also recommended to construct a suitable superclass, even if you do manage to generate an appropriate WSDL.

Title: Translate java object to soap

Body:
I have this (not so cool) web service:

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

@WebService()
public class WMCWeb {
}

And would like to do something like

@WebMethod(operationName = "getMyObject")
public MyObject getMyObject(@WebParam(name = "id") String id) {
        ...
        return new myObject;
}

But I can't just return an object. I don't really know what I should do to be able to do so. I read something about writing a org.apache.soap.util.Serializer, but it seems like an old solution. How can I make the WebService know how to translate the object to a Soap response?


问:
How to get a scatter plot of mixture data with different shape and colour for each distribution?
I am running a simulation of mixture data. My function is harder than Gaussian distribution. Hence, here, I simplified my question to be in Gaussian form. That is, if I simulated a mixture data like this:

```<code>  N=2000
 U=runif(N, min=0,max=1)
 X = matrix(NA, nrow=N, ncol=2)
         for (i in 1:N){
              if(U[i] < 0.7){
               X[i,] <-   rnorm(1,0.5,1)
                    } else {
               X[i,] <- rnorm(1,3,5)
      }
 }
</code>```

How can I have a scatter plot with different colour and shape (type of the plot point) for each cluster or distribution? I would like to have this manually since my function is hard  and complex.  I tried plot(X[,1],X[,2],col=c("red","blue")) but it does not work.

答:
Here's what I got, but I'm not sure if this what you are looking for - the location of the observations for both clusters are exactly the same.

```<code>library(tidyverse)
df <- data.frame(X = X, U = U)
df <- gather(df, key = cluster, value = X, -U)
ggplot(df, aes(x = X, y = U, colour = cluster)) + geom_point() + facet_wrap(~cluster)
</code>```

EDIT: I don't seem to be understanding what you are looking to map onto a scatter plot, so I'll indicate how you need to shape your data in order to create a chart like the above with the proper X and Y coordinates:

```<code> head(df)
            U cluster          X
 1 0.98345408     X.1  2.3296047
 2 0.33939935     X.1 -0.6042917
 3 0.66715421     X.1 -2.2673422
 4 0.06093674     X.1  2.4007376
 5 0.48162959     X.1 -2.3118850
 6 0.50780007     X.1 -0.7307929
</code>```

So you want one variable for the Y coordinate (I'm using variable U here), one variable for the X coordinate (using X here), and a 3rd variable that indicates whether the observation belongs to cluster 1 or cluster 2 (variable cluster here).

Body:
I am running a simulation of mixture data. My function is harder than Gaussian distribution. Hence, here, I simplified my question to be in Gaussian form. That is, if I simulated a mixture data like this:

  N=2000
 U=runif(N, min=0,max=1)
 X = matrix(NA, nrow=N, ncol=2)
         for (i in 1:N){
              if(U[i] < 0.7){
               X[i,] <-   rnorm(1,0.5,1)
                    } else {
               X[i,] <- rnorm(1,3,5)
      }
 }

How can I have a scatter plot with different colour and shape (type of the plot point) for each cluster or distribution? I would like to have this manually since my function is hard  and complex.  I tried plot(X[,1],X[,2],col=c("red","blue")) but it does not work.

Body:
Here's what I got, but I'm not sure if this what you are looking for - the location of the observations for both clusters are exactly the same.

library(tidyverse)
df <- data.frame(X = X, U = U)
df <- gather(df, key = cluster, value = X, -U)
ggplot(df, aes(x = X, y = U, colour = cluster)) + geom_point() + facet_wrap(~cluster)

EDIT: I don't seem to be understanding what you are looking to map onto a scatter plot, so I'll indicate how you need to shape your data in order to create a chart like the above with the proper X and Y coordinates:

 head(df)
            U cluster          X
 1 0.98345408     X.1  2.3296047
 2 0.33939935     X.1 -0.6042917
 3 0.66715421     X.1 -2.2673422
 4 0.06093674     X.1  2.4007376
 5 0.48162959     X.1 -2.3118850
 6 0.50780007     X.1 -0.7307929

So you want one variable for the Y coordinate (I'm using variable U here), one variable for the X coordinate (using X here), and a 3rd variable that indicates whether the observation belongs to cluster 1 or cluster 2 (variable cluster here).


问:
Xcode 6.4 quits unexpectedly in macOS Sierra?
I have many working projects built in Xcode 6.4(had OS X Yosemite).
Recently i updated to macOS Sierra.
And also i have installed Xcode version 7.3.1.
i.e. i have multiple Xcode versions installed following this link.
http://iosdevelopertips.com/xcode/install-multiple-versions-of-xcode.html

However i can open my projects in Xcode 7.3.1 but it shows too many errors. i want to open it in Xcode 6.4, which is giving me the error "Xcode quit unexpectedly." each time i reopen the project in Xcode 6.4

I tried this solutions, still no results

Xcode quits unexpectedly every time I open my project

Xcode 5 crashes -- Xcode quit unexpectedly

I understand there is some compatibility issue.
Is there any solution.SOMEONE PLEASE HELP ME.

答:
I have the same issue.Out project is on xcode6.4.When i upgrade from mac 10.11 to 10.12.
Xcode 6.4 crashed when open.
I just downgraded to 10.11 back.</p>


问:
Merge JSON records using Python
I have a huge json file as follows,

```<code>{"id": "KA88457","name": "Steven", "phone":"+6590876589"},
{"id": "KA88457", "fax": ["+6563323248"], "email":"steve@alexandra.com"}
</code>```

I need to merge the two and obtain the desired result as

```<code>{"id": "KA88457",
 "name": "Steven",
 "phone":"+6590876589",
 "fax":["+6563323248"],
 "email":"steve@alexandra.com"}
</code>```

I checked online but I was able to find only merging two json files in python. Can you please help to in merging these type of records using python.

答:
Assuming you know how to convert the strings from json to a python dictionary object (see json module) you can 'merge' them in the way you describe, with the following:

```<code>objOne = {"id": "KA88457","name": "Steven", "phone":"+6590876589"}
objTwo = {"id": "KA88457", "fax": ["+6563323248"], "email":"steve@alexandra.com"}

for key in objOne:
    objTwo[key] = objOne[key]
</code>```

This should take all the properties of objOne and add them to objTwo.

Title: Merge JSON records using Python

Body:
I have a huge json file as follows,

{"id": "KA88457","name": "Steven", "phone":"+6590876589"},
{"id": "KA88457", "fax": ["+6563323248"], "email":"steve@alexandra.com"}

I need to merge the two and obtain the desired result as

{"id": "KA88457",
 "name": "Steven",
 "phone":"+6590876589",
 "fax":["+6563323248"],
 "email":"steve@alexandra.com"}

I checked online but I was able to find only merging two json files in python. Can you please help to in merging these type of records using python.

Body:
Assuming you know how to convert the strings from json to a python dictionary object (see json module) you can 'merge' them in the way you describe, with the following:

objOne = {"id": "KA88457","name": "Steven", "phone":"+6590876589"}
objTwo = {"id": "KA88457", "fax": ["+6563323248"], "email":"steve@alexandra.com"}

for key in objOne:
    objTwo[key] = objOne[key]

This should take all the properties of objOne and add them to objTwo.


问:
PHP code does not recognize some values
EDIT: Thank you all for the very quick answers! I have been at this for a while, trying to figure out why $id was being recognized and why the strings weren't. I feel a bit silly now seeing the obvious answer but I'm relieved to have it working.

I apologize if this has been answered before, I've looked for hours and could not find something similar to help me figure this out.

I am trying to update a row in my database of devices with new information. Problem is, the php file only recognizes $data->devID; and nothing else.

If I have something like
$sql = "UPDATE devices SET devName = 'static test string', description = 'static test string' WHERE devID = $id";
the entry with the correct ID will update in my database table just fine.

If I try
$sql = "UPDATE devices SET devName = $name, description = $desc WHERE devID = $id";
it does not work.

Where am I going wrong?

HTML:

```<code><div data-ng-repeat="info in deviceInfo">
    <form class="deviceInfo">
        <h2>Device ID: {{info.devID}}</h2>
        <p>Device Name:</p>
        <input type="text" data-ng-model="info.devName">
        <p>Device Description:</p>
        <textarea data-ng-model="info.description"></textarea>
        <p>Device Available: {{info.isAvailable}}</p>
        <input type="submit" name="Update" value="Update" data-ng-click="updateInfo(info.devID, info.devName, info.description)">
    </form>
</div>
</code>```

updateDeviceInfo.php:

```<code><?php

$data = json_decode(file_get_contents("php://input"));

include('config.php');

$id = $data->devID;
$name = $data->devName;
$desc = $data->description;

$sql = "UPDATE devices SET devName = $name, description = $desc WHERE devID = $id";

$qry = $conn->query($sql);

$data = $qry;

$sql = "SELECT * FROM devices";

$qry = $conn->query($sql);

$data = array();

if($qry->num_rows > 0){
    while($row = $qry->fetch_object()){
        $data[] = $row;
    }
}else {
    $data[] = null;
}

$conn->close();

echo json_encode($data);
</code>```

controller.js:

```<code>$scope.updateInfo = function($paramID, $paramName, $paramDesc){

    console.log($paramID);
    console.log($paramName);
    console.log($paramDesc);

    $scope.dataOneTest = {
            devID: $paramID,
            devName: $paramName,
            description: $paramDesc

        };

    console.log($scope.dataOneTest.devID);

    $http.post('./js/updateDeviceInfo.php', {'devID': $paramID, 'devName': $paramName, 'description': $paramDesc})
        .success(function(data){
            $scope.results = data;
        })
        .error(function(err){
            $log.error(err);
        })
}
</code>```

答:
change this becuase description and devName which are string should be quoted

$sql = "UPDATE devices SET devName = $name, description = $desc WHERE devID = $id";

to

$sql = "UPDATE devices SET devName = '".$name."', description = '".$desc."' WHERE devID = $id";

Title: PHP code does not recognize some values

Body:
EDIT: Thank you all for the very quick answers! I have been at this for a while, trying to figure out why $id was being recognized and why the strings weren't. I feel a bit silly now seeing the obvious answer but I'm relieved to have it working.

I apologize if this has been answered before, I've looked for hours and could not find something similar to help me figure this out.

I am trying to update a row in my database of devices with new information. Problem is, the php file only recognizes $data->devID; and nothing else.

If I have something like
$sql = "UPDATE devices SET devName = 'static test string', description = 'static test string' WHERE devID = $id";
the entry with the correct ID will update in my database table just fine.

If I try
$sql = "UPDATE devices SET devName = $name, description = $desc WHERE devID = $id";
it does not work.

Where am I going wrong?

HTML:

    <form class="deviceInfo">

Device ID: {{info.devID}}

Device Name:

        <input type="text" data-ng-model="info.devName">

Device Description:

        <textarea data-ng-model="info.description"></textarea>

Device Available: {{info.isAvailable}}

        <input type="submit" name="Update" value="Update" data-ng-click="updateInfo(info.devID, info.devName, info.description)">
    </form>

updateDeviceInfo.php:

<?php

$data = json_decode(file_get_contents("php://input"));

include('config.php');

$id = $data->devID;
$name = $data->devName;
$desc = $data->description;

$sql = "UPDATE devices SET devName = $name, description = $desc WHERE devID = $id";

$qry = $conn->query($sql);

$data = $qry;

$sql = "SELECT * FROM devices";

$qry = $conn->query($sql);

$data = array();

if($qry->num_rows > 0){
    while($row = $qry->fetch_object()){
        $data[] = $row;
    }
}else {
    $data[] = null;
}

$conn->close();

echo json_encode($data);

controller.js:

$scope.updateInfo = function($paramID, $paramName, $paramDesc){

    console.log($paramID);
    console.log($paramName);
    console.log($paramDesc);

    $scope.dataOneTest = {
            devID: $paramID,
            devName: $paramName,
            description: $paramDesc

        };

    console.log($scope.dataOneTest.devID);

    $http.post('./js/updateDeviceInfo.php', {'devID': $paramID, 'devName': $paramName, 'description': $paramDesc})
        .success(function(data){
            $scope.results = data;
        })
        .error(function(err){
            $log.error(err);
        })
}


问:
Regex java operators
This is my regex .+\s*(?=!|<|>|=|LIKE) and it doesnt work.

I want to match everything on the left side to the operators <,>,<=,>=,=,!=,LIKE.

Obviously my regex doesn't do the work so I am wondering if you could help me.

Check out what is wrong on this link: https://regex101.com/r/skRdTr/1
(it matches everything on the left side, including >,<,! if operator is <=,>=,!=)

答: I found the answer: .+?\s*(?=!|<|>|=|LIKE).

Title: Regex java operators


答:
Try this, $sql = "UPDATE devices SET devName = '$name', description = '$desc' WHERE devID = $id";

As title and description are string it requires single quote wrapping inside double quotes.

Title: PHP code does not recognize some values