问:
Storing list of instances (of self) in class level attribute?
I have a class in which I would like to store a static reference list of objects of the same class. For example:

```<code>class Apple:

    NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red'),
        Apple('Pink Lady', 'Pink')]

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour
</code>```

This results in a NameError: name 'Apple' is not defined error.
Why doesn't this work?

I've changed the code to the following, which seems to work on the console:

```<code>class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

Apple.NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red'),
        Apple('Pink Lady', 'Pink')]
</code>```

Is there a better way to do this?
Will this work inside and outside the module, and is this dependent on the way I import the module?

答:
Declare NICE_APPLES as an empty list in the Apple class, and then inside __init__(), when you're done assigning all the local variables, append self to the list.

```<code>class Apple(object):

    NICE_APPLES = []

    def __init__(self, name, color, keep=False):
        self.name = name
        self.color = color

        if keep:
            Apple.NICE_APPLES.append(self)
</code>```

Body:
I have a class in which I would like to store a static reference list of objects of the same class. For example:

class Apple:

    NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red'),
        Apple('Pink Lady', 'Pink')]

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

This results in a NameError: name 'Apple' is not defined error.
Why doesn't this work?

I've changed the code to the following, which seems to work on the console:

class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

Apple.NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red'),
        Apple('Pink Lady', 'Pink')]

Is there a better way to do this?
Will this work inside and outside the module, and is this dependent on the way I import the module?

Body:
Declare NICE_APPLES as an empty list in the Apple class, and then inside __init__(), when you're done assigning all the local variables, append self to the list.

class Apple(object):

    NICE_APPLES = []

    def __init__(self, name, color, keep=False):
        self.name = name
        self.color = color

        if keep:
            Apple.NICE_APPLES.append(self)


来源: stackexchange

问:
Tensorboard on Windows reports "No scalar data was found"
Doing the tutorial off the TensorFlow community Git repository at https://github.com/BinRoot/TensorFlow-Book/blob/master/ch02_basics/Concept08_TensorBoard.ipynb

When running tensorboard --logdir=path/to/logs in the command panel I get, Starting TensorBoard b'47' at http://0.0.0.0:6006.

Then when I go to explorer and look at the board it brings up, No scalar data was found. I am not sure what I am missing.

Copy of the code as I have it in my Python script:

```<code>import tensorflow as tf
import numpy as np

raw_data = np.random.normal(10, 1, 100)

alpha = tf.constant(0.05)
curr_value = tf.placeholder(tf.float32)
prev_avg = tf.Variable(0.)

update_avg = alpha * curr_value + (1 - alpha) * prev_avg

avg_hist = tf.summary.scalar("running_average", update_avg)
value_hist = tf.summary.scalar("incoming_values", curr_value)

merged = tf.summary.merge_all()
writer = tf.summary.FileWriter("./logs")

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for i in range(len(raw_data)):
        summary_str, curr_avg = sess.run([merged, update_avg], feed_dict=
{curr_value: raw_data[i]})
        sess.run(tf.assign(prev_avg, curr_avg))
        print(raw_data[i], curr_avg)
        writer.add_summary(summary_str, i)
</code>```

答:
Tensorboard has a known issue with paths on windows.

To summarize, tensorboard's --logdir can take a path, such as --logdir=/my/path, but the user can also specify a name to one or several comma separated paths, such as --logdir=foo:/my/path1,bar:/my/path2.

The problem is that this naming system does not play nice with Windows' drive name. When specifying --logdir=C:\my\path, how does tensorboard knows C: is a drive name and not a path name? Well, it doesn't, and you end up with a nice tensorboard webpage showing no summaries at all.

The solution is either to omit the drive letter and make sure you start from the correct drive, or somewhat more robustly, to always provide a path name, as in --logdir foo:"C:\My path\to my logs".

UPDATE

Since TF 1.5, tensorboard learned to recognize Windows drives and do not treat them as labels anymore.

ContentLicense: CC BY-SA 3.0

Body:
Doing the tutorial off the TensorFlow community Git repository at https://github.com/BinRoot/TensorFlow-Book/blob/master/ch02_basics/Concept08_TensorBoard.ipynb

When running tensorboard --logdir=path/to/logs in the command panel I get, Starting TensorBoard b'47' at http://0.0.0.0:6006.

Then when I go to explorer and look at the board it brings up, No scalar data was found. I am not sure what I am missing.

Copy of the code as I have it in my Python script:

import tensorflow as tf
import numpy as np

raw_data = np.random.normal(10, 1, 100)

alpha = tf.constant(0.05)
curr_value = tf.placeholder(tf.float32)
prev_avg = tf.Variable(0.)

update_avg = alpha * curr_value + (1 - alpha) * prev_avg

avg_hist = tf.summary.scalar("running_average", update_avg)
value_hist = tf.summary.scalar("incoming_values", curr_value)

merged = tf.summary.merge_all()
writer = tf.summary.FileWriter("./logs")

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for i in range(len(raw_data)):
        summary_str, curr_avg = sess.run([merged, update_avg], feed_dict=
{curr_value: raw_data[i]})
        sess.run(tf.assign(prev_avg, curr_avg))
        print(raw_data[i], curr_avg)
        writer.add_summary(summary_str, i)

ContentLicense: CC BY-SA 4.0


问:
AS3: Line of Sight
How to check whether the object(s) between the point and the object?

答:
found this. Looks very good -

http://www.baconandgames.com/2010/02/22/intersection-of-an-ellipse-and-a-line-in-as3/

Title: AS3: Line of Sight

ContentLicense: CC BY-SA 2.5


问:
GWT JsInterop - call an object like it's a function
Using JsInterop, I've wrapped the following JavaScript code:

```<code>var voronoi = d3.geom.voronoi()
    .clipExtent([[0, 0], [width, height]]);
</code>```

as follows:

```<code>private Voronoi voronoi;
...
voronoi = d3.geom().voronoi()
          .clipExtent(new Double[][] {{0.D, 0.D}, {width, height}});
</code>```

This much appears to be working.

Later on, on the JavaScript side of things, they make the following call:

```<code>path = path
  .data(voronoi(vertices), polygon);
</code>```

I'm having a hard time figuring out how to call my voronoi instance as if it's a function in this way.

In this document: https://docs.google.com/document/d/10fmlEYIHcyead_4R1S5wKGs1t2I7Fnp_PaNaa7XTEk0/edit#, I'm seeing the following line:

@JsFunction
Another powerful feature of JsInterop is the ability to represent JavaScript function contracts between Java and JavaScript. That means a JavaScript function can be easily called from Java or a Java object can be called like a function in JavaScript:

Right now my Voronoi object is the following:

```<code>@JsType(isNative = true)
public interface Voronoi extends Geometry {

    <D> Voronoi clipExtent(D[][] bounds);
}
</code>```

Any ideas what I need to do to call my Voronoi instance as if it's a function?

Thank you

答:
```<code>@JsType(isNative = true)
public interface Voronoi extends Geometry {

    @JsMethod
    static native [TheTypeItReturns] call(Voronoi self, [ParameterTypes]... args);

    <D> Voronoi clipExtent(D[][] bounds);
}
</code>```

Look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply .

Body:
Using JsInterop, I've wrapped the following JavaScript code:

var voronoi = d3.geom.voronoi()
    .clipExtent([[0, 0], [width, height]]);

as follows:

private Voronoi voronoi;
...
voronoi = d3.geom().voronoi()
          .clipExtent(new Double[][] {{0.D, 0.D}, {width, height}});

This much appears to be working.

Later on, on the JavaScript side of things, they make the following call:

path = path
  .data(voronoi(vertices), polygon);

I'm having a hard time figuring out how to call my voronoi instance as if it's a function in this way.

In this document: https://docs.google.com/document/d/10fmlEYIHcyead_4R1S5wKGs1t2I7Fnp_PaNaa7XTEk0/edit#, I'm seeing the following line:

@JsFunction
Another powerful feature of JsInterop is the ability to represent JavaScript function contracts between Java and JavaScript. That means a JavaScript function can be easily called from Java or a Java object can be called like a function in JavaScript:

Right now my Voronoi object is the following:

@JsType(isNative = true)
public interface Voronoi extends Geometry {

    <D> Voronoi clipExtent(D[][] bounds);
}

Any ideas what I need to do to call my Voronoi instance as if it's a function?

Thank you

Body:
@JsType(isNative = true)
public interface Voronoi extends Geometry {

    @JsMethod
    static native [TheTypeItReturns] call(Voronoi self, [ParameterTypes]... args);

    <D> Voronoi clipExtent(D[][] bounds);
}

Look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply .


问:
Plot a step function (cadlag) in R (two dots: continuity and discontinuity point)
Essentially I want to plot a compound Poisson process. Everything works fine except that I don't know how to edit the plot parameters correctly.
I want to have the continuity points with a full dot and the discontinuity points with an empty dot. Right now I only am able to manage the full dot.

Minimal working example (plots an compound Poisson path with 10 jumps)

```<code>n <- 10
n.t <- cumsum(rexp(n))
x <- c(0,cumsum(rnorm(n)))
plot(stepfun(n.t, x), xlab="t", ylab="X",do.points = TRUE,pch = 16,col.points = "blue",verticals = FALSE)
</code>```

So how can I add the discontinuity points to the right? Any idea?

答:
You can use points to add the points after the original plot.

```<code>set.seed(2017)      ## For reproducibility

## Your code
n <- 10
n.t <- cumsum(rexp(n))
x <- c(0,cumsum(rnorm(n)))
plot(stepfun(n.t, x), xlab="t", ylab="X",
    do.points = TRUE,pch = 16,col.points = "blue",verticals = FALSE)

## Add the endpoints
points(n.t, x[-length(x)], pch = 1)
</code>```

Body:
Essentially I want to plot a compound Poisson process. Everything works fine except that I don't know how to edit the plot parameters correctly.
I want to have the continuity points with a full dot and the discontinuity points with an empty dot. Right now I only am able to manage the full dot.

Minimal working example (plots an compound Poisson path with 10 jumps)

n <- 10
n.t <- cumsum(rexp(n))
x <- c(0,cumsum(rnorm(n)))
plot(stepfun(n.t, x), xlab="t", ylab="X",do.points = TRUE,pch = 16,col.points = "blue",verticals = FALSE)

So how can I add the discontinuity points to the right? Any idea?

Body:
You can use points to add the points after the original plot.

set.seed(2017)      ## For reproducibility

## Your code
n <- 10
n.t <- cumsum(rexp(n))
x <- c(0,cumsum(rnorm(n)))
plot(stepfun(n.t, x), xlab="t", ylab="X",
    do.points = TRUE,pch = 16,col.points = "blue",verticals = FALSE)

## Add the endpoints
points(n.t, x[-length(x)], pch = 1)


问:
Why are my flex items wrapping off the screen?
I have a flex nav and it's wrapping to the left and partially off of the screen. Does anyone with more experience know what could be causing this? I can't figure out why it's doing this.

header {
  background-color: rgba(255, 165, 0, .8);
  border-bottom: 12px solid black;
  display: flex;
  flex-flow: row wrap;
  align-content: center;
}

header h1 {
  text-align: center;
  margin: 0;
  padding: 15px;
  text-shadow: 5px 5px 5px rgba(0, 0, 0, .3);
  border: 8px solid black;
}

header h1,
nav a {
  font-weight: 700;
  font-family: arial;
}

header nav {
  display: none;
}

nav ul {
  list-style: none;
  padding: 0;
}

nav ul li {
  text-align: center;
  margin: 1px;
  border: 1px solid white;
  border-radius: 15px;
}

a {
  text-decoration: none;
}

a:visited,
a,
h1 {
  color: white;
}

@media screen and (min-width: 400px) {
  header {
    height: 120px;
    display: flex;
    justify-content: space-between;
  }
  header h1 {
    margin: 0 0 0 8%;
    font-size: 2em;
    align-self: flex-start;
    white-space: nowrap;
  }
  header nav {
    display: block;
    align-self: flex-end;
  }
  nav ul {
    display: flex;
    justify-content: flex-end;
    margin: 0 8% 0 0;
  }
  nav ul li {
    border-radius: 8px;
    padding: 5px;
    margin: 4px 1%;
    font-size: 1.5rem;
  }
  .characters:hover {
    position: relative;
    border-radius: 8px 8px 0 0;
  }
  .drop-menu {
    position: absolute;
    display: none;
    top: 38px;
    white-space: nowrap;
    left: 0;
    background-color: rgba(255, 165, 0, .8);
    border: 1px solid rgba(0, 0, 0, .02);
    box-shadow: 5px 5px 5px 2px rgba(0, 0, 0, .3);
  }
  .characters:hover .drop-menu {
    display: block;
  }
  .drop-menu li {
    margin: 0;
    border-radius: 0;
  }
  footer nav {
    display: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <h1>Seraph Chronicles</h1>
  <nav>
    <ul class="main-nav">
      <li class="main-nav-item">Home</li>
      <li class="main-nav-item">About</li>
      <li class="main-nav-item characters">
        Characters
        <ul class="drop-menu">
          <li>Ethan Clarke</li>
          <li>Serena Kiriaga</li>
          <li>Marcus Flynn</li>
          <li>Emily Ashdown</li>
          <li>Director Miles West</li>
        </ul>
      </li>
      <li class="main-nav-item">Author</li>
    </ul>
  </nav>
</header></code>```

https://jsfiddle.net/ca75sqzc/17/

答:
Just erase justify-content: flex-end; from the rule for nav ul in the media query section:

header {
  background-color: rgba(255, 165, 0, .8);
  border-bottom: 12px solid black;
  display: flex;
  flex-flow: row wrap;
  align-content: center;
}

header h1 {
  text-align: center;
  margin: 0;
  padding: 15px;
  text-shadow: 5px 5px 5px rgba(0, 0, 0, .3);
  border: 8px solid black;
}

header h1,
nav a {
  font-weight: 700;
  font-family: arial;
}

header nav {
  display: none;
}

nav ul {
  list-style: none;
  padding: 0;
}

nav ul li {
  text-align: center;
  margin: 1px;
  border: 1px solid white;
  border-radius: 15px;
}

a {
  text-decoration: none;
}

a:visited,
a,
h1 {
  color: white;
}

@media screen and (min-width: 400px) {
  header {
    height: 120px;
    display: flex;
    justify-content: space-between;
  }
  header h1 {
    margin: 0 0 0 8%;
    font-size: 2em;
    align-self: flex-start;
    white-space: nowrap;
  }
  header nav {
    display: block;
    align-self: flex-end;
  }
  nav ul {
    display: flex;
    margin: 0 8% 0 0;
  }
  nav ul li {
    border-radius: 8px;
    padding: 5px;
    margin: 4px 1%;
    font-size: 1.5rem;
  }
  .characters:hover {
    position: relative;
    border-radius: 8px 8px 0 0;
  }
  .drop-menu {
    position: absolute;
    display: none;
    top: 38px;
    white-space: nowrap;
    left: 0;
    background-color: rgba(255, 165, 0, .8);
    border: 1px solid rgba(0, 0, 0, .02);
    box-shadow: 5px 5px 5px 2px rgba(0, 0, 0, .3);
  }
  .characters:hover .drop-menu {
    display: block;
  }
  .drop-menu li {
    margin: 0;
    border-radius: 0;
  }
  footer nav {
    display: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <h1>Seraph Chronicles</h1>
  <nav>
    <ul class="main-nav">
      <li class="main-nav-item">Home</li>
      <li class="main-nav-item">About</li>
      <li class="main-nav-item characters">
        Characters
        <ul class="drop-menu">
          <li>Ethan Clarke</li>
          <li>Serena Kiriaga</li>
          <li>Marcus Flynn</li>
          <li>Emily Ashdown</li>
          <li>Director Miles West</li>
        </ul>
      </li>
      <li class="main-nav-item">Author</li>
    </ul>
  </nav>
</header></code>```

https://jsfiddle.net/7dubc44L/

Body:
I have a flex nav and it's wrapping to the left and partially off of the screen. Does anyone with more experience know what could be causing this? I can't figure out why it's doing this.

header {
  background-color: rgba(255, 165, 0, .8);
  border-bottom: 12px solid black;
  display: flex;
  flex-flow: row wrap;
  align-content: center;
}

header h1 {
  text-align: center;
  margin: 0;
  padding: 15px;
  text-shadow: 5px 5px 5px rgba(0, 0, 0, .3);
  border: 8px solid black;
}

header h1,
nav a {
  font-weight: 700;
  font-family: arial;
}

header nav {
  display: none;
}

nav ul {
  list-style: none;
  padding: 0;
}

nav ul li {
  text-align: center;
  margin: 1px;
  border: 1px solid white;
  border-radius: 15px;
}

a {
  text-decoration: none;
}

a:visited,
a,
h1 {
  color: white;
}

@media screen and (min-width: 400px) {
  header {
    height: 120px;
    display: flex;
    justify-content: space-between;
  }
  header h1 {
    margin: 0 0 0 8%;
    font-size: 2em;
    align-self: flex-start;
    white-space: nowrap;
  }
  header nav {
    display: block;
    align-self: flex-end;
  }
  nav ul {
    display: flex;
    justify-content: flex-end;
    margin: 0 8% 0 0;
  }
  nav ul li {
    border-radius: 8px;
    padding: 5px;
    margin: 4px 1%;
    font-size: 1.5rem;
  }
  .characters:hover {
    position: relative;
    border-radius: 8px 8px 0 0;
  }
  .drop-menu {
    position: absolute;
    display: none;
    top: 38px;
    white-space: nowrap;
    left: 0;
    background-color: rgba(255, 165, 0, .8);
    border: 1px solid rgba(0, 0, 0, .02);
    box-shadow: 5px 5px 5px 2px rgba(0, 0, 0, .3);
  }
  .characters:hover .drop-menu {
    display: block;
  }
  .drop-menu li {
    margin: 0;
    border-radius: 0;
  }
  footer nav {
    display: none;
  }
}

Seraph Chronicles

Home

About

        Characters

Ethan Clarke

Serena Kiriaga

Marcus Flynn

Emily Ashdown

Director Miles West

Author

https://jsfiddle.net/ca75sqzc/17/

Body:
Just erase justify-content: flex-end; from the rule for nav ul in the media query section:

header {
  background-color: rgba(255, 165, 0, .8);
  border-bottom: 12px solid black;
  display: flex;
  flex-flow: row wrap;
  align-content: center;
}

header h1 {
  text-align: center;
  margin: 0;
  padding: 15px;
  text-shadow: 5px 5px 5px rgba(0, 0, 0, .3);
  border: 8px solid black;
}

header h1,
nav a {
  font-weight: 700;
  font-family: arial;
}

header nav {
  display: none;
}

nav ul {
  list-style: none;
  padding: 0;
}

nav ul li {
  text-align: center;
  margin: 1px;
  border: 1px solid white;
  border-radius: 15px;
}

a {
  text-decoration: none;
}

a:visited,
a,
h1 {
  color: white;
}

@media screen and (min-width: 400px) {
  header {
    height: 120px;
    display: flex;
    justify-content: space-between;
  }
  header h1 {
    margin: 0 0 0 8%;
    font-size: 2em;
    align-self: flex-start;
    white-space: nowrap;
  }
  header nav {
    display: block;
    align-self: flex-end;
  }
  nav ul {
    display: flex;
    margin: 0 8% 0 0;
  }
  nav ul li {
    border-radius: 8px;
    padding: 5px;
    margin: 4px 1%;
    font-size: 1.5rem;
  }
  .characters:hover {
    position: relative;
    border-radius: 8px 8px 0 0;
  }
  .drop-menu {
    position: absolute;
    display: none;
    top: 38px;
    white-space: nowrap;
    left: 0;
    background-color: rgba(255, 165, 0, .8);
    border: 1px solid rgba(0, 0, 0, .02);
    box-shadow: 5px 5px 5px 2px rgba(0, 0, 0, .3);
  }
  .characters:hover .drop-menu {
    display: block;
  }
  .drop-menu li {
    margin: 0;
    border-radius: 0;
  }
  footer nav {
    display: none;
  }
}

<header>
  <h1>Seraph Chronicles</h1>
  <nav>
    <ul class="main-nav">
      <li class="main-nav-item"><a href="index.html">Home</a></li>
      <li class="main-nav-item"><a href="about.html">About</a></li>
      <li class="main-nav-item characters">
        <a href="characters.html">Characters</a>
        <ul class="drop-menu">
          <li><a href="ethanClarke.html">Ethan Clarke</a></li>
          <li><a href="serenaKiriaga.html">Serena Kiriaga</a></li>
          <li><a href="MarcusFlynn.html">Marcus Flynn</a></li>
          <li><a href="EmilyAshdown.html">Emily Ashdown</a></li>
          <li><a href="MilesWest.html">Director Miles West</a></li>
        </ul>
      </li>
      <li class="main-nav-item"><a href="auther.html">Author</a></li>
    </ul>
  </nav>
</header>

https://jsfiddle.net/7dubc44L/


问:
How to retrieve products by tags (SQL question)
I have two MySQL tables:

product has id, title, price and some other product attributes

tag has *product_id* and *tag_name* fields

each product row can have one ore more rows in table tag joined by *product_id* field.
Question: how do I select products by *tag_name* and other attributes?
Example: I need to select all books cheaper than $10 and tagged 'foreign' and 'sci-fi'

I know how to select products with one tag (join product and tag by *product_id* and set where clause)
I know how to select products with more than one tag using a stored procedure, however queries take very long time to run.
Is there a way to avoid stored procedure and still get the result?

Update: StackOverflow does something like this when you click "Related Tags" on the right hand side bar. Now, I don't know what architechture their DB has, but the result is fairly quick selection of all questions tagged with multiple tags.

答:
try,</p>

```<code>SELECT p.* FROM products p
INNER JOIN tag t ON p.id = t.product_id
WHERE p.price < 10 AND p.id IN( SELECT product_id FROM tag  WHERE  t.tag_name = 'foreign' OR t.tag_name = 'sci-fi' GROUP BY product_id HAVING COUNT(product_id) = 2)
</code>```

Body:
try,

SELECT p.* FROM products p
INNER JOIN tag t ON p.id = t.product_id
WHERE p.price < 10 AND p.id IN( SELECT product_id FROM tag  WHERE  t.tag_name = 'foreign' OR t.tag_name = 'sci-fi' GROUP BY product_id HAVING COUNT(product_id) = 2)


问:
Share .mailmap or other top-level files between multiple Git repositories, cross-platform
I have a number of Git repositories with similar contributors. Over the lifetime of those repositories, most contributors have used a variety of email addresses, etc. As such, each repository has a .mailmap file to facilitate git shortlog -s -e.

Because these .mailmap files are nearly identical to each other, the existing situation is not DRY. And each time a contributor adopts a new email address or suchlike, a new alias needs to be added across all the .mailmap files in all the repositories they are contributing to.

I would like to factor the .mailmap files out into a single repository (let's call it mailmap), so that new aliases only need to be added in one place, that will propagate to all the other repositories.

Using a git submodule called mailmap, with a symbolic link in each other repository from .mailmap to mailmap/.mailmap, seems like a reasonable option, but will the symbolic link work on Windows? I.e. will git shortlog -s -e show the same thing on Windows as it does on POSIX systems? (The current contributors don't use Windows, but Windows users might clone the Git repositories, and we want git shortlog -s -e to work for them as well as it works for us.)

If not, what might be a better solution?

答:
To make the symbolic links work on Windows, there are several possibilities, including:

Ensure that Windows users use GNU/kWindows (aka Windows Subsystem for Linux).

Ensure that Windows users use Cygwin with elevated privileges and either CYGWIN=winsymlinks:nativestrict or CYGWIN=winsymlinks:native.

Ensure that Windows users manually (or perhaps automatically via a hook) replace POSIX symlinks with Windows equivalents.


问:
shiny plotly no graph
I'm switching to plotly from ggplot for my shiny app, but when I run app from Rstudio the plots are not showing in browser, if I use print(gg) the plotly shows correctly in Rstudio viewer. The following minimal example works if I switch back to ggplot. Thanks!

ui.R

```<code>library(shiny)
library(httr)
library(jsonlite)

# get the list of all packages on CRAN
package_names = names(httr::content(httr::GET("http://crandb.r-
pkg.org/-/desc")))

shinyUI(fluidPage(

# Application title
"R Package Downloads",

# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
  br(),
  selectInput("package",
              label = "Packages",
              selected = "ggplot2", # initialize the graph with a random package
              choices = package_names,
              multiple = TRUE),
  selectInput("plot1",
              label = "Select Plot Type",
              choices = c("","Downloads vs Time (monthly)","Downloads vs Time (cumulative)","Map (cumulative)","Map (dominance)"),
              multiple = FALSE)),

# Show a plot of the generated distribution
mainPanel(
  plotlyOutput("plot1")
))
))
</code>```

server.R

```<code>library(shiny,quietly = T);    library(stringr,quietly = T)
library(dplyr,quietly = T);    library(plotly,quietly = T)
library(ggplot2,quietly = T);    library(lubridate,quietly = T)
library(cranlogs,quietly = T);    library(zoo,quietly = T)
library(scales,quietly = T);    library(broom,quietly = T)
library(rworldmap,quietly = T);    library(countrycode,quietly = T)
library(data.table,quietly = T)

shinyServer(function(input, output) {
  load("CRANlog_cleaned_month.RData")
  output$plot1 <- renderPlotly({
    dat.p <<- subset(dat,package %in% input$package)
    dat.ts <<- aggregate(times~package+month,data=dat.p,sum)
      DTmonthly <<- ggplot(dat.ts, aes(month, times, color = package)) +
        geom_line() + xlab("Date") + scale_y_continuous(name="Number of downloads", labels = comma)
      gg <- ggplotly(DTmonthly)
      gg
  })
})
</code>```

答: I managed to solve this by changing the name of selectInput from "plot1" to another name, might be because of the plotlyOutput is also using "plot1". This was fine if I just use plotOutput. Probably due to some error checking code is missing in plotlyOutput.</p>

Title: shiny plotly no graph

Body:
I'm switching to plotly from ggplot for my shiny app, but when I run app from Rstudio the plots are not showing in browser, if I use print(gg) the plotly shows correctly in Rstudio viewer. The following minimal example works if I switch back to ggplot. Thanks!

ui.R

library(shiny)
library(httr)
library(jsonlite)

# get the list of all packages on CRAN
package_names = names(httr::content(httr::GET("http://crandb.r-
pkg.org/-/desc")))

shinyUI(fluidPage(

# Application title
"R Package Downloads",

# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
  br(),
  selectInput("package",
              label = "Packages",
              selected = "ggplot2", # initialize the graph with a random package
              choices = package_names,
              multiple = TRUE),
  selectInput("plot1",
              label = "Select Plot Type",
              choices = c("","Downloads vs Time (monthly)","Downloads vs Time (cumulative)","Map (cumulative)","Map (dominance)"),
              multiple = FALSE)),

# Show a plot of the generated distribution
mainPanel(
  plotlyOutput("plot1")
))
))

server.R

library(shiny,quietly = T);    library(stringr,quietly = T)
library(dplyr,quietly = T);    library(plotly,quietly = T)
library(ggplot2,quietly = T);    library(lubridate,quietly = T)
library(cranlogs,quietly = T);    library(zoo,quietly = T)
library(scales,quietly = T);    library(broom,quietly = T)
library(rworldmap,quietly = T);    library(countrycode,quietly = T)
library(data.table,quietly = T)

shinyServer(function(input, output) {
  load("CRANlog_cleaned_month.RData")
  output$plot1 <- renderPlotly({
    dat.p <<- subset(dat,package %in% input$package)
    dat.ts <<- aggregate(times~package+month,data=dat.p,sum)
      DTmonthly <<- ggplot(dat.ts, aes(month, times, color = package)) +
        geom_line() + xlab("Date") + scale_y_continuous(name="Number of downloads", labels = comma)
      gg <- ggplotly(DTmonthly)
      gg
  })
})


问:
slideshow of images using jquery from the right center of the image
I am working on making slideshow of images and I was trying to use this tutorial: http://www.slidesjs.com/

I downloaded the zip file and started using it and it works fine. Only thing I was trying out but couldn't make it work was those four dots at the right bottom, I wanted them to be on the actual image but at right center just on the border line.

An example will be like this: https://s2.postimg.org/ochp3uevt/scroller.png

if you check above image out (not showing full image), in this all the dots are vertical instead of horizontal and at the right center on that image. I want to do something similar as well. Is this possible to do that?

I tried using margin-top but it didn't worked for me.

Update:-

There is a CSS from which that four dots image is coming up and I have modified that to include margin-top but it didn't worked:

```<code>.slidesjs-pagination li a {
  display: block;
  width: 13px;
  height: 0;
  padding-top: 13px;
  background-image: url("https://s16.postimg.org/pt4k43i9x/pagination.png");
  background-position: 0 0;
  float: left;
  <!-- added by me-->
  margin-top: -50px;
}
</code>```

Here is the full HTML code:

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>SlidesJS Standard Code Example</title>
  <meta name="description" content="SlidesJS is a simple slideshow plugin for jQuery. Packed with a useful set of features to help novice and advanced developers alike create elegant and user-friendly slideshows.">
  <meta name="author" content="Nathan Searles">

  <!-- SlidesJS Required (if responsive): Sets the page width to the device width. -->
  <meta name="viewport" content="width=device-width">
  <!-- End SlidesJS Required -->

  <!-- CSS for slidesjs.com example -->
  <link rel="stylesheet" href="css/example.css">
  <link rel="stylesheet" href="css/font-awesome.min.css">
  <!-- End CSS for slidesjs.com example -->

  <!-- SlidesJS Optional: If you'd like to use this design -->
  <style>
    body {
      -webkit-font-smoothing: antialiased;
      font: normal 15px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
      color: #232525;
      padding-top:70px;
    }

    #slides,
    #slides2,
    #slides3 {
      display: none;
      margin-bottom:50px;
    }

    .slidesjs-navigation {
      margin-top:3px;
    }

    .slidesjs-previous {
      margin-right: 5px;
      float: left;
    }

    .slidesjs-next {
      margin-right: 5px;
      float: left;
    }

    .slidesjs-pagination {
      margin: 6px 0 0;
      float: right;
      list-style: none;
    }

    .slidesjs-pagination li {
      float: left;
      margin: 0 1px;
    }

    .slidesjs-pagination li a {
      display: block;
      width: 13px;
      height: 0;
      padding-top: 13px;
      background-image: url("https://s16.postimg.org/pt4k43i9x/pagination.png");
      background-position: 0 0;
      float: left;
      overflow: hidden;
    }

    .slidesjs-pagination li a.active,
    .slidesjs-pagination li a:hover.active {
      background-position: 0 -13px
    }

    .slidesjs-pagination li a:hover {
      background-position: 0 -26px
    }

    a:link,
    a:visited {
      color: #333
    }

    a:hover,
    a:active {
      color: #9e2020
    }

    .navbar {
      overflow: hidden
    }
  </style>
  <!-- End SlidesJS Optional-->

  <!-- SlidesJS Required: These styles are required if you'd like a responsive slideshow -->
  <style>
    #slides {
      display: none
    }

    .container {
      margin: 0 auto
    }

    /* For tablets & smart phones */
    @media (max-width: 767px) {
      body {
        padding-left: 20px;
        padding-right: 20px;
      }
      .container {
        width: auto
      }
    }

    /* For smartphones */
    @media (max-width: 480px) {
      .container {
        width: auto
      }
    }

    /* For smaller displays like laptops */
    @media (min-width: 768px) and (max-width: 979px) {
      .container {
        width: 724px
      }
    }

    /* For larger displays */
    @media (min-width: 1200px) {
      .container {
        width: 1170px
      }
    }
  </style>
  <!-- SlidesJS Required: -->
</head>
<body>
  <!-- SlidesJS Required: Start Slides -->
  <!-- The container is used to define the width of the slideshow -->
  <div class="container">
    <div id="slides">
      <img src="https://s24.postimg.org/7cyxxftpd/example-slide-1.jpg" alt="Photo by: Missy S Link: http://www.flickr.com/photos/listenmissy/5087404401/">
      <img src="https://s24.postimg.org/5mfwvyc69/example-slide-2.jpg" alt="Photo by: Daniel Parks Link: http://www.flickr.com/photos/parksdh/5227623068/">
      <img src="https://s24.postimg.org/48oa0ncwx/example-slide-3.jpg" alt="Photo by: Mike Ranweiler Link: http://www.flickr.com/photos/27874907@N04/4833059991/">
      <img src="https://s24.postimg.org/rbjedk3s1/example-slide-4.jpg" alt="Photo by: Stuart SeegerLink: http://www.flickr.com/photos/stuseeger/97577796/">
      <a href="#" class="slidesjs-previous slidesjs-navigation"><i class="icon-chevron-left"></i></a>
      <a href="#" class="slidesjs-next slidesjs-navigation"><i class="icon-chevron-right"></i></a>
    </div>
  </div>
  <!-- End SlidesJS Required: Start Slides -->

  <!-- SlidesJS Required: Link to jQuery -->
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <!-- End SlidesJS Required -->

  <!-- SlidesJS Required: Link to jquery.slides.js -->
  <script src="js/jquery.slides.min.js"></script>
  <!-- End SlidesJS Required -->

  <!-- SlidesJS Required: Initialize SlidesJS with a jQuery doc ready -->
  <script>
    $(function() {
      $('#slides').slidesjs({
        width: 940,
        height: 528,
        navigation: false
      });

      /*
        To have multiple slideshows on the same page
        they just need to have separate IDs
      */
      $('#slides2').slidesjs({
        width: 940,
        height: 528,
        navigation: false,
        start: 3,
        play: {
          auto: true
        }
      });

      $('#slides3').slidesjs({
        width: 940,
        height: 528,
        navigation: false
      });
    });
  </script>
  <!-- End SlidesJS Required -->
</body>
</html>
</code>```

答:
Add this CSS by replacing the rules:</p>

```<code>#slides {
    position: relative;
}
.slidesjs-pagination {
    margin: 6px 0 0;
    float: none;
    list-style: none;
    position: absolute;
    top: 50%;
    right: 30px;
    z-index: 100;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    transform: translateY(-50%);
}
.slidesjs-pagination li {
    float: none;
    margin: 0 1px;
}

.slidesjs-pagination li a {
    display: block;
    width: 13px;
    height: 0;
    padding-top: 13px;
    background-image: url(https://s16.postimg.org/pt4k43i9x/pagination.png);
    background-position: 0 0;
    float: left;
    overflow: hidden;
    margin: 5px 0;
}
</code>```

Body:
I am working on making slideshow of images and I was trying to use this tutorial: http://www.slidesjs.com/

I downloaded the zip file and started using it and it works fine. Only thing I was trying out but couldn't make it work was those four dots at the right bottom, I wanted them to be on the actual image but at right center just on the border line.

An example will be like this: https://s2.postimg.org/ochp3uevt/scroller.png

if you check above image out (not showing full image), in this all the dots are vertical instead of horizontal and at the right center on that image. I want to do something similar as well. Is this possible to do that?

I tried using margin-top but it didn't worked for me.

Update:-

There is a CSS from which that four dots image is coming up and I have modified that to include margin-top but it didn't worked:

.slidesjs-pagination li a {
  display: block;
  width: 13px;
  height: 0;
  padding-top: 13px;
  background-image: url("https://s16.postimg.org/pt4k43i9x/pagination.png");
  background-position: 0 0;
  float: left;

  margin-top: -50px;
}

Here is the full HTML code:

<!doctype html>

  <meta charset="utf-8">
  <title>SlidesJS Standard Code Example</title>
  <meta name="description" content="SlidesJS is a simple slideshow plugin for jQuery. Packed with a useful set of features to help novice and advanced developers alike create elegant and user-friendly slideshows.">
  <meta name="author" content="Nathan Searles">

  <meta name="viewport" content="width=device-width">

  <link rel="stylesheet" href="css/example.css">
  <link rel="stylesheet" href="css/font-awesome.min.css">

Body:
Add this CSS by replacing the rules:

#slides {
    position: relative;
}
.slidesjs-pagination {
    margin: 6px 0 0;
    float: none;
    list-style: none;
    position: absolute;
    top: 50%;
    right: 30px;
    z-index: 100;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    transform: translateY(-50%);
}
.slidesjs-pagination li {
    float: none;
    margin: 0 1px;
}

.slidesjs-pagination li a {
    display: block;
    width: 13px;
    height: 0;
    padding-top: 13px;
    background-image: url(https://s16.postimg.org/pt4k43i9x/pagination.png);
    background-position: 0 0;
    float: left;
    overflow: hidden;
    margin: 5px 0;
}


问:
For loop does not complete inside Promise
I'm trying to write a function that includes a for loop inside a Promise, however the loop only performs on iteration and the promise is never resolved.

My code looks like this:

```<code>function appendPosts() {
    return functionThatReturnsAPromise()
       .then( result => {
           return new Promise( (resolve, reject) => {
              var list = [];
              result.forEach( item => {
                 //do stuff to item
                 list.push(item);
              });
             resolve(list);
           });
       })
       .then( list => {
          return new Promise( (resolve, reject) => {
             //This loop only runs once, even when list has contains many items
          for ( var i = 0; i < list.length; i++ ) {
             document.querySelector("someSelector").appendChild( list[i] );
          }
          resolve();
       });
   });
}
</code>```

Clearly I'm doing something wrong. Any ideas?

Thanks for your time.
- Daniel

答:
The selector probably did not return a match, and so appendChild was called on undefined, triggering an exception translated to a rejected promise.

You could treat this error if in your call you add a .catch:

```<code>appendPosts().then(function () {
    console.log('all done');
}).catch(function (err) {
    console.log('error occurred: ', err);
});
</code>```

But it should also be mentioned that you are using the promise constructor anti-pattern. Namely, in a then callback you can just return a value, and that value will become the promised value of the promise that then will return. So there is no need to do new Promise(). Instead, do this:

```<code>function appendPosts() {
    return functionThatReturnsAPromise().then( result => {
        // Just return the mapped array:
        return result.map( item => {
            //do stuff to item
            return item;
        }).then( list => {
            for ( var i = 0; i < list.length; i++ ) {
                // Make sure the selector will result in a match:
                document.querySelector("someSelector").appendChild( list[i] );
            }
        });
    });
}
</code>```

Body:
I'm trying to write a function that includes a for loop inside a Promise, however the loop only performs on iteration and the promise is never resolved.

My code looks like this:

function appendPosts() {
    return functionThatReturnsAPromise()
       .then( result => {
           return new Promise( (resolve, reject) => {
              var list = [];
              result.forEach( item => {
                 //do stuff to item
                 list.push(item);
              });
             resolve(list);
           });
       })
       .then( list => {
          return new Promise( (resolve, reject) => {
             //This loop only runs once, even when list has contains many items
          for ( var i = 0; i < list.length; i++ ) {
             document.querySelector("someSelector").appendChild( list[i] );
          }
          resolve();
       });
   });
}

Clearly I'm doing something wrong. Any ideas?

Thanks for your time.
- Daniel

Body:
The selector probably did not return a match, and so appendChild was called on undefined, triggering an exception translated to a rejected promise.

You could treat this error if in your call you add a .catch:

appendPosts().then(function () {
    console.log('all done');
}).catch(function (err) {
    console.log('error occurred: ', err);
});

But it should also be mentioned that you are using the promise constructor anti-pattern. Namely, in a then callback you can just return a value, and that value will become the promised value of the promise that then will return. So there is no need to do new Promise(). Instead, do this:

function appendPosts() {
    return functionThatReturnsAPromise().then( result => {
        // Just return the mapped array:
        return result.map( item => {
            //do stuff to item
            return item;
        }).then( list => {
            for ( var i = 0; i < list.length; i++ ) {
                // Make sure the selector will result in a match:
                document.querySelector("someSelector").appendChild( list[i] );
            }
        });
    });
}


答:
use a classmethod to append apples to your class list.</p>

```<code>class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

    @classmethod
    def add_nice_apple(cls, name, colour):
        cls.NICE_APPLES.append(cls(name, colour))

Apple.add_nice_apple('Elstar','Green')
Apple.add_nice_apple('Braeburn','Red')
</code>```

Title: Storing list of instances (of self) in class level attribute?

Body:
use a classmethod to append apples to your class list.

class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

    @classmethod
    def add_nice_apple(cls, name, colour):
        cls.NICE_APPLES.append(cls(name, colour))

Apple.add_nice_apple('Elstar','Green')
Apple.add_nice_apple('Braeburn','Red')


问:
How to get all values from resultset?
I'm trying to get all the values from the table and then assign them to a variable, there are only 2 options in the table so it can have 1 or 2 values, but when trying this it only gives back when first number (1) and the second (<code>$fila2 = $rs2[1];</code>) it says that is a Undefined offset </p>

```<code>include('conexion.php');
$str_query2 = "SELECT gc_id FROM prod_grupocompl where pr_id='171' "; //  Variable que guarda la consulta a efectuar
$query2 = mysqli_query($conexion,$str_query2) or die (mysql_error()); // EjecuciÛn de la consulta y se guarda el resultado en $query
$rs2 = mysqli_fetch_array($query2);
$fila = $rs2[0];
$fila2 = $rs2[1];
echo $fila;
echo $fila2;
</code>```

答:
Not sure but you can try this:

```<code>$rs2 = mysqli_fetch_array($query2, MYSQLI_NUM);
$fila = $rs2[0];
$fila2 = $rs2[1];
</code>```

and if not try to see what is inside the array with:

```<code>print_r($rs2);
</code>```

UPDATE: But as @Devon says: Source

Fetch a result row as an associative, a numeric array, or both

Title: How to get all values from resultset?

Body:
I'm trying to get all the values from the table and then assign them to a variable, there are only 2 options in the table so it can have 1 or 2 values, but when trying this it only gives back when first number (1) and the second ($fila2 = $rs2[1];) it says that is a Undefined offset

include('conexion.php');
$str_query2 = "SELECT gc_id FROM prod_grupocompl where pr_id='171' "; //  Variable que guarda la consulta a efectuar
$query2 = mysqli_query($conexion,$str_query2) or die (mysql_error()); // EjecuciÛn de la consulta y se guarda el resultado en $query
$rs2 = mysqli_fetch_array($query2);
$fila = $rs2[0];
$fila2 = $rs2[1];
echo $fila;
echo $fila2;

Body:
Not sure but you can try this:

$rs2 = mysqli_fetch_array($query2, MYSQLI_NUM);
$fila = $rs2[0];
$fila2 = $rs2[1];

and if not try to see what is inside the array with:

print_r($rs2);

UPDATE: But as @Devon says: Source

Fetch a result row as an associative, a numeric array, or both


问:
How do you set the delegate when passing data from ViewController to View?
Here's the relevant code:

in ViewController

```<code>protocol LocationDelegate {

    func setLocation(coordinate: CLLocationCoordinate2D)
}

var locationDelegate: LocationDelegate?

func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {

    locationDelegate?.setLocation(coordinate: coordinate)

    createPostView = createViewFromNib()
    createPostView.center = SCREEN_CENTER_POSITION
    self.view.addSubview(createPostView)
}
</code>```

in CreatePostView

```<code>class CreatePostView: UIView, UINavigationControllerDelegate, LocationDelegate {

 var location: CLLocation! = CLLocation()

 func setLocation(coordinate: CLLocationCoordinate2D) {

    self.location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
 }

}
</code>```

This doesn't work. "location" is always being saved as empty and I believe it's because I haven't set the delegate. I know this is usually done in prepareForSegue when passing data between two ViewControllers, but in this case, I'm not sure when to set it. How should I go about this?

答:
I think you are confused about how the delegate pattern works.

If I understand what you are trying to do... In ViewController you are accepting a longPress on the mapView, which is also passing the CLLocationCoordinate2D. You then create a CreatePostView which you want to add to your view as a subview... and you want to set the location var in that createPostView instance to the long-press coordinate. Correct?

If so, you don't need the delegate at all.

Instead, your CreatePostView class should have:

```<code>class CreatePostView: UIView, UINavigationControllerDelegate {

    var location: CLLocation! = CLLocation()

    func setLocation(coordinate: CLLocationCoordinate2D) {

        self.location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)

    }

}
</code>```

and your ViewController class should have:

```<code>func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {

    // instantiate your CreatePostView
    createPostView = createViewFromNib()

    // set it's .center property
    createPostView.center = SCREEN_CENTER_POSITION

    // here is where you "pass in" the coordinate
    createPostView.setLocation(coordinate: coordinate)

    // add it to your view
    self.view.addSubview(createPostView)

}
</code>```

You would want to use a delegate pattern if, for example, your createPostView had text fields and buttons, and you want to pass those values "up" to your ViewController.

Body:
Here's the relevant code:

in ViewController

protocol LocationDelegate {

    func setLocation(coordinate: CLLocationCoordinate2D)
}

var locationDelegate: LocationDelegate?

func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {

    locationDelegate?.setLocation(coordinate: coordinate)

    createPostView = createViewFromNib()
    createPostView.center = SCREEN_CENTER_POSITION
    self.view.addSubview(createPostView)
}

in CreatePostView

class CreatePostView: UIView, UINavigationControllerDelegate, LocationDelegate {

 var location: CLLocation! = CLLocation()

 func setLocation(coordinate: CLLocationCoordinate2D) {

    self.location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
 }

}

This doesn't work. "location" is always being saved as empty and I believe it's because I haven't set the delegate. I know this is usually done in prepareForSegue when passing data between two ViewControllers, but in this case, I'm not sure when to set it. How should I go about this?

Body:
I think you are confused about how the delegate pattern works.

If I understand what you are trying to do... In ViewController you are accepting a longPress on the mapView, which is also passing the CLLocationCoordinate2D. You then create a CreatePostView which you want to add to your view as a subview... and you want to set the location var in that createPostView instance to the long-press coordinate. Correct?

If so, you don't need the delegate at all.

Instead, your CreatePostView class should have:

class CreatePostView: UIView, UINavigationControllerDelegate {

    var location: CLLocation! = CLLocation()

    func setLocation(coordinate: CLLocationCoordinate2D) {

        self.location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)

    }

}

and your ViewController class should have:

func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {

    // instantiate your CreatePostView
    createPostView = createViewFromNib()

    // set it's .center property
    createPostView.center = SCREEN_CENTER_POSITION

    // here is where you "pass in" the coordinate
    createPostView.setLocation(coordinate: coordinate)

    // add it to your view
    self.view.addSubview(createPostView)

}

You would want to use a delegate pattern if, for example, your createPostView had text fields and buttons, and you want to pass those values "up" to your ViewController.


问:
How to convert Protobuf ByteString to an octal-escaped String in java?
Could anyone please let me know how to convert protobuf's ByteString to  an octal escape sequence String in java?

In my case, I am getting the ByteString value as \376\024\367 so,  when I print the string value in console using System.out.println(), I should get "\376\024\367".

Many thanks.

答:
Normally, you'd convert a ByteString to a String using ByteString#toString(Charset). This method lets you specify what charset the text is encoded in. If it's UTF-8, you can also use the method toStringUtf8() as a shortcut.

From your question, though, it sounds like you actually want to produce the escaped format using C-style three-digit octal escapes. AFAIK there's no public function to do this, but you can see the code here. You could copy that code into your own project and use it.


问:
Quick and dirty solution for communication between processes in different machines
I have two processes written in java in two machines within my network that should pass simple chunks of data to each other.

I'm looking for a quick and dirty way (without resorting to writing files and polling for changes on network share files)

答:
I'll second the idea of having your processes communicate via sockets, and mention that Apache's MINA package makes that sort of thing very simple and robust, as well as scalable, without the overhead of a larger system like RMI or JMS.  It also contains some good support for encoding and decoding messages.  I've used very successfully in a medium-scale system.

This kind of communication tends to be pretty easy to abstract, too.  Whether or not you use MINA, once you have classes set up to handle establishing/tearing down connections and moving data across the connections, they will probably be highly reusable.

OwnerDisplayName: Dani

OwnerDisplayName: MattK


问:
Check if one integer is an integer power of another
This is an interview question: "Given 2 integers x and y, check if x is an integer power of y" (e.g. for x = 8 and y = 2 the answer is "true", and for x = 10 and y = 2 "false").

The obvious solution is:```<code>int n = y; while(n < x) n *= y; return n == x</code>```

Now I am thinking about how to improve it.

Of course, I can check some special cases: e.g. both x and y should be either odd or even numbers, i.e. we can check the least significant bit of x and y. However I wonder if I can improve the core algorithm itself.

答:
This looks to be pretty fast for positive numbers as it finds the lower and upper limits for desired power and then applies binary search.</p>

```<code>#include <iostream>
#include <cmath>
using namespace std;

//x is the dividend, y the divisor.
bool isIntegerPower(int x, int y)
{
    int low = 0, high;
    int exp = 1;
    int val = y;
    //Loop by changing exponent in the powers of 2 and
    //Find out low and high exponents between which the required exponent lies.
    while(1)
    {
        val = pow((double)y, exp);
        if(val == x)
            return true;
        else if(val > x)
            break;
        low = exp;
        exp = exp * 2;
        high = exp;
    }
    //Use binary search to find out the actual integer exponent if exists
    //Otherwise, return false as no integer power.
    int mid = (low + high)/2;
    while(low < high)
    {
        val = pow((double)y, mid);
        if(val > x)
        {
            high = mid-1;
        }
        else if(val == x)
        {
            return true;
        }
        else if(val < x)
        {
            low = mid+1;
        }
        mid = (low + high)/2;
    }
    return false;
}

int main()
{
    cout<<isIntegerPower(1024,2);
}
</code>```

Body:
This is an interview question: "Given 2 integers x and y, check if x is an integer power of y" (e.g. for x = 8 and y = 2 the answer is "true", and for x = 10 and y = 2 "false").

The obvious solution is:
int n = y; while(n < x) n *= y; return n == x

Now I am thinking about how to improve it.

Of course, I can check some special cases: e.g. both x and y should be either odd or even numbers, i.e. we can check the least significant bit of x and y. However I wonder if I can improve the core algorithm itself.

Body:
This looks to be pretty fast for positive numbers as it finds the lower and upper limits for desired power and then applies binary search.

#include <iostream>
#include <cmath>
using namespace std;

//x is the dividend, y the divisor.
bool isIntegerPower(int x, int y)
{
    int low = 0, high;
    int exp = 1;
    int val = y;
    //Loop by changing exponent in the powers of 2 and
    //Find out low and high exponents between which the required exponent lies.
    while(1)
    {
        val = pow((double)y, exp);
        if(val == x)
            return true;
        else if(val > x)
            break;
        low = exp;
        exp = exp * 2;
        high = exp;
    }
    //Use binary search to find out the actual integer exponent if exists
    //Otherwise, return false as no integer power.
    int mid = (low + high)/2;
    while(low < high)
    {
        val = pow((double)y, mid);
        if(val > x)
        {
            high = mid-1;
        }
        else if(val == x)
        {
            return true;
        }
        else if(val < x)
        {
            low = mid+1;
        }
        mid = (low + high)/2;
    }
    return false;
}

int main()
{
    cout<<isIntegerPower(1024,2);
}


问:
How to correctly write into Google Spreadsheet with Google Apps Script?
I'm creating a webpage with a form and I have to send data to a Google Spreadsheet. I found a good code searching this site but I don't know how to edit it to store my data in Google Spreadsheet.

My form is made this way

```<code><form name="reqForm" id="reqForm" method="get" action="SCRIPT" accept-charset="UTF-8">
            <input type="hidden" name="reqID" id="reqID" />
            <label for="name">Name:</label>
               <input type="text" name="Name" id="Name"/>
            <label for="surname">Surname:</label>
               <input type="text" name="surname" id="surname"/>
            <label for="SERIAL">Serial:</label>
               <input type="text" name="serial" id="serial"/>
            <label for="email">E-mail:</label>
               <input type="text" name="email" id="mail"/>
            <label for="text">Request:</label>
               <textarea id="text"></textarea>
               <input type="submit" value="Send" />
</form>
</code>```

The script is the same, from the example I linked (I just changed the function name because of an error)

```<code>function doPost(e){

   var id = "";
   var name = e.parameter['name'];
   var surname = e.parameter['surname'];
   var serial = e.parameter['serial'];
   var eMail = e.parameter['email'];
   var text = e.parameter['text'];
   var date = new Date();
   var ans = ""
   var flag = "WIP";

   var vals = [id, date, name, surname, serial, eMail, text, ans, flag];

  var sheetObj = SpreadsheetApp.openById("myKey").getSheetByName('Requests').appendRow(vals);
  // return ContentService.createTextOutput(e);
</code>```

}

If I fill the form in this way:

Name: John

Surname: Doe

Serial: 123456

Email: 123@456.com

Request: Hello

in my Spreadsheet I see data in this order:
[DATE] [Serial] [Mail] [Name] [Surname]

How can modify the function to put my data into the spreadsheet in some kind of order that I can decide?

[UPDATE]: I updated the code: the result of this is a line correctly ordered but filled with "undefined"...

答:
After submitting the form, you can get form parameters using e.parameter[<parameter_name>].

For example to get the surname,

```<code>var surname = e.parameter['surname'];
</code>```

To insert form data in Google Spreadsheet,

```<code>var sheetObj = SpreadsheetApp.openById("myKey").getSheetByName("sheetname");
//Here you can shuffle the order of values anyway you want.
sheetObj.appendRow([DATE, Serial, Mail, Name, Surname]);
//or you can do it like this
sheetObj.appendRow([DATE, Mail, Name, Surname, Serial]);
</code>```

Hope this helps.

Body:
I'm creating a webpage with a form and I have to send data to a Google Spreadsheet. I found a good code searching this site but I don't know how to edit it to store my data in Google Spreadsheet.

My form is made this way

<form name="reqForm" id="reqForm" method="get" action="SCRIPT" accept-charset="UTF-8">
            <input type="hidden" name="reqID" id="reqID" />
            Name:
               <input type="text" name="Name" id="Name"/>
            Surname:
               <input type="text" name="surname" id="surname"/>
            Serial:
               <input type="text" name="serial" id="serial"/>
            E-mail:
               <input type="text" name="email" id="mail"/>
            Request:
               <textarea id="text"></textarea>
               <input type="submit" value="Send" />
</form>

The script is the same, from the example I linked (I just changed the function name because of an error)

function doPost(e){

   var id = "";
   var name = e.parameter['name'];
   var surname = e.parameter['surname'];
   var serial = e.parameter['serial'];
   var eMail = e.parameter['email'];
   var text = e.parameter['text'];
   var date = new Date();
   var ans = ""
   var flag = "WIP";

   var vals = [id, date, name, surname, serial, eMail, text, ans, flag];

  var sheetObj = SpreadsheetApp.openById("myKey").getSheetByName('Requests').appendRow(vals);
  // return ContentService.createTextOutput(e);

}

If I fill the form in this way:

Name: John

Surname: Doe

Serial: 123456

Email: 123@456.com

Request: Hello

in my Spreadsheet I see data in this order:
[DATE] [Serial] [Mail] [Name] [Surname]

How can modify the function to put my data into the spreadsheet in some kind of order that I can decide?

[UPDATE]: I updated the code: the result of this is a line correctly ordered but filled with "undefined"...

Body:
After submitting the form, you can get form parameters using e.parameter[<parameter_name>].

For example to get the surname,

var surname = e.parameter['surname'];

To insert form data in Google Spreadsheet,

var sheetObj = SpreadsheetApp.openById("myKey").getSheetByName("sheetname");
//Here you can shuffle the order of values anyway you want.
sheetObj.appendRow([DATE, Serial, Mail, Name, Surname]);
//or you can do it like this
sheetObj.appendRow([DATE, Mail, Name, Surname, Serial]);

Hope this helps.


问:
How to repartition a data frame in sparklyr
This is proving difficult to find for some reason. I can easily find the repartition function in pyspark and in sparkr, but no such function seems to exist in sparklyr.

Does anyone know how to repartition a Spark dataframe in sparklyr?

答:
Now you can use sdf_repartition(), e.g.

```<code>iris_tbl %>%
  sdf_repartition(5L, columns = c("Species", "Petal_Width")) %>%
  spark_dataframe() %>%
  invoke("queryExecution") %>%
  invoke("optimizedPlan")
# <jobj[139]>
#   class org.apache.spark.sql.catalyst.plans.logical.RepartitionByExpression
# RepartitionByExpression [Species#14, Petal_Width#13], 5
#                          +- InMemoryRelation [Sepal_Length#10, Sepal_Width#11, Petal_Length#12, Petal_Width#13, Species#14], true, 10000, StorageLevel(disk, memory, deserialized, 1 replicas), `iris`
#                                               +- *FileScan csv [Sepal_Length#10,Sepal_Width#11,Petal_Length#12,Petal_Width#13,Species#14] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/var/folders/ry/_l__tbl57d940bk2kgj8q2nj3s_d9b/T/Rtmpjgtnl6/spark_serializ..., PartitionFilters: [], PushedFilters: [], ReadSchema: struct<Sepal_Length:double,Sepal_Width:double,Petal_Length:double,Petal_Width:double,Species:string>
</code>```

Body:
Now you can use sdf_repartition(), e.g.

iris_tbl %>%
  sdf_repartition(5L, columns = c("Species", "Petal_Width")) %>%
  spark_dataframe() %>%
  invoke("queryExecution") %>%
  invoke("optimizedPlan")
# <jobj[139]>
#   class org.apache.spark.sql.catalyst.plans.logical.RepartitionByExpression
# RepartitionByExpression [Species#14, Petal_Width#13], 5
#                          +- InMemoryRelation [Sepal_Length#10, Sepal_Width#11, Petal_Length#12, Petal_Width#13, Species#14], true, 10000, StorageLevel(disk, memory, deserialized, 1 replicas), `iris`
#                                               +- *FileScan csv [Sepal_Length#10,Sepal_Width#11,Petal_Length#12,Petal_Width#13,Species#14] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/var/folders/ry/_l__tbl57d940bk2kgj8q2nj3s_d9b/T/Rtmpjgtnl6/spark_serializ..., PartitionFilters: [], PushedFilters: [], ReadSchema: struct<Sepal_Length:double,Sepal_Width:double,Petal_Length:double,Petal_Width:double,Species:string>


问:
When would getters and setters with mutex be thread safe?
Consider the following class:

```<code>class testThreads
{
private:
    int var; // variable to be modified
    std::mutex mtx; // mutex
public:
    void set_var(int arg) // setter
    {
        std::lock_guard<std::mutex> lk(mtx);
        var = arg;
    }

    int get_var() // getter
    {
        std::lock_guard<std::mutex> lk(mtx);
        return var;
    }

    void hundred_adder()
    {
        for(int i = 0; i < 100; i++)
        {
            int got = get_var();
            set_var(got + 1);
            sleep(0.1);
        }
     }
};
</code>```

When I create two threads in main(), each with a thread function of hundred_adder modifying the same variable var, the end result of the var is always different i.e. not 200 but some other number.

Conceptually speaking, why is this use of mutex with getter and setter functions not thread-safe? Do the lock-guards fail to prevent the race-condition to var? And what would be an alternative solution?

答:
```<code>Thread a: get 0
Thread b: get 0
Thread a: set 1
Thread b: set 1
</code>```

Lo and behold, var is 1 even though it should've been 2.

It should be obvious that you need to lock the whole operation:

```<code>for(int i = 0; i < 100; i++){
     std::lock_guard<std::mutex> lk(mtx);
     var += 1;
}
</code>```

Alternatively, you could make the variable atomic (even a relaxed one could do in your case).

Body:
Consider the following class:

class testThreads
{
private:
    int var; // variable to be modified
    std::mutex mtx; // mutex
public:
    void set_var(int arg) // setter
    {
        std::lock_guard<std::mutex> lk(mtx);
        var = arg;
    }

    int get_var() // getter
    {
        std::lock_guard<std::mutex> lk(mtx);
        return var;
    }

    void hundred_adder()
    {
        for(int i = 0; i < 100; i++)
        {
            int got = get_var();
            set_var(got + 1);
            sleep(0.1);
        }
     }
};

When I create two threads in main(), each with a thread function of hundred_adder modifying the same variable var, the end result of the var is always different i.e. not 200 but some other number.

Conceptually speaking, why is this use of mutex with getter and setter functions not thread-safe? Do the lock-guards fail to prevent the race-condition to var? And what would be an alternative solution?

Body:
Thread a: get 0
Thread b: get 0
Thread a: set 1
Thread b: set 1

Lo and behold, var is 1 even though it should've been 2.

It should be obvious that you need to lock the whole operation:

for(int i = 0; i < 100; i++){
     std::lock_guard<std::mutex> lk(mtx);
     var += 1;
}

Alternatively, you could make the variable atomic (even a relaxed one could do in your case).


问:
Clears the screen faster in assemly
I have problem with clearing the screen.

I was using call Clrscr but its slow. It is not fast enough, so i have screen, black, with no figure, because of waiting on function Clrscr to finish.

```<code>    call Clrscr

  ; Write a string to the console:
    INVOKE WriteConsole,
        consoleHandle,              ;console output handle
        ADDR HANGMAN_GOODGAME_00,               ; string pointer
        messageSizeGoodGame,                ; string length
        ADDR bytesWritten,          ; returns num bytes written
        0                           ; not used

    mov eax, drowDelay
    call Delay
    call Clrscr

  ; Write a string to the console:
    INVOKE WriteConsole,
        consoleHandle,              ;console output handle
        ADDR HANGMAN_GOODGAME_01,               ; string pointer
        messageSizeGoodGame,                ; string length
        ADDR bytesWritten,          ; returns num bytes written
        0                           ; not used

    mov eax, drowDelay
    call Delay
    call Clrscr

  ........
</code>```

This is photo. How Its look without slearing. I am trying to make animation..:)

答:
You can just set cursor position.

Just use setcursorpos from winapi:

```<code>push 0
push 0
call [SetCursorPos]
</code>```

Its in the user32.dll

Edit: the way it wokrs is simple, you set the cursor position to the top left corner making the feel of movement

Title: Clears the screen faster in assemly

Body:
I have problem with clearing the screen.

I was using call Clrscr but its slow. It is not fast enough, so i have screen, black, with no figure, because of waiting on function Clrscr to finish.

    call Clrscr

  ; Write a string to the console:
    INVOKE WriteConsole,
        consoleHandle,              ;console output handle
        ADDR HANGMAN_GOODGAME_00,               ; string pointer
        messageSizeGoodGame,                ; string length
        ADDR bytesWritten,          ; returns num bytes written
        0                           ; not used

    mov eax, drowDelay
    call Delay
    call Clrscr

  ; Write a string to the console:
    INVOKE WriteConsole,
        consoleHandle,              ;console output handle
        ADDR HANGMAN_GOODGAME_01,               ; string pointer
        messageSizeGoodGame,                ; string length
        ADDR bytesWritten,          ; returns num bytes written
        0                           ; not used

    mov eax, drowDelay
    call Delay
    call Clrscr

  ........

This is photo. How Its look without slearing. I am trying to make animation..:)

Body:
You can just set cursor position.

Just use setcursorpos from winapi:

push 0
push 0
call [SetCursorPos]

Its in the user32.dll

Edit: the way it wokrs is simple, you set the cursor position to the top left corner making the feel of movement


问:
iPhone Gigya integration sharing Facebook, twitter inconsistency
I am  currently integrating facebook and twitter for iphone with gigya.

For Twitter sometimes its sharing and sometimes don't. Facebook also happening same as well.

lately facebook not even opening its login in screen. On device unlike simulator delegate methods like LoginDidFail, DidLogin called more than once.not sure why.

I am not storing any object to store provider info when login happens.

Can you please let me know why this inconsis

答:
I am using following code snippet

GSAPI *gsAPI // declared this in header file

gsAPI = [[GSAPI alloc] initWithAPIKey:XX viewController:self]; // i kept this in viewDidload

// add this code to have facebook and twitter on provider list. this was put in in one method which will be called when user tries to share

GSDictionary *pParams5 = [[GSDictionary new] autorelease]; [pParams5 putStringValue:@"facebook,twitter" forKey:@"enabledProviders"];
[gsAPI showAddConnectionsUI:pParams5 delegate:self context:nil];

//this method called when login fails -(void)gsLoginUIDidFail:(int)errorCode errorMessage:(NSString*)errorMessage context:(id)context {

}

// this method called on successful login
- (void) gsLoginUIDidLogin:(NSString*)provider user:(GSDictionary*)user context:(id)context {

GSDictionary *userAction = [[GSDictionary new] autorelease];

[userAction putStringValue:@"title" forKey:@"title"];

[userAction putStringValue:@"userMessage" forKey:@"userMessage"];

[userAction putStringValue:@"desc" forKey:@"description"];

[userAction putStringValue:@"imageurl" forKey:@"linkBack"];

GSDictionary *pParams5 = [[GSDictionary new] autorelease];

[pParams5 putGSDictionaryValue:userAction forKey:@"userAction"];

[gsAPI sendRequest:@"socialize.publishUserAction" params:pParams5 delegate:self context:nil];

}

-(void) gsDidReceiveResponse:(NSString*)method response:(GSResponse*)response context:(id)context  {
//showing alert messages on successful sharing
//this method getting called more than twice on device
}


问:
Google Play - Fully Shadowed apk
I have an existing app on the PlayStore. I am releasing new version of the app as staged rollout. However, I am not able to publish the app due to "Fully Shadowed APK" error.

So far, I haven't found any documentation as to how to resolve this error. Anyone else faced this?

答:
We ran into this problem as well with split APKs. We assigned version code for each ABI with the following gradle (simplified):

```<code>ext.abiCodes = ['universal': 0, 'arm64-v8a': 1, 'armeabi-v7a': 2, 'x86': 3, 'x86_64': 4, ...]

android {

  applicationVariants.all { variant ->

    variant.outputs.each { output ->
      def abiName = output.getFilter(OutputFile.ABI)
      def abiVersionCode = project.ext.abiCodes.get(abiName)

      output.versionCodeOverride = variant.versionCode * 100 + abiVersionCode
      ...
</code>```

With that we will have these APKs:

```<code>| ABI       | Version Code |
|-----------|--------------|
| universal | v100         |
| arm64-v8a | v101         |
| arm64-v7a | v102         |
| ...       | ...          |
</code>```

And we got this "Fully Shadowed APK" error on APK v101. The reason is that any device that is on arm64-v8a will be able to install v102 since it is backward compatible.

Problem solved after we make the version code of armeabi-v8a higher than arm64-v7a.

```<code>ext.abiCodes = ['universal': 0, 'arm64-v7a': 1, 'armeabi-v8a': 2, 'x86': 3, 'x86_64': 4, ...]
</code>```

You should watch out for this too.

Title: Google Play - Fully Shadowed apk

Body:
We ran into this problem as well with split APKs. We assigned version code for each ABI with the following gradle (simplified):

ext.abiCodes = ['universal': 0, 'arm64-v8a': 1, 'armeabi-v7a': 2, 'x86': 3, 'x86_64': 4, ...]

android {

  applicationVariants.all { variant ->

    variant.outputs.each { output ->
      def abiName = output.getFilter(OutputFile.ABI)
      def abiVersionCode = project.ext.abiCodes.get(abiName)

      output.versionCodeOverride = variant.versionCode * 100 + abiVersionCode
      ...

With that we will have these APKs:

| ABI       | Version Code |
|-----------|--------------|
| universal | v100         |
| arm64-v8a | v101         |
| arm64-v7a | v102         |
| ...       | ...          |

And we got this "Fully Shadowed APK" error on APK v101. The reason is that any device that is on arm64-v8a will be able to install v102 since it is backward compatible.

Problem solved after we make the version code of armeabi-v8a higher than arm64-v7a.

ext.abiCodes = ['universal': 0, 'arm64-v7a': 1, 'armeabi-v8a': 2, 'x86': 3, 'x86_64': 4, ...]

You should watch out for this too.


问:
fgets() doesn't function as expected
This is my code

```<code>int main(){
   int N,i,radius,diameter,count =0;
   char str[20];
   char color[N][20];
   printf("Get the num : ");
   scanf("%d",&N);

   printf("Enter the mesage\n");
   for(i=0;i<N;i++){
      fgets(color[i],20,stdin);
   }
   for(i=0;i<N;i++){
      printf("%s",color[i]);
  }
  return 0;
}
</code>```

Given inputs are:

```<code>N = 3
red 50,
50 green,
blue 50
</code>```

Here the problem is fgets inside for loop gets executed only twice if N is 3. This problem doesn't arise if I comment the scanf statement. Can somebody explain me what is causing this problem and how it can be solved?

答:
After using scanf you'd need to clean the buffer. I suggest to never use scanf, just use fgets and then convert the output to a number:

```<code>int main(){
   int N,i,radius,diameter,count =0;
   char str[20];
   char color[N][20];
   printf("Get the num : ");

   char buffer[64];
   fgets(buffer, 64, stdin);
   N = atoi(buffer); // you need to include stdlib.h

   printf("Enter the mesage\n");
   for(i=0;i<N;i++){
      fgets(color[i],20,stdin);
   }
   for(i=0;i<N;i++){
      printf("%s",color[i]);
  }
  return 0;
}
</code>```

Title: fgets() doesn't function as expected

Body:
This is my code

int main(){
   int N,i,radius,diameter,count =0;
   char str[20];
   char color[N][20];
   printf("Get the num : ");
   scanf("%d",&N);

   printf("Enter the mesage\n");
   for(i=0;i<N;i++){
      fgets(color[i],20,stdin);
   }
   for(i=0;i<N;i++){
      printf("%s",color[i]);
  }
  return 0;
}

Given inputs are:

N = 3
red 50,
50 green,
blue 50

Here the problem is fgets inside for loop gets executed only twice if N is 3. This problem doesn't arise if I comment the scanf statement. Can somebody explain me what is causing this problem and how it can be solved?

Body:
After using scanf you'd need to clean the buffer. I suggest to never use scanf, just use fgets and then convert the output to a number:

int main(){
   int N,i,radius,diameter,count =0;
   char str[20];
   char color[N][20];
   printf("Get the num : ");

   char buffer[64];
   fgets(buffer, 64, stdin);
   N = atoi(buffer); // you need to include stdlib.h

   printf("Enter the mesage\n");
   for(i=0;i<N;i++){
      fgets(color[i],20,stdin);
   }
   for(i=0;i<N;i++){
      printf("%s",color[i]);
  }
  return 0;
}


问:
How do I to successfully build angular 2 without magic tools like Angular CLI
I've had a working Angular 2 application since Beta. Things were rather straightforward early on, with the build process mostly being a loading of various script files and referencing them.

With systemjs, things have grown more steadily complicated. Every tutorial and guide out there basically recommends you copy the entirety of the node_modules/@angular folder.

There's so much unnecessary junk in there though that I'm trying to avoid that. I'm trying to understand all the individual components involved so I can cleanly structure my build process without requiring tools to "magically" handle it for me.

I thought the bundles in @angular/bundles would solve this for me, where I can copy those over to my build directory and reference them in the systemjs configuration file and be dandy. That doesn't seem to be the case, however.

A whole other can of worms is opened when you also try doing the same for RXJS, which angular is dependent on. So that's another entire folder that I'm encouraged to copy over entirely.

Is the bootstrapping and module loading process really so complex that we should be encouraging developers to rely on carefully crafted seed libraries or tools like angular-cli, without themselves fully understanding how everything is integrated and loaded?

答:
There are many ways to build Angular 2. Tooling is one of those things that tends to drift slowly over time. There are starter projects that will get you going, but it is useful to be able to build your tools yourself, without relying on magic, even if you ultimately end up on the happy-path with ng-cli.

Here are the things  you will need:

Node / NPM

Node is JavaScript that runs in your command line. It's the platform on which pretty much everything else is built.

It comes with a package manager called NPM, which we use to install the other dependencies.

Create a new folder to house your project. Navigate to it, and type:

```<code>npm init
</code>```

to initialise a new project.

Node projects are insanely low-tech. The project will consist of a folder with a package.json file inside it. Package.json simply defines the project name, description, dev scripts and dependencies. This is all you need. The rest is up to you.

Webpack

Webpack is a JavaScript module builder with additional capabilities. Point it at a root file, then require other files, and they will be bundled into a tree of managed dependencies.

Webpack has loaders which will let it interact with other file types, notably TypeScript and SASS.

It's an npm install. Get the command line tool with:

```<code>npm install webpack -g
</code>```

Then for good measure, install a local copy in your project directory:

```<code>npm install webpack --save-dev
</code>```

TSC (TypeScript Compiler)

This transforms TypeScript into regular JavaScript. Again, it's an npm install.

```<code>npm install tsc --save-dev
</code>```

and for good measure, because we might want the command line tool from outside a project directory later:

```<code>npm install tsc -g
</code>```

TypeScript-loader

Now you need to connect TypeScript to Webpack. You do this with a loader. The standard adapter is called typescript-loader, but there are others.

```<code>npm install typescript-loader --save-dev
</code>```

webpack.config.js

You'll need some config files in the root folder of your project. webpack.config.js tells webpack how to build. Here's a micro version that just points at app.js and builds app.build.js, using the typescript-loader for compilation.

```<code>module.exports =  {
  entry: {
    app: "./app/app.ts"
  },
  output: {
    filename: "./app.build/app.build.js",
  },
  resolve: {
    extensions: ['.js', '.ts']
  },
  resolveLoader: {
    root: path.join(__dirname, 'node_modules')
  },
  module: {
    loaders: [
      {
        test: /\.ts$/,
        loaders: ['typescript-loader'],
        tsconfig: './tsconfig,json'
      },
    ]
  }
}
</code>```

tsconfig.json

Now you need some Angular specific instructions to tell TypeScript how to build Angular code. You'll need to tell it about decorators, and tell it to preserve typing information.

```<code>{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}
</code>```

Typings

Typings let the TSC compiler work with JavaScript libraries. You can use typings to manage them, or you can just stick them in a directory.

Get your typings here:

https://angular.io/docs/ts/latest/guide/typescript-configuration.html

Running it

Because we have webpack, you should be able to just run:

```<code>webpack -wd
</code>```

in the root of the project.

Done?

There's going to be a lot of debugging here. It'll take a while to get this right. Also, your build tools will change over time, and you'll want to stay up to date.

This list was current in June 2017, but will probably be out of date pretty quickly.

That should be enough for a minimal stack. There's a lot more we might want to build into this. We might also want:

Tests with Karma

SASS, built with Webpack

Separate vendor.js and polyfills.js

Livereload, probably with live-server

NPM convenience scripts

Code Generation with Yeoman

All this will change...

Webpack is the current best build tool, but there will be others. Before Webpack, we had Gulp, Browserify, Grunt, even RequireJS. They all did their own things, and had their own configuration. Manually keeping a toolchain up to date can take up a not-inconsequential fraction of your day.

This is why we have tools like @angular/cli, which is a community effort to produce a really nice toolchain that does all the above and more. It's really fast, and it hardly ever crashes.

Building your own toolchain is rather like building your own lightsabre though. Sure, you can buy a lightsabre off the shelf, but to be a real Jedi, you must know how to construct your own.

Body:
There are many ways to build Angular 2. Tooling is one of those things that tends to drift slowly over time. There are starter projects that will get you going, but it is useful to be able to build your tools yourself, without relying on magic, even if you ultimately end up on the happy-path with ng-cli.

Here are the things  you will need:

Node / NPM

Node is JavaScript that runs in your command line. It's the platform on which pretty much everything else is built.

It comes with a package manager called NPM, which we use to install the other dependencies.

Create a new folder to house your project. Navigate to it, and type:

npm init

to initialise a new project.

Node projects are insanely low-tech. The project will consist of a folder with a package.json file inside it. Package.json simply defines the project name, description, dev scripts and dependencies. This is all you need. The rest is up to you.

Webpack

Webpack is a JavaScript module builder with additional capabilities. Point it at a root file, then require other files, and they will be bundled into a tree of managed dependencies.

Webpack has loaders which will let it interact with other file types, notably TypeScript and SASS.

It's an npm install. Get the command line tool with:

npm install webpack -g

Then for good measure, install a local copy in your project directory:

npm install webpack --save-dev

TSC (TypeScript Compiler)

This transforms TypeScript into regular JavaScript. Again, it's an npm install.

npm install tsc --save-dev

and for good measure, because we might want the command line tool from outside a project directory later:

npm install tsc -g

TypeScript-loader

Now you need to connect TypeScript to Webpack. You do this with a loader. The standard adapter is called typescript-loader, but there are others.

npm install typescript-loader --save-dev

webpack.config.js

You'll need some config files in the root folder of your project. webpack.config.js tells webpack how to build. Here's a micro version that just points at app.js and builds app.build.js, using the typescript-loader for compilation.

module.exports =  {
  entry: {
    app: "./app/app.ts"
  },
  output: {
    filename: "./app.build/app.build.js",
  },
  resolve: {
    extensions: ['.js', '.ts']
  },
  resolveLoader: {
    root: path.join(__dirname, 'node_modules')
  },
  module: {
    loaders: [
      {
        test: /\.ts$/,
        loaders: ['typescript-loader'],
        tsconfig: './tsconfig,json'
      },
    ]
  }
}

tsconfig.json

Now you need some Angular specific instructions to tell TypeScript how to build Angular code. You'll need to tell it about decorators, and tell it to preserve typing information.

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

Typings

Typings let the TSC compiler work with JavaScript libraries. You can use typings to manage them, or you can just stick them in a directory.

Get your typings here:

https://angular.io/docs/ts/latest/guide/typescript-configuration.html

Running it

Because we have webpack, you should be able to just run:

webpack -wd

in the root of the project.

Done?

There's going to be a lot of debugging here. It'll take a while to get this right. Also, your build tools will change over time, and you'll want to stay up to date.

This list was current in June 2017, but will probably be out of date pretty quickly.

That should be enough for a minimal stack. There's a lot more we might want to build into this. We might also want:

Tests with Karma

SASS, built with Webpack

Separate vendor.js and polyfills.js

Livereload, probably with live-server

NPM convenience scripts

Code Generation with Yeoman

All this will change...

Webpack is the current best build tool, but there will be others. Before Webpack, we had Gulp, Browserify, Grunt, even RequireJS. They all did their own things, and had their own configuration. Manually keeping a toolchain up to date can take up a not-inconsequential fraction of your day.

This is why we have tools like @angular/cli, which is a community effort to produce a really nice toolchain that does all the above and more. It's really fast, and it hardly ever crashes.

Building your own toolchain is rather like building your own lightsabre though. Sure, you can buy a lightsabre off the shelf, but to be a real Jedi, you must know how to construct your own.


答:
The code show in thread-safe in a sense that it will never set or get partial value of the variable.

But your usage of the methods does not guarantee that value will correctly change: reading and writing from multiple threads can collide with each other. Both threads read the value (11), both increment it (to 12) and than both set to the same (12) - now you counted 2 but effectively incremented only once.

Option to fix:

provide "safe increment" operation

provide equivalent of InterlockedCompareExchange to make sure value you are updating correspond to original one and retry as necessary

wrap calling code into separate mutex or use other synchronization mechanism to prevent operations to intermix.

Title: When would getters and setters with mutex be thread safe?


问:
Spacing at last part of the regex
I've the following regex:

/(\(*)?(\d+)(\)*)?([+\-*\/^%]+)(\(*)?(\)*)?/g

I have the following string:

(5+4+8+5)+(5^2/(23%2))

I use the regex to add space between numbers, arithmetic operators and parentheses.

I do that like:

\1 \2 \3 \4 \5 \6

That turns the string into:

( 5  +   4  +   8  +   5 ) + (  5  ^   2  / (  23  %  2))

As you can see the last two parentheses don't get spaced.

How can I make them space as well?

The output should look like:

( 5  +   4  +   8  +   5 ) + (  5  ^   2  / (  23  %  2 ))

Try out the regex here.

答:
You could try a simple and fast solution

edit

Some tips:

I know you are not validating the simple math expressions, but it would not hurt to do that before trying to beautify.

Either way you should remove all whitespace ahead of time

Find \s+  Replace nothing

To condense summation symbols you could do:

Find (?:--)+|\++  Replace +

Find [+-]*-+* Replace -

Division and power symbol meaning will vary with implementation,

and to condense them is not advisable, and better to just validate the form.

Validation is the more complex feat complicated by the meaning of parenthesis,

and their balance. That is another topic.

A minimum character validation should be done though.

String must be matched by ^[+\-*/^%()\d]+$ at least.

After optionally doing the above, run the beautifier on it.

https://regex101.com/r/NUj036/2

Find ((?:(?<=[+\-*/^%()])-)?\d+(?!\d)|[+\-*/^%()])(?!$))

Replace '$1 '

Explained

```<code> (                             # (1 start)
      (?:                           # Allow negation if symbol is behind it
           (?<= [+\-*/^%()] )
           -
      )?
      \d+                           # Many digits
      (?! \d )                      #  - don't allow digits ahead
   |                              # or,
      [+\-*/^%()]                   # One of these operators
 )                             # (1 end)
 (?! $ )                       # Don't match if at end of string
</code>```

Title: Spacing at last part of the regex

Body:
You could try a simple and fast solution

edit

Some tips:

I know you are not validating the simple math expressions, but it would not hurt to do that before trying to beautify.

Either way you should remove all whitespace ahead of time

Find \s+  Replace nothing

To condense summation symbols you could do:

Find (?:--)+|\++  Replace +

Find [+-]*-+* Replace -

Division and power symbol meaning will vary with implementation,

and to condense them is not advisable, and better to just validate the form.

Validation is the more complex feat complicated by the meaning of parenthesis,

and their balance. That is another topic.

A minimum character validation should be done though.

String must be matched by ^[+\-*/^%()\d]+$ at least.

After optionally doing the above, run the beautifier on it.

https://regex101.com/r/NUj036/2

Find ((?:(?<=[+\-*/^%()])-)?\d+(?!\d)|[+\-*/^%()])(?!$))

Replace '$1 '

Explained

 (                             # (1 start)
      (?:                           # Allow negation if symbol is behind it
           (?<= [+\-*/^%()] )
           -
      )?
      \d+                           # Many digits
      (?! \d )                      #  - don't allow digits ahead
   |                              # or,
      [+\-*/^%()]                   # One of these operators
 )                             # (1 end)
 (?! $ )                       # Don't match if at end of string


问:
Can't get object attribute in IE8
I have following problem that I can't figure out.
I a homepage on my WP blog that contains some youtube videos.
My task is to get all youtube URLs from youtube objects on the page.

So I did something like this:

```<code>jQuery("object").each(function() {
  $ytbURL = jQuery(this).find("embed").attr("src");
  $ytbID = $ytbURL.match(...); //here I got error from IE8 that ytbURLis null or not and object
});
</code>```

On FF it works flawlessly.

Update 15/12:
Here are the code samples.

IE8 - Developer tools:

```<code><OBJECT codeBase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" classid=clsid:d27cdb6e-ae6d-11cf-96b8-444553540000 width=320 height=267><PARAM NAME="_cx" VALUE="8466"><PARAM NAME="_cy" VALUE="7064"><PARAM NAME="FlashVars" VALUE=""><PARAM NAME="Movie" VALUE="http://www.youtube.com/v/TDlqMuGqTyE?fs=1&hl=en&fs=1&rel=0"><PARAM NAME="Src" VALUE="http://www.youtube.com/v/TDlqMuGqTyE?fs=1&hl=en&fs=1&rel=0"><PARAM NAME="WMode" VALUE="Transparent"><PARAM NAME="Play" VALUE="0"><PARAM NAME="Loop" VALUE="-1"><PARAM NAME="Quality" VALUE="High"><PARAM NAME="SAlign" VALUE="LT"><PARAM NAME="Menu" VALUE="-1"><PARAM NAME="Base" VALUE=""><PARAM NAME="AllowScriptAccess" VALUE=""><PARAM NAME="Scale" VALUE="NoScale"><PARAM NAME="DeviceFont" VALUE="0"><PARAM NAME="EmbedMovie" VALUE="0"><PARAM NAME="BGColor" VALUE=""><PARAM NAME="SWRemote" VALUE=""><PARAM NAME="MovieData" VALUE=""><PARAM NAME="SeamlessTabbing" VALUE="1"><PARAM NAME="Profile" VALUE="0"><PARAM NAME="ProfileAddress" VALUE=""><PARAM NAME="ProfilePort" VALUE="0"><PARAM NAME="AllowNetworking" VALUE="all"><PARAM NAME="AllowFullScreen" VALUE="true">
<embed type="application/x-shockwave-flash" width="320" height="267" src="http://www.youtube.com/v/TDlqMuGqTyE?fs=1&hl=en&fs=1&rel=0" allowfullscreen="true" wmode="transparent"></embed></OBJECT>
</code>```

Wordpress:

```<code><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="320" height="267" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="wmode" value="transparent" /><param name="allowfullscreen" value="true" /><param name="src" value="http://www.youtube.com/v/TDlqMuGqTyE?fs=1&hl=en&fs=1&rel=0" /><embed type="application/x-shockwave-flash" width="320" height="267" src="http://www.youtube.com/v/TDlqMuGqTyE?fs=1&hl=en&fs=1&rel=0" allowfullscreen="true" wmode="transparent"></embed></object>
</code>```

Looks like IE8 does some changes to source HTML or maybe it's the way how Developer Tools displays it?

Thanx

Sam

答:
I would try using jQuery's awesome $ function instead of jQuery, and see if it works:

```<code>$('object').each(function()
{
  $ytbURL = $(this).find('embed').attr('src');
  $ytbID = $ytbURL.match(...);
});
</code>```

I doubt there would be a difference, but it might work. Oh, and here's a really useful YouTube video ID grabber regex, just in case you need it: (?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+.

Good luck!

Try this. Also, could you give us an example of the DOM jQuery is parsing? It could be because there are multiple <embed> tags, so jQuery(this).find('embed') would return an array, not a single object.

```<code>jQuery('object').each(function()
{
  $ytbURL = jQuery(this).children('embed:eq(0)').attr('src');
  $ytbID = $ytbURL.match(...);
});
</code>```

Title: Can't get object attribute in IE8

Body:
I have following problem that I can't figure out.
I a homepage on my WP blog that contains some youtube videos.
My task is to get all youtube URLs from youtube objects on the page.

So I did something like this:

jQuery("object").each(function() {
  $ytbURL = jQuery(this).find("embed").attr("src");
  $ytbID = $ytbURL.match(...); //here I got error from IE8 that ytbURLis null or not and object
});

On FF it works flawlessly.

Update 15/12:
Here are the code samples.

IE8 - Developer tools:

<OBJECT codeBase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" classid=clsid:d27cdb6e-ae6d-11cf-96b8-444553540000 width=320 height=267><PARAM NAME="_cx" VALUE="8466"><PARAM NAME="_cy" VALUE="7064"><PARAM NAME="FlashVars" VALUE=""><PARAM NAME="Movie" VALUE="http://www.youtube.com/v/TDlqMuGqTyE?fs=1&hl=en&fs=1&rel=0"><PARAM NAME="Src" VALUE="http://www.youtube.com/v/TDlqMuGqTyE?fs=1&hl=en&fs=1&rel=0"><PARAM NAME="WMode" VALUE="Transparent"><PARAM NAME="Play" VALUE="0"><PARAM NAME="Loop" VALUE="-1"><PARAM NAME="Quality" VALUE="High"><PARAM NAME="SAlign" VALUE="LT"><PARAM NAME="Menu" VALUE="-1"><PARAM NAME="Base" VALUE=""><PARAM NAME="AllowScriptAccess" VALUE=""><PARAM NAME="Scale" VALUE="NoScale"><PARAM NAME="DeviceFont" VALUE="0"><PARAM NAME="EmbedMovie" VALUE="0"><PARAM NAME="BGColor" VALUE=""><PARAM NAME="SWRemote" VALUE=""><PARAM NAME="MovieData" VALUE=""><PARAM NAME="SeamlessTabbing" VALUE="1"><PARAM NAME="Profile" VALUE="0"><PARAM NAME="ProfileAddress" VALUE=""><PARAM NAME="ProfilePort" VALUE="0"><PARAM NAME="AllowNetworking" VALUE="all"><PARAM NAME="AllowFullScreen" VALUE="true">
<embed type="application/x-shockwave-flash" width="320" height="267" src="http://www.youtube.com/v/TDlqMuGqTyE?fs=1&hl=en&fs=1&rel=0" allowfullscreen="true" wmode="transparent"></embed></OBJECT>

Wordpress:

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="320" height="267" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="wmode" value="transparent" /><param name="allowfullscreen" value="true" /><param name="src" value="http://www.youtube.com/v/TDlqMuGqTyE?fs=1&hl=en&fs=1&rel=0" /><embed type="application/x-shockwave-flash" width="320" height="267" src="http://www.youtube.com/v/TDlqMuGqTyE?fs=1&hl=en&fs=1&rel=0" allowfullscreen="true" wmode="transparent"></embed></object>

Looks like IE8 does some changes to source HTML or maybe it's the way how Developer Tools displays it?

Thanx

Sam

Body:
I would try using jQuery's awesome $ function instead of jQuery, and see if it works:

$('object').each(function()
{
  $ytbURL = $(this).find('embed').attr('src');
  $ytbID = $ytbURL.match(...);
});

I doubt there would be a difference, but it might work. Oh, and here's a really useful YouTube video ID grabber regex, just in case you need it: (?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+.

Good luck!

Try this. Also, could you give us an example of the DOM jQuery is parsing? It could be because there are multiple <embed> tags, so jQuery(this).find('embed') would return an array, not a single object.

jQuery('object').each(function()
{
  $ytbURL = jQuery(this).children('embed:eq(0)').attr('src');
  $ytbID = $ytbURL.match(...);
});