问:
Too many "&&"s in condition coding. The better codes?
The following code works as intended but seems inelegant.

```<code>.Where(x =>     x.Attributes().Contains(x.Attribute("Quick"))
            && !x.Attributes().Contains(x.Attribute("Brown"))
            && !x.Attributes().Contains(x.Attribute("Fox"))
            && !x.Attributes().Contains(x.Attribute("Jumps"))
            && !x.Attributes().Contains(x.Attribute("Lazy"))
            && !x.Attributes().Contains(x.Attribute("Dogs")))
</code>```

As you can see, I am checking whether

the XElement has exactly one attribute

this attribute has the specified name

[Edit] My intention is..I want to make sure that the element has only one attribute. I mean only "Quick" attribute in this case. I know the count style though, the count does not distinguish its name.[/Edit]

[Edit2]I want elements if only if it has sigle attribute, nothing else.[/Edit2]

[Edit3]"x" is an element for instance..

```<code><mySeg Quick="1" Brown="Two" Fox="None" Jumps="2016_En" Lazy="100" Dogs="Source">  //  I do not want this XElement
</code>```

or

```<code><mySeg Quick="2" Brown="Ten">  //  Nah.
</code>```

or

```<code><mySeg Quick="3">  // yes, this is one I'm looking for.
</code>```

[Edit3]

[Edit4]
I guess, I have to use this one. Actually, it is the one I used before this post. I was thingking one shot.

```<code>x.Attributes().Contains(x.Attribute("Quick")) && x.Attributes().Count() == 1 //thanks Ryan
</code>```

[Edit4]

答:
At first gloss, you are testing

that a specific item is present

that none of a set of other items are present

Specifically, you are looking for a succinct way to express "none of these".

Rufus almost answered this question. Set up a list using his approach.

```<code>var exclusions = new string[] { "Brown", "Fox" , "Jumps", "Lazy", "Dogs" };
</code>```

Now you can test for the absence of this entire set. Remember that "none of" is the same as "not any of". We intersect the set of attribute names with the exclusion set and check whether it is empty using ! and .Any().

```<code>.Where(x => x.Attributes().Contains(x.Attribute("Quick"))
  && !a.Attributes().Select(a => a.Name).Intersect(exclusions).Any())
</code>```

However

You clarified the requirements to

XElement has exactly one attribute

This attribute has a specific name

and since you already credited "Ryan" with the obvious solution to this much simpler question here I stop.

You are doing set based comparison. Here's some homework.

The join operator

Get a copy of Linqpad and use that to experiment as you learn to use Linq effectively.

Intersect

Union

Except

Join as a lambda expression is messy. I prefer the inline syntax for joins.

You may also find it useful to explore the fact that you can combine Count with Where - Count can take a lambda expression that resolves to a Boolean, just like Where, and the result is the number of items that satisfied the condition. You can use this to count along several different dimensions in a single compound condition.

Body:
The following code works as intended but seems inelegant.

.Where(x =>     x.Attributes().Contains(x.Attribute("Quick"))
            && !x.Attributes().Contains(x.Attribute("Brown"))
            && !x.Attributes().Contains(x.Attribute("Fox"))
            && !x.Attributes().Contains(x.Attribute("Jumps"))
            && !x.Attributes().Contains(x.Attribute("Lazy"))
            && !x.Attributes().Contains(x.Attribute("Dogs")))

As you can see, I am checking whether

the XElement has exactly one attribute

this attribute has the specified name

[Edit] My intention is..I want to make sure that the element has only one attribute. I mean only "Quick" attribute in this case. I know the count style though, the count does not distinguish its name.[/Edit]

[Edit2]I want elements if only if it has sigle attribute, nothing else.[/Edit2]

[Edit3]"x" is an element for instance..

<mySeg Quick="1" Brown="Two" Fox="None" Jumps="2016_En" Lazy="100" Dogs="Source">  //  I do not want this XElement

or

<mySeg Quick="2" Brown="Ten">  //  Nah.

or

<mySeg Quick="3">  // yes, this is one I'm looking for.

[Edit3]

[Edit4]
I guess, I have to use this one. Actually, it is the one I used before this post. I was thingking one shot.

x.Attributes().Contains(x.Attribute("Quick")) && x.Attributes().Count() == 1 //thanks Ryan

[Edit4]

Body:
At first gloss, you are testing

that a specific item is present

that none of a set of other items are present

Specifically, you are looking for a succinct way to express "none of these".

Rufus almost answered this question. Set up a list using his approach.

var exclusions = new string[] { "Brown", "Fox" , "Jumps", "Lazy", "Dogs" };

Now you can test for the absence of this entire set. Remember that "none of" is the same as "not any of". We intersect the set of attribute names with the exclusion set and check whether it is empty using ! and .Any().

.Where(x => x.Attributes().Contains(x.Attribute("Quick"))
  && !a.Attributes().Select(a => a.Name).Intersect(exclusions).Any())

However

You clarified the requirements to

XElement has exactly one attribute

This attribute has a specific name

and since you already credited "Ryan" with the obvious solution to this much simpler question here I stop.

You are doing set based comparison. Here's some homework.

The join operator

Get a copy of Linqpad and use that to experiment as you learn to use Linq effectively.

Intersect

Union

Except

Join as a lambda expression is messy. I prefer the inline syntax for joins.

You may also find it useful to explore the fact that you can combine Count with Where - Count can take a lambda expression that resolves to a Boolean, just like Where, and the result is the number of items that satisfied the condition. You can use this to count along several different dimensions in a single compound condition.


来源: stackexchange

问:
Copy changes origin/development to origin/master
I have this history graph in Sourcetree:
Sourcetree graph

How can I copy the last commits from origin/development to origin/master branch?

The second question is: what are the meanings of the symbols "origin/development", "master", "origin/master", and "origin/HEAD" in the picture?

答:
To incorporate the commits which are on the branch "origin/development" into "master", you will need to "merge" origin/development into master. You accomplish this by checking out your destination branch (master) with the command git checkout master.

Then you perform the merge with the command git merge origin/development. You may have to resolve merge conflicts before this is successful.

In answer to your second question: The symbols are Git "branches" of your source tree. origin/master and origin/development are what are known as remote branches. They represent the last known revisions of a remote Git repository - in this case "origin". Your local branches master and development are your local copies of these branches.

As you don't seem to have a grasp of the entry-level concepts of Git, I highly recommend you read the Git Book - it will ground you in the basics, and then build up to the more advanced concepts.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
T-SQL Updating Query
I'm new to SQL and I'm trying to figure out how to SUM several columns and update an existing column with 1 or 0 if the SUM of the columns is more than 0.
Also, making sure null values get assigned a 0 value.

How to do something like the following in T-SQL?

```<code>if (select (coalesce(COL1, 0) +
coalesce(COL2 0) +
coalesce(COL3, 0) +
coalesce(COL4, 0) +
coalesce(COL5, 0) from SOMETABLE where X_CONDITION = 10)  >  0)
update SOMETABLE set ABC_COLUMN = 1
    else
    set ABC_COLUMN = 0;
</code>```

EDIT:

Currently the table looks somewhat like this:

```<code>x_condition | col1 | col2 |col3| col4| col5| abc_column
------------| -----| -----| ---| ----|-----|-----------
     7      | 1    |      |    |     |     |    0  (this in incorrect)
     7      | 0    |   0  |    |  0  |     |    0  (this is correct)
     5      | 1    |   1  |    |     |     |    0  (this is incorrect)
</code>```

I want the abc_column fixed - almost like a flag:

```<code> x_condition | col1 | col2 |col3| col4| col5| abc_column
------------| -----| -----| ---| ----|-----|-----------
     7      | 1    |      |    |     |     |    1
     7      | 0    |   0  |    |  0  |     |    0
     5      | 1    |   1  |    |     |     |    1
</code>```

Thank you!

答:
This sounds like an update statement with some arithmetic:

```<code>update SOMETABLE
    set ABC_COLUMN = (case when coalesce(COL1, 0) + coalesce(COL2 0) +
                                coalesce(COL3, 0) + coalesce(COL4, 0) +
                                coalesce(COL5, 0) > 0
                           then 1 else 0
                      end);
</code>```

You pretty much have all the pieces in your query.

Title: T-SQL Updating Query

Body:
I'm new to SQL and I'm trying to figure out how to SUM several columns and update an existing column with 1 or 0 if the SUM of the columns is more than 0.
Also, making sure null values get assigned a 0 value.

How to do something like the following in T-SQL?

if (select (coalesce(COL1, 0) +
coalesce(COL2 0) +
coalesce(COL3, 0) +
coalesce(COL4, 0) +
coalesce(COL5, 0) from SOMETABLE where X_CONDITION = 10)  >  0)
update SOMETABLE set ABC_COLUMN = 1
    else
    set ABC_COLUMN = 0;

EDIT:

Currently the table looks somewhat like this:

x_condition | col1 | col2 |col3| col4| col5| abc_column
------------| -----| -----| ---| ----|-----|-----------
     7      | 1    |      |    |     |     |    0  (this in incorrect)
     7      | 0    |   0  |    |  0  |     |    0  (this is correct)
     5      | 1    |   1  |    |     |     |    0  (this is incorrect)

I want the abc_column fixed - almost like a flag:

 x_condition | col1 | col2 |col3| col4| col5| abc_column
------------| -----| -----| ---| ----|-----|-----------
     7      | 1    |      |    |     |     |    1
     7      | 0    |   0  |    |  0  |     |    0
     5      | 1    |   1  |    |     |     |    1

Thank you!

Body:
This sounds like an update statement with some arithmetic:

update SOMETABLE
    set ABC_COLUMN = (case when coalesce(COL1, 0) + coalesce(COL2 0) +
                                coalesce(COL3, 0) + coalesce(COL4, 0) +
                                coalesce(COL5, 0) > 0
                           then 1 else 0
                      end);

You pretty much have all the pieces in your query.


问:
What's the advantage of multimap over map of vectors?
I don't understand why multimap exists if we can create map of vectors or map of sets.
For me only differences are:

using equal_range in multimap for getting elements of a key and in map of vectors we simply use [] operator and have vector of elements.

using multimap.insert(make_pair(key,value)) in multimap for adding elements and map_of_vectors[key].push_back(value) in map of vectors.

So why use multimap? For me it's better to have a vector than two iterators to get all values of a key.

This question applies also to unordered_map of vectors and unordered_multimap.

答:
I would say it depends on whether all the values with same key have a relationship that you want to address.

So for example, do you often go through all elements with key X, or pass them to a function, and so on? Then it is more convenient to already have them in their separate container, that you can address directly.

However, if you just have a collection of items, that may share same key value, or not, why use vectors in between? It is more convenient to run through the multimap with iterators than have a nested for-loop for the map, vector case.

Another way of looking at this: If multiple entries per key is very common, your structure is more efficient in the map, vector case. If they seldomly happen, it is the opposite.

ContentLicense: CC BY-SA 2.5


问:
I want to get all links from a certain webpage using python
i want to be able to pull all urls from the following webpage using python https://yeezysupply.com/pages/all i tried using some other suggestions i found but they didn't seem to work with this particular website. i would end up not finding any urls at all.</p>

```<code>import urllib
import lxml.html
connection = urllib.urlopen('https://yeezysupply.com/pages/all')

dom =  lxml.html.fromstring(connection.read())

for link in dom.xpath('//a/@href'):
    print link
</code>```

答:
perhaps it would be useful for you to make use of modules specifically designed for this. heres a quick and dirty script that gets the relative links on the page

```<code>#!/usr/bin/python3

import requests, bs4

res = requests.get('https://yeezysupply.com/pages/all')

soup = bs4.BeautifulSoup(res.text,'html.parser')
links = soup.find_all('a')

for link in links:
    print(link.attrs['href'])
</code>```

it generates output like this:

```<code>/pages/jewelry
/pages/clothing
/pages/footwear
/pages/all
/cart
/products/womens-boucle-dress-bleach/?back=%2Fpages%2Fall
/products/double-sleeve-sweatshirt-bleach/?back=%2Fpages%2Fall
/products/boxy-fit-zip-up-hoodie-light-sand/?back=%2Fpages%2Fall
/products/womens-boucle-skirt-cream/?back=%2Fpages%2Fall
etc...
</code>```

is this what you are looking for? requests and beautiful soup are amazing tools for scraping.

Body:
i want to be able to pull all urls from the following webpage using python https://yeezysupply.com/pages/all i tried using some other suggestions i found but they didn't seem to work with this particular website. i would end up not finding any urls at all.

import urllib
import lxml.html
connection = urllib.urlopen('https://yeezysupply.com/pages/all')

dom =  lxml.html.fromstring(connection.read())

for link in dom.xpath('//a/@href'):
    print link

Body:
perhaps it would be useful for you to make use of modules specifically designed for this. heres a quick and dirty script that gets the relative links on the page

#!/usr/bin/python3

import requests, bs4

res = requests.get('https://yeezysupply.com/pages/all')

soup = bs4.BeautifulSoup(res.text,'html.parser')
links = soup.find_all('a')

for link in links:
    print(link.attrs['href'])

it generates output like this:

/pages/jewelry
/pages/clothing
/pages/footwear
/pages/all
/cart
/products/womens-boucle-dress-bleach/?back=%2Fpages%2Fall
/products/double-sleeve-sweatshirt-bleach/?back=%2Fpages%2Fall
/products/boxy-fit-zip-up-hoodie-light-sand/?back=%2Fpages%2Fall
/products/womens-boucle-skirt-cream/?back=%2Fpages%2Fall
etc...

is this what you are looking for? requests and beautiful soup are amazing tools for scraping.


问:
Docker daemon "unknown: Authentication is required" message
I installed docker-toolbox on my Mac.

I ran the following command to login to our private registry (JFrog Artifactory 4.1). Provided username, email and password when requested and login succeeded.

```<code>docker login <registry url>
</code>```

This created a file ~/.docker/config.json on my system having some representation of my credentials.

Pulling and pushing images worked fine for a while. At some point later, when i tried to pull an image, i ended up with the following

```<code>b745547eea8f: Retrying in 1 second
8e68617bcad0: Retrying in 1 second
d0a4a553178b: Retrying in 1 second
4ef6bb1e3944: Retrying in 1 second
5f70bf18a086: Retrying in 1 second
69bd93b9db4e: Waiting
unknown: Authentication is required
</code>```

Retried multiple times with no luck. Ran "docker login" again and retried. Same issue was seen for 2-3 minutes. After 2-3 minutes, "docker pull" worked.

Questions:

After ~/.docker/config.json file is created, do these credentials expire after a certain amount of time? If yes, how can i increase the expiration time.

Why did "docker pull" fail for first 2-3 minutes after logging in for the second time. Does this have anything to do with time on my local machine and VM on VirtualBox created by docker-toolbox?

We are about to open our private registry to everyone in our company. Don't want people to face these things while pulling images.

答: Upgrading to latest version of Artifactory (4.10) helped. Didn't see this issue after that. </p>

Body:
I installed docker-toolbox on my Mac.

I ran the following command to login to our private registry (JFrog Artifactory 4.1). Provided username, email and password when requested and login succeeded.

docker login <registry url>

This created a file ~/.docker/config.json on my system having some representation of my credentials.

Pulling and pushing images worked fine for a while. At some point later, when i tried to pull an image, i ended up with the following

b745547eea8f: Retrying in 1 second
8e68617bcad0: Retrying in 1 second
d0a4a553178b: Retrying in 1 second
4ef6bb1e3944: Retrying in 1 second
5f70bf18a086: Retrying in 1 second
69bd93b9db4e: Waiting
unknown: Authentication is required

Retried multiple times with no luck. Ran "docker login" again and retried. Same issue was seen for 2-3 minutes. After 2-3 minutes, "docker pull" worked.

Questions:

After ~/.docker/config.json file is created, do these credentials expire after a certain amount of time? If yes, how can i increase the expiration time.

Why did "docker pull" fail for first 2-3 minutes after logging in for the second time. Does this have anything to do with time on my local machine and VM on VirtualBox created by docker-toolbox?

We are about to open our private registry to everyone in our company. Don't want people to face these things while pulling images.


问:
Multiple headers in HTML
I'm to code a webpage where a large header is at the top of the page. This header contains the navigation bar, the logo and the website title. Once the user starts scrolling, I'd like this to switch to a small header with just a navigation bar, which stays at the top of the page as the user scrolls. I couldn't find any way to do this online, and thought this might be interesting for me and other people.

This is the large, first header, with css code:

```<code>    <style>
    header {
    background-color: #0097A7;
    color: #ffffff;
    padding: 2%;
    text-align: center;
    }

    h1 {
    font-size: 270%;
    margin: 2% 0;
    }

    nav {
    background-color: rgba( 255, 255, 255, .4);
    border-radius: 25px;
    width: 50%;
    margin-left: auto;
    margin-right: auto;
    font-family: 'Neuton', serif;
    font-weight: bold;
    }

    nav a {
    color: #fff;
    display :inline-block;
    font-size: 100%;
    font-weight: bold;
    padding: 1% 4%;
    }

    nav a:hover {
    background-color: rgba( 255, 255, 255, .4);
    box-sizing: border-box;
    border-radius: 25px;
    }

    </style>

    <header>
      <h1><img alt="Logo" class="logo" height="50" src="media/logo.png">
      Fish & Chips </h1>
     <nav>
        <a href="index.php">Home</a>
        <a href="gallery.php">Gallery</a>
        <a href="about.php">About Us</a>
        <a href="contact.php">Contact Us</a>
      </nav>
    </header>
</code>```

This is the header I would like to switch to:

```<code>    <header>
     <nav>
        <a href="index.php">Home</a>
        <a href="gallery.php">Gallery</a>
        <a href="about.php">About Us</a>
        <a href="contact.php">Contact Us</a>
      </nav>
    </header>
</code>```

This is the code I found online to fix the header to the top of the screen

```<code>    <style>
    nav {
      position:fixed;
      top:0px;
    }
    </style>
</code>```

I am unsure how to switch between these two headers. I assume it may be simple jquery like :

```<code>    if (xPos > 0){
    switch to small, fixed header
    } else{
    switch to large header
    }
</code>```

Where xPos is how far down the page the user is.

However, I am unsure how to do this and can't find it online.

答: Have you tried using Bootstrap responsive designs? check them out.</p>

Title: Multiple headers in HTML

Body:
I'm to code a webpage where a large header is at the top of the page. This header contains the navigation bar, the logo and the website title. Once the user starts scrolling, I'd like this to switch to a small header with just a navigation bar, which stays at the top of the page as the user scrolls. I couldn't find any way to do this online, and thought this might be interesting for me and other people.

This is the large, first header, with css code:

      Fish & Chips

        Home
        Gallery
        About Us
        Contact Us

This is the header I would like to switch to:

        Home
        Gallery
        About Us
        Contact Us

This is the code I found online to fix the header to the top of the screen

I am unsure how to switch between these two headers. I assume it may be simple jquery like :

    if (xPos > 0){
    switch to small, fixed header
    } else{
    switch to large header
    }

Where xPos is how far down the page the user is.

However, I am unsure how to do this and can't find it online.


问:
How to update field value by determining each digit in field?
Although I saw update statements to update field based on existing values, I could not find anything similar to this scenario:

Suppose you have a table with only one column of number(4) type.  The value in the first record is 1010.

```<code>create table stab(
  nmbr number(4)
);

insert into stab values(1010);

For each digit
   When the digit is 1 -- add 3 to the digit
   When the digit is 0 -- add four to the digit
end
</code>```

This operations needs to be completed in a single statement without using pl/sql.

I think substr function need to be used but don't know how to go about completing this.

Thanks in advance.

答:
So, it seems you need to convert every 0 and 1 to a 4, and leave all the other digits alone. This seems like a string operation (and the reference to "digits" itself suggests the same thing). So, convert the number to a string, use the Oracle TRANSLATE function (see the documentation), and convert back to number.

```<code>update stab
set    nmbr = to_number(translate(to_char(nmbr, '9999'), '01', '44'))
;
</code>```

Body:
Although I saw update statements to update field based on existing values, I could not find anything similar to this scenario:

Suppose you have a table with only one column of number(4) type.  The value in the first record is 1010.

create table stab(
  nmbr number(4)
);

insert into stab values(1010);

For each digit
   When the digit is 1 -- add 3 to the digit
   When the digit is 0 -- add four to the digit
end

This operations needs to be completed in a single statement without using pl/sql.

I think substr function need to be used but don't know how to go about completing this.

Thanks in advance.

Body:
So, it seems you need to convert every 0 and 1 to a 4, and leave all the other digits alone. This seems like a string operation (and the reference to "digits" itself suggests the same thing). So, convert the number to a string, use the Oracle TRANSLATE function (see the documentation), and convert back to number.

update stab
set    nmbr = to_number(translate(to_char(nmbr, '9999'), '01', '44'))
;


答:
origin/development and origin/master are remote tracking branches that represent the state of the development and master branches on the origin server. You don't directly modify these, rather they get updated when you pull or fetch from origin.

To update them, you would commit the changes you want into your local development or master branch and push those changes to origin. But first, do a pull or fetch to make sure that you're working on the latest versions of both.

In this case, an easy shortcut would be to change your branch to master, reset --hard to origin/development, which forces the current state of your local master to that of origin/development, and then push to origin, which will cause origin/master to receive all the additional commits (from origin/development) that are now present in your master. Note that this only works because origin/master does not contain any commits that are not already in origin/development.

Title: Copy changes origin/development to origin/master

Body:
I have this history graph in Sourcetree:
Sourcetree graph

How can I copy the last commits from origin/development to origin/master branch?

The second question is: what are the meanings of the symbols "origin/development", "master", "origin/master", and "origin/HEAD" in the picture?


问:
Assigning the return value of new by reference is deprecated
Install "xampp-win32-1.7.3.exe" and put my php project in htdocs folder. this is working on another machine which having PHP version of 5.3 same version is here also but gives me following error

Deprecated: Assigning the return value
  of new by reference is deprecated in
  C:\xampp\htdocs\businesscaliber\system\codeigniter\Common.php
  on line 62 A PHP Error was encountered

Severity: 8192

Message: Function
  set_magic_quotes_runtime() is
  deprecated

Filename: codeigniter/CodeIgniter.php

Line Number: 45

答: Make sure you have your codeigniter version updated to the last version.</p>


问:
Why Does This Javascript Program Not Display Table When Used in Loop
I am trying to use an infinite loop before prodNum and quantity prompts to continuously accept user input and output to the table. The program works fine when I run it, except in a loop the table is never displayed. I tried moving the script to different parts of the web page. Using Chrome.</p>

```<code>       <html>

<head>
</head>

<body>

  <table>
    <tr>
      <th>Product Number</th>
      <th>Total Sales ($)</th>
    </tr>
    <tr>
      <td>1</td>
      <td id="total1">$0.00</td>
    </tr>
    <tr>
      <td>2</td>
      <td id="total2">$0.00</td>
    </tr>
    <tr>
      <td>3</td>
      <td id="total3">$0.00</td>
    </tr>
    <tr>
      <td>4</td>
      <td id="total4">$0.00</td>
    </tr>
    <tr>
      <td>5</td>
      <td id="total5">$0.00</td>
    </tr>
  </table>

  <script type="text/javascript">
    var total1 = 0.00;
    var total2 = 0.00;
    var total3 = 0.00;
    var total4 = 0.00;
    var total5 = 0.00;
    var prodNum = 0;
    var prodNumInt = 0;
    quantityFloat = 0.00;

    var quantity = 0;

    prodNum = window.prompt("Please enter the product number (Enter -1 to quit)");
    quantity = window.prompt("Please enter the quantity sold (Enter -2 to quit)");
    prodNumInt = parseInt(prodNum);
    quantityFloat = parseFloat(quantity);

    switch (prodNumInt) {
      case 1:
        total1 += quantityFloat * 2.98;
        document.getElementById("total1").innerHTML = "$" + parseFloat(total1).toFixed(2);
        break;
      case 2:
        total2 += quantityFloat * 4.50;
        document.getElementById("total2").innerHTML = "$" + parseFloat(total2).toFixed(2);
        break;
      case 3:
        total3 += quantityFloat * 9.98;
        document.getElementById("total3").innerHTML = "$" + parseFloat(total3).toFixed(2);
        break;
      case 4:
        total4 += quantityFloat * 4.49;
        document.getElementById("total4").innerHTML = "$" + parseFloat(total4).toFixed(2);
        break;
      case 5:
        total5 += quantityFloat * 6.87;
        document.getElementById("total5").innerHTML = "$" + parseFloat(total5).toFixed(2);
    }
  </script>
</body>

</html>
</code>```

答:
Put your code in a function, and call it again with setTimeout(). This will allow the browser to render the previous table while waiting for the timeout.

function update_table() {
  var total1 = 0.00;
  var total2 = 0.00;
  var total3 = 0.00;
  var total4 = 0.00;
  var total5 = 0.00;
  var prodNum = 0;
  var prodNumInt = 0;
  var quantityFloat = 0.00;

  var quantity = 0;

  prodNum = window.prompt("Please enter the product number (Enter -1 to quit)");
  if (prodNum == '-1') {
    return;
  }
  quantity = window.prompt("Please enter the quantity sold (Enter -2 to quit)");
  if (quantity == '-2') {
    return;
  }
  prodNumInt = parseInt(prodNum);
  quantityFloat = parseFloat(quantity);

  switch (prodNumInt) {
    case 1:
      total1 += quantityFloat * 2.98;
      document.getElementById("total1").innerHTML = "$" + total1.toFixed(2);
      break;
    case 2:
      total2 += quantityFloat * 4.50;
      document.getElementById("total2").innerHTML = "$" + total2.toFixed(2);
      break;
    case 3:
      total3 += quantityFloat * 9.98;
      document.getElementById("total3").innerHTML = "$" + total3.toFixed(2);
      break;
    case 4:
      total4 += quantityFloat * 4.49;
      document.getElementById("total4").innerHTML = "$" + total4.toFixed(2);
      break;
    case 5:
      total5 += quantityFloat * 6.87;
      document.getElementById("total5").innerHTML = "$" + total5.toFixed(2);

  }
  setTimeout(update_table, 1000);
}

update_table();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <th>Product Number</th>
    <th>Total Sales ($)</th>
  </tr>
  <tr>
    <td>1</td>
    <td id="total1">$0.00</td>
  </tr>
  <tr>
    <td>2</td>
    <td id="total2">$0.00</td>
  </tr>
  <tr>
    <td>3</td>
    <td id="total3">$0.00</td>
  </tr>
  <tr>
    <td>4</td>
    <td id="total4">$0.00</td>
  </tr>
  <tr>
    <td>5</td>
    <td id="total5">$0.00</td>
  </tr>
</table></code>```

BTW, you don't need to use parseFloat(total1), since total1 is already a float.

Body:
I am trying to use an infinite loop before prodNum and quantity prompts to continuously accept user input and output to the table. The program works fine when I run it, except in a loop the table is never displayed. I tried moving the script to different parts of the web page. Using Chrome.

      Product Number
      Total Sales ($)

      1
      $0.00

      2
      $0.00

      3
      $0.00

      4
      $0.00

      5
      $0.00

Body:
Put your code in a function, and call it again with setTimeout(). This will allow the browser to render the previous table while waiting for the timeout.

function update_table() {
  var total1 = 0.00;
  var total2 = 0.00;
  var total3 = 0.00;
  var total4 = 0.00;
  var total5 = 0.00;
  var prodNum = 0;
  var prodNumInt = 0;
  var quantityFloat = 0.00;

  var quantity = 0;

  prodNum = window.prompt("Please enter the product number (Enter -1 to quit)");
  if (prodNum == '-1') {
    return;
  }
  quantity = window.prompt("Please enter the quantity sold (Enter -2 to quit)");
  if (quantity == '-2') {
    return;
  }
  prodNumInt = parseInt(prodNum);
  quantityFloat = parseFloat(quantity);

  switch (prodNumInt) {
    case 1:
      total1 += quantityFloat * 2.98;
      document.getElementById("total1").innerHTML = "$" + total1.toFixed(2);
      break;
    case 2:
      total2 += quantityFloat * 4.50;
      document.getElementById("total2").innerHTML = "$" + total2.toFixed(2);
      break;
    case 3:
      total3 += quantityFloat * 9.98;
      document.getElementById("total3").innerHTML = "$" + total3.toFixed(2);
      break;
    case 4:
      total4 += quantityFloat * 4.49;
      document.getElementById("total4").innerHTML = "$" + total4.toFixed(2);
      break;
    case 5:
      total5 += quantityFloat * 6.87;
      document.getElementById("total5").innerHTML = "$" + total5.toFixed(2);

  }
  setTimeout(update_table, 1000);
}

update_table();

<table>
  <tr>
    <th>Product Number</th>
    <th>Total Sales ($)</th>
  </tr>
  <tr>
    <td>1</td>
    <td id="total1">$0.00</td>
  </tr>
  <tr>
    <td>2</td>
    <td id="total2">$0.00</td>
  </tr>
  <tr>
    <td>3</td>
    <td id="total3">$0.00</td>
  </tr>
  <tr>
    <td>4</td>
    <td id="total4">$0.00</td>
  </tr>
  <tr>
    <td>5</td>
    <td id="total5">$0.00</td>
  </tr>
</table>

BTW, you don't need to use parseFloat(total1), since total1 is already a float.


问:
Bluetooth: Android 6 & 7 Sniff mode
I am developing a custom FW on STM32, which communicates over Bluetooth classic with Android device.

It worked flawlessly with Android 5. But starting from Android 6, the Sniff mode is requested by Android and its values are out of the range for our use cases.

We tried to exit sniff mode immediately after Android requested Sniff mode. This didn't help, because after next 5 seconds, Android will request the sniff mode again.

Similarly, when we set our sniff values, Android will ignore them and request its own "big" values.

We have under control Android App and FW on the Bt device. Is there any way
to control sniff mode from Android side? As far as I know there is no public API for doing that. Just asking if I missed something.

Thanks.

答: I've seen the issue as well. The only solution that seems to work is using a "keep alive", whereby we send arbitrary data over the bluetooth socket every 1.5 seconds or so from the Android device. This seems to keep sniff mode from re-enabling.</p>

Title: Bluetooth: Android 6 & 7 Sniff mode


问:
Putting a time restriction on input
I have searched this for a while but I have not found a way that has worked
what I want to do is this:

```<code>prompt=str(input('press "l" within two seconds:'):
    if prompt=='l':
        print('ta da')
    else:
        print('loser')
</code>```

how do I add a time restriction to that?

答:
If you are not caring about beeing thread safe, this is a good aproach:</p>

```<code>import datetime
import threading
win = False
time_out = False
def MyThread1(t_name, prompt, time_var):
    global win
    global time_out
    prompt=str(input('press "l" within two seconds:'))
    win = False
    if(not time_out and prompt == 'l'):
      win = True
      print('ta da')
    else:
      print('loser')

def MyThread2(t_name, prompt, time_var):
  global win
  global time_out
  while (time_var > datetime.datetime.now()):
    pass
  time_out = True

time_var = datetime.datetime.now() + datetime.timedelta(seconds=2)
prompt = 'l'

t1 = threading.Thread(target=MyThread1, args=("Thread-1", prompt, time_var))
t2 = threading.Thread(target=MyThread2, args=("Thread-2", prompt, time_var))
t1.start()
t2.start()
</code>```

Title: Putting a time restriction on input

Body:
I have searched this for a while but I have not found a way that has worked
what I want to do is this:

prompt=str(input('press "l" within two seconds:'):
    if prompt=='l':
        print('ta da')
    else:
        print('loser')

how do I add a time restriction to that?

Body:
If you are not caring about beeing thread safe, this is a good aproach:

import datetime
import threading
win = False
time_out = False
def MyThread1(t_name, prompt, time_var):
    global win
    global time_out
    prompt=str(input('press "l" within two seconds:'))
    win = False
    if(not time_out and prompt == 'l'):
      win = True
      print('ta da')
    else:
      print('loser')

def MyThread2(t_name, prompt, time_var):
  global win
  global time_out
  while (time_var > datetime.datetime.now()):
    pass
  time_out = True

time_var = datetime.datetime.now() + datetime.timedelta(seconds=2)
prompt = 'l'

t1 = threading.Thread(target=MyThread1, args=("Thread-1", prompt, time_var))
t2 = threading.Thread(target=MyThread2, args=("Thread-2", prompt, time_var))
t1.start()
t2.start()


问:
I want to create a case in salesforce from Android App
We have a REST API in salesforce to create cases.We want to access the same API from Android/IOS App to create a case.Here my problem is authentication.

We are using OAuth 2.0 user agent flow for authentication because in username-password we need to expose username and password so we
  don't want to use that flow to get the access token. In User Agent
  flow should the user need to enter the password or it will authorize
  based on authorization code?

If user need to enter the password how we will avoid because the user will be customer they don't have any password and username ,can
  we store password and use it to for logging automatically.

Thanks in advance

答: you could try exposing a public Rest API in Salesforce. So that your mobile App can do a Post request to that specific end-point, and a case can be created via Apex, based on the criteria specified in your Json.</p>


问:
Processing some directives leaving others
I use to go through C code having lot of #ifdef, #if and #endif directive which keep some portion active and some portion inactive depending on some variables are defined or not. I searched for something that can process them to generate final C code. But the preprocessing also does the same for #include and #define. But I want to keep them.

So, is there any thing to preprocess these files or project with some filtering?

答:
I assume you're using gcc.

If you mean all #includes, I think you need to remove them, expand the resulting file with gcc -E then add the #includess back.

If you mean only the standard headers, the option -nostdinc may help you do what you want

```user@host:~/test/tmp$ cat 4437465.c
#include <stdio.h>

#ifndef OUTPUT_TYPE
#define OUTPUT_TYPE 1
#endif

int main(void) {
#if OUTPUT_TYPE == 1
  printf("output type 1\n");
#elif OUTPUT_TYPE == 2
  printf("output type 2\n");
#else
  printf("default output type\n");
#endif
  return 0;
}```

```user@host:~/test/tmp$ gcc -DOUTPUT_TYPE=2 -nostdinc -E 4437465.c
# 1 "4437465.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "4437465.c"
4437465.c:1:19: error: no include path in which to search for stdio.h

int main(void) {

  printf("output type 2\n");

  return 0;
}```

Body:
I assume you're using gcc.

If you mean all #includes, I think you need to remove them, expand the resulting file with gcc -E then add the #includess back.

If you mean only the standard headers, the option -nostdinc may help you do what you want

user@host:~/test/tmp$ cat 4437465.c
#include <stdio.h>

#ifndef OUTPUT_TYPE
#define OUTPUT_TYPE 1
#endif

int main(void) {
#if OUTPUT_TYPE == 1
  printf("output type 1\n");
#elif OUTPUT_TYPE == 2
  printf("output type 2\n");
#else
  printf("default output type\n");
#endif
  return 0;
}

user@host:~/test/tmp$ gcc -DOUTPUT_TYPE=2 -nostdinc -E 4437465.c
# 1 "4437465.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "4437465.c"
4437465.c:1:19: error: no include path in which to search for stdio.h

int main(void) {

  printf("output type 2\n");

  return 0;
}


问:
BigQuery: Querying with standard sql
I have this table:

```<code>client_id   session_id  time    action  transaction_id
------------------------------------------------------
1   1   15:01   view    NULL
1   1   15:02   basket  NULL
1   1   15:03   basket  NULL
1   1   15:04   purchase    1
1   2   15:05   basket  NULL
1   2   15:06   purchase    2
1   2   15:07   view    NULL
</code>```

And I want inside the session, for all the previous actions to register the transaction_id that occur for the first time (therefore at 15:03 transaction_id = NULL)

```<code>session_id  time    transaction_id
------------------------------------
1   15:01   1
1   15:02   1
1   15:03   NULL
1   15:04   1
2   15:05   2
2   15:06   2
2   15:07   NULL
</code>```

答:
Below is for BigQuery Standard SQL

#standardSQL
SELECT
  client_id, session_id, time, action,
  (CASE
    WHEN ROW_NUMBER()
         OVER (PARTITION BY client_id, session_id, grp, action ORDER BY time) = 1
    THEN MAX(transaction_id) OVER (PARTITION BY client_id, session_id, grp) END
  ) AS transaction_id
FROM (
  SELECT *,
    COUNTIF(transaction_id IS NOT NULL)
      OVER(PARTITION BY client_id, session_id
      ORDER BY time ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS grp
  FROM YourTable
)
-- ORDER BY client_id, session_id, time
```

<p>You can test play with dummy data as below   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH YourTable AS (
  SELECT 1 AS client_id, 1 AS session_id, '15:01' AS time, 'view' AS action, NULL AS transaction_id UNION ALL
  SELECT 1, 1, '15:02', 'basket', NULL UNION ALL
  SELECT 1, 1, '15:03', 'basket', NULL UNION ALL
  SELECT 1, 1, '15:04', 'purchase', 1 UNION ALL
  SELECT 1, 1, '15:05', 'basket', NULL UNION ALL
  SELECT 1, 1, '15:06', 'basket', NULL UNION ALL
  SELECT 1, 1, '15:07', 'purchase', 3 UNION ALL
  SELECT 1, 2, '15:08', 'basket', NULL UNION ALL
  SELECT 1, 2, '15:09', 'purchase', 2 UNION ALL
  SELECT 1, 2, '15:10', 'view', NULL
)
SELECT
  client_id, session_id, time, action,
  (CASE
    WHEN ROW_NUMBER()
         OVER (PARTITION BY client_id, session_id, grp, action ORDER BY time) = 1
    THEN MAX(transaction_id) OVER (PARTITION BY client_id, session_id, grp) END
  ) AS transaction_id
FROM (
  SELECT *,
    COUNTIF(transaction_id IS NOT NULL)
      OVER(PARTITION BY client_id, session_id
      ORDER BY time ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS grp
  FROM YourTable
)
-- ORDER BY client_id, session_id, time
</code>```

Output is as expected

client_id   session_id  time    action      transaction_id
1           1           15:01   view        1
1           1           15:02   basket      1
1           1           15:03   basket      null
1           1           15:04   purchase    1
1           1           15:05   basket      3
1           1           15:06   basket      null
1           1           15:07   purchase    3
1           2           15:08   basket      2
1           2           15:09   purchase    2
1           2           15:10   view        null
```

Title: BigQuery: Querying with standard sql

Body:
I have this table:

client_id   session_id  time    action  transaction_id
------------------------------------------------------
1   1   15:01   view    NULL
1   1   15:02   basket  NULL
1   1   15:03   basket  NULL
1   1   15:04   purchase    1
1   2   15:05   basket  NULL
1   2   15:06   purchase    2
1   2   15:07   view    NULL

And I want inside the session, for all the previous actions to register the transaction_id that occur for the first time (therefore at 15:03 transaction_id = NULL)

session_id  time    transaction_id
------------------------------------
1   15:01   1
1   15:02   1
1   15:03   NULL
1   15:04   1
2   15:05   2
2   15:06   2
2   15:07   NULL

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT
  client_id, session_id, time, action,
  (CASE
    WHEN ROW_NUMBER()
         OVER (PARTITION BY client_id, session_id, grp, action ORDER BY time) = 1
    THEN MAX(transaction_id) OVER (PARTITION BY client_id, session_id, grp) END
  ) AS transaction_id
FROM (
  SELECT *,
    COUNTIF(transaction_id IS NOT NULL)
      OVER(PARTITION BY client_id, session_id
      ORDER BY time ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS grp
  FROM YourTable
)
-- ORDER BY client_id, session_id, time

You can test play with dummy data as below

#standardSQL
WITH YourTable AS (
  SELECT 1 AS client_id, 1 AS session_id, '15:01' AS time, 'view' AS action, NULL AS transaction_id UNION ALL
  SELECT 1, 1, '15:02', 'basket', NULL UNION ALL
  SELECT 1, 1, '15:03', 'basket', NULL UNION ALL
  SELECT 1, 1, '15:04', 'purchase', 1 UNION ALL
  SELECT 1, 1, '15:05', 'basket', NULL UNION ALL
  SELECT 1, 1, '15:06', 'basket', NULL UNION ALL
  SELECT 1, 1, '15:07', 'purchase', 3 UNION ALL
  SELECT 1, 2, '15:08', 'basket', NULL UNION ALL
  SELECT 1, 2, '15:09', 'purchase', 2 UNION ALL
  SELECT 1, 2, '15:10', 'view', NULL
)
SELECT
  client_id, session_id, time, action,
  (CASE
    WHEN ROW_NUMBER()
         OVER (PARTITION BY client_id, session_id, grp, action ORDER BY time) = 1
    THEN MAX(transaction_id) OVER (PARTITION BY client_id, session_id, grp) END
  ) AS transaction_id
FROM (
  SELECT *,
    COUNTIF(transaction_id IS NOT NULL)
      OVER(PARTITION BY client_id, session_id
      ORDER BY time ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS grp
  FROM YourTable
)
-- ORDER BY client_id, session_id, time

Output is as expected

client_id   session_id  time    action      transaction_id
1           1           15:01   view        1
1           1           15:02   basket      1
1           1           15:03   basket      null
1           1           15:04   purchase    1
1           1           15:05   basket      3
1           1           15:06   basket      null
1           1           15:07   purchase    3
1           2           15:08   basket      2
1           2           15:09   purchase    2
1           2           15:10   view        null


问:
How to validate that user input valid year in android EditTextPreference?
I have the following EditText preference

```<code>    <EditTextPreference android:key="pref_movies_min_year"
        android:title="@string/pref_movies_min_year"
        android:summary="@string/pref_movies_min_year_summary"
        android:defaultValue="1950"/>
</code>```

I need to validate that user has input valid year (i.e. the value is numeric, 4 digits, between 1900 and current year). Ideally to do it when user changes the preference.

How should I do it?

答:
```<code>String year = eyear.getText().toString();
                if (!year.subSequence(0, 2).equals("19") || year.length()!= 4) {

                    LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
                            .getSystemService(LAYOUT_INFLATER_SERVICE);
                    View popupView = layoutInflater.inflate(R.layout.helppop, null);
                    final PopupWindow popupWindow = new PopupWindow(popupView,
                            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                    ImageButton img = (ImageButton) popupView
                            .findViewById(R.id.imageButton1);
                    img.setBackground(getResources()
                            .getDrawable(R.drawable.warning));
                    TextView txt = (TextView) popupView.findViewById(R.id.helptxt);
                    txt.setText("the year you entert is incorret");
</code>```

Body:
I have the following EditText preference

    <EditTextPreference android:key="pref_movies_min_year"
        android:title="@string/pref_movies_min_year"
        android:summary="@string/pref_movies_min_year_summary"
        android:defaultValue="1950"/>

I need to validate that user has input valid year (i.e. the value is numeric, 4 digits, between 1900 and current year). Ideally to do it when user changes the preference.

How should I do it?


问:
How can I call on multiple variables to determine their average only if they exist?
So I have multiple loops like this:

```<code>HPBL = grbs[15].values
lat = input('Enter lat:')
lon = input('Enter lon:')
print 'PBL Height:',HPBL[int(lat),int(lon)],'m'
HGT_1000 = grbs[256].values
if HGT_1000[int(lat),int(lon)]<HPBL[int(lat),int(lon)]:
    UGRD_1000 = grbs[260].values
    VGRD_1000 = grbs[261].values
    UGRD_1000_val = UGRD_1000[int(lat),int(lat)]
    VGRD_1000_val = VGRD_1000[int(lat),int(lat)]
    wind_1000 = math.sqrt(UGRD_1000_val**2+VGRD_1000_val**2)
    print '1000mb wind is:',wind_1000,'m/s'
else:
    print '1000mb winds not below PBL'
</code>```

Where the end goal is to print an average of wind_1000, wind_975, wind_950, and etc but only if each wind_xxxx variable has a value. Per the loop, I have it skip if the 'if' requirement is not met.
So what I am having trouble thinking of is how I would go about computing the average

```<code>wind_ave=np.mean(wind_1000,wind_975,wind_950,...wind_xxx)
</code>```

but of course my problem is that the wind variables won't always have a value per the if loops. How can I compute the wind_ave only if the wind_xxx variables have values to them?

答:
Are you looking for something like this?

```<code>total = 0
n_inputs = 0
while my_loop_condition:
    if there_is_a_value:
        total += value
        n_inputs += 1
average = total / n_inputs
</code>```

which can also be done in numpy with: my_values[~np.isnan(my_values)].mean() if missing values are coded with np.nan.

Body:
So I have multiple loops like this:

HPBL = grbs[15].values
lat = input('Enter lat:')
lon = input('Enter lon:')
print 'PBL Height:',HPBL[int(lat),int(lon)],'m'
HGT_1000 = grbs[256].values
if HGT_1000[int(lat),int(lon)]<HPBL[int(lat),int(lon)]:
    UGRD_1000 = grbs[260].values
    VGRD_1000 = grbs[261].values
    UGRD_1000_val = UGRD_1000[int(lat),int(lat)]
    VGRD_1000_val = VGRD_1000[int(lat),int(lat)]
    wind_1000 = math.sqrt(UGRD_1000_val**2+VGRD_1000_val**2)
    print '1000mb wind is:',wind_1000,'m/s'
else:
    print '1000mb winds not below PBL'

Where the end goal is to print an average of wind_1000, wind_975, wind_950, and etc but only if each wind_xxxx variable has a value. Per the loop, I have it skip if the 'if' requirement is not met.
So what I am having trouble thinking of is how I would go about computing the average

wind_ave=np.mean(wind_1000,wind_975,wind_950,...wind_xxx)

but of course my problem is that the wind variables won't always have a value per the if loops. How can I compute the wind_ave only if the wind_xxx variables have values to them?

Body:
Are you looking for something like this?

total = 0
n_inputs = 0
while my_loop_condition:
    if there_is_a_value:
        total += value
        n_inputs += 1
average = total / n_inputs

which can also be done in numpy with: my_values[~np.isnan(my_values)].mean() if missing values are coded with np.nan.


问:
Visual Studio 2008 projects from Visual Studio 2010 without conversion
Is there a way?
Can I use and build Visual Studio 2008 projects from Visual Studio 2010 without conversion?

I found this explanation:

http://blogs.msdn.com/b/visualstudio/archive/2010/03/15/why-does-visual-studio-2010-convert-my-projects.aspx

Is there any "hack" for this? :)

In my team, we need this in order to work on same VS version of project(source is on svn) and from different IDE's.

答:
I don't think you can go that way - but you can load VS2010 projects in VS2008. Take a backup of the 2008 solution, let VS2010 do the conversion, and then load the 2008 solution again. There will be warnings that it's using an unknown tool version, but so long as your projects are "simple" (don't use any 2010-specific stuff) it should work.

I use this technique for Noda Time, with solutions of "Noda Time VS2008.sln" and "Noda Time VS2010.sln". Using the same project files for both solutions is a real boon - it means you don't need to remember to add source files to "the other" project when you're adding them to one.


问:
How to avoid Decimal values in input type number
How to avoid Decimal values from input of Number in HTML5. Currently it allows user to type decimal value.</p>

答:
An alternative to the supplied answers is to monitor the keypress while in the input. I personally like leaving the type="number" as an attribute. Here's a JSFiddle

```<code><form action="#" method="post">
  Numbers: <input name="num"
                  type="number"
                  min="1"
                  step="1"
                  onkeypress="return event.charCode >= 48 && event.charCode <= 57"
                  title="Numbers only">
  <input type="submit">
</form>
</code>```

Body:
An alternative to the supplied answers is to monitor the keypress while in the input. I personally like leaving the type="number" as an attribute. Here's a JSFiddle

<form action="#" method="post">
  Numbers: <input name="num"
                  type="number"
                  min="1"
                  step="1"
                  onkeypress="return event.charCode >= 48 && event.charCode <= 57"
                  title="Numbers only">
  <input type="submit">
</form>


问:
How to cut off int at the end of a line
I have a txt file similar to the following:

```<code>f1, max, inputs: 10 2 4

f2, sum, inputs: 2 4 5

f3, prod, inputs: 6 5
</code>```

I should find the max from the line where the max is stated (10), print the sum of the numbers from where the sum is (11), and the product from where the prod is (30).

My code looks like this:

```<code>f = File.open("test.txt") or die "Unable to open file..."
contentArray=[]
f.each_line {|line|
    contentArray.push line
}

i=0
while i<contentArray.size() do
    if contentArray[i].include? "max"
        print "max is here"
        i+=1
    elsif contentArray[i].include? "sum"
        print "sum is here"
        i+=1
    elsif contentArray[i].include? "prod"
        print "prod is here"
        i+=1
    end
end
</code>```

I can find which line has the max, sum, or prod string, but I don't know how I should cut off the integers from the end and do the maths with them.

答:
Consider this:

```<code>content_array = [
  'f1, max, inputs: 10 2 4',
  'f2, sum, inputs: 2 4 5',
  'f3, prod, inputs: 6 5'
]
</code>```

I'd solve the basic problem like this:

```<code>content_array.each do |li|
  values = li.scan(/\b \d+ \b/x).map(&:to_i)

  operation, result = case li
          when /\b max \b/x
            ['max', values.max]
          when /\b sum \b/x
            ['sum', values.sum]
          when /\b prod \b/x
            ['prod', values.inject(:*)]
          end
  puts "#{operation}: #{result}"
end
</code>```

Which outputs:

```<code>max: 10
sum: 11
prod: 30
</code>```

Doing it this way will handle more numbers being added to the ends of the lines without changes to the code.

If I added an additional record:

```<code>'f4, prod, inputs: 6 5 4 3 2'
</code>```

I'd get:

```<code>prod: 720
</code>```

Breaking it down:

```<code>values = li.scan(/\b \d+ \b/x) # => ["10", "2", "4"], ["2", "4", "5"], ["6", "5"]
  .map(&:to_i)                 # => [10, 2, 4],       [2, 4, 5],       [6, 5]
</code>```

Where /\b \d+ \b/x is a Regexp pattern that searches for stand-alone numbers.

Title: How to cut off int at the end of a line

Body:
I have a txt file similar to the following:

f1, max, inputs: 10 2 4

f2, sum, inputs: 2 4 5

f3, prod, inputs: 6 5

I should find the max from the line where the max is stated (10), print the sum of the numbers from where the sum is (11), and the product from where the prod is (30).

My code looks like this:

f = File.open("test.txt") or die "Unable to open file..."
contentArray=[]
f.each_line {|line|
    contentArray.push line
}

i=0
while i<contentArray.size() do
    if contentArray[i].include? "max"
        print "max is here"
        i+=1
    elsif contentArray[i].include? "sum"
        print "sum is here"
        i+=1
    elsif contentArray[i].include? "prod"
        print "prod is here"
        i+=1
    end
end

I can find which line has the max, sum, or prod string, but I don't know how I should cut off the integers from the end and do the maths with them.

Body:
Consider this:

content_array = [
  'f1, max, inputs: 10 2 4',
  'f2, sum, inputs: 2 4 5',
  'f3, prod, inputs: 6 5'
]

I'd solve the basic problem like this:

content_array.each do |li|
  values = li.scan(/\b \d+ \b/x).map(&:to_i)

  operation, result = case li
          when /\b max \b/x
            ['max', values.max]
          when /\b sum \b/x
            ['sum', values.sum]
          when /\b prod \b/x
            ['prod', values.inject(:*)]
          end
  puts "#{operation}: #{result}"
end

Which outputs:

max: 10
sum: 11
prod: 30

Doing it this way will handle more numbers being added to the ends of the lines without changes to the code.

If I added an additional record:

'f4, prod, inputs: 6 5 4 3 2'

I'd get:

prod: 720

Breaking it down:

values = li.scan(/\b \d+ \b/x) # => ["10", "2", "4"], ["2", "4", "5"], ["6", "5"]
  .map(&:to_i)                 # => [10, 2, 4],       [2, 4, 5],       [6, 5]

Where /\b \d+ \b/x is a Regexp pattern that searches for stand-alone numbers.


问:
keypress event listener producing inconsistent motion in processing.js
I use the keypress event listener in a lot of animations in processing js and here is a problem that consistently plagues me. In this example I made, when I press the 'd' button, a ball moves to the right. Actually, the ball is stationary, and the ground moves left below it.

The problem is this: When I press and hold 'd', the ball lurches right at the correct speed almost instantly, but then stops for an instant, then reaches the correct speed and then continues at that speed for as long as I hold 'd'. I don't know why the ball doesn't hit that speed and stay there, but that is what I'd like it to do.

Here is a fiddle which may show what I mean:

https://jsfiddle.net/4s14wq4d/

The method is quite simple:

```<code>hill.prototype.moveRight = function() {
  this.x -= 5;
};
</code>```

And here is the event listener in action:

```<code>var myCanvas = document.getElementById("myCanvas");
myCanvas.addEventListener("keypress", functionMove);
function functionMove(e) {
  if (e.keyCode == "100") {
    for (var i = 0; i < hillArray.length; i++) {
      hillArray[i].moveRight();
    }
  }
};
</code>```

答:
First off, you should not be adding your own event listeners. Processing gives you functions like keyPressed() and keyReleased(). Use those instead.

Secondly, what you probably want to do is create variables that keep track of whether a key is pressed or not. Something like this:

```<code>var wPressed = false;
var sPressed = false;
var aPressed = false;
var dPressed = false;
</code>```

Then in the keyPressed()  function, you would set the corresponding variable to true, and in the keyReleased() function, you'd set it to false.

Finally, in the draw() function, you'd check each of the variable and do the right thing. Something like this:

```<code>if(dPressed){
   for (var i = 0; i < hillArray.length; i++) {
     hillArray[i].moveRight();
   }
}
</code>```

(Side note: If you're moving all of the elements by the same distance, you might just want to use a single xOffset variable or something that you use, that way you don't have to loop over every item to move it individually.)

Shameless self promotion: I wrote a tutorial on user input (including the above approach) available here. It's for regular Processing, but all of the ideas are the same in Processing.js.

Body:
I use the keypress event listener in a lot of animations in processing js and here is a problem that consistently plagues me. In this example I made, when I press the 'd' button, a ball moves to the right. Actually, the ball is stationary, and the ground moves left below it.

The problem is this: When I press and hold 'd', the ball lurches right at the correct speed almost instantly, but then stops for an instant, then reaches the correct speed and then continues at that speed for as long as I hold 'd'. I don't know why the ball doesn't hit that speed and stay there, but that is what I'd like it to do.

Here is a fiddle which may show what I mean:

https://jsfiddle.net/4s14wq4d/

The method is quite simple:

hill.prototype.moveRight = function() {
  this.x -= 5;
};

And here is the event listener in action:

var myCanvas = document.getElementById("myCanvas");
myCanvas.addEventListener("keypress", functionMove);
function functionMove(e) {
  if (e.keyCode == "100") {
    for (var i = 0; i < hillArray.length; i++) {
      hillArray[i].moveRight();
    }
  }
};

Body:
First off, you should not be adding your own event listeners. Processing gives you functions like keyPressed() and keyReleased(). Use those instead.

Secondly, what you probably want to do is create variables that keep track of whether a key is pressed or not. Something like this:

var wPressed = false;
var sPressed = false;
var aPressed = false;
var dPressed = false;

Then in the keyPressed()  function, you would set the corresponding variable to true, and in the keyReleased() function, you'd set it to false.

Finally, in the draw() function, you'd check each of the variable and do the right thing. Something like this:

if(dPressed){
   for (var i = 0; i < hillArray.length; i++) {
     hillArray[i].moveRight();
   }
}

(Side note: If you're moving all of the elements by the same distance, you might just want to use a single xOffset variable or something that you use, that way you don't have to loop over every item to move it individually.)

Shameless self promotion: I wrote a tutorial on user input (including the above approach) available here. It's for regular Processing, but all of the ideas are the same in Processing.js.


问:
Client error: (405) Method Not Allowed while trying to use Neo4j syntax in R
I'm trying to use Neo4j in RStudio for the first time. I'm just trying this tutorial https://github.com/nicolewhite/RNeo4j

But when I try a query like this one:

```<code>nicole = createNode(graph, "Person", name="Nicole", age=24)
</code>```

I got this error:

```<code>Client error: (405) Method Not Allowed
</code>```

Is there any way to solve this problem? Thank you in advance for your time.

答:
Your error can happen if you accidentally leave some information out of your startGraph() call.  Make sure you have /db/data/ on the end of your graph's url.  (If this isnt the case then please post your startGraph command you used).

with /db/data

```<code>library(RNeo4j)
graph  = startGraph("http://localhost:7474/db/data/")
nicole = createNode(graph, "Person", name="Nicole", age=24)
nicole
# Person
#
# $name
# [1] "Nicole"
#
# $age
# [1] 24
</code>```

without

```<code>graph  = startGraph("http://localhost:7474")
nicole = createNode(graph, "Person", name="Nicole", age=24)
Error: Client error: (405) Method Not Allowed
</code>```

Body:
I'm trying to use Neo4j in RStudio for the first time. I'm just trying this tutorial https://github.com/nicolewhite/RNeo4j

But when I try a query like this one:

nicole = createNode(graph, "Person", name="Nicole", age=24)

I got this error:

Client error: (405) Method Not Allowed

Is there any way to solve this problem? Thank you in advance for your time.

Body:
Your error can happen if you accidentally leave some information out of your startGraph() call.  Make sure you have /db/data/ on the end of your graph's url.  (If this isnt the case then please post your startGraph command you used).

with /db/data

library(RNeo4j)
graph  = startGraph("http://localhost:7474/db/data/")
nicole = createNode(graph, "Person", name="Nicole", age=24)
nicole
# Person
#
# $name
# [1] "Nicole"
#
# $age
# [1] 24

without

graph  = startGraph("http://localhost:7474")
nicole = createNode(graph, "Person", name="Nicole", age=24)
Error: Client error: (405) Method Not Allowed


问:
Change filter in Silverlight Pivot Viewer to use AND instead of OR
I need to modify the way the filter acts in the Silverlight Pivot viewer.

I have this filter:

Keywords:

x Keyword a

_ Keyword b

x Keyword c

_ Keyword d

_ Keyword e

The filter generates “Keyword a OR Keyword c”. What I need is “Keyword a AND Keyword c”.

Is that possible?

Any help is appreciated!

答:
What Poker Villain says is quite right but that doesn't mean the PivotViewer is not a solution for you.  I had a similar problem with a system I've been working on and managed to find a suitable way of making the PivotViewer play nice.  This will only work for JIT collections though since it relies on re-fetching the data.

Essentially the system I've been working on is a case management system.  Much of the data associated with a case is mutually exclusive and so fits the model of the PivotViewer but there is also the ability to add 'tags' to a case and like you suggest, often the user will want to combinational logic there.  Here's what I did to fix the problem.

First off,..you're gonna want a copy of Silverlight Spy.  Now in the explorer tab of SSpy, you can drill right down the Visual Tree and look at the guts of the PivotViewer.  Here's how mine looks...

You can see I've drilled right down into the control named 'PART_FacetPane'.  Below that there's a bunch of CustomAccordianItems.  Essentially, you just need to subclass the PivotViewer (that's why mine says PivotViewerEx) and override the OnApplyTemplate method.

In here you will be able to use GetTemplateChild or some other means to navigate the VisualTree and add another control yourself.  In my project, I used a simple tag cloud control I'd previously built.

What I do is handle the events of the tag cloud control and append querystring values to the URL used to build the CXML and filter the data based on these parameters.  It's not as fluid as being able to filter the data 'live' as it were but it's a solution for now.

It's probably worth mentioning that depending on your circumstances, you may need to add a final, randomly generated querystring value to the CXML URL so you don't get a cached copy of the data.

HTH, Stimul8d.


问:
Import Error : Calling python script from shell
I want to run my python script from a shell.

```<code>#! /usr/bin/python

import subprocess
import time

from path.to.my.function1 import function1
from path.to.my.function2 import function2

  #some code here

if __name__ == "__main__":
</code>```

From my shell command, I want to run it like this:

```<code>./myPythonScript.py
</code>```

The result is :

```<code>ImportError: No module named path.to.my.function1
</code>```

When I run it from Eclipse for example, I don't have any errors. I have some empty _ init _.py files in my directories.

I don't want to add

```<code>sys.path.append(0, /path/to/my/function1)
</code>```

because it needs to be easily exportable. Also I don't want to add my file path to the source folder of PYTHONPATH. It needs to be plug and play.

I don't know if i have a different compiler or I should modify my #! /usr/bin/python. Or could it be my PYTHONPATH ?

答: Use PYTHONPATH=/path/to/package/root where the package root is the directory above path

Body:
I want to run my python script from a shell.

#! /usr/bin/python

import subprocess
import time

from path.to.my.function1 import function1
from path.to.my.function2 import function2

  #some code here

if __name__ == "__main__":

From my shell command, I want to run it like this:

./myPythonScript.py

The result is :

ImportError: No module named path.to.my.function1

When I run it from Eclipse for example, I don't have any errors. I have some empty _ init _.py files in my directories.

I don't want to add

sys.path.append(0, /path/to/my/function1)

because it needs to be easily exportable. Also I don't want to add my file path to the source folder of PYTHONPATH. It needs to be plug and play.

I don't know if i have a different compiler or I should modify my #! /usr/bin/python. Or could it be my PYTHONPATH ?


问:
Cannot connect to the Docker daemon on macOS
I normally prefer to manage my apps on my OSX with brew

I am able to install docker, docker-compose and docker-machine

```<code>docker --version
Docker version 17.05.0-ce, build 89658be
docker-compose --version
docker-compose version 1.13.0, build unknown
docker-machine --version
docker-machine version 0.11.0, build 5b27455
</code>```

I did not download and run 'Docker for Mac' app.

However when I try to run

```<code>> docker run -d -p 80:80 --name webserver nginx
docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.
</code>```

I have already checked the sock file

```<code>ls -lah /var/run/docker.sock /var/tmp/docker.sock
ls: /var/run/docker.sock: No such file or directory
ls: /var/tmp/docker.sock: No such file or directory
</code>```

I have also tried this proposed solution: Mac OS X sudo docker Cannot connect to the Docker daemon. Is the docker daemon running on this host?

But I got this error message:

```<code>$ eval $(docker-machine env default)
Host does not exist: "default"
</code>```

Is it possible to get a docker service to run by command line tools?

答:
on OSX assure you have launched the Docker application before issuing

```<code>docker ps
</code>```

or docker build ... etc ... yes it seems strange and somewhat misleading that issuing

```<code>docker --version
</code>```

gives version even though the docker daemon is not running ... ditto for those other version cmds ...  I just encountered exactly the same symptoms ... this behavior on OSX is different from on linux

Body:
I normally prefer to manage my apps on my OSX with brew

I am able to install docker, docker-compose and docker-machine

docker --version
Docker version 17.05.0-ce, build 89658be
docker-compose --version
docker-compose version 1.13.0, build unknown
docker-machine --version
docker-machine version 0.11.0, build 5b27455

I did not download and run 'Docker for Mac' app.

However when I try to run

> docker run -d -p 80:80 --name webserver nginx
docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.

I have already checked the sock file

ls -lah /var/run/docker.sock /var/tmp/docker.sock
ls: /var/run/docker.sock: No such file or directory
ls: /var/tmp/docker.sock: No such file or directory

I have also tried this proposed solution: Mac OS X sudo docker Cannot connect to the Docker daemon. Is the docker daemon running on this host?

But I got this error message:

$ eval $(docker-machine env default)
Host does not exist: "default"

Is it possible to get a docker service to run by command line tools?

Body:
on OSX assure you have launched the Docker application before issuing

docker ps

or docker build ... etc ... yes it seems strange and somewhat misleading that issuing

docker --version

gives version even though the docker daemon is not running ... ditto for those other version cmds ...  I just encountered exactly the same symptoms ... this behavior on OSX is different from on linux


问:
How can i add latin5 character?
How can i add latin5 character?
Not clear on Oracle website

properties file

答:
Javadoc of Properties.load(InputStream inStream) says:

The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, are represented in keys and elements using Unicode escapes as defined in section 3.3 of The Java™ Language Specification.

That means, e.g.

All_Axes=Tüm Eksenler
```

<p>should be</p>

<pre class="lang-none prettyprint-override"><code>All_Axes=T\u00FCm Eksenler
</code>```

However, if you have control over how the property file is read, you can use Properties.load(Reader reader) instead. That way, you can control the character set and your file will work, as-is:

```<code>Properties props = new Properties();
try (Reader in = new InputStreamReader(new FileInputStream("/path/to/my.properties"),
                                       "ISO-8859-9"/*or "latin5"*/)) {
    props.load(in);
}
</code>```

Title: How can i add latin5 character?

Body:
Javadoc of Properties.load(InputStream inStream) says:

The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, are represented in keys and elements using Unicode escapes as defined in section 3.3 of The Java™ Language Specification.

That means, e.g.

All_Axes=Tüm Eksenler

should be

All_Axes=T\u00FCm Eksenler

However, if you have control over how the property file is read, you can use Properties.load(Reader reader) instead. That way, you can control the character set and your file will work, as-is:

Properties props = new Properties();
try (Reader in = new InputStreamReader(new FileInputStream("/path/to/my.properties"),
                                       "ISO-8859-9"/*or "latin5"*/)) {
    props.load(in);
}


问:
How to prevent a custom Mapbox callout automatically hide when zoom or panning on Map View
I follow this article Custom Call out

Every time when I zoom or panning on Mapbox View, the call out is automatically hide!

How to prevent this behavior?

Thanks

答:
You need to add two class variables to your CustomCalloutView class. Add these two lines before your init method:

```<code>var dismissesAutomatically: Bool = false
var isAnchoredToAnnotation: Bool = true
</code>```

This seems to fix the problem of the Callout being dismissed, and allows the callout to follow the annotation.

However, this runs into a new problem where every time the map is panned/zoomed, the callout seems to drop down about 10 pixels. I'm still trying to figure this out. I have opened another question here to see if anybody knows how to solve the issue.

Body:
You need to add two class variables to your CustomCalloutView class. Add these two lines before your init method:

var dismissesAutomatically: Bool = false
var isAnchoredToAnnotation: Bool = true

This seems to fix the problem of the Callout being dismissed, and allows the callout to follow the annotation.

However, this runs into a new problem where every time the map is panned/zoomed, the callout seems to drop down about 10 pixels. I'm still trying to figure this out. I have opened another question here to see if anybody knows how to solve the issue.


问:
ASP.Net: How to control div-style in backend?
I will control the style from a div-container from the backend (c#, code behind).

I will not use the runat="server"-tag, because the div-id is much used in javaScript.

How to do?

答:
Lets say you have a div that you want to use in code behind and in jQuery.

```<code><div id="myDiv" runat="server"></div>
</code>```

As we both know, when you view the source code of the page the id is changed by asp.net. So to access it using jQuery do this:

```<code>$("#<%=myDiv.ClientID %>")
</code>```

Body:
Lets say you have a div that you want to use in code behind and in jQuery.

<div id="myDiv" runat="server"></div>

As we both know, when you view the source code of the page the id is changed by asp.net. So to access it using jQuery do this:

$("#<%=myDiv.ClientID %>")


问:
Placing one layout above another layout in the bottom of the screen
I am trying to create a black view and placing it on top of another view as can be seen in the image below. So far so good.

But I can't figure out how to place the black view in the bottom of the screen? (still on top of the white pdf background...)

Here is my xml code so far:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/background_pdf"
        android:layout_below="@+id/background_pdf2"
        android:orientation="vertical"

        >
    <com.radaee.pdf.MLPDFViewer
        android:id="@+id/pdf"
        android:background="@android:color/white"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/background_pdf2"
        android:orientation="vertical"
        android:gravity="bottom"
        android:layout_gravity="bottom"
        >
        <View
            android:layout_width="match_parent"
            android:layout_height="75px"
            android:gravity="bottom"
            android:layout_gravity="bottom"
            android:background="@android:color/black"
             />

    </LinearLayout>

</RelativeLayout>
</code>```

If I add the following code android:layout_alignParentBottom="true" to              android:id="@+id/background_pdf2" my result is the following:

As you can see the black view is placed at the bottom but the main-view (white pdf) dissapears. I don't understand this...

答:
Give android:layout_alignParentBottom="true" to your Linear layout with id background_pdf2, like below

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

    <LinearLayout
        android:id="@+id/background_pdf"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <com.radaee.pdf.MLPDFViewer
            android:id="@+id/pdf"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"
            android:visibility="visible"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/background_pdf2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        android:gravity="bottom"
        android:orientation="vertical">

        <View
            android:layout_width="match_parent"
            android:layout_height="75px"
            android:layout_gravity="bottom"
            android:background="@android:color/black"
            android:gravity="bottom"
            />

    </LinearLayout>

</RelativeLayout>
</code>```

Body:
I am trying to create a black view and placing it on top of another view as can be seen in the image below. So far so good.

But I can't figure out how to place the black view in the bottom of the screen? (still on top of the white pdf background...)

Here is my xml code so far:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/background_pdf"
        android:layout_below="@+id/background_pdf2"
        android:orientation="vertical"

        >
    <com.radaee.pdf.MLPDFViewer
        android:id="@+id/pdf"
        android:background="@android:color/white"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/background_pdf2"
        android:orientation="vertical"
        android:gravity="bottom"
        android:layout_gravity="bottom"
        >
        <View
            android:layout_width="match_parent"
            android:layout_height="75px"
            android:gravity="bottom"
            android:layout_gravity="bottom"
            android:background="@android:color/black"
             />

    </LinearLayout>

</RelativeLayout>

If I add the following code android:layout_alignParentBottom="true" to              android:id="@+id/background_pdf2" my result is the following:

As you can see the black view is placed at the bottom but the main-view (white pdf) dissapears. I don't understand this...

Body:
Give android:layout_alignParentBottom="true" to your Linear layout with id background_pdf2, like below

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

    <LinearLayout
        android:id="@+id/background_pdf"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <com.radaee.pdf.MLPDFViewer
            android:id="@+id/pdf"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"
            android:visibility="visible"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/background_pdf2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        android:gravity="bottom"
        android:orientation="vertical">

        <View
            android:layout_width="match_parent"
            android:layout_height="75px"
            android:layout_gravity="bottom"
            android:background="@android:color/black"
            android:gravity="bottom"
            />

    </LinearLayout>

</RelativeLayout>


问:
Return a pointer to 2D array from a function - C++
So what I am trying to achieve is to return a pointer to a 2D array from the function so it could accessed in main(). I know there are some C++ libraries that does it for you like std::vector but I am trying to avoid dynamic memory allocation since I am working on embedded board (STM32) so I will stick to just normal pointers and arrays. (ALSO for some reason I can't use std::array in KEIL uVision, which is also why I am forced to work with pointers/arrays)

In addition, I understand that returning a pointer to a local array int arr[2][2] defined inside the function is not a good idea since it will no longer be valid after the function returns, which is why I creating test_array, declaring it inside a class and defining it in a function (acting as a global variable) so I assume this shouldn't be a problem. What do you guys think? However, doing it this way gives an error "Excess elements in scalar initializer"

```<code>#include <iostream>
#include "file.hpp"

int main() {

  myClass class_object;

  class_object.value = class_object.foo();

}
</code>```

```<code>//file.hpp

#include <stdio.h>

class myClass{

  int array[2][2];
  int (*foo())[2];
  int (*value)[2];

  int test_array[2][2];   //declaring here!

};
</code>```

```<code>//file.cpp

#include "file.hpp"

int (*myClass::foo())[2]{

    test_array[2][2]={ {10,20}, {30, 40} }; //defining here - ERROR!!

    int arr[2][2]= {
        {1, 10},
        {20, 30}
    };

return arr;

}
</code>```

答:
The immediate problem:

```<code>test_array[2][2]={ {10,20}, {30, 40} }; //defining here - ERROR!!
</code>```

is not defining. test_array was defined up in myClass. This is attempting to assign to a single element of test_array, specifically [2][2] which does not exist. What particularly offends the compiler is not the out of bounds access, but that ={ {10,20}, {30, 40} }; is trying to stuff an array into a single array element. The compiler is expecting a single number, so four numbers is definitely in excess.

Unfortunately I don't know of a good way to do what you want to do. You can initialize an array with an initializer list, but you can't assign from one.

So

```<code>class myClass{
public:

    myClass();
    void foo();

    int test_array[2][2];   //declaring here!
};

// you can do this:
myClass::myClass(): test_array{ {10,20}, {30, 40} }
{

}

void myClass::foo()
{
    // but you can't do this:
    test_array = { {10,20}, {30, 40} };
}
</code>```

Depending on what you do with test_array, initializing in the constructor may work for you. If you have to reset the array on every call to foo, perhaps an Automatic variable is a better fit for you

```<code>void myClass::foo()
{
    int temp_array[2][2] = { {10,20}, {30, 40} };

    // use temp_array

    // maybe copy temp_array to test_array with good ol' memcpy here if you
    // need to carry the state for some reason.
}
</code>```

To silence the elephant in the room and gain access to std::array, give this a try. Note: I've never done this. It could be an utter freaking disaster for all I know, so take it with a grain of salt.

Body:
So what I am trying to achieve is to return a pointer to a 2D array from the function so it could accessed in main(). I know there are some C++ libraries that does it for you like std::vector but I am trying to avoid dynamic memory allocation since I am working on embedded board (STM32) so I will stick to just normal pointers and arrays. (ALSO for some reason I can't use std::array in KEIL uVision, which is also why I am forced to work with pointers/arrays)

In addition, I understand that returning a pointer to a local array int arr[2][2] defined inside the function is not a good idea since it will no longer be valid after the function returns, which is why I creating test_array, declaring it inside a class and defining it in a function (acting as a global variable) so I assume this shouldn't be a problem. What do you guys think? However, doing it this way gives an error "Excess elements in scalar initializer"

#include <iostream>
#include "file.hpp"

int main() {

  myClass class_object;

  class_object.value = class_object.foo();

}

//file.hpp

#include <stdio.h>

class myClass{

  int array[2][2];
  int (*foo())[2];
  int (*value)[2];

  int test_array[2][2];   //declaring here!

};

//file.cpp

#include "file.hpp"

int (*myClass::foo())[2]{

    test_array[2][2]={ {10,20}, {30, 40} }; //defining here - ERROR!!

    int arr[2][2]= {
        {1, 10},
        {20, 30}
    };

return arr;

}

Body:
The immediate problem:

test_array[2][2]={ {10,20}, {30, 40} }; //defining here - ERROR!!

is not defining. test_array was defined up in myClass. This is attempting to assign to a single element of test_array, specifically [2][2] which does not exist. What particularly offends the compiler is not the out of bounds access, but that ={ {10,20}, {30, 40} }; is trying to stuff an array into a single array element. The compiler is expecting a single number, so four numbers is definitely in excess.

Unfortunately I don't know of a good way to do what you want to do. You can initialize an array with an initializer list, but you can't assign from one.

So

class myClass{
public:

    myClass();
    void foo();

    int test_array[2][2];   //declaring here!
};

// you can do this:
myClass::myClass(): test_array{ {10,20}, {30, 40} }
{

}

void myClass::foo()
{
    // but you can't do this:
    test_array = { {10,20}, {30, 40} };
}

Depending on what you do with test_array, initializing in the constructor may work for you. If you have to reset the array on every call to foo, perhaps an Automatic variable is a better fit for you

void myClass::foo()
{
    int temp_array[2][2] = { {10,20}, {30, 40} };

    // use temp_array

    // maybe copy temp_array to test_array with good ol' memcpy here if you
    // need to carry the state for some reason.
}

To silence the elephant in the room and gain access to std::array, give this a try. Note: I've never done this. It could be an utter freaking disaster for all I know, so take it with a grain of salt.


问:
How to convert all elements in an array to integer in JavaScript?
I am getting an array after some manipulation. I need to convert all array values as integers.

My sample code

```<code>var result_string = 'a,b,c,d|1,2,3,4';
result = result_string.split("|");
alpha = result[0];
count = result[1];
// console.log(alpha);
// console.log(count);
count_array = count.split(",");
</code>```

count_array now contains 1,2,3,4 but I need these value to be in integers.

I had used parseInt(count_array);, but it fails. JS considers each value in this array as string.

答:
Just loop the array and convert items:

```<code>for(var i=0, len=count_array.length; i<len; i++){
    count_array[i] = parseInt(count_array[i], 10);
}
</code>```

Don't forget the second argument for parseInt.

Body:
I am getting an array after some manipulation. I need to convert all array values as integers.

My sample code

var result_string = 'a,b,c,d|1,2,3,4';
result = result_string.split("|");
alpha = result[0];
count = result[1];
// console.log(alpha);
// console.log(count);
count_array = count.split(",");

count_array now contains 1,2,3,4 but I need these value to be in integers.

I had used parseInt(count_array);, but it fails. JS considers each value in this array as string.

Body:
Just loop the array and convert items:

for(var i=0, len=count_array.length; i<len; i++){
    count_array[i] = parseInt(count_array[i], 10);
}

Don't forget the second argument for parseInt.


问:
Keystone Error - You cannot update populated relationships
I have created a model

```<code>newProject = new Project.model({

    licensee:           req.query.licensee ? req.query.licensee : '',
    webUrl:             req.query.webUrl ? req.query.webUrl : '',
    appName:            req.query.appName ? req.query.appName : '',
    licenseDesktop:     req.query.cart.license.desktop.quantity ? req.query.cart.license.desktop.quantity : '',
    licenseDesktopLabel:req.query.cart.license.desktop.label ? req.query.cart.license.desktop.label : '',
    licenseWeb:         req.query.cart.license.web.quantity ? req.query.cart.license.web.quantity : '',
    licenseWebLabel:    req.query.cart.license.web.label ? req.query.cart.license.web.label : '',
    licenseApp:         req.query.cart.license.app.quantity ? req.query.cart.license.app.quantity : '',
    licenseAppLabel:    req.query.cart.license.app.label ? req.query.cart.license.app.label : '',
    collections:        req.query.cart.collections,
    pairs:              req.query.cart.pairs,
    fonts:              req.query.cart.fonts,
    downloadName:       downloadName,
    fileCreated:        false
});
</code>```

That seems correctly structured

```<code>{
    licensee: 'wer',
    webUrl: '',
    appName: '',
    mindate: 0,
    fileCreated: 'false',
    cost: 0,
    downloadName: 'wer-68201706172956354',
    fonts:
     [ { _id: 55945f1e67c1b9371e2b1241,
             __v: 0,
             createdAt: Wed Jul 01 2015 14:43:58 GMT-0700 (PDT),
             createdBy: 558c02e92e1093453a504a0e,
             description: '',
             slug: 'fort-thin',
             sortOrder: 14,
             title: 'Fort Thin',
             tokens: [],
             trackingAmount: '',
             trackingChange: '',
             typefaceName: 'Fort',
             updatedAt: Sun Jul 03 2016 10:28:35 GMT-0700 (PDT),
             updatedBy: 55df7e156bee0c7728109df9,
             weightName: 'Thin',
             price: 50,
             sell: true,
             style: 'Normal',
             weight: '100',
             otfFile: [Object],
             ttfFile: [Object],
             eotFile: [Object],
             woffFile: [Object],
             onHomepage: 'show' },
         { _id: 55c073bfe490ca292ae80814,
             __v: 0,
             createdAt: Tue Aug 04 2015 01:11:43 GMT-0700 (PDT),
             createdBy: 558c02e92e1093453a504a0e,
             description: '',
             slug: 'fort-thin-italic',
             sortOrder: 15,
             title: 'Fort Thin Italic',
             tokens: [],
             trackingAmount: '',
             trackingChange: '',
             typefaceName: 'Fort',
             updatedAt: Sun Jul 03 2016 10:28:56 GMT-0700 (PDT),
             updatedBy: 55df7e156bee0c7728109df9,
             weightName: 'Thin',
             price: 50,
             sell: true,
             style: 'Italic',
             weight: '100',
             otfFile: [Object],
             ttfFile: [Object],
             eotFile: [Object],
             woffFile: [Object],
             onHomepage: 'show' } ],
    pairs:
     [ { _id: 574dfc9a7c2cb9a32819d2b1,
             __v: 1,
             createdAt: Tue May 31 2016 14:05:30 GMT-0700 (PDT),
             createdBy: 55df7e156bee0c7728109df9,
             slug: 'fort-thins',
             sortOrder: 3,
             title: 'Fort Thins',
             titleStyle: 55945f1e67c1b9371e2b1241,
             updatedAt: Tue May 31 2016 14:08:21 GMT-0700 (PDT),
             updatedBy: 55df7e156bee0c7728109df9,
             price: 75,
             sell: true,
             fonts: [Object],
             autoStyle: true } ],
    collections: [],
    licenseAppLabel: '0 applications',
    licenseApp: '0',
    licenseWebLabel: '0 visitors / month',
    licenseWeb: '0',
    licenseDesktopLabel: 'Up to 3 computers',
    licenseDesktop: '1',
    _id: 5935f784c69f58a58003ff6c
}
</code>```

but when I run

```<code>var updater = newProject.getUpdateHandler(req, res, {

        errorMessage: 'There was an error creating your new project.'
    });

updater.process(req.body, {

    flashErrors: true,
    logErrors: true
}, function(err) {

    if (err) {

        console.log("There was an error updating your account. ");
    }
    next();
});
</code>```

I receive an error (Error: fieldTypes.relationship.updateItem() Error - You cannot update populated relationships.)

It seems to fire on newProject.getUpdateHandler. I can't seem to get around this error, I'm using keystone 4.0, does anyone have any idea?

答:
This seems to resolve the issue.. but I feel like it isn't the correct answer.</p>

```<code>newProject.save(function(err) {

    if (err) {

        logError(err, "There was an error updating your account. ");
    }
    next();
});
</code>```

Body:
I have created a model

newProject = new Project.model({

    licensee:           req.query.licensee ? req.query.licensee : '',
    webUrl:             req.query.webUrl ? req.query.webUrl : '',
    appName:            req.query.appName ? req.query.appName : '',
    licenseDesktop:     req.query.cart.license.desktop.quantity ? req.query.cart.license.desktop.quantity : '',
    licenseDesktopLabel:req.query.cart.license.desktop.label ? req.query.cart.license.desktop.label : '',
    licenseWeb:         req.query.cart.license.web.quantity ? req.query.cart.license.web.quantity : '',
    licenseWebLabel:    req.query.cart.license.web.label ? req.query.cart.license.web.label : '',
    licenseApp:         req.query.cart.license.app.quantity ? req.query.cart.license.app.quantity : '',
    licenseAppLabel:    req.query.cart.license.app.label ? req.query.cart.license.app.label : '',
    collections:        req.query.cart.collections,
    pairs:              req.query.cart.pairs,
    fonts:              req.query.cart.fonts,
    downloadName:       downloadName,
    fileCreated:        false
});

That seems correctly structured

{
    licensee: 'wer',
    webUrl: '',
    appName: '',
    mindate: 0,
    fileCreated: 'false',
    cost: 0,
    downloadName: 'wer-68201706172956354',
    fonts:
     [ { _id: 55945f1e67c1b9371e2b1241,
             __v: 0,
             createdAt: Wed Jul 01 2015 14:43:58 GMT-0700 (PDT),
             createdBy: 558c02e92e1093453a504a0e,
             description: '',
             slug: 'fort-thin',
             sortOrder: 14,
             title: 'Fort Thin',
             tokens: [],
             trackingAmount: '',
             trackingChange: '',
             typefaceName: 'Fort',
             updatedAt: Sun Jul 03 2016 10:28:35 GMT-0700 (PDT),
             updatedBy: 55df7e156bee0c7728109df9,
             weightName: 'Thin',
             price: 50,
             sell: true,
             style: 'Normal',
             weight: '100',
             otfFile: [Object],
             ttfFile: [Object],
             eotFile: [Object],
             woffFile: [Object],
             onHomepage: 'show' },
         { _id: 55c073bfe490ca292ae80814,
             __v: 0,
             createdAt: Tue Aug 04 2015 01:11:43 GMT-0700 (PDT),
             createdBy: 558c02e92e1093453a504a0e,
             description: '',
             slug: 'fort-thin-italic',
             sortOrder: 15,
             title: 'Fort Thin Italic',
             tokens: [],
             trackingAmount: '',
             trackingChange: '',
             typefaceName: 'Fort',
             updatedAt: Sun Jul 03 2016 10:28:56 GMT-0700 (PDT),
             updatedBy: 55df7e156bee0c7728109df9,
             weightName: 'Thin',
             price: 50,
             sell: true,
             style: 'Italic',
             weight: '100',
             otfFile: [Object],
             ttfFile: [Object],
             eotFile: [Object],
             woffFile: [Object],
             onHomepage: 'show' } ],
    pairs:
     [ { _id: 574dfc9a7c2cb9a32819d2b1,
             __v: 1,
             createdAt: Tue May 31 2016 14:05:30 GMT-0700 (PDT),
             createdBy: 55df7e156bee0c7728109df9,
             slug: 'fort-thins',
             sortOrder: 3,
             title: 'Fort Thins',
             titleStyle: 55945f1e67c1b9371e2b1241,
             updatedAt: Tue May 31 2016 14:08:21 GMT-0700 (PDT),
             updatedBy: 55df7e156bee0c7728109df9,
             price: 75,
             sell: true,
             fonts: [Object],
             autoStyle: true } ],
    collections: [],
    licenseAppLabel: '0 applications',
    licenseApp: '0',
    licenseWebLabel: '0 visitors / month',
    licenseWeb: '0',
    licenseDesktopLabel: 'Up to 3 computers',
    licenseDesktop: '1',
    _id: 5935f784c69f58a58003ff6c
}

but when I run

var updater = newProject.getUpdateHandler(req, res, {

        errorMessage: 'There was an error creating your new project.'
    });

updater.process(req.body, {

    flashErrors: true,
    logErrors: true
}, function(err) {

    if (err) {

        console.log("There was an error updating your account. ");
    }
    next();
});

I receive an error (Error: fieldTypes.relationship.updateItem() Error - You cannot update populated relationships.)

It seems to fire on newProject.getUpdateHandler. I can't seem to get around this error, I'm using keystone 4.0, does anyone have any idea?

Body:
This seems to resolve the issue.. but I feel like it isn't the correct answer.

newProject.save(function(err) {

    if (err) {

        logError(err, "There was an error updating your account. ");
    }
    next();
});