问:
How use indices and import data for Python PuLP Mathematical Optimization
I have used optimization modelers in the past, but it's been a while and I am still learning how to do this in python.  I have done some online research and am using the open-source version of PuLp https://pythonhosted.org/PuLP/

I have the following formulated and working for three locations.  My questions are how to formulate the problem with imported data from a CSV, since my dataset actually includes 70 locations. Typing the number of possibilities for the routes to those routes would seem foolish; I imagine there is a better way to program this.  I understand how to use csv.reader() but I am less sure of how to proceed with formulating the problem.

Example Model:

```<code>"""
Traveling Salesman Problem (TSP) Simplified Model
Date: 2017-03-30
"""

# Import PuLP modeler functions
from pulp import *

# Create the 'prob' variable to contain the problem data
prob = LpProblem("The TSP Problem1",LpMinimize)

# Formulation summary
#   The decision variable x is equal to 1 or 0, whether the path is chosen
#   Each path has a cost associated with it
#   The objective is to choose the shortest path
#   The constraint, essentially, is that each location is visited

# The LpVariable class has four parameters
    # the first is an arbitrary name
    # the second is the lower bound
    # the third is the upper bound
    # the fourth is the type of data, discrete or continuous
x12=LpVariable("flow12",0,None,LpInteger)
x13=LpVariable("flow13",0,None,LpInteger)
x21=LpVariable("flow21",0,None,LpInteger)
x23=LpVariable("flow23",0,None,LpInteger)
x31=LpVariable("flow31",0,None,LpInteger)
x32=LpVariable("flow32",0,None,LpInteger)

# The objective function is added to 'prob' first
# the objective is to minimize the total distance traveled
# the numbers represent the distances between two variables

prob += 30*x12 + 5*x13 +25*x21 + 1*x23 + 5*x31 + 8*x32, "Total Distance Traveled"

# The constraints:

# each location needs to be on the route but only once
prob += x12 + x32 == 1.0, "Location2 is visited"
prob += x13 + x23 == 1.0, "Location3 is visited"
prob += x21 + x31 == 1.0, "Location1 is visited"

# each location is departed exactly once
prob += x31 + x32 == 1.0, "Location3 is departed"
prob += x21 + x23 == 1.0, "Location2 is departed"
prob += x12 + x13 == 1.0, "Location is departed"

# The problem data is written to an .lp file
prob.writeLP("SupplyChainAssignment.lp")

# The problem is solved using PuLP's choice of Solver
prob.solve()

# The status of the solution is printed to the screen
print "Status:", LpStatus[prob.status]

# Each of the variables is printed with it's resolved optimum value
for v in prob.variables():
    print v.name, "=", v.varValue

# The optimized objective function value is printed to the screen
print "Total Cost TSP Assignment = ", value(prob.objective)
</code>```

That's the end of the example which is currently working.

I am thinking that I can use dictionaries such as the following for distance:

```<code>distance = {'x12': 30,
            'x13': 5,
            'x21': 25,
            'x23': 1,
            'x31': 5,
            'x32': 8}
</code>```

But I am not sure if the following would work for variables:

```<code>x = {'x12',
     'x13',
     'x21',
     'x23',
     'x31',
     'x32'}

x=LpVariable("flow",0,1,LpInteger)
</code>```

And that also does not solve my question of how to rewrite the constraints using indices, so I haven't tested whether my guess on syntax above would work:

```<code>prob += x12 + x32 == 1.0, "Location2 is visited"
prob += x13 + x23 == 1.0, "Location3 is visited"
prob += x21 + x31 == 1.0, "Location1 is visited"

# each location is departed
prob += x31 + x32 == 1.0, "Location3 is departed"
prob += x21 + x23 == 1.0, "Location2 is departed"
prob += x12 + x13 == 1.0, "Location is departed"
</code>```

Any suggestions on what I should read up on, or if there are any examples that you could point me to would be helpful.

Thanks!

答:
Read a bit more of the documentation and you will see some good examples

https://pythonhosted.org/PuLP/CaseStudies/a_blending_problem.html#solution-to-full-problem

From this document you will see the following

```<code># A dictionary called 'ingredient_vars' is created to contain the referenced Variables
ingredient_vars = LpVariable.dicts("Ingr",Ingredients,0)
</code>```

Since costs and ingredient_vars are now dictionaries with the reference keys as the Ingredient names, the data can be simply extracted with a list comprehension as shown. The lpSum() function will add the elements of the resulting list. Thus the objective function is simply entered and assigned a name:

```<code># The objective function is added to 'prob' first
prob += lpSum([costs[i]*ingredient_vars[i] for i in Ingredients]), "Total Cost of Ingredients per can"
</code>```

Further list comprehensions are used to define the other 5 constraints, which are also each given names describing them.

```<code># The five constraints are added to 'prob'
prob += lpSum([ingredient_vars[i] for i in Ingredients]) == 100, "PercentagesSum"
prob += lpSum([proteinPercent[i] * ingredient_vars[i] for i in Ingredients]) >= 8.0, "ProteinRequirement"
prob += lpSum([fatPercent[i] * ingredient_vars[i] for i in Ingredients]) >= 6.0, "FatRequirement"
prob += lpSum([fibrePercent[i] * ingredient_vars[i] for i in Ingredients]) <= 2.0, "FibreRequirement"
prob += lpSum([saltPercent[i] * ingredient_vars[i] for i in Ingredients]) <= 0.4, "SaltRequirement"
</code>```

In this example you can see how to define a problem using dictionaries of variables and dictionaries of parameters.

Then you will have to use the csv module to read the parameter data (I would recommend csv.DictReader to do this)

You are right however, it would be nice to have a specific example in the documentation.

Body:
I have used optimization modelers in the past, but it's been a while and I am still learning how to do this in python.  I have done some online research and am using the open-source version of PuLp https://pythonhosted.org/PuLP/

I have the following formulated and working for three locations.  My questions are how to formulate the problem with imported data from a CSV, since my dataset actually includes 70 locations. Typing the number of possibilities for the routes to those routes would seem foolish; I imagine there is a better way to program this.  I understand how to use csv.reader() but I am less sure of how to proceed with formulating the problem.

Example Model:

"""
Traveling Salesman Problem (TSP) Simplified Model
Date: 2017-03-30
"""

# Import PuLP modeler functions
from pulp import *

# Create the 'prob' variable to contain the problem data
prob = LpProblem("The TSP Problem1",LpMinimize)

# Formulation summary
#   The decision variable x is equal to 1 or 0, whether the path is chosen
#   Each path has a cost associated with it
#   The objective is to choose the shortest path
#   The constraint, essentially, is that each location is visited

# The LpVariable class has four parameters
    # the first is an arbitrary name
    # the second is the lower bound
    # the third is the upper bound
    # the fourth is the type of data, discrete or continuous
x12=LpVariable("flow12",0,None,LpInteger)
x13=LpVariable("flow13",0,None,LpInteger)
x21=LpVariable("flow21",0,None,LpInteger)
x23=LpVariable("flow23",0,None,LpInteger)
x31=LpVariable("flow31",0,None,LpInteger)
x32=LpVariable("flow32",0,None,LpInteger)

# The objective function is added to 'prob' first
# the objective is to minimize the total distance traveled
# the numbers represent the distances between two variables

prob += 30*x12 + 5*x13 +25*x21 + 1*x23 + 5*x31 + 8*x32, "Total Distance Traveled"

# The constraints:

# each location needs to be on the route but only once
prob += x12 + x32 == 1.0, "Location2 is visited"
prob += x13 + x23 == 1.0, "Location3 is visited"
prob += x21 + x31 == 1.0, "Location1 is visited"

# each location is departed exactly once
prob += x31 + x32 == 1.0, "Location3 is departed"
prob += x21 + x23 == 1.0, "Location2 is departed"
prob += x12 + x13 == 1.0, "Location is departed"

# The problem data is written to an .lp file
prob.writeLP("SupplyChainAssignment.lp")

# The problem is solved using PuLP's choice of Solver
prob.solve()

# The status of the solution is printed to the screen
print "Status:", LpStatus[prob.status]

# Each of the variables is printed with it's resolved optimum value
for v in prob.variables():
    print v.name, "=", v.varValue

# The optimized objective function value is printed to the screen
print "Total Cost TSP Assignment = ", value(prob.objective)

That's the end of the example which is currently working.

I am thinking that I can use dictionaries such as the following for distance:

distance = {'x12': 30,
            'x13': 5,
            'x21': 25,
            'x23': 1,
            'x31': 5,
            'x32': 8}

But I am not sure if the following would work for variables:

x = {'x12',
     'x13',
     'x21',
     'x23',
     'x31',
     'x32'}

x=LpVariable("flow",0,1,LpInteger)

And that also does not solve my question of how to rewrite the constraints using indices, so I haven't tested whether my guess on syntax above would work:

prob += x12 + x32 == 1.0, "Location2 is visited"
prob += x13 + x23 == 1.0, "Location3 is visited"
prob += x21 + x31 == 1.0, "Location1 is visited"

# each location is departed
prob += x31 + x32 == 1.0, "Location3 is departed"
prob += x21 + x23 == 1.0, "Location2 is departed"
prob += x12 + x13 == 1.0, "Location is departed"

Any suggestions on what I should read up on, or if there are any examples that you could point me to would be helpful.

Thanks!

Body:
Read a bit more of the documentation and you will see some good examples

https://pythonhosted.org/PuLP/CaseStudies/a_blending_problem.html#solution-to-full-problem

From this document you will see the following

# A dictionary called 'ingredient_vars' is created to contain the referenced Variables
ingredient_vars = LpVariable.dicts("Ingr",Ingredients,0)

Since costs and ingredient_vars are now dictionaries with the reference keys as the Ingredient names, the data can be simply extracted with a list comprehension as shown. The lpSum() function will add the elements of the resulting list. Thus the objective function is simply entered and assigned a name:

# The objective function is added to 'prob' first
prob += lpSum([costs[i]*ingredient_vars[i] for i in Ingredients]), "Total Cost of Ingredients per can"

Further list comprehensions are used to define the other 5 constraints, which are also each given names describing them.

# The five constraints are added to 'prob'
prob += lpSum([ingredient_vars[i] for i in Ingredients]) == 100, "PercentagesSum"
prob += lpSum([proteinPercent[i] * ingredient_vars[i] for i in Ingredients]) >= 8.0, "ProteinRequirement"
prob += lpSum([fatPercent[i] * ingredient_vars[i] for i in Ingredients]) >= 6.0, "FatRequirement"
prob += lpSum([fibrePercent[i] * ingredient_vars[i] for i in Ingredients]) <= 2.0, "FibreRequirement"
prob += lpSum([saltPercent[i] * ingredient_vars[i] for i in Ingredients]) <= 0.4, "SaltRequirement"

In this example you can see how to define a problem using dictionaries of variables and dictionaries of parameters.

Then you will have to use the csv module to read the parameter data (I would recommend csv.DictReader to do this)

You are right however, it would be nice to have a specific example in the documentation.


来源: stackexchange

问:
SQL Join 2 tables
I have two tables one named Person, which contains columns ID and Name and the second one, named Relation, which contains two columns, each of which contains an ID of a Person. It's about a relation between customer and serviceman. I'd like to Join these two tables so that I'll have names of people in every relation. Is it possible to write this query with some kind of joining?

EDIT::

I must do something wrong, but it's not working. I had tried a lot of forms of so looking queries, but I had been only getting one column or some errors. It's actually the school task, I have it already done (with different JOIN query). Firstly I had been trying to do this, but I'd failed: It seems to be very common situation, so I don't know why it's too complicated for me..

Here are my tables:

```<code>CREATE TABLE Oprava..(Repair) (
  KodPodvozku INTEGER PRIMARY KEY REFERENCES Automobil(KodPodvozku),
  IDzakaznika..(IDcustomer) INTEGER REFERENCES Osoba(ID),
  IDzamestnance..(IDemployee) INTEGER REFERENCES Osoba(ID)
);

CREATE TABLE Osoba..(Person) (
  ID INTEGER CONSTRAINT primaryKeyOsoba PRIMARY KEY ,
  Jmeno..(Name) VARCHAR(256) NOT NULL,
  OP INTEGER UNIQUE NOT NULL
);
</code>```

It's in Czech, but the words in brackets after ".." are english equivalents.
PS: I am using Oracle SQL.

答:
Assuming your tables are:

```<code>persons:   (id, name)
relations: (customer_id, serviceman_id)
</code>```

Using standard SQL:

```<code>SELECT p1.name AS customer_name,
       p2.name AS serviceman_name
FROM persons p1
     JOIN relations ON p1.id=relations.customer_id
     JOIN persons p2 ON relations.serviceman_d=p2.id;
</code>```

Further explanation

The join creates the following table:

```<code>p1.id|p1.name|relations.customer_id|relations.serviceman_id|p2.id|p2.name
</code>```

Where p1.id=relations.customer_id, and p2.id=relations.serviceman_id. The SELECT clause chooses only the names from the JOIN.

Note that if all the ids from relations are also in persons, the result size would be exactly the size of the relations table. You might want to add a foreign key to verify that.

ContentLicense: CC BY-SA 3.0

Title: SQL Join 2 tables

Body:
I have two tables one named Person, which contains columns ID and Name and the second one, named Relation, which contains two columns, each of which contains an ID of a Person. It's about a relation between customer and serviceman. I'd like to Join these two tables so that I'll have names of people in every relation. Is it possible to write this query with some kind of joining?

EDIT::

I must do something wrong, but it's not working. I had tried a lot of forms of so looking queries, but I had been only getting one column or some errors. It's actually the school task, I have it already done (with different JOIN query). Firstly I had been trying to do this, but I'd failed: It seems to be very common situation, so I don't know why it's too complicated for me..

Here are my tables:

CREATE TABLE Oprava..(Repair) (
  KodPodvozku INTEGER PRIMARY KEY REFERENCES Automobil(KodPodvozku),
  IDzakaznika..(IDcustomer) INTEGER REFERENCES Osoba(ID),
  IDzamestnance..(IDemployee) INTEGER REFERENCES Osoba(ID)
);

CREATE TABLE Osoba..(Person) (
  ID INTEGER CONSTRAINT primaryKeyOsoba PRIMARY KEY ,
  Jmeno..(Name) VARCHAR(256) NOT NULL,
  OP INTEGER UNIQUE NOT NULL
);

It's in Czech, but the words in brackets after ".." are english equivalents.
PS: I am using Oracle SQL.

Body:
Assuming your tables are:

persons:   (id, name)
relations: (customer_id, serviceman_id)

Using standard SQL:

SELECT p1.name AS customer_name,
       p2.name AS serviceman_name
FROM persons p1
     JOIN relations ON p1.id=relations.customer_id
     JOIN persons p2 ON relations.serviceman_d=p2.id;

Further explanation

The join creates the following table:

p1.id|p1.name|relations.customer_id|relations.serviceman_id|p2.id|p2.name

Where p1.id=relations.customer_id, and p2.id=relations.serviceman_id. The SELECT clause chooses only the names from the JOIN.

Note that if all the ids from relations are also in persons, the result size would be exactly the size of the relations table. You might want to add a foreign key to verify that.

ContentLicense: CC BY-SA 2.5


问:
how to write a single sql query based on combobox selection?
I have a winform in which user input values through a combobox. I am assigning combobox value to search db. If there is no selection then the SQL server query should not use that column to filter.

example -

```<code>if (string.IsNullOrEmpty(combobox1.text)) {
  .....Select * from country
}
else if (combobox1.selectedindex > -1) {
   ....Select * from country where city_name = combobox.text
}
</code>```

Is there a way to write a single query instead of using this multiple 'IF' conditions in case where user selects or doesn't select a value from combobox.

答:
I have a sample, try it</p>

```<code>string select = this.combobox1.GetItemText(this.combobox1.SelectedItem); cm1 = new SqlCommand("Select * from country where city_name=@select or @select is null", con);
            cm1.Parameters.Add("@select", SqlDbType.NVarChar, 50);
            cm1.Parameters["@select"].Value = select;
            dap = new SqlDataAdapter(cm1);
            ds = new System.Data.DataSet();
            dap.Fill(ds, "DATABASE");
            //DataGridView1.DataSource = ds.Tables[0]; get data
</code>```

Body:
I have a winform in which user input values through a combobox. I am assigning combobox value to search db. If there is no selection then the SQL server query should not use that column to filter.

example -

if (string.IsNullOrEmpty(combobox1.text)) {
  .....Select * from country
}
else if (combobox1.selectedindex > -1) {
   ....Select * from country where city_name = combobox.text
}

Is there a way to write a single query instead of using this multiple 'IF' conditions in case where user selects or doesn't select a value from combobox.

Body:
I have a sample, try it

string select = this.combobox1.GetItemText(this.combobox1.SelectedItem); cm1 = new SqlCommand("Select * from country where city_name=@select or @select is null", con);
            cm1.Parameters.Add("@select", SqlDbType.NVarChar, 50);
            cm1.Parameters["@select"].Value = select;
            dap = new SqlDataAdapter(cm1);
            ds = new System.Data.DataSet();
            dap.Fill(ds, "DATABASE");
            //DataGridView1.DataSource = ds.Tables[0]; get data


问:
UnknownHostException: email.us-west-1.amazonaws.com with Amazon SES
Writing a trivial Spring Boot app that uses Amazon Simple Email Service (SES). The sending fails with an UnknownHostException regarding the us-west-1 endpoint.

```<code>Caused by: java.net.UnknownHostException: email.us-west-1.amazonaws.com
at java.net.InetAddress.getAllByName0(InetAddress.java:1280)
at java.net.InetAddress.getAllByName(InetAddress.java:1192)
at java.net.InetAddress.getAllByName(InetAddress.java:1126)
at com.amazonaws.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:27)
at com.amazonaws.http.DelegatingDnsResolver.resolve(DelegatingDnsResolver.java:38)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:112)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:359)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.amazonaws.http.conn.ClientConnectionManagerFactory$Handler.invoke(ClientConnectionManagerFactory.java:76)
at com.amazonaws.http.conn.$Proxy49.connect(Unknown Source)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at com.amazonaws.http.apache.client.impl.SdkHttpClient.execute(SdkHttpClient.java:72)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1181)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1030)
... 93 more
</code>```

Any ideas?

答: Well, according to here, it seems that SES is not available in us-west-1 anymore! Can't ping the endpoint as expected.</p>

Body:
Writing a trivial Spring Boot app that uses Amazon Simple Email Service (SES). The sending fails with an UnknownHostException regarding the us-west-1 endpoint.

Caused by: java.net.UnknownHostException: email.us-west-1.amazonaws.com
at java.net.InetAddress.getAllByName0(InetAddress.java:1280)
at java.net.InetAddress.getAllByName(InetAddress.java:1192)
at java.net.InetAddress.getAllByName(InetAddress.java:1126)
at com.amazonaws.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:27)
at com.amazonaws.http.DelegatingDnsResolver.resolve(DelegatingDnsResolver.java:38)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:112)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:359)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.amazonaws.http.conn.ClientConnectionManagerFactory$Handler.invoke(ClientConnectionManagerFactory.java:76)
at com.amazonaws.http.conn.$Proxy49.connect(Unknown Source)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at com.amazonaws.http.apache.client.impl.SdkHttpClient.execute(SdkHttpClient.java:72)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1181)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1030)
... 93 more

Any ideas?


问:
Button that have a time set to be shown and to be hidden
Need some help here...How can I create a Button that will visible when the time in my device is 6:00am-8:59am...and when the time is 9:00am the button will gone. any help please, I'm just newBie learning new things in android. Thank you!</p>

答:
You can use java.util.Calendar

```<code>    Calendar SIX_AM = Calendar.getInstance();
    SIX_AM.set(Calendar.HOUR_OF_DAY,6);
    SIX_AM.set(Calendar.MINUTE,0);
    SIX_AM.set(Calendar.SECOND,0);
    Calendar NINE_AM = Calendar.getInstance();
    NINE_AM.set(Calendar.HOUR_OF_DAY,9);
    NINE_AM.set(Calendar.MINUTE,0);
    NINE_AM.set(Calendar.SECOND,0);
    Calendar SIX_PM = Calendar.getInstance();
    SIX_PM.set(Calendar.HOUR_OF_DAY,18);
    SIX_PM.set(Calendar.MINUTE,0);
    SIX_PM.set(Calendar.SECOND,0);
    Calendar NINE_PM = Calendar.getInstance();
    NINE_PM.set(Calendar.HOUR_OF_DAY,21);
    NINE_PM.set(Calendar.MINUTE,0);
    NINE_PM.set(Calendar.SECOND,0);
    Calendar current = Calendar.getInstance();
    if(current.compareTo(SIX_AM)>=0 && current.compareTo(NINE_AM)<0) {
        btnAm.setVisibility(View.VISIBLE);
    } else {
        btnAm.setVisibility(View.GONE);
    }
    if(current.compareTo(SIX_PM)>=0 && current.compareTo(NINE_PM)<0) {
        btnPm.setVisibility(View.VISIBLE);
    } else {
        btnPm.setVisibility(View.GONE);
    }
</code>```

Hope that helps

Body:
You can use java.util.Calendar

    Calendar SIX_AM = Calendar.getInstance();
    SIX_AM.set(Calendar.HOUR_OF_DAY,6);
    SIX_AM.set(Calendar.MINUTE,0);
    SIX_AM.set(Calendar.SECOND,0);
    Calendar NINE_AM = Calendar.getInstance();
    NINE_AM.set(Calendar.HOUR_OF_DAY,9);
    NINE_AM.set(Calendar.MINUTE,0);
    NINE_AM.set(Calendar.SECOND,0);
    Calendar SIX_PM = Calendar.getInstance();
    SIX_PM.set(Calendar.HOUR_OF_DAY,18);
    SIX_PM.set(Calendar.MINUTE,0);
    SIX_PM.set(Calendar.SECOND,0);
    Calendar NINE_PM = Calendar.getInstance();
    NINE_PM.set(Calendar.HOUR_OF_DAY,21);
    NINE_PM.set(Calendar.MINUTE,0);
    NINE_PM.set(Calendar.SECOND,0);
    Calendar current = Calendar.getInstance();
    if(current.compareTo(SIX_AM)>=0 && current.compareTo(NINE_AM)<0) {
        btnAm.setVisibility(View.VISIBLE);
    } else {
        btnAm.setVisibility(View.GONE);
    }
    if(current.compareTo(SIX_PM)>=0 && current.compareTo(NINE_PM)<0) {
        btnPm.setVisibility(View.VISIBLE);
    } else {
        btnPm.setVisibility(View.GONE);
    }

Hope that helps


问:
Does the order of fields in C# matter?
This question is inspired by Jon Skeet's answer:
Is there a c# equivalent to c++'s access-modifier regions

He makes a comment that it is possible for the order of fields in a file to matter. I am guessing that this has to do with the order that the fields are initialized, but I think it's a dangerous enough thing to code based on this side effect that it warranted its own question and discussion.

Are there other thoughts around how the order of fields within your code file could be manipulated and what impact that might have?

答:
You can use (abuse?) the order of fields as metadata of your class which you can than read via reflection.

for example, if you have a class that represents a network protocol with fields ID, PORT, and XOR, in that order, you could define it as:

```<code>class MyProtocol {
    int ID;
    int PORT;
    int XOR;
}
</code>```

Now suppose you use reflection to iterate the fields of the protocol, to send over the wire. The order returned by GetProperties will be as you defined, and you didn't have to write any extra metadata explicitly.

Not sure if it's a good idea though to depend on this.

OwnerDisplayName: Josh

Title: Does the order of fields in C# matter?

LastEditorDisplayName: Mehrdad Afshari

Body:
You can use (abuse?) the order of fields as metadata of your class which you can than read via reflection.

for example, if you have a class that represents a network protocol with fields ID, PORT, and XOR, in that order, you could define it as:

class MyProtocol {
    int ID;
    int PORT;
    int XOR;
}

Now suppose you use reflection to iterate the fields of the protocol, to send over the wire. The order returned by GetProperties will be as you defined, and you didn't have to write any extra metadata explicitly.

Not sure if it's a good idea though to depend on this.

OwnerDisplayName: Roy Peled


问:
Event handlers for Twitter Bootstrap dropdowns?
I'd like to use a Twitter Bootstrap dropdown button:

```<code>    <div class="btn-group">
      <button class="btn dropdown-toggle" data-toggle="dropdown">Action <span class="caret"></span></button>
      <ul class="dropdown-menu">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
      </ul>
    </div><!-- /btn-group -->
</code>```

When the user changes the value of the button to 'Another action', instead of simply navigating to #, I'd actually like to handle the action in a custom way.

But I can't see any event handlers in the dropdown plugin for doing this.

Is it actually possible to use Bootstrap dropdown buttons to handle user actions? I'm starting to wonder if they're only intended for navigation - it's confusing that the example gives a list of actions.

答:
Without having to change your button group at all, you can do the following. Below, I assume your dropdown button has an id of fldCategory.

```<code><script type="text/javascript">

$(document).ready(function(){

  $('#fldCategory').parent().find('UL LI A').click(function (e) {
    var sVal = e.currentTarget.text;
    $('#fldCategory').html(sVal + ' <span class="caret"></span>');
    console.log(sVal);
  });

});

</script>
</code>```

Now, if you set the .btn-group of this item itself to have the id of fldCategory, that's actually more efficient jQuery and runs a little faster:

```<code><script type="text/javascript">

$(document).ready(function(){

  $('#fldCategory UL LI A').click(function (e) {
    var sVal = e.currentTarget.text;
    $('#fldCategory BUTTON').html(sVal + ' <span class="caret"></span>');
    console.log(sVal);
  });

});

</script>
</code>```

Body:
I'd like to use a Twitter Bootstrap dropdown button:

      <button class="btn dropdown-toggle" data-toggle="dropdown">Action </button>

Action

Another action

Something else here

When the user changes the value of the button to 'Another action', instead of simply navigating to #, I'd actually like to handle the action in a custom way.

But I can't see any event handlers in the dropdown plugin for doing this.

Is it actually possible to use Bootstrap dropdown buttons to handle user actions? I'm starting to wonder if they're only intended for navigation - it's confusing that the example gives a list of actions.

Body:
Without having to change your button group at all, you can do the following. Below, I assume your dropdown button has an id of fldCategory.

<script type="text/javascript">

$(document).ready(function(){

  $('#fldCategory').parent().find('UL LI A').click(function (e) {
    var sVal = e.currentTarget.text;
    $('#fldCategory').html(sVal + ' <span class="caret"></span>');
    console.log(sVal);
  });

});

</script>

Now, if you set the .btn-group of this item itself to have the id of fldCategory, that's actually more efficient jQuery and runs a little faster:

<script type="text/javascript">

$(document).ready(function(){

  $('#fldCategory UL LI A').click(function (e) {
    var sVal = e.currentTarget.text;
    $('#fldCategory BUTTON').html(sVal + ' <span class="caret"></span>');
    console.log(sVal);
  });

});

</script>


问:
Count how many UL have so many LI elements in jQuery
I have various UL and I need to know about all existing UL, how many UL have two LI, what I'm trying to do with a each, this will be the right way.

$(function(){

 var count = '';
 var total = 1;

 $('ul li').each(function(index, el) {
   count++;
   if(count == 12) {
    total + 1;
   }

   count = '';
  });

    console.log('We found 2 UL with 2 li');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
 <li>Item</li>
  <li>Item</li>
</ul>

<ul>
 <li>Item</li>
 <li>Item</li>
</ul></code>```

The this code, result: We found 2 UL with 2 li.

答:
$(function() {

  $('ul').filter(function() {

    return $(this).children('li').length == 2
  }).css("background-color", "red")

  console.log('We found 2 UL with 2 li');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Item</li>
</ul>

<ul>
  <li>Item</li>
</ul>

<ul>
  <li>Item</li>
  <li>Item</li>
</ul>

<ul>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ul>

<ul>
  <li>Item</li>
  <li>Item</li>
</ul></code>```

You can use filter then return the ul with li length == 2

ContentLicense: CC BY-SA 4.0

Body:
I have various UL and I need to know about all existing UL, how many UL have two LI, what I'm trying to do with a each, this will be the right way.

$(function(){

 var count = '';
 var total = 1;

 $('ul li').each(function(index, el) {
   count++;
   if(count == 12) {
    total + 1;
   }

   count = '';
  });

    console.log('We found 2 UL with 2 li');
});

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

The this code, result: We found 2 UL with 2 li.

Body:
$(function() {

  $('ul').filter(function() {

    return $(this).children('li').length == 2
  }).css("background-color", "red")

  console.log('We found 2 UL with 2 li');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Item</li>
</ul>

<ul>
  <li>Item</li>
</ul>

<ul>
  <li>Item</li>
  <li>Item</li>
</ul>

<ul>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ul>

<ul>
  <li>Item</li>
  <li>Item</li>
</ul>

You can use filter then return the ul with li length == 2


问:
Draw a plot and show points on Python
I am using Python to draw a 2-axis plot.

X-axis is 'Q'(integer); Y-axis is 'Z(Q)', a function of 'Q'.

I would like Q to be integer from 0, 1, 2, ..., 10 for example. And I have Z(Q) already defined and it runs okay.

I want to see the plot of Z(Q) versus Q with each point (0, 1, 2, ..., 10) on the plot.

Can I write:

```<code>for Q in range(0, 10):
   pl.plot(Q,Z(Q))
</code>```

And it returns error.

Error Message:

name 'Q' is not defined.

How could I change the code in defining Q?

Thank you!

Appendix - Entire Code:

```<code>import numpy as np
import scipy.stats as stats
from scipy.stats import poisson, norm

mu = 4.68
cs = 100
co = 300
G = poisson(mu)
p = G.pmf(np.arange(3*mu))

def Z(Q):
    ES = sum(i*p[i] for i in range(len(p)))
    return co*max((Q-ES), 0) + cs*max((ES-Q), 0)

Qstar = np.ceil(poisson.ppf(co/(cs+co), mu))
print(Qstar)

from scipy.integrate import quad
import pylab as pl

for Q in range(0, Qstar):
    pl.plot(Q,Z(Q))
</code>```

And this is my full code, the last two lines do not return any result, the rest is fine. Thank you!

答:
The problem is the numpy data conversion, this can not be used in the range () function, I have corrected the code considering the above.

```<code>import numpy as np
import scipy.stats as stats
from scipy.stats import poisson, norm

mu = 4.68
cs = 100
co = 300
G = poisson(mu)
p = G.pmf(np.arange(3*mu))

def Z(Q):
    ES = sum(i*p[i] for i in range(len(p)))
    return co*max((Q-ES), 0) + cs*max((ES-Q), 0)

Qstar = np.ceil(poisson.ppf(co/(cs+co), mu))
print(Qstar)

Qstar = int(np.float64(Qstar).item())

from scipy.integrate import quad
import pylab as pl

for Q in range(0, Qstar):
    pl.plot(Q,Z(Q), '*')

pl.show()
</code>```

Lines:

```<code>import numpy as np
import scipy.stats as stats
from scipy.stats import poisson, norm

mu = 4.68
cs = 100
co = 300
G = poisson(mu)
p = G.pmf(np.arange(3*mu))

def Z(Q):
    ES = sum(i*p[i] for i in range(len(p)))
    return co*max((Q-ES), 0) + cs*max((ES-Q), 0)

Qstar = np.ceil(poisson.ppf(co/(cs+co), mu))
print(Qstar)

Qstar = int(np.float64(Qstar).item())

from scipy.integrate import quad
import pylab as pl

x = []

y = []

for Q in range(0, Qstar):
    x.append(Q)
    y.append(Z(Q))

pl.plot(x, y)

pl.show()
</code>```

Title: Draw a plot and show points on Python

Body:
I am using Python to draw a 2-axis plot.

X-axis is 'Q'(integer); Y-axis is 'Z(Q)', a function of 'Q'.

I would like Q to be integer from 0, 1, 2, ..., 10 for example. And I have Z(Q) already defined and it runs okay.

I want to see the plot of Z(Q) versus Q with each point (0, 1, 2, ..., 10) on the plot.

Can I write:

for Q in range(0, 10):
   pl.plot(Q,Z(Q))

And it returns error.

Error Message:

name 'Q' is not defined.

How could I change the code in defining Q?

Thank you!

Appendix - Entire Code:

import numpy as np
import scipy.stats as stats
from scipy.stats import poisson, norm

mu = 4.68
cs = 100
co = 300
G = poisson(mu)
p = G.pmf(np.arange(3*mu))

def Z(Q):
    ES = sum(i*p[i] for i in range(len(p)))
    return co*max((Q-ES), 0) + cs*max((ES-Q), 0)

Qstar = np.ceil(poisson.ppf(co/(cs+co), mu))
print(Qstar)

from scipy.integrate import quad
import pylab as pl

for Q in range(0, Qstar):
    pl.plot(Q,Z(Q))

And this is my full code, the last two lines do not return any result, the rest is fine. Thank you!

Body:
The problem is the numpy data conversion, this can not be used in the range () function, I have corrected the code considering the above.

import numpy as np
import scipy.stats as stats
from scipy.stats import poisson, norm

mu = 4.68
cs = 100
co = 300
G = poisson(mu)
p = G.pmf(np.arange(3*mu))

def Z(Q):
    ES = sum(i*p[i] for i in range(len(p)))
    return co*max((Q-ES), 0) + cs*max((ES-Q), 0)

Qstar = np.ceil(poisson.ppf(co/(cs+co), mu))
print(Qstar)

Qstar = int(np.float64(Qstar).item())

from scipy.integrate import quad
import pylab as pl

for Q in range(0, Qstar):
    pl.plot(Q,Z(Q), '*')

pl.show()

Lines:

import numpy as np
import scipy.stats as stats
from scipy.stats import poisson, norm

mu = 4.68
cs = 100
co = 300
G = poisson(mu)
p = G.pmf(np.arange(3*mu))

def Z(Q):
    ES = sum(i*p[i] for i in range(len(p)))
    return co*max((Q-ES), 0) + cs*max((ES-Q), 0)

Qstar = np.ceil(poisson.ppf(co/(cs+co), mu))
print(Qstar)

Qstar = int(np.float64(Qstar).item())

from scipy.integrate import quad
import pylab as pl

x = []

y = []

for Q in range(0, Qstar):
    x.append(Q)
    y.append(Z(Q))

pl.plot(x, y)

pl.show()


问:
error browser prevent my form - click submit button in ajax's success
I have a problem about browser block my submit form (submit in new tab) when i click submit button in ajax's success.

First: i used ajax to get my text translate into chinese and put the result to text field of this form. In Ajax's success function, i put $("my submit button").click(). then my form is not submit because browser block it :

Here is my form:

```<code>  <?php
    $catnews = CatNews::model()->findAll();
    echo CHtml::beginForm(['site/timkiemtaobao'], 'post', ['target' => '_blank']) . CHtml::textField('txtkeyword', '', ['placeholder' => 'Nhập theo sản phẩm, danh mục, hay nhãn hiệu tìm kiếm', 'class' => 'xx'])
        . CHtml::link('<img src="images/source/search.png">', 'javascript:void(0)', ['class' => 'btntim', 'id' => 'btntimkiem'])
        . CHtml::dropDownList('search', '', CHtml::listData($catnews, 'id', 'name'), ['class' => 'searchdrop']) ?>
    <div class="clearfix"></div>
    <?php echo CHtml::textField('stringtimkiem', "", ['class' => 'hidden']) . CHtml::button('1', ['class' => 'hidden', 'id' => 'subbtn']) . CHtml::endForm(); ?>
</code>```

And here is my js:

```<code>$(document).on('click', '#btntimkiem', function() { // this for translate to chinese
  if ($("#txtkeyword").val() != '') {
    var c = $("#txtkeyword").val();
    $.ajax({
      url: "https://translate.yandex.net/api/v1.5/tr.json/translate?key=myapikey",
      type: 'get',
      dataType: 'json',
      async: false,
      data: {
        text: c,
        lang: "vi-zh"
      },
      beforeSend: function() {
        $("#txtkeyword").attr('disabled', 'disabled');
        $("#btntimkiem").attr('disabled', 'disabled');
      },
      success: function(data) {
        console.log(data.text[0]);
        $("#stringtimkiem").val(data.text[0]);
        $("#subbtn").attr('type', 'submit').click().removeAttr('type');

      }
    });
    $("#txtkeyword").removeAttr('disabled');
    $("#btntimkiem").removeAttr('disabled');
  }
});
</code>```

So i'm very tired, because i have tried to fix it for 2 days but nothing is fixed.
i looking forward to your help. thank so much.

答:
I expect that neither your handler nor your ajax is even being executed and the form is executing as a normal form. You can check this by adding in a console.log statement and checking for network activity in the browser's developer tools.

You need to give the form an id, something like:

```<code>CHtml::beginForm(['site/timkiemtaobao'], 'post', ['id' => 'btntimkiem'])
</code>```

Body:
I have a problem about browser block my submit form (submit in new tab) when i click submit button in ajax's success.

First: i used ajax to get my text translate into chinese and put the result to text field of this form. In Ajax's success function, i put $("my submit button").click(). then my form is not submit because browser block it :

Here is my form:

  <?php
    $catnews = CatNews::model()->findAll();
    echo CHtml::beginForm(['site/timkiemtaobao'], 'post', ['target' => '_blank']) . CHtml::textField('txtkeyword', '', ['placeholder' => 'Nhập theo sản phẩm, danh mục, hay nhãn hiệu tìm kiếm', 'class' => 'xx'])
        . CHtml::link('', 'javascript:void(0)', ['class' => 'btntim', 'id' => 'btntimkiem'])
        . CHtml::dropDownList('search', '', CHtml::listData($catnews, 'id', 'name'), ['class' => 'searchdrop']) ?>

    <?php echo CHtml::textField('stringtimkiem', "", ['class' => 'hidden']) . CHtml::button('1', ['class' => 'hidden', 'id' => 'subbtn']) . CHtml::endForm(); ?>

And here is my js:

$(document).on('click', '#btntimkiem', function() { // this for translate to chinese
  if ($("#txtkeyword").val() != '') {
    var c = $("#txtkeyword").val();
    $.ajax({
      url: "https://translate.yandex.net/api/v1.5/tr.json/translate?key=myapikey",
      type: 'get',
      dataType: 'json',
      async: false,
      data: {
        text: c,
        lang: "vi-zh"
      },
      beforeSend: function() {
        $("#txtkeyword").attr('disabled', 'disabled');
        $("#btntimkiem").attr('disabled', 'disabled');
      },
      success: function(data) {
        console.log(data.text[0]);
        $("#stringtimkiem").val(data.text[0]);
        $("#subbtn").attr('type', 'submit').click().removeAttr('type');

      }
    });
    $("#txtkeyword").removeAttr('disabled');
    $("#btntimkiem").removeAttr('disabled');
  }
});

So i'm very tired, because i have tried to fix it for 2 days but nothing is fixed.
i looking forward to your help. thank so much.

Body:
I expect that neither your handler nor your ajax is even being executed and the form is executing as a normal form. You can check this by adding in a console.log statement and checking for network activity in the browser's developer tools.

You need to give the form an id, something like:

CHtml::beginForm(['site/timkiemtaobao'], 'post', ['id' => 'btntimkiem'])


问:
Comparing two drawables in android
How to compare two drawables, I am doing like this but not having any success</p>

```<code>public void MyClick(View view)
{
 Drawable fDraw = view.getBackground();
 Drawable sDraw = getResources().getDrawable(R.drawable.twt_hover);

  if(fDraw.equals(sDraw))
  {
   //Not coming
  }
}
</code>```

答:
getDrawable(int) is Now Deprecated. Use  getDrawable(context,R.drawable.yourimageid)

To Compare Two Backgrounds

```<code>Boolean Condition1=v.getBackground().getConstantState().equals(
ContextCompat.getDrawable(getApplicationContext(),R.drawable.***).getConstantState());
</code>```

Title: Comparing two drawables in android

Body:
How to compare two drawables, I am doing like this but not having any success

public void MyClick(View view)
{
 Drawable fDraw = view.getBackground();
 Drawable sDraw = getResources().getDrawable(R.drawable.twt_hover);

  if(fDraw.equals(sDraw))
  {
   //Not coming
  }
}

Body:
getDrawable(int) is Now Deprecated. Use  getDrawable(context,R.drawable.yourimageid)

To Compare Two Backgrounds

Boolean Condition1=v.getBackground().getConstantState().equals(
ContextCompat.getDrawable(getApplicationContext(),R.drawable.***).getConstantState());


问:
Django - download file without reloading the page
The flow looks like that:

user is filling the form

form is passed to the server by ajax

form is saved to db, then the pdf with the form data is created and saved in the app folder (probably a bad move here...)

ajax success causes the page to append a button 'Download' with value equal to current pdf's name so button 'Download' appears to the user

If user presses the button the very pdf that was just saved is gonna download.

Refreshing the page makes the button disappear.

I've got stuck on point 5. I have created another ajax (to avoid reloading the page) bound to the Download button. It correctly asks the server to look for the file, creates a django File object: pdf_file = File(open(file_path, 'rb'))
and creates a HttpResponse with file, and content_type='application/pdf' or 'application/download'.
response['Content-Disposition'] is attachment.

Then the ajax returns response - only it does not. Server raises no error but ajax error function is called.

I've read that downloading with ajax is not possible. Could you help me a bit to get it straight? If above snippets are not clear, I shall provide more code.
Python 3.5, Django 1.10

答:
Instead of using ajax to download the file bind the button to a download link where the file may be hosted

https://www.mywebsite/download/?fileid=3247023

You should at least seperate your file in a media root
Note: in production you will have to use a cdn to host your static files


问:
Linux: how to program to monitor process existing/quiting?
SIGCHLD can only be caught by father process to monitor if child process exits. But I wish to write a stand-alone program to monitor some processes, if they quit, report a log immediately.

Is there any programming ways that I can use, rather than using a shell "ps" command to monitor process name/id, and then query in a dead loop?

答:
You can monitor process activity through proc pseudo-filesystem usually mounted at /proc. For reference use:
https://www.kernel.org/doc/Documentation/filesystems/proc.txt</p>


问:
Auto adjust div heights with jquery
I am not much of a javascript person so I am a little lost if what I have done is ok.

I have 3 columns of divs that contain dynamic content and differing numbers of child divs.

I wish to dynamically resize the height so they are all the same height as the tallest column and any difference is distributed evenly amongst the divs in each shorter column. Here is an image of what I mean:

I have hacked together some very ugly js that seems to work... but looks horrible. Is there a better way to do this that someone can suggest? It also seems a little sluggish on load, is there a way to make it faster?

```<code>   myHeightTest = function(container){
    var listOFHeights = new Array(),
        tallestContainer = 0;
    $(container).each(function(){
      listOFHeights.push($(this).height());
    });

    //Get the tallest
    tallestContainer = Math.max.apply(null,listOFHeights);

    //check I can calculate the hieght
    console.log('tallest: ' + tallestContainer);

    adjustChildHeights = function(parent,height) {
      var countKids = 0;
      $(parent.children('.flex-item')).each(function(){
        countKids += 1;
      });
      var offset = (height/countKids);
      $(parent.children('.flex-item')).each(function(){
        $(this).css('min-height',$(this).height() + offset);
      });
    }
    //now loop through and adjust
    $(container).each(function(){
      adjustChildHeights($(this),(tallestContainer - $(this).height()));
    });

  }

    $(window).load(function() {
  myHeightTest('.myflex-col');
    });

    $(window).resize(function(){
  myHeightTest('.myflex-col');
    });
</code>```

答:
Unless I am misunderstanding your question I think you can easily accomplish this with just CSS using flexbox, no need for any fancy javascript here. Here is an example (I haven't done any padding or margins so it's a bit ugly but I think it'll give you the idea.

```<code><div id="outside">
    <div class="column">
        <div class="child">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin dignissim iaculis orci eget malesuada. Quisque auctor orci ipsum, in ornare felis volutpat ut. Integer nec laoreet ex. Sed nec feugiat erat. Vestibulum vel suscipit dui. Aenean ultricies feugiat pulvinar. Donec eu luctus lorem. Integer dapibus dolor nibh, nec aliquet velit dapibus a. Nulla accumsan, sapien eu scelerisque convallis, ligula est lobortis libero, at tincidunt justo ligula maximus elit.</p>
        </div>
        <div class="child">
            <p>Sed aliquam est hendrerit mattis vestibulum. Aliquam consectetur, sapien ut placerat ullamcorper, risus orci malesuada dolor, eu consequat eros arcu a risus. Ut congue condimentum nisi nec dignissim. Sed laoreet purus orci, sit amet vestibulum metus tempus quis. Vestibulum facilisis nibh nisl. Aenean semper pharetra sem eu ultricies. Curabitur ut velit tortor. Aliquam vel metus consectetur ante suscipit rutrum. Duis volutpat hendrerit augue, vitae pretium orci laoreet vel.</p>
        </div>
        <div class="child">
           <p>In varius dapibus felis, placerat ultricies diam condimentum id. Phasellus lobortis purus tellus, at faucibus mauris varius vitae. Vestibulum vitae lectus lectus. Praesent ut diam vitae odio tincidunt porttitor sagittis sed ipsum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Integer scelerisque scelerisque tincidunt. Curabitur et magna pulvinar, auctor est eget, semper nisl.</p>
        </div>
    </div>
    <div class="column">
        <div class="child">
            <p>Pellentesque et euismod mi. Nulla id ipsum convallis lacus eleifend vehicula quis id velit. In quis tempus sem, at vulputate nisi. Aenean sit amet tempor massa. Nunc et pulvinar mauris. Nunc pellentesque leo eget massa auctor tempor. Fusce nibh magna, iaculis at massa vel, consequat sagittis nisi.
        </div>
        <div class="child">
            <p>Curabitur nec placerat ligula, sed vehicula urna. Aliquam eget convallis lacus. Aenean et lacus eu ligula mollis ornare. Proin sit amet dolor eu dolor suscipit malesuada id sed urna. Integer quam ligula, semper ac elementum a, sollicitudin non turpis. Donec varius ullamcorper lacinia. Donec placerat rutrum nulla quis porta. Aenean auctor, lorem nec elementum semper, odio leo congue enim, lobortis molestie turpis dui quis leo. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec nibh ante, ornare ac sapien nec, aliquet sagittis diam. Proin id pellentesque ipsum. Aenean sollicitudin condimentum metus, quis pellentesque mauris vehicula vitae. In non venenatis nulla, eget consequat arcu.</p>
        </div>
    </div>
    <div class="column">
        <div class="child">
            <p>Etiam libero magna, imperdiet sit amet tincidunt eget, tristique a mi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi aliquet purus id sagittis vulputate. Phasellus dignissim egestas augue aliquet venenatis. Duis condimentum massa odio, at congue purus suscipit eget. Ut sit amet neque eget felis pretium tempus. Fusce imperdiet, ipsum quis ultrices sagittis, lorem diam mollis nisi, eget tempus nisi eros at ligula. In hac habitasse platea dictumst. Nulla iaculis sed arcu hendrerit elementum. Aenean vel mi ut sapien posuere vulputate at ut tellus. Nunc convallis, justo et placerat dictum, libero eros scelerisque dolor, eu lacinia metus magna eu tellus.</p>
        </div>
        <div class="child">
            <p>Smaller one for testing</p>
        </div>
        <div class="child"></div>
        <div class="child">
            <p>other small one</p>
        </div>
        <div class="child">
            <p>Here is something that I wrote that is not horribly long but still ong enough so you get the picture I image</p>
        </div>
    </div>
</div>
</code>```

And the CSS:

```<code>#outside {
    display: flex;
}
.column {
    display:flex;
    flex-direction: column;

}
.child {
    background-color: aqua;
    flex-grow: 1;
}
</code>```

Make the surrounding container for the columns display:flex and also make each column a column flex. Then by setting the column items to flex-grow: 1 The will all end up taking up the whole column.

If you really needed to do this using javascript you should just be able to add this CSS to the DOM elements.

Title: Auto adjust div heights with jquery

Body:
I am not much of a javascript person so I am a little lost if what I have done is ok.

I have 3 columns of divs that contain dynamic content and differing numbers of child divs.

I wish to dynamically resize the height so they are all the same height as the tallest column and any difference is distributed evenly amongst the divs in each shorter column. Here is an image of what I mean:

I have hacked together some very ugly js that seems to work... but looks horrible. Is there a better way to do this that someone can suggest? It also seems a little sluggish on load, is there a way to make it faster?

   myHeightTest = function(container){
    var listOFHeights = new Array(),
        tallestContainer = 0;
    $(container).each(function(){
      listOFHeights.push($(this).height());
    });

    //Get the tallest
    tallestContainer = Math.max.apply(null,listOFHeights);

    //check I can calculate the hieght
    console.log('tallest: ' + tallestContainer);

    adjustChildHeights = function(parent,height) {
      var countKids = 0;
      $(parent.children('.flex-item')).each(function(){
        countKids += 1;
      });
      var offset = (height/countKids);
      $(parent.children('.flex-item')).each(function(){
        $(this).css('min-height',$(this).height() + offset);
      });
    }
    //now loop through and adjust
    $(container).each(function(){
      adjustChildHeights($(this),(tallestContainer - $(this).height()));
    });

  }

    $(window).load(function() {
  myHeightTest('.myflex-col');
    });

    $(window).resize(function(){
  myHeightTest('.myflex-col');
    });

Body:
Unless I am misunderstanding your question I think you can easily accomplish this with just CSS using flexbox, no need for any fancy javascript here. Here is an example (I haven't done any padding or margins so it's a bit ugly but I think it'll give you the idea.

<div id="outside">
    <div class="column">
        <div class="child">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin dignissim iaculis orci eget malesuada. Quisque auctor orci ipsum, in ornare felis volutpat ut. Integer nec laoreet ex. Sed nec feugiat erat. Vestibulum vel suscipit dui. Aenean ultricies feugiat pulvinar. Donec eu luctus lorem. Integer dapibus dolor nibh, nec aliquet velit dapibus a. Nulla accumsan, sapien eu scelerisque convallis, ligula est lobortis libero, at tincidunt justo ligula maximus elit.</p>
        </div>
        <div class="child">
            <p>Sed aliquam est hendrerit mattis vestibulum. Aliquam consectetur, sapien ut placerat ullamcorper, risus orci malesuada dolor, eu consequat eros arcu a risus. Ut congue condimentum nisi nec dignissim. Sed laoreet purus orci, sit amet vestibulum metus tempus quis. Vestibulum facilisis nibh nisl. Aenean semper pharetra sem eu ultricies. Curabitur ut velit tortor. Aliquam vel metus consectetur ante suscipit rutrum. Duis volutpat hendrerit augue, vitae pretium orci laoreet vel.</p>
        </div>
        <div class="child">
           <p>In varius dapibus felis, placerat ultricies diam condimentum id. Phasellus lobortis purus tellus, at faucibus mauris varius vitae. Vestibulum vitae lectus lectus. Praesent ut diam vitae odio tincidunt porttitor sagittis sed ipsum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Integer scelerisque scelerisque tincidunt. Curabitur et magna pulvinar, auctor est eget, semper nisl.</p>
        </div>
    </div>
    <div class="column">
        <div class="child">
            <p>Pellentesque et euismod mi. Nulla id ipsum convallis lacus eleifend vehicula quis id velit. In quis tempus sem, at vulputate nisi. Aenean sit amet tempor massa. Nunc et pulvinar mauris. Nunc pellentesque leo eget massa auctor tempor. Fusce nibh magna, iaculis at massa vel, consequat sagittis nisi.
        </div>
        <div class="child">
            <p>Curabitur nec placerat ligula, sed vehicula urna. Aliquam eget convallis lacus. Aenean et lacus eu ligula mollis ornare. Proin sit amet dolor eu dolor suscipit malesuada id sed urna. Integer quam ligula, semper ac elementum a, sollicitudin non turpis. Donec varius ullamcorper lacinia. Donec placerat rutrum nulla quis porta. Aenean auctor, lorem nec elementum semper, odio leo congue enim, lobortis molestie turpis dui quis leo. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec nibh ante, ornare ac sapien nec, aliquet sagittis diam. Proin id pellentesque ipsum. Aenean sollicitudin condimentum metus, quis pellentesque mauris vehicula vitae. In non venenatis nulla, eget consequat arcu.</p>
        </div>
    </div>
    <div class="column">
        <div class="child">
            <p>Etiam libero magna, imperdiet sit amet tincidunt eget, tristique a mi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi aliquet purus id sagittis vulputate. Phasellus dignissim egestas augue aliquet venenatis. Duis condimentum massa odio, at congue purus suscipit eget. Ut sit amet neque eget felis pretium tempus. Fusce imperdiet, ipsum quis ultrices sagittis, lorem diam mollis nisi, eget tempus nisi eros at ligula. In hac habitasse platea dictumst. Nulla iaculis sed arcu hendrerit elementum. Aenean vel mi ut sapien posuere vulputate at ut tellus. Nunc convallis, justo et placerat dictum, libero eros scelerisque dolor, eu lacinia metus magna eu tellus.</p>
        </div>
        <div class="child">
            <p>Smaller one for testing</p>
        </div>
        <div class="child"></div>
        <div class="child">
            <p>other small one</p>
        </div>
        <div class="child">
            <p>Here is something that I wrote that is not horribly long but still ong enough so you get the picture I image</p>
        </div>
    </div>
</div>

And the CSS:

#outside {
    display: flex;
}
.column {
    display:flex;
    flex-direction: column;

}
.child {
    background-color: aqua;
    flex-grow: 1;
}

Make the surrounding container for the columns display:flex and also make each column a column flex. Then by setting the column items to flex-grow: 1 The will all end up taking up the whole column.

If you really needed to do this using javascript you should just be able to add this CSS to the DOM elements.


答:
In your case AlarmManager will work.
set two alarm

at 6:00 a.m. (Handle by logic it is time to show button)

at 8:59 a.m. (Handle by logic it is time to hide button)

How to start Service using Alarm Manager in Android?

for you i will suggest to use setExact instead of setRepeating. Here is the code...

```<code>AlarmManager am = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
int ALARM_TYPE = AlarmManager.RTC_WAKEUP;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    am.setExact(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);
else
    am.set(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);
</code>```

Remember setExact does not provide repeating feature so every time you have to set it from your service again...

Title: Button that have a time set to be shown and to be hidden

Body: Need some help here...How can I create a Button that will visible when the time in my device is 6:00am-8:59am...and when the time is 9:00am the button will gone. any help please, I'm just newBie learning new things in android. Thank you!

Body:
In your case AlarmManager will work.
set two alarm

at 6:00 a.m. (Handle by logic it is time to show button)

at 8:59 a.m. (Handle by logic it is time to hide button)

How to start Service using Alarm Manager in Android?

for you i will suggest to use setExact instead of setRepeating. Here is the code...

AlarmManager am = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
int ALARM_TYPE = AlarmManager.RTC_WAKEUP;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    am.setExact(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);
else
    am.set(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);

Remember setExact does not provide repeating feature so every time you have to set it from your service again...


问:
Display table-cell width percentages not obeyed
Why do the cells in the below example stretch fully collectively when it should only cover half the table width?

I've looked through numerous stackoverflow posts with similar issues, but none of their answers worked for me. And this is reflected in the below codepen example.

The reason why I'm trying to utilise table/table-cell for this is, because I will have elements, which will have variable heights. I can't have it zig-zag up and down using a float, and I don't want to set min/max-heights for the elements.

http://codepen.io/anon/pen/LWMROW

ul {
  border: 1px solid black;
  display: table;
  padding: 0;
  table-layout: fixed;
  width: 100%;
}

ul li {
  border: 1px solid black;
  display: table-cell;
  width: 25%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>This is a cell</li>
  <li>This is a cell</li>
</ul></code>```

答:
If you would like to mimick a tr/td, I believe a displaying the ul tag as flex can do the job. Also the width of the li tags can be set using css flex  property

ul {
  border: 1px solid black;
  display: table;
  padding: 0;
  table-layout: fixed;
  width: 100%;
}

ul li {
  border: 1px solid black;
  flex:0 0 25%;
  margin:0;
  border:solid red;
}
ul{
  position:relative;
  display:flex;
  list-style-type:none;
}
li{

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>This is a cell</li>
  <li>This is a cell<br><br>addsd</li>
</ul></code>```

Body:
Why do the cells in the below example stretch fully collectively when it should only cover half the table width?

I've looked through numerous stackoverflow posts with similar issues, but none of their answers worked for me. And this is reflected in the below codepen example.

The reason why I'm trying to utilise table/table-cell for this is, because I will have elements, which will have variable heights. I can't have it zig-zag up and down using a float, and I don't want to set min/max-heights for the elements.

http://codepen.io/anon/pen/LWMROW

ul {
  border: 1px solid black;
  display: table;
  padding: 0;
  table-layout: fixed;
  width: 100%;
}

ul li {
  border: 1px solid black;
  display: table-cell;
  width: 25%;
}

This is a cell

This is a cell

Body:
If you would like to mimick a tr/td, I believe a displaying the ul tag as flex can do the job. Also the width of the li tags can be set using css flex  property

ul {
  border: 1px solid black;
  display: table;
  padding: 0;
  table-layout: fixed;
  width: 100%;
}

ul li {
  border: 1px solid black;
  flex:0 0 25%;
  margin:0;
  border:solid red;
}
ul{
  position:relative;
  display:flex;
  list-style-type:none;
}
li{

}

<ul>
  <li>This is a cell</li>
  <li>This is a cell<br><br>addsd</li>
</ul>


问:
phpUnit Fatal Error
I've just started creating Unit Tests for my code again. I have had PHPUnit working in the past but today it's not playing ball. Before I created any new tests I decided to run some old ones to see if they were still valid but I get a Fatal Error from PHPUnit itself. I run PHPUnit from the CLI in Ubuntu.

```<code>phpunit TestCaseFile

PHP Deprecated:  Comments starting with '#' are deprecated in /etc/php5/cli/conf.d/imap.ini on line 1 in Unknown on line 0
PHP Warning:  Xdebug MUST be loaded as a Zend extension in Unknown on line 0

Warning: Directive 'register_long_arrays' is deprecated in PHP 5.3 and greater in Unknown on line 0

Warning: Directive 'magic_quotes_gpc' is deprecated in PHP 5.3 and greater in Unknown on line 0

Fatal error: Class 'PHPUnit_Framework_MockObject_Matcher_InvokedRecorder' not found in /usr/share/php/PHPUnit/Framework/MockObject/Matcher/InvokedAtLeastOnce.php on line 60

Call Stack:
    0.0002     651688   1. {main}() /usr/bin/phpunit:0
    0.0031    1173168   2. require('/usr/share/php/PHPUnit/TextUI/Command.php') /usr/bin/phpunit:48
    0.0046    1485456   3. require_once('/usr/share/php/PHPUnit/TextUI/TestRunner.php') /usr/share/php/PHPUnit/TextUI/Command.php:47
    0.0047    1503344   4. require_once('/usr/share/php/PHPUnit/Framework.php') /usr/share/php/PHPUnit/TextUI/TestRunner.php:47
    0.0168    3848688   5. require('/usr/share/php/PHPUnit/Framework/TestCase.php') /usr/share/php/PHPUnit/Framework.php:68
    0.0178    4091880   6. require_once('/usr/share/php/PHPUnit/Framework/MockObject/Matcher/InvokedAtLeastOnce.php') /usr/share/php/PHPUnit/Framework/TestCase.php:49
</code>```

I checked to make sure that the files exist, that the file paths etc are correct but I don't really know how to go about fixing it can anyone help?

答:
No worries people I fixed it.

It turns out that when I first installed PHPUnit I installed with APT I ran

apt-get remove phpunit

then re installed

apt-get install phpunit

Got me the latest version and all works fine. Hope this helps other people with a similar problem.

Title: phpUnit Fatal Error

Body:
I've just started creating Unit Tests for my code again. I have had PHPUnit working in the past but today it's not playing ball. Before I created any new tests I decided to run some old ones to see if they were still valid but I get a Fatal Error from PHPUnit itself. I run PHPUnit from the CLI in Ubuntu.

phpunit TestCaseFile

PHP Deprecated:  Comments starting with '#' are deprecated in /etc/php5/cli/conf.d/imap.ini on line 1 in Unknown on line 0
PHP Warning:  Xdebug MUST be loaded as a Zend extension in Unknown on line 0

Warning: Directive 'register_long_arrays' is deprecated in PHP 5.3 and greater in Unknown on line 0

Warning: Directive 'magic_quotes_gpc' is deprecated in PHP 5.3 and greater in Unknown on line 0

Fatal error: Class 'PHPUnit_Framework_MockObject_Matcher_InvokedRecorder' not found in /usr/share/php/PHPUnit/Framework/MockObject/Matcher/InvokedAtLeastOnce.php on line 60

Call Stack:
    0.0002     651688   1. {main}() /usr/bin/phpunit:0
    0.0031    1173168   2. require('/usr/share/php/PHPUnit/TextUI/Command.php') /usr/bin/phpunit:48
    0.0046    1485456   3. require_once('/usr/share/php/PHPUnit/TextUI/TestRunner.php') /usr/share/php/PHPUnit/TextUI/Command.php:47
    0.0047    1503344   4. require_once('/usr/share/php/PHPUnit/Framework.php') /usr/share/php/PHPUnit/TextUI/TestRunner.php:47
    0.0168    3848688   5. require('/usr/share/php/PHPUnit/Framework/TestCase.php') /usr/share/php/PHPUnit/Framework.php:68
    0.0178    4091880   6. require_once('/usr/share/php/PHPUnit/Framework/MockObject/Matcher/InvokedAtLeastOnce.php') /usr/share/php/PHPUnit/Framework/TestCase.php:49

I checked to make sure that the files exist, that the file paths etc are correct but I don't really know how to go about fixing it can anyone help?


问:
Javascript return statement inside filter function, get uniques. Why code works?
I have a big array of objects where I need to get the unique values for some keys.
I have the code working, but I would like to understand it.

Object

```<code>{
"cor": {
    "id": 89,
    "code": "192"
},
"tamanho": {
    "id": 74,
    "code": "L"
},
"price": "56,34",
"prevPrice": "93,90",
"stock": 0
}
</code>```

And this is the iteration that return only unique values.
What I can't understand is the return statement, how does javasacript reads it?

```<code>var tamanhos = [];
data.grelha.filter(function(el, i, arr) {
  return tamanhos.indexOf(el.tamanho.id) == -1 && tamanhos.push(el.tamanho.id);
});
</code>```

Thanks a lot!

答:
Before I get to what I think you're asking, let's talk about .filter(). Firstly, it returns a new array, so calling .filter() without using its return value is not how you are supposed to use it: if you just want to iterate over the array you should use .forEach() instead. It works by calling the function you pass it once per array element. Only elements for which your function returns a truthy value will be added to the output array. The correct way to use .filter() to solve this problem would be something like this:

```<code>var tamanhos = data.grelha.map(el) { return el.tamaho.id }).filter(function(el, i, arr) {
  return arr.indexOf(el) === i
})
</code>```

That is, first use .map() to get a list of all the IDs, then use .filter() to only keep elements if they are the first occurrence of that ID in the array, thus setting tamanhos to be an array of unique IDs.

Now to what you seem to be asking, which is for an explanation of what the following line is doing:

```<code>return tamanhos.indexOf(el.tamanho.id) == -1 && tamanhos.push(el.tamanho.id);
</code>```

The key is the && (logical AND) operator. It uses short circuit evaluation, which means that the expression on the right-hand-side of the && will only be evaluated if the expression on the left-hand-side is truthy.

Two simple examples (click "Run"):

true && alert('This WILL display because alert() is called.');
false && alert('This will NOT display because alert() is not called');```
</div>
</div>
</p>

<p>So if <code>tamanhos.indexOf(el.tamanho.id) == -1</code> <em>is</em> true then the <code>tamanhos.push(el.tamanho.id)</code> part will be executed, otherwise the <code>.push()</code> will <em>not</em> be executed. In other words, the part after the <code>return</code> is equivalent to doing this:</p>

```if (tamanhos.indexOf(el.tamanho.id) == -1) {
  tamanhos.push(el.tamanho.id);
}
```

<p>(That is, if the item isn't already in the <code>tamanhos</code> array then add it.)</p>

<p>The result of the whole <code>&&</code> expression is then returned, but as mentioned above that is not really relevant because you don't use the return value from <code>.filter()</code>. So what your code is doing is equivalent to this:</p>

```var tamanhos = [];
data.grelha.forEach(function(el) {
  if (tamanhos.indexOf(el.tamanho.id) == -1) {
    tamanhos.push(el.tamanho.id);
  }
});
```

Body:
I have a big array of objects where I need to get the unique values for some keys.
I have the code working, but I would like to understand it.

Object

{
"cor": {
    "id": 89,
    "code": "192"
},
"tamanho": {
    "id": 74,
    "code": "L"
},
"price": "56,34",
"prevPrice": "93,90",
"stock": 0
}

And this is the iteration that return only unique values.
What I can't understand is the return statement, how does javasacript reads it?

var tamanhos = [];
data.grelha.filter(function(el, i, arr) {
  return tamanhos.indexOf(el.tamanho.id) == -1 && tamanhos.push(el.tamanho.id);
});

Thanks a lot!

Body:
Before I get to what I think you're asking, let's talk about .filter(). Firstly, it returns a new array, so calling .filter() without using its return value is not how you are supposed to use it: if you just want to iterate over the array you should use .forEach() instead. It works by calling the function you pass it once per array element. Only elements for which your function returns a truthy value will be added to the output array. The correct way to use .filter() to solve this problem would be something like this:

var tamanhos = data.grelha.map(el) { return el.tamaho.id }).filter(function(el, i, arr) {
  return arr.indexOf(el) === i
})

That is, first use .map() to get a list of all the IDs, then use .filter() to only keep elements if they are the first occurrence of that ID in the array, thus setting tamanhos to be an array of unique IDs.

Now to what you seem to be asking, which is for an explanation of what the following line is doing:

return tamanhos.indexOf(el.tamanho.id) == -1 && tamanhos.push(el.tamanho.id);

The key is the && (logical AND) operator. It uses short circuit evaluation, which means that the expression on the right-hand-side of the && will only be evaluated if the expression on the left-hand-side is truthy.

Two simple examples (click "Run"):

true && alert('This WILL display because alert() is called.');
false && alert('This will NOT display because alert() is not called');

So if tamanhos.indexOf(el.tamanho.id) == -1 is true then the tamanhos.push(el.tamanho.id) part will be executed, otherwise the .push() will not be executed. In other words, the part after the return is equivalent to doing this:

if (tamanhos.indexOf(el.tamanho.id) == -1) {
  tamanhos.push(el.tamanho.id);
}

(That is, if the item isn't already in the tamanhos array then add it.)

The result of the whole && expression is then returned, but as mentioned above that is not really relevant because you don't use the return value from .filter(). So what your code is doing is equivalent to this:

var tamanhos = [];
data.grelha.forEach(function(el) {
  if (tamanhos.indexOf(el.tamanho.id) == -1) {
    tamanhos.push(el.tamanho.id);
  }
});


问:
Jssor - Uncaught TypeError: Cannot read property 'currentStyle' of undefined
Jssor is causing a JavaScript error on . It is the same problem for IE 8, and IE 11.

What I have tried:

Checked https://stackoverflow.com/questions/26465515/script5007-error-in-jssor-slider-in-ie8

Checked https://stackoverflow.com/questions/26632335/jssor-slider-js-error-on-testing-server

Checked JSSOR - Cannot read type property 'currentStyle' of undefined

Updated to latest version jssor on github.

Checked the code for error in the code.

Checked on other browsers and it works well.

Outcome

Couldn't get any working solution.

The error message

```<code> Error line  `var jssor_slider1 = new $JssorSlider$("slider1_containerc", options);`

 Uncaught TypeError: Cannot read property 'currentStyle' of undefined     jssor.slider.min.js:2

E jssor.slider.min.js:2
V jssor.slider.min.js:2(anonymous function) jssor.slider.min.js:2
f.$JssorSlider$ jssor.slider.min.js:2
$.ajax.success map.js:584
j jquery-2.1.1.min.js:2
k.fireWith jquery-2.1.1.min.js:2
x jquery-2.1.1.min.js:4(anonymous function)
</code>```

The code;

HTML

```<code>      <div class="sideshowcontc"><div class="slideshowc" id="slidemapc"><img class="slidelegendc" src="images/chlor_a-legend.png"><div id="slider1_containerc" style="position: relative; top: 0px; left: 0px; width: 640px; height: 612px; display: inline-block;">
        <!-- Slides Container -->
        <div u="slides" style="cursor: move; position: absolute; overflow: hidden; left: 0px; top: 0px; width: 640px; height: 612px;"> <div><img u="CHLOR_A-2003-APR-MAY-JUN" src="data/chlor_a/seasonal/chlor_a-2003-Apr-May-Jun.png">
            <div style="position: absolute; bottom: 0px; left: 0px; width: 640px; height: 50px;
            background-color: #4f91da; opacity: 0.9; filter: alpha(opacity=90);">
          </div>
          <div style="position: absolute; bottom: 0px; left: 0px; width: 640px; height: 50px;
          color: White; font-size: 16px; font-weight: bold; line-height: 50px; text-align: center;">CHLOR_A-2003-APR-MAY-JUN</div></div>
           <div><img u="CHLOR_A-2004-APR-MAY-JUN" src="data/chlor_a/seasonal/chlor_a-2004-Apr-May-Jun.png">
            <div style="position: absolute; bottom: 0px; left: 0px; width: 640px; height: 50px;
            background-color: #4f91da; opacity: 0.9; filter: alpha(opacity=90);">
          </div>
          <div style="position: absolute; bottom: 0px; left: 0px; width: 640px; height: 50px;
          color: White; font-size: 16px; font-weight: bold; line-height: 50px; text-align: center;">CHLOR_A-2004-APR-MAY-JUN</div></div>
           <div><img u="CHLOR_A-2005-APR-MAY-JUN" src="data/chlor_a/seasonal/chlor_a-2005-Apr-May-Jun.png">
            <div style="position: absolute; bottom: 0px; left: 0px; width: 640px; height: 50px;
            background-color: #4f91da; opacity: 0.9; filter: alpha(opacity=90);">
          </div>

          <div style="position: absolute; bottom: 0px; left: 0px; width: 640px; height: 50px;
          color: White; font-size: 16px; font-weight: bold; line-height: 50px; text-align: center;">CHLOR_A-2013-APR-MAY-JUN</div></div>
          </div>
        <span u="arrowleft" class="jssora03l" style="width: 55px; height: 55px; top: 200px; left: 8px;">
        </span>
        <span u="arrowright" class="jssora03r" style="width: 55px; height: 55px; top: 200px; right: 8px">
        </span>

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

jssor js in jquery ajax function:

```<code>var _CaptionTransitions = [];
var _SlideshowTransitions = [
        //{$Duration:1200,x:0.3,$SlideOut:true,$Easing
        {$Left:$JssorEasing$.$EaseInCubic,$Opacity:$JssorEasing$.$EaseLinear},$Opacity:2}
        {$Duration:3000,$Opacity:4,$Brother:{$Duration:3000,$Opacity:1}}//Fade
 ];

 var options = {
                   $AutoPlay: true,                                      //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false
                   $DragOrientation: 1,                                //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0)
                   $CaptionSliderOptions: {                            //[Optional] Options which specifies how to animate caption
                   $PlayInMode: 1,                                 //[Optional] 0 None (no play), 1 Chain (goes after main slide), 3 Chain Flatten (goes after main slide and flatten all caption animations), default value is 1
                   $PlayOutMode: 3                                //[Optional] 0 None (no play), 1 Chain (goes before main slide), 3 Chain Flatten (goes before main slide and flatten all caption animations), default value is 1
                                  },
                   $AutoPlayInterval: 1500,                            //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000
                   $SlideshowOptions: {                                //[Optional] Options to specify and enable slideshow or not
                   $Class: $JssorSlideshowRunner$,                 //[Required] Class to create instance of slideshow
                   $Transitions: _SlideshowTransitions,            //[Required] An array of slideshow transitions to play slideshow
                   $TransitionsOrder: 1,                           //[Optional] The way to choose transition to play slide, 1 Sequence, 0 Random
                   $ShowLink: true
               },
                  $HWA:false,
                  $ArrowNavigatorOptions: {                       //[Optional] Options to specify and enable arrow navigator or not
                  $Class: $JssorArrowNavigator$,              //[Requried] Class to create arrow navigator instance
                  $ChanceToShow: 2,                               //[Required] 0 Never, 1 Mouse Over, 2 Always
                  $AutoCenter: 0,                                 //[Optional] Auto center arrows in parent container, 0 No, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
                  $Steps: 1                                       //[Optional] Steps to go for each navigation request, default value is 1
                                  }
                                };

var jssor_slider1 = new $JssorSlider$("slider1_containerc", options);   // The error line is here.

function ScaleSlider() {
        var parentWidth = $(".resulttab2").width() - 90;
        if (parentWidth) {
            jssor_slider1.$ScaleWidth(Math.min(parentWidth, 640));
        }
}

ScaleSlider();
</code>```

答:
```<code>This Worked for me. Flicker in the chart was issue.
</code>```

Check this for information:

function fixFlicker(docid, tname) {

```<code>var eDoc = document.getElementById(docid);
var cNode = eDoc.getElementsByTagName(tname);

//Copy All the Tag Name
 var arr = [];
 for (var i = 0; i < cNode.length; i++) {
   arr.push(cNode[i].id);
 } //End for loop

 //Delete the Container Elements
 eDoc.innerHTML = "";

//Add back each element
 for (var j = 0; j < arr.length; j++) {
     var newElement = {};
     var newElement = document.createElement(tname);
     newElement.setAttribute("id", arr[j]);
     eDoc.appendChild(newElement)
     console.log(newElement);
   }
}//End of Flicker Clean Up

fixFlicker("div", "canvas");
</code>```

Body:
Jssor is causing a JavaScript error on . It is the same problem for IE 8, and IE 11.

What I have tried:

Checked https://stackoverflow.com/questions/26465515/script5007-error-in-jssor-slider-in-ie8

Checked https://stackoverflow.com/questions/26632335/jssor-slider-js-error-on-testing-server

Checked JSSOR - Cannot read type property 'currentStyle' of undefined

Updated to latest version jssor on github.

Checked the code for error in the code.

Checked on other browsers and it works well.

Outcome

Couldn't get any working solution.

The error message

 Error line  `var jssor_slider1 = new $JssorSlider$("slider1_containerc", options);`

 Uncaught TypeError: Cannot read property 'currentStyle' of undefined     jssor.slider.min.js:2

E jssor.slider.min.js:2
V jssor.slider.min.js:2(anonymous function) jssor.slider.min.js:2
f.$JssorSlider$ jssor.slider.min.js:2
$.ajax.success map.js:584
j jquery-2.1.1.min.js:2
k.fireWith jquery-2.1.1.min.js:2
x jquery-2.1.1.min.js:4(anonymous function)

The code;

HTML

CHLOR_A-2003-APR-MAY-JUN

CHLOR_A-2004-APR-MAY-JUN

CHLOR_A-2013-APR-MAY-JUN

jssor js in jquery ajax function:

var _CaptionTransitions = [];
var _SlideshowTransitions = [
        //{$Duration:1200,x:0.3,$SlideOut:true,$Easing
        {$Left:$JssorEasing$.$EaseInCubic,$Opacity:$JssorEasing$.$EaseLinear},$Opacity:2}
        {$Duration:3000,$Opacity:4,$Brother:{$Duration:3000,$Opacity:1}}//Fade
 ];

 var options = {
                   $AutoPlay: true,                                      //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false
                   $DragOrientation: 1,                                //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0)
                   $CaptionSliderOptions: {                            //[Optional] Options which specifies how to animate caption
                   $PlayInMode: 1,                                 //[Optional] 0 None (no play), 1 Chain (goes after main slide), 3 Chain Flatten (goes after main slide and flatten all caption animations), default value is 1
                   $PlayOutMode: 3                                //[Optional] 0 None (no play), 1 Chain (goes before main slide), 3 Chain Flatten (goes before main slide and flatten all caption animations), default value is 1
                                  },
                   $AutoPlayInterval: 1500,                            //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000
                   $SlideshowOptions: {                                //[Optional] Options to specify and enable slideshow or not
                   $Class: $JssorSlideshowRunner$,                 //[Required] Class to create instance of slideshow
                   $Transitions: _SlideshowTransitions,            //[Required] An array of slideshow transitions to play slideshow
                   $TransitionsOrder: 1,                           //[Optional] The way to choose transition to play slide, 1 Sequence, 0 Random
                   $ShowLink: true
               },
                  $HWA:false,
                  $ArrowNavigatorOptions: {                       //[Optional] Options to specify and enable arrow navigator or not
                  $Class: $JssorArrowNavigator$,              //[Requried] Class to create arrow navigator instance
                  $ChanceToShow: 2,                               //[Required] 0 Never, 1 Mouse Over, 2 Always
                  $AutoCenter: 0,                                 //[Optional] Auto center arrows in parent container, 0 No, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
                  $Steps: 1                                       //[Optional] Steps to go for each navigation request, default value is 1
                                  }
                                };

var jssor_slider1 = new $JssorSlider$("slider1_containerc", options);   // The error line is here.

function ScaleSlider() {
        var parentWidth = $(".resulttab2").width() - 90;
        if (parentWidth) {
            jssor_slider1.$ScaleWidth(Math.min(parentWidth, 640));
        }
}

ScaleSlider();

Body:
This Worked for me. Flicker in the chart was issue.

Check this for information:

function fixFlicker(docid, tname) {

var eDoc = document.getElementById(docid);
var cNode = eDoc.getElementsByTagName(tname);

//Copy All the Tag Name
 var arr = [];
 for (var i = 0; i < cNode.length; i++) {
   arr.push(cNode[i].id);
 } //End for loop

 //Delete the Container Elements
 eDoc.innerHTML = "";

//Add back each element
 for (var j = 0; j < arr.length; j++) {
     var newElement = {};
     var newElement = document.createElement(tname);
     newElement.setAttribute("id", arr[j]);
     eDoc.appendChild(newElement)
     console.log(newElement);
   }
}//End of Flicker Clean Up

fixFlicker("div", "canvas");


问:
Space concatenated with an expression is sometimes dropped
JSFiddle contains:

```<code>var d = " " + true ? "am" : "pm";
var e = " " + "am";
alert("|" + d + "|");
alert("|" + e + "|");
</code>```

Why does d not contain the leading space?

答: you want var d = " " + (true ? "am" : "pm")

Body:
JSFiddle contains:

var d = " " + true ? "am" : "pm";
var e = " " + "am";
alert("|" + d + "|");
alert("|" + e + "|");

Why does d not contain the leading space?


问:
How can I maintain consistency in a 2-way object relationship in JavaScript?
If I have a 2-way relationship between 2 objects, such that A relates to B and B relates to A, how can I keep this consistent such that the 2 objects will always refer back to each other?

I'm struggling to put my very simple problem into words, so here's a very simple example. I start with Husband and Wife:

```<code>function Husband() { this.wife; }
function Wife() { this.husband; }

var harry = new Husband();
var wendy = new Wife();

harry.wife = wendy;
wendy.husband = harry;
</code>```

Logically, if Harry's wife is Wendy, then Wendy's husband is Harry.

I need a way of keeping this relationship consistent. So I create a setter method on Husband and denote that the wife variable should be treated as private by prefixing with an underscore.

```<code>function Husband() {
    this._wife;
    this.setWife = function(wife) {
        this._wife = wife;
        wife.husband = this;
    }
}
</code>```

Describing this relationship is now simple and encourages consistency:

```<code>harry.setWife(wendy);
</code>```

Likewise, it would be nice to have the reverse option:

```<code>wendy.setHusband(harry);
</code>```

To do this I create a setHusband method on Wife, and tweak Husband as needed.

```<code>function Husband() {
    this._wife;
    this.setWife = function(wife) {
        this._wife = wife;
        // wife.husband = this; // <-- husband is now _husband (private)...
        wife.setHusband(this);  // <-- switching to a public method
    }
}

function Wife() {
    this._husband;
    this.setHusband = function(husband) {
        this._husband = husband;
        husband._wife = this;  // <-- Oops! _wife is private!
        husband.setWife(this); // <-- Oops! this results in an infinite loop!
    }
}
</code>```

At this point I run into a snag. My new setHusband method needs to be able to maintain consistency, but wife is now _wife (private), and calling setWife causes an infinite loop because they reciprocate each other.

I could create another set of methods like reallyJustSetHusband but that seems silly.

My conundrum isn't particular to JavaScript, but I've mentioned it in the question in case there's a particular approach needed.

What is the best way to achieve consistency between these 2 objects? Is there something I've overlooked?

Similar Pattern in the DOM

In the DOM, if you call parent.appendChild(child), then child.parentNode === parent. They are never inconsistent. If a parent has a child the child has the same parent. Other relationships such as nextSibling are also kept consistent.

答:
._wife isn't necessarily private - a wife knows its husband and should be allowed to set his properties. Also you can easily break out of the infinite loop:

```<code>class Wife() {
  constructor() {
    this._husband=null;
  }
  get husband() { return this._husband }
  set husband(h) {
    if (this._husband) this._husband._wife = null;
    this._husband = h;
    if (h && h.wife != this) h.wife = this;
  }
}
</code>```

If you don't want this insider knowledge, you need to use an intermediate class Marriage that manages a relationship (can be created, queried and broken).

```<code>class Marriage {
  constructor(h, w) {
    this.husband = h;
    this.wife = w;
  }
  divorce() {
    this.husband.marriage = null;
    this.wife.marriage = null;
  }
}
class Wife() {
  constructor() {
    this.marriage = null;
  }
  get husband() {
    return this.marriage && this.marriage.husband;
  }
  set husband(h) {
    if (this.marriage) this.marriage.divorce();
    if (h.marriage) h.marriage.divorce();
    this.marriage = h.marriage = new Marriage(h, this);
  }
}
</code>```

Body:
If I have a 2-way relationship between 2 objects, such that A relates to B and B relates to A, how can I keep this consistent such that the 2 objects will always refer back to each other?

I'm struggling to put my very simple problem into words, so here's a very simple example. I start with Husband and Wife:

function Husband() { this.wife; }
function Wife() { this.husband; }

var harry = new Husband();
var wendy = new Wife();

harry.wife = wendy;
wendy.husband = harry;

Logically, if Harry's wife is Wendy, then Wendy's husband is Harry.

I need a way of keeping this relationship consistent. So I create a setter method on Husband and denote that the wife variable should be treated as private by prefixing with an underscore.

function Husband() {
    this._wife;
    this.setWife = function(wife) {
        this._wife = wife;
        wife.husband = this;
    }
}

Describing this relationship is now simple and encourages consistency:

harry.setWife(wendy);

Likewise, it would be nice to have the reverse option:

wendy.setHusband(harry);

To do this I create a setHusband method on Wife, and tweak Husband as needed.

function Husband() {
    this._wife;
    this.setWife = function(wife) {
        this._wife = wife;
        // wife.husband = this; // <-- husband is now _husband (private)...
        wife.setHusband(this);  // <-- switching to a public method
    }
}

function Wife() {
    this._husband;
    this.setHusband = function(husband) {
        this._husband = husband;
        husband._wife = this;  // <-- Oops! _wife is private!
        husband.setWife(this); // <-- Oops! this results in an infinite loop!
    }
}

At this point I run into a snag. My new setHusband method needs to be able to maintain consistency, but wife is now _wife (private), and calling setWife causes an infinite loop because they reciprocate each other.

I could create another set of methods like reallyJustSetHusband but that seems silly.

My conundrum isn't particular to JavaScript, but I've mentioned it in the question in case there's a particular approach needed.

What is the best way to achieve consistency between these 2 objects? Is there something I've overlooked?

Similar Pattern in the DOM

In the DOM, if you call parent.appendChild(child), then child.parentNode === parent. They are never inconsistent. If a parent has a child the child has the same parent. Other relationships such as nextSibling are also kept consistent.

Body:
._wife isn't necessarily private - a wife knows its husband and should be allowed to set his properties. Also you can easily break out of the infinite loop:

class Wife() {
  constructor() {
    this._husband=null;
  }
  get husband() { return this._husband }
  set husband(h) {
    if (this._husband) this._husband._wife = null;
    this._husband = h;
    if (h && h.wife != this) h.wife = this;
  }
}

If you don't want this insider knowledge, you need to use an intermediate class Marriage that manages a relationship (can be created, queried and broken).

class Marriage {
  constructor(h, w) {
    this.husband = h;
    this.wife = w;
  }
  divorce() {
    this.husband.marriage = null;
    this.wife.marriage = null;
  }
}
class Wife() {
  constructor() {
    this.marriage = null;
  }
  get husband() {
    return this.marriage && this.marriage.husband;
  }
  set husband(h) {
    if (this.marriage) this.marriage.divorce();
    if (h.marriage) h.marriage.divorce();
    this.marriage = h.marriage = new Marriage(h, this);
  }
}


问:
Spark.sql and sqlContext.sql
I have imported the below modules. I tried to load data from sqlCtx.read.format, I am getting "IllegalArgumentException: u"Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState':"" error, but it works well when I use spark.read.format. I am seeing same behavior when I am retrieving data from registered temptable/view. What can I add extra to use sqlCtx.sql instead of spark.sql?

```<code>import os
import sys
import pandas as pd
import odbc as pyodbc
import os
import sys
import re
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import *
from pyspark.sql import Row
from pyspark.sql.functions import *
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import pyspark.sql.functions as func
import matplotlib.patches as mpatches
import time as time
from matplotlib.patches import Rectangle
import datetime
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
conf = SparkConf()
conf.setMaster("local")
conf.setAppName("AppName")
sqlCtx = SQLContext(sc)
</code>```

答:
I spent two hours of my life in this one, just to realize I did not need:

```<code>sqlCtx = SQLContext(sc)
</code>```

Just using SQLContext.read.(...), solved this in my case.

Title: Spark.sql and sqlContext.sql

Body:
I have imported the below modules. I tried to load data from sqlCtx.read.format, I am getting "IllegalArgumentException: u"Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState':"" error, but it works well when I use spark.read.format. I am seeing same behavior when I am retrieving data from registered temptable/view. What can I add extra to use sqlCtx.sql instead of spark.sql?

import os
import sys
import pandas as pd
import odbc as pyodbc
import os
import sys
import re
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import *
from pyspark.sql import Row
from pyspark.sql.functions import *
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import pyspark.sql.functions as func
import matplotlib.patches as mpatches
import time as time
from matplotlib.patches import Rectangle
import datetime
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
conf = SparkConf()
conf.setMaster("local")
conf.setAppName("AppName")
sqlCtx = SQLContext(sc)

Body:
I spent two hours of my life in this one, just to realize I did not need:

sqlCtx = SQLContext(sc)

Just using SQLContext.read.(...), solved this in my case.


答:
Check the edit here.

The javascript order of operations is computing " " + true before the ternary operator.

Title: Space concatenated with an expression is sometimes dropped