问:
Use a clojure macro to automatically create getters and setters inside a reify call
I am trying to implement a huge Java interface with numerous (~50) getter and setter methods (some with irregular names). I thought it would be nice to use a macro to reduce the amount of code. So instead of

```<code>(def data (atom {:x nil}))
(reify HugeInterface
  (getX [this] (:x @data))
  (setX [this v] (swap! data assoc :x v)))
</code>```

I want to be able to write

```<code>(def data (atom {:x nil}))
(reify HugeInterface
  (set-and-get getX setX :x))
</code>```

Is this set-and-get macro (or something similar) possible? I haven't been able to make it work.

答:
(Updated with a second approach -- see below the second horizontal rule -- as well as some explanatory remarks re: the first one.)

I wonder if this might be a step in the right direction:

```<code>(defmacro reify-from-maps [iface implicits-map emit-map & ms]
  `(reify ~iface
     ~@(apply concat
         (for [[mname & args :as m] ms]
           (if-let [emit ((keyword mname) emit-map)]
             (apply emit implicits-map args)
             [m])))))

(def emit-atom-g&ss
  {:set-and-get (fn [implicits-map gname sname k]
                  [`(~gname [~'this] (~k @~(:atom-name implicits-map)))
                   `(~sname [~'this ~'v]
                      (swap! ~(:atom-name implicits-map) assoc ~k ~'v))])})

(defmacro atom-bean [iface a & ms]
  `(reify-from-maps ~iface {:atom-name ~a} ~emit-atom-g&ss ~@ms))
</code>```

NB. that the atom-bean macro passes the actual compile-time value of emit-atom-g&ss on to reify-from-maps. Once a particular atom-bean form is compiled, any subsequent changes to emit-atom-g&ss have no effect on the behaviour of the created object.

An example macroexpansion from the REPL (with some line breaks and indentation added for clarity):

```<code>user> (-> '(atom-bean HugeInterface data
             (set-and-get setX getX :x))
          macroexpand-1
          macroexpand-1)
(clojure.core/reify HugeInterface
  (setX [this] (:x (clojure.core/deref data)))
  (getX [this v] (clojure.core/swap! data clojure.core/assoc :x v)))
</code>```

Two macroexpand-1s are necessary, because atom-bean is a macro which expands to a further macro call. macroexpand would not be particularly useful, as it would expand this all the way to a call to reify*, the implementation detail behind reify.

The idea here is that you can supply an emit-map like emit-atom-g&ss above, keyed by keywords whose names (in symbolic form) will trigger magic method generation in reify-from-maps calls. The magic is performed by the functions stored as functions in the given emit-map; the arguments to the functions are a map of "implicits" (basically any and all information which should be accessible to all method definitions in a reify-from-maps form, like the name of the atom in this particular case) followed by whichever arguments were given to the "magic method specifier" in the reify-from-maps form. As mentioned above, reify-from-maps needs to see an actual keyword -> function map, not its symbolic name; so, it's only really usable with literal maps, inside other macros or with help of eval.

Normal method definitions can still be included and will be treated as in a regular reify form, provided keys matching their names do not occur in the emit-map. The emit functions must return seqables (e.g. vectors) of method definitions in the format expected by reify: in this way, the case with multiple method definitions returned for one "magic method specifier" is relatively simple. If the iface argument were replaced with ifaces and ~iface with ~@ifaces in reify-from-maps' body, multiple interfaces could be specified for implementation.

Here's another approach, possibly easier to reason about:

```<code>(defn compile-atom-bean-converter [ifaces get-set-map]
  (eval
   (let [asym (gensym)]
     `(fn [~asym]
        (reify ~@ifaces
          ~@(apply concat
              (for [[k [g s]] get-set-map]
                [`(~g [~'this] (~k @~asym))
                 `(~s [~'this ~'v]
                      (swap! ~asym assoc ~k ~'v))])))))))
</code>```

This calls on the compiler at runtime, which is somewhat expensive, but only needs to be done once per set of interfaces to be implemented. The result is a function which takes an atom as an argument and reifies a wrapper around the atom implementing the given interfaces with getters and setters as specified in the get-set-map argument. (Written this way, this is less flexible than the previous approach, but most of the code above could be reused here.)

Here's a sample interface and a getter/setter map:

```<code>(definterface IFunky
  (getFoo [])
  (^void setFoo [v])
  (getFunkyBar [])
  (^void setWeirdBar [v]))

(def gsm
  '{:foo [getFoo setFoo]
    :bar [getFunkyBar setWeirdBar]})
</code>```

And some REPL interactions:

```<code>user> (def data {:foo 1 :bar 2})
#'user/data
user> (def atom-bean-converter (compile-atom-bean-converter '[IFunky] gsm))
#'user/atom-bean-converter
user> (def atom-bean (atom-bean-converter data))
#'user/atom-bean
user> (.setFoo data-bean 3)
nil
user> (.getFoo atom-bean)
3
user> (.getFunkyBar data-bean)
2
user> (.setWeirdBar data-bean 5)
nil
user> (.getFunkyBar data-bean)
5
</code>```

Body:
I am trying to implement a huge Java interface with numerous (~50) getter and setter methods (some with irregular names). I thought it would be nice to use a macro to reduce the amount of code. So instead of

(def data (atom {:x nil}))
(reify HugeInterface
  (getX [this] (:x @data))
  (setX [this v] (swap! data assoc :x v)))

I want to be able to write

(def data (atom {:x nil}))
(reify HugeInterface
  (set-and-get getX setX :x))

Is this set-and-get macro (or something similar) possible? I haven't been able to make it work.

Body:
(Updated with a second approach -- see below the second horizontal rule -- as well as some explanatory remarks re: the first one.)

I wonder if this might be a step in the right direction:

(defmacro reify-from-maps [iface implicits-map emit-map & ms]
  `(reify ~iface
     ~@(apply concat
         (for [[mname & args :as m] ms]
           (if-let [emit ((keyword mname) emit-map)]
             (apply emit implicits-map args)
             [m])))))

(def emit-atom-g&ss
  {:set-and-get (fn [implicits-map gname sname k]
                  [`(~gname [~'this] (~k @~(:atom-name implicits-map)))
                   `(~sname [~'this ~'v]
                      (swap! ~(:atom-name implicits-map) assoc ~k ~'v))])})

(defmacro atom-bean [iface a & ms]
  `(reify-from-maps ~iface {:atom-name ~a} ~emit-atom-g&ss ~@ms))

NB. that the atom-bean macro passes the actual compile-time value of emit-atom-g&ss on to reify-from-maps. Once a particular atom-bean form is compiled, any subsequent changes to emit-atom-g&ss have no effect on the behaviour of the created object.

An example macroexpansion from the REPL (with some line breaks and indentation added for clarity):

user> (-> '(atom-bean HugeInterface data
             (set-and-get setX getX :x))
          macroexpand-1
          macroexpand-1)
(clojure.core/reify HugeInterface
  (setX [this] (:x (clojure.core/deref data)))
  (getX [this v] (clojure.core/swap! data clojure.core/assoc :x v)))

Two macroexpand-1s are necessary, because atom-bean is a macro which expands to a further macro call. macroexpand would not be particularly useful, as it would expand this all the way to a call to reify*, the implementation detail behind reify.

The idea here is that you can supply an emit-map like emit-atom-g&ss above, keyed by keywords whose names (in symbolic form) will trigger magic method generation in reify-from-maps calls. The magic is performed by the functions stored as functions in the given emit-map; the arguments to the functions are a map of "implicits" (basically any and all information which should be accessible to all method definitions in a reify-from-maps form, like the name of the atom in this particular case) followed by whichever arguments were given to the "magic method specifier" in the reify-from-maps form. As mentioned above, reify-from-maps needs to see an actual keyword -> function map, not its symbolic name; so, it's only really usable with literal maps, inside other macros or with help of eval.

Normal method definitions can still be included and will be treated as in a regular reify form, provided keys matching their names do not occur in the emit-map. The emit functions must return seqables (e.g. vectors) of method definitions in the format expected by reify: in this way, the case with multiple method definitions returned for one "magic method specifier" is relatively simple. If the iface argument were replaced with ifaces and ~iface with ~@ifaces in reify-from-maps' body, multiple interfaces could be specified for implementation.

Here's another approach, possibly easier to reason about:

(defn compile-atom-bean-converter [ifaces get-set-map]
  (eval
   (let [asym (gensym)]
     `(fn [~asym]
        (reify ~@ifaces
          ~@(apply concat
              (for [[k [g s]] get-set-map]
                [`(~g [~'this] (~k @~asym))
                 `(~s [~'this ~'v]
                      (swap! ~asym assoc ~k ~'v))])))))))

This calls on the compiler at runtime, which is somewhat expensive, but only needs to be done once per set of interfaces to be implemented. The result is a function which takes an atom as an argument and reifies a wrapper around the atom implementing the given interfaces with getters and setters as specified in the get-set-map argument. (Written this way, this is less flexible than the previous approach, but most of the code above could be reused here.)

Here's a sample interface and a getter/setter map:

(definterface IFunky
  (getFoo [])
  (^void setFoo [v])
  (getFunkyBar [])
  (^void setWeirdBar [v]))

(def gsm
  '{:foo [getFoo setFoo]
    :bar [getFunkyBar setWeirdBar]})

And some REPL interactions:

user> (def data {:foo 1 :bar 2})
#'user/data
user> (def atom-bean-converter (compile-atom-bean-converter '[IFunky] gsm))
#'user/atom-bean-converter
user> (def atom-bean (atom-bean-converter data))
#'user/atom-bean
user> (.setFoo data-bean 3)
nil
user> (.getFoo atom-bean)
3
user> (.getFunkyBar data-bean)
2
user> (.setWeirdBar data-bean 5)
nil
user> (.getFunkyBar data-bean)
5


来源: stackexchange

问:
Change date format dot instead of slash in Date Range Picker
is it possible to change the date format from 02/03/2017 to 02.03.2017
dot instead of slash ?
please advice

link to jquery plugin daterangepicker.com

答:
var date = "02/03/2017"

date = date.split('/').join('.');

Just convert before or after using it.

ContentLicense: CC BY-SA 3.0


问:
Reduce PythonRDD of lists into one list
Going to keep this short post, but happy to add more context / details if they are necessary. I have a PythonRDD that looks as follows:

```<code>print(myRDD)
PythonRDD[4] at RDD at PythonRDD.scala:43

print(myRDD.take(1))
[[0.305, 0.302, -0.005, 0.302]]

print(myRDD.collect())
[[0.305, 0.302, -0.005, 0.302],
 [0.294, 0.183, 0.084, 0.277],
 [0.184, 0.997, -1.123, 0.654]]
</code>```

Each of the 3 lists contains the 4 values for a 2x2 matrix. I would like to add these 3 matrices together, hence I would like to use some reduce function on myRDD such that the output is:

[[.783, 1.482, -1.044, 1.233]]
```

<p>Where .783 = .305 + .294 + .184, etc. I tried to do:</p>

```myRDD.reduce(lambda a, b: a + b)
```

However this did not give me what I desired. Any help appreciated! Thanks!

答:
what you need is something along below lines - </p>

```<code>myRDD.reduce(lambda a, b: [a[0] + b[0], a[1]+b[1],a[2]+b[2],a[3]+b[3]])
</code>```

Title: Reduce PythonRDD of lists into one list

Body:
Going to keep this short post, but happy to add more context / details if they are necessary. I have a PythonRDD that looks as follows:

print(myRDD)
PythonRDD[4] at RDD at PythonRDD.scala:43

print(myRDD.take(1))
[[0.305, 0.302, -0.005, 0.302]]

print(myRDD.collect())
[[0.305, 0.302, -0.005, 0.302],
 [0.294, 0.183, 0.084, 0.277],
 [0.184, 0.997, -1.123, 0.654]]

Each of the 3 lists contains the 4 values for a 2x2 matrix. I would like to add these 3 matrices together, hence I would like to use some reduce function on myRDD such that the output is:

[[.783, 1.482, -1.044, 1.233]]

Where .783 = .305 + .294 + .184, etc. I tried to do:

myRDD.reduce(lambda a, b: a + b)

However this did not give me what I desired. Any help appreciated! Thanks!

Body:
what you need is something along below lines -

myRDD.reduce(lambda a, b: [a[0] + b[0], a[1]+b[1],a[2]+b[2],a[3]+b[3]])


问:
Using target="_blank" in a php redirect. Where do i put it?
Good day stackoverflow. Thank you for your time.

I have this php

```<code>$ImageLinks['image.png'] = 'http://www.example.com/r/redirect.php';
</code>```

which redirects to the 'redirect.php' - which is the following

```<code><?php $URL="http://thetargetlinktobeopenedinnewtab.com";
header ("Location: $URL");
exit();
?>
</code>```

How can I make this $URL open in a new tab? I've tried placing the target="_blank" all over the place.

答:
You can try this out via javascript.

```<code><script type="text/javascript" language="Javascript">window.open('http://www.example.com');
</script>
</code>```

Now, you can use a javascript generator from php to convert this to PHP code.

Please note this will fail with a lot of the pop-up blockers around.

Body:
Good day stackoverflow. Thank you for your time.

I have this php

$ImageLinks['image.png'] = 'http://www.example.com/r/redirect.php';

which redirects to the 'redirect.php' - which is the following

<?php $URL="http://thetargetlinktobeopenedinnewtab.com";
header ("Location: $URL");
exit();
?>

How can I make this $URL open in a new tab? I've tried placing the target="_blank" all over the place.

Body:
You can try this out via javascript.

<script type="text/javascript" language="Javascript">window.open('http://www.example.com');
</script>

Now, you can use a javascript generator from php to convert this to PHP code.

Please note this will fail with a lot of the pop-up blockers around.


问:
Can't Manage Access Keys for Cognitive Services Resource Azure
I have had trouble managing my access keys for my Cognitive Services Resource on Azure. Every time I log in any browser and click on Manage Keys... the keys don't appear. Even if I click on the cloud icon, they only appear for a split second and then disappear. Has anyone else had this problem? How did they solve it?

答:
See Translator Speech API Keys No Longer Show in Portal & Have Stopped Working:

That error means that your Azure subscription (which is different than your F0 free tier Cognitive Services account) is not active. Typically this happens if you have a 1 month Azure free trial subscription and the free 1 month period has expired, but it can also happen to paid Azure accounts if there is a problem with the billing such as an expired credit card.

You should be able to validate this in the subscription list in the Azure portal - https://portal.azure.com/#blade/Microsoft_Azure_Billing/SubscriptionsBlade.


问:
C++ - stat(), access() not working under gnu gcc
I've got a pretty basic console program here, to determine if a folder or file exists or not using stat:

```<code>#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  char path[] = "myfolder/";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

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

I have also tried the access version:

```<code>#include <iostream>
#include <io.h>

using namespace std;

int main() {
  char path[] = "myfolder/";

  if(access(path,0)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

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

Neither of them find my folder (which is right there in the same directory as the program).  These worked on my last compiler (the default one with DevCpp). I switched to CodeBlocks and am compiling with Gnu GCC now, if that helps.  I'm sure it's a quick fix - can someone help out?

(Obviously I'm a noob at this so if you need any other information I've left out please let me know).

UPDATE

The problem was with the base directory.  The updated, working program is as follows:

```<code>#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  cout << "Current directory: " << system("cd") << endl;

  char path[] = "./bin/Release/myfolder";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Directory found." << endl; }
  else { cout << "Can't find directory." << endl; } //Doesn't exist

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

ANOTHER UPDATE

Turns out that a trailing backslash on the path is big trouble.

答:
Right before your stat call, insert the code:

```<code>system("pwd");  // for UNIXy systems
system("cd");   // for Windowsy systems
</code>```

(or equivalent) to check your current directory. I think you'll find it's not what you think.

Alternatively, run the executable from the command line where you know what directory you're in. IDEs will frequently run your executable from a directory you may not expect.

Or, use the full path name so that it doesn't matter which directory you're in.

For what it's worth, your first code segment works perfectly (gcc under Ubuntu 10):

```<code>pax$ ls my*
ls: cannot access my*: No such file or directory

pax$ ./qq
Cannot find folder.

pax$ mkdir myfolder

pax$ ll -d my*
drwxr-xr-x 2 pax pax 4096 2010-12-14 09:33 myfolder/

pax$ ./qq
Folder found.
</code>```

Body:
I've got a pretty basic console program here, to determine if a folder or file exists or not using stat:

#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  char path[] = "myfolder/";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

I have also tried the access version:

#include <iostream>
#include <io.h>

using namespace std;

int main() {
  char path[] = "myfolder/";

  if(access(path,0)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

Neither of them find my folder (which is right there in the same directory as the program).  These worked on my last compiler (the default one with DevCpp). I switched to CodeBlocks and am compiling with Gnu GCC now, if that helps.  I'm sure it's a quick fix - can someone help out?

(Obviously I'm a noob at this so if you need any other information I've left out please let me know).

UPDATE

The problem was with the base directory.  The updated, working program is as follows:

#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  cout << "Current directory: " << system("cd") << endl;

  char path[] = "./bin/Release/myfolder";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Directory found." << endl; }
  else { cout << "Can't find directory." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

ANOTHER UPDATE

Turns out that a trailing backslash on the path is big trouble.

Body:
Right before your stat call, insert the code:

system("pwd");  // for UNIXy systems
system("cd");   // for Windowsy systems

(or equivalent) to check your current directory. I think you'll find it's not what you think.

Alternatively, run the executable from the command line where you know what directory you're in. IDEs will frequently run your executable from a directory you may not expect.

Or, use the full path name so that it doesn't matter which directory you're in.

For what it's worth, your first code segment works perfectly (gcc under Ubuntu 10):

pax$ ls my*
ls: cannot access my*: No such file or directory

pax$ ./qq
Cannot find folder.

pax$ mkdir myfolder

pax$ ll -d my*
drwxr-xr-x 2 pax pax 4096 2010-12-14 09:33 myfolder/

pax$ ./qq
Folder found.

ContentLicense: CC BY-SA 2.5


问:
pulling a random item from multiple arrays
I have 12 arrays named f1 to f12 each with five items. I want to randomly pull one item from each array and push these into the new array sm1.

```<code>var sm1 = [];

for (var i=1; i<=12; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push("f"+i[randomPrompt]);
}
</code>```

However, this returns a random index of "f"+i instead of it indexing f1, f2, f3, f4, etc.

答:
Changes below line

```<code>sm1.push("f"+i[randomPrompt]);
</code>```

to

```<code>sm1.push(eval("f"+i+"["+randomPrompt+"]"));
</code>```

Body:
I have 12 arrays named f1 to f12 each with five items. I want to randomly pull one item from each array and push these into the new array sm1.

var sm1 = [];

for (var i=1; i<=12; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push("f"+i[randomPrompt]);
}

However, this returns a random index of "f"+i instead of it indexing f1, f2, f3, f4, etc.

Body:
Changes below line

sm1.push("f"+i[randomPrompt]);

to

sm1.push(eval("f"+i+"["+randomPrompt+"]"));


问:
Updating state from child component reactjs
I am trying to refactor component elegantly so we can easily use the component for same usecase.

I have two component,

NewPurchaseOrder (parent comp.)

SelectWarehouse (child comp.)

SelectWarehouse component would render the dropdown list of available warehouses in NewPurchaseOrder component.

The parent component has one state warehouseId to track selected warehouse, to update the parent components state (warehouseId) from the child component i am doing this,

Parent Component

```<code><SelectWarehouse
  updateTarget={ ( ghostValue ) => {
    this.setState( {
      warehouseId: ghostValue // updating the state from child comp. value
    }, () => {
      console.log( 'yokygoky', this.state.warehouseId )
    } )
  } }
/>
</code>```

Child Component

```<code>handleChangeWarehouse( e ) {
  this.setState( {
    selectedWarehouse: e.target.value
  }, () => {
    this.props.updateTarget( e.target.value ) // Updating the parent props
  } )
}
</code>```

Now what i am trying to do, is to send only the state name from the parent instead of sending a function and then update that state of parent component from the child component.
It would look something like this,

```<code><SelectWarehouse
  updateTarget={ warehouseId }
/>
</code>```

And then update the warehouseId from the child component.

Is it possible?

I have tested it by only sending the state with no luck, also its not possible to bind this context with only a simple state.

答:
State is something that is specific to a component scope and thus you cannot just access and modify the state of one component from another by directly accessing it, You have to call a method of the specific component whose state you want to change.

So, the first method that you have used is a right way to  do it.

Perhaps to make it more cleaner you can have the logic in a separate function and pass that function as a prop

Parent

```<code>updateTarget = (newValue) => {

    this.setState( {
      warehouseId: newValue // updating the state from child comp. value
    }, () => {
      console.log( 'yokygoky', this.state.warehouseId )
    } )
}
<SelectWarehouse
  updateTarget={ ( ghostValue ) => this.updateTarget(ghostValue) }
/>
</code>```

Body:
I am trying to refactor component elegantly so we can easily use the component for same usecase.

I have two component,

NewPurchaseOrder (parent comp.)

SelectWarehouse (child comp.)

SelectWarehouse component would render the dropdown list of available warehouses in NewPurchaseOrder component.

The parent component has one state warehouseId to track selected warehouse, to update the parent components state (warehouseId) from the child component i am doing this,

Parent Component

<SelectWarehouse
  updateTarget={ ( ghostValue ) => {
    this.setState( {
      warehouseId: ghostValue // updating the state from child comp. value
    }, () => {
      console.log( 'yokygoky', this.state.warehouseId )
    } )
  } }
/>

Child Component

handleChangeWarehouse( e ) {
  this.setState( {
    selectedWarehouse: e.target.value
  }, () => {
    this.props.updateTarget( e.target.value ) // Updating the parent props
  } )
}

Now what i am trying to do, is to send only the state name from the parent instead of sending a function and then update that state of parent component from the child component.
It would look something like this,

<SelectWarehouse
  updateTarget={ warehouseId }
/>

And then update the warehouseId from the child component.

Is it possible?

I have tested it by only sending the state with no luck, also its not possible to bind this context with only a simple state.

Body:
State is something that is specific to a component scope and thus you cannot just access and modify the state of one component from another by directly accessing it, You have to call a method of the specific component whose state you want to change.

So, the first method that you have used is a right way to  do it.

Perhaps to make it more cleaner you can have the logic in a separate function and pass that function as a prop

Parent

updateTarget = (newValue) => {

    this.setState( {
      warehouseId: newValue // updating the state from child comp. value
    }, () => {
      console.log( 'yokygoky', this.state.warehouseId )
    } )
}
<SelectWarehouse
  updateTarget={ ( ghostValue ) => this.updateTarget(ghostValue) }
/>


答:
There's a few ways to accomplish what you ask.

Example:

var myArray = {
   "f1": [1,2,3,4,5],
   "f2": [6,7,8,9,10],
   "f3": [11,12,13,14,15],
   "f4": [16,17,18,19,20]
}

var sm1 = [];
for (var i=1; i<=4; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push(myArray["f"+i][randomPrompt]);
}
console.log(sm1);```
</div>
</div>
</p>

<p>OR, If you are using code in the browser:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f1 = [1,2,3,4,5];
f2 = [6,7,8,9,10];
f3 = [11,12,13,14,15];
f4 = [16,17,18,19,20];

var sm1 = [];

for (var i=1; i<=4; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push(window["f"+i][randomPrompt]);
}
console.log(sm1);</code>```

Or use eval():

f1 = [1,2,3,4,5];
f2 = [6,7,8,9,10];
f3 = [11,12,13,14,15];
f4 = [16,17,18,19,20];

var sm1 = [],item;

for (var i=1; i<=4; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    item = eval(["f"+i][0]);
    sm1.push(item[randomPrompt]);
}
console.log(sm1);```

Title: pulling a random item from multiple arrays

Body:
There's a few ways to accomplish what you ask.

Example:

var myArray = {
   "f1": [1,2,3,4,5],
   "f2": [6,7,8,9,10],
   "f3": [11,12,13,14,15],
   "f4": [16,17,18,19,20]
}

var sm1 = [];
for (var i=1; i<=4; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push(myArray["f"+i][randomPrompt]);
}
console.log(sm1);

OR, If you are using code in the browser:

f1 = [1,2,3,4,5];
f2 = [6,7,8,9,10];
f3 = [11,12,13,14,15];
f4 = [16,17,18,19,20];

var sm1 = [];

for (var i=1; i<=4; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push(window["f"+i][randomPrompt]);
}
console.log(sm1);

Or use eval():

f1 = [1,2,3,4,5];
f2 = [6,7,8,9,10];
f3 = [11,12,13,14,15];
f4 = [16,17,18,19,20];

var sm1 = [],item;

for (var i=1; i<=4; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    item = eval(["f"+i][0]);
    sm1.push(item[randomPrompt]);
}
console.log(sm1);


问:
Different out for same function in Java against Python
I have a formula to evaluate

```<code>((x+y-1)*(x+y-2))/2 + x
</code>```

and get the string representation of it.
So in Java 1.7 I write

```<code>public static void main(String[] args)
{
    int x = 99999;
    int y = 99999;
    int answer = ((x+y-1)*(x+y-2))/2 + x;
    String s = Integer.toString(answer);
    System.out.println(s);
}
</code>```

and in Python 2.7

```<code>def answer(x, y):
  z = ((x+y-1)*(x+y-2))/2 + x
  return str(z);

print(answer(99999,99999))
</code>```

Java gave me the out put of 672047173 while Python gave me 19999400005 and seems the value from Python is correct. What is the reason behind this difference.

答:
19999400005 is a too large value for int variables, so the Java calculations would overflow.

Use long variables instead:

```<code>public static void main(String[] args)
{
    long x = 99999;
    long y = 99999;
    long answer = ((x+y-1)*(x+y-2))/2 + x;
    String s = Long.toString(answer);
    System.out.println(s);
}
</code>```

Output is:

```<code>19999400005
</code>```

Also note that you can print answer directly and don't have to convert it to String explicitly:

```<code>System.out.println(answer);
</code>```

Body:
I have a formula to evaluate

((x+y-1)*(x+y-2))/2 + x

and get the string representation of it.
So in Java 1.7 I write

public static void main(String[] args)
{
    int x = 99999;
    int y = 99999;
    int answer = ((x+y-1)*(x+y-2))/2 + x;
    String s = Integer.toString(answer);
    System.out.println(s);
}

and in Python 2.7

def answer(x, y):
  z = ((x+y-1)*(x+y-2))/2 + x
  return str(z);

print(answer(99999,99999))

Java gave me the out put of 672047173 while Python gave me 19999400005 and seems the value from Python is correct. What is the reason behind this difference.

Body:
19999400005 is a too large value for int variables, so the Java calculations would overflow.

Use long variables instead:

public static void main(String[] args)
{
    long x = 99999;
    long y = 99999;
    long answer = ((x+y-1)*(x+y-2))/2 + x;
    String s = Long.toString(answer);
    System.out.println(s);
}

Output is:

19999400005

Also note that you can print answer directly and don't have to convert it to String explicitly:

System.out.println(answer);


问:
Custom UILabel not displaying properly in Interface Builder
I have a custom UILabel based class, that does not display properly in the storyboard.

All it displays is a blank label. It happens with both XCode 6 and 7 beta.

```<code>import UIKit

@IBDesignable

class CCLabel: UILabel {

@IBInspectable var spacingChar: CGFloat = 0 {
    didSet {
        self.updateAttributed(self.text)
    }
}

@IBInspectable var extraLineSpacing: CGFloat = 0 {
    didSet {
        self.updateAttributed(self.text)
    }
}

override var bounds: CGRect {
    didSet {
        if (bounds.size.width != self.bounds.size.width) {
            self.setNeedsUpdateConstraints()
        }
        super.bounds = bounds
    }
}

override func updateConstraints() {
    if (self.preferredMaxLayoutWidth != self.bounds.size.width) {
        self.preferredMaxLayoutWidth = self.bounds.size.width
    }
    super.updateConstraints()
}

override var text: String? {
    didSet {
        if let txt = text {
            self.updateAttributed(txt)
        }
    }
}

private func updateAttributed(text: String?) {

    if (text == nil) {
        return
    }

    if (extraLineSpacing > 0 || spacingChar > 0) {

        let attrString = NSMutableAttributedString(string: text!)
        let rng = NSMakeRange(0, attrString.length)

        if (extraLineSpacing > 0) {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = extraLineSpacing
            paragraphStyle.alignment = self.textAlignment

            attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:rng)
        }
        if (spacingChar > 0) {
            attrString.addAttribute(NSKernAttributeName, value:spacingChar, range:rng)
        }

        attrString.addAttribute(NSFontAttributeName, value: self.font, range: rng)

        self.attributedText = attrString

    }
}
}
</code>```

That's the custom UILabel class in IB:

When I delete the name of the custom class label, it displays properly.

When I add it again, it does not disappear. However, the next time it's white again.

When you run the project, it's perfect. I suppose XCode is not rendering it properly, but cannot tell why.

答:
I think you  need to call this:

[super drawRect:rect];

Body:
I have a custom UILabel based class, that does not display properly in the storyboard.

All it displays is a blank label. It happens with both XCode 6 and 7 beta.

import UIKit

@IBDesignable

class CCLabel: UILabel {

@IBInspectable var spacingChar: CGFloat = 0 {
    didSet {
        self.updateAttributed(self.text)
    }
}

@IBInspectable var extraLineSpacing: CGFloat = 0 {
    didSet {
        self.updateAttributed(self.text)
    }
}

override var bounds: CGRect {
    didSet {
        if (bounds.size.width != self.bounds.size.width) {
            self.setNeedsUpdateConstraints()
        }
        super.bounds = bounds
    }
}

override func updateConstraints() {
    if (self.preferredMaxLayoutWidth != self.bounds.size.width) {
        self.preferredMaxLayoutWidth = self.bounds.size.width
    }
    super.updateConstraints()
}

override var text: String? {
    didSet {
        if let txt = text {
            self.updateAttributed(txt)
        }
    }
}

private func updateAttributed(text: String?) {

    if (text == nil) {
        return
    }

    if (extraLineSpacing > 0 || spacingChar > 0) {

        let attrString = NSMutableAttributedString(string: text!)
        let rng = NSMakeRange(0, attrString.length)

        if (extraLineSpacing > 0) {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = extraLineSpacing
            paragraphStyle.alignment = self.textAlignment

            attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:rng)
        }
        if (spacingChar > 0) {
            attrString.addAttribute(NSKernAttributeName, value:spacingChar, range:rng)
        }

        attrString.addAttribute(NSFontAttributeName, value: self.font, range: rng)

        self.attributedText = attrString

    }
}
}

That's the custom UILabel class in IB:

When I delete the name of the custom class label, it displays properly.

When I add it again, it does not disappear. However, the next time it's white again.

When you run the project, it's perfect. I suppose XCode is not rendering it properly, but cannot tell why.


问:
falcon api using gunicorn WORKER TIMEOUT Raspberry Pi
```<code>import falcon
global_var=False

class set_gv(object):
    def on_get(self, req, res):
        """Handles all GET requests."""
        res.status = falcon.HTTP_200  # This is the default status
        global global_var
        global_var=not global_var
        res.body = (str(global_var))

class ask_gv(object):
    def on_get(self, req, res):
        """Handles all GET requests."""
        res.status = falcon.HTTP_200  # This is the default status
        res.body = str(global_var)

# Create the Falcon application object
app = falcon.API()

# Instantiate the TestResource class
set = set_gv()
get = ask_gv()

# Add a route to serve the resource
app.add_route('/set', set)
app.add_route('/get', get)
</code>```

I am using Falcon framework with gunicorn and above code to host an API to hold a variable and change and retrieve it using API calls with command

```<code>`gunicorn -b 0.0.0.0:5000 main:app --reload`
</code>```

When I open http://localhost/set it correctly changes and return the value but after sometime I get following error on console and the varaible value is reset

```<code>[CRITICAL] WORKER TIMEOUT (pid:8545)
</code>```

Any help on how to fix that. Thanks in advance.

答:
So I figure out that worker process is still timeout and restart after some time but I was able to solve the issue with following:

Instead of defining a global variable which gets reset after every timeout I used pickle module to save variable value on disk and change it and read it with every set and get call respectively.

```<code>import pickle
f = open('store.pckl', 'wb')
pickle.dump(False, f)
f.close()

class set_gv(object):
    def on_get(self, req, res):
        """Handles all GET requests."""
        res.status = falcon.HTTP_200  # This is the default status
        f = open('store.pckl', 'rb')
        obj = not pickle.load(f)
        f.close()
        f = open('store.pckl', 'wb')
        pickle.dump(obj, f)
        f.close()
        res.body = (str(obj))

class ask_gv(object):
    def on_get(self, req, res):
        """Handles all GET requests."""
        res.status = falcon.HTTP_200  # This is the default status
        f = open('store.pckl', 'rb')
        obj = pickle.load(f)
        f.close()
        res.body = (str(obj))
</code>```

I added 3 workers to ensure uptime.

gunicorn -b 0.0.0.0:5000 main:app --reload --workers=3

Update: I was able to solve the worker timeout issue, I was running the api server on a Raspberry Pi and the input voltage to it was a little bit less than optimal and was causing the worker timeout issue. Fixing the voltage fixed the issue.

Body:
import falcon
global_var=False

class set_gv(object):
    def on_get(self, req, res):
        """Handles all GET requests."""
        res.status = falcon.HTTP_200  # This is the default status
        global global_var
        global_var=not global_var
        res.body = (str(global_var))

class ask_gv(object):
    def on_get(self, req, res):
        """Handles all GET requests."""
        res.status = falcon.HTTP_200  # This is the default status
        res.body = str(global_var)

# Create the Falcon application object
app = falcon.API()

# Instantiate the TestResource class
set = set_gv()
get = ask_gv()

# Add a route to serve the resource
app.add_route('/set', set)
app.add_route('/get', get)

I am using Falcon framework with gunicorn and above code to host an API to hold a variable and change and retrieve it using API calls with command

`gunicorn -b 0.0.0.0:5000 main:app --reload`

When I open http://localhost/set it correctly changes and return the value but after sometime I get following error on console and the varaible value is reset

[CRITICAL] WORKER TIMEOUT (pid:8545)

Any help on how to fix that. Thanks in advance.

Body:
So I figure out that worker process is still timeout and restart after some time but I was able to solve the issue with following:

Instead of defining a global variable which gets reset after every timeout I used pickle module to save variable value on disk and change it and read it with every set and get call respectively.

import pickle
f = open('store.pckl', 'wb')
pickle.dump(False, f)
f.close()

class set_gv(object):
    def on_get(self, req, res):
        """Handles all GET requests."""
        res.status = falcon.HTTP_200  # This is the default status
        f = open('store.pckl', 'rb')
        obj = not pickle.load(f)
        f.close()
        f = open('store.pckl', 'wb')
        pickle.dump(obj, f)
        f.close()
        res.body = (str(obj))

class ask_gv(object):
    def on_get(self, req, res):
        """Handles all GET requests."""
        res.status = falcon.HTTP_200  # This is the default status
        f = open('store.pckl', 'rb')
        obj = pickle.load(f)
        f.close()
        res.body = (str(obj))

I added 3 workers to ensure uptime.

gunicorn -b 0.0.0.0:5000 main:app --reload --workers=3

Update: I was able to solve the worker timeout issue, I was running the api server on a Raspberry Pi and the input voltage to it was a little bit less than optimal and was causing the worker timeout issue. Fixing the voltage fixed the issue.


问:
JQuery: how to use enter keypress for href submition when focus is in text box
I'm trying to use jquery and flask to change some values in my python script without refreshing the page. I can only submit when I click the link, or have the link selected when i press enter.

Is it possible to have a link submit on an 'Enter' press when the focus is on a different element only (i.e. the text box i'm using to set the value, but not anything else on the page) without making a separate link?

HTML:

```<code> <h3>Change Value</h3>
   <p">New Value: <input type="text" size="5" name="entry"> <br>
     last entry: <span id="result">none</span> <br>
     <a href=# id="set_value">set value</a>
   </p>
</code>```

JAVASCRIPT:

```<code><script type="text/javascript">
  $(function() {
    var submit_form = function(e) {
      $.getJSON($SCRIPT_ROOT + '/_set_beam', {
        q: $('input[name="entry"]').val()
      }, function(data) {
        $('#result').text(data.result[0]);
        $('input[name=q]').focus().select();
      });
      return false;
    };

    $('a#set_value').bind('click', submit_form);
    $('input[type=text]').bind('keydown', function(e) {
      if (e.keyCode == 13) {
        if ( $("set_value").is(":focus") ) {
          submit_form(e);
        }
        //elseif ( $("entry").is(":focus) ) {submit_form(e);}//something like this?
      }
    });
    $('input[name=q]').focus();
  });
</script>
</code>```

PYTHON:

```<code>@app.route('/_set_value')
def set_value():
    """set a new value"""
    entry = request.args.get('entry', default='nothing', type=str)
    if entry == 'something':
        result = doSomething(entry):
    else:
        result = doSomethingEelse(entry)
    return jsonify( result=[entry] )
</code>```

答:
You can use the default behavior of a <form> tag that will do exactly that, and bind your action to the submit event.

This way, you shorten your code and won't worry in the future about a new type of input being added and not supported by your script.

HTML

```<code><form id="my_form">
   <h3>Change Value</h3>
   <p>New Value: <input type="text" size="5" name="entry"> <br>
     last entry: <span id="result">none</span> <br>
     <a href=# id="set_value">set value</a>
   </p>
</form>
</code>```

JavaScript

```<code>$('my_form').submit( function(e) { // submit handler
      $.getJSON($SCRIPT_ROOT + '/_set_beam', {
        q: $('input[name="entry"]').val()
      }, function(data) {
        $('#result').text(data.result[0]);
        $('input[name=q]').focus().select();
      });
});
</code>```

Personally, I prefer to use a lot of default behaviors, because they not only keep your code short but they end up aging better. When web conventions evolve, everything that is heavily custom made will fail to get better, while default stuff will keep changing and getting more and more easy to use and bug free over time.

Also, using a form input for something that is "submitable?" is better for the user, because it will honor any special handling or special treatment that the browser of his choice is adding to forms in general.

Body:
I'm trying to use jquery and flask to change some values in my python script without refreshing the page. I can only submit when I click the link, or have the link selected when i press enter.

Is it possible to have a link submit on an 'Enter' press when the focus is on a different element only (i.e. the text box i'm using to set the value, but not anything else on the page) without making a separate link?

HTML:

Change Value

New Value: <input type="text" size="5" name="entry">

     last entry: none

     set value

JAVASCRIPT:

PYTHON:

@app.route('/_set_value')
def set_value():
    """set a new value"""
    entry = request.args.get('entry', default='nothing', type=str)
    if entry == 'something':
        result = doSomething(entry):
    else:
        result = doSomethingEelse(entry)
    return jsonify( result=[entry] )

Body:
You can use the default behavior of a <form> tag that will do exactly that, and bind your action to the submit event.

This way, you shorten your code and won't worry in the future about a new type of input being added and not supported by your script.

HTML

<form id="my_form">
   <h3>Change Value</h3>
   <p>New Value: <input type="text" size="5" name="entry"> <br>
     last entry: <span id="result">none</span> <br>
     <a href=# id="set_value">set value</a>
   </p>
</form>

JavaScript

$('my_form').submit( function(e) { // submit handler
      $.getJSON($SCRIPT_ROOT + '/_set_beam', {
        q: $('input[name="entry"]').val()
      }, function(data) {
        $('#result').text(data.result[0]);
        $('input[name=q]').focus().select();
      });
});

Personally, I prefer to use a lot of default behaviors, because they not only keep your code short but they end up aging better. When web conventions evolve, everything that is heavily custom made will fail to get better, while default stuff will keep changing and getting more and more easy to use and bug free over time.

Also, using a form input for something that is "submitable?" is better for the user, because it will honor any special handling or special treatment that the browser of his choice is adding to forms in general.


问:
How to get remaining days for certain birthday?
When I'm calculating my age, the code below showing "xxx days left for your next birthday". But I want to know, how many days left for my certain birthday. (i.e: I want to know how many days left for my 30th birthday. The result should be like this "xxx days left for your 30th birthday" instead of next birthday.)
What change I need to do?

function wr_document() {
  var w = new Date();
  var s_d = w.getDate();
  var s_m = w.getMonth() + 1;
  var s_y = w.getFullYear();

  document.cir.len11.value = s_d;
  document.cir.len12.value = s_m;
  document.cir.len13.value = s_y;
}

function isNum(arg) {
  var args = arg;
  if (args == "" || args == null || args.length == 0) {
    return false;
  }
  args = args.toString();
  for (var i = 0; i < args.length; i++) {
    if ((args.substring(i, i + 1) < "0" || args.substring(i, i + 1) > "9") && args.substring(i, i + 1) != ".") {
      return false;
    }
  }
  return true;
}

function checkday(aa) {
  var val = aa.value;
  var valc = val.substring(0, 1);
  if (val.length > 0 && val.length < 3) {
    if (!isNum(val) || val == 0) {
      aa.value = "";
    } else if (val < 1 || val > 31) {
      aa.value = valc;
    }
  } else if (val.length > 2) {
    val = val.substring(0, 2);
    aa.value = val;
  }
}

function checkmon(aa) {
  var val = aa.value;
  var valc = val.substring(0, 1);
  if (val.length > 0 && val.length < 3) {
    if (!isNum(val) || val == 0) {
      aa.value = "";
    } else if (val < 1 || val > 12) {
      aa.value = valc;
    }
  } else if (val.length > 2) {
    val = val.substring(0, 2);
    aa.value = val;
  }
}

function checkyear(aa) {
  var val = aa.value;
  var valc = val.substring(0, (val.length - 1));
  if (val.length > 0 && val.length < 7) {
    if (!isNum(val) || val == 0) {
      aa.value = valc;
    } else if (val < 1 || val > 275759) {
      aa.value = "";
    }
  } else if (val.length > 4) {
    aa.value = valc;
  }
}

function checkleapyear(datea) {
  if (datea.getYear() % 4 == 0) {
    if (datea.getYear() % 10 != 0) {
      return true;
    } else {
      if (datea.getYear() % 400 == 0)
        return true;
      else
        return false;
    }
  }
  return false;
}

function DaysInMonth(Y, M) {
  with(new Date(Y, M, 1, 12)) {
    setDate(0);
    return getDate();
  }
}

function datediff(date1, date2) {
  var y1 = date1.getFullYear(),
    m1 = date1.getMonth(),
    d1 = date1.getDate(),
    y2 = date2.getFullYear(),
    m2 = date2.getMonth(),
    d2 = date2.getDate();
  if (d1 < d2) {
    m1--;
    d1 += DaysInMonth(y2, m2);
  }
  if (m1 < m2) {
    y1--;
    m1 += 12;
  }
  return [y1 - y2, m1 - m2, d1 - d2];
}

function calage() {
  var curday = document.cir.len11.value;
  var curmon = document.cir.len12.value;
  var curyear = document.cir.len13.value;
  var calday = document.cir.len21.value;
  var calmon = document.cir.len22.value;
  var calyear = document.cir.len23.value;
  if (curday == "" || curmon == "" || curyear == "" || calday == "" || calmon == "" || calyear == "") {
    alert("Please fill all the values and click 'Go'");
  } else if (curday == calday && curmon == calmon && curyear == calyear) {
    alert("Today your birthday & Your age is 0 years old")
  } else {
    var curd = new Date(curyear, curmon - 1, curday);
    var cald = new Date(calyear, calmon - 1, calday);
    var diff = Date.UTC(curyear, curmon, curday, 0, 0, 0) -
      Date.UTC(calyear, calmon, calday, 0, 0, 0);
    var dife = datediff(curd, cald);
    document.cir.val.value = dife[0] + " years, " + dife[1] + " months, and " + dife[2] + " days";
    var secleft = diff / 1000 / 60;
    document.cir.val3.value = secleft + " minutes since your birth";
    var hrsleft = secleft / 60;
    document.cir.val2.value = hrsleft + " hours since your birth";
    var daysleft = hrsleft / 24;
    document.cir.val1.value = daysleft + " days since your birth";
    //alert(""+parseInt(calyear)+"--"+dife[0]+"--"+1);
    var as = parseInt(calyear) + dife[0] + 1;
    var diff = Date.UTC(as, calmon, calday, 0, 0, 0) -
      Date.UTC(curyear, curmon, curday, 0, 0, 0);
    var datee = diff / 1000 / 60 / 60 / 24;
    document.cir.val4.value = datee + " days left for your next birthday";
  }
}

function color(test) {
  for (var j = 7; j < 12; j++) {
    var myI = document.getElementsByTagName("input").item(j);
    //myI.setAttribute("style",ch);
    myI.style.backgroundColor = test;
  }
}

function color1(test) {
  var myI = document.getElementsByTagName("table").item(0);
  //myI.setAttribute("style",ch);
  myI.style.backgroundColor = test;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cal-container {
  width: 540px;
  margin: 10px auto 0;
}

#age-calculator {
  background: none repeat scroll 0 0 #DDDDDD;
  border: 1px solid #BEBEBE;
  padding-left: 20px;
}

.calc {
  border-color: #AAAAAA #999999 #929292 #AAAAAA;
  border-style: solid;
  border-width: 1px 2px 2px 1px;
  padding: 2px 30px 3px;
  height: 27px;
}

.calc:active {
  border-color: #AAAAAA #999999 #929292 #AAAAAA;
  border-style: solid;
  border-width: 1px;
}</code>```

<title>Age calculator </title>

                Age Calculator

                Calculate your age in days, years, minutes, seconds. Know how many days are left for your next birthday.

                                <form name="cir">

 Today's Date is:

                                          Date -
                                          <input class="innerc resform" name="len11" onkeyup="checkday(this)" size="2" type="text" value="" /> Month -
                                          <input class="innerc resform" name="len12" onkeyup="checkmon(this)" size="2" type="text" value="" /> Year -
                                          <input class="innerc resform" name="len13" onkeyup="checkyear(this)" size="4" type="text" value="" />

                                         Enter Your Date of Birth :

                                          Date -
                                          <input class="innerc resform" name="len21" onkeyup="checkday(this)" size="2" type="text" /> Month -
                                          <input class="innerc resform" name="len22" onkeyup="checkmon(this)" size="2" type="text" /> Year -
                                          <input class="innerc resform" name="len23" onkeyup="checkyear(this)" size="4" type="text" />

                                          <input class="calc" name="but" onclick="calage()" type="button" value=" Go " />

                                           Your Age is

                                          <input class="resform" name="val" readonly="" size="36" type="text" />

                                           Your Age in Days

                                          <input class="resform" name="val1" readonly="" size="36" type="text" />

                                           Your Age in Hours

                                          <input class="resform" name="val2" readonly="" size="36" type="text" /> (Approximate)

                                           Your Age in Minutes

                                          <input class="resform" name="val3" readonly="" size="36" type="text" /> (Approximate)

                                          <input class="innerc resform" name="val4" readonly="" size="36" type="text" />

                                </form>

```

答:
Not clear about purpose of your whole code, but based on your question following script may help you.

// Let below variables store your birth date
var day = 13;
var month = 03;
var year = 1993;
var x = 30; // Finding 30th birthday
var xthBirthday = new Date((year + x), (month - 1), day); // As month starts with 0
var timeForXthBirthday = xthBirthday.getTime() - Date.now();
var noOfDaysForXthBirthday = Math.ceil(timeForXthBirthday / (1000 * 60 * 60 * 24)); // No. of days left for your xth birthday
document.write(noOfDaysForXthBirthday+" days left for your "+x+"th birthday.");```

Hope this helps.

Body:
When I'm calculating my age, the code below showing "xxx days left for your next birthday". But I want to know, how many days left for my certain birthday. (i.e: I want to know how many days left for my 30th birthday. The result should be like this "xxx days left for your 30th birthday" instead of next birthday.)
What change I need to do?

function wr_document() {
  var w = new Date();
  var s_d = w.getDate();
  var s_m = w.getMonth() + 1;
  var s_y = w.getFullYear();

  document.cir.len11.value = s_d;
  document.cir.len12.value = s_m;
  document.cir.len13.value = s_y;
}

function isNum(arg) {
  var args = arg;
  if (args == "" || args == null || args.length == 0) {
    return false;
  }
  args = args.toString();
  for (var i = 0; i < args.length; i++) {
    if ((args.substring(i, i + 1) < "0" || args.substring(i, i + 1) > "9") && args.substring(i, i + 1) != ".") {
      return false;
    }
  }
  return true;
}

function checkday(aa) {
  var val = aa.value;
  var valc = val.substring(0, 1);
  if (val.length > 0 && val.length < 3) {
    if (!isNum(val) || val == 0) {
      aa.value = "";
    } else if (val < 1 || val > 31) {
      aa.value = valc;
    }
  } else if (val.length > 2) {
    val = val.substring(0, 2);
    aa.value = val;
  }
}

function checkmon(aa) {
  var val = aa.value;
  var valc = val.substring(0, 1);
  if (val.length > 0 && val.length < 3) {
    if (!isNum(val) || val == 0) {
      aa.value = "";
    } else if (val < 1 || val > 12) {
      aa.value = valc;
    }
  } else if (val.length > 2) {
    val = val.substring(0, 2);
    aa.value = val;
  }
}

function checkyear(aa) {
  var val = aa.value;
  var valc = val.substring(0, (val.length - 1));
  if (val.length > 0 && val.length < 7) {
    if (!isNum(val) || val == 0) {
      aa.value = valc;
    } else if (val < 1 || val > 275759) {
      aa.value = "";
    }
  } else if (val.length > 4) {
    aa.value = valc;
  }
}

function checkleapyear(datea) {
  if (datea.getYear() % 4 == 0) {
    if (datea.getYear() % 10 != 0) {
      return true;
    } else {
      if (datea.getYear() % 400 == 0)
        return true;
      else
        return false;
    }
  }
  return false;
}

function DaysInMonth(Y, M) {
  with(new Date(Y, M, 1, 12)) {
    setDate(0);
    return getDate();
  }
}

function datediff(date1, date2) {
  var y1 = date1.getFullYear(),
    m1 = date1.getMonth(),
    d1 = date1.getDate(),
    y2 = date2.getFullYear(),
    m2 = date2.getMonth(),
    d2 = date2.getDate();
  if (d1 < d2) {
    m1--;
    d1 += DaysInMonth(y2, m2);
  }
  if (m1 < m2) {
    y1--;
    m1 += 12;
  }
  return [y1 - y2, m1 - m2, d1 - d2];
}

function calage() {
  var curday = document.cir.len11.value;
  var curmon = document.cir.len12.value;
  var curyear = document.cir.len13.value;
  var calday = document.cir.len21.value;
  var calmon = document.cir.len22.value;
  var calyear = document.cir.len23.value;
  if (curday == "" || curmon == "" || curyear == "" || calday == "" || calmon == "" || calyear == "") {
    alert("Please fill all the values and click 'Go'");
  } else if (curday == calday && curmon == calmon && curyear == calyear) {
    alert("Today your birthday & Your age is 0 years old")
  } else {
    var curd = new Date(curyear, curmon - 1, curday);
    var cald = new Date(calyear, calmon - 1, calday);
    var diff = Date.UTC(curyear, curmon, curday, 0, 0, 0) -
      Date.UTC(calyear, calmon, calday, 0, 0, 0);
    var dife = datediff(curd, cald);
    document.cir.val.value = dife[0] + " years, " + dife[1] + " months, and " + dife[2] + " days";
    var secleft = diff / 1000 / 60;
    document.cir.val3.value = secleft + " minutes since your birth";
    var hrsleft = secleft / 60;
    document.cir.val2.value = hrsleft + " hours since your birth";
    var daysleft = hrsleft / 24;
    document.cir.val1.value = daysleft + " days since your birth";
    //alert(""+parseInt(calyear)+"--"+dife[0]+"--"+1);
    var as = parseInt(calyear) + dife[0] + 1;
    var diff = Date.UTC(as, calmon, calday, 0, 0, 0) -
      Date.UTC(curyear, curmon, curday, 0, 0, 0);
    var datee = diff / 1000 / 60 / 60 / 24;
    document.cir.val4.value = datee + " days left for your next birthday";
  }
}

function color(test) {
  for (var j = 7; j < 12; j++) {
    var myI = document.getElementsByTagName("input").item(j);
    //myI.setAttribute("style",ch);
    myI.style.backgroundColor = test;
  }
}

function color1(test) {
  var myI = document.getElementsByTagName("table").item(0);
  //myI.setAttribute("style",ch);
  myI.style.backgroundColor = test;
}

.cal-container {
  width: 540px;
  margin: 10px auto 0;
}

#age-calculator {
  background: none repeat scroll 0 0 #DDDDDD;
  border: 1px solid #BEBEBE;
  padding-left: 20px;
}

.calc {
  border-color: #AAAAAA #999999 #929292 #AAAAAA;
  border-style: solid;
  border-width: 1px 2px 2px 1px;
  padding: 2px 30px 3px;
  height: 27px;
}

.calc:active {
  border-color: #AAAAAA #999999 #929292 #AAAAAA;
  border-style: solid;
  border-width: 1px;
}

<title>Age calculator </title>

                Age Calculator

                Calculate your age in days, years, minutes, seconds. Know how many days are left for your next birthday.

                                <form name="cir">

 Today's Date is:

                                          Date -
                                          <input class="innerc resform" name="len11" onkeyup="checkday(this)" size="2" type="text" value="" /> Month -
                                          <input class="innerc resform" name="len12" onkeyup="checkmon(this)" size="2" type="text" value="" /> Year -
                                          <input class="innerc resform" name="len13" onkeyup="checkyear(this)" size="4" type="text" value="" />

                                         Enter Your Date of Birth :

                                          Date -
                                          <input class="innerc resform" name="len21" onkeyup="checkday(this)" size="2" type="text" /> Month -
                                          <input class="innerc resform" name="len22" onkeyup="checkmon(this)" size="2" type="text" /> Year -
                                          <input class="innerc resform" name="len23" onkeyup="checkyear(this)" size="4" type="text" />

                                          <input class="calc" name="but" onclick="calage()" type="button" value=" Go " />

                                           Your Age is

                                          <input class="resform" name="val" readonly="" size="36" type="text" />

                                           Your Age in Days

                                          <input class="resform" name="val1" readonly="" size="36" type="text" />

                                           Your Age in Hours

                                          <input class="resform" name="val2" readonly="" size="36" type="text" /> (Approximate)

                                           Your Age in Minutes

                                          <input class="resform" name="val3" readonly="" size="36" type="text" /> (Approximate)

                                          <input class="innerc resform" name="val4" readonly="" size="36" type="text" />

                                </form>

Body:
Not clear about purpose of your whole code, but based on your question following script may help you.

// Let below variables store your birth date
var day = 13;
var month = 03;
var year = 1993;
var x = 30; // Finding 30th birthday
var xthBirthday = new Date((year + x), (month - 1), day); // As month starts with 0
var timeForXthBirthday = xthBirthday.getTime() - Date.now();
var noOfDaysForXthBirthday = Math.ceil(timeForXthBirthday / (1000 * 60 * 60 * 24)); // No. of days left for your xth birthday
document.write(noOfDaysForXthBirthday+" days left for your "+x+"<sup>th</sup> birthday.");

Hope this helps.


问:
Youtube API how to get video info
When you right click on the video and say "show video info", there is popup that shows fps, frames dropped etc in real time with a timestamp.

I tried to look in the API documentation but couldn't find how this data could be retrieved.

I would like to store this realtime video info data in a file and do post analysis based on time to understand video streaming quality.

Thanks in advance.

答:
You're going to have to use the new v3 API. You can sign up for a YouTube key here: https://console.developers.google.com/apis/api/youtube.googleapis.com

Documentation: https://developers.google.com/youtube/v3/docs/videos/list

To get the actual video info you can then use this URL:

```<code>https://www.googleapis.com/youtube/v3/videos?id={VIDEO_ID}&part=snippet%2CcontentDetails%2Cstatistics &key={YOUR_API_KEY}
</code>```

Title: Youtube API how to get video info

Body:
You're going to have to use the new v3 API. You can sign up for a YouTube key here: https://console.developers.google.com/apis/api/youtube.googleapis.com

Documentation: https://developers.google.com/youtube/v3/docs/videos/list

To get the actual video info you can then use this URL:

https://www.googleapis.com/youtube/v3/videos?id={VIDEO_ID}&part=snippet%2CcontentDetails%2Cstatistics &key={YOUR_API_KEY}


问:
Service docker start not work(daemon), ubuntu-15.10, To run dockerfile with intelliJ
I have installed docker on ubuntu 15.10 but it does not start, these are the console outputs, I'm new with this from docker, try installing docker from this tutorial https://tecadmin.net/install-and-manage-docker-on-ubuntu/

My interest is to be able to run my dockerfile from intellij

service docker start

```<code>root@rubnPC:/var/lib/docker# service docker start
Job for docker.service failed because the control process exited with error
code. See "systemctl status docker.service" and "journalctl -xe" for details.
</code>```

systemctl status docker.service

```<code>root@rubnPC:/var/lib/docker# systemctl status docker.service
● docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset:
enabled)
Active: failed (Result: exit-code) since sáb 2017-06-03 18:24:42 VET; 3min
18s ago
Docs: https://docs.docker.com
Process: 21270 ExecStart=/usr/bin/dockerd -H fd:// (code=exited,
status=1/FAILURE)
Main PID: 21270 (code=exited, status=1/FAILURE)

jun 03 18:24:42 rubnPC systemd[1]: Starting Docker Application Container
Engine...
jun 03 18:24:42 rubnPC dockerd[21270]: time="2017-06-03T18:24:42.614560352-
04:30" le...id"
jun 03 18:24:42 rubnPC systemd[1]: docker.service: Main process exited,
code=exited,...URE
jun 03 18:24:42 rubnPC systemd[1]: Failed to start Docker Application
Container Engine.
jun 03 18:24:42 rubnPC systemd[1]: docker.service: Unit entered failed
state.
jun 03 18:24:42 rubnPC systemd[1]: docker.service: Failed with result 'exit-
code'.
Hint: Some lines were ellipsized, use -l to show in full.
</code>```

journalctl -xe

```<code>root@rubnPC:/var/lib/docker# journalctl -xe
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has begun starting up.
jun 03 18:24:42 rubnPC dockerd[21270]: time="2017-06-03T18:24:42.614560352-
04:30" level=fa
jun 03 18:24:42 rubnPC systemd[1]: docker.service: Main process exited,
code=exited, statu
jun 03 18:24:42 rubnPC systemd[1]: Failed to start Docker Application
Container Engine.
-- Subject: Unit docker.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has failed.
--
-- The result is failed.
jun 03 18:24:42 rubnPC systemd[1]: docker.service: Unit entered failed
state.
jun 03 18:24:42 rubnPC systemd[1]: docker.service: Failed with result 'exit-
code'.
jun 03 18:24:42 rubnPC polkitd(authority=local)[865]: Unregistered
Authentication Agent fo
jun 03 18:31:24 rubnPC polkitd(authority=local)[865]: Registered
Authentication Agent for
jun 03 18:31:24 rubnPC systemd[1]: Listening on Docker Socket for the API.
-- Subject: Unit docker.socket has finished start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.socket has finished starting up.
</code>```

System-Info

```<code>  rubn _> lsb_release -a
  No LSB modules are available.
  Distributor ID:   Ubuntu
  Description:  Ubuntu 15.10
  Release:  15.10
  Codename: wily
</code>```

Docker version

```<code>rubn _> docker version
Client:
Version:      1.12.6
API version:  1.24
Go version:   go1.6.4
Git commit:   78d1802
Built:        Tue Jan 10 20:32:39 2017
OS/Arch:      linux/amd64
Cannot connect to the Docker daemon. Is the docker daemon running on this
host?
</code>```

Kernel Version

```<code>rubn _> uname -a
Linux rubnPC 4.2.0-42-generic #49-Ubuntu SMP Tue Jun 28 21:26:26 UTC 2016
x86_64 x86_64 x86_64 GNU/Linux
</code>```

UPDATE: dockerfile

```<code># Set the WILDFLY_VERSION env variable ENV WILDFLY_VERSION 10.0.0.Final ENV WILDFLY_SHA1 c0dd7552c5207b0d116a9c25eb94d10b4f375549
ENV JBOSS_HOME /opt/jboss/wildfly

# Add the WildFly distribution to /opt, and make wildfly the owner of the extracted tar content
# Make sure the distribution is available from a well-known place
RUN cd $HOME \
    && curl -O https://download.jboss.org/wildfly/$WILDFLY_VERSION/wildfly-$WILDFLY_VERSION.tar.gz \
    && sha1sum wildfly-$WILDFLY_VERSION.tar.gz | grep $WILDFLY_SHA1 \
    && tar xf wildfly-$WILDFLY_VERSION.tar.gz \
    && mv $HOME/wildfly-$WILDFLY_VERSION $JBOSS_HOME \
    && rm wildfly-$WILDFLY_VERSION.tar.gz

# Ensure signals are forwarded to the JVM process correctly for graceful shutdown
ENV LAUNCH_JBOSS_IN_BACKGROUND true

# Expose the ports we're interested in
EXPOSE 8080

# Set the default command to run on boot
# This will boot WildFly in the standalone mode and bind to all interface
CMD ["/opt/jboss/wildfly/bin/standalone.sh", "-b", "0.0.0.0"]

ADD ROOT.war /opt/jboss/wildfly/standalone/deployments/
</code>```

/etc/default/docker

```<code># Docker Upstart and SysVinit configuration file

#
# THIS FILE DOES NOT APPLY TO SYSTEMD
#
#   Please see the documentation for "systemd drop-ins":
#   https://docs.docker.com/engine/articles/systemd/
#

# Customize location of Docker binary (especially for development testing).
#DOCKERD="/usr/local/bin/dockerd"

# Use DOCKER_OPTS to modify the daemon startup options.
#DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"

# If you need Docker to use an HTTP proxy, it can also be specified here.
#export http_proxy="http://127.0.0.1:3128/"

# This is also a handy place to tweak where Docker's temporary files go.
#export TMPDIR="/mnt/bigdrive/docker-tmp"
</code>```

Solved

Docker can't connect to docker daemon

答:
Can you post the contents of /etc/default/docker?

It seems you have invalid content that is failing the startup. I'm guessing you have fd:// in it. If you do, just remove that & then try restarting docker just as before.

Body:
I have installed docker on ubuntu 15.10 but it does not start, these are the console outputs, I'm new with this from docker, try installing docker from this tutorial https://tecadmin.net/install-and-manage-docker-on-ubuntu/

My interest is to be able to run my dockerfile from intellij

service docker start

root@rubnPC:/var/lib/docker# service docker start
Job for docker.service failed because the control process exited with error
code. See "systemctl status docker.service" and "journalctl -xe" for details.

systemctl status docker.service

root@rubnPC:/var/lib/docker# systemctl status docker.service
● docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset:
enabled)
Active: failed (Result: exit-code) since sáb 2017-06-03 18:24:42 VET; 3min
18s ago
Docs: https://docs.docker.com
Process: 21270 ExecStart=/usr/bin/dockerd -H fd:// (code=exited,
status=1/FAILURE)
Main PID: 21270 (code=exited, status=1/FAILURE)

jun 03 18:24:42 rubnPC systemd[1]: Starting Docker Application Container
Engine...
jun 03 18:24:42 rubnPC dockerd[21270]: time="2017-06-03T18:24:42.614560352-
04:30" le...id"
jun 03 18:24:42 rubnPC systemd[1]: docker.service: Main process exited,
code=exited,...URE
jun 03 18:24:42 rubnPC systemd[1]: Failed to start Docker Application
Container Engine.
jun 03 18:24:42 rubnPC systemd[1]: docker.service: Unit entered failed
state.
jun 03 18:24:42 rubnPC systemd[1]: docker.service: Failed with result 'exit-
code'.
Hint: Some lines were ellipsized, use -l to show in full.

journalctl -xe

root@rubnPC:/var/lib/docker# journalctl -xe
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has begun starting up.
jun 03 18:24:42 rubnPC dockerd[21270]: time="2017-06-03T18:24:42.614560352-
04:30" level=fa
jun 03 18:24:42 rubnPC systemd[1]: docker.service: Main process exited,
code=exited, statu
jun 03 18:24:42 rubnPC systemd[1]: Failed to start Docker Application
Container Engine.
-- Subject: Unit docker.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has failed.
--
-- The result is failed.
jun 03 18:24:42 rubnPC systemd[1]: docker.service: Unit entered failed
state.
jun 03 18:24:42 rubnPC systemd[1]: docker.service: Failed with result 'exit-
code'.
jun 03 18:24:42 rubnPC polkitd(authority=local)[865]: Unregistered
Authentication Agent fo
jun 03 18:31:24 rubnPC polkitd(authority=local)[865]: Registered
Authentication Agent for
jun 03 18:31:24 rubnPC systemd[1]: Listening on Docker Socket for the API.
-- Subject: Unit docker.socket has finished start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.socket has finished starting up.

System-Info

  rubn _> lsb_release -a
  No LSB modules are available.
  Distributor ID:   Ubuntu
  Description:  Ubuntu 15.10
  Release:  15.10
  Codename: wily

Docker version

rubn _> docker version
Client:
Version:      1.12.6
API version:  1.24
Go version:   go1.6.4
Git commit:   78d1802
Built:        Tue Jan 10 20:32:39 2017
OS/Arch:      linux/amd64
Cannot connect to the Docker daemon. Is the docker daemon running on this
host?

Kernel Version

rubn _> uname -a
Linux rubnPC 4.2.0-42-generic #49-Ubuntu SMP Tue Jun 28 21:26:26 UTC 2016
x86_64 x86_64 x86_64 GNU/Linux

UPDATE: dockerfile

# Set the WILDFLY_VERSION env variable ENV WILDFLY_VERSION 10.0.0.Final ENV WILDFLY_SHA1 c0dd7552c5207b0d116a9c25eb94d10b4f375549
ENV JBOSS_HOME /opt/jboss/wildfly

# Add the WildFly distribution to /opt, and make wildfly the owner of the extracted tar content
# Make sure the distribution is available from a well-known place
RUN cd $HOME \
    && curl -O https://download.jboss.org/wildfly/$WILDFLY_VERSION/wildfly-$WILDFLY_VERSION.tar.gz \
    && sha1sum wildfly-$WILDFLY_VERSION.tar.gz | grep $WILDFLY_SHA1 \
    && tar xf wildfly-$WILDFLY_VERSION.tar.gz \
    && mv $HOME/wildfly-$WILDFLY_VERSION $JBOSS_HOME \
    && rm wildfly-$WILDFLY_VERSION.tar.gz

# Ensure signals are forwarded to the JVM process correctly for graceful shutdown
ENV LAUNCH_JBOSS_IN_BACKGROUND true

# Expose the ports we're interested in
EXPOSE 8080

# Set the default command to run on boot
# This will boot WildFly in the standalone mode and bind to all interface
CMD ["/opt/jboss/wildfly/bin/standalone.sh", "-b", "0.0.0.0"]

ADD ROOT.war /opt/jboss/wildfly/standalone/deployments/

/etc/default/docker

# Docker Upstart and SysVinit configuration file

#
# THIS FILE DOES NOT APPLY TO SYSTEMD
#
#   Please see the documentation for "systemd drop-ins":
#   https://docs.docker.com/engine/articles/systemd/
#

# Customize location of Docker binary (especially for development testing).
#DOCKERD="/usr/local/bin/dockerd"

# Use DOCKER_OPTS to modify the daemon startup options.
#DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"

# If you need Docker to use an HTTP proxy, it can also be specified here.
#export http_proxy="http://127.0.0.1:3128/"

# This is also a handy place to tweak where Docker's temporary files go.
#export TMPDIR="/mnt/bigdrive/docker-tmp"

Solved

Docker can't connect to docker daemon


问:
Reading text file and present data in python matplotlib
I have tried to use python csv to read txt file then presented in graph using python matplotlib

simple of data in text file:

```<code>261 P 0.18 0 834 64627 0 768 0 320 834 64627 0 768 0 320 (radio 1.17% / 1.17% tx 0.00% / 0.00% listen 1.17% / 1.17%)
</code>```

and this python script for reading the file but it does not work and no error message.

```<code>import csv
import matplotlib.pyplot as plt

# for P lines
#0-> str,
#1 -> clock_time(),2-> P, 3->rimeaddr_node_addr.u8[0],rimeaddr_node_addr.u8[1], 4-> seqno,
#5 -> all_cpu,6-> all_lpm,7-> all_transmit,8-> all_listen,9-> all_idle_transmit,10-> all_idle_listen,
#11->cpu,12-> lpm,13-> transmit,14-> listen, 15 ->idle_transmit, 16 -> idle_listen, [RADIO STATISTICS...]

from collections import defaultdict
cpuOverTime =  defaultdict(list)

with open('loglistener.txt', 'rb') as f:
    reader = csv.reader(f,delimiter=' ')
    for row in reader:
        if row[2] is 'P':
            cpuOverTime[row[3]].append(row[11])

for i in cpuOverTime:
    plt.plot(cpuOverTime[i])
plt.show()
##########
</code>```

答:
In Python, as is common with most programming languages, offsets start at 0 not 1.

From your sample data we can see that P is the 2nd space-delimited item in the row and therefore has index of 1:

```<code>Offset    0   | 1  | 2    | 3 | 4   | 5     | 6
Row       261 | P  | 0.18 | 0 | 834 | 64627 | 0
</code>```

To fix the problem simply change the index to be 1:

```<code>with open('loglistener.txt', 'rb') as f:
    reader = csv.reader(f,delimiter=' ')
    for row in reader:
        if row[1] is 'P':
            cpuOverTime[row[3]].append(row[11])
</code>```

I haven't checked but you likely have the same problem with row[3] and row[11]

Body:
I have tried to use python csv to read txt file then presented in graph using python matplotlib

simple of data in text file:

261 P 0.18 0 834 64627 0 768 0 320 834 64627 0 768 0 320 (radio 1.17% / 1.17% tx 0.00% / 0.00% listen 1.17% / 1.17%)

and this python script for reading the file but it does not work and no error message.

import csv
import matplotlib.pyplot as plt

# for P lines
#0-> str,
#1 -> clock_time(),2-> P, 3->rimeaddr_node_addr.u8[0],rimeaddr_node_addr.u8[1], 4-> seqno,
#5 -> all_cpu,6-> all_lpm,7-> all_transmit,8-> all_listen,9-> all_idle_transmit,10-> all_idle_listen,
#11->cpu,12-> lpm,13-> transmit,14-> listen, 15 ->idle_transmit, 16 -> idle_listen, [RADIO STATISTICS...]

from collections import defaultdict
cpuOverTime =  defaultdict(list)

with open('loglistener.txt', 'rb') as f:
    reader = csv.reader(f,delimiter=' ')
    for row in reader:
        if row[2] is 'P':
            cpuOverTime[row[3]].append(row[11])

for i in cpuOverTime:
    plt.plot(cpuOverTime[i])
plt.show()
##########

Body:
In Python, as is common with most programming languages, offsets start at 0 not 1.

From your sample data we can see that P is the 2nd space-delimited item in the row and therefore has index of 1:

Offset    0   | 1  | 2    | 3 | 4   | 5     | 6
Row       261 | P  | 0.18 | 0 | 834 | 64627 | 0

To fix the problem simply change the index to be 1:

with open('loglistener.txt', 'rb') as f:
    reader = csv.reader(f,delimiter=' ')
    for row in reader:
        if row[1] is 'P':
            cpuOverTime[row[3]].append(row[11])

I haven't checked but you likely have the same problem with row[3] and row[11]


答:
It is not right to update the state of a parent component directly from the child. The first version of <SelectWarehouse /> with updateTarget as func is right.

Also, it is not necessary the store the warehouseId in the state in the child component. The warehouseId can be passed as props to the child component.

```<code><SelectWarehouse
  updateTarget={( ghostValue ) => {
    this.setState( {
      warehouseId: ghostValue
    })
  }}
  warehouseId={this.state.warehouseId}
/>
</code>```

Title: Updating state from child component reactjs

Body:
It is not right to update the state of a parent component directly from the child. The first version of <SelectWarehouse /> with updateTarget as func is right.

Also, it is not necessary the store the warehouseId in the state in the child component. The warehouseId can be passed as props to the child component.

<SelectWarehouse
  updateTarget={( ghostValue ) => {
    this.setState( {
      warehouseId: ghostValue
    })
  }}
  warehouseId={this.state.warehouseId}
/>


问:
Disconnection using HTTPS with Nodemcu
I am using the following build:

```<code>NodeMCU custom build by frightanic.com
.branch: master
.commit: c8ac5cfb912ff206b03dd7c60ffbb2dafb83fe5e
.SSL: true
.modules: file,gpio,http,i2c,net,node,spi,tmr,uart,wifi,tls
 build .built on: 2017-06-03 03:24
 powered by Lua 5.1.4 on SDK 2.1.0(116b762)
</code>```

Using the http module I can succesfully make a get call:

```<code>> http.get("http://httpbin.org/ip", nil, function(code, data)
if (code < 0) then
  print("HTTP request failed")
else
  print(code, data)
end
end)>> >>
> 200   {
"origin": "61.69.19.186"
}
</code>```

Making an equivalent call using https causes a timeout:

```<code>http.get("https://httpbin.org/ip", nil, function(code, data)
if (code < 0) then
  print("HTTP request failed")
else
  print(code, data)
end
end)>> >>
</code>```

with the following messages shown on the console:

```<code>HTTP client: Disconnected with error: 9
HTTP client: Connection timeout
</code>```

A couple of other similar questions from about a year ago talk about fixes required for net module and a specific version of SSL implementation required to call httpbin.org:

HTTPS (SSL) get request with NodeMCU

HTTPS get requests with NodeMCU and ESP8266

The build was created today with the TLS/SSL support by mbedTLS.

答:
Rather than in a comment I'm offering this as an "answer" so the question can be closed afterwards (helps those who watch the nodemcu tag here).

This is a known issue tracked at https://github.com/nodemcu/nodemcu-firmware/issues/1707. It seems something broke with Espressif SDK upgrade 2.0 wrt establishing secure HTTP connections.

Title: Disconnection using HTTPS with Nodemcu

Body:
I am using the following build:

NodeMCU custom build by frightanic.com
.branch: master
.commit: c8ac5cfb912ff206b03dd7c60ffbb2dafb83fe5e
.SSL: true
.modules: file,gpio,http,i2c,net,node,spi,tmr,uart,wifi,tls
 build .built on: 2017-06-03 03:24
 powered by Lua 5.1.4 on SDK 2.1.0(116b762)

Using the http module I can succesfully make a get call:

> http.get("http://httpbin.org/ip", nil, function(code, data)
if (code < 0) then
  print("HTTP request failed")
else
  print(code, data)
end
end)>> >>
> 200   {
"origin": "61.69.19.186"
}

Making an equivalent call using https causes a timeout:

http.get("https://httpbin.org/ip", nil, function(code, data)
if (code < 0) then
  print("HTTP request failed")
else
  print(code, data)
end
end)>> >>

with the following messages shown on the console:

HTTP client: Disconnected with error: 9
HTTP client: Connection timeout

A couple of other similar questions from about a year ago talk about fixes required for net module and a specific version of SSL implementation required to call httpbin.org:

HTTPS (SSL) get request with NodeMCU

HTTPS get requests with NodeMCU and ESP8266

The build was created today with the TLS/SSL support by mbedTLS.


问:
image can't be displayed from within function
I have a simple GUI tryout where I want to display few images on my screen. I start with setting the window with gray squares allover it and resizing the desired image and now I want to put it on the frame:

```<code>img = [img_resize(yellow_square, img_size), "text"]

base_panel = Label(root, image = img[0])
base_txt   = Label(root, text =  img[1])
base_panel.grid(row = x, column = y)
base_txt.grid  (row = x, column = y)
...
for im in ls:
    panel = Label(root, image = im[0])
    panel.grid(row = x+im[1][1], column = y+im[1][2])

    txt = Label(root, text =  im[2])
    txt.grid(row = x+im[1][1], column = y+im[1][2], sticky = 'S')
</code>```

ls is a list [image (using Image.open(img)), location offset, text]

When I copy these lines to my main script, it all goes well and I get the desired

but when trying to do so from a function, I only get the text part to work

I guess something is wrong with my image = ... but I don't understand what, as I have the code working after I just copied these lines to main. The main has another image, so maybe this is affecting somehow?

This is the code from main:

```<code>for im in background: # background is a list of gray squares
# some manipulation an a,b

panel = Label(root, image = im)
panel.grid(row = a, column = b)
</code>```

Here should come the function call or the lines themselves

答:
This is a common problem. You have to keep a reference to the image, or else python deletes it from memory. If you aren't in a function then the variable is a global variable, which keeps the reference. But in a function you need to do something like this: </p>

```<code>panel = Label(root)
panel.img = im[0]
panel.config(image = panel.img)
</code>```

Body:
I have a simple GUI tryout where I want to display few images on my screen. I start with setting the window with gray squares allover it and resizing the desired image and now I want to put it on the frame:

img = [img_resize(yellow_square, img_size), "text"]

base_panel = Label(root, image = img[0])
base_txt   = Label(root, text =  img[1])
base_panel.grid(row = x, column = y)
base_txt.grid  (row = x, column = y)
...
for im in ls:
    panel = Label(root, image = im[0])
    panel.grid(row = x+im[1][1], column = y+im[1][2])

    txt = Label(root, text =  im[2])
    txt.grid(row = x+im[1][1], column = y+im[1][2], sticky = 'S')

ls is a list [image (using Image.open(img)), location offset, text]

When I copy these lines to my main script, it all goes well and I get the desired

but when trying to do so from a function, I only get the text part to work

I guess something is wrong with my image = ... but I don't understand what, as I have the code working after I just copied these lines to main. The main has another image, so maybe this is affecting somehow?

This is the code from main:

for im in background: # background is a list of gray squares
# some manipulation an a,b

panel = Label(root, image = im)
panel.grid(row = a, column = b)

Here should come the function call or the lines themselves

Body:
This is a common problem. You have to keep a reference to the image, or else python deletes it from memory. If you aren't in a function then the variable is a global variable, which keeps the reference. But in a function you need to do something like this:

panel = Label(root)
panel.img = im[0]
panel.config(image = panel.img)


问:
How to display the maximum duration of a song using timespan?
In my music player, there are 2 labels.

Label 1 is for showing the progress time:

```<code>lblTime.Content = TimeSpan.FromSeconds(sliProgress.Value).ToString(@"mm\:ss");
</code>```

And label 2 is for showing the maximum duration of a song:

```<code>lblTime2.Content = TimeSpan.MaxValue.ToString(@"mm\:ss");
</code>```

Label 1 was working well from start playing and when I move the slider. But the label 2 somehow doesn't show anything. I have tried using Properties.Duration syntax in taglib-sharp. But for me, it show too much details, since I just want show the minutes and the seconds, not the hours even the miliseconds.

What should I do to fix the label 2?

答:
I suddenly found an idea about using ToString syntax to taglib, similar to as I did for label 1. Now it works as I expected, displaying just only minutes and seconds.

This is the code I use:

```<code>lblTime2.Content=tagFile.Properties.Duration.ToString(@"mm\:ss");
</code>```

Body:
In my music player, there are 2 labels.

Label 1 is for showing the progress time:

lblTime.Content = TimeSpan.FromSeconds(sliProgress.Value).ToString(@"mm\:ss");

And label 2 is for showing the maximum duration of a song:

lblTime2.Content = TimeSpan.MaxValue.ToString(@"mm\:ss");

Label 1 was working well from start playing and when I move the slider. But the label 2 somehow doesn't show anything. I have tried using Properties.Duration syntax in taglib-sharp. But for me, it show too much details, since I just want show the minutes and the seconds, not the hours even the miliseconds.

What should I do to fix the label 2?

Body:
I suddenly found an idea about using ToString syntax to taglib, similar to as I did for label 1. Now it works as I expected, displaying just only minutes and seconds.

This is the code I use:

lblTime2.Content=tagFile.Properties.Duration.ToString(@"mm\:ss");


问:
With Facebook Open Graph, is there some way to specify separate OG tags for Like vs. Share?
This is a really basic (potentially very dumb) question but I can't find an answer scouring the Facebook developer site.

Say your website's main page is www.example.com.  And you have a subpage on the site at www.example.com/specific-page.php

On specific-page.php, I'd like to have two buttons next to each other:

A Facebook Like button that when clicked, likes my main domain (www.example.com).

A Facebook Share button that when clicked, shares specific-page.php

Obviously I'd have OG meta tags on specific-page.php (like those below) but both the Share and Like buttons are using that info, so it seems you can't have the Like be attributed to the primary domain and the Share to the specific page's info.

In other words, if the Like button count on www.example.com's homepage showed 143 likes and then someone on specific-page.php clicked Like, I'd want that homepage number to now be 144.

```<code><meta property="og:image"content="http://www.example.com/images/facebookthumb.png" />
<meta property="og:title" content="Example" />
<meta property="og:url" content="http://www.example.com/specific-page.php" />
<meta property="og:site_name" content="Example"/>
<meta property="og:type" content="website"/>
<meta property="og:description" content="Example.com is an exemplary site." />
</code>```

So I guess my ultimate question is:  Is there some way to specify separate OG tags for Like vs. Share?

答:
No, there is no way. Earlier, there was an option to use the FB.ui feed dialog for sharing with custom parameters: https://developers.facebook.com/docs/sharing/reference/feed-dialog

As of April 18, 2017, the following parameters are no longer supported
  by Graph API versions 2.9 and higher. For versions 2.8 and lower, the
  parameters will continue working until July 17, 2017.

Body:
This is a really basic (potentially very dumb) question but I can't find an answer scouring the Facebook developer site.

Say your website's main page is www.example.com.  And you have a subpage on the site at www.example.com/specific-page.php

On specific-page.php, I'd like to have two buttons next to each other:

A Facebook Like button that when clicked, likes my main domain (www.example.com).

A Facebook Share button that when clicked, shares specific-page.php

Obviously I'd have OG meta tags on specific-page.php (like those below) but both the Share and Like buttons are using that info, so it seems you can't have the Like be attributed to the primary domain and the Share to the specific page's info.

In other words, if the Like button count on www.example.com's homepage showed 143 likes and then someone on specific-page.php clicked Like, I'd want that homepage number to now be 144.

<meta property="og:image"content="http://www.example.com/images/facebookthumb.png" />
<meta property="og:title" content="Example" />
<meta property="og:url" content="http://www.example.com/specific-page.php" />
<meta property="og:site_name" content="Example"/>
<meta property="og:type" content="website"/>
<meta property="og:description" content="Example.com is an exemplary site." />

So I guess my ultimate question is:  Is there some way to specify separate OG tags for Like vs. Share?


问:
Angular 2 animating transition based on dynamic value instead of time
While I understand that Angular 2's animate is primarily used to animate the transition between states in a fixed time, this is not always what is most convenient.

In my case, I have a slide-able element, that I wish to animate based on how far I have moved it from its default position. That is, I want to provide the handler dynamically with, for example a float number between 0 and 1 representing how far along the animation I should be. Can the angular 2 framework handle this? Can I perhaps, somehow, bypass the default animate(time) property, and directly call the underlying function that changes the css?

答:
I'm not 100% clear on your problem, but I don't think what you're asking for is possible with Angular animations. Angular's animations are built on top of the Web Animation API, which itself is just a streamlined means of interacting with CSS Animations. CSS animations are defined with keyframes + durations (see https://css-tricks.com/almanac/properties/a/animation/).

Theoretically, you could create a complex set of keyframes that you "stepped through" based on the position of your slide-able element, but it would be a hack and not really what you're asking for.

To accomplish your goal, I think you'll need to use custom Javascript or find an outside library to help you. You're a little vague on the project details, but, as an example, a library like Tether might help you.


问:
static variables, libgdx and android pause/resume memory usage
Program example:

```<code>public class main extends ApplicationAdapter
{
    public static int a;
    public static int b;
    public static Player player;

    public void create()
    {
        resume();
    }

    public void render()
    {
    }

    public void resize()
    {
    }

    //pause runs when home button is pressed
    public void pause()
    {
        player = null;
    }

    //resume runs when the program is re-opened
    public void resume()
    {
        a = 10;
        b = 20;
        player = new Player();
    }
}
</code>```

On android, when the home button is pressed, the program is kept in memory and static variables keep their values.  Now when this program is re-opened, does this example create new static variables or just assign values to the old static variables that were in memory?

I'm asking because I have a program that has an issue where pressing home and re-opening the program results in the memory increasing each time and I'm wondering if this could play a role in why that occurs.

updated: Does the player object get removed from memory when it is declared null before getting created again?

答:
create new static variables or just assign values to the old static variables that was is in memory ?

Only assign value to a, b by resume() method.

Static variables are initialized only once , at the start of the execution.

EDIT

You're creating new object of Player and assigning to player reference  variable. After that you don't have reference of old player object so when JVM feel need to run garbage collector, garbage collector will run and clear memory of old player object.

Body:
Program example:

public class main extends ApplicationAdapter
{
    public static int a;
    public static int b;
    public static Player player;

    public void create()
    {
        resume();
    }

    public void render()
    {
    }

    public void resize()
    {
    }

    //pause runs when home button is pressed
    public void pause()
    {
        player = null;
    }

    //resume runs when the program is re-opened
    public void resume()
    {
        a = 10;
        b = 20;
        player = new Player();
    }
}

On android, when the home button is pressed, the program is kept in memory and static variables keep their values.  Now when this program is re-opened, does this example create new static variables or just assign values to the old static variables that were in memory?

I'm asking because I have a program that has an issue where pressing home and re-opening the program results in the memory increasing each time and I'm wondering if this could play a role in why that occurs.

updated: Does the player object get removed from memory when it is declared null before getting created again?


问:
Verify whether the next char is the same as first char
I found a problem and i tried my logic but i failed to get to the solution.

This is the problem i am trying to solve in java.

For every opening brace (i.e., (, {, or [), there is a matching closing brace (i.e., ), }, or ]) of the same type (i.e., (matches ), { matches }, and [ matches ]). An opening brace must appear before (to the left of) it’s matching closing brace. For example, ]{}[ is not balanced.

No unmatched braces lie between some pair of matched braces. For example, ({[]}) is balanced, but {[}] and [{)] are not balanced.

I want to write java code which would take such a string input of braces and output whether it is balanced or not.

I am not able to apply logic for this kind of code, i tried however it was not even close to expectations. Please provide with some logic. I know this is not a homework completion site but i am stuck on the logic of this problem. a code snippet would be appreciated.

答:
Another way to solve this problem.

This can be solved using Stack Datastructure.

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String string = in.next(); //input string -> eg : {{[[(())]]}}
        boolean check = Paran(string);
        if(check){
           System.out.println("YES");
        }
        else{
           System.out.println("NO");

        }
    }

    //function that checks brackets are balanced or not
    public static boolean Paran(String string){
        //create a stack
        Stack<Character> s = new Stack<Character>();

        //check if string is empty
        //if string is empty then Balanced
        if(string.length() == 0){
            return true;
        }

        //if string is not empty, go through each character
        for(int i = 0; i< string.length(); i++){

            //fetch each character
            char current = string.charAt(i);

            //check if that character id any of {([
            // if yes push on to the stack
            if(current == '[' || current == '{' || current == '('){
                    s.push(current);
            }

            //check if that character id any of }])
            if(current == '}' || current == ']' || current == ')'){
                //check stack is empty
                //if yes then return false
                if(s.isEmpty()){
                    return false;
                }

                //else fetch top most item
                char pre = s.peek();
                if((current == '}' && pre == '{') || (current == ']' && pre == '[') || (current == ')' && pre == '(')){
                        s.pop();
                    }
                    else{
                        return false;
                    }
             }
        }
        return s.isEmpty();
    }

 }
</code>```

Hope this helps

Body:
Another way to solve this problem.

This can be solved using Stack Datastructure.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String string = in.next(); //input string -> eg : {{[[(())]]}}
        boolean check = Paran(string);
        if(check){
           System.out.println("YES");
        }
        else{
           System.out.println("NO");

        }
    }

    //function that checks brackets are balanced or not
    public static boolean Paran(String string){
        //create a stack
        Stack<Character> s = new Stack<Character>();

        //check if string is empty
        //if string is empty then Balanced
        if(string.length() == 0){
            return true;
        }

        //if string is not empty, go through each character
        for(int i = 0; i< string.length(); i++){

            //fetch each character
            char current = string.charAt(i);

            //check if that character id any of {([
            // if yes push on to the stack
            if(current == '[' || current == '{' || current == '('){
                    s.push(current);
            }

            //check if that character id any of }])
            if(current == '}' || current == ']' || current == ')'){
                //check stack is empty
                //if yes then return false
                if(s.isEmpty()){
                    return false;
                }

                //else fetch top most item
                char pre = s.peek();
                if((current == '}' && pre == '{') || (current == ']' && pre == '[') || (current == ')' && pre == '(')){
                        s.pop();
                    }
                    else{
                        return false;
                    }
             }
        }
        return s.isEmpty();
    }

 }

Hope this helps