问:
Find last sequence episode and increment count variable
My data looks like this (person-period file), where hldid represents a unique identifier, variable represents time and paid is a dummy vector of interest

```<code>   hldid variable paid
1      1        1    0
2      1        2    0
3      1        3    0
4      1        4    1
5      1        5    1
6      1        6    0
7      1        7    1
8      1        8    1
9      1        9    0
10     1       10    0
11     2        1    0
12     2        2    0
13     2        3    1
14     2        4    1
15     2        5    0
16     2        6    1
17     2        7    0
18     2        8    0
19     2        9    0
20     2       10    0
</code>```

What I would like to achieve is this:

```<code>  hldid variable  paid  last wwork2
 1     1        1     0     0      0
 2     1        2     0     0      0
 3     1        3     0     0      0
 4     1        4     1     0      0
 5     1        5     1     0      0
 6     1        6     0     0     -2
 7     1        7     1     0     -1
 8     1        8     1     1      0
 9     1        9     0     0      1
10     1       10     0     0      2
11     2        1     0     0      0
12     2        2     0     0      0
13     2        3     1     0      0
14     2        4     1     0     -2
15     2        5     0     0     -1
16     2        6     1     1      0
17     2        7     0     0      1
18     2        8     0     0      2
19     2        9     0     0      0
20     2       10     0     0      0
</code>```

I would like to create a vector that (1) finds the latest episode of paid for each hldid and (2) to decrement/increment 2 episodes before and 2 episodes after the last episode of paid.

So far, this is what I did.

Find last episode of paid

What is complicated here is that paid is not a continuous sequence. For instance hldid == 1 stops paid at episode 6 and starts again at episode 7 and the last episode is at 8.

So my idea is to subset all the paid == 1, count the number of episodes and then merge it back. However, I am not sure this is the most efficient strategy.

```<code>ddw = dta %>% filter(paid == 1)
ddw$work = 0

for(i in 2:nrow(ddw)){
  if(ddw$hldid[i] == ddw$hldid[i-1] &
     ddw$paid[i] == 1){
    ddw$work[i] <- ddw$work[i-1] + 1
 }
}

ddf = merge(dta, ddw, by = c('hldid', 'variable', 'paid'), all = T)
</code>```

Then, I find the last episode with

```<code>ddw2 = ddf %>% group_by(hldid) %>% mutate(end_work = ifelse(work == max(work, na.rm = T), variable, 0))
</code>```

and finally I create a dummy indicating the position of the final paid episode

```<code>ddw2$end_work[is.na(ddw2$end_work)] <- 0
ddw2 = ddw2 %>% group_by(hldid) %>% mutate(wwork = ifelse(end_work == variable, 1, 0))
</code>```

Increment/decrement

Now, from here I don't know how to increment/decrement before and after the last episode. So far I could only come up with this:

```<code>df = ddw2
df$wwork2 = 0

for(i in 2:nrow(df)){
  if(df$hldid[i] == df$hldid[i-1] &
     df$wwork[i] == 1){
    df$wwork2[i-1] <- 1; df$wwork2[i] <- 1; df$wwork2[i+1] <- 1
  }
}
</code>```

data

```<code>dta = rbind(c(1,1,0),
      c(1,2,0),
      c(1,3,0),
      c(1,4,1),
      c(1,5,1),
      c(1,6,0),
      c(1,7,1),
      c(1,8,1),
      c(1,9,0),
      c(1,10,0),
      c(2,1,0),
      c(2,2,0),
      c(2,3,1),
      c(2,4,1),
      c(2,5,0),
      c(2,6,1),
      c(2,7,0),
      c(2,8,0),
      c(2,9,0),
      c(2,10,0))

colnames(dta) = c('hldid', 'variable', 'paid')
dta = as.data.frame(dta)

library(dplyr)
</code>```

Body:
My data looks like this (person-period file), where hldid represents a unique identifier, variable represents time and paid is a dummy vector of interest

   hldid variable paid
1      1        1    0
2      1        2    0
3      1        3    0
4      1        4    1
5      1        5    1
6      1        6    0
7      1        7    1
8      1        8    1
9      1        9    0
10     1       10    0
11     2        1    0
12     2        2    0
13     2        3    1
14     2        4    1
15     2        5    0
16     2        6    1
17     2        7    0
18     2        8    0
19     2        9    0
20     2       10    0

What I would like to achieve is this:

  hldid variable  paid  last wwork2
 1     1        1     0     0      0
 2     1        2     0     0      0
 3     1        3     0     0      0
 4     1        4     1     0      0
 5     1        5     1     0      0
 6     1        6     0     0     -2
 7     1        7     1     0     -1
 8     1        8     1     1      0
 9     1        9     0     0      1
10     1       10     0     0      2
11     2        1     0     0      0
12     2        2     0     0      0
13     2        3     1     0      0
14     2        4     1     0     -2
15     2        5     0     0     -1
16     2        6     1     1      0
17     2        7     0     0      1
18     2        8     0     0      2
19     2        9     0     0      0
20     2       10     0     0      0

I would like to create a vector that (1) finds the latest episode of paid for each hldid and (2) to decrement/increment 2 episodes before and 2 episodes after the last episode of paid.

So far, this is what I did.

Find last episode of paid

What is complicated here is that paid is not a continuous sequence. For instance hldid == 1 stops paid at episode 6 and starts again at episode 7 and the last episode is at 8.

So my idea is to subset all the paid == 1, count the number of episodes and then merge it back. However, I am not sure this is the most efficient strategy.

ddw = dta %>% filter(paid == 1)
ddw$work = 0

for(i in 2:nrow(ddw)){
  if(ddw$hldid[i] == ddw$hldid[i-1] &
     ddw$paid[i] == 1){
    ddw$work[i] <- ddw$work[i-1] + 1
 }
}

ddf = merge(dta, ddw, by = c('hldid', 'variable', 'paid'), all = T)

Then, I find the last episode with

ddw2 = ddf %>% group_by(hldid) %>% mutate(end_work = ifelse(work == max(work, na.rm = T), variable, 0))

and finally I create a dummy indicating the position of the final paid episode

ddw2$end_work[is.na(ddw2$end_work)] <- 0
ddw2 = ddw2 %>% group_by(hldid) %>% mutate(wwork = ifelse(end_work == variable, 1, 0))

Increment/decrement

Now, from here I don't know how to increment/decrement before and after the last episode. So far I could only come up with this:

df = ddw2
df$wwork2 = 0

for(i in 2:nrow(df)){
  if(df$hldid[i] == df$hldid[i-1] &
     df$wwork[i] == 1){
    df$wwork2[i-1] <- 1; df$wwork2[i] <- 1; df$wwork2[i+1] <- 1
  }
}

data

dta = rbind(c(1,1,0),
      c(1,2,0),
      c(1,3,0),
      c(1,4,1),
      c(1,5,1),
      c(1,6,0),
      c(1,7,1),
      c(1,8,1),
      c(1,9,0),
      c(1,10,0),
      c(2,1,0),
      c(2,2,0),
      c(2,3,1),
      c(2,4,1),
      c(2,5,0),
      c(2,6,1),
      c(2,7,0),
      c(2,8,0),
      c(2,9,0),
      c(2,10,0))

colnames(dta) = c('hldid', 'variable', 'paid')
dta = as.data.frame(dta)

library(dplyr)

Body:
We can try with data.table

library(data.table)
setDT(dta)[,  c('last', 'wwork2') := {
       i1 <- which.max(cumsum(paid))
       i2 <- seq_len(.N) - i1
     .(as.integer(seq_len(.N) ==i1), i2*(abs(i2) <=2))
         },  by = hldid]

df1
#     hldid variable paid last wwork2
# 1:     1        1    0    0      0
# 2:     1        2    0    0      0
# 3:     1        3    0    0      0
# 4:     1        4    1    0      0
# 5:     1        5    1    0      0
# 6:     1        6    0    0     -2
# 7:     1        7    1    0     -1
# 8:     1        8    1    1      0
# 9:     1        9    0    0      1
#10:     1       10    0    0      2
#11:     2        1    0    0      0
#12:     2        2    0    0      0
#13:     2        3    1    0      0
#14:     2        4    1    0     -2
#15:     2        5    0    0     -1
#16:     2        6    1    1      0
#17:     2        7    0    0      1
#18:     2        8    0    0      2
#19:     2        9    0    0      0
#20:     2       10    0    0      0


来源: stackexchange

问:
how to add shake animation for a span element inside div
```<code> <div id="about-desc">
    <p>
 Lorem ipsum dolor sit <span class="animation">amet</span>, consectetur adipisicing elit. <span class="animation"> Officia reprehenderit</span>, <span class="animation"> sit eligendi</span> deserunt, blanditiis quas porro omnis provident quidem voluptate! Fugit ipsa mollitia, atque commodi asperiores, rerum dicta ratione aut.
    </p>
 </div>

$(document).ready(function () {
  $(".animation").addClass("animated shake");
});
</code>```

<p>I am not able to figure out where i actually went wrong. When i add animation to div element it is working correctly but it's not happening with span element? Can somebody explain how to solve this problem </p>

答:
span is an inline element by default and therefore can not perform a transformation. Add display: inline-block to your animation or add to the span so it is transformable.

transformable element

A transformable element is an element in one of these categories:

an element whose layout is governed by the CSS box model which is either a block-level or atomic inline-level element, or whose display property computes to table-row, table-row-group, table-header-group, table-footer-group, table-cell, or table-caption [CSS21]

an element in the SVG namespace and not governed by the CSS box model which has the attributes transform, patternTransform or gradientTransform [SVG11].

REF: https://drafts.csswg.org/css-transforms-1/#terminology

The HTML  element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element is appropriate.  is very much like a
 element, but
 is a block-level element whereas a  is an inline element.

REF: https://developer.mozilla.org/en/docs/Web/HTML/Element/span

Option 1: Shake on hover

$(document).ready(function () {
  $(".animation").addClass("animated shake");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.shake:hover {
  animation: shake 0.82s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
  display: inline-block;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}</code>```

 Lorem ipsum dolor sit amet, consectetur adipisicing elit.  Officia reprehenderit,  sit eligendi deserunt, blanditiis quas porro omnis provident quidem voluptate! Fugit ipsa mollitia, atque commodi asperiores, rerum dicta ratione aut.

```
</div>
</div>
</p>
<h2>Option 2: shake forever</h2>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () {
  $(".animation").addClass("animated shake");
});</code>```

.shake {
  animation: shake 0.82s cubic-bezier(.36, .07, .19, .97) both infinite;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
  display: inline-block;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="about-desc">
    <p>
 Lorem ipsum dolor sit <span class="animation">amet</span>, consectetur adipisicing elit. <span class="animation"> Officia reprehenderit</span>, <span class="animation"> sit eligendi</span> deserunt, blanditiis quas porro omnis provident quidem voluptate! Fugit ipsa mollitia, atque commodi asperiores, rerum dicta ratione aut.
    </p>
 </div></code>```

ContentLicense: CC BY-SA 3.0

Body:
 Lorem ipsum dolor sit amet, consectetur adipisicing elit.  Officia reprehenderit,  sit eligendi deserunt, blanditiis quas porro omnis provident quidem voluptate! Fugit ipsa mollitia, atque commodi asperiores, rerum dicta ratione aut.

$(document).ready(function () {
  $(".animation").addClass("animated shake");
});

I am not able to figure out where i actually went wrong. When i add animation to div element it is working correctly but it's not happening with span element? Can somebody explain how to solve this problem

Body:
span is an inline element by default and therefore can not perform a transformation. Add display: inline-block to your animation or add to the span so it is transformable.

transformable element

A transformable element is an element in one of these categories:

an element whose layout is governed by the CSS box model which is either a block-level or atomic inline-level element, or whose display property computes to table-row, table-row-group, table-header-group, table-footer-group, table-cell, or table-caption [CSS21]

an element in the SVG namespace and not governed by the CSS box model which has the attributes transform, patternTransform or gradientTransform [SVG11].

REF: https://drafts.csswg.org/css-transforms-1/#terminology

The HTML <span> element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element is appropriate. <span> is very much like a <div> element, but <div> is a block-level element whereas a <span> is an inline element.

REF: https://developer.mozilla.org/en/docs/Web/HTML/Element/span

Option 1: Shake on hover

$(document).ready(function () {
  $(".animation").addClass("animated shake");
});

.shake:hover {
  animation: shake 0.82s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
  display: inline-block;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="about-desc">
    <p>
 Lorem ipsum dolor sit <span class="animation">amet</span>, consectetur adipisicing elit. <span class="animation"> Officia reprehenderit</span>, <span class="animation"> sit eligendi</span> deserunt, blanditiis quas porro omnis provident quidem voluptate! Fugit ipsa mollitia, atque commodi asperiores, rerum dicta ratione aut.
    </p>
 </div>

Option 2: shake forever

$(document).ready(function () {
  $(".animation").addClass("animated shake");
});

.shake {
  animation: shake 0.82s cubic-bezier(.36, .07, .19, .97) both infinite;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
  display: inline-block;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="about-desc">
    <p>
 Lorem ipsum dolor sit <span class="animation">amet</span>, consectetur adipisicing elit. <span class="animation"> Officia reprehenderit</span>, <span class="animation"> sit eligendi</span> deserunt, blanditiis quas porro omnis provident quidem voluptate! Fugit ipsa mollitia, atque commodi asperiores, rerum dicta ratione aut.
    </p>
 </div>


问:
Selenium PhantomJS click button inside class
i have problem when i tried to click button using selenium with webdriver Phantonjs. My code is like this :

```<code>from selenium import webdriver

driver = webdriver.PhantomJS()
driver.set_window_size(1120, 550)
driver.get("https://www.instagram.com/nike/")
dt = driver.find_elements_by_class_name("a_8imhp _glz1g")

for i in dt:
    i.click()

driver.quit()
</code>```

And the error is :

```<code>  File "test.py", line 8, in <module>
    dt = driver.find_elements_by_class_name("a_8imhp _glz1g")
  File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 427, in find_elements_by_class_name
    return self.find_elements(by=By.CLASS_NAME, value=name)
  File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 782, in find_elements
    'value': value})['value']
  File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 238, in execute
    self.error_handler.check_response(response)
  File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 193, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: {"errorMessage":"Compound class names not permitted","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"103","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:41380","User-Agent":"Python-urllib/3.6"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"class name\", \"value\": \"a_8imhp _glz1g\", \"sessionId\": \"fba6d030-4934-11e7-8712-9506860019f4\"}","url":"/elements","urlParsed":{"anchor":"","query":"","file":"elements","directory":"/","path":"/elements","relative":"/elements","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/elements","queryKey":{},"chunks":["elements"]},"urlOriginal":"/session/fba6d030-4934-11e7-8712-9506860019f4/elements"}}
Screenshot: available via screen
</code>```

答:
You cannot pass more than one class name to find_elements_by_class_name(). You can try to pass single name, e.g.

```<code>driver.find_elements_by_class_name("a_8imhp")
</code>```

or to use complex selectors, e.g. XPath or CSS selector

Just replace this

```<code>dt = driver.find_elements_by_class_name("a_8imhp _glz1g")
</code>```

with this

```<code>dt = driver.find_elements_by_css_selector(".a_8imhp._glz1g")
</code>```

or this

```<code>dt = driver.find_elements_by_xpath("//*[@class='a_8imhp _glz1g')
</code>```

Body:
i have problem when i tried to click button using selenium with webdriver Phantonjs. My code is like this :

from selenium import webdriver

driver = webdriver.PhantomJS()
driver.set_window_size(1120, 550)
driver.get("https://www.instagram.com/nike/")
dt = driver.find_elements_by_class_name("a_8imhp _glz1g")

for i in dt:
    i.click()

driver.quit()

And the error is :

  File "test.py", line 8, in <module>
    dt = driver.find_elements_by_class_name("a_8imhp _glz1g")
  File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 427, in find_elements_by_class_name
    return self.find_elements(by=By.CLASS_NAME, value=name)
  File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 782, in find_elements
    'value': value})['value']
  File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 238, in execute
    self.error_handler.check_response(response)
  File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 193, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: {"errorMessage":"Compound class names not permitted","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"103","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:41380","User-Agent":"Python-urllib/3.6"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"class name\", \"value\": \"a_8imhp _glz1g\", \"sessionId\": \"fba6d030-4934-11e7-8712-9506860019f4\"}","url":"/elements","urlParsed":{"anchor":"","query":"","file":"elements","directory":"/","path":"/elements","relative":"/elements","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/elements","queryKey":{},"chunks":["elements"]},"urlOriginal":"/session/fba6d030-4934-11e7-8712-9506860019f4/elements"}}
Screenshot: available via screen

Body:
You cannot pass more than one class name to find_elements_by_class_name(). You can try to pass single name, e.g.

driver.find_elements_by_class_name("a_8imhp")

or to use complex selectors, e.g. XPath or CSS selector

Just replace this

dt = driver.find_elements_by_class_name("a_8imhp _glz1g")

with this

dt = driver.find_elements_by_css_selector(".a_8imhp._glz1g")

or this

dt = driver.find_elements_by_xpath("//*[@class='a_8imhp _glz1g')


问:
PHP/HTML - Trying to make image appear using localhost
I am using XAMPP for APACHE server on localhost:8080 (I had to change the default port for it to work). Assume that I have the rest of the html needed to run.
Here is the current code:

home.html

```<code><body>
<script src="main/profile.php"></script>
</body>
</code>```

profile.php

```<code><?php
$imagepath ="omj/logo.jpg";
$image = imagecreatefromjpeg( $imagepath);
header('Content-Type: image/jpeg');
imagejpeg($image);
?>
</code>```

I tried referencing the following articles to no avail:

http://www.configure-all.com/howto_display_image.php

How to display images from a folder using php - PHP

Edit
I got the image to work using HTML by simply moving the image folder inside the html folder. Now the question remains, why isn't the php code running to show the image?

The image path is within the directory of the html file. Like this: /htmlfolder/imagefolder/image.jpg while html file is /htmlfolder/file.html

答:
An html file cannot run php code.

Change your file name from home.html to home.php.

Then change this line:

```<code><script src="main/profile.php"></script>
</code>```

to

```<code><?php echo '<img src="omj/logo.jpg"/>'; ?>
</code>```

Body:
I am using XAMPP for APACHE server on localhost:8080 (I had to change the default port for it to work). Assume that I have the rest of the html needed to run.
Here is the current code:

home.html

profile.php

<?php
$imagepath ="omj/logo.jpg";
$image = imagecreatefromjpeg( $imagepath);
header('Content-Type: image/jpeg');
imagejpeg($image);
?>

I tried referencing the following articles to no avail:

http://www.configure-all.com/howto_display_image.php

How to display images from a folder using php - PHP

Edit
I got the image to work using HTML by simply moving the image folder inside the html folder. Now the question remains, why isn't the php code running to show the image?

The image path is within the directory of the html file. Like this: /htmlfolder/imagefolder/image.jpg while html file is /htmlfolder/file.html

Body:
An html file cannot run php code.

Change your file name from home.html to home.php.

Then change this line:

<script src="main/profile.php"></script>

to

<?php echo '<img src="omj/logo.jpg"/>'; ?>


问:
Changing the output of this python code in to a list?
The following python code gives me the different combinations from the given values.

```<code>import itertools

iterables = [ [1,2,3,4], [88,99], ['a','b'] ]
for t in itertools.product(*iterables):
    print t
</code>```

Output:-

```<code>(1, 88, 'a')
(1, 88, 'b')
(1, 99, 'a')
(1, 99, 'b')
(2, 88, 'a')
</code>```

and so on.

Can some one please tell me how to modify this code so the output looks like a list;

```<code>188a
188b
199a
199b
288a
</code>```

答:
You can try this:</p>

```<code>iterables = [ [1,2,3,4], [88,99], ['a','b'] ]

new_list = [''.join(map(str, i)) for i in itertools.product(*iterables)]
</code>```

Body:
The following python code gives me the different combinations from the given values.

import itertools

iterables = [ [1,2,3,4], [88,99], ['a','b'] ]
for t in itertools.product(*iterables):
    print t

Output:-

(1, 88, 'a')
(1, 88, 'b')
(1, 99, 'a')
(1, 99, 'b')
(2, 88, 'a')

and so on.

Can some one please tell me how to modify this code so the output looks like a list;

188a
188b
199a
199b
288a

Body:
You can try this:

iterables = [ [1,2,3,4], [88,99], ['a','b'] ]

new_list = [''.join(map(str, i)) for i in itertools.product(*iterables)]


答:
You'll have to convert the numbers to strings, then join the results:

```<code>print ''.join(map(str, t))
</code>```

You could avoid having to convert if you made your inputs strings to begin with:

```<code>iterables = [['1', '2', '3', '4'], ['88', '99'], ['a', 'b']]
for t in itertools.product(*iterables):
    print ''.join(t)
</code>```

If all you want is to print the values together (and not do anything with them otherwise) then use print() as a function (by using the from __future__ import print_function Python 2 feature switch or by using Python 3):

```<code>from __future__ import print_function

iterables = [[1, 2, 3, 4], [88, 99], ['a', 'b']]
for t in itertools.product(*iterables):
    print(*t)
</code>```

Title: Changing the output of this python code in to a list?

Body:
You'll have to convert the numbers to strings, then join the results:

print ''.join(map(str, t))

You could avoid having to convert if you made your inputs strings to begin with:

iterables = [['1', '2', '3', '4'], ['88', '99'], ['a', 'b']]
for t in itertools.product(*iterables):
    print ''.join(t)

If all you want is to print the values together (and not do anything with them otherwise) then use print() as a function (by using the from __future__ import print_function Python 2 feature switch or by using Python 3):

from __future__ import print_function

iterables = [[1, 2, 3, 4], [88, 99], ['a', 'b']]
for t in itertools.product(*iterables):
    print(*t)


问:
JSON.parse() not working
I have a json from my server which is -

```<code>{"canApprove": true,"hasDisplayed": false}
</code>```

I can parse the json like this -

```<code>var msg = JSON.parse('{"canApprove": true,"hasDisplayed": false}');
alert(msg.canApprove);  //shows true.
</code>```

At my ajax response function I caught the same json mentioned earlier by a method parameter jsonObject -

```<code>//response function
function(jsonObject){

  //here jsonObject contains the same json -  {"canApprove":true,"hasDisplayed": false}
  //But without the surrounding single quote
  //I have confirmed about this by seeing my server side log.

  var msg = JSON.parse(jsonObject); // this gives the error

}
</code>```

But now I got the following error -

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of
  the JSON data

Can anyone tell me why I am getting the error?

答:
As someone mentioned up there, this actually fixes the problem. What I learnt from this is that may be how PHP encodes a json object is not familiar to JavaScript.

```<code>var receivedData = data.toString()
receivedData = JSON.parse(receivedData)
console.log(receivedData.canApprove)
</code>```

This will work.

Title: JSON.parse() not working

Body:
I have a json from my server which is -

{"canApprove": true,"hasDisplayed": false}

I can parse the json like this -

var msg = JSON.parse('{"canApprove": true,"hasDisplayed": false}');
alert(msg.canApprove);  //shows true.

At my ajax response function I caught the same json mentioned earlier by a method parameter jsonObject -

//response function
function(jsonObject){

  //here jsonObject contains the same json -  {"canApprove":true,"hasDisplayed": false}
  //But without the surrounding single quote
  //I have confirmed about this by seeing my server side log.

  var msg = JSON.parse(jsonObject); // this gives the error

}

But now I got the following error -

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of
  the JSON data

Can anyone tell me why I am getting the error?

Body:
As someone mentioned up there, this actually fixes the problem. What I learnt from this is that may be how PHP encodes a json object is not familiar to JavaScript.

var receivedData = data.toString()
receivedData = JSON.parse(receivedData)
console.log(receivedData.canApprove)

This will work.


问:
bash: oneliner to convert hex numbers in output to decimals
Does anyone know of a oneliner into which some output can be piped into in bash, to match and convert all occurrences of hexadecimal numbers and leave all other text untouched?

maybe match rather arbitrary output which could be a hexadecimal
shall somehow converted through a regexp, i.e.
/(0x)?[0-9a-fA-F]{5,}/

a leading 0x shall not be neccessary, but
also be handled properly

there can be false-positives, if not
specifying a minimum length of the numbers, but that should not be an
issue

the goal is to find solution which can be used with as much possible outputs having hex numbers in them

It should work on output like:

```<code>ssg sjas # cat /proc/net/stat/arp_cache | column -t
entries   allocs    destroys  hash_grows  lookups   hits      res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
0000000d  00000006  00000004  00000000    0000c3b9  0000c35e  00000000    00000000          00000000          0000965b          00000000        00000000             00000000
0000000d  0000000d  00000004  00000001    00000000  00000000  00000000    00000000          00000000          000007cd          00000000        00000000             00000000
0000000d  00000008  00000008  00000001    00000000  00000000  00000000    00000000          00000000          000006e0          00000000        00000000             00000000
0000000d  0000000a  00000008  00000000    00000000  00000000  00000002    00000000          00000000          00000704          00000000        00000000             00000000
</code>```

Most other questions on stackoverflow only tackle the issue of how to convert single numbers between number systems, only do the conversion for a specified column or completely kill the formatting being present in the input.

Desired output should look like: (column -t is there anyway, it really just need to replace the hex values it can find, and adding leading zeroes to a printf statement is also not a problem)

```<code>ssg sjas # cat /proc/net/stat/arp_cache | perl -pe 's/(?:0x)?[0-9a-f]{5,}/hex($&)/ge' | column -t
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           50105    50014  0           0                 0                 38491             0               0                    0
13       13      4         1           0        0      0           0                 0                 1997              0               0                    0
13       8       8         1           0        0      0           0                 0                 1760              0               0                    0
13       10      8         0           0        0      2           0                 0                 1796              0               0                    0
</code>```

I could not find a short viable/reliable solution via sed/awk/perl in the last two hours, so I came here for help.

答:
A leading 0 is considered to be octal, and a leading 0x is considered to be hexadecimal.  If your numbers conform to that standard, then $(( <number> )) will convert them to decimal:

```<code>$ echo $(( 0x1b ))
27
$ echo $(( 014 ))
12
</code>```

Body:
Does anyone know of a oneliner into which some output can be piped into in bash, to match and convert all occurrences of hexadecimal numbers and leave all other text untouched?

maybe match rather arbitrary output which could be a hexadecimal
shall somehow converted through a regexp, i.e.
/(0x)?[0-9a-fA-F]{5,}/

a leading 0x shall not be neccessary, but
also be handled properly

there can be false-positives, if not
specifying a minimum length of the numbers, but that should not be an
issue

the goal is to find solution which can be used with as much possible outputs having hex numbers in them

It should work on output like:

ssg sjas # cat /proc/net/stat/arp_cache | column -t
entries   allocs    destroys  hash_grows  lookups   hits      res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
0000000d  00000006  00000004  00000000    0000c3b9  0000c35e  00000000    00000000          00000000          0000965b          00000000        00000000             00000000
0000000d  0000000d  00000004  00000001    00000000  00000000  00000000    00000000          00000000          000007cd          00000000        00000000             00000000
0000000d  00000008  00000008  00000001    00000000  00000000  00000000    00000000          00000000          000006e0          00000000        00000000             00000000
0000000d  0000000a  00000008  00000000    00000000  00000000  00000002    00000000          00000000          00000704          00000000        00000000             00000000

Most other questions on stackoverflow only tackle the issue of how to convert single numbers between number systems, only do the conversion for a specified column or completely kill the formatting being present in the input.

Desired output should look like: (column -t is there anyway, it really just need to replace the hex values it can find, and adding leading zeroes to a printf statement is also not a problem)

ssg sjas # cat /proc/net/stat/arp_cache | perl -pe 's/(?:0x)?[0-9a-f]{5,}/hex($&)/ge' | column -t
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           50105    50014  0           0                 0                 38491             0               0                    0
13       13      4         1           0        0      0           0                 0                 1997              0               0                    0
13       8       8         1           0        0      0           0                 0                 1760              0               0                    0
13       10      8         0           0        0      2           0                 0                 1796              0               0                    0

I could not find a short viable/reliable solution via sed/awk/perl in the last two hours, so I came here for help.

Body:
A leading 0 is considered to be octal, and a leading 0x is considered to be hexadecimal.  If your numbers conform to that standard, then $(( <number> )) will convert them to decimal:

$ echo $(( 0x1b ))
27
$ echo $(( 014 ))
12


问:
Passing JSON-ed array to PHP with $.Post
I have this code:

```<code>$("#sendData").click(function(e) {

// converts to JSON the array and returns a string.
var updateValues = JSON.stringify(dataArray);

$.post("test.php", updateValues, function(data){
    document.write(alert)});
});
</code>```

As you may see, is my intention to send a JSON array to test.php. Now in test.php i have something like:

```<code><?php

    if(isset($_POST["updateValues"])) {
        echo $_POST["updateValues"];
    } else {
        echo "Error."
    }

?>
</code>```

Now, i'm getting "Error". I believe it's because the array can not be passed just that way, even if it's JSON-ed. What's the correct way of passing arrays to PHP scripts?

答:
Try...

```<code>$.post("test.php", {'updateValues': updateValues}, function(data){
        alert(data);
});
</code>```

You had a few syntax issues - and each post variable should have a key in the object to access it in PHP like that.

ContentLicense: CC BY-SA 2.5

Body:
I have this code:

$("#sendData").click(function(e) {

// converts to JSON the array and returns a string.
var updateValues = JSON.stringify(dataArray);

$.post("test.php", updateValues, function(data){
    document.write(alert)});
});

As you may see, is my intention to send a JSON array to test.php. Now in test.php i have something like:

<?php

    if(isset($_POST["updateValues"])) {
        echo $_POST["updateValues"];
    } else {
        echo "Error."
    }

?>

Now, i'm getting "Error". I believe it's because the array can not be passed just that way, even if it's JSON-ed. What's the correct way of passing arrays to PHP scripts?

Body:
Try...

$.post("test.php", {'updateValues': updateValues}, function(data){
        alert(data);
});

You had a few syntax issues - and each post variable should have a key in the object to access it in PHP like that.


问:
Breakout Clone Lives Bug
I am currently making a Breakout clone and it's almost fully playable, but I'm running into an issue with the ball: When the ball hits the bottom of the canvas, it should normally reset to its starting position, but in my case it just keeps bouncing towards the bottom again. Here's some of the collision code. You can see all of the code on Codepen.

```<code>else if(y + dy > canvas.height - ballRadius) {
    if(x > paddleX && x < paddleX + paddleWidth) {
        dy = -dy;
    }
    else {
        lives--;
        if(!lives) {
            alert("GAME OVER!");
            window.location.reload(true);
        }
        else {
            x = canvas.width / 2;
            y = canvas.height - 30;
            dx = 2;
            dx = -2;
        }
   }
</code>```

}

答:
You have a typo in the code that resets the position and direction of the ball. Should be:</p>

```<code>{
    x = canvas.width / 2;
    y = canvas.height - 30;
    dx = 2;
    dy = -2;
}
</code>```

Title: Breakout Clone Lives Bug

Body:
I am currently making a Breakout clone and it's almost fully playable, but I'm running into an issue with the ball: When the ball hits the bottom of the canvas, it should normally reset to its starting position, but in my case it just keeps bouncing towards the bottom again. Here's some of the collision code. You can see all of the code on Codepen.

else if(y + dy > canvas.height - ballRadius) {
    if(x > paddleX && x < paddleX + paddleWidth) {
        dy = -dy;
    }
    else {
        lives--;
        if(!lives) {
            alert("GAME OVER!");
            window.location.reload(true);
        }
        else {
            x = canvas.width / 2;
            y = canvas.height - 30;
            dx = 2;
            dx = -2;
        }
   }

}

Body:
You have a typo in the code that resets the position and direction of the ball. Should be:

{
    x = canvas.width / 2;
    y = canvas.height - 30;
    dx = 2;
    dy = -2;
}


问:
When and how to use POST, PUT, and Delete method in Web API
I am new to Web API and the tutorial I was watching uses Fiddler to sniff and send request.

My question is how to use the post, put and delete methods without using fiddler and where are these usually used in the when creating in software development? Fiddler allows you to compose a request body how about the browser though?

I don't seem to understand why you are only able to use these on a sniffing tool. I understand that I am most probably speaking out of ignorance.

答:
(This answer is not specific to ASP.NET)

To avoid any confusion, I'm assuming you understand this much about RESTful webservices:

If you are creating a new entity, use POST.

If you are reading an entity, use GET.

If you are updating an entity, use PUT.

If you are deleting an entity, use DELETE.

As you noticed, only the GET and POST methods can be used in plain web forms. AJAX, however, supports using any HTTP method. Therefore, to use the PUT and DELETE methods, send your data to the server using JavaScript methods such as XMLHttpRequest, the newer Fetch API or a convenient wrapper like jQuery's $.ajax. (There are many tutorials for whichever you pick.) For example, if you have a form of updated values, replace your input button with a button element that has a JavaScript click event handler. The same principle applies to a delete link, swap the href for a click event handler that makes an AJAX request to your server.


问:
Rename several columns (variable number)
I have a dataset where the last columns indicate the number of stops extracted from that dataset.

```<code>ColA  ColB  ColC  1  2  3  4  5  6  7  8  9  10  (...)
 a     g     c    a  q  e  r  e  r  q  g  h  q   (...)
</code>```

What I want is to select from column 1, until the last column, and add Stop before it, ending up with Stop1, Stop2, etc...
The problem is that those columns can vary. Sometimes I have 10 after 1 other times I have 6.

I've tried with dplyr and data.table but I'm not sure how to automate this.

EDIT: ColA to ColC are fixed and always the same.

Body:
I have a dataset where the last columns indicate the number of stops extracted from that dataset.

ColA  ColB  ColC  1  2  3  4  5  6  7  8  9  10  (...)
 a     g     c    a  q  e  r  e  r  q  g  h  q   (...)

What I want is to select from column 1, until the last column, and add Stop before it, ending up with Stop1, Stop2, etc...
The problem is that those columns can vary. Sometimes I have 10 after 1 other times I have 6.

I've tried with dplyr and data.table but I'm not sure how to automate this.

EDIT: ColA to ColC are fixed and always the same.

Body:
If I correctly understood your problem, this is a sufficiently flexible code that should solve your problem. Start considering the following dataset:

set.seed(1)
df <- data.frame(matrix(rpois(130, 20),ncol=13))
names(df) <- c(paste("Col",LETTERS[1:3],sep=""),as.character(1:10))
df

#######
   ColA ColB ColC  1  2  3  4  5  6  7  8  9 10
1    17   21   20 13 13 15 29 25 16 15 12 23 17
2    25   17   11 24 23 14 22 23 25 14 18 19 15
3    25   18   22 18 19 30 16 19 23 27 18 19 11
4    21   18   24 25 23 19 19 18 27 23 18 16 18
5    13   21   16 18 21 23 22 18 22 24 22 26 15
6    22   16   17 27 17 20 24 24 14 21 19 17 15
7    23   23   18 22 16 16 20 18 21 27 17 22 14
8    22   22   17 17 26 13 19 25 24 17 15 13 20
9    18   24   21 22 28 26 15 22 23 20 19 15 27
10   26   23   19 16 18 20 17 25 16 20 19 18 19

Now rename columuns as required:

k <- which(names(df)=="1")
names(df)[k:ncol(df)] <- paste("Stop",1:(ncol(df)-k+1),sep="")
df

#############
   ColA ColB ColC Stop1 Stop2 Stop3 Stop4 Stop5 Stop6 Stop7 Stop8 Stop9 Stop10
1    17   21   20    13    13    15    29    25    16    15    12    23     17
2    25   17   11    24    23    14    22    23    25    14    18    19     15
3    25   18   22    18    19    30    16    19    23    27    18    19     11
4    21   18   24    25    23    19    19    18    27    23    18    16     18
5    13   21   16    18    21    23    22    18    22    24    22    26     15
6    22   16   17    27    17    20    24    24    14    21    19    17     15
7    23   23   18    22    16    16    20    18    21    27    17    22     14
8    22   22   17    17    26    13    19    25    24    17    15    13     20
9    18   24   21    22    28    26    15    22    23    20    19    15     27
10   26   23   19    16    18    20    17    25    16    20    19    18     19

I hope it can help you.


问:
How to call getFragmentManager on Recycler.Adapter?
I am converting ListView of my app to RecyclerView. On ListView, it was very easy to implement OnClickListener but in RecyclerView, we have to do it in adapter. I want to open a new Fragment when user clicks on a item. To do this I have to call FragmentManager in adapter which I am not able to do.
This is my code of RecyclerAdapter:

```<code>public ListItemViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.title);
            description = (TextView) itemView.findViewById(R.id.description);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            //Call FragmentManager and add Fragment to it.
            }
        }
</code>```

So, how to call FragmentManager and add Fragments in it. Is there any better way than this like sendingBroadcast or any other method.

答:
You just need an activity context passed in your constructor. Be sure to call new Adapter(this,...) from activities and new Adapter(getActivity(),...) from fragments.

private Context context;
@Override
public void onClick(View v) {
    FragmentManager manager = ((Activity) context).getFragmentManager();}

Body:
I am converting ListView of my app to RecyclerView. On ListView, it was very easy to implement OnClickListener but in RecyclerView, we have to do it in adapter. I want to open a new Fragment when user clicks on a item. To do this I have to call FragmentManager in adapter which I am not able to do.
This is my code of RecyclerAdapter:

public ListItemViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.title);
            description = (TextView) itemView.findViewById(R.id.description);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            //Call FragmentManager and add Fragment to it.
            }
        }

So, how to call FragmentManager and add Fragments in it. Is there any better way than this like sendingBroadcast or any other method.


问:
Django autocomplete light
model.py:

```<code>class Reservation(models.Model):
    company = models.ForeignKey(GuestContact, on_delete=models.PROTECT)

class GuestContact(models.Model):
    company = models.CharField(max_lenght=30)
    last_name = models.CharField(max_lenght=30)
    first_name = models.CharField(max_lenght=30)
</code>```

form.py.

```<code>class ReservationForm(ModelForm):

    class Meta:
        model = Reservation
        fields = '__all__'
        widgets = {
            'company': autocomplete.ModelSelect2()
    }
</code>```

views.py

```<code>class GuestContactAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = GuestContact.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs
</code>```

How i can add to autocomplete queryset only not empty "company" field ?
Can you help me ?

答:
Your company field is required, so I don't think that you will have empty values. Anyways, you can accomplish what you want to do by this:

GuestContact.objects.exclude(company__isnull=True).exclude(company__exact='')

Basically, what it does is to exclude null and '' values from the querset.

Hope it helps.

Title: Django autocomplete light

Body:
model.py:

class Reservation(models.Model):
    company = models.ForeignKey(GuestContact, on_delete=models.PROTECT)

class GuestContact(models.Model):
    company = models.CharField(max_lenght=30)
    last_name = models.CharField(max_lenght=30)
    first_name = models.CharField(max_lenght=30)

form.py.

class ReservationForm(ModelForm):

    class Meta:
        model = Reservation
        fields = '__all__'
        widgets = {
            'company': autocomplete.ModelSelect2()
    }

views.py

class GuestContactAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = GuestContact.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs

How i can add to autocomplete queryset only not empty "company" field ?
Can you help me ?


问:
CheckBox isSelected() method always returns false
I am working on an Android application where I have to check the CheckBox selection onClick() so I made this

```<code>                if (checkBoxRM.isSelected() == true) {
                isSelectedValue = "True";
                //debug
                Toast.makeText(MainActivity.this, "Kiejölés értéke: " + isSelectedValue, Toast.LENGTH_SHORT).show();
            } else {
                //debug
                isSelectedValue = "False";
                Toast.makeText(MainActivity.this, "Kiejölés értéke: " + isSelectedValue, Toast.LENGTH_SHORT).show();
            }
</code>```

But seems like isSelectedValue is always false.

答: Instead of isSelected() perform isChecked().

Body:
I am working on an Android application where I have to check the CheckBox selection onClick() so I made this

                if (checkBoxRM.isSelected() == true) {
                isSelectedValue = "True";
                //debug
                Toast.makeText(MainActivity.this, "Kiejölés értéke: " + isSelectedValue, Toast.LENGTH_SHORT).show();
            } else {
                //debug
                isSelectedValue = "False";
                Toast.makeText(MainActivity.this, "Kiejölés értéke: " + isSelectedValue, Toast.LENGTH_SHORT).show();
            }

But seems like isSelectedValue is always false.


问:
Machine Learning Suggestions
I have data of a lot of students who got selected by some colleges based on their marks. Iam new to machine Learning. Can I have some suggestions how can I add Azure Machine Learning for predicting the colleges that they can get based on their marks</p>

答:
This is very subjective. Just applying any algorithm that classifies into categories won't be a good idea. Without performing Exploratory Data Analysis and checking following things you can't be sure of a doing predictive analytics, apart from missing values:

Quantitative and Qualitative variable.

Univariate, Bivariate and multivariate distribution.

Variable relationship to your response(college) variable.

Looking for outliers(multivariate and univariate).

Required variable transformation.

Can be the Y variable broken down into chunks for example location, for example whether a candidate can be a part of Colleges in California or New York. If there is a higher chance of California, then what college. In this way you could capture Linear + non-linear relationships.

For base learners you can fit Softmax regression model or 1 vs all Logistic regression which does not really matters a lot and CART for non-linear relationship. I would also do K-nn and K-means to check for different groups within data and decide on predictive learners.

I hope this makes sense!

Title: Machine Learning Suggestions


问:
Onloading data(image in this case) from JSON it displays the images in browser but in that TAB keeps on spinning?
On running the code in browser the spinner doesn't stop spinning i.e it keeps on loading how can I stop after the data from JSON is loaded.Link to JSON data -> http://starlord.hackerearth.com/sureify/cokestudio

```<code><script type="text/javascript">
        var requestURL = 'http://starlord.hackerearth.com/sureify/cokestudio';

        var request = new XMLHttpRequest();

        request.open('GET', requestURL);

        request.responseType = 'json';

        request.send();

        request.onload = function(){
            var myjsondata = request.response; //request.response contains all our JSON data
            showdata(myjsondata);

        }

        function showdata(data){
            for(var i=0;i<data.length;i++){
            var str = "<IMG src='"+data[i].cover_image+"'/>";
            document.write(str);
            }
        }
    </script>
</code>```

See the screenshot for better understanding:

答: That's probably because the images are still loading.</p>

Body:
On running the code in browser the spinner doesn't stop spinning i.e it keeps on loading how can I stop after the data from JSON is loaded.Link to JSON data -> http://starlord.hackerearth.com/sureify/cokestudio

See the screenshot for better understanding:


问:
personal version control system to recommend
For personal use. Anyone can recommend the version control system for Windows</p>

答:
If you are going to be working on a project just by yourself, and more importantly, committing regularly and can afford maintaining multiple branches(only if you need to), Go for subversion. Otherwise, choose Git, because,

it allows you to stash changes without committing to your repository

The entire version history is maintained locally, so this makes it quicker to view changes for others who are going to access your code

In Git you dont need to maintain separate project(source) directories for each of your code branches.


问:
Strange behavior of volatile array
I know it means the reference to the array is volatile not the items in the array if you declare an array volatile.

I am learning mutex algorithm, so I write some test code:

```<code>public class MutualExclusion {
    static final int N = 10;
    static final int M = 100000;

    volatile static int count = 0;

    public static void main(String[] args) {
        Thread[] threads = new Thread[N];
        for (int i = 0; i < N; i++) {
            Thread t = new Worker(i);
            threads[i] = t;
            t.start();
        }
        for (Thread t: threads) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (count != N * M) {
            System.out.println("count (" + count + ") != N * M (" + String.valueOf(N * M) + ")");
        }
    }

    static class Worker extends Thread {
        int id;
        Worker(int  id) {
            this.id = id;
        }

        @Override
        public void run() {
            for (int i = 0; i < M; i++) {
                this.lock();
                // critical section
                count++;
                if (i % 1000 == 0) {
                    System.out.println(this.getName() + ": " + count);
                }
                this.unlock();
            }
        }

        void lock() {
            filterLock();
        }

        void unlock() {
            filterUnlock();
        }

        static volatile int level[] = new int[N];
        static volatile int lastToEnter[] = new int[N - 1];

        void filterLock() {
            for (int i = 0; i < (N - 1); i++) {
                level[this.id] = i;
                lastToEnter[i] = this.id;
                outer:
                while (lastToEnter[i] == this.id) {
                    for (int k = 0; k < N; k++ ) {
                        if (k != this.id && level[k] >= i) {
                            continue outer;
                        }
                    }
                    break;
                }
            }
        }

        void filterUnlock() {
            level[this.id] = -1;
        }
    }
}
</code>```

In my first implementation of filter algorithm, I missed volatile for variable level and lastToEnter, not surprisingly, the program went into a infinite loop. After I added the missing volatile, the program can end as expected.

As I said in beginning, a volatile array doesn't mean items in the array are volatile, so why can the program end as expected after I added the missing volatile?

I asked myself this question when I was implementing another mutex algorithm which still doesn't run correctly after I added volatile keyword. I have to use a trick (Java volatile array?) to make items in the array looks like being volatile: (code below can be pasted into Worker class directly)

```<code>volatile static boolean[] b = new boolean[N];
volatile static boolean[] c = new boolean[N];
volatile static int k = 0;

void dijkstraLock() {
    b[this.id] = false;
    outer:
    for (;;) {
        if (k == this.id) {
            c[this.id] = false;

            c = c; // IMPORTANT! the trick

            for (int i = 0; i < N; i++) {
                if (i != this.id && !c[i]) {
                    continue outer;
                }
            }
            break;
        } else {
            c[this.id] = true;
            if (b[k]) {
                k = this.id;
            }
        }
    }
}

void dijkstraUnlock() {
    b[this.id] = true;
    c[this.id] = true;
}
</code>```

答:
Volatile arrays in Java do not contain volatile elements - but if you access them via the array reference (which is volatile) you will get a volatile read. For instance, in the code above:

```<code>static volatile int lastToEnter[] = new int[N - 1];
</code>```

is a volatile write, whereas

```<code>lastToEnter[i] = this.id;
</code>```

is not. however, the evaluating of the array value - such as:

```<code>lastToEnter[i] == this.id
</code>```

is a volatile read - you first read the reference to the array which is volatile, and only then access the i'th element to evaluate its value.

I suspect this is the reason your execution succeeds once the array is declared as volatile.

Title: Strange behavior of volatile array

Body:
I know it means the reference to the array is volatile not the items in the array if you declare an array volatile.

I am learning mutex algorithm, so I write some test code:

public class MutualExclusion {
    static final int N = 10;
    static final int M = 100000;

    volatile static int count = 0;

    public static void main(String[] args) {
        Thread[] threads = new Thread[N];
        for (int i = 0; i < N; i++) {
            Thread t = new Worker(i);
            threads[i] = t;
            t.start();
        }
        for (Thread t: threads) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (count != N * M) {
            System.out.println("count (" + count + ") != N * M (" + String.valueOf(N * M) + ")");
        }
    }

    static class Worker extends Thread {
        int id;
        Worker(int  id) {
            this.id = id;
        }

        @Override
        public void run() {
            for (int i = 0; i < M; i++) {
                this.lock();
                // critical section
                count++;
                if (i % 1000 == 0) {
                    System.out.println(this.getName() + ": " + count);
                }
                this.unlock();
            }
        }

        void lock() {
            filterLock();
        }

        void unlock() {
            filterUnlock();
        }

        static volatile int level[] = new int[N];
        static volatile int lastToEnter[] = new int[N - 1];

        void filterLock() {
            for (int i = 0; i < (N - 1); i++) {
                level[this.id] = i;
                lastToEnter[i] = this.id;
                outer:
                while (lastToEnter[i] == this.id) {
                    for (int k = 0; k < N; k++ ) {
                        if (k != this.id && level[k] >= i) {
                            continue outer;
                        }
                    }
                    break;
                }
            }
        }

        void filterUnlock() {
            level[this.id] = -1;
        }
    }
}

In my first implementation of filter algorithm, I missed volatile for variable level and lastToEnter, not surprisingly, the program went into a infinite loop. After I added the missing volatile, the program can end as expected.

As I said in beginning, a volatile array doesn't mean items in the array are volatile, so why can the program end as expected after I added the missing volatile?

I asked myself this question when I was implementing another mutex algorithm which still doesn't run correctly after I added volatile keyword. I have to use a trick (Java volatile array?) to make items in the array looks like being volatile: (code below can be pasted into Worker class directly)

volatile static boolean[] b = new boolean[N];
volatile static boolean[] c = new boolean[N];
volatile static int k = 0;

void dijkstraLock() {
    b[this.id] = false;
    outer:
    for (;;) {
        if (k == this.id) {
            c[this.id] = false;

            c = c; // IMPORTANT! the trick

            for (int i = 0; i < N; i++) {
                if (i != this.id && !c[i]) {
                    continue outer;
                }
            }
            break;
        } else {
            c[this.id] = true;
            if (b[k]) {
                k = this.id;
            }
        }
    }
}

void dijkstraUnlock() {
    b[this.id] = true;
    c[this.id] = true;
}

Body:
Volatile arrays in Java do not contain volatile elements - but if you access them via the array reference (which is volatile) you will get a volatile read. For instance, in the code above:

static volatile int lastToEnter[] = new int[N - 1];

is a volatile write, whereas

lastToEnter[i] = this.id;

is not. however, the evaluating of the array value - such as:

lastToEnter[i] == this.id

is a volatile read - you first read the reference to the array which is volatile, and only then access the i'th element to evaluate its value.

I suspect this is the reason your execution succeeds once the array is declared as volatile.


问:
Printing word by word from a sentence
I have a sentence "Computer Science" as my input and I want to print Computer and Science seperately. I wrote a program in c++ but it is printing only "Computer". Could anyone help me find out why it is not printing both the words seperately?</p>

```<code>int main()
{
    char string[]="Computer Science";
    int l;
    l=strlen(string);
    char begin[l];
    int i=0,ind=0;

        while(string[i]!='\0')
        {
            begin[ind]=string[i];
            if(string[i]==' ')
                {
                    begin[ind]=NULL;
                    cout<<begin<<"\n";

                    ind=0;
                    //ind++;
                    i++;
                }
            else
            {

                ind++;
                i++;
            }
        }

    return 0;
}
</code>```

答:
Modern C++ offers a lot of features for handling strings. These features are designed to simplify handling string in more efficient way. Don't use C-Style string unless you have to. In your case, you could do </p>

```<code>#include <iostream>
#include <string>

int main()
{
    std::string str("Computer Science");
    for(int i(0); i < str.size(); ++i){
        if( str[i] == ' ' )
            std::cout << '\n';
        else{
            std::cout << str[i];
        }
    }
    std::cout << std::endl;

    return 0;
}
</code>```

<p>With C++, you can do more reduction but I leave it as is. </p>

Title: Printing word by word from a sentence

Body:
I have a sentence "Computer Science" as my input and I want to print Computer and Science seperately. I wrote a program in c++ but it is printing only "Computer". Could anyone help me find out why it is not printing both the words seperately?

int main()
{
    char string[]="Computer Science";
    int l;
    l=strlen(string);
    char begin[l];
    int i=0,ind=0;

        while(string[i]!='\0')
        {
            begin[ind]=string[i];
            if(string[i]==' ')
                {
                    begin[ind]=NULL;
                    cout<<begin<<"\n";

                    ind=0;
                    //ind++;
                    i++;
                }
            else
            {

                ind++;
                i++;
            }
        }

    return 0;
}

Body:
Modern C++ offers a lot of features for handling strings. These features are designed to simplify handling string in more efficient way. Don't use C-Style string unless you have to. In your case, you could do

#include <iostream>
#include <string>

int main()
{
    std::string str("Computer Science");
    for(int i(0); i < str.size(); ++i){
        if( str[i] == ' ' )
            std::cout << '\n';
        else{
            std::cout << str[i];
        }
    }
    std::cout << std::endl;

    return 0;
}

With C++, you can do more reduction but I leave it as is.


问:
angularjs - object property is undefined
In my Angular.js app, I have one parent controller, which generate my present longitude and latitude so that I can get that data into my child controller. My code is given below:

Parent Controller

```<code>(function() {
  'use strict';
   angular.module('app').controller('InitCtrl', InitCtrl);
   function InitCtrl() {
      var init = this;
      init.g_map = {};
      init.g_map.current = {};
      let geocoder = new google.maps.Geocoder();
      // current latitude & longitude
      navigator.geolocation.getCurrentPosition(function(position) {
        init.g_map.current.lat = position.coords.latitude;
         init.g_map.current.lng = position.coords.longitude;
      });
   }
})();
</code>```

Child Controller

```<code>(function() {
   'use strict';

   angular.module('app').controller('ListCtrl', ListCtrl);

   function ListCtrl($scope, $timeout, _, NgMap, RestaurantApi) {
      let list = this;

      list.load = function load() {
        let init = $scope.$parent.init;
        list.res = {};
        list.res = init.g_map.current;
        console.log("list.res  1: ", list.res);
        /* Output (console window):
             list.res 1 : >Object{}
                           {
                               lat: 'my-current-lat'
                               lng: 'my-current-lng'
                           }
            // here I have got my parent controller data
         */
        // but in the following console, I got undefine
        // even if I already got data which is printed previous console
        console.log("list.res  2 : ", list.res.lat, list.res.lng);
       /* Output (console window)
           list.res 2 : undefined undefined
        */
      }

     list.load();
   }

 })();
</code>```

I don't understand why this is happening, any suggestion ?

答:
I'm missing a comma after lat: 'my-current-lat' console output. Maybe there is a hidden bug?

You can try to access the properties using this syntax:

```<code>console.log('list.res 2: ', list.res['lat'], list.res['lng']);
</code>```

Body:
In my Angular.js app, I have one parent controller, which generate my present longitude and latitude so that I can get that data into my child controller. My code is given below:

Parent Controller

(function() {
  'use strict';
   angular.module('app').controller('InitCtrl', InitCtrl);
   function InitCtrl() {
      var init = this;
      init.g_map = {};
      init.g_map.current = {};
      let geocoder = new google.maps.Geocoder();
      // current latitude & longitude
      navigator.geolocation.getCurrentPosition(function(position) {
        init.g_map.current.lat = position.coords.latitude;
         init.g_map.current.lng = position.coords.longitude;
      });
   }
})();

Child Controller

(function() {
   'use strict';

   angular.module('app').controller('ListCtrl', ListCtrl);

   function ListCtrl($scope, $timeout, _, NgMap, RestaurantApi) {
      let list = this;

      list.load = function load() {
        let init = $scope.$parent.init;
        list.res = {};
        list.res = init.g_map.current;
        console.log("list.res  1: ", list.res);
        /* Output (console window):
             list.res 1 : >Object{}
                           {
                               lat: 'my-current-lat'
                               lng: 'my-current-lng'
                           }
            // here I have got my parent controller data
         */
        // but in the following console, I got undefine
        // even if I already got data which is printed previous console
        console.log("list.res  2 : ", list.res.lat, list.res.lng);
       /* Output (console window)
           list.res 2 : undefined undefined
        */
      }

     list.load();
   }

 })();

I don't understand why this is happening, any suggestion ?

Body:
I'm missing a comma after lat: 'my-current-lat' console output. Maybe there is a hidden bug?

You can try to access the properties using this syntax:

console.log('list.res 2: ', list.res['lat'], list.res['lng']);


问:
htaccess to disable directory browsing in Apache/2.4.10 (Debian) doesn't work
I create a .htaccess file with this content: (in the folder of the site)

```<code>#Disable directory indexes
Options -Indexes
</code>```

But I still see the directories in the browser.

And in apache2.conf I rewrite this:

```<code><Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>
</code>```

What did I do wrong?

答:
If that didn't work and you got no error then it looks like .htaccess files are not enabled on your server. You'll need something like AllowOverride All in the server config that controls this area of the filesystem.

At the very least you would need the following to permit just that one directive.

```<code>AllowOverride Options=Indexes
</code>```

Body:
I create a .htaccess file with this content: (in the folder of the site)

#Disable directory indexes
Options -Indexes

But I still see the directories in the browser.

And in apache2.conf I rewrite this:

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

What did I do wrong?

Body:
If that didn't work and you got no error then it looks like .htaccess files are not enabled on your server. You'll need something like AllowOverride All in the server config that controls this area of the filesystem.

At the very least you would need the following to permit just that one directive.

AllowOverride Options=Indexes


问:
Cannot load a file in Octave
Apologies in advance if I get something wrong. This is my first post here (I'm sure there will be many to follow).

I have a file I want to load into Octave but it doesn't work. It is a plain text file (.txt).
The file is homogeneous and an excerpt of a few lines from it look like this:

```<code>0023,225.935,341.770,17.658
0024,225.935,341.758,17.782
LTAX17,228.152,353.935,17.665
LTAX24,288.304,332.878,24.074
</code>```

where the first column depicts the name of the point while the rest represent its 3D coordinates.

Some of the options I've tried (but not limited to these) were unsuccessful.

```<code>x=load(text.txt)
error: scalar cannot be indexed with .
error: evaluating argument list element number 1

x=load("-text", "text.txt")
warning: load: file found in load path
error: load: empty name keyword or no data found in file 'text.txt'

x=fileread(text.txt)
warning: load: file found in load path
error: load: empty name keyword or no data found in file 'text.txt'
</code>```

I have also tried simplifying the file, leaving only the coordinates and treating the file as a CSV but I keep getting similar errors.

答:
open a notepad
give this format

```<code># Created by Octave 4.2.1, Sat Jun 03 19:48:46 2017 GMT <unknown@Asus>
# name: a
# type: matrix
# rows: 6
# columns: 3
60 30 50
20 45 65
24 23 23
23 32 32
23 65 65
34 54 45
</code>```

save as file.data

open octave

```<code>>>load file.data
>>a
</code>```

Title: Cannot load a file in Octave

Body:
Apologies in advance if I get something wrong. This is my first post here (I'm sure there will be many to follow).

I have a file I want to load into Octave but it doesn't work. It is a plain text file (.txt).
The file is homogeneous and an excerpt of a few lines from it look like this:

0023,225.935,341.770,17.658
0024,225.935,341.758,17.782
LTAX17,228.152,353.935,17.665
LTAX24,288.304,332.878,24.074

where the first column depicts the name of the point while the rest represent its 3D coordinates.

Some of the options I've tried (but not limited to these) were unsuccessful.

x=load(text.txt)
error: scalar cannot be indexed with .
error: evaluating argument list element number 1

x=load("-text", "text.txt")
warning: load: file found in load path
error: load: empty name keyword or no data found in file 'text.txt'

x=fileread(text.txt)
warning: load: file found in load path
error: load: empty name keyword or no data found in file 'text.txt'

I have also tried simplifying the file, leaving only the coordinates and treating the file as a CSV but I keep getting similar errors.

Body:
open a notepad
give this format

# Created by Octave 4.2.1, Sat Jun 03 19:48:46 2017 GMT <unknown@Asus>
# name: a
# type: matrix
# rows: 6
# columns: 3
60 30 50
20 45 65
24 23 23
23 32 32
23 65 65
34 54 45

save as file.data

open octave

>>load file.data
>>a


问:
App crashes when uploading data to firebase as the app crashes when upload button is clicked
I keep getting the error below

```<code>Process: com.attendanceapp.obare.attendanceapp, PID: 8494
                  java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.contains(java.lang.CharSequence)' on a null object reference
                      at android.content.ContentResolver.checkLeakDetectIgnoreList(ContentResolver.java:2695)
                      at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1178)
                      at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:958)
                      at android.content.ContentResolver.openInputStream(ContentResolver.java:678)
                      at com.google.firebase.storage.UploadTask.<init>(Unknown Source)
                      at com.google.firebase.storage.StorageReference.putFile(Unknown Source)
                      at com.Healthcareapp.medicalapp.AddEmployeePackage.Add_employee$4.onClick(Add_employee.java:142)
                      at android.view.View.performClick(View.java:5274)
                      at android.view.View$PerformClick.run(View.java:21543)
                      at android.os.Handler.handleCallback(Handler.java:815)
                      at android.os.Handler.dispatchMessage(Handler.java:104)
                      at android.os.Looper.loop(Looper.java:207)
                      at android.app.ActivityThread.main(ActivityThread.java:5728)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
</code>```

The code is shown below, error occurs at the addOnSuccessListener. Any help would be greatly appreciated. Everything is working great though.

final StorageReference onlineStoragePhotoRef = mStorageReference.child("WorkForce_Photos").child(FirstName).child(photoUri.getLastPathSegment());

```<code>            progressBar.setMessage("Uploading file to Firebase");
            progressBar.show();

            final String finalFirstNameText = FirstName;
            final String finalLastNameText = LastName;
            final String finalIDnumText = IDnum;
            final String finalContactText = Contactnum;
            final String finaWorkBadgeText = WBadge;

            onlineStoragePhotoRef.putFile(photoUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    progressBar.setMessage("Success");
                    photoUrl = taskSnapshot.getDownloadUrl().toString();
                    WorkForceData workForceData = new WorkForceData(finalFirstNameText, finalLastNameText, finalIDnumText, finalContactText, finaWorkBadgeText,photoUrl);
                    mDatabaseReference.child("WorkForce").push().setValue(workForceData);
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(Add_employee.this, e.getMessage(), Toast.LENGTH_LONG).show();
                    photoUrl = "";
                    WorkForceData workForceData = new WorkForceData(finalFirstNameText, finalLastNameText, finalIDnumText, finalContactText, finaWorkBadgeText, photoUrl);
                    mDatabaseReference.child("Users").push().setValue(workForceData);
                }
            });

            progressBar.dismiss();
            finish();

        }
    });

}
</code>```

答:
The success listener executes asynchronously, after the upload completes.  This is occurring after you dismiss the progress bar and finish the activity with these statements:

```<code>progressBar.dismiss();
finish();
</code>```

Refactor your code to perform those operations when the upload completes:

```<code>onlineStoragePhotoRef.putFile(photoUri)
        .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
        if (task.isSuccessful()) {
            progressBar.setMessage("Success");
            photoUrl = task.getResult().getDownloadUrl().toString();
            WorkForceData workForceData = new WorkForceData(finalFirstNameText, finalLastNameText, finalIDnumText, finalContactText, finaWorkBadgeText,photoUrl);
            mDatabaseReference.child("WorkForce").push().setValue(workForceData);
        } else {
            Toast.makeText(Add_employee.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
            photoUrl = "";
            WorkForceData workForceData = new WorkForceData(finalFirstNameText, finalLastNameText, finalIDnumText, finalContactText, finaWorkBadgeText, photoUrl);
            mDatabaseReference.child("Users").push().setValue(workForceData);
        }
        progressBar.dismiss();
        finish();
    }
});
</code>```

Body:
I keep getting the error below

Process: com.attendanceapp.obare.attendanceapp, PID: 8494
                  java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.contains(java.lang.CharSequence)' on a null object reference
                      at android.content.ContentResolver.checkLeakDetectIgnoreList(ContentResolver.java:2695)
                      at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1178)
                      at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:958)
                      at android.content.ContentResolver.openInputStream(ContentResolver.java:678)
                      at com.google.firebase.storage.UploadTask.<init>(Unknown Source)
                      at com.google.firebase.storage.StorageReference.putFile(Unknown Source)
                      at com.Healthcareapp.medicalapp.AddEmployeePackage.Add_employee$4.onClick(Add_employee.java:142)
                      at android.view.View.performClick(View.java:5274)
                      at android.view.View$PerformClick.run(View.java:21543)
                      at android.os.Handler.handleCallback(Handler.java:815)
                      at android.os.Handler.dispatchMessage(Handler.java:104)
                      at android.os.Looper.loop(Looper.java:207)
                      at android.app.ActivityThread.main(ActivityThread.java:5728)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

The code is shown below, error occurs at the addOnSuccessListener. Any help would be greatly appreciated. Everything is working great though.

final StorageReference onlineStoragePhotoRef = mStorageReference.child("WorkForce_Photos").child(FirstName).child(photoUri.getLastPathSegment());

            progressBar.setMessage("Uploading file to Firebase");
            progressBar.show();

            final String finalFirstNameText = FirstName;
            final String finalLastNameText = LastName;
            final String finalIDnumText = IDnum;
            final String finalContactText = Contactnum;
            final String finaWorkBadgeText = WBadge;

            onlineStoragePhotoRef.putFile(photoUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    progressBar.setMessage("Success");
                    photoUrl = taskSnapshot.getDownloadUrl().toString();
                    WorkForceData workForceData = new WorkForceData(finalFirstNameText, finalLastNameText, finalIDnumText, finalContactText, finaWorkBadgeText,photoUrl);
                    mDatabaseReference.child("WorkForce").push().setValue(workForceData);
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(Add_employee.this, e.getMessage(), Toast.LENGTH_LONG).show();
                    photoUrl = "";
                    WorkForceData workForceData = new WorkForceData(finalFirstNameText, finalLastNameText, finalIDnumText, finalContactText, finaWorkBadgeText, photoUrl);
                    mDatabaseReference.child("Users").push().setValue(workForceData);
                }
            });

            progressBar.dismiss();
            finish();

        }
    });

}

Body:
The success listener executes asynchronously, after the upload completes.  This is occurring after you dismiss the progress bar and finish the activity with these statements:

progressBar.dismiss();
finish();

Refactor your code to perform those operations when the upload completes:

onlineStoragePhotoRef.putFile(photoUri)
        .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
        if (task.isSuccessful()) {
            progressBar.setMessage("Success");
            photoUrl = task.getResult().getDownloadUrl().toString();
            WorkForceData workForceData = new WorkForceData(finalFirstNameText, finalLastNameText, finalIDnumText, finalContactText, finaWorkBadgeText,photoUrl);
            mDatabaseReference.child("WorkForce").push().setValue(workForceData);
        } else {
            Toast.makeText(Add_employee.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
            photoUrl = "";
            WorkForceData workForceData = new WorkForceData(finalFirstNameText, finalLastNameText, finalIDnumText, finalContactText, finaWorkBadgeText, photoUrl);
            mDatabaseReference.child("Users").push().setValue(workForceData);
        }
        progressBar.dismiss();
        finish();
    }
});


问:
How exactly does "inc" in assembly works here?
I am learning assembly and I am not sure about this little thing here.
So I've got this piece of code here

```<code>mov DWORD PTR [ebp-4],0X0
cmp DWORD PTR [ebp-4],0X9
.
.
.
lea eax,[ebp-4]
inc DWORD PTR [eax]
...
</code>```

and I am not sure why exactly do I have to use the "lea" and "eax" here. If I understand it correctly, [ebp-4] points to int(4 bytes) with the value of 0. Could I increment it directly without using "eax" reigster ?
Also, obviously I can directly compare the value in [ebp-4] with value "9" so why couldn't I increment it in the same fashion ?

Thanks for every hint.

答:
Simple:

```<code>lea eax,[ebp-4]      ; eax = ebp-4
inc DWORD PTR [eax]  ;decrease dword at location ebp-4 by one.
</code>```

If you had written:

```<code>inc DWORD PTR [ebp-4]
</code>```

It would have done the exact same thing.

There is no need to use EAX here, you can use complex addressing anywhere you can address memory at no cost (other than perhaps instruction length).

Perhaps the code is reusing eax a lot further down, or perhaps you're looking at unoptimized code.

Body:
I am learning assembly and I am not sure about this little thing here.
So I've got this piece of code here

mov DWORD PTR [ebp-4],0X0
cmp DWORD PTR [ebp-4],0X9
.
.
.
lea eax,[ebp-4]
inc DWORD PTR [eax]
...

and I am not sure why exactly do I have to use the "lea" and "eax" here. If I understand it correctly, [ebp-4] points to int(4 bytes) with the value of 0. Could I increment it directly without using "eax" reigster ?
Also, obviously I can directly compare the value in [ebp-4] with value "9" so why couldn't I increment it in the same fashion ?

Thanks for every hint.

Body:
Simple:

lea eax,[ebp-4]      ; eax = ebp-4
inc DWORD PTR [eax]  ;decrease dword at location ebp-4 by one.

If you had written:

inc DWORD PTR [ebp-4]

It would have done the exact same thing.

There is no need to use EAX here, you can use complex addressing anywhere you can address memory at no cost (other than perhaps instruction length).

Perhaps the code is reusing eax a lot further down, or perhaps you're looking at unoptimized code.


问:
Does wifi scanning comply with Apple's guidelines to scan wifi hotspot on ios4
Does wifi scanning comply with Apple's guidelines to scan wifi hotspot on ios4</p>

答:
"Is it legal?" is a very unwise question here for the following reasons:

legality depends on (at a minimum) your jurisdiction, which you haven't supplied.

despite the armchair lawyers here, the vast majority of us are not lawyers, not your lawyers, and probably not allowed to give legal advice at all.

advice off the net is worth every cent you paid for it.

Now that the question has changed to "Does it comply with Apple's guidelines?", that's another matter.

The AppStore guidelines are made available by Apple but you have to be already registered as a developer to get them. Despite the sometimes seemingly arbitrary nature of rejections complained about on the web (and I have no idea whether those complaints are justified), these guidelines should be a good starting point.

That same page also shows an appeals process if you think your application was rejected wrongly so it looks like Apple is at least making the process a little more transparent.

While I disapprove of the iDevices being so locked down (Apple returning to the halcyon days of IBM mainframes where the operators in their ivory towers had full control over what you were allowed to do - what was the personal computer revolution for if not to free us up from that?), this is at least a little encouraging, although I have to wonder how much of that is fear of Android :-)


问:
How to generate correlated random numbers?
I want to generate two random integers in python, which are correlated.
Let's say that integer n is a random integer between 0 and 10, and I want integer q to be in the same range but be not more that n. Any suggestions?

```<code>from __future__ import division

from random import randint

population = randint(100, 1000)
number_of_successes = randint(1, 100)
number_of_fails = population-number_of_successes
probability = number_of_successes/population
</code>```

答:
n integer is a random integer between 0 and 10, and i want integer q to be in the same range but be not more that n

So q is not in "the same range" as n. It is in the range [0, n] (or [0, n), this is not clear from the question).

This is quite a simple task:

```<code>n = randint(100, 1000)
q = randint(100, n)
</code>```

If q must not be equal to n, remove n from the range of q:

```<code>n = randint(100, 1000)
q = randint(100, n - 1)
</code>```

Body:
I want to generate two random integers in python, which are correlated.
Let's say that integer n is a random integer between 0 and 10, and I want integer q to be in the same range but be not more that n. Any suggestions?

from __future__ import division

from random import randint

population = randint(100, 1000)
number_of_successes = randint(1, 100)
number_of_fails = population-number_of_successes
probability = number_of_successes/population

Body:
n integer is a random integer between 0 and 10, and i want integer q to be in the same range but be not more that n

So q is not in "the same range" as n. It is in the range [0, n] (or [0, n), this is not clear from the question).

This is quite a simple task:

n = randint(100, 1000)
q = randint(100, n)

If q must not be equal to n, remove n from the range of q:

n = randint(100, 1000)
q = randint(100, n - 1)


答:
You can try this:</p>

```<code>import random

first_number = random.randint(0, 10)

second_number = random.randint(0, first_number)
</code>```

Title: How to generate correlated random numbers?

Body:
You can try this:

import random

first_number = random.randint(0, 10)

second_number = random.randint(0, first_number)


问:
Watchers, Breakpoints, single-step and stepthrough
I know what a breakpoint is: it pauses the execution of code at certain points. I think its purpose is to check the value of certain variables at certain points in the program. However, watchers, single-step and stepthrough seem to be the same thing. Are they the same?

Thanks in advance

答:
Breakpoints allow you to stop at a specific point without needing to step through line-by-line to get there. The program execution will stop whenever it gets to a breakpoint, this will (generally) override the step logic - it will stop there even if you did a step.

Step executes the program until it gets to the "next" line and stops there ("next" could mean various things, see below). This allows you to execute the program line-by-line without needing to set a breakpoint on every line and easily move between methods.

Step over steps to the following line in the same method or goes back to the line where this method was called from in the calling method if this method is returning.

Step in is like "step over", but also steps into whatever method appears on the current line (starting at the first line of that method).

Step out steps out of the current method, i.e. runs until it returns and stops at the line where this method was called from in the calling method.

Watch allows you to easily see the value of variables or more complex expressions during debugging without needing to manually check them every time. It might also allow you to stop execution when the variable changes - something that can be very useful for bigger applications.

These things may not all exist in all debugging tools, there may be others and they may sometimes have slightly different names.

They all broadly serve the purpose "to debug", and you don't technically need all of them, but having access to all of them tends to make the debugging process a lot easier.


问:
Error: trying to diff 'value' Only arrays and iterables are allowed
I have a component to add multiple values. When i tried to set its value using patch value, i get the error "error trying to diff  'oatMeal' Only arrays and iterables are allowed" how can i update its value?

Here is the code in plunker:https://plnkr.co/edit/hfiJ3SQokGjOwsf9OviG?p=preview

This is the method i call to update the form field

```<code>updateForm() {
      this.formGroup.patchValue({venueAmenities: 'oatmeal'});
}
</code>```

答:
Because you will need to pass an array to your ngFor. In your case, venueAmenities should be an array, and hence your patched value should be an array too.

This is how you should do it.

```<code>updateForm() {
      this.formGroup.patchValue({venueAmenities: ['oatmeal']});
}
</code>```

Working plnkr

Body:
I have a component to add multiple values. When i tried to set its value using patch value, i get the error "error trying to diff  'oatMeal' Only arrays and iterables are allowed" how can i update its value?

Here is the code in plunker:https://plnkr.co/edit/hfiJ3SQokGjOwsf9OviG?p=preview

This is the method i call to update the form field

updateForm() {
      this.formGroup.patchValue({venueAmenities: 'oatmeal'});
}

Body:
Because you will need to pass an array to your ngFor. In your case, venueAmenities should be an array, and hence your patched value should be an array too.

This is how you should do it.

updateForm() {
      this.formGroup.patchValue({venueAmenities: ['oatmeal']});
}

Working plnkr


答:
Everything looks OK here.

Open your browser's developer tools and take a look at the "Network" tab, you'll probably find the cause there.

Title: Onloading data(image in this case) from JSON it displays the images in browser but in that TAB keeps on spinning?

Body:
On running the code in browser the spinner doesn't stop spinning i.e it keeps on loading how can I stop after the data from JSON is loaded.Link to JSON data -> http://starlord.hackerearth.com/sureify/cokestudio

See the screenshot for better understanding:


问:
Trying to use highcharts inside native script web-view. Does not work
I got a problem. I need to use highcharts in mobile app. So I decided to use web-view. And it does not work neither on iOS nor on Android.

I have 3 questions:

1) I've tried to launch simple highchairs demo in my web view. Something went wrong. What I did wrong in the code below ? I suppose the problem is with loading js scripts.

HTML code inside the web-view component is the following :

```<code><html lang="en" >
<head>
    <meta charset="utf-8" />
    <meta name="author" content="Script Tutorials" />
    <title>How to create active charts using Highcharts | Script Tutorials</title>

    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>

</head>
<body>
    <div id="chart_1" class="chart"></div>
    <script type='text/javascript'>
    $(document).ready(function() {

// First chart initialization
var chart1 = new Highcharts.Chart({
 chart: {
    renderTo: 'chart_1',
    type: 'area',
    height: 350,
 },
 title: {
    text: 'Tools developers plans to use to make html5 games (in %)'
 },
 xAxis: {
    categories: ['Processing.js', 'Impact.js', 'Other', 'Ease.js', 'Box2D.js', 'WebGL', 'DOM', 'CSS', 'Canvas', 'Javascript']
 },
 yAxis: {
    title: {
       text: 'Interviewed'
    }
 },
 series: [{
    name: 'Dev #1',
    data: [5, 10, 20, 22, 25, 28, 30, 40, 80, 90]
 }, {
    name: 'Dev #2',
    data: [15, 15, 18, 40, 30, 25, 60, 60, 80, 70]
 }, {
    name: 'Dev #3',
    data: [1, 3, 6, 0, 50, 25, 50, 60, 30, 100]
 }]
});

});</script>
</body>
</html>
</code>```

my component.ts is enabling web-view like that :

```<code>export class ChartComponent implements AfterViewInit {
    public webViewSrc: string = generateChartHtml();

    @ViewChild("myWebView") webViewRef: ElementRef;
    @ViewChild("labelResult") labelResultRef: ElementRef;

    ngAfterViewInit() {
        let webview: WebView = this.webViewRef.nativeElement;
        let label: Label = this.labelResultRef.nativeElement;
        label.text = "WebView is still loading...";

        webview.on(WebView.loadFinishedEvent, function (args: LoadEventData) {
            let message;
            if (!args.error) {
                message = "WebView finished loading of " + args.url;
            } else {
                message = "Error loading " + args.url + ": " + args.error;
            }

            label.text = message;
            console.log("WebView message - " + message);
        });
    }
}
</code>```

PS : generateChartHtml function is simple and just returns html code written above

here is my component.html :

```<code><ActionBar title="chaaaRtT">
</ActionBar>

<StackLayout #container VerticalOptions="FillAndExpand" height="350" [ngClass]="{'isSigningUp' : !isLoggingIn}">
    <WebView  #myWebView [src]="webViewSrc"></WebView>
    <Label  #labelResult></Label>
</StackLayout>
</code>```

tns - v3.0.1
angular - v4

And my second question is :
It is related to this issue 1659.

2) How can I load local files by html inside the web-view?

Issue 1659's solution is outdated I suppose. And it says nothing about iOS.
And its not said what would be root for html file when it would try to load css/js file.
For example here

```<code><head>
   <link rel="stylesheet" href="/form.css"/>
</head>
</code>```

And the last one :

3) Would it try to load form.css from the root of machine, or from some 'local' root, i.e. current folder?

Thanks in advance for the help

答:
solutions :
1) iOS : App Transport Security has blocked a cleartext HTTP resource - this would enable making http requests to any domains. By default in iOS native script is disabled.

2) same as in any web app

3) simply relative to the folder your webview html file is in

Body:
I got a problem. I need to use highcharts in mobile app. So I decided to use web-view. And it does not work neither on iOS nor on Android.

I have 3 questions:

1) I've tried to launch simple highchairs demo in my web view. Something went wrong. What I did wrong in the code below ? I suppose the problem is with loading js scripts.

HTML code inside the web-view component is the following :

    <meta charset="utf-8" />
    <meta name="author" content="Script Tutorials" />
    <title>How to create active charts using Highcharts | Script Tutorials</title>

my component.ts is enabling web-view like that :

export class ChartComponent implements AfterViewInit {
    public webViewSrc: string = generateChartHtml();

    @ViewChild("myWebView") webViewRef: ElementRef;
    @ViewChild("labelResult") labelResultRef: ElementRef;

    ngAfterViewInit() {
        let webview: WebView = this.webViewRef.nativeElement;
        let label: Label = this.labelResultRef.nativeElement;
        label.text = "WebView is still loading...";

        webview.on(WebView.loadFinishedEvent, function (args: LoadEventData) {
            let message;
            if (!args.error) {
                message = "WebView finished loading of " + args.url;
            } else {
                message = "Error loading " + args.url + ": " + args.error;
            }

            label.text = message;
            console.log("WebView message - " + message);
        });
    }
}

PS : generateChartHtml function is simple and just returns html code written above

here is my component.html :

<ActionBar title="chaaaRtT">
</ActionBar>

<StackLayout #container VerticalOptions="FillAndExpand" height="350" [ngClass]="{'isSigningUp' : !isLoggingIn}">
    <WebView  #myWebView [src]="webViewSrc"></WebView>

</StackLayout>

tns - v3.0.1
angular - v4

And my second question is :
It is related to this issue 1659.

2) How can I load local files by html inside the web-view?

Issue 1659's solution is outdated I suppose. And it says nothing about iOS.
And its not said what would be root for html file when it would try to load css/js file.
For example here

   <link rel="stylesheet" href="/form.css"/>

And the last one :

3) Would it try to load form.css from the root of machine, or from some 'local' root, i.e. current folder?

Thanks in advance for the help