问:
Java + Spark simple joins
I'm completely new to Spark and I have to do this at my uni.

Here are 2 text files with data base.

User information: (id, email, language, location)

```<code>1   user1@test.com  EN  US
2   user2@test2.com EN  GB
3   user3@test3.com FR  FR
</code>```

Transaction infromation: (transaction-id, product-id, user-id, purchase-amount, itemdescription)

```<code>1   1   1   300 prod1
2   1   2   300 prod1
3   1   2   300 prod2
4   2   3   100 prod2
5   1   3   300 prod3
</code>```

My task is to provide a query like that:

User_id, count(product_id), location

Many thanks for your help in advance!

答:
Here is an simple example, so you can get started. But please please read the spark doc here

```<code>val spark =
    SparkSession.builder().master("local").appName("test").getOrCreate()
    import spark.implicits._
    val df1 = spark.sparkContext.parallelize(Seq(
          (1, "user1@test.com", "EN", "US"),
          (2, "user2@test2.com", "EN", "GB"),
          (3, "user3@test3.com", "FR", "FR")
        ))
      .toDF("id", "email", "language", "location")

    val df2 = spark.sparkContext.parallelize(Seq(
          (1, 1, 1, 300, "prod1"),
          (2, 1, 2, 300, "prod1"),
          (3, 1, 2, 300, "prod2"),
          (4, 2, 3, 100, "prod2"),
          (5, 1, 3, 300, "prod3")
        )
      ).toDF("transaction-id", "product-id","user-id", "purchase-amount", "itemdescription")

    val df2Count = df2.groupBy("user-id").count().alias("count_product_id")

    val result = df2Count.join(df1, df2Count("user-id") === df1("id"))

    result.select("user-id", "count", "location").show
</code>```

Output:

```<code>+-------+-----+--------+
|user-id|count|location|
+-------+-----+--------+
|      1|    1|      US|
|      3|    2|      FR|
|      2|    2|      GB|
+-------+-----+--------+
</code>```

Title: Java + Spark simple joins

Body:
I'm completely new to Spark and I have to do this at my uni.

Here are 2 text files with data base.

User information: (id, email, language, location)

1   user1@test.com  EN  US
2   user2@test2.com EN  GB
3   user3@test3.com FR  FR

Transaction infromation: (transaction-id, product-id, user-id, purchase-amount, itemdescription)

1   1   1   300 prod1
2   1   2   300 prod1
3   1   2   300 prod2
4   2   3   100 prod2
5   1   3   300 prod3

My task is to provide a query like that:

User_id, count(product_id), location

Many thanks for your help in advance!

Body:
Here is an simple example, so you can get started. But please please read the spark doc here

val spark =
    SparkSession.builder().master("local").appName("test").getOrCreate()
    import spark.implicits._
    val df1 = spark.sparkContext.parallelize(Seq(
          (1, "user1@test.com", "EN", "US"),
          (2, "user2@test2.com", "EN", "GB"),
          (3, "user3@test3.com", "FR", "FR")
        ))
      .toDF("id", "email", "language", "location")

    val df2 = spark.sparkContext.parallelize(Seq(
          (1, 1, 1, 300, "prod1"),
          (2, 1, 2, 300, "prod1"),
          (3, 1, 2, 300, "prod2"),
          (4, 2, 3, 100, "prod2"),
          (5, 1, 3, 300, "prod3")
        )
      ).toDF("transaction-id", "product-id","user-id", "purchase-amount", "itemdescription")

    val df2Count = df2.groupBy("user-id").count().alias("count_product_id")

    val result = df2Count.join(df1, df2Count("user-id") === df1("id"))

    result.select("user-id", "count", "location").show

Output:

+-------+-----+--------+
|user-id|count|location|
+-------+-----+--------+
|      1|    1|      US|
|      3|    2|      FR|
|      2|    2|      GB|
+-------+-----+--------+


来源: stackexchange

问:
The effect affects all the button in css
Im wondering why is this happening. If I hover a button, all buttons applies the effect which supposedly not. I want to apply the effect only on the button that I've hover.

.buttons{
  font-family: arial;
  text-decoration: none;
  padding: 10px 15px;
  background: #000;
  color: #fff;
  border-radius: 3px;
}

.buttons:after{
 content: "";
    position: absolute;
    top: 0px;
    left: 0px;
    width: 0%;
    height: 100%;
    background-color: rgba(255,255,255,0.4);
    -webkit-transition: none;
    -moz-transition: none;
    -ms-transition: none;
    -o-transition: none;
    transition: none;
}

.buttons:hover:after{
 width: 120%;
 background-color: rgba(255,255,255,0);
    -webkit-transition: all 0.3s ease-out;
    -moz-transition: all 0.3s ease-out;
    -ms-transition: all 0.3s ease-out;
    -o-transition: all 0.3s ease-out;
    transition: all 0.3s ease-out;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br><br>
Submit
Submit
Submit
Submit</code>```

答:
Your width: 120%; in :hover is measuring relative to the document (which is the pseudo-element's offsetParent), not the button.

Add position: relative; to the button to make that the offset parent instead:

.buttons{
  position: relative;
  font-family: arial;
  text-decoration: none;
  padding: 10px 15px;
  background: #000;
  color: #fff;
  border-radius: 3px;
}

.buttons:after{
 content: "";
    position: absolute;
    top: 0px;
    left: 0px;
    width: 0%;
    height: 100%;
    background-color: rgba(255,255,255,0.4);
    -webkit-transition: none;
    -moz-transition: none;
    -ms-transition: none;
    -o-transition: none;
    transition: none;
}

.buttons:hover:after{
 width: 120%;
 background-color: rgba(255,255,255,0);
    -webkit-transition: all 0.3s ease-out;
    -moz-transition: all 0.3s ease-out;
    -ms-transition: all 0.3s ease-out;
    -o-transition: all 0.3s ease-out;
    transition: all 0.3s ease-out;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br><br>
Submit
Submit
Submit
Submit</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im wondering why is this happening. If I hover a button, all buttons applies the effect which supposedly not. I want to apply the effect only on the button that I've hover.

.buttons{
  font-family: arial;
  text-decoration: none;
  padding: 10px 15px;
  background: #000;
  color: #fff;
  border-radius: 3px;
}

.buttons:after{
 content: "";
    position: absolute;
    top: 0px;
    left: 0px;
    width: 0%;
    height: 100%;
    background-color: rgba(255,255,255,0.4);
    -webkit-transition: none;
    -moz-transition: none;
    -ms-transition: none;
    -o-transition: none;
    transition: none;
}

.buttons:hover:after{
 width: 120%;
 background-color: rgba(255,255,255,0);
    -webkit-transition: all 0.3s ease-out;
    -moz-transition: all 0.3s ease-out;
    -ms-transition: all 0.3s ease-out;
    -o-transition: all 0.3s ease-out;
    transition: all 0.3s ease-out;
}

Submit
Submit
Submit
Submit

Body:
Your width: 120%; in :hover is measuring relative to the document (which is the pseudo-element's offsetParent), not the button.

Add position: relative; to the button to make that the offset parent instead:

.buttons{
  position: relative;
  font-family: arial;
  text-decoration: none;
  padding: 10px 15px;
  background: #000;
  color: #fff;
  border-radius: 3px;
}

.buttons:after{
 content: "";
    position: absolute;
    top: 0px;
    left: 0px;
    width: 0%;
    height: 100%;
    background-color: rgba(255,255,255,0.4);
    -webkit-transition: none;
    -moz-transition: none;
    -ms-transition: none;
    -o-transition: none;
    transition: none;
}

.buttons:hover:after{
 width: 120%;
 background-color: rgba(255,255,255,0);
    -webkit-transition: all 0.3s ease-out;
    -moz-transition: all 0.3s ease-out;
    -ms-transition: all 0.3s ease-out;
    -o-transition: all 0.3s ease-out;
    transition: all 0.3s ease-out;
}

<br><br>
<a href="#" class="buttons">Submit</a>
<a href="#" class="buttons">Submit</a>
<a href="#" class="buttons">Submit</a>
<a href="#" class="buttons">Submit</a>


问:
Can't get jQuery find if in ViewPort to work
I know the question of how to find if an element is visible in the viewport using jQuery has already been answered, but I'm having trouble getting it to work for me. The jQuery code that I'm using based on other answers is:

```<code>jQuery(document).ready(function() {
$(window).scroll(function() {
var top_of_element = $(".basic-box1").offset().top;
var bottom_of_element = $(".basic-box1").offset().top + $(".basic-box1").outerHeight();
var bottom_of_screen = $(window).scrollTop() + $(window).height();
var top_of_screen = $(window).scrollTop();

if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
   $('.basic-box1').fadeIn();
}
else {
   $('.basic-box1').fadeOut();
}
});
});
</code>```

Html:

```<code><div class="basic-box1">
  <p class="how-p1">Text text text</p>
</div>
</code>```

CSS:

```<code>.basic-box1 {
  background-color: antiquewhite;
  border: solid;
  border-width: 2px;
  padding: 40px;
  margin: auto;
  width: 50%;
  margin-bottom: 700px;
  margin-top: 800px;
}
</code>```

I feel like I must be missing something obvious. I've tried just about everything I know and can't get it to work. Any help would be much appreciated.
If it would help to see it on my site it's at http://www.claywhaley.com

答: Your website console has an error $ is not a function coz of wordpress. Please have a look here

Body:
I know the question of how to find if an element is visible in the viewport using jQuery has already been answered, but I'm having trouble getting it to work for me. The jQuery code that I'm using based on other answers is:

jQuery(document).ready(function() {
$(window).scroll(function() {
var top_of_element = $(".basic-box1").offset().top;
var bottom_of_element = $(".basic-box1").offset().top + $(".basic-box1").outerHeight();
var bottom_of_screen = $(window).scrollTop() + $(window).height();
var top_of_screen = $(window).scrollTop();

if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
   $('.basic-box1').fadeIn();
}
else {
   $('.basic-box1').fadeOut();
}
});
});

Html:

Text text text

CSS:

.basic-box1 {
  background-color: antiquewhite;
  border: solid;
  border-width: 2px;
  padding: 40px;
  margin: auto;
  width: 50%;
  margin-bottom: 700px;
  margin-top: 800px;
}

I feel like I must be missing something obvious. I've tried just about everything I know and can't get it to work. Any help would be much appreciated.
If it would help to see it on my site it's at http://www.claywhaley.com


问:
Using a Function in a Callback/Using a SegmentedControl within a Cell
I have an app that has UISegmentedControls in each UITableViewCell, it looks like this:

https://i.stack.imgur.com/ezMUJ.png

For every row in which the user selects the "Yes" option, I would like to print the index of the row.

The first step, in this case, would be to use an addTarget on the UISegmentedControl in order to specify a function to handle the Segmented Control's action. However, since I am using a custom segmented control, the addTarget is not available (callback and delegation are the only ways of passing information into the segmented control).

My first question is, is there a way to call a method within a callback?
My second question is, is there an easier way to do this overall? Some people have suggested protocols and delegation for transferring data between the cell and the view controller, but I am not really sure how to do this or that it would be appropriate.

Here is the code I have so far:

import UIKit

class MyTableViewController: UITableViewController {

```<code>override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 150
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return 10
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
    cell.backgroundColor = .green
    return cell

}

func printCellIndexPath(cell: UITableViewCell){

}

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.register(MyCell.self, forCellReuseIdentifier: "cellId")

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
</code>```

}

class MyCell: UITableViewCell{

```<code>var myTableViewController: MyTableViewController?

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    setupViews()

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

let nameLabel: UILabel = {
    let label = UILabel()
    label.text = "Sample Item"
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
    }()

let actionButton = YSSegmentedControl(
    frame: CGRect.zero,
    titles: [
        "Yes",
        "No"
    ],
    action: {
        control, index in
        if index == 1 {
            print ("tapped")
        }
        else{

        }

})

func setupViews(){

    addSubview(nameLabel)
    addSubview(actionButton)
    actionButton.translatesAutoresizingMaskIntoConstraints = false

    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-160-[v1]-16-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel, "v1": actionButton]));
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-60-[v0]-60-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": actionButton]))

}
</code>```

}

Where MyCell is my custom cell class and actionButton is the UISegmentedControl that exists within each cell.

答:
To Remove delegation and callbacks why not u make YSSegmentedControl in cellForrowatIndexpath method and there u will pass tag to YSSegmentedControl's object as like that

actionButton.tag = indexpath.row

and when u click on any segment u will get callback in YSSegmentedControl delegates which are

func segmentedControl(_ segmentedControl: YSSegmentedControl,
  willPressItemAt index: Int){
           print("(segmentedControl.tag)" + "(index)")
      }

```<code>func segmentedControl(_ segmentedControl: YSSegmentedControl, didPressItemAt index: Int){

}
</code>```

From these delegates method u will get YSSegmentedControl row via
segmentedControl.tag and particular button index via index

ContentLicense: CC BY-SA 4.0

Body:
I have an app that has UISegmentedControls in each UITableViewCell, it looks like this:

https://i.stack.imgur.com/ezMUJ.png

For every row in which the user selects the "Yes" option, I would like to print the index of the row.

The first step, in this case, would be to use an addTarget on the UISegmentedControl in order to specify a function to handle the Segmented Control's action. However, since I am using a custom segmented control, the addTarget is not available (callback and delegation are the only ways of passing information into the segmented control).

My first question is, is there a way to call a method within a callback?
My second question is, is there an easier way to do this overall? Some people have suggested protocols and delegation for transferring data between the cell and the view controller, but I am not really sure how to do this or that it would be appropriate.

Here is the code I have so far:

import UIKit

class MyTableViewController: UITableViewController {

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 150
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return 10
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
    cell.backgroundColor = .green
    return cell

}

func printCellIndexPath(cell: UITableViewCell){

}

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.register(MyCell.self, forCellReuseIdentifier: "cellId")

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

class MyCell: UITableViewCell{

var myTableViewController: MyTableViewController?

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    setupViews()

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

let nameLabel: UILabel = {
    let label = UILabel()
    label.text = "Sample Item"
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
    }()

let actionButton = YSSegmentedControl(
    frame: CGRect.zero,
    titles: [
        "Yes",
        "No"
    ],
    action: {
        control, index in
        if index == 1 {
            print ("tapped")
        }
        else{

        }

})

func setupViews(){

    addSubview(nameLabel)
    addSubview(actionButton)
    actionButton.translatesAutoresizingMaskIntoConstraints = false

    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-160-[v1]-16-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel, "v1": actionButton]));
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-60-[v0]-60-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": actionButton]))

}

}

Where MyCell is my custom cell class and actionButton is the UISegmentedControl that exists within each cell.

Body:
To Remove delegation and callbacks why not u make YSSegmentedControl in cellForrowatIndexpath method and there u will pass tag to YSSegmentedControl's object as like that

actionButton.tag = indexpath.row

and when u click on any segment u will get callback in YSSegmentedControl delegates which are

func segmentedControl(_ segmentedControl: YSSegmentedControl,
  willPressItemAt index: Int){
           print("(segmentedControl.tag)" + "(index)")
      }

func segmentedControl(_ segmentedControl: YSSegmentedControl, didPressItemAt index: Int){

}

From these delegates method u will get YSSegmentedControl row via
segmentedControl.tag and particular button index via index


问:
Type casting with pointers in C
Does the following type cast create a new variable in memory?
It is referenced in the printf function below, and it prints 1.23 as the answer.</p>

```<code>#include<stdio.h>
int main(){
    int num;
    num = 1.23456;
    printf("num = %.2f \n", (float)num);
    *((float*) &num) = 1.23456;
    printf("num = %.2f \n", *((float*)&num));
    return 0;
}
</code>```

答:
The main idea here is that when you cast to float pointer and write the value into memory:

```<code>*((float*) &num) = 1.23456;
</code>```

The compiler writes the value in memory as if it was a float. So indeed you will have a float stored in the place where an int was supposed to be stored, something you wouldn't normally be allowed to do.
So when you show it as a float:

```<code>printf("num = %.2f \n", *((float*)&num));
</code>```

It works. But when you go back and show it as a int again after assigning it directly with:

```<code>printf("num = %d \n", num);
</code>```

You will see a different value:

```<code>num = 1067320848
</code>```

Which is the representation of a float value shown as an integer one.

Remember that internally integers and floats are stored differently, in what concerns the bits, due to the floating point representation.

Title: Type casting with pointers in C

Body:
Does the following type cast create a new variable in memory?
It is referenced in the printf function below, and it prints 1.23 as the answer.

#include<stdio.h>
int main(){
    int num;
    num = 1.23456;
    printf("num = %.2f \n", (float)num);
    *((float*) &num) = 1.23456;
    printf("num = %.2f \n", *((float*)&num));
    return 0;
}

Body:
The main idea here is that when you cast to float pointer and write the value into memory:

*((float*) &num) = 1.23456;

The compiler writes the value in memory as if it was a float. So indeed you will have a float stored in the place where an int was supposed to be stored, something you wouldn't normally be allowed to do.
So when you show it as a float:

printf("num = %.2f \n", *((float*)&num));

It works. But when you go back and show it as a int again after assigning it directly with:

printf("num = %d \n", num);

You will see a different value:

num = 1067320848

Which is the representation of a float value shown as an integer one.

Remember that internally integers and floats are stored differently, in what concerns the bits, due to the floating point representation.


问:
Gradle: exclude and include multiple groups/modules in single line from compile closure
this syntax may be not yet provided but I am asking to avoid redundant code.
Right now I am excluding jars like this

```<code> compile ('com.mygroup:myJar:0.1.1-M1-SNAPSHOT+') {
    exclude group: 'org.apache.xmlgraphics'
    exclude group:'org.apache.avalon.framework'
    exclude group:'net.engio'
    exclude group: 'com.google.guava'
}
</code>```

How can i exclude multiple groups/modules on a single line of code, for example, this syntax

```<code>compile ('com.mygroup:myJar:0.1.1-M1-SNAPSHOT+'){
    exclude group: ['org.apache.xmlgraphics', 'org.apache.avalon.framework', 'net.engio', 'com.google.guava']
}
</code>```

Or is there any other short code which does the same thing.

Thank You.

答:
```<code>compile ('com.mygroup:myJar:0.1.1-M1-SNAPSHOT+'){dep ->
    ['org.apache.xmlgraphics', 'org.apache.avalon.framework', 'net.engio', 'com.google.guava'].each {group -> dep.exclude group: group }
}
</code>```

Refer to this.

Body:
this syntax may be not yet provided but I am asking to avoid redundant code.
Right now I am excluding jars like this

 compile ('com.mygroup:myJar:0.1.1-M1-SNAPSHOT+') {
    exclude group: 'org.apache.xmlgraphics'
    exclude group:'org.apache.avalon.framework'
    exclude group:'net.engio'
    exclude group: 'com.google.guava'
}

How can i exclude multiple groups/modules on a single line of code, for example, this syntax

compile ('com.mygroup:myJar:0.1.1-M1-SNAPSHOT+'){
    exclude group: ['org.apache.xmlgraphics', 'org.apache.avalon.framework', 'net.engio', 'com.google.guava']
}

Or is there any other short code which does the same thing.

Thank You.

Body:
compile ('com.mygroup:myJar:0.1.1-M1-SNAPSHOT+'){dep ->
    ['org.apache.xmlgraphics', 'org.apache.avalon.framework', 'net.engio', 'com.google.guava'].each {group -> dep.exclude group: group }
}

Refer to this.


问:
How many iOS Ad Hoc distibution certificates can be created? Limit for certificates?
Can anybody please shed some light on how many iOS Ad-Hoc & Development certificates are allowed by Apple? For both Enterprise and non-Enterprise accounts. Any official links will help.

Thanks

答: IOS distribution certificate personal account can only apply for three, the company accounts to create more</p>


问:
Save the id of autocomplete field instead of the text (Jquery autocomplete) in Rails3
I have managed to setup autocomplete field for my rails app.  What I'm trying to do is to have the contents of a lookup table listed and when I have selected the lookup text for few lines I would like the id of the lookup to be saved instead of the text itself.  Here is what I have done:

Recipe model:

```<code>class Recipe < ActiveRecord::Base
  # validates :name,  :presence => true
  # validates :directions, :presence => true

  # has_and_belongs_to_many :ingradients

  has_many :ingredients_recipes
  has_many :ingredients, :through => :ingredients_recipes

  accepts_nested_attributes_for :ingredients_recipes, :allow_destroy => true
end
</code>```

Controller:

```<code>class RecipesController < ApplicationController
  # autocomplete :ndb_food_des, :long_desc
  autocomplete :ndb_food_de, :long_desc, :limit => 15

  ... more lines
end
</code>```

I then use this in the view:

```<code> <% f.fields_for :ingredients_recipes do |rif| %>
          <td>
              <%= rif.autocomplete_field :ingredient_id, recipes_autocomplete_ndb_food_de_long_desc_path, :width=>1000, :size=>60 %>
          </td>
<% end %>
</code>```

I have three detail lines generated when the view opens and what I want to do is write the id of the selected item from the autocomplete.  If I specify the correct field in the view as ingredient_id then I always get 0 in the id in the insert.  If I specify some other field I get the full text of the autocomplete, so it seems that Rails is picking up the correct field and seems to know what to do ... but it's not getting the correct id.

Here is a trace of what the system does:

```<code>Started POST "/recipes" for 127.0.0.1 at 2010-10-17 16:28:10 +0000
  Processing by RecipesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"wmNQbsGoiGccrNpmFs7r7D7ZBq//SBe9yrk6SFXP0lc=", "recipe"=>{"name"=>"dfsa", "description"=>"sdfa", "directions"=>"sadf", "ingredients_recipes_attributes"=>{"0"=>{"ingredient_id"=>"CAMPBELL Soup Company, CAMPBELL'S Beef Gravy", "readable_qty"=>"30", "description"=>""}, "1"=>{"ingredient_id"=>"Eclairs, custard-filled with chocolate glaze, prepared from recipe", "readable_qty"=>"60", "description"=>""}, "2"=>{"ingredient_id"=>"DENNY'S, MOONS & STARS chicken nuggets, from kid's menu", "readable_qty"=>"10", "description"=>""}}, "servings"=>"3", "time"=>"3"}, "commit"=>"Create Recipe"}
  SQL (27.9ms)  INSERT INTO "recipes" ("created_at", "description", "directions", "name", "owner", "servings", "time", "updated_at") VALUES ('2010-10-17 16:28:10.686644', 'sdfa', 'sadf', 'dfsa', NULL, 3, 3, '2010-10-17 16:28:10.686644')
  SQL (0.2ms)  INSERT INTO "ingredients_recipes" ("created_at", "description", "ingredient_id", "qty", "recipe_id", "updated_at") VALUES ('2010-10-17 16:28:10.729542', '', **0,** 32.0, 18, '2010-10-17 16:28:10.729542')
  SQL (0.1ms)  INSERT INTO "ingredients_recipes" ("created_at", "description", "ingredient_id", "qty", "recipe_id", "updated_at") VALUES ('2010-10-17 16:28:10.783068', '', **0,** 62.0, 18, '2010-10-17 16:28:10.783068')
  SQL (0.1ms)  INSERT INTO "ingredients_recipes" ("created_at", "description", "ingredient_id", "qty", "recipe_id", "updated_at") VALUES ('2010-10-17 16:28:10.784333', '', **0,** 12.0, 18, '2010-10-17 16:28:10.784333')
Redirected to http://0.0.0.0:3000/recipes/18
Completed 302 Found in 190ms

Started GET "/recipes/18" for 127.0.0.1 at 2010-10-17 16:28:10 +0000
  Processing by RecipesController#show as HTML
  Parameters: {"id"=>"18"}
  Recipe Load (0.4ms)  SELECT "recipes".* FROM "recipes" WHERE ("recipes"."id" = 18) LIMIT 1
  IngredientsRecipe Load (0.3ms)  SELECT "ingredients_recipes".* FROM "ingredients_recipes" WHERE ("ingredients_recipes".recipe_id = 18)
  Ingredient Load (0.2ms)  SELECT "ingredients".* FROM "ingredients" WHERE ("ingredients"."id" = 0) LIMIT 1
  CACHE (0.0ms)  SELECT "ingredients".* FROM "ingredients" WHERE ("ingredients"."id" = 0) LIMIT 1
  CACHE (0.0ms)  SELECT "ingredients".* FROM "ingredients" WHERE ("ingredients"."id" = 0) LIMIT 1
  CACHE (0.0ms)  SELECT "ingredients".* FROM "ingredients" WHERE ("ingredients"."id" = 0) LIMIT 1
  CACHE (0.0ms)  SELECT "ingredients".* FROM "ingredients" WHERE ("ingredients"."id" = 0) LIMIT 1
  CACHE (0.0ms)  SELECT "ingredients".* FROM "ingredients" WHERE ("ingredients"."id" = 0) LIMIT 1
Rendered recipes/show.html.erb within layouts/application (112.1ms)
Completed 200 OK in 143ms (Views: 117.4ms | ActiveRecord: 0.9ms)
</code>```

I have made the text bold in the example above where it's writing the text instead of the id from the autocomplete.  I don't have a clue how to set it up to use the id instead.

Help would be very appreciated.

答: you can use :id_element to get the id of selected element

ContentLicense: CC BY-SA 2.5

Body:
I have managed to setup autocomplete field for my rails app.  What I'm trying to do is to have the contents of a lookup table listed and when I have selected the lookup text for few lines I would like the id of the lookup to be saved instead of the text itself.  Here is what I have done:

Recipe model:

class Recipe < ActiveRecord::Base
  # validates :name,  :presence => true
  # validates :directions, :presence => true

  # has_and_belongs_to_many :ingradients

  has_many :ingredients_recipes
  has_many :ingredients, :through => :ingredients_recipes

  accepts_nested_attributes_for :ingredients_recipes, :allow_destroy => true
end

Controller:

class RecipesController < ApplicationController
  # autocomplete :ndb_food_des, :long_desc
  autocomplete :ndb_food_de, :long_desc, :limit => 15

  ... more lines
end

I then use this in the view:

 <% f.fields_for :ingredients_recipes do |rif| %>

              <%= rif.autocomplete_field :ingredient_id, recipes_autocomplete_ndb_food_de_long_desc_path, :width=>1000, :size=>60 %>

<% end %>

I have three detail lines generated when the view opens and what I want to do is write the id of the selected item from the autocomplete.  If I specify the correct field in the view as ingredient_id then I always get 0 in the id in the insert.  If I specify some other field I get the full text of the autocomplete, so it seems that Rails is picking up the correct field and seems to know what to do ... but it's not getting the correct id.

Here is a trace of what the system does:

Started POST "/recipes" for 127.0.0.1 at 2010-10-17 16:28:10 +0000
  Processing by RecipesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"wmNQbsGoiGccrNpmFs7r7D7ZBq//SBe9yrk6SFXP0lc=", "recipe"=>{"name"=>"dfsa", "description"=>"sdfa", "directions"=>"sadf", "ingredients_recipes_attributes"=>{"0"=>{"ingredient_id"=>"CAMPBELL Soup Company, CAMPBELL'S Beef Gravy", "readable_qty"=>"30", "description"=>""}, "1"=>{"ingredient_id"=>"Eclairs, custard-filled with chocolate glaze, prepared from recipe", "readable_qty"=>"60", "description"=>""}, "2"=>{"ingredient_id"=>"DENNY'S, MOONS & STARS chicken nuggets, from kid's menu", "readable_qty"=>"10", "description"=>""}}, "servings"=>"3", "time"=>"3"}, "commit"=>"Create Recipe"}
  SQL (27.9ms)  INSERT INTO "recipes" ("created_at", "description", "directions", "name", "owner", "servings", "time", "updated_at") VALUES ('2010-10-17 16:28:10.686644', 'sdfa', 'sadf', 'dfsa', NULL, 3, 3, '2010-10-17 16:28:10.686644')
  SQL (0.2ms)  INSERT INTO "ingredients_recipes" ("created_at", "description", "ingredient_id", "qty", "recipe_id", "updated_at") VALUES ('2010-10-17 16:28:10.729542', '', **0,** 32.0, 18, '2010-10-17 16:28:10.729542')
  SQL (0.1ms)  INSERT INTO "ingredients_recipes" ("created_at", "description", "ingredient_id", "qty", "recipe_id", "updated_at") VALUES ('2010-10-17 16:28:10.783068', '', **0,** 62.0, 18, '2010-10-17 16:28:10.783068')
  SQL (0.1ms)  INSERT INTO "ingredients_recipes" ("created_at", "description", "ingredient_id", "qty", "recipe_id", "updated_at") VALUES ('2010-10-17 16:28:10.784333', '', **0,** 12.0, 18, '2010-10-17 16:28:10.784333')
Redirected to http://0.0.0.0:3000/recipes/18
Completed 302 Found in 190ms

Started GET "/recipes/18" for 127.0.0.1 at 2010-10-17 16:28:10 +0000
  Processing by RecipesController#show as HTML
  Parameters: {"id"=>"18"}
  Recipe Load (0.4ms)  SELECT "recipes".* FROM "recipes" WHERE ("recipes"."id" = 18) LIMIT 1
  IngredientsRecipe Load (0.3ms)  SELECT "ingredients_recipes".* FROM "ingredients_recipes" WHERE ("ingredients_recipes".recipe_id = 18)
  Ingredient Load (0.2ms)  SELECT "ingredients".* FROM "ingredients" WHERE ("ingredients"."id" = 0) LIMIT 1
  CACHE (0.0ms)  SELECT "ingredients".* FROM "ingredients" WHERE ("ingredients"."id" = 0) LIMIT 1
  CACHE (0.0ms)  SELECT "ingredients".* FROM "ingredients" WHERE ("ingredients"."id" = 0) LIMIT 1
  CACHE (0.0ms)  SELECT "ingredients".* FROM "ingredients" WHERE ("ingredients"."id" = 0) LIMIT 1
  CACHE (0.0ms)  SELECT "ingredients".* FROM "ingredients" WHERE ("ingredients"."id" = 0) LIMIT 1
  CACHE (0.0ms)  SELECT "ingredients".* FROM "ingredients" WHERE ("ingredients"."id" = 0) LIMIT 1
Rendered recipes/show.html.erb within layouts/application (112.1ms)
Completed 200 OK in 143ms (Views: 117.4ms | ActiveRecord: 0.9ms)

I have made the text bold in the example above where it's writing the text instead of the id from the autocomplete.  I don't have a clue how to set it up to use the id instead.

Help would be very appreciated.


问:
Backup configuration page not loading
I upgraded my app service to Standard a few days ago.  However, when I go to the backup configuration page, it never finishes loading.  I just get the dots across the top of the screen forever.</p>

答:
According to your description, I have checked this issue. Per my test, I found I could not configure my backups for my mobile app on Azure Portal as follows:

While for web app, I could configure the backups via Azure Portal as follows:

Then I Use REST to back up and restore App Service apps and Use PowerShell to back up and restore App Service apps to check this issue. After configure the backup for my mobile app, I could see the Configure button on Azure Portal, but when I try to change the backup configuration, I encountered the same issue as you mentioned.

Per my understanding, you could leverage the powershell command Edit-AzureRmWebAppBackupConfiguration for a simple way to edit your Backup Configuration, you could refer to here for more details.

Title: Backup configuration page not loading


问:
Blur issues on drop-down search box in jQuery
I've implemented a search box that acts as a filter. When a user clicks in the search area, a drop-down box is displayed showing all of the possible options. Typing in the search box filters the results. Clicking outside of the box hides the results.

It uses the following HTML/CSS heiarchy

```<code>&ltdiv class="search">
    &ltinput type="text" name="search" value="search" placeholder="search"/>
    &ltdiv class="results">
        &ltdiv class="result">
            Result 1
        &lt/div>
        &ltdiv class="result">
            Result 2
        &lt/div>
        ...
    &lt/div>
&lt/div></code>```

I use jQuery to show/hide the dropdown on focus/blur events

```<code>var searchBar = {
    init : function(){
        $('input[name=search]').focus(searchBar.openSearch);
        $('input[name=search]').blur(searchBar.closeSearch);
        $('div.result').each(function(e){
            $(this).click(draftboardDynamic.selectResult);
        });
    },
    openSearch : function(e){
        $('div.results').show();
    },
    closeSearch : function(e){
        $('div.results').hide();
    },
    selectResult : function(e){
        console.log($(this));
    },
}
$(document).ready(searchBar.init);</code>```

This works quite well and I can open, close, and search (JS removed for clarity) without issue. The only bit I'm having trouble with is selecting results. The blur event seems to trigger before result.click events and the handler is never called.  I can correct this issue by removing the blur binding, however, I can't figure out how to close my drop-down box when the input loses focus.

Any ideas?

答:
Binding and unbinding the blur event on mouse over / mouse out works. For those interested i've created a fiddle to demonstrate this: https://jsfiddle.net/AdamKMorris/uoqvfy2L/

My example uses basic jquery and .bind/.unbind to toggle the search box:

```<code>$("#searchButton").click(function()
{
    $("#searchBar").slideToggle();
    $("#searchText").focus();
}).mouseover(function()
{
    $("#searchText").unbind('blur');
}).mouseout(function()
{
    $("#searchText").bind('blur', function()
    {
        $("#searchBar").slideToggle("fast");
    });
});
</code>```

Body:
I've implemented a search box that acts as a filter. When a user clicks in the search area, a drop-down box is displayed showing all of the possible options. Typing in the search box filters the results. Clicking outside of the box hides the results.

It uses the following HTML/CSS heiarchy

&ltdiv class="search">
    &ltinput type="text" name="search" value="search" placeholder="search"/>
    &ltdiv class="results">
        &ltdiv class="result">
            Result 1
        &lt/div>
        &ltdiv class="result">
            Result 2
        &lt/div>
        ...
    &lt/div>
&lt/div>

I use jQuery to show/hide the dropdown on focus/blur events

var searchBar = {
    init : function(){
        $('input[name=search]').focus(searchBar.openSearch);
        $('input[name=search]').blur(searchBar.closeSearch);
        $('div.result').each(function(e){
            $(this).click(draftboardDynamic.selectResult);
        });
    },
    openSearch : function(e){
        $('div.results').show();
    },
    closeSearch : function(e){
        $('div.results').hide();
    },
    selectResult : function(e){
        console.log($(this));
    },
}
$(document).ready(searchBar.init);

This works quite well and I can open, close, and search (JS removed for clarity) without issue. The only bit I'm having trouble with is selecting results. The blur event seems to trigger before result.click events and the handler is never called.  I can correct this issue by removing the blur binding, however, I can't figure out how to close my drop-down box when the input loses focus.

Any ideas?

Body:
Binding and unbinding the blur event on mouse over / mouse out works. For those interested i've created a fiddle to demonstrate this: https://jsfiddle.net/AdamKMorris/uoqvfy2L/

My example uses basic jquery and .bind/.unbind to toggle the search box:

$("#searchButton").click(function()
{
    $("#searchBar").slideToggle();
    $("#searchText").focus();
}).mouseover(function()
{
    $("#searchText").unbind('blur');
}).mouseout(function()
{
    $("#searchText").bind('blur', function()
    {
        $("#searchBar").slideToggle("fast");
    });
});


问:
PHP to JQuery code conversion [If else]
How can I do it on JQuery? When I click hide, the element will be hidden, same goes for show, the element will be shown. How am I going to do it? Thanks!

```<code><form method="POST">

<button type="submit" name="hidden" >Hide</button>
<button type="submit" name="submit" >Show</button>

</form>

<?php

    if (isset($_POST['hidden']) == true){
        echo '*hidden*';
    } else if ($_POST['']) {
        echo 'shown';
    }

?>
</code>```

答:
I know you asked for JQuery, the best option is straight JS as stated in another post here. But using php, you could define some classes and then change the class value in the tag you wish to control display for upon proper submit of your $_POST value.</p>

```<code><?php

$result = ''; //You could place your default value here or run it through an if/else or switch stmt
if(isset($_POST['show'])){
        $result = 'show';
    } else if ($_POST['hidden']) {
        $result = 'hide';
    } else {
        $result = 'default';
    }

?>

<style>
    .show {
        display:block;
    }
    .hide {
       display:none;
    }
    .default {
       //however you wish your default CSS to act hidden or visible
    }
</style>
<body>
<form method="POST">

<button type="submit" name="hidden" >Hide</button>
<button type="submit" name="show" >Show</button>

</form>

<div id="theElement" class="<?=$result?>"></div>
</body>
</code>```

Title: PHP to JQuery code conversion [If else]

Body:
How can I do it on JQuery? When I click hide, the element will be hidden, same goes for show, the element will be shown. How am I going to do it? Thanks!

<form method="POST">

<button type="submit" name="hidden" >Hide</button>
<button type="submit" name="submit" >Show</button>

</form>

<?php

    if (isset($_POST['hidden']) == true){
        echo '*hidden*';
    } else if ($_POST['']) {
        echo 'shown';
    }

?>

Body:
I know you asked for JQuery, the best option is straight JS as stated in another post here. But using php, you could define some classes and then change the class value in the tag you wish to control display for upon proper submit of your $_POST value.

<?php

$result = ''; //You could place your default value here or run it through an if/else or switch stmt
if(isset($_POST['show'])){
        $result = 'show';
    } else if ($_POST['hidden']) {
        $result = 'hide';
    } else {
        $result = 'default';
    }

?>

<style>
    .show {
        display:block;
    }
    .hide {
       display:none;
    }
    .default {
       //however you wish your default CSS to act hidden or visible
    }
</style>
<body>
<form method="POST">

<button type="submit" name="hidden" >Hide</button>
<button type="submit" name="show" >Show</button>

</form>

<div id="theElement" class="<?=$result?>"></div>
</body>


答:
You missed the below property,

Update css :

```<code>.buttons{
  position:relative;/* Add this property */
}
</code>```

.buttons{
  font-family: arial;
  text-decoration: none;
  padding: 10px 15px;
  background: #000;
  color: #fff;
  border-radius: 3px;
  position:relative;
}

.buttons:after{
 content: "";
    position: absolute;
    top: 0px;
    left: 0px;
    width: 0%;
    height: 100%;
    background-color: rgba(255,255,255,0.4);
    -webkit-transition: none;
    -moz-transition: none;
    -ms-transition: none;
    -o-transition: none;
    transition: none;
    overflow:hidden;
}

.buttons:hover:after{
 width: 120%;
 background-color: rgba(255,255,255,0);
    -webkit-transition: all 0.3s ease-out;
    -moz-transition: all 0.3s ease-out;
    -ms-transition: all 0.3s ease-out;
    -o-transition: all 0.3s ease-out;
    transition: all 0.3s ease-out;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Submit
Submit
Submit
Submit</code>```

Title: The effect affects all the button in css

Body:
You missed the below property,

Update css :

.buttons{
  position:relative;/* Add this property */
}

.buttons{
  font-family: arial;
  text-decoration: none;
  padding: 10px 15px;
  background: #000;
  color: #fff;
  border-radius: 3px;
  position:relative;
}

.buttons:after{
 content: "";
    position: absolute;
    top: 0px;
    left: 0px;
    width: 0%;
    height: 100%;
    background-color: rgba(255,255,255,0.4);
    -webkit-transition: none;
    -moz-transition: none;
    -ms-transition: none;
    -o-transition: none;
    transition: none;
    overflow:hidden;
}

.buttons:hover:after{
 width: 120%;
 background-color: rgba(255,255,255,0);
    -webkit-transition: all 0.3s ease-out;
    -moz-transition: all 0.3s ease-out;
    -ms-transition: all 0.3s ease-out;
    -o-transition: all 0.3s ease-out;
    transition: all 0.3s ease-out;
}

<a href="#" class="buttons">Submit</a>
<a href="#" class="buttons">Submit</a>
<a href="#" class="buttons">Submit</a>
<a href="#" class="buttons">Submit</a>


答:
```<code>num = 1.23456;
</code>```

That sets the value of num to 1.  (The fractional part, .23456, is discarded, since according to the C language rules, an int can't hold fractional values)

```<code>*((float*) &num) = 1.23456;
</code>```

Here you are taking the floating-point value 1.23456 and overwriting the memory location where num lives with that bit-pattern.  I suspect that this is invoking undefined behavior; in any case this can only 'work' on computers where sizeof(float)==sizeof(int), so it's a bad idea to do this.

```<code>printf("num = %.2f \n", *((float*)&num));
</code>```

Here you are pretending that the memory location where num is located is actually the location of a float, and printing out that memory as if it were a floating point value.  It just so happens to do what you expected, on your machine, but you shouldn't rely on it doing so.  By doing tricky casting and type-punning like this, you are effectively "going behind the compiler's back" and bypassing its type-system.  The likely way this will bite you (even on computers where float and int both take up the same number of bytes) is when you enable optimizations and the compiler optimizes your code in some way that assumes that an int and a float can't occupy the same address in memory -- but your code is deliberately breaking that assumption, and thus your program ends up doing something unexpected (like crashing, or printing out the wrong value).

Is the following type cast creates a new variable in memory?

C being a fairly low-level language (by modern standards anyway), it is trying to do what your program told it to do, no more and no less.  In particular, your program told it to treat a pointer-to-int as a pointer-to-float, and the C compiler trusts that you know what you are doing and lets your violate the type system by using casts.  So the program isn't creating a new variable in memory so much as overwriting the bytes of memory where an existing variable (num) is located, in a questionable and unsafe way.

Title: Type casting with pointers in C

Body:
num = 1.23456;

That sets the value of num to 1.  (The fractional part, .23456, is discarded, since according to the C language rules, an int can't hold fractional values)

*((float*) &num) = 1.23456;

Here you are taking the floating-point value 1.23456 and overwriting the memory location where num lives with that bit-pattern.  I suspect that this is invoking undefined behavior; in any case this can only 'work' on computers where sizeof(float)==sizeof(int), so it's a bad idea to do this.

printf("num = %.2f \n", *((float*)&num));

Here you are pretending that the memory location where num is located is actually the location of a float, and printing out that memory as if it were a floating point value.  It just so happens to do what you expected, on your machine, but you shouldn't rely on it doing so.  By doing tricky casting and type-punning like this, you are effectively "going behind the compiler's back" and bypassing its type-system.  The likely way this will bite you (even on computers where float and int both take up the same number of bytes) is when you enable optimizations and the compiler optimizes your code in some way that assumes that an int and a float can't occupy the same address in memory -- but your code is deliberately breaking that assumption, and thus your program ends up doing something unexpected (like crashing, or printing out the wrong value).

Is the following type cast creates a new variable in memory?

C being a fairly low-level language (by modern standards anyway), it is trying to do what your program told it to do, no more and no less.  In particular, your program told it to treat a pointer-to-int as a pointer-to-float, and the C compiler trusts that you know what you are doing and lets your violate the type system by using casts.  So the program isn't creating a new variable in memory so much as overwriting the bytes of memory where an existing variable (num) is located, in a questionable and unsafe way.


问:
All possible permutations of dice rolls
I want to write a program that simulates the following: I have 6 dice, and I roll with some dice every time.

When I don't roll with a die, I just assume that I rolled 0 with that.

I want to list all the possible variations I can get this way. A few examples:

1,2,4,6,0,1

3,5,1,0,0,4

6,6,4,2,0,0
etc.

Any ideas on how to do this?
(I am using Java, but of course, I'm only interested in the general concept.)

答:
Simple Python implementation.

This is when you just print.

```<code>def PrintAllPerms(n, str_):
    if (n == 0):
        print str_
    else:
        for i in ["1","2","3","4","5","6"]:
            str_ = str_ + i
            PrintAllPerms(n-1, str_)
            str_ = str_[:-1]

PrintAllPerms(2,"")
</code>```

This is when you want to return the whole permutation.

```<code>def PrintAllPerms(n, arr, str_):
    if (n == 0):
        arr.append(str_)
        return arr
    else:
        for i in ["1","2","3","4","5","6"]:
            str_ = str_ + i
            arr = PrintAllPerms(n-1,arr,str_)
            str_ = str_[:-1]
        return arr

PrintAllPerms(2,[],"")
</code>```

Title: All possible permutations of dice rolls

Body:
Simple Python implementation.

This is when you just print.

def PrintAllPerms(n, str_):
    if (n == 0):
        print str_
    else:
        for i in ["1","2","3","4","5","6"]:
            str_ = str_ + i
            PrintAllPerms(n-1, str_)
            str_ = str_[:-1]

PrintAllPerms(2,"")

This is when you want to return the whole permutation.

def PrintAllPerms(n, arr, str_):
    if (n == 0):
        arr.append(str_)
        return arr
    else:
        for i in ["1","2","3","4","5","6"]:
            str_ = str_ + i
            arr = PrintAllPerms(n-1,arr,str_)
            str_ = str_[:-1]
        return arr

PrintAllPerms(2,[],"")


问:
Need to make Python / Pika code robust - unstable connection and high latency
I am using Python and the Pika library to publish messages to a RabbitMQ server.  The script below will read the last line of a text file every 30 seconds, then publish the last line to the rabbitmq server.

My problem is that the internet connection is very unstable and has a high latency (600ms - 800ms).  The code will run fine for a couple minutes, but then it starts throwing exceptions. The most recent exception is:

```<code>ERROR:pika.adapters.base_connection:Connection to 64.61.123.233:5672 failed: timeout
WARNING:pika.connection:Could not connect, 2 attempts left

Traceback (most recent call last):
  File "C:\Users\CF-30 ASCI\Desktop\ascii.py", line 50, in <module>
    dmsPublish(csample)
  File "C:\Users\CF-30 ASCI\Desktop\ascii.py", line 27, in dmsPublish
    connection = pika.BlockingConnection(params) # Connect to CloudAMQP
  File "C:\Python27\lib\site-packages\pika\adapters\blocking_connection.py", line 339, in __init__
    self._process_io_for_connection_setup()
  File "C:\Python27\lib\site-packages\pika\adapters\blocking_connection.py", line 374, in _process_io_for_connection_setup
    self._open_error_result.is_ready)
  File "C:\Python27\lib\site-packages\pika\adapters\blocking_connection.py", line 410, in _flush_output
    self._impl.ioloop.poll()
  File "C:\Python27\lib\site-packages\pika\adapters\select_connection.py", line 400, in poll
    self.get_next_deadline())
error: (10022, 'An invalid argument was supplied')
</code>```

This exception was thrown after about 5 minutes of running.  I am assuming it is because the internet connection dropped or became unstable.  I would love this script to continue running if there is a failure.  It is OK if I do not receive some of the messages.  I would be happy if 75% made it through given the poor quality of the link.

```<code>import os
import csv
import time
import pika
import logging
import datetime

logging.basicConfig()

def getLastFile(filename):
    distance = 1024
    with open(filename,'rb') as f:
        lastline = f.readlines()[-1]
    return lastline

def dmsPublish(message):

    url = os.environ.get('CLOUDAMQP_URL', 'amqp://guest:guest@64.61.123.233/%2f?connection_attempts=3&heartbeat_interval=3600')
    params = pika.URLParameters(url)
    params.socket_timeout = 5
    params.connection_attempts = 3
    params.retry_delay = 3
    print time.ctime() + " [x] Connecting to RabbitMQ server"
    connection = pika.BlockingConnection(params) # Connect to CloudAMQP
    channel = connection.channel() # start a channel
    channel.queue_declare(queue='LastLine') # Declare a queue
    channel.basic_publish(exchange='', routing_key='LastLine', body=message)
    print time.ctime() + " [x] Message sent to rabbitMQ"
    connection.close()

loop = 1
while True:
        lastline = getLastFile("teraterm.log")
        sampletime = datetime.datetime.utcnow().isoformat() + ","
        csample = sampletime + lastline
#        print " [x] Most Recent Sample: " + csample
        try:
            dmsPublish(csample)
        except pika.exceptions.ProbableAccessDeniedError:
            print " [!] Auth error... trying again."
        print time.ctime() + " [x] Sleeping 30 seconds ....."
        time.sleep(30)
</code>```

答:
I am no expert related to python, in fact, I am just starting to learn it, but
why don't you use a try catch inside the dmsPublish method, surrounding the connection code?

```<code>connection = pika.BlockingConnection(params)
</code>```

I know it is not a great workaround, but perhaps you can even place a counter to avoid an infinite loop.

This is mere guessing, if you have tried that just disregard.

Body:
I am using Python and the Pika library to publish messages to a RabbitMQ server.  The script below will read the last line of a text file every 30 seconds, then publish the last line to the rabbitmq server.

My problem is that the internet connection is very unstable and has a high latency (600ms - 800ms).  The code will run fine for a couple minutes, but then it starts throwing exceptions. The most recent exception is:

ERROR:pika.adapters.base_connection:Connection to 64.61.123.233:5672 failed: timeout
WARNING:pika.connection:Could not connect, 2 attempts left

Traceback (most recent call last):
  File "C:\Users\CF-30 ASCI\Desktop\ascii.py", line 50, in <module>
    dmsPublish(csample)
  File "C:\Users\CF-30 ASCI\Desktop\ascii.py", line 27, in dmsPublish
    connection = pika.BlockingConnection(params) # Connect to CloudAMQP
  File "C:\Python27\lib\site-packages\pika\adapters\blocking_connection.py", line 339, in __init__
    self._process_io_for_connection_setup()
  File "C:\Python27\lib\site-packages\pika\adapters\blocking_connection.py", line 374, in _process_io_for_connection_setup
    self._open_error_result.is_ready)
  File "C:\Python27\lib\site-packages\pika\adapters\blocking_connection.py", line 410, in _flush_output
    self._impl.ioloop.poll()
  File "C:\Python27\lib\site-packages\pika\adapters\select_connection.py", line 400, in poll
    self.get_next_deadline())
error: (10022, 'An invalid argument was supplied')

This exception was thrown after about 5 minutes of running.  I am assuming it is because the internet connection dropped or became unstable.  I would love this script to continue running if there is a failure.  It is OK if I do not receive some of the messages.  I would be happy if 75% made it through given the poor quality of the link.

import os
import csv
import time
import pika
import logging
import datetime

logging.basicConfig()

def getLastFile(filename):
    distance = 1024
    with open(filename,'rb') as f:
        lastline = f.readlines()[-1]
    return lastline

def dmsPublish(message):

    url = os.environ.get('CLOUDAMQP_URL', 'amqp://guest:guest@64.61.123.233/%2f?connection_attempts=3&heartbeat_interval=3600')
    params = pika.URLParameters(url)
    params.socket_timeout = 5
    params.connection_attempts = 3
    params.retry_delay = 3
    print time.ctime() + " [x] Connecting to RabbitMQ server"
    connection = pika.BlockingConnection(params) # Connect to CloudAMQP
    channel = connection.channel() # start a channel
    channel.queue_declare(queue='LastLine') # Declare a queue
    channel.basic_publish(exchange='', routing_key='LastLine', body=message)
    print time.ctime() + " [x] Message sent to rabbitMQ"
    connection.close()

loop = 1
while True:
        lastline = getLastFile("teraterm.log")
        sampletime = datetime.datetime.utcnow().isoformat() + ","
        csample = sampletime + lastline
#        print " [x] Most Recent Sample: " + csample
        try:
            dmsPublish(csample)
        except pika.exceptions.ProbableAccessDeniedError:
            print " [!] Auth error... trying again."
        print time.ctime() + " [x] Sleeping 30 seconds ....."
        time.sleep(30)

Body:
I am no expert related to python, in fact, I am just starting to learn it, but
why don't you use a try catch inside the dmsPublish method, surrounding the connection code?

connection = pika.BlockingConnection(params)

I know it is not a great workaround, but perhaps you can even place a counter to avoid an infinite loop.

This is mere guessing, if you have tried that just disregard.


问:
Filebeat kafka output use filename as key
I want to use filebeat 5.4.0 to ship log to kafka. My logs are all docker container logs, in /var/lib/docker/containers/*/${container_name}.log, or soft link in /var/log/containers/${appname}-${container_name}.log.

I want to save all app logs to one topic in kafka. And my requirements are:

Make sure the log from the same container go to the same partition
in order.

The msg must contains the appname and the container_name where it comes out.

And I'm facing two problems.

How to get log from a soft link?

How to get the appname and container_name from the filename, and set to key of output.kafka?

答:
Beats are supposed to be lightweight, if you want to do more filtering then that is what logstash is for. You can use filebeats+logstash+kafka. Before sending to kafka, use logstash's split filter.
Also you can use 'type' property in filebeats to map the log paths like below
...
paths:

"/var/log/container/${appname}-${container_name}"

document_type: log
output.kafka:
    ...
    key:'%{[type]}'
...


问:
SSIS error: delimiter for column "columnX" is not found
This question was asked here before but the solutions proposed don't seem to be working for me.

I'm trying to import a text file pipe delimited text qualifier ". The SSIS package is returning the error message

delimiter for column "columnX" is not found

where column X is the last field in the file.

In the connection manager advanced tab, I have set up the column delimiter for columnX to {LF} while all the other fields are set to vertical |.

I have verified the file and there are no missing fields. There are some null values but all the fields are there.

I can't point out what is causing this. Your help would be greatly appreciated.

答: Do not set the last column delimiter to LF. If the file row ends with {LF} (which I believe you have verified) then set the header row delimiter to {LF}:


问:
I'm trying to write a recursive static method with a helper in order to reverse a string. Why am I getting "stack overflow?"
So as the title says, I want to write a static method in Java that takes a String (like "hello!") and reverses it using a helper recursive method. However, I get stack overflow errors. My code is:

```<code>  public static String reverse2(String text){
    return reverseHelp(text, "", text.length()-1);
  }

  public static String reverseHelp(String text, String newString, int index) {
    if(index <= 0){
      return newString;
    }
    else
    {
      index = text.length()-1;
      return newString = text.charAt(index) + reverseHelp(text, newString, index - 1);
    }

  }
</code>```

What I'm trying to do is append the last character to the new string. How can I get this to work?

答:
```<code> public static String reverse2(String text){
    return reverseHelp(text, "", text.length()-1);
  }

  public static String reverseHelp(String text, String newString, int index){
    if(index < 0){
      return newString;
    }
    else
    {
      index = text.length()-1;
      return newString = text.charAt(index) + reverseHelp(text.substring(0,index), newString, index - 1);
    }
  }
</code>```

2 errors, the first is reverseHelp(text.substring(0,index), newString, index - 1); you need to recurse over a smaller string or else it won't terminate.

The second is         if(index < 0){ otherwise it misses the first/last character.

However there are still some code quality issues.

You don't need to assign on the last statement, and you also no longer need to pass the index through, as the string is changing.

Alternately, you could not substring, if you don't assign a new value to index each time.

Body:
So as the title says, I want to write a static method in Java that takes a String (like "hello!") and reverses it using a helper recursive method. However, I get stack overflow errors. My code is:

  public static String reverse2(String text){
    return reverseHelp(text, "", text.length()-1);
  }

  public static String reverseHelp(String text, String newString, int index) {
    if(index <= 0){
      return newString;
    }
    else
    {
      index = text.length()-1;
      return newString = text.charAt(index) + reverseHelp(text, newString, index - 1);
    }

  }

What I'm trying to do is append the last character to the new string. How can I get this to work?

Body:
 public static String reverse2(String text){
    return reverseHelp(text, "", text.length()-1);
  }

  public static String reverseHelp(String text, String newString, int index){
    if(index < 0){
      return newString;
    }
    else
    {
      index = text.length()-1;
      return newString = text.charAt(index) + reverseHelp(text.substring(0,index), newString, index - 1);
    }
  }

2 errors, the first is reverseHelp(text.substring(0,index), newString, index - 1); you need to recurse over a smaller string or else it won't terminate.

The second is         if(index < 0){ otherwise it misses the first/last character.

However there are still some code quality issues.

You don't need to assign on the last statement, and you also no longer need to pass the index through, as the string is changing.

Alternately, you could not substring, if you don't assign a new value to index each time.


问:
what is the actual use of interface in java?

Possible Duplicates:

  Abstract class and Interface class?

  Java: interface / abstract classes / abstract method

In Java, whatever use of interface is fulfilled by abstract class. I know one advantage of interfaces is that if we implement an interface then we can also extend another class. Is there any other use or advantage of interface in Java?

答:
Multiple interfaces can be implemented, but only one class can be extended. A completely abstract class is a lot like an interface, except that an abstract class can contain variables.

It really depends on what you need. C++ allows you to extend as many classes you want, and it turns into a bit of a disaster. The nice thing about having only one superclass is that there's only ever one other set of implementations that you have to worry about (even if the parent has a parent, the parent's particular combination becomes your parent...)

Interfaces allow one object to play many roles, but they don't allow code reuse.

It's really to simplify thinking about inheritance. On the balance, I think they got it right.


问:
How can I test if an object inherits or is a member of a generic class?
Suppose I have a class class C<T>.

I want to write a function f(_ a: Any) -> Bool, which returns true when a is a member of class inheriting from C (or is a C itself). I don't care about the specialization: passing C<Int>, C<Double>, C<Whatever> should all return true.

It seems like I should be able to just write a is C or a as? C != nil as the body of that function, however, these both don't compile in a playground; swiftc complains that "generic parameter 'T' could not be inferred in cast to 'C<_>'". If I write f inside of C as an instance method, C is implicitly C<T>, and so writing let c = C<Int>(); c.f(C<Double>()) returns false.

I can work around this by writing a protocol P, which C conforms to, and then test for that but I don't consider that a good solution; it's just a hack.

Is there any way to do this?

Here's all the code I wrote to try this:

```<code>class C<T> {
  func test(_ a: Any) -> (Bool, Bool) {
    return (type(of: a) == C.self, a is C)
  }
}

class D: C<Double> { }

let d = D()

func f(_ a: Any) -> Bool {
  return a is C // generic parameter 'T' could not be inferred in cast to 'C<_>'
}

d.test(C<Int>()) // false, false

// bad solution

protocol P { }

extension C: P { }

d is P // true
</code>```

答: Writing a protocol that specifies what you are expecting for this test is not at all a hack; it's exactly how Swift should be used. (What you are asking is indeed impossible, and purposefully so.) Write that protocol, but not as an empty hack; fill it with what you are testing for and then view it as a beautiful part of your code's structure!</p>

Body:
Suppose I have a class class C<T>.

I want to write a function f(_ a: Any) -> Bool, which returns true when a is a member of class inheriting from C (or is a C itself). I don't care about the specialization: passing C<Int>, C<Double>, C<Whatever> should all return true.

It seems like I should be able to just write a is C or a as? C != nil as the body of that function, however, these both don't compile in a playground; swiftc complains that "generic parameter 'T' could not be inferred in cast to 'C<_>'". If I write f inside of C as an instance method, C is implicitly C<T>, and so writing let c = C<Int>(); c.f(C<Double>()) returns false.

I can work around this by writing a protocol P, which C conforms to, and then test for that but I don't consider that a good solution; it's just a hack.

Is there any way to do this?

Here's all the code I wrote to try this:

class C<T> {
  func test(_ a: Any) -> (Bool, Bool) {
    return (type(of: a) == C.self, a is C)
  }
}

class D: C<Double> { }

let d = D()

func f(_ a: Any) -> Bool {
  return a is C // generic parameter 'T' could not be inferred in cast to 'C<_>'
}

d.test(C<Int>()) // false, false

// bad solution

protocol P { }

extension C: P { }

d is P // true


问:
AttributeError: 'NoneType' object has no attribute 'append' (recursion function)
I'm trying to get all possible permutations of dice rolls. Below is my code.

```<code>def PrintAllPerms(n, arr, str_):
    if (n == 0):
        print str_
        arr.append(str_)
        return arr
    else:
        for i in ["1","2","3","4","5","6"]:
            str_ = str_ + i
            arr = PrintAllPerms(n-1,arr,str_)
            str_ = str_[:-1]

PrintAllPerms(2,[],"")
</code>```

But I got following error after printing only this much.

```<code>PrintAllPerms(2,[],"")

11
12
13
14
15
16
21

<ipython-input-7-d03e70079ce2> in PrintAllPerms(n, arr, str_)
      2     if (n == 0):
      3         print str_
----> 4         arr.append(str_)
      5         return arr
      6     else:

AttributeError: 'NoneType' object has no attribute 'append'
</code>```

Why does it print until 2,1 then?

And what is the correct to way to deal with this?

答:
This is due to the following line:

```<code>arr = PrintAllPerms(n-1,arr,str_)
</code>```

Your PrintAllPerms function doesn't return anything if it takes the else path, and thus is treated as if it's returning None. So arr gets set to None.

Body:
I'm trying to get all possible permutations of dice rolls. Below is my code.

def PrintAllPerms(n, arr, str_):
    if (n == 0):
        print str_
        arr.append(str_)
        return arr
    else:
        for i in ["1","2","3","4","5","6"]:
            str_ = str_ + i
            arr = PrintAllPerms(n-1,arr,str_)
            str_ = str_[:-1]

PrintAllPerms(2,[],"")

But I got following error after printing only this much.

PrintAllPerms(2,[],"")

11
12
13
14
15
16
21

<ipython-input-7-d03e70079ce2> in PrintAllPerms(n, arr, str_)
      2     if (n == 0):
      3         print str_
----> 4         arr.append(str_)
      5         return arr
      6     else:

AttributeError: 'NoneType' object has no attribute 'append'

Why does it print until 2,1 then?

And what is the correct to way to deal with this?

Body:
This is due to the following line:

arr = PrintAllPerms(n-1,arr,str_)

Your PrintAllPerms function doesn't return anything if it takes the else path, and thus is treated as if it's returning None. So arr gets set to None.


问:
ActiveModel::MissingAttributeError: can't write unknown attribute `attendee_id`
I am trying to create an association between a User model and an Attendance model in which an attendee_id references a user. The association is a many to many relationship between users and concerts. The join table attendances has two fields
:attendee and :concert.

seed.rb file:

```<code>require 'faker'

Concert.destroy_all
User.destroy_all
Attendance.destroy_all

15.times do
  Concert.create(band: Faker::RockBand.name, venue: "#{Faker::LordOfTheRings.location}", date: Faker::Date.forward(rand(30)), start_time: "8:00 PM")
end

5.times do |number|
  User.create(first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: "#{number}@email.com", password: "password")
end

concerts = Concert.all
users = User.all

15.times do
  Attendance.create(attendee: users.sample, concert: concerts.sample)
end
</code>```

Here are the models:

```<code>class Attendance < ApplicationRecord
  belongs_to :attendee, class_name: "User"
  belongs_to :concert
end
class Concert < ApplicationRecord
  validates :band, :venue, :date, :start_time, presence: true
  has_many :attendances
  has_many :attendees, through: :attendances
end
class User < ApplicationRecord
  validates :first_name, :last_name, :email, presence: true
  validates_format_of :email, with: /@/
  has_secure_password
  has_many :attendances, foreign_key: :attendee_id
  has_many :concerts, through: :attendances
end
</code>```

Here are the migrations:

```<code>class CreateAttendances < ActiveRecord::Migration[5.0]
  def change
    create_table :attendances do |t|
      t.references :attendee
      t.references :concert, index: true

      t.timestamps
    end
  end
end

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
      t.string :password_digest

      t.timestamps
    end
  end
end

class CreateConcerts < ActiveRecord::Migration[5.0]
  def change
    create_table :concerts do |t|
      t.string :band
      t.string :venue
      t.datetime :date
      t.time :start_time

      t.timestamps
    end
  end
end
</code>```

答: I run bundle exec rake db:drop and then I created the database bundle exec rake db:create and bundle exec rake db:migrate I was then able to seed the database.

Body:
I am trying to create an association between a User model and an Attendance model in which an attendee_id references a user. The association is a many to many relationship between users and concerts. The join table attendances has two fields
:attendee and :concert.

seed.rb file:

require 'faker'

Concert.destroy_all
User.destroy_all
Attendance.destroy_all

15.times do
  Concert.create(band: Faker::RockBand.name, venue: "#{Faker::LordOfTheRings.location}", date: Faker::Date.forward(rand(30)), start_time: "8:00 PM")
end

5.times do |number|
  User.create(first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: "#{number}@email.com", password: "password")
end

concerts = Concert.all
users = User.all

15.times do
  Attendance.create(attendee: users.sample, concert: concerts.sample)
end

Here are the models:

class Attendance < ApplicationRecord
  belongs_to :attendee, class_name: "User"
  belongs_to :concert
end
class Concert < ApplicationRecord
  validates :band, :venue, :date, :start_time, presence: true
  has_many :attendances
  has_many :attendees, through: :attendances
end
class User < ApplicationRecord
  validates :first_name, :last_name, :email, presence: true
  validates_format_of :email, with: /@/
  has_secure_password
  has_many :attendances, foreign_key: :attendee_id
  has_many :concerts, through: :attendances
end

Here are the migrations:

class CreateAttendances < ActiveRecord::Migration[5.0]
  def change
    create_table :attendances do |t|
      t.references :attendee
      t.references :concert, index: true

      t.timestamps
    end
  end
end

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
      t.string :password_digest

      t.timestamps
    end
  end
end

class CreateConcerts < ActiveRecord::Migration[5.0]
  def change
    create_table :concerts do |t|
      t.string :band
      t.string :venue
      t.datetime :date
      t.time :start_time

      t.timestamps
    end
  end
end


问:
p.update is a function error in my multiplayer game
I have been making a multiplayer html5 game and when i implemented pipe code i am getting error p.update is not a function. below is my code.

server.js

```<code>var express = require('express');
var http = require('http');
var path = require('path');
var socketIO = require('socket.io');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
app.set('port', 5000);
app.use('/static', express.static(__dirname + '/static'));

// Routing
app.get('/', function(request, response) {
  response.sendFile(path.join(__dirname, '/static/index.html'));
});

// Starts the server
server.listen(5000, function() {
  console.log('Starting server on port 5000');
});

// Game vars
var
width,
height,

frames = 0,
clients = {},
pipes = [];

// Bird class
function Bird() {
    this.x = 64;
    this.y = height/2;
    this.r = 32;
    this.gravity = 0.5;
    this.velocity = 0;
    this.lift = 10;
    this.time = new Date().getTime();

    this.up = function() {
        this.velocity = -this.lift;
        this.velocity = this.velocity * 0.9;
    }

    this.update = function() {
        this.velocity += this.gravity;
        this.y += this.velocity;
        if (this.y > height) {
            this.y = height;
            this.velocity = -(this.velocity * 0.8);
        }
        if (this.y < 0) {
            this.y = 0;
            this.velocity = 0;
        }
    }
}

function Pipe() {
    this.x = width;
    this.y = 0;
    this.width = 20;
    this.speed = 1;
    this.topPipe = Math.random()*height/2;
    this.bottomPipe = Math.random()*height/2;
    this.highlight = null;

    this.update = function () {
        this.x -= this.speed;
    }
}

// Updating
function update() {
    frames++;

    if(frames % 100 == 0) {
        pipes.push(new Pipe());
    }

    for(var key in clients) {
        var b = clients[key];
        b.update();
    }

    io.sockets.emit('update', {
        birds: clients,
        pipes: pipes
    });
}

io.on("connection", function(socket) {
    socket.on('new-client', function(data) {
        width = data.width;
        height = data.height;
        clients[socket.id] = new Bird();
    });
    socket.on('disconnect', function() {
        delete clients[socket.id];
    });
});

setInterval(update, 1000/60);
</code>```

client.js

```<code>// Vars
var

socket = io(),
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
width = canvas.width = innerWidth,
height = canvas.height = innerHeight,
time = new Date().getTime();

var birds = {
    _birds: null,

    update: function(data) {
        this._birds = data;
    },

    draw: function() {
        for(var key in this._birds) {
            var b = this._birds[key];
            var newX = b.x+((b.time-time)*1/(1000/60));

            ctx.fillStyle = socket.id == key ? "#fff" : "#f00";
            ctx.beginPath();
            ctx.arc(newX, b.y, b.r, 0, Math.PI*2);
            ctx.fill();
            ctx.closePath();
        }
    }
};

var pipes = {
    _pipes: null,

    update: function(data) {
        this._pipes = data;

        for(var key in this._pipes) {
            var p = this._pipes[key];
            p.update();

            if(p.x > -p.width) {
                delete this._pipes[key];
            }
        }
    },

    draw: function() {
        for(var key in this._pipes) {
            var p = this._pipes[key];

            ctx.fillStyle = "#000";
            ctx.fillRect(p.x, p.y, p.width, p.topPipe);
            ctx.fillRect(p.x, height-p.bottomPipe, p.width, p.bottomPipe);
        }
    }
}

// New client
socket.emit("new-client", {
    width: width,
    height: height
});

// Draw
socket.on('update', function(data) {
    birds.update(data.birds);
    pipes.update(data.pipes);

    ctx.fillStyle = "#eee";
    ctx.fillRect(0, 0, width, height);

    birds.draw();
    pipes.draw();
});
</code>```

I am getting error on the client side in the "pipes" object.

答:
When you do

```<code>   socket.on('update', function(data) {
    birds.update(data.birds);
    pipes.update(data.pipes);
</code>```

data.birds and data.pipes is an serialised array of JSON object, it does not retain its function properties (such as update) or prototype methods.

I suggest making the Pipe class accessible to both client and server, and turn update into a method. Unless you need to re-assign, using functions as object properties is not a good idea (for example, they take more space rather than using prototype methods).

```<code>Pipe.prototype.update = function () {
    this.x -= this.speed;
}
// To apply the function
for(var key in this._pipes) {
    var p = this._pipes[key];
    Pipe.prototype.update.call(p); // Equivalent to p.update()
    if(p.x > -p.width) {
      delete this._pipes[key];
    }
}
</code>```

Then you can call update even on serialised objects by using apply. Of course, it's better if you have a function that deserialise data from socket.io into Pipe instance.

Body:
I have been making a multiplayer html5 game and when i implemented pipe code i am getting error p.update is not a function. below is my code.

server.js

var express = require('express');
var http = require('http');
var path = require('path');
var socketIO = require('socket.io');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
app.set('port', 5000);
app.use('/static', express.static(__dirname + '/static'));

// Routing
app.get('/', function(request, response) {
  response.sendFile(path.join(__dirname, '/static/index.html'));
});

// Starts the server
server.listen(5000, function() {
  console.log('Starting server on port 5000');
});

// Game vars
var
width,
height,

frames = 0,
clients = {},
pipes = [];

// Bird class
function Bird() {
    this.x = 64;
    this.y = height/2;
    this.r = 32;
    this.gravity = 0.5;
    this.velocity = 0;
    this.lift = 10;
    this.time = new Date().getTime();

    this.up = function() {
        this.velocity = -this.lift;
        this.velocity = this.velocity * 0.9;
    }

    this.update = function() {
        this.velocity += this.gravity;
        this.y += this.velocity;
        if (this.y > height) {
            this.y = height;
            this.velocity = -(this.velocity * 0.8);
        }
        if (this.y < 0) {
            this.y = 0;
            this.velocity = 0;
        }
    }
}

function Pipe() {
    this.x = width;
    this.y = 0;
    this.width = 20;
    this.speed = 1;
    this.topPipe = Math.random()*height/2;
    this.bottomPipe = Math.random()*height/2;
    this.highlight = null;

    this.update = function () {
        this.x -= this.speed;
    }
}

// Updating
function update() {
    frames++;

    if(frames % 100 == 0) {
        pipes.push(new Pipe());
    }

    for(var key in clients) {
        var b = clients[key];
        b.update();
    }

    io.sockets.emit('update', {
        birds: clients,
        pipes: pipes
    });
}

io.on("connection", function(socket) {
    socket.on('new-client', function(data) {
        width = data.width;
        height = data.height;
        clients[socket.id] = new Bird();
    });
    socket.on('disconnect', function() {
        delete clients[socket.id];
    });
});

setInterval(update, 1000/60);

client.js

// Vars
var

socket = io(),
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
width = canvas.width = innerWidth,
height = canvas.height = innerHeight,
time = new Date().getTime();

var birds = {
    _birds: null,

    update: function(data) {
        this._birds = data;
    },

    draw: function() {
        for(var key in this._birds) {
            var b = this._birds[key];
            var newX = b.x+((b.time-time)*1/(1000/60));

            ctx.fillStyle = socket.id == key ? "#fff" : "#f00";
            ctx.beginPath();
            ctx.arc(newX, b.y, b.r, 0, Math.PI*2);
            ctx.fill();
            ctx.closePath();
        }
    }
};

var pipes = {
    _pipes: null,

    update: function(data) {
        this._pipes = data;

        for(var key in this._pipes) {
            var p = this._pipes[key];
            p.update();

            if(p.x > -p.width) {
                delete this._pipes[key];
            }
        }
    },

    draw: function() {
        for(var key in this._pipes) {
            var p = this._pipes[key];

            ctx.fillStyle = "#000";
            ctx.fillRect(p.x, p.y, p.width, p.topPipe);
            ctx.fillRect(p.x, height-p.bottomPipe, p.width, p.bottomPipe);
        }
    }
}

// New client
socket.emit("new-client", {
    width: width,
    height: height
});

// Draw
socket.on('update', function(data) {
    birds.update(data.birds);
    pipes.update(data.pipes);

    ctx.fillStyle = "#eee";
    ctx.fillRect(0, 0, width, height);

    birds.draw();
    pipes.draw();
});

I am getting error on the client side in the "pipes" object.

Body:
When you do

   socket.on('update', function(data) {
    birds.update(data.birds);
    pipes.update(data.pipes);

data.birds and data.pipes is an serialised array of JSON object, it does not retain its function properties (such as update) or prototype methods.

I suggest making the Pipe class accessible to both client and server, and turn update into a method. Unless you need to re-assign, using functions as object properties is not a good idea (for example, they take more space rather than using prototype methods).

Pipe.prototype.update = function () {
    this.x -= this.speed;
}
// To apply the function
for(var key in this._pipes) {
    var p = this._pipes[key];
    Pipe.prototype.update.call(p); // Equivalent to p.update()
    if(p.x > -p.width) {
      delete this._pipes[key];
    }
}

Then you can call update even on serialised objects by using apply. Of course, it's better if you have a function that deserialise data from socket.io into Pipe instance.


答:
ultimate, this worked out:</p>

```<code>  public static String reverse2(String text){
    return reverseHelp(text, "", text.length()-1);
  }

  public static String reverseHelp(String text, String newString, int index){
    if(index < 0){
      return newString;
    }
    else{
     return newString = text.charAt(index) + reverseHelp(text, newString, index - 1);
    }
  }
</code>```

Title: I'm trying to write a recursive static method with a helper in order to reverse a string. Why am I getting "stack overflow?"

Body:
ultimate, this worked out:

  public static String reverse2(String text){
    return reverseHelp(text, "", text.length()-1);
  }

  public static String reverseHelp(String text, String newString, int index){
    if(index < 0){
      return newString;
    }
    else{
     return newString = text.charAt(index) + reverseHelp(text, newString, index - 1);
    }
  }


问:
Start, Pause and Stop a Node.js process/loop
I'm in the process of building a bot that basically fetches images based on a search query(simple string), this bot needs to run 24/7, however multiple bots must be 'spawned' for different accounts, I already have the bot done, it basically takes in a config file and starts looping, however what would be the best approach to pause and stop this process?

I have looked into Node's spawn child functions, i have looked into RxJs's scheduler, but I am not sure which is the best bet, to approach something like this. Any insight would be helpful, thank you!

答:
According to your description, you need to stop the whole process tree. The solution depends on which platform your code is running. On windows, we can run taskkill command to kill them, on linux/macos, we can utilize tree-kill package from npm. And first of all, you need to get the PID of the process to be killed. Here below is an implementation for reference:

```<code>const procTreeKill = require('tree-kill')
const cp = require('child_process')

const onMacOS = () => {
    return process.platform === 'darwin'
}

const onLinux = () => {
    return process.platform === 'linux'
}

const onWindows = () => {
    return process.platform === 'win32'
}

function kill(pid) {
    return new Promise(function (resolve, reject) {
        if (onWindows()) {
            try {
                const options = {
                    stdio: [
                        'pipe',
                        'pipe',
                        'ignore',
                    ]
                }

                cp.execFile(
                    'taskkill',
                    ['/T', '/F', '/PID', pid.toString()],
                    options,
                    (error, stdout, stderr) => {
                        if (error) {
                            return reject(error)
                        }

                        return resolve(true)
                    }
                )
            } catch (error) {
                return reject(error)
            }
        } else if (onLinux() || onMacOS()) {
            try {
                procTreeKill(pid, 'SIGKILL', function (error) {
                    if (error) {
                        return reject(error)
                    }

                    return resolve(true)
                })
            } catch (error) {
                return reject(error)
            }
        } else {
            return reject(new Error('Platform unsupported.'))
        }
    })
}
</code>```

You can use this function to kill the all bot process tree when you pass the PID of the 24/7 running process(the parent process of your bots), or you can just kill a worker process with its PID passed.

Body:
According to your description, you need to stop the whole process tree. The solution depends on which platform your code is running. On windows, we can run taskkill command to kill them, on linux/macos, we can utilize tree-kill package from npm. And first of all, you need to get the PID of the process to be killed. Here below is an implementation for reference:

const procTreeKill = require('tree-kill')
const cp = require('child_process')

const onMacOS = () => {
    return process.platform === 'darwin'
}

const onLinux = () => {
    return process.platform === 'linux'
}

const onWindows = () => {
    return process.platform === 'win32'
}

function kill(pid) {
    return new Promise(function (resolve, reject) {
        if (onWindows()) {
            try {
                const options = {
                    stdio: [
                        'pipe',
                        'pipe',
                        'ignore',
                    ]
                }

                cp.execFile(
                    'taskkill',
                    ['/T', '/F', '/PID', pid.toString()],
                    options,
                    (error, stdout, stderr) => {
                        if (error) {
                            return reject(error)
                        }

                        return resolve(true)
                    }
                )
            } catch (error) {
                return reject(error)
            }
        } else if (onLinux() || onMacOS()) {
            try {
                procTreeKill(pid, 'SIGKILL', function (error) {
                    if (error) {
                        return reject(error)
                    }

                    return resolve(true)
                })
            } catch (error) {
                return reject(error)
            }
        } else {
            return reject(new Error('Platform unsupported.'))
        }
    })
}

You can use this function to kill the all bot process tree when you pass the PID of the 24/7 running process(the parent process of your bots), or you can just kill a worker process with its PID passed.


问:
What is the best way of showing progress on an Ajax call?
I have an Ajax call that updates 5,000 records in a database so this takes a lot of time.  I have an Ajax "Loading image" showing that something is happening, but I am looking for a better way to show "Updating  50 of 5000 . . .", "Updating 200 of 5000", or something like that.

What is the best way to do something like this in Ajax / jQuery without doing 5000 different posts?

答:
You could update the response buffer with a progress, flushing your response buffer periodically from the server.

But you may have trouble reading a request before it's complete via xhttpr. You might be able to make your request via an iframe, and have that load in progress via 'http streaming'.

But even that can be sketchy. HTTP is not the meant to transfer things piecemeal/fragmented. Like others point out, it would be best to make a separate subsequent calls to get the status of the operation.


问:
Create an AJAX Powered Data Driven App
When I type in an artist and I click the button, I should get a nice list of their songs in a format that is aesthetically pleasing.

My error is:
  Nothing is returns whenever I press the button, I don't know why that is.

HTML File

```<code><!DOCTYPE html>
<html>
<head>
    <title>Songs</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet"     href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
    </script>
    <script
    src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
    </script>
    <script src="ajaxfunctions.js"></script>
</head>
<body>
    <div class="container">
        <h2>Songs </h2>
        <br/>
        <p>Try entering an artist to find their songs</p>
        <div>
            <div id="musicbox" class="control-group">
                <label for="songs">artistr</label>
                <input type="text" name="songs" id="songs" placeholder="Type an artist to their songs" />
            </div>
        </div>
        <br />
        <div>
            <button class='btn btn-success btn-large' onclick="Music('songs')">Find Songs</button>
        </div>
        <br />
        <div>
        </div>
    </div>
</body>
</html>
</code>```

JS File

```<code>function Music(songs) {
    var yourmusic = document.getElementById(songs).value;
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function () {
        if (this.readyState === 4) {
            if(this.status === 200) {
                displayMusic(this.responseText);
            } else if (this.status === 404){
                displayMusic('{ "songs" : "none" }');
            } else {
                console.log("We have a problem: " + this.status);
            }
        } else {
        }
    };
    var url = " https://api.mixcloud.com/discover/funk/";
    httpRequest.open("GET", url, true);
    httpRequest.send();
}

function displayMusic(data){
    var music = JSON.parse(data);
    if(music.songs === "none") {
        document.getElementById("songs").className = "alert alert-warning";\
        document.getElementById("songs").innerHTML ="there are no songs for this artist"
        document.getElementById("songs").innerHTML = "The songs are" + music;
    } else {
        document.getElementById("songs").className = "alert alert-success";
        document.getElementById("songs").innerHTML = "The songs are" + music;
    }
}
</code>```

答:
You check code:</p>

```<code>document.getElementById("music") // element id "music" not exist
</code>```

Title: Create an AJAX Powered Data Driven App

Body:
When I type in an artist and I click the button, I should get a nice list of their songs in a format that is aesthetically pleasing.

My error is:
  Nothing is returns whenever I press the button, I don't know why that is.

HTML File

<!DOCTYPE html>

    <title>Songs</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet"     href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Songs

Try entering an artist to find their songs

                artistr
                <input type="text" name="songs" id="songs" placeholder="Type an artist to their songs" />

            <button class='btn btn-success btn-large' onclick="Music('songs')">Find Songs</button>

JS File

function Music(songs) {
    var yourmusic = document.getElementById(songs).value;
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function () {
        if (this.readyState === 4) {
            if(this.status === 200) {
                displayMusic(this.responseText);
            } else if (this.status === 404){
                displayMusic('{ "songs" : "none" }');
            } else {
                console.log("We have a problem: " + this.status);
            }
        } else {
        }
    };
    var url = " https://api.mixcloud.com/discover/funk/";
    httpRequest.open("GET", url, true);
    httpRequest.send();
}

function displayMusic(data){
    var music = JSON.parse(data);
    if(music.songs === "none") {
        document.getElementById("songs").className = "alert alert-warning";\
        document.getElementById("songs").innerHTML ="there are no songs for this artist"
        document.getElementById("songs").innerHTML = "The songs are" + music;
    } else {
        document.getElementById("songs").className = "alert alert-success";
        document.getElementById("songs").innerHTML = "The songs are" + music;
    }
}

Body:
You check code:

document.getElementById("music") // element id "music" not exist


问:
Error: Invalid column name
I get these errors:

Invalid column name 'Addmin'.

Invalid column name 'Addmin'.

The multi-part identifier "Admin@hotmail.com" could not be bound.

Invalid column name 'P@55word'.

Invalid column name 'BioMedical_Sciences'.

I am trying to enter data into a table. I have included my create table code too so you can look at the data types and so on.

```<code>CREATE TABLE Accounts
(
     ID INT NOT NULL,
     FIRSTNAME CHAR(20) NOT NULL,
     SURNAME CHAR(20) NOT NULL,
     EMAIL CHAR(50) NOT NULL,
     PASSWORD CHAR(20) NOT NULL,
     AGE INT NOT NULL,
     COURSE CHAR(25),

     PRIMARY KEY (ID)
);

ALTER TABLE Accounts
ALTER COLUMN FIRSTNAME CHAR;

ALTER TABLE Accounts
ALTER COLUMN SURNAME CHAR;

ALTER TABLE Accounts
ALTER COLUMN EMAIL CHAR;

ALTER TABLE Accounts
ALTER COLUMN PASSWORD CHAR;

ALTER TABLE Accounts
ALTER COLUMN AGE INT;

ALTER TABLE Accounts
ALTER COLUMN COURSE CHAR;

INSERT INTO Accounts (ID, FIRSTNAME, SURNAME, EMAIL, PASSWORD, AGE, COURSE)
VALUES (1, Addmin, Addmin, Admin@hotmail.com, P@55word, 19, BioMedical_Sciences);
</code>```

答:
Default char length is 1.

https://learn.microsoft.com/en-us/sql/t-sql/data-types/char-and-varchar-transact-sql

When you altered the column types, you reset the char column sizes to 1, and hence the truncation is occurring.

Title: Error: Invalid column name

Body:
I get these errors:

Invalid column name 'Addmin'.

Invalid column name 'Addmin'.

The multi-part identifier "Admin@hotmail.com" could not be bound.

Invalid column name 'P@55word'.

Invalid column name 'BioMedical_Sciences'.

I am trying to enter data into a table. I have included my create table code too so you can look at the data types and so on.

CREATE TABLE Accounts
(
     ID INT NOT NULL,
     FIRSTNAME CHAR(20) NOT NULL,
     SURNAME CHAR(20) NOT NULL,
     EMAIL CHAR(50) NOT NULL,
     PASSWORD CHAR(20) NOT NULL,
     AGE INT NOT NULL,
     COURSE CHAR(25),

     PRIMARY KEY (ID)
);

ALTER TABLE Accounts
ALTER COLUMN FIRSTNAME CHAR;

ALTER TABLE Accounts
ALTER COLUMN SURNAME CHAR;

ALTER TABLE Accounts
ALTER COLUMN EMAIL CHAR;

ALTER TABLE Accounts
ALTER COLUMN PASSWORD CHAR;

ALTER TABLE Accounts
ALTER COLUMN AGE INT;

ALTER TABLE Accounts
ALTER COLUMN COURSE CHAR;

INSERT INTO Accounts (ID, FIRSTNAME, SURNAME, EMAIL, PASSWORD, AGE, COURSE)
VALUES (1, Addmin, Addmin, Admin@hotmail.com, P@55word, 19, BioMedical_Sciences);


答:
You need to return arr in the else branch.

```<code>def PrintAllPerms(n, arr = [], str_ = ''):
    if n == 0:
        print(str_)
        arr.append(str_)
        return arr
    else:
        for i in ['1','2','3','4','5','6']:
            str_ = str_ + i
            arr = PrintAllPerms(n-1,arr,str_)
            str_ = str_[:-1]
        return arr

PrintAllPerms(2)
</code>```

Title: AttributeError: 'NoneType' object has no attribute 'append' (recursion function)

Body:
You need to return arr in the else branch.

def PrintAllPerms(n, arr = [], str_ = ''):
    if n == 0:
        print(str_)
        arr.append(str_)
        return arr
    else:
        for i in ['1','2','3','4','5','6']:
            str_ = str_ + i
            arr = PrintAllPerms(n-1,arr,str_)
            str_ = str_[:-1]
        return arr

PrintAllPerms(2)