问:
How should I start designing an AI algorithm for an artillery warfare game?
Here's the background... in my free time I'm designing an artillery warfare game called Staker (inspired by the old BASIC games Tank Wars and Scorched Earth) and I'm programming it in MATLAB. Your first thought might be "Why MATLAB? There are plenty of other languages/software packages that are better for game design." And you would be right. However, I'm a dork and I'm interested in learning the nuts and bolts of how you would design a game from the ground up, so I don't necessarily want to use anything with prefab modules. Also, I've used MATLAB for years and I like the challenge of doing things with it that others haven't really tried to do.

Now to the problem at hand: I want to incorporate AI so that the player can go up against the computer. I've only just started thinking about how to design the algorithm to choose an azimuth angle, elevation angle, and projectile velocity to hit a target, and then adjust them each turn. I feel like maybe I've been overthinking the problem and trying to make the AI too complex at the outset, so I thought I'd pause and ask the community here for ideas about how they would design an algorithm.

Some specific questions:

Are there specific references for AI design that you would suggest I check out?

Would you design the AI players to vary in difficulty in a continuous manner (a difficulty of 0 (easy) to 1 (hard), all still using the same general algorithm) or would you design specific algorithms for a discrete number of AI players (like an easy enemy that fires in random directions or a hard enemy that is able to account for the effects of wind)?

What sorts of mathematical algorithms (pseudocode description) would you start with?

Some additional info: the model I use to simulate projectile motion incorporates fluid drag and the effect of wind. The "fluid" can be air or water. In air, the air density (and thus effect of drag) varies with height above the ground based on some simple atmospheric models. In water, the drag is so great that the projectile usually requires additional thrust. In other words, the projectile can be affected by forces other than just gravity.

答:
In a real artillery situation all these factors would be handled either with formulas or simply brute-force simulation:  Fire an electronic shell, apply all relevant forces and see where it lands.  Adjust and try again until the electronic shell hits the target.  Now you have your numbers to send to the gun.

Given the complexity of the situation I doubt there is any answer better than the brute-force one.  While you could precalculate a table of expected drag effects vs velocity I can't see it being worthwhile.

Of course a game where the AI dropped the first shell on your head every time wouldn't be interesting.  Once you know the correct values you'll have to make the AI a lousy shot.  Apply a random factor to the shot and then walk to towards the target--move it say 30+random(140)% towards the true target each time it shoots.

Edit:

I do agree with BCS's notion of improving it as time goes on.  I said that but then changed my mind on how to write a bunch of it and then ended up forgetting to put it back in.  The tougher it's supposed to be the smaller the random component should be.

OwnerDisplayName: gnovice

LastEditorDisplayName: gnovice

OwnerDisplayName: Loren Pechtel

LastEditorDisplayName: Loren Pechtel


来源: stackexchange

问:
AWK command to compare two files, report row of first file if not found in second file, report row of second file if found
I have a basic level of unix understanding, so this problem might be easy.

I have been trying to use the "awk" command to compare two files (two columns in each file separated by a tab), with the ultimate goal of having a file with all the rows of file 1, but if the row is found in file 2, I would like the row of file 1 to be replaced with that same row from file 2.

```<code>File 1:
Supercontig_12.1,420    0
Supercontig_12.1,421    0
Supercontig_12.1,422    0
Supercontig_12.1,423    0
…(rows continue in numerical order)
Supercontig_12.1,428    0
Supercontig_12.1,429    0
Supercontig_12.1,430    0

File 2 (not in numerical order):
Supercontig_12.1,422    0.6
Supercontig_12.1,426    0.333333
Supercontig_12.1,428    0.5
Supercontig_12.1,429    0
</code>```

desired output

```<code>Output:
Supercontig_12.1,420    0
Supercontig_12.1,421    0
Supercontig_12.1,422    0.6
Supercontig_12.1,423    0.333333
…
Supercontig_12.1,428    0.5
Supercontig_12.1,429    0
Supercontig_12.1,430    0
</code>```

I have been using the following command, but all it does is add the rows of file 2 to the end of the rows of file 1, much like the "cat" command.

```<code>$ awk -F"\t" 'NR==FNR{a[$1]} $1 in a{print $1 "\t" $2}' file1.txt file2.txt > output.txt
</code>```

I know I am making an array the size of file 1, which is what I would like to do, but I'm not selecting for the file 2 data within that array.  Any help would be most welcome.  Thanks in advance.

Andy

答:
When all lines have the same length (not Supercontig_12.1,420 and Supercontig_12.1,4202) you can grep and cut:
You can get the first field of file2 with

```<code>cut -f1 file2.txt
</code>```

The output of this command can be used as if it is a file with process substitution <(some_command).

To remove these lines from file1.txt

```<code>grep -vf <(cut -f1 file2.txt) file1.txt
</code>```

Put this together with file2 and sort the result

```<code>cat file2.txt <(grep -vf <(cut -f1 file2.txt) file1.txt) |sort
</code>```

What is wrong with your awk?

```<code>awk -F"\t" 'NR==FNR{a[$1]} $1 in a{print $1 "\t" $2}' file1.txt file2.txt
</code>```

When parsing file1.txt, you do not want to print anything. Use next. And store $0:

```<code>awk -F"\t" 'NR==FNR{a[$1]=$0; next} $1 in a{print $1 "\t" $2}' file1.txt file2.txt
</code>```

When $1 from file2.txt is found in a, replace the value (don't print yet)

```<code>awk -F"\t" 'NR==FNR{a[$1]=$0; next} $1 in a{a[$1]=$0}' file1.txt file2.txt
</code>```

When everything is parsed, print content of array.

```<code>awk -F"\t" 'NR==FNR{a[$1]=$0; next} $1 in a{a[$1]=$0} END { for (i in a) print a[i] } ' file1.txt file2.txt
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a basic level of unix understanding, so this problem might be easy.

I have been trying to use the "awk" command to compare two files (two columns in each file separated by a tab), with the ultimate goal of having a file with all the rows of file 1, but if the row is found in file 2, I would like the row of file 1 to be replaced with that same row from file 2.

File 1:
Supercontig_12.1,420    0
Supercontig_12.1,421    0
Supercontig_12.1,422    0
Supercontig_12.1,423    0
…(rows continue in numerical order)
Supercontig_12.1,428    0
Supercontig_12.1,429    0
Supercontig_12.1,430    0

File 2 (not in numerical order):
Supercontig_12.1,422    0.6
Supercontig_12.1,426    0.333333
Supercontig_12.1,428    0.5
Supercontig_12.1,429    0

desired output

Output:
Supercontig_12.1,420    0
Supercontig_12.1,421    0
Supercontig_12.1,422    0.6
Supercontig_12.1,423    0.333333
…
Supercontig_12.1,428    0.5
Supercontig_12.1,429    0
Supercontig_12.1,430    0

I have been using the following command, but all it does is add the rows of file 2 to the end of the rows of file 1, much like the "cat" command.

$ awk -F"\t" 'NR==FNR{a[$1]} $1 in a{print $1 "\t" $2}' file1.txt file2.txt > output.txt

I know I am making an array the size of file 1, which is what I would like to do, but I'm not selecting for the file 2 data within that array.  Any help would be most welcome.  Thanks in advance.

Andy

Body:
When all lines have the same length (not Supercontig_12.1,420 and Supercontig_12.1,4202) you can grep and cut:
You can get the first field of file2 with

cut -f1 file2.txt

The output of this command can be used as if it is a file with process substitution <(some_command).

To remove these lines from file1.txt

grep -vf <(cut -f1 file2.txt) file1.txt

Put this together with file2 and sort the result

cat file2.txt <(grep -vf <(cut -f1 file2.txt) file1.txt) |sort

What is wrong with your awk?

awk -F"\t" 'NR==FNR{a[$1]} $1 in a{print $1 "\t" $2}' file1.txt file2.txt

When parsing file1.txt, you do not want to print anything. Use next. And store $0:

awk -F"\t" 'NR==FNR{a[$1]=$0; next} $1 in a{print $1 "\t" $2}' file1.txt file2.txt

When $1 from file2.txt is found in a, replace the value (don't print yet)

awk -F"\t" 'NR==FNR{a[$1]=$0; next} $1 in a{a[$1]=$0}' file1.txt file2.txt

When everything is parsed, print content of array.

awk -F"\t" 'NR==FNR{a[$1]=$0; next} $1 in a{a[$1]=$0} END { for (i in a) print a[i] } ' file1.txt file2.txt


问:
Loading JavaScript files selectively in Django
I have Post model for a blog app in Django. It has a field named body. In posts, I may use Latex so I need to use MathJax.js. In some posts, I add code snippet, so I use highlight.js. In some I use both, in some I use none of them.

I want to load the relevant javascript depending on the body field of the Post model (similar to THIS). How can I make the relevant .js file(s) to load automatically?

I know that I can add an indicator field like hasLatex (True, False) or hasCode (True, False). But I'm lazy, I want Post.body to be automatically scanned and only relevant js files loaded.

答:
Set something in your context or use a template context processor. For example I load code that handles forms if there is a form key is my context. For something I want on almost every page I put a no_something in my context to disable it. This is done by putting a conditional around the tag in your base template. If the variable is not there or is false it won't show.

What I also do is put my static files in lists inside of my context. JavaScript is in context['js'] and css in context['css']. Those are looped through in my header. I can implement get_context_data in a base class, and all the views that extend from that will have the javascript and css files.


问:
How do I incorporate new local changes into an existing Bitbucket repository?
I have a Bitbucket repository where I keep my projects. I committed all the projects at once using the following commands:

```<code>git init
git remote add origin (paste link from step 2)
git add .
git commit –a –m “First commit”
git push origin master
</code>```

Now suppose that I want to add a new project to the repository. After I copy the project in the folder, which commands should I use to include this new project?

答:
I'd recommend keeping different repos for each project, but to each their own... If you're ready to push your new project, do:</p>

```<code>$ git add -A && git commit -m "Your Message"
$ git push origin master
</code>```

Body:
I have a Bitbucket repository where I keep my projects. I committed all the projects at once using the following commands:

git init
git remote add origin (paste link from step 2)
git add .
git commit –a –m “First commit”
git push origin master

Now suppose that I want to add a new project to the repository. After I copy the project in the folder, which commands should I use to include this new project?

Body:
I'd recommend keeping different repos for each project, but to each their own... If you're ready to push your new project, do:

$ git add -A && git commit -m "Your Message"
$ git push origin master


问:
MySQL -> RESTful API
Is there anything out there that given a MySQL database can create RESTful webservice endpoints? I'm ok with it doing stupid basic things to start with, as long as the data model is tunable after.

For bonus points it could understand foreign keys to join data, and create searching endpoints for indexed columns.

答:
Check out restSQL. It's an open-source, ultra-lightweight persistence layer. It's a got enough for basic CRUD and a little bit of basic filtering support.

It has built in support for MySQL and PostgreSQL, but is architected to be extended to other RDBMSes. It runs in standard JEE containers, e.g. Tomcat, or is bundled as a Docker container.

You can take it for a spin using the sandboxed instance and explore the docs at http://restsql.org.

ContentLicense: CC BY-SA 2.5

Title: MySQL -> RESTful API


问:
change alignment of last row of multiple div inside container
I have a container div that contains many divs inside it as indicated in the below.

.result-container {
  max-width: 650px;
  margin: 0 auto;
  background: blue;
  border: 1px solid;
  position: relative;
  text-align: center;
}

.result-container .item {
  display: inline-block;
  max-width: 200px;
  min-width: 200px;
  background: green;
  border: 1px solid;
}

.result-container .item img {
  display: block;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="result-container">
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>

</div></code>```

the parent div has text-align: center to make the child divs centered inside the parent. but i'm not satisfied with the look of the last row

is there is any way by which i can make the result as the below image

and if i used display: table is it considered good practice
appreciate your help.

答:
Since your single DIVs actually have a fixed width (max-width and  min-width are set to 200px), you can use a fixed width on the container,  distribute the difference between the three DIV widths and the container width to the margins and apply text-align: left; to it:

```<code>.result-container {
  width: 614px;
  padding: 0 18px;
  text-align: left;
  etc..
}
</code>```

.result-container {
  width: 614px;
  padding: 0 18px;
  margin: 0 auto;
  background: blue;
  border: 1px solid;
  position: relative;
  text-align: left;
}

.result-container .item {
  display: inline-block;
  max-width: 200px;
  min-width: 200px;
  background: green;
  border: 1px solid;
}

.result-container .item img {
  display: block;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="result-container">
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>

</div></code>```

Body:
I have a container div that contains many divs inside it as indicated in the below.

.result-container {
  max-width: 650px;
  margin: 0 auto;
  background: blue;
  border: 1px solid;
  position: relative;
  text-align: center;
}

.result-container .item {
  display: inline-block;
  max-width: 200px;
  min-width: 200px;
  background: green;
  border: 1px solid;
}

.result-container .item img {
  display: block;
  margin: 0 auto;
}

the parent div has text-align: center to make the child divs centered inside the parent. but i'm not satisfied with the look of the last row

is there is any way by which i can make the result as the below image

and if i used display: table is it considered good practice
appreciate your help.

Body:
Since your single DIVs actually have a fixed width (max-width and  min-width are set to 200px), you can use a fixed width on the container,  distribute the difference between the three DIV widths and the container width to the margins and apply text-align: left; to it:

.result-container {
  width: 614px;
  padding: 0 18px;
  text-align: left;
  etc..
}

.result-container {
  width: 614px;
  padding: 0 18px;
  margin: 0 auto;
  background: blue;
  border: 1px solid;
  position: relative;
  text-align: left;
}

.result-container .item {
  display: inline-block;
  max-width: 200px;
  min-width: 200px;
  background: green;
  border: 1px solid;
}

.result-container .item img {
  display: block;
  margin: 0 auto;
}

<div class="result-container">
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>
  <div class="item">
    <img src="http://devimg.com/150x150" width="150" height="150">

  </div>

</div>


问:
Infinite Loop and Rotation of Array
so I have this list,

List: [0, 0, 1, 0, 1];

And I need made a algorithm with a for to show all the list (list[i]).

When I am in first array position, I can do list[i-2] and list[i-1], with this I can see the elements of the last position and the position before the last position.

Exemple : list[0] = 0; list[i-1] = list[4] = 1; list[i-2] = list[3] = 0; so I can go to the last position and start from there.

But when I do, list[i+1] in the last position I got a IndexError: list index out of range from the terminal.

My question is: If I was in the last positions and I want again come to  from the first one and keep doing the for loop, to see infinite times all array elements from all positions, How I can do it?
If the size of my array it is 5, and I am in second position(list[1]) in the loop and want do list[i + 11], how can I put this representing this, list[2]?

I am trying make this on python.

答:
You can implement such an "infinite iterator" as follows:

```<code>def infinite_iterator(lst):
    i = 0
    def next():
        global i
        while True:
            result = lst[i % len(lst)]
            i += 1
            yield result
    return next()
</code>```

and use it with:

```<code>lst = [1,2,3,4,5]
iter = infinite_iterator(lst)

for i in range(17): # 17 is just an example, you can put any number or `while True:`
    print(next(iter))
</code>```

Title: Infinite Loop and Rotation of Array

Body:
You can implement such an "infinite iterator" as follows:

def infinite_iterator(lst):
    i = 0
    def next():
        global i
        while True:
            result = lst[i % len(lst)]
            i += 1
            yield result
    return next()

and use it with:

lst = [1,2,3,4,5]
iter = infinite_iterator(lst)

for i in range(17): # 17 is just an example, you can put any number or `while True:`
    print(next(iter))


问:
Trouble in obtaining correct geometric transformation of cartesian coordinates
I am working in python and i have previous (x_prev,y_prev) = (1.5, 3) coordinate and current (x,y) = (2, 3.2)coordinate and angle difference between them and i want the next coordinate to be at a certain distance d with the same orientation as the current (x,y)coordinate. I have tried using the rotation and translation formula but it fails to give the proper answer. here is the code so far what i tried.

```<code>d = 0.5
angle = np.arctan2((y - y_prev), (x - x_prev))
x_ = x * np.cos(angle) - y * np.sin(angle) + (d * np.sinc(angle_/2)* np.cos(angle/2))
y_ = x * np.sin(angle) + y * np.cos(angle) + (d * np.sinc(angle_/2)* np.sin(angle/2))
</code>```

the expected coordinate is approximately (x_,y_) = (2.5, 3.6) with the same orientation as the current but it results in wrong coordinate so is there anything i am missing.

Thanks in advance

答:
I partly agree with @ImportanceOfBeingErnest that your question is a geometrical one. However, I'm adding an answer because numpy lets you avoid all that trigonometric work that you are trying to do in the first place.

What you want is to find the point (x_new,y_new) based on (x_prev,y_prev) and (x_now,y_now) such that the three points lie on the same line and the distance between (x_prev,y_prev) and (x_new,y_new) is a preset d.

You don't need trigonometry if you can work with proper two-dimensional vectors. You can normalize the vector (x_now,y_now) - (x_prev,y_prev) to get an orientation vector of the line along which you need to move from (x_prev,y_prev) in order to end up at (x_new,y_new). Numpy lets you handle this elegantly:

```<code>import numpy as np

x_prev,y_prev = (1.5, 3)
x_now,y_now = (2, 3.2)
d = 0.5

# use 2d arrays for elegant vector operations
# of course we can directly define these from coordinates if we want to
p_prev = np.array([x_prev,y_prev])
p_now = np.array([x_now,y_now])

# compute the unit direction vector for p_new - p_prev
t = p_now - p_prev
t /= np.linalg.norm(t) # use Euclidean norm by default

# p_new is simple now:
p_new = p_prev + d*t

print(p_prev)
print(p_now)
print(p_new)
</code>```

The above results in (x_new,y_new)=(1.96423835,3.18569534). Your points are actually such that (x_now,y_now) is almost at 0.5 distance from (x_prev,y_prev), so the resulting vector is hardly different from the original one. But anyway, the above procedure will always give you a new point which is at the same angle from (x_prev,y_prev) as (x_now,y_now) but at the fixed distance.

Body:
I am working in python and i have previous (x_prev,y_prev) = (1.5, 3) coordinate and current (x,y) = (2, 3.2)coordinate and angle difference between them and i want the next coordinate to be at a certain distance d with the same orientation as the current (x,y)coordinate. I have tried using the rotation and translation formula but it fails to give the proper answer. here is the code so far what i tried.

d = 0.5
angle = np.arctan2((y - y_prev), (x - x_prev))
x_ = x * np.cos(angle) - y * np.sin(angle) + (d * np.sinc(angle_/2)* np.cos(angle/2))
y_ = x * np.sin(angle) + y * np.cos(angle) + (d * np.sinc(angle_/2)* np.sin(angle/2))

the expected coordinate is approximately (x_,y_) = (2.5, 3.6) with the same orientation as the current but it results in wrong coordinate so is there anything i am missing.

Thanks in advance

Body:
I partly agree with @ImportanceOfBeingErnest that your question is a geometrical one. However, I'm adding an answer because numpy lets you avoid all that trigonometric work that you are trying to do in the first place.

What you want is to find the point (x_new,y_new) based on (x_prev,y_prev) and (x_now,y_now) such that the three points lie on the same line and the distance between (x_prev,y_prev) and (x_new,y_new) is a preset d.

You don't need trigonometry if you can work with proper two-dimensional vectors. You can normalize the vector (x_now,y_now) - (x_prev,y_prev) to get an orientation vector of the line along which you need to move from (x_prev,y_prev) in order to end up at (x_new,y_new). Numpy lets you handle this elegantly:

import numpy as np

x_prev,y_prev = (1.5, 3)
x_now,y_now = (2, 3.2)
d = 0.5

# use 2d arrays for elegant vector operations
# of course we can directly define these from coordinates if we want to
p_prev = np.array([x_prev,y_prev])
p_now = np.array([x_now,y_now])

# compute the unit direction vector for p_new - p_prev
t = p_now - p_prev
t /= np.linalg.norm(t) # use Euclidean norm by default

# p_new is simple now:
p_new = p_prev + d*t

print(p_prev)
print(p_now)
print(p_new)

The above results in (x_new,y_new)=(1.96423835,3.18569534). Your points are actually such that (x_now,y_now) is almost at 0.5 distance from (x_prev,y_prev), so the resulting vector is hardly different from the original one. But anyway, the above procedure will always give you a new point which is at the same angle from (x_prev,y_prev) as (x_now,y_now) but at the fixed distance.


问:
Showing only part of an article when listing all articles using Big5 encoding
I'm writing a website with some articles for a Chinese audience. On the page that lists the articles I would like it to list the title and a small proportion of the article. However, the articles are encoded in a mixture of different Big5 encodings. Don't ask me why - that's what I got - so I can't guarantee the number of bytes each character takes to encode.

How can I then trim down the string to show only a small proportion of the article, without chopping off the bytes needed to encode a character?

答: If you're certain that you won't have any characters outside of the BMP then you can convert the text to UCS-2 and then slice on an even boundary.</p>

OwnerDisplayName: Ageis

OwnerDisplayName: Ignacio Vazquez-Abrams


问:
Ending a while loop with a predetermined input in eclipse
I'm writing a small script that will take miles input by user and gallons input and show the number of trips and the miles per gallon of the total trips taken. Here's what I have.

```<code>public class FuelEfficiency
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        double totalMiles = 0;
        double totalGallons = 0;
        int tripCounter = 0;

        while (tripCounter > -1)
        {
            System.out.print("Enter miles driven: "); //Want to say "Enter miles driven or 'q' to quit: "
            double milesDriven = input.nextDouble();
            totalMiles = totalMiles + milesDriven;

            System.out.print("Enter gallons of gas consumed: "); // Similar to the above.
            double gasConsumed = input.nextDouble();
            totalGallons = totalGallons + gasConsumed;

            tripCounter = tripCounter + 1;

            double milesPerGallon = totalMiles / totalGallons;

        System.out.printf("%nYour number of trips is: %s%n", tripCounter);
        System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", milesPerGallon);
        }

    }

}
</code>```

As it is right now, the loop will continue indefinitely. What I want to do is be able to accept a predefined input (like 'quit' or 'q') to end the loop and report the previous trip and milePerGallon without making a new equation or adding another trip. (I have also thought of trying to continue the loop until a value of '0' is entered. I suspect I would be using milesDriven and gasConsumed to loop that way. But whenever I tried that it would still take those values into account when it runs the new milePerGallon.)

Any tips on what I should use to do this?

答:
What I want to do is be able to accept a predefined input (like 'quit'
  or 'q') to end the loop and report the previous trip and milePerGallon
  without making a new equation or adding another trip.

Firstly, I wanted to state that even though I can understand why you've tripCounter > -1 as your while loop conditions, it doesn't make much sense as you're always incrementing tripCounter hence the condition will never become false. With that in mind we can simplify it to while(true) then basically break whenever the user decides to quit.

Solution:

Considering what you've mentioned, we could use a Stack to store the records after each iteration and basically when a user decides to quit then we can simply pop the last record and display it.

```<code>Scanner input = new Scanner(System.in);

double totalMiles = 0;
double totalGallons = 0;
int tripCounter = 0;
Stack<String> trips = new Stack<>();

while (true){
     System.out.print("Enter miles driven: "); //Want to say "Enter miles driven or 'q' to quit: "
     String milesInput = input.next();
     if(milesInput.equalsIgnoreCase("q") || milesInput.equalsIgnoreCase("quit")){
          if(trips.empty()) {
              System.out.println("no data entered");
              break;
          }

          String[] previousRecord  = trips.pop().split(" ");
          System.out.printf("%nYour number of trips is: %s%n", previousRecord[0]);
          System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", previousRecord[1]);
          break;
     }
     double milesDriven = Double.parseDouble(milesInput); // consider adding extra checks before converting
     totalMiles = totalMiles + milesDriven;

     System.out.print("Enter gallons of gas consumed: "); // Similar to the above.
     String gallonsInput = input.next();
     if(gallonsInput.equalsIgnoreCase("q") || gallonsInput.equalsIgnoreCase("quit")){
         if(trips.empty()) {
             System.out.println("no data entered");
             break;
         }
         String[] previousRecord  = trips.pop().split(" ");
         System.out.printf("%nYour number of trips is: %s%n", previousRecord[0]);
         System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", previousRecord[1]);
         break;
     }
     double gasConsumed = Double.parseDouble(gallonsInput);
     totalGallons = totalGallons + gasConsumed;

     tripCounter = tripCounter + 1;

     double milesPerGallon = totalMiles / totalGallons;
     trips.push(tripCounter + " " + milesPerGallon);

     System.out.printf("%nYour number of trips is: %s%n", tripCounter);
     System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", milesPerGallon);
}
</code>```

What I have added on top of your code:

Stack data structure

split(String regex)

equalsIgnoreCase()

Double.parseDouble()

Break statement

Body:
I'm writing a small script that will take miles input by user and gallons input and show the number of trips and the miles per gallon of the total trips taken. Here's what I have.

public class FuelEfficiency
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        double totalMiles = 0;
        double totalGallons = 0;
        int tripCounter = 0;

        while (tripCounter > -1)
        {
            System.out.print("Enter miles driven: "); //Want to say "Enter miles driven or 'q' to quit: "
            double milesDriven = input.nextDouble();
            totalMiles = totalMiles + milesDriven;

            System.out.print("Enter gallons of gas consumed: "); // Similar to the above.
            double gasConsumed = input.nextDouble();
            totalGallons = totalGallons + gasConsumed;

            tripCounter = tripCounter + 1;

            double milesPerGallon = totalMiles / totalGallons;

        System.out.printf("%nYour number of trips is: %s%n", tripCounter);
        System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", milesPerGallon);
        }

    }

}

As it is right now, the loop will continue indefinitely. What I want to do is be able to accept a predefined input (like 'quit' or 'q') to end the loop and report the previous trip and milePerGallon without making a new equation or adding another trip. (I have also thought of trying to continue the loop until a value of '0' is entered. I suspect I would be using milesDriven and gasConsumed to loop that way. But whenever I tried that it would still take those values into account when it runs the new milePerGallon.)

Any tips on what I should use to do this?

Body:
What I want to do is be able to accept a predefined input (like 'quit'
  or 'q') to end the loop and report the previous trip and milePerGallon
  without making a new equation or adding another trip.

Firstly, I wanted to state that even though I can understand why you've tripCounter > -1 as your while loop conditions, it doesn't make much sense as you're always incrementing tripCounter hence the condition will never become false. With that in mind we can simplify it to while(true) then basically break whenever the user decides to quit.

Solution:

Considering what you've mentioned, we could use a Stack to store the records after each iteration and basically when a user decides to quit then we can simply pop the last record and display it.

Scanner input = new Scanner(System.in);

double totalMiles = 0;
double totalGallons = 0;
int tripCounter = 0;
Stack<String> trips = new Stack<>();

while (true){
     System.out.print("Enter miles driven: "); //Want to say "Enter miles driven or 'q' to quit: "
     String milesInput = input.next();
     if(milesInput.equalsIgnoreCase("q") || milesInput.equalsIgnoreCase("quit")){
          if(trips.empty()) {
              System.out.println("no data entered");
              break;
          }

          String[] previousRecord  = trips.pop().split(" ");
          System.out.printf("%nYour number of trips is: %s%n", previousRecord[0]);
          System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", previousRecord[1]);
          break;
     }
     double milesDriven = Double.parseDouble(milesInput); // consider adding extra checks before converting
     totalMiles = totalMiles + milesDriven;

     System.out.print("Enter gallons of gas consumed: "); // Similar to the above.
     String gallonsInput = input.next();
     if(gallonsInput.equalsIgnoreCase("q") || gallonsInput.equalsIgnoreCase("quit")){
         if(trips.empty()) {
             System.out.println("no data entered");
             break;
         }
         String[] previousRecord  = trips.pop().split(" ");
         System.out.printf("%nYour number of trips is: %s%n", previousRecord[0]);
         System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", previousRecord[1]);
         break;
     }
     double gasConsumed = Double.parseDouble(gallonsInput);
     totalGallons = totalGallons + gasConsumed;

     tripCounter = tripCounter + 1;

     double milesPerGallon = totalMiles / totalGallons;
     trips.push(tripCounter + " " + milesPerGallon);

     System.out.printf("%nYour number of trips is: %s%n", tripCounter);
     System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", milesPerGallon);
}

What I have added on top of your code:

Stack data structure

split(String regex)

equalsIgnoreCase()

Double.parseDouble()

Break statement


问:
Program to find numbers with odd no of divisors
Given 2 integers L and R, you are expected to find the number of integers between L and R that have odd number of divisors.

Input Format :

First line contains a single integer T
, the number of test cases. Each of the next T lines contains two space separated integers Li and Ri, depicting the parameters of the ith test case.

Constraints

1≤ T ≤ 10000

1≤ L ≤ R ≤ 10^18

```<code>#include <stdio.h>

int main(void)
{
    int t;
    long int cnt,countj;
    scanf("%d",&t);
    long long int l[t], r[t];
    int i=0;
    for(i=0;i<t;i++){
        scanf("%d%d",&l[i],&r[i]);
        }

    int div[t];
    for(i=0;i<t;i++){
        //count[i]=0;
        cnt=0;
        for(int j=l[i]+1;j<r[i];j++){
            countj=0;
            for(int k=1;k<=j/2;k++){
                if(j%k==0)
                   countj++;
            }
            if ((countj%2)==0)
            cnt++;
        }
        printf("%ld\n",cnt);
    }
    return 0;
}
</code>```

This program takes too long to execute, especially for bigger numbers, how can it be optimized ?
And it doesent pass all the test cases, what may be error in the code?

答: You are saying that you want to count the numbers that have odd numbers of divisors, but you are counting, the even ones.</p>

Body:
Given 2 integers L and R, you are expected to find the number of integers between L and R that have odd number of divisors.

Input Format :

First line contains a single integer T
, the number of test cases. Each of the next T lines contains two space separated integers Li and Ri, depicting the parameters of the ith test case.

Constraints

1≤ T ≤ 10000

1≤ L ≤ R ≤ 10^18

#include <stdio.h>

int main(void)
{
    int t;
    long int cnt,countj;
    scanf("%d",&t);
    long long int l[t], r[t];
    int i=0;
    for(i=0;i<t;i++){
        scanf("%d%d",&l[i],&r[i]);
        }

    int div[t];
    for(i=0;i<t;i++){
        //count[i]=0;
        cnt=0;
        for(int j=l[i]+1;j<r[i];j++){
            countj=0;
            for(int k=1;k<=j/2;k++){
                if(j%k==0)
                   countj++;
            }
            if ((countj%2)==0)
            cnt++;
        }
        printf("%ld\n",cnt);
    }
    return 0;
}

This program takes too long to execute, especially for bigger numbers, how can it be optimized ?
And it doesent pass all the test cases, what may be error in the code?


问:
How to check airplane seat reservation in C++
I am new to C++ and I am trying to reserve a seat in airplane with an two dimensional array; everything work except it won't check if the seat is already taken.

```<code>for example:
 1  A B C D
 2  A B C D
 3  A B C D
 4  A B C D
 5  A B C D
</code>```

if the user choose row 1 letter A then it will be:

```<code> 1  X B C D
 2  A B C D
 3  A B C D
 4  A B C D
 5  A B C D
</code>```

Then if the user choose row 1 letter A again it should display message says the seat is already taken.This is my code

```<code>void reserveSeat(char seatChart[ROW][COLUM]){

    int row;
    char colum;

    cout<<"Enter the row number with colum letter ex(0 A): ";
    cin>>row>>colum;
    colum = toupper(colum);

    for(int r = 0; r<ROW;r++){

        for(int c = 0; c<COLUM;c++){

            if(seatChart[row][c] == colum){

                //check if the seat is taken
                if( seatChart[row][c] == 'X'){

                    cout<<"seat is already taken\n\n";
                }else
                    seatChart[row][c] = 'X';
            }
        }//end of inner for loop
    }//end of outer for loop
}
</code>```

答:
The second if can never be true because you are already checking if it's something else. You can probably get away with just removing the first if statement and just checking if it's an 'X' or not.

```<code>        if(seatChart[row][c] == colum){

            //check if the seat is taken
            if( seatChart[row][c] == 'X'){
</code>```

Body:
I am new to C++ and I am trying to reserve a seat in airplane with an two dimensional array; everything work except it won't check if the seat is already taken.

for example:
 1  A B C D
 2  A B C D
 3  A B C D
 4  A B C D
 5  A B C D

if the user choose row 1 letter A then it will be:

 1  X B C D
 2  A B C D
 3  A B C D
 4  A B C D
 5  A B C D

Then if the user choose row 1 letter A again it should display message says the seat is already taken.This is my code

void reserveSeat(char seatChart[ROW][COLUM]){

    int row;
    char colum;

    cout<<"Enter the row number with colum letter ex(0 A): ";
    cin>>row>>colum;
    colum = toupper(colum);

    for(int r = 0; r<ROW;r++){

        for(int c = 0; c<COLUM;c++){

            if(seatChart[row][c] == colum){

                //check if the seat is taken
                if( seatChart[row][c] == 'X'){

                    cout<<"seat is already taken\n\n";
                }else
                    seatChart[row][c] = 'X';
            }
        }//end of inner for loop
    }//end of outer for loop
}

Body:
The second if can never be true because you are already checking if it's something else. You can probably get away with just removing the first if statement and just checking if it's an 'X' or not.

        if(seatChart[row][c] == colum){

            //check if the seat is taken
            if( seatChart[row][c] == 'X'){


问:
Order of carriage return and new line feed
Is it important to have the correct order of carriage return then new line feed? For text editors does it matter in what order they appear?

For example instead of

```<code>\r\n
</code>```

this

```<code>\n\r
</code>```

Seems like Jeff has allready writen up a very nice Blog Post  on the subject.

答:
There are numerous newline converters out there.

E.g. this one. They do most of the work for you.

Body:
Is it important to have the correct order of carriage return then new line feed? For text editors does it matter in what order they appear?

For example instead of

\r\n

this

\n\r

Seems like Jeff has allready writen up a very nice Blog Post  on the subject.


问:
Pass row_array() to Codeigniter view
I have this controller code:

```<code>10 $rowArr=$this->m_model->getItemData($itemID);
11 $rowArr=['code'=>'123','desc'=>'456','price'=>'789'];
12 $this->load->view('item_v',$rowArr);
</code>```

In my model I have:

```<code>$result=$this->db
  ->select('code','desc','price')
  ->where('itemID',$itemID)
  ->get('catalog')
  ->row_array();
return $result;
</code>```

When I run it I get the expected 123, 456, 789 displayed in the 'code', 'desc' and 'price' columns because the second definition of $rowArr gets sent. But when I comment out line 11, allowing the first (intended) definition to take over - I get undefined variable errors for all three in the view.

In my view I'm using:

```<code><div>
   <?php
        echo "<div>";
        echo "code: ".$code."<br>";
        echo "desc: ".$desc."<br>";
        echo "price: ".$price."<br>";
        echo "</div>";
   ?>
</div>
</code>```

Since it works OK using the literal array I know the problem must be in the model - no doubt where I attempt to create an array from the db query object. The CI docs seem clear that using the row_array() method should turn the db object into a php array for me. I've tried every variation I could find or think of but nothing works. Can anyone tell me what mistake I'm making? Thanks in advance.

答:
As you can see from the comments, thanks to @DFriend and @shaggy I found the problem but not where I was so certain it would be. To open the page described as the view, above, the user clicks the tsEditButt in this code:

```<code>$('.tsEditButt').click(function() {
    var itemID=$(this).closest('.item').attr('id');
    var base_url=$('#hiddenDiv').text(); //'http://localhost/CID17/';
    var url=base_url+'controller_a/index/'+itemID,_blank;
    window.open(url);
</code>```

I had somehow deleted part of the line:

```<code> var url=base_url+'controller_a/index/'+itemID,_blank;
</code>```

So it was opening the new page but the itemID was missing and was never passed to the model. As @DFriend said, "If the model is returning null then there is no record where itemID=$itemID". After 2 days of going cross-eyed I think I'll remember this one.

Title: Pass row_array() to Codeigniter view

Body:
I have this controller code:

10 $rowArr=$this->m_model->getItemData($itemID);
11 $rowArr=['code'=>'123','desc'=>'456','price'=>'789'];
12 $this->load->view('item_v',$rowArr);

In my model I have:

$result=$this->db
  ->select('code','desc','price')
  ->where('itemID',$itemID)
  ->get('catalog')
  ->row_array();
return $result;

When I run it I get the expected 123, 456, 789 displayed in the 'code', 'desc' and 'price' columns because the second definition of $rowArr gets sent. But when I comment out line 11, allowing the first (intended) definition to take over - I get undefined variable errors for all three in the view.

In my view I'm using:

   <?php
        echo "
";
        echo "code: ".$code."
";
        echo "desc: ".$desc."
";
        echo "price: ".$price."
";
        echo "
";
   ?>

Since it works OK using the literal array I know the problem must be in the model - no doubt where I attempt to create an array from the db query object. The CI docs seem clear that using the row_array() method should turn the db object into a php array for me. I've tried every variation I could find or think of but nothing works. Can anyone tell me what mistake I'm making? Thanks in advance.

Body:
As you can see from the comments, thanks to @DFriend and @shaggy I found the problem but not where I was so certain it would be. To open the page described as the view, above, the user clicks the tsEditButt in this code:

$('.tsEditButt').click(function() {
    var itemID=$(this).closest('.item').attr('id');
    var base_url=$('#hiddenDiv').text(); //'http://localhost/CID17/';
    var url=base_url+'controller_a/index/'+itemID,_blank;
    window.open(url);

I had somehow deleted part of the line:

 var url=base_url+'controller_a/index/'+itemID,_blank;

So it was opening the new page but the itemID was missing and was never passed to the model. As @DFriend said, "If the model is returning null then there is no record where itemID=$itemID". After 2 days of going cross-eyed I think I'll remember this one.


问:
Abaqus CAE: Importing Deformed Geometry Issue
I am running a simple bending analysis on a tube. I am interested in the deformed geometry, which I wish to import for further analysis. The method I'm using is:
Import >> Part >> *.odb file >> Import Deformed Geometry >> Choose Step and Frame

However, on doing so I notice that the imported part is no different from my original part (it is the same!). Although my analysis does show noticeable deformation.

Any input on where I'm going wrong. Thanks a bunch!

答:
To import the geometry for futher analysis. In CAE select:
"File" >> "Import" >> "Part"
In the popup box select the ODB file type
and then select the results file you want to use the deformed geometry from.
The next popup box allows you to select "import defomred configuration" and lets you select which frame / step you require.
I hope this helps.</p>


问:
What is the difference between image classification and image recognition (in the context of face recognition)?
A classic example of image classification problem is to classify handwritten digits using softmax linear regression model for MNIST data. Let us suppose there is a facial database of 10 subjects and 10 images for each subject. This will be a problem of image (face) recognition.

So considering the difference in the feature space of digits and faces, by analogy can I assume each subject as each digit and images of subjects as examples of handwritten digits and apply the classification algorithm to perform recognition. Check this link

Please help me understand this?

答:
In this context there is no difference. Just two data sets for a classification problem: handwritten digit images with digits as labels or face images with subjects as labels.

However normally face recognition tasks involve finding all faces in one picture, not labeling them


问:
Arranging different height divs around a circle with a radius
So, I have been trying to create a large number of divs (we can call them bars) and have them rotated and positioned so that it creates a circle in the center. I am bad at explaining so here is an example where all bars have the same width and height.

JSFiddle Here:

Everything looks good here. However, the problem arises when I change the height of the bars. JSFiddle Here:

I assume my troubles arise from my positioning and rotating functions are messed up or the nature of the absolute positioning. Here is an example of my js for the second JSFiddle.

```<code>var $bars = [];
var viz = document.getElementById('viz');

function create(num) {
    for(var i = 0; i < num; i++) {
        var a = document.createElement('div');
        a.classList.add('bar');
        viz.appendChild(a);
        $bars.push($(a));
    }
}

create(256);

$(document).ready(function(){
    var step = Math.PI * 2 / $bars.length;
    var radius = 200;
    var angle = 0;

    for (var i = 0; i < $bars.length; i++) {
        var x = Math.round(radius * Math.cos(angle));
        var y = Math.round(radius * Math.sin(angle));
        $bars[i].css('left', x + 'px');
        $bars[i].css('top', y + 'px');
        $bars[i].css('height', i + 1);
        var rot = 90 + (1.4025 * i);
        $bars[i].css('transform', 'rotate(' + rot + 'deg)');
        angle += step;
    }
});
</code>```

Is there a way to maintain the circle radius with all divs/bars even if the heights are different from my example?
(I am relatively new a js so please forgive my poor code)

答:
The code is performing as intended, you are changing the height as you go around the circle.  However, if you update the height to solid number then it will perform properly:

```<code>$bars[i].css('height', 20);
</code>```

https://jsfiddle.net/rzt5L0sh/1/

Body:
So, I have been trying to create a large number of divs (we can call them bars) and have them rotated and positioned so that it creates a circle in the center. I am bad at explaining so here is an example where all bars have the same width and height.

JSFiddle Here:

Everything looks good here. However, the problem arises when I change the height of the bars. JSFiddle Here:

I assume my troubles arise from my positioning and rotating functions are messed up or the nature of the absolute positioning. Here is an example of my js for the second JSFiddle.

var $bars = [];
var viz = document.getElementById('viz');

function create(num) {
    for(var i = 0; i < num; i++) {
        var a = document.createElement('div');
        a.classList.add('bar');
        viz.appendChild(a);
        $bars.push($(a));
    }
}

create(256);

$(document).ready(function(){
    var step = Math.PI * 2 / $bars.length;
    var radius = 200;
    var angle = 0;

    for (var i = 0; i < $bars.length; i++) {
        var x = Math.round(radius * Math.cos(angle));
        var y = Math.round(radius * Math.sin(angle));
        $bars[i].css('left', x + 'px');
        $bars[i].css('top', y + 'px');
        $bars[i].css('height', i + 1);
        var rot = 90 + (1.4025 * i);
        $bars[i].css('transform', 'rotate(' + rot + 'deg)');
        angle += step;
    }
});

Is there a way to maintain the circle radius with all divs/bars even if the heights are different from my example?
(I am relatively new a js so please forgive my poor code)

Body:
The code is performing as intended, you are changing the height as you go around the circle.  However, if you update the height to solid number then it will perform properly:

$bars[i].css('height', 20);

https://jsfiddle.net/rzt5L0sh/1/


问:
Is ChefSpec in chef really usable compared to testing with Kitchen
I had covered recipe code with ChefSpec and after that I have integration testing with Kitchen. To me at the end ChefSpec is not really usable just one extra think to maintain because:

When I'm writing Java with TDD/BDD I see real benefits from using this approach- lots of smaller classes, DI integration, modularity, less bugs.

However with Chef and ChefSpec to me is only usable default generated spec the helps me with some compile and syntax errors.

How to use ChefSpec with Chef to see the same benefits like TDD/BDD in Java for example.

答: ChefSpec is a faster way to run recipes because its using Chef Solo. In that way you are able to provide different node attributes, assert behaviors that's are OS specific without running Kitchen.</p>


问:
C# Duplication of generic parameter in class declaration
I'm playing with C# generics and interfaces today and trying implement classic definition of Graphs. Here is my best attempt (for exercise only):

```<code>interface IVertex
{
    string Name { get; set; }
}

interface IEdge<V> where V : IVertex
{
    V From { get; set; }
    V To { get; set; }
}

interface IGraph<V, E> where E: IEdge<V> where V: IVertex
{
    IList<V> Vertices { get; }
    IList<E> Edges { get; }
}

class Vertex : IVertex
{
    public string Name { get; set; }

    public Vertex(string name)
    {
        Name = name;
    }
}

class Edge<V> : IEdge<V> where V: IVertex
{
    public V From { get; set; }
    public V To { get; set; }

    public Edge(V from, V to)
    {
        From = from;
        To = to;
    }
}

class Graph<V, E> : IGraph<V, E> where E: IEdge<V> where V : IVertex
{
    public IList<V> Vertices { get; } = new List<V>();
    public IList<E> Edges { get; } = new List<E>();
}
</code>```

But I think, that I'm doing something wrong, because in following usage:

```<code>var a = new Vertex("A");
var b = new Vertex("B");
var c = new Vertex("C");

var x = new Edge<Vertex>(a, b);
var y = new Edge<Vertex>(b, c);
var z = new Edge<Vertex>(c, a);

var graph = new Graph<Vertex, Edge<Vertex>>()
{
    Vertices = { a, b, c },
    Edges = {x, y, z}
};
</code>```

I need to specify the generic argument Vertex (at line new Graph<Vertex, Edge<Vertex>>()) twice...

答:
Without more context, it's not clear what your constraints and requirements are. But, depending on what you're trying to accomplish, the syntax you currently have may be required, to ensure that your IList<E> is declared appropriately.

It is also possible that you don't require the Graph class to have the exact IEdge<V> type. If so, then you could declare it like this:

```<code>class Graph<V> : IGraph<V, IEdge<V>> where V : IVertex
{
    public IList<V> Vertices { get; } = new List<V>();
    public IList<IEdge<V>> Edges { get; } = new List<IEdge<V>>();
}
</code>```

In this approach, you will not be able e.g. to assign Edges to a variable of type IList<E> where E is some type other than IEdge<V>. For example, this wouldn't work, while it would work if you require both types to be specified:

```<code>IList<Edge<Vertex>> list = graph.Edges;
</code>```

It all depends on how you actually want to use these types.

Body:
I'm playing with C# generics and interfaces today and trying implement classic definition of Graphs. Here is my best attempt (for exercise only):

interface IVertex
{
    string Name { get; set; }
}

interface IEdge<V> where V : IVertex
{
    V From { get; set; }
    V To { get; set; }
}

interface IGraph<V, E> where E: IEdge<V> where V: IVertex
{
    IList<V> Vertices { get; }
    IList<E> Edges { get; }
}

class Vertex : IVertex
{
    public string Name { get; set; }

    public Vertex(string name)
    {
        Name = name;
    }
}

class Edge<V> : IEdge<V> where V: IVertex
{
    public V From { get; set; }
    public V To { get; set; }

    public Edge(V from, V to)
    {
        From = from;
        To = to;
    }
}

class Graph<V, E> : IGraph<V, E> where E: IEdge<V> where V : IVertex
{
    public IList<V> Vertices { get; } = new List<V>();
    public IList<E> Edges { get; } = new List<E>();
}

But I think, that I'm doing something wrong, because in following usage:

var a = new Vertex("A");
var b = new Vertex("B");
var c = new Vertex("C");

var x = new Edge<Vertex>(a, b);
var y = new Edge<Vertex>(b, c);
var z = new Edge<Vertex>(c, a);

var graph = new Graph<Vertex, Edge<Vertex>>()
{
    Vertices = { a, b, c },
    Edges = {x, y, z}
};

I need to specify the generic argument Vertex (at line new Graph<Vertex, Edge<Vertex>>()) twice...

Body:
Without more context, it's not clear what your constraints and requirements are. But, depending on what you're trying to accomplish, the syntax you currently have may be required, to ensure that your IList<E> is declared appropriately.

It is also possible that you don't require the Graph class to have the exact IEdge<V> type. If so, then you could declare it like this:

class Graph<V> : IGraph<V, IEdge<V>> where V : IVertex
{
    public IList<V> Vertices { get; } = new List<V>();
    public IList<IEdge<V>> Edges { get; } = new List<IEdge<V>>();
}

In this approach, you will not be able e.g. to assign Edges to a variable of type IList<E> where E is some type other than IEdge<V>. For example, this wouldn't work, while it would work if you require both types to be specified:

IList<Edge<Vertex>> list = graph.Edges;

It all depends on how you actually want to use these types.


问:
Javascript String to Regex without Escaping
I have a question regarding regular expressions in nodejs/javascript.

What I am trying to achieve is to convert a regex (loaded from a database as a string) without any escaping to a RegExp object in js.

```<code>var regex       = /Apache\/([0-9\.]+) \(([a-zA-Z ]+)\) (.+)/;
var regexString = '/Apache\/([0-9\.]+) \(([a-zA-Z ]+)\) (.+)/';

var str = 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18';

var match = str.match(regex);
var match2 = str.match(new RegExp(regexString));
console.log(match);
console.log(match2);
</code>```

That's what I tried so far. But as you can see it won't match if the string gets escaped...
My output:

```<code>[ 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18',
  '2.2.9',
  'Debian',
  'PHP/5.2.6-1+lenny18',
  index: 0,
  input: 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18' ]
null
</code>```

Am I missing something simple? If not any suggestions for me?
Thanks

答:
The two bounding / are not supposed to be present when used in the string argument of new RegExp().

Also, when you would write the string as a literal (which I understand is not really your case, since you get the string from the DB), you need to escape any backslashes in that literal to \\:

var regex       = /Apache\/([0-9\.]+) \(([a-zA-Z ]+)\) (.+)/;
var regexString = 'Apache\/([0-9\.]+) \\(([a-zA-Z ]+)\\) (.+)';

var str = 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18';

var match = str.match(regex);
var match2 = str.match(new RegExp(regexString));
console.log(match);
console.log(match2);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have a question regarding regular expressions in nodejs/javascript.

What I am trying to achieve is to convert a regex (loaded from a database as a string) without any escaping to a RegExp object in js.

var regex       = /Apache\/([0-9\.]+) \(([a-zA-Z ]+)\) (.+)/;
var regexString = '/Apache\/([0-9\.]+) \(([a-zA-Z ]+)\) (.+)/';

var str = 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18';

var match = str.match(regex);
var match2 = str.match(new RegExp(regexString));
console.log(match);
console.log(match2);

That's what I tried so far. But as you can see it won't match if the string gets escaped...
My output:

[ 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18',
  '2.2.9',
  'Debian',
  'PHP/5.2.6-1+lenny18',
  index: 0,
  input: 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18' ]
null

Am I missing something simple? If not any suggestions for me?
Thanks

Body:
The two bounding / are not supposed to be present when used in the string argument of new RegExp().

Also, when you would write the string as a literal (which I understand is not really your case, since you get the string from the DB), you need to escape any backslashes in that literal to \\:

var regex       = /Apache\/([0-9\.]+) \(([a-zA-Z ]+)\) (.+)/;
var regexString = 'Apache\/([0-9\.]+) \\(([a-zA-Z ]+)\\) (.+)';

var str = 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18';

var match = str.match(regex);
var match2 = str.match(new RegExp(regexString));
console.log(match);
console.log(match2);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Working with REST, SQL, foreign keys, and nested resources
I'm struggling to understand how to handle nested resources in REST.

For example, if I have a table called cities, and another table called companies that has a foreign key constraint(a company exists in a city), then when someone GETs a city, should I also send a list of all companies in that city? If so, if they do a PUT on a specific city(cities/55) and they have the nested collection of companies present, do I also update the nested companies?

Or how about a delete? Do I cascade delete all companies in a city, or just change the city they are in to a null value temporarily...

At a certain point, the SQL I am doing on the nested resources could get pretty unwieldy, imagine doing a PUT on cities/55 and have changed the list of companies associated with the city(or even a worker, in a company, in a city, all in a PUT on a city...)

If this doesn't make sense, let me know and I'll try to clarify. I've looked around and haven't found any answers regarding this exactly.

答: You could look at restSQL for inspiration. It can model resources as two level hierarchies. Write ops can be on the parents or children, but not both.</p>


问:
Realm Results To Array In Kii
am using Realm as a local store. I am currently trying to get the objects found in a realm Query (RLMResults) and store them in an array as part of a KiiObject.

I have very little experience using NSArray or NSDictionary to create an array of JSON to store in the KiiObject. As the number of objects in the realm search will vary i thought this might work:

```<code>for (RLMObject *object in currentEventResults) {
    [array addObject:object];
}
</code>```

and then add the array to my KiiObject.

```<code> [object setObject:array forKey:@"arryofObj"];
</code>```

But the array has no objects in it when saved to Kii, but i know currentEventResults has 45 objects.

答:
After a night of tinkering came up with this:

```<code>for (RLMObject *object in currentEvent) {

     NSDictionary *dictOBJ =
@{@"eventID":[object objectForKeyedSubscript:@"eventID"],
@"longValue":[object objectForKeyedSubscript:@"longValue"],
@"latValue":[object objectForKeyedSubscript:@"latValue"],
@"pingTime":[object objectForKeyedSubscript:@"pingTime"]};

            [mutableArray addObject:dictOBJ];
        }
</code>```

I then :

```<code>NSArray *arrayToSave = [mutableArray copy];
</code>```

I then save the array to my Kii Object.

It works well. If there is a better solution please post it.

Title: Realm Results To Array In Kii

Body:
am using Realm as a local store. I am currently trying to get the objects found in a realm Query (RLMResults) and store them in an array as part of a KiiObject.

I have very little experience using NSArray or NSDictionary to create an array of JSON to store in the KiiObject. As the number of objects in the realm search will vary i thought this might work:

for (RLMObject *object in currentEventResults) {
    [array addObject:object];
}

and then add the array to my KiiObject.

 [object setObject:array forKey:@"arryofObj"];

But the array has no objects in it when saved to Kii, but i know currentEventResults has 45 objects.

Body:
After a night of tinkering came up with this:

for (RLMObject *object in currentEvent) {

     NSDictionary *dictOBJ =
@{@"eventID":[object objectForKeyedSubscript:@"eventID"],
@"longValue":[object objectForKeyedSubscript:@"longValue"],
@"latValue":[object objectForKeyedSubscript:@"latValue"],
@"pingTime":[object objectForKeyedSubscript:@"pingTime"]};

            [mutableArray addObject:dictOBJ];
        }

I then :

NSArray *arrayToSave = [mutableArray copy];

I then save the array to my Kii Object.

It works well. If there is a better solution please post it.


问:
How do I upgrade my PHP 4.0 login script to PHP 5.6?
my script below worked perfect on PHP 4.0 but my ISP upgraded to PHP 5.6 and now there seems to be something wrong (it does not connect to mySQL, etc), any help is appreciated

Many thanks

```<code><?php
$userdb="var1";
$pass="var2";
$database="var3";

mysql_connect("sql.servername.com",$userdb,$pass);
@mysql_select_db($database) or die ( header('location: status4.htm') );
$match = "select id from USER_ACCOUNTS where username = '$username' and password = '$password'";
$qry = mysql_query($match)
or die ( header('location: status.htm?status=9') );
$num_rows = mysql_num_rows($qry);

// Valid Username and Password
if ($num_rows > 0) {
$qry = "SELECT * FROM USER_ACCOUNTS WHERE username like '%" . $username . "%'";
$res = mysql_query($qry);
$output='';
while($row = mysql_fetch_assoc($res)){
// loop through all returned results
$output .= '&viewUsername=' . $row['viewUsername'] . '&viewPassword=' . $row['viewPassword'] . '&username=' . $row['username'] . '&password=' . $row['password'] . '&name=' . $row['name'] . '&title=' . $row['title'] . '&email=' . $row['email'] . '&admin=' . $row['admin'] . '&file=' . $row['file'] . '&file2=' . $row['file2'] . '&file3=' . $row['file3'] . '&file4=' . $row['file4'];
echo "&status=1";
echo $output;
}
}
?>
</code>```

Here is the mySQL 4.0 Table

```<code>id  viewUsername    viewPassword    username    password    name    title   email   admin   file    file2   file3   file4

1                                   user1       pass123     USER1   Manager email1   1      file1   file2   file3   file4
</code>```

答:
I would guess that on your old version you had register_globals enabled, thus in $username and $password you were getting directly what was posted from a form, which is no longer happening.

The quick solution would be to add at the start of the php code:

$username = $_REQUEST['username'];
$password = $_REQUEST['password'];

That being said, every line in your code screams bad practices and possible vulnerabilities. I would highly recommend you getting some help for a complete makeover if you are using that in a productive website.

Body:
my script below worked perfect on PHP 4.0 but my ISP upgraded to PHP 5.6 and now there seems to be something wrong (it does not connect to mySQL, etc), any help is appreciated

Many thanks

<?php
$userdb="var1";
$pass="var2";
$database="var3";

mysql_connect("sql.servername.com",$userdb,$pass);
@mysql_select_db($database) or die ( header('location: status4.htm') );
$match = "select id from USER_ACCOUNTS where username = '$username' and password = '$password'";
$qry = mysql_query($match)
or die ( header('location: status.htm?status=9') );
$num_rows = mysql_num_rows($qry);

// Valid Username and Password
if ($num_rows > 0) {
$qry = "SELECT * FROM USER_ACCOUNTS WHERE username like '%" . $username . "%'";
$res = mysql_query($qry);
$output='';
while($row = mysql_fetch_assoc($res)){
// loop through all returned results
$output .= '&viewUsername=' . $row['viewUsername'] . '&viewPassword=' . $row['viewPassword'] . '&username=' . $row['username'] . '&password=' . $row['password'] . '&name=' . $row['name'] . '&title=' . $row['title'] . '&email=' . $row['email'] . '&admin=' . $row['admin'] . '&file=' . $row['file'] . '&file2=' . $row['file2'] . '&file3=' . $row['file3'] . '&file4=' . $row['file4'];
echo "&status=1";
echo $output;
}
}
?>

Here is the mySQL 4.0 Table

id  viewUsername    viewPassword    username    password    name    title   email   admin   file    file2   file3   file4

1                                   user1       pass123     USER1   Manager email1   1      file1   file2   file3   file4


问:
Primefaces Calendar with Converter doesn't update correctly upon ajax "valueChange" event
I want my p:calendar to work both by clicking on a date in the calendar popup, as well as by editing the date directly in the text input field.

This works fine:

```<code>        <p:calendar value="#{myBackingBean.date}">
            <p:ajax event="valueChange" listener="#{myBackingBean.updateDate()}" />
            <p:ajax event="dateSelect" listener="#{myBackingBean.selectDate()}" />
        </p:calendar>
</code>```

However, as soon as I add a converter (see below), the new date is no longer set for "valueChange" events (when the date is edited by keyboard in the text field), even though the new date is converted correctly, but the date that is set in the backing bean is the old value, not the new one I edited in the text field:

```<code>        <p:calendar value="#{myBackingBean.date}">
            <f:converter converterId="myLocalDateConverter"/>
            <p:ajax event="valueChange" listener="#{myBackingBean.updateDate()}" />
            <p:ajax event="dateSelect" listener="#{myBackingBean.selectDate()}" />
        </p:calendar>
</code>```

How can I get this to work together?

答:
Refer this.  https://www.javacodegeeks.com/2015/06/utilizing-the-java-8-date-time-api-with-jsf-and-java-ee-7.html

Its is using converter attribute of Calendar to implement the custom converter. This example is specifically for Java 8 Date API. You can write your code accordingly.

Body:
I want my p:calendar to work both by clicking on a date in the calendar popup, as well as by editing the date directly in the text input field.

This works fine:

However, as soon as I add a converter (see below), the new date is no longer set for "valueChange" events (when the date is edited by keyboard in the text field), even though the new date is converted correctly, but the date that is set in the backing bean is the old value, not the new one I edited in the text field:

            <f:converter converterId="myLocalDateConverter"/>

How can I get this to work together?


问:
How to count Firebase child items that match a certain criteria
For each user account I'm trying to count how many events they have today.

My data is structured as follows:

```<code>accounts -
{
 "-KaxcGWx1-a8s7dhsjhsd" : {
 "name" : "Bill",
 "events" : [ {
  "event" : "-KdHscYor4mA--ubIHBj"
 }, {
  "event" : "-KdKsJBdHimgPPQQ6bcA"
 } ],
 },
 "-KaxcGWx1-rA2anjKI4h" : {
 "name" : "Bob",
 "username" : "Bob"
 "events" : [ {
  "event" : "-KdHscYor4mA--ubIHBj"
 }]
 }
}

events -
{
 "-KdHscYor4mA--ubIHBj" : {
   "dateCreated" : "Fri Feb 17 2017 23:37:32 GMT+0000 (GMT)",
   "eventDate" : "2017-04-01",
   "name" : "Event 1",
},
 "-KdKsJBdHimgPPQQ6bcA" : {
   "dateCreated" : "Fri Feb 17 2017 23:37:32 GMT+0000 (GMT)",
   "eventDate" : "2017-04-01",
   "name" : "Event 2",
 }
 }
</code>```

So given that both events are for today. I would expect to Bill to have two and Bob to have one.

The code I have tried is:

```<code>var todayDate = '2017-04-01';
var ref = firebase.database().ref('accounts/');
ref.once('value', function (snapshot) {
    //Foreach user account
    var eventCount = 0;
    snapshot.forEach(function (account) {
        var ref = firebase.database().ref('accounts/' + account.key);
        ref.child('events').once('value', function (eventSnapshot) {
            //Foreach event
            eventSnapshot.forEach(function (child) {
                firebase.database().ref('events/' + child.val().event).once('value', function (event) {
                        if (eventDate === todayDate) {
                            console.log(account.val().name, 'has an event today -', event.val().name);
                            eventCount++;
                        }
                });
            });
        });
        console.log(account.val().name, 'total events -', eventCount);
    });
});
</code>```

However, the result I'm getting in the console is:

```<code>Bill total events - 0
Bob total events - 0
Bill has an event today Event 1
Bill has an event today Event 2
Bob has an event today Event 2
</code>```

答:
With your current structure you will have problems when scaling because you would need to retrieve all the users and then all time events for that user and check each one of the dates. You could do it much simpler by changing your events data structure a bit.

```<code>events: {
  eventId1: {
   date: '20170401',
   attendingAccount:{
     accountId1: true,
     accountId2: true,
   }
  },
  eventId2: {...}
}
</code>```

If you just save the accountId of the users that are attending the event like above you would just need to run something like the following:

```<code>let attendingCount = {};

firebase.database().ref('events').orderByChild('date').equalTo(today).once(snap => {
    let events = snap.val();

    if (events){
        Object.keys(events).forEach(eventId => {
            Object.keys(events[eventId].attendingAccounts).forEach(accountId => {
                if (!attendingCount[accountId]){
                    attendingCount[accountId] = 0;
                }
                attendingCount[accountId]++;
            });
        });
    }
});
</code>```

This would result in the object attendingCount having the count for each one of the accountIds.

```<code>attendingCount: {
   accountId1: 2,
   accountId2: 5,
   ...
}
</code>```

Body:
For each user account I'm trying to count how many events they have today.

My data is structured as follows:

accounts -
{
 "-KaxcGWx1-a8s7dhsjhsd" : {
 "name" : "Bill",
 "events" : [ {
  "event" : "-KdHscYor4mA--ubIHBj"
 }, {
  "event" : "-KdKsJBdHimgPPQQ6bcA"
 } ],
 },
 "-KaxcGWx1-rA2anjKI4h" : {
 "name" : "Bob",
 "username" : "Bob"
 "events" : [ {
  "event" : "-KdHscYor4mA--ubIHBj"
 }]
 }
}

events -
{
 "-KdHscYor4mA--ubIHBj" : {
   "dateCreated" : "Fri Feb 17 2017 23:37:32 GMT+0000 (GMT)",
   "eventDate" : "2017-04-01",
   "name" : "Event 1",
},
 "-KdKsJBdHimgPPQQ6bcA" : {
   "dateCreated" : "Fri Feb 17 2017 23:37:32 GMT+0000 (GMT)",
   "eventDate" : "2017-04-01",
   "name" : "Event 2",
 }
 }

So given that both events are for today. I would expect to Bill to have two and Bob to have one.

The code I have tried is:

var todayDate = '2017-04-01';
var ref = firebase.database().ref('accounts/');
ref.once('value', function (snapshot) {
    //Foreach user account
    var eventCount = 0;
    snapshot.forEach(function (account) {
        var ref = firebase.database().ref('accounts/' + account.key);
        ref.child('events').once('value', function (eventSnapshot) {
            //Foreach event
            eventSnapshot.forEach(function (child) {
                firebase.database().ref('events/' + child.val().event).once('value', function (event) {
                        if (eventDate === todayDate) {
                            console.log(account.val().name, 'has an event today -', event.val().name);
                            eventCount++;
                        }
                });
            });
        });
        console.log(account.val().name, 'total events -', eventCount);
    });
});

However, the result I'm getting in the console is:

Bill total events - 0
Bob total events - 0
Bill has an event today Event 1
Bill has an event today Event 2
Bob has an event today Event 2

Body:
With your current structure you will have problems when scaling because you would need to retrieve all the users and then all time events for that user and check each one of the dates. You could do it much simpler by changing your events data structure a bit.

events: {
  eventId1: {
   date: '20170401',
   attendingAccount:{
     accountId1: true,
     accountId2: true,
   }
  },
  eventId2: {...}
}

If you just save the accountId of the users that are attending the event like above you would just need to run something like the following:

let attendingCount = {};

firebase.database().ref('events').orderByChild('date').equalTo(today).once(snap => {
    let events = snap.val();

    if (events){
        Object.keys(events).forEach(eventId => {
            Object.keys(events[eventId].attendingAccounts).forEach(accountId => {
                if (!attendingCount[accountId]){
                    attendingCount[accountId] = 0;
                }
                attendingCount[accountId]++;
            });
        });
    }
});

This would result in the object attendingCount having the count for each one of the accountIds.

attendingCount: {
   accountId1: 2,
   accountId2: 5,
   ...
}


问:
C++ dynamic array of dynamic strings
I know how to create a dynamic array of strings in C++:

```<code>string* array = new string[10];
</code>```

But how do I create a dynamic array of dynamic strings in C++? I mean a dynamic array that holds string* objects. And how do I initialize each one of the dynamic strings?

答:
I agree that if you need to implement what you're asking, you should probably rethink your design. However the syntax for what you're asking is exactly correlative to the array of strings:

```<code>string** sillyIdea = new string*[10];
//some access examples
sillyIdea[0]= new string;
*(sillyIdea[0]) = "hello";
(*(sillyIdea[0]))[0] = 'H';
 sillyIdea[1]= new string;

//statement below looks like a 2d array construct but it is not,
//just shorthand for
// *((sillyIdea[1]) + 0)
 sillyIdea[1][0] = "world";
//an array of pointers can usually be treated programtcally as a
//jaggedarray(asymtrical multi-dimensional array). In other words,
// your array of string pointers can be treated like an array of one
//element string arrays, making for a cleaner syntax, but worse code.

//in int main(int argc, char** argv), argv is one such example of a jagged array.
</code>```

the string vector suggested above will yield less heartache

Title: C++ dynamic array of dynamic strings

Body:
I know how to create a dynamic array of strings in C++:

string* array = new string[10];

But how do I create a dynamic array of dynamic strings in C++? I mean a dynamic array that holds string* objects. And how do I initialize each one of the dynamic strings?

Body:
I agree that if you need to implement what you're asking, you should probably rethink your design. However the syntax for what you're asking is exactly correlative to the array of strings:

string** sillyIdea = new string*[10];
//some access examples
sillyIdea[0]= new string;
*(sillyIdea[0]) = "hello";
(*(sillyIdea[0]))[0] = 'H';
 sillyIdea[1]= new string;

//statement below looks like a 2d array construct but it is not,
//just shorthand for
// *((sillyIdea[1]) + 0)
 sillyIdea[1][0] = "world";
//an array of pointers can usually be treated programtcally as a
//jaggedarray(asymtrical multi-dimensional array). In other words,
// your array of string pointers can be treated like an array of one
//element string arrays, making for a cleaner syntax, but worse code.

//in int main(int argc, char** argv), argv is one such example of a jagged array.

the string vector suggested above will yield less heartache


答:
I think you do not have to run for loops for your solution, when you are taking rows and columns from user, You can simply subtract A from alphabet to check if this was the column, if you subtract A form any upper case letter It will become array counting like A-A=0,B-A=1,C-A=2
So here is solution you can use :

```<code>    int row;
    char colum;
    cout<<"Enter the row number with colum letter ex(0 A): ";
    cin>>row>>colum;
    colum = toupper(colum);
    int c= int(colum - 'A');
      //check if the seat is taken
      if( seatChart[row][c] == 'X'){
       cout<<"seat is already taken\n\n";
       }else
       seatChart[row][c] = 'X';
</code>```

Title: How to check airplane seat reservation in C++

Body:
I am new to C++ and I am trying to reserve a seat in airplane with an two dimensional array; everything work except it won't check if the seat is already taken.

for example:
 1  A B C D
 2  A B C D
 3  A B C D
 4  A B C D
 5  A B C D

if the user choose row 1 letter A then it will be:

 1  X B C D
 2  A B C D
 3  A B C D
 4  A B C D
 5  A B C D

Then if the user choose row 1 letter A again it should display message says the seat is already taken.This is my code

void reserveSeat(char seatChart[ROW][COLUM]){

    int row;
    char colum;

    cout<<"Enter the row number with colum letter ex(0 A): ";
    cin>>row>>colum;
    colum = toupper(colum);

    for(int r = 0; r<ROW;r++){

        for(int c = 0; c<COLUM;c++){

            if(seatChart[row][c] == colum){

                //check if the seat is taken
                if( seatChart[row][c] == 'X'){

                    cout<<"seat is already taken\n\n";
                }else
                    seatChart[row][c] = 'X';
            }
        }//end of inner for loop
    }//end of outer for loop
}

Body:
I think you do not have to run for loops for your solution, when you are taking rows and columns from user, You can simply subtract A from alphabet to check if this was the column, if you subtract A form any upper case letter It will become array counting like A-A=0,B-A=1,C-A=2
So here is solution you can use :

    int row;
    char colum;
    cout<<"Enter the row number with colum letter ex(0 A): ";
    cin>>row>>colum;
    colum = toupper(colum);
    int c= int(colum - 'A');
      //check if the seat is taken
      if( seatChart[row][c] == 'X'){
       cout<<"seat is already taken\n\n";
       }else
       seatChart[row][c] = 'X';


答:
You already know that you can create an array of string objects with new string[n].

You can expand that idea to allocate an array of objects of any† type T: new T[n]. If you wish to create an array of string* objects, you can simply use new string*[n].

That said, there is hardly ever need to dynamically allocate an instance of std::string. And hardly ever need to manually allocate a dynamic array instead of using std::vector.

† There are some limitations. With this particular syntax, the type must be default constructible.

Title: C++ dynamic array of dynamic strings


问:
C - Counting numbers
I am a coding-beginner and would like to hear your advice relating to following solution of this exercise:

Write a program that loops prompting for positive or zero integers of data type long. Then the number of digits the integer consists of (in decimal representation) should be printed to stdout. Entering a negative number immediately stops the program.
  Output examples: 0 has 1 digit. 999 has 3 digits. etc.

I've written the code below and according to the tests I did, the program fulfills all given tasks. But what do you think about it? How can I improve it?

(And I also think that I am not allowed to use any finished helpful function in any c-library. It is just 'plain' C coding or so. Idk how to describe it.)

(The programming language is C)

```<code>#include <stdio.h>

int main(void)
{
  long number;
  int n=0;

  do
  {
      printf("Enter a number: ");
      scanf_s("%ld", &number);

      if (number > 0)
      {
          while (number != 0)
          {
              number /= 10;
              n++;
          }
      }
      else if(number == 0){
          n = 1;
      }
      else {
          exit();
      }

      printf("The number you've entered has %d digits.\n\n",n);
      n = 0;

  } while (getchar() != 'EOF');

  return 0;
}
</code>```

答: That getchar it's useless because EOF it's to say that a file it's over and you're not reading an file. Change that to while(number >=0).</p>

Title: C - Counting numbers

Body:
I am a coding-beginner and would like to hear your advice relating to following solution of this exercise:

Write a program that loops prompting for positive or zero integers of data type long. Then the number of digits the integer consists of (in decimal representation) should be printed to stdout. Entering a negative number immediately stops the program.
  Output examples: 0 has 1 digit. 999 has 3 digits. etc.

I've written the code below and according to the tests I did, the program fulfills all given tasks. But what do you think about it? How can I improve it?

(And I also think that I am not allowed to use any finished helpful function in any c-library. It is just 'plain' C coding or so. Idk how to describe it.)

(The programming language is C)

#include <stdio.h>

int main(void)
{
  long number;
  int n=0;

  do
  {
      printf("Enter a number: ");
      scanf_s("%ld", &number);

      if (number > 0)
      {
          while (number != 0)
          {
              number /= 10;
              n++;
          }
      }
      else if(number == 0){
          n = 1;
      }
      else {
          exit();
      }

      printf("The number you've entered has %d digits.\n\n",n);
      n = 0;

  } while (getchar() != 'EOF');

  return 0;
}


问:
How to remove unwanted space below scrollview in android?
When I run this code on my device, additional space appears below the imageView. In the end, I would like my images to fulfill the greatest amount of space on the screen without distorting their dimensions. Any help would be greatly appreciated. I have attached the code for my elements and their attributes. Thanks!
    </p>

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_ch0_example_problems"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:clipToPadding="false"
android:fillViewport="false"
android:scrollbarStyle="insideOverlay"
tools:context="com.example.android.chsalgebra.Ch0ExampleProblems">

<Button
    android:id="@+id/prevBut1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="6dp"
    android:layout_marginLeft="6dp"
    android:onClick="displayProblemMinus"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Previous"
    android:textAllCaps="false"
    android:textColor="#769ecd" />

<Button
    android:id="@+id/nextBut1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="6dp"
    android:layout_marginRight="6dp"
    android:onClick="displayProblemPlus"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Next"
    android:textAllCaps="false"
    android:textColor="#769ecd" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/prevBut1"
    android:layout_alignLeft="@+id/prevBut1"
    android:layout_alignParentTop="true"
    android:layout_alignStart="@+id/prevBut1">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/ex1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:paddingTop="12dp"
            android:scaleType="fitStart"
            app:srcCompat="@drawable/ch0ex1" />
    </LinearLayout>
</ScrollView>
</RelativeLayout>
</code>```

答: I ended up playing around with attributes and I found that android:adjustViewBounds set to true fixed my problem. I don't know exactly this attribute does, but it worked! Thanks again.</p>

Body:
When I run this code on my device, additional space appears below the imageView. In the end, I would like my images to fulfill the greatest amount of space on the screen without distorting their dimensions. Any help would be greatly appreciated. I have attached the code for my elements and their attributes. Thanks!

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_ch0_example_problems"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:clipToPadding="false"
android:fillViewport="false"
android:scrollbarStyle="insideOverlay"
tools:context="com.example.android.chsalgebra.Ch0ExampleProblems">

<Button
    android:id="@+id/prevBut1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="6dp"
    android:layout_marginLeft="6dp"
    android:onClick="displayProblemMinus"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Previous"
    android:textAllCaps="false"
    android:textColor="#769ecd" />

<Button
    android:id="@+id/nextBut1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="6dp"
    android:layout_marginRight="6dp"
    android:onClick="displayProblemPlus"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Next"
    android:textAllCaps="false"
    android:textColor="#769ecd" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/prevBut1"
    android:layout_alignLeft="@+id/prevBut1"
    android:layout_alignParentTop="true"
    android:layout_alignStart="@+id/prevBut1">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/ex1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:paddingTop="12dp"
            android:scaleType="fitStart"
            app:srcCompat="@drawable/ch0ex1" />
    </LinearLayout>
</ScrollView>
</RelativeLayout>


问:
python: create a new dataframe with specific column using pandas
```<code>def csv_reader(fileName):
    usecols=['_id__$oid','payload','channel']
    io = pd.read_csv(fileName,sep=",",names=usecols)
    df = pd.DataFrame(io,columns=['_id__$oid','payload','channel'])
    print(df)
    df.to_csv('trimmed.csv')

if __name__=="__main__":
    csv_path = "snort_alerts.csv"
    csv_reader(csv_path)
</code>```

Using pandas for python for the first time.

I am trying to extract 3 columns from a dataset based on the column names and write it back to another csv using pandas. The dataframe io contains all the columns instead of just the columns specified usecols, I even tried doing the same by specifying the column numbers.Am I missing something?

答:
is this what you are looking for ? </p>

```<code>xcolumns = ['_id__$oid','payload','channel']

io[xcolumns]
</code>```

<p>despite the minus vote, I think that this is is what the user is looking for </p>

```<code>io = pd.read_csv("snort_alerts.csv",sep=",")
df = io[['_id__$oid','payload','channel']]
</code>```

Body:
def csv_reader(fileName):
    usecols=['_id__$oid','payload','channel']
    io = pd.read_csv(fileName,sep=",",names=usecols)
    df = pd.DataFrame(io,columns=['_id__$oid','payload','channel'])
    print(df)
    df.to_csv('trimmed.csv')

if __name__=="__main__":
    csv_path = "snort_alerts.csv"
    csv_reader(csv_path)

Using pandas for python for the first time.

I am trying to extract 3 columns from a dataset based on the column names and write it back to another csv using pandas. The dataframe io contains all the columns instead of just the columns specified usecols, I even tried doing the same by specifying the column numbers.Am I missing something?

Body:
is this what you are looking for ?

xcolumns = ['_id__$oid','payload','channel']

io[xcolumns]

despite the minus vote, I think that this is is what the user is looking for

io = pd.read_csv("snort_alerts.csv",sep=",")
df = io[['_id__$oid','payload','channel']]


问:
pyautogui.pixel picking up color from upper left of actual position

while True:
 x=pyautogui.position()
 print(x+pyautogui.pixel(x[0],x[1]))
```

and program is picking up color that is actually upper left of my cursor...

I am using python 3.6, windows 10, on 125% magnification. is this one of the reason?

答:
Usually picking color with the mouse gives NOT the color of the mouse pointer on the screen but the color of the screen 'below' the cursor.

On my box (Linux Mint) the code:

```<code>import pyautogui
while True:
    posXY = pyautogui.position()
    print(posXY, pyautogui.pixel(posXY[0], posXY[1]) )
    if posXY[0] == 0:
        break
</code>```

delivers what it should - the color 'below' the mouse pointer.

Notice the 'break' in the endless loop. This allows you to stop the loop by moving the mouse to the left edge of the screen :)

ContentLicense: CC BY-SA 4.0

Body:
while True:
 x=pyautogui.position()
 print(x+pyautogui.pixel(x[0],x[1]))

and program is picking up color that is actually upper left of my cursor...

I am using python 3.6, windows 10, on 125% magnification. is this one of the reason?

Body:
Usually picking color with the mouse gives NOT the color of the mouse pointer on the screen but the color of the screen 'below' the cursor.

On my box (Linux Mint) the code:

import pyautogui
while True:
    posXY = pyautogui.position()
    print(posXY, pyautogui.pixel(posXY[0], posXY[1]) )
    if posXY[0] == 0:
        break

delivers what it should - the color 'below' the mouse pointer.

Notice the 'break' in the endless loop. This allows you to stop the loop by moving the mouse to the left edge of the screen :)


问:
Why does a .NET Core app need C# AND VB assemblies?
I noticed that among the dependencies for a .NET Core application, there are Microsoft.CSharp and Microsoft.VisualBasic, with pretty much the same dependencies:

I'd like to better understand:

Why (what seem like) language-specific DLLs are needed in the first place;

Why both DLLs are needed.

答:
Why (what seem like) language-specific DLLs are needed in the first place;

They exist to support language-specific functionality. In the case of C#, this is primarily for dynamic. In the case of VB, this is mostly for VB-specific members, like AscW or vbCrLf (which can be used from C# too) and also some types used by the VB compiler.

Why both DLLs are needed.

Because, at least in theory, the Microsoft.NETCore.App package, which includes both the C# and the VB package, is language neutral. Though in practice, VB is not currently supported on .Net Core. And F# (which is supported) has its own package, which is not included by default.