问:
Numbers aren't displaying for my output
I am trying to get the numbers display as my output from the ArrayList I have created. I asked the user how many numbers do they want in the ArrayList, then used a for loop to generate random numbers between 1-100 and they would be thrown into the ArrayList however many times the user wants the to be. I just can't get the to be displayed, here's my code:

The KNW_MyList class:

```<code>   public class KNW_MyList<T extends Number>
{
  //Create the array list object of type T
  ArrayList<T> al = new ArrayList<T>();

  /**
   * The adds method, add a number of type T to
   * array list.
   * @param number, the number to be added.
   * */
  public void add( T number)
  {
    al.add(number);
  }

  /**
   * The largest method, returns the largest value in the
   * array list.
   * */
  public T largest()
  {
    T large = al.get(0);

    //For-loop to find the largest value
    for(int x = 0; x < al.size(); x++)
    {
      if(al.get(x).toString().compareTo(large.toString()) > 0)
      {
        large = al.get(0);
      }
    }
    return large;
  }

  /**
   * The smallest method, returns the smallest value in the
   * array list.
   * */
  public T smallest()
  {
    T small = al.get(0);

    //For-loop to find the largest value
    for(int x = 0; x < al.size(); x++)
    {
      if(al.get(x).toString().compareTo(small.toString()) < 0)
      {
        small = al.get(0);
      }
    }
    return small;
  }

  /**
   * The show method, wil show the elements in the array
   * list.
   * */
  public void show()
  {
    System.out.println(al);
  }
}
</code>```

Demo:

```<code>import java.util.*;
import java.lang.Math;

public class KNW_MyListDemo
{
  public static void main(String args[])
  {
    //Create random class
    Random rand = new Random();

int numbers;
Scanner scan = new Scanner(System.in);

//Create ArrayList object
KNW_MyList<Number> numList = new KNW_MyList<Number>();

//Ask the user how many numbers they want in the array
System.out.println("How many numbers do you want?: ");
numbers = scan.nextInt();

if(numbers <= 0)
{
  System.out.println("Not Valid!");
}
else
{
  for(int x = 1; x >= numbers; x++)
  {
    int num = rand.nextInt(100) + 1;
    numList.add(num);
    x++;
  }

//Call the show method
System.out.println("Numbers in the array: ");
numList.show();
}

  }
}
</code>```

Is there something wrong with my ArrayList or my forloop? I am not quite sure, am kinda new to array list so maybe this might or might not have any effect? I just wanna get the random numbers to display 'x' amount of times, 'x' being the number of times the user wants.

答:
I assume problem is with saving your numbers to list. Your condition in:

```<code>for(int x = 1; x >= numbers; x++)
</code>```

makes loop almost never running, because loop is only true if x is bigger than numbers. You are starting with x = 1 so only if numbers are exactly 1 your loop is kinda working. Kinda, because it will be infinite loop. Change it to

```<code>for(int x = 1; x <= numbers; x++)
</code>```

and it should be fine.

Edit

Ayo K mentioned my mistake, I forgot equals in condition.

Also, you are incrementing your list twice, once in loop declaration, and once in body.

Title: Numbers aren't displaying for my output

Body:
I am trying to get the numbers display as my output from the ArrayList I have created. I asked the user how many numbers do they want in the ArrayList, then used a for loop to generate random numbers between 1-100 and they would be thrown into the ArrayList however many times the user wants the to be. I just can't get the to be displayed, here's my code:

The KNW_MyList class:

   public class KNW_MyList<T extends Number>
{
  //Create the array list object of type T
  ArrayList<T> al = new ArrayList<T>();

  /**
   * The adds method, add a number of type T to
   * array list.
   * @param number, the number to be added.
   * */
  public void add( T number)
  {
    al.add(number);
  }

  /**
   * The largest method, returns the largest value in the
   * array list.
   * */
  public T largest()
  {
    T large = al.get(0);

    //For-loop to find the largest value
    for(int x = 0; x < al.size(); x++)
    {
      if(al.get(x).toString().compareTo(large.toString()) > 0)
      {
        large = al.get(0);
      }
    }
    return large;
  }

  /**
   * The smallest method, returns the smallest value in the
   * array list.
   * */
  public T smallest()
  {
    T small = al.get(0);

    //For-loop to find the largest value
    for(int x = 0; x < al.size(); x++)
    {
      if(al.get(x).toString().compareTo(small.toString()) < 0)
      {
        small = al.get(0);
      }
    }
    return small;
  }

  /**
   * The show method, wil show the elements in the array
   * list.
   * */
  public void show()
  {
    System.out.println(al);
  }
}

Demo:

import java.util.*;
import java.lang.Math;

public class KNW_MyListDemo
{
  public static void main(String args[])
  {
    //Create random class
    Random rand = new Random();

int numbers;
Scanner scan = new Scanner(System.in);

//Create ArrayList object
KNW_MyList<Number> numList = new KNW_MyList<Number>();

//Ask the user how many numbers they want in the array
System.out.println("How many numbers do you want?: ");
numbers = scan.nextInt();

if(numbers <= 0)
{
  System.out.println("Not Valid!");
}
else
{
  for(int x = 1; x >= numbers; x++)
  {
    int num = rand.nextInt(100) + 1;
    numList.add(num);
    x++;
  }

//Call the show method
System.out.println("Numbers in the array: ");
numList.show();
}

  }
}

Is there something wrong with my ArrayList or my forloop? I am not quite sure, am kinda new to array list so maybe this might or might not have any effect? I just wanna get the random numbers to display 'x' amount of times, 'x' being the number of times the user wants.

Body:
I assume problem is with saving your numbers to list. Your condition in:

for(int x = 1; x >= numbers; x++)

makes loop almost never running, because loop is only true if x is bigger than numbers. You are starting with x = 1 so only if numbers are exactly 1 your loop is kinda working. Kinda, because it will be infinite loop. Change it to

for(int x = 1; x <= numbers; x++)

and it should be fine.

Edit

Ayo K mentioned my mistake, I forgot equals in condition.

Also, you are incrementing your list twice, once in loop declaration, and once in body.


来源: stackexchange

问:
ETL Data from Amazon DMS to S3 to Redshift
I am currently building a data lake within S3 and have successfully moved data from a mysql DB to S3 using DMS.  Within DMS I chose the option 'Migrate existing data and replicate ongoing changes'.  I transformed the data to csv, but in the future will probably choose parquet.  This method creates an initial csv file that has all the raw data from the database tables.  It then creates subsequent csv files with inserts, deletes, updates.

Now I am looking for a strategy to copy the data from S3 into Redshift.  I am looking for a strategy to copy the bulk data and copy the continual changes from S3 into Redshift.  I will likely need to aggregate and summarize much of this data.  Preferably I'll use AWS Glue, which uses Python.  This ETL process will have to read from csv files in S3 and know to ignore files that have already been processed.

How can I facilitate this? Any ideas are welcome.  Ideally I'm hoping for some Python (or Java) scripts that precisely do the process as described.

Thanks.

答:
Recommend setting up AWS Glue to automatically watch the S3 destination and  convert the CSV into Parquet.
- http://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html
- https://github.com/awslabs/aws-glue-samples

Then use Amazon Redshift Spectrum to selectively load and/or query the data directly from the data lake.
- http://docs.aws.amazon.com/redshift/latest/dg/c-getting-started-using-spectrum.html

ContentLicense: CC BY-SA 3.0


Title: How to parse d character to different date format in R?

Body:
I have a data table as

 V1                V2                V3
1: 3 09/09/17 21:31:23 09/09/17 21:31:23
2: 3 09/09/17 22:06:47 09/09/17 22:06:47
3: 3 09/09/17 22:14:29 09/09/17 22:18:17

from this I want to tranform it to

 V1                V2                V3
1: 3 2017-09-09 21:31:23 2017-09-09 21:31:23
2: 3 2017-09-09 22:06:47 2017-09-09 22:06:47
3: 3 2017-09-09 22:14:29 2017-09-09 22:18:17

The V2 and V3 columns are characters.

I tried by

DT[,V2:=parse_date_time2(V2,orders="YmdHMS",tz="NA")]
DT[,V3:=parse_date_time2(V3,orders="YmdHMS",tz="NA")]
DT[,V2:=strftime(V2, format="%Y/%m/%d %H:%M:%S"]
DT[,V3:=strftime(V3, format="%Y/%m/%d %H:%M:%S"]

But did not work. Any help is appreciated.

Body:
Using dplyr and lubridate:

library(lubridate)
library(dplyr)

df %>%
  mutate_at(2:3, dmy_hms)

    # A tibble: 3 x 3
     V1                  V2                  V3
  <chr>              <dttm>              <dttm>
1  1: 3 2017-09-09 21:31:23 2017-09-09 21:31:23
2  2: 3 2017-09-09 22:06:47 2017-09-09 22:06:47
3  3: 3 2017-09-09 22:14:29 2017-09-09 22:18:17


问:
Unable to uncheck input type checkbox in mobile view
I'm trying to create a responsive table, I have the most part of this down, I am trying to make it accordion like when viewed on smaller resolutions, unfortunately when the checkbox is clicked, it will not uncheck (retract). I'm probably missing something very obvious or doing something completely wrong. I've tried using JS to create the function. Could someone please point me in the right direction with this?

$(function() {

  $(".close").on('change', function(e) {
    var el = $(this); {
      $(".close").not(el).prop('checked', false);
    }

  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #cacaca;
  margin: 0;
  padding: 20px;
  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
  font-weight: 300;
}

#table {
  display: table;
  width: 100%;
  background: #fff;
  margin: 0;
  box-sizing: border-box;
}

.caption {
  display: block;
  width: 100%;
  background: #64e0ef;
  height: 55px;
  padding-left: 10px;
  color: #fff;
  font-size: 20px;
  line-height: 55px;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, .3);
  box-sizing: border-box;
}

.header-row {
  background: #8b8b8b;
  color: #fff;
}

.row {
  display: table-row;
}

.cell {
  display: table-cell;
  padding: 6px;
  border-bottom: 1px solid #e5e5e5;
  text-align: center;
}

.primary {
  text-align: left;
}

input[type="radio"],
input[type="checkbox"] {
  display: none;
}

@media only screen and (max-width: 760px) {
  body {
    padding: 0;
  }
  #table {
    display: block;
    margin: 44px 0 0 0;
  }
  .caption {
    position: fixed;
    top: 0;
    text-align: center;
    height: 44px;
    line-height: 44px;
    z-index: 5;
    border-bottom: 2px solid #999;
  }
  .row {
    position: relative;
    display: block;
    border-bottom: 1px solid #ccc;
  }
  .header-row {
    display: none;
  }
  .cell {
    display: block;
    border: none;
    position: relative;
    height: 45px;
    line-height: 45px;
    text-align: left;
  }
  .primary:after {
    content: "";
    display: block;
    position: absolute;
    right: 20px;
    top: 18px;
    z-index: 2;
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #ccc;
  }
  .cell:nth-of-type(n+2) {
    display: none;
  }
  input[type="radio"],
  input[type="checkbox"] {
    display: block;
    position: absolute;
    z-index: 1;
    width: 99%;
    height: 100%;
    opacity: 0;
  }
  input[type="radio"]:checked,
  input[type="checkbox"]:checked {
    z-index: -1;
  }
  input[type="radio"]:checked~.cell,
  input[type="checkbox"]:checked~.cell {
    display: block;
    border-bottom: 1px solid #eee;
  }
  input[type="radio"]:checked~.cell:nth-of-type(n+2),
  input[type="checkbox"]:checked~.cell:nth-of-type(n+2) {
    background: #e0e0e0;
  }
  input[type="radio"]:checked~.cell:nth-of-type(n+2):before,
  input[type="checkbox"]:checked~.cell:nth-of-type(n+2):before {
    content: attr(data-label);
    display: inline-block;
    width: 60px;
    background: #999;
    border-radius: 10px;
    height: 20px;
    margin-right: 10px;
    font-size: 12px;
    line-height: 20px;
    text-align: center;
    color: white;
  }
  input[type="radio"]:checked~.primary,
  input[type="checkbox"]:checked~.primary {
    border-bottom: 2px solid #999;
  }
  input[type="radio"]:checked~.primary:after,
  input[type="checkbox"]:checked~.primary:after {
    position: absolute;
    right: 18px;
    top: 22px;
    border-right: 10px solid transparent;
    border-left: 10px solid transparent;
    border-top: 10px solid #ccc;
    z-index: 2;
  }
}</code>```

Main Title

    Developer
    Foundation
    Accelerator
    Enterprise

    <input type="checkbox" name="expand" class="close">
    Item 1
    Sub Item
    Sub Item
    Sub Item
    Sub Item

    <input type="checkbox" name="expand" class="close">
    Item 2
    Sub Item
    Sub Item
    Sub Item
    Sub Item

    <input type="checkbox" name="expand" class="close">
    Item 3
    Sub Item
    Sub Item
    Sub Item
    Sub Item

    <input type="checkbox" name="expand" class="close">
    Item 4
    Sub Item
    Sub Item
    Sub Item
    Sub Item

    <input type="checkbox" name="expand" class="close">
    Item 5
    Sub Item
    Sub Item
    Sub Item
    Sub Item

    <input type="checkbox" name="expand" class="close">
    Item 6
    Sub Item
    Sub Item
    Sub Item
    Sub Item

```

答:
It works like an accordion, meaning if you open another item, the other ones are collapsed. If you want to also close the active one on reclick/retap on it, you need to trigger the click on the checkbox.

Add the following to your JavaScript code and it will fix your issue.

$('.primary').on('click', function() {
  $(this).prev().trigger('click');
})

As an explanation as to why it works the first time, it's because you actually click the checkbox the first time, but after that, the primary cell comes over and captures the pointer events.

Body:
I'm trying to create a responsive table, I have the most part of this down, I am trying to make it accordion like when viewed on smaller resolutions, unfortunately when the checkbox is clicked, it will not uncheck (retract). I'm probably missing something very obvious or doing something completely wrong. I've tried using JS to create the function. Could someone please point me in the right direction with this?

$(function() {

  $(".close").on('change', function(e) {
    var el = $(this); {
      $(".close").not(el).prop('checked', false);
    }

  });

});

body {
  background: #cacaca;
  margin: 0;
  padding: 20px;
  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
  font-weight: 300;
}

#table {
  display: table;
  width: 100%;
  background: #fff;
  margin: 0;
  box-sizing: border-box;
}

.caption {
  display: block;
  width: 100%;
  background: #64e0ef;
  height: 55px;
  padding-left: 10px;
  color: #fff;
  font-size: 20px;
  line-height: 55px;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, .3);
  box-sizing: border-box;
}

.header-row {
  background: #8b8b8b;
  color: #fff;
}

.row {
  display: table-row;
}

.cell {
  display: table-cell;
  padding: 6px;
  border-bottom: 1px solid #e5e5e5;
  text-align: center;
}

.primary {
  text-align: left;
}

input[type="radio"],
input[type="checkbox"] {
  display: none;
}

@media only screen and (max-width: 760px) {
  body {
    padding: 0;
  }
  #table {
    display: block;
    margin: 44px 0 0 0;
  }
  .caption {
    position: fixed;
    top: 0;
    text-align: center;
    height: 44px;
    line-height: 44px;
    z-index: 5;
    border-bottom: 2px solid #999;
  }
  .row {
    position: relative;
    display: block;
    border-bottom: 1px solid #ccc;
  }
  .header-row {
    display: none;
  }
  .cell {
    display: block;
    border: none;
    position: relative;
    height: 45px;
    line-height: 45px;
    text-align: left;
  }
  .primary:after {
    content: "";
    display: block;
    position: absolute;
    right: 20px;
    top: 18px;
    z-index: 2;
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #ccc;
  }
  .cell:nth-of-type(n+2) {
    display: none;
  }
  input[type="radio"],
  input[type="checkbox"] {
    display: block;
    position: absolute;
    z-index: 1;
    width: 99%;
    height: 100%;
    opacity: 0;
  }
  input[type="radio"]:checked,
  input[type="checkbox"]:checked {
    z-index: -1;
  }
  input[type="radio"]:checked~.cell,
  input[type="checkbox"]:checked~.cell {
    display: block;
    border-bottom: 1px solid #eee;
  }
  input[type="radio"]:checked~.cell:nth-of-type(n+2),
  input[type="checkbox"]:checked~.cell:nth-of-type(n+2) {
    background: #e0e0e0;
  }
  input[type="radio"]:checked~.cell:nth-of-type(n+2):before,
  input[type="checkbox"]:checked~.cell:nth-of-type(n+2):before {
    content: attr(data-label);
    display: inline-block;
    width: 60px;
    background: #999;
    border-radius: 10px;
    height: 20px;
    margin-right: 10px;
    font-size: 12px;
    line-height: 20px;
    text-align: center;
    color: white;
  }
  input[type="radio"]:checked~.primary,
  input[type="checkbox"]:checked~.primary {
    border-bottom: 2px solid #999;
  }
  input[type="radio"]:checked~.primary:after,
  input[type="checkbox"]:checked~.primary:after {
    position: absolute;
    right: 18px;
    top: 22px;
    border-right: 10px solid transparent;
    border-left: 10px solid transparent;
    border-top: 10px solid #ccc;
    z-index: 2;
  }
}

Main Title

    Developer
    Foundation
    Accelerator
    Enterprise

    <input type="checkbox" name="expand" class="close">
    Item 1
    Sub Item
    Sub Item
    Sub Item
    Sub Item

    <input type="checkbox" name="expand" class="close">
    Item 2
    Sub Item
    Sub Item
    Sub Item
    Sub Item

    <input type="checkbox" name="expand" class="close">
    Item 3
    Sub Item
    Sub Item
    Sub Item
    Sub Item

    <input type="checkbox" name="expand" class="close">
    Item 4
    Sub Item
    Sub Item
    Sub Item
    Sub Item

    <input type="checkbox" name="expand" class="close">
    Item 5
    Sub Item
    Sub Item
    Sub Item
    Sub Item

    <input type="checkbox" name="expand" class="close">
    Item 6
    Sub Item
    Sub Item
    Sub Item
    Sub Item


问:
Dynamically instantiate multiple copies of a MC
I have aa question re:AS 3. I made a Post-It note movie clip that is draggable. I want to create a whole pad of notes, or at least simulate this. I thought the best way to do this would be to add another Post-It whenever the startDrag() is triggered.

I first tried creating the Post-It with symbols but didn't think I could dynamically create new ones this way. I then created a class and added it to the stage:

...
addChild(new PostItNote());

But I wasn't able to (or don't know how) to set the x, y position on the stage.

Anyone have suggestions on the best way to accomplish this or even another way altogether?

EDIT:

```<code>package  {

 import flash.display.MovieClip;
 import flash.display.Sprite;
 import flash.events.MouseEvent;
 import flash.events.Event;
 import flash.text.TextField;
 import flash.media.Sound;
 import flash.media.SoundChannel;
 import flash.text.TextFormat;

 public class CoinHitTest extends MovieClip {

  var count:Number = 0;
  var total_count:TextField;
  var hitting:Boolean = false;
  var coinSnd:Sound = new coin_drop();
  var myMoney:TextFormat = new TextFormat();
  var noteStack:Vector.<PostItNotes> = new Vector.<PostItNotes>();

public function CoinHitTest(){
    for(var $i:int = 0; $i <5;$i++)
{
    var newPostIt:PostItNotes = new PostItNotes();
    this.addChild(newPostIt);
    this.noteStack.push(newPostIt);
}
// constructor code
   coin.addEventListener(MouseEvent.MOUSE_DOWN, __handleCoinDown);
   coin.addEventListener(MouseEvent.MOUSE_UP, __handleCoinUp);

   total_count = new TextField();
   total_count.x = 795.20;
   total_count.y = 506.15;
   total_count.mouseEnabled = false;

   myMoney.size = 28;
   total_count.defaultTextFormat = myMoney;
   total_count.text = String("$" + count);
   addChild(total_count);
  }

  private function __handleCoinDown($evt:MouseEvent):void {

   coin.startDrag(true);
     coin.scaleX = 1.5;
     coin.scaleY = 1.5;
   addEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __handleCoinUp($evt:MouseEvent):void {
   coin.stopDrag();
     coin.scaleX = 1;
     coin.scaleY = 1;
   removeEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __checkHit($evt:Event):void {
    if (this.coffee.hitTestPoint(coin.x,coin.y, false))
    {
        // do our in-circle check
        if((coffee.x - coin.x) * 2 + (coffee.y - coin.y) * 2 <= (coffee.width/2 + coin.width/2) * 2)
        {
            stopDrag();
            coin.scaleX = 1;
     coin.scaleY = 1;
            removeChild(coin);
            coin.x = 116;
     coin.y = 380.1;
      addChild(coin);

        }
    }
    else
    {
        trace("Didn't Hit Mug");
    }
   if (this.coin.hitTestObject(target)) {
     if (!hitting) {
         coinSnd.play();
     count++;
       total_count.text = String("$" + count);
       coin.stopDrag();

     removeChild(coin);
     hitting = !hitting;

     coin.x = 116;
     coin.y = 380.1;
      addChild(coin);
     coin.scaleX = 1;
     coin.scaleY = 1;

}
   } else {
    hitting = false;
   }
  }

   }
}
</code>```

EDIT:

```<code>package  {
    import flash.display.MovieClip;
public class PostItNotes extends Sprite{

        public function PostItNotes() {
            // constructor code
        }

    }

}
</code>```

答:
By the way: You can combine a AS3 class with a Symbol so that you can work with code and graphic within the same class.

That might be easier for you when you have to deal with the PostIt as a graphic element and all the logic written in ActionScript.

That way you can handle all the drag action within the PostIt Class itself.

ContentLicense: CC BY-SA 2.5

Body:
I have aa question re:AS 3. I made a Post-It note movie clip that is draggable. I want to create a whole pad of notes, or at least simulate this. I thought the best way to do this would be to add another Post-It whenever the startDrag() is triggered.

I first tried creating the Post-It with symbols but didn't think I could dynamically create new ones this way. I then created a class and added it to the stage:

...
addChild(new PostItNote());

But I wasn't able to (or don't know how) to set the x, y position on the stage.

Anyone have suggestions on the best way to accomplish this or even another way altogether?

EDIT:

package  {

 import flash.display.MovieClip;
 import flash.display.Sprite;
 import flash.events.MouseEvent;
 import flash.events.Event;
 import flash.text.TextField;
 import flash.media.Sound;
 import flash.media.SoundChannel;
 import flash.text.TextFormat;

 public class CoinHitTest extends MovieClip {

  var count:Number = 0;
  var total_count:TextField;
  var hitting:Boolean = false;
  var coinSnd:Sound = new coin_drop();
  var myMoney:TextFormat = new TextFormat();
  var noteStack:Vector.<PostItNotes> = new Vector.<PostItNotes>();

public function CoinHitTest(){
    for(var $i:int = 0; $i <5;$i++)
{
    var newPostIt:PostItNotes = new PostItNotes();
    this.addChild(newPostIt);
    this.noteStack.push(newPostIt);
}
// constructor code
   coin.addEventListener(MouseEvent.MOUSE_DOWN, __handleCoinDown);
   coin.addEventListener(MouseEvent.MOUSE_UP, __handleCoinUp);

   total_count = new TextField();
   total_count.x = 795.20;
   total_count.y = 506.15;
   total_count.mouseEnabled = false;

   myMoney.size = 28;
   total_count.defaultTextFormat = myMoney;
   total_count.text = String("$" + count);
   addChild(total_count);
  }

  private function __handleCoinDown($evt:MouseEvent):void {

   coin.startDrag(true);
     coin.scaleX = 1.5;
     coin.scaleY = 1.5;
   addEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __handleCoinUp($evt:MouseEvent):void {
   coin.stopDrag();
     coin.scaleX = 1;
     coin.scaleY = 1;
   removeEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __checkHit($evt:Event):void {
    if (this.coffee.hitTestPoint(coin.x,coin.y, false))
    {
        // do our in-circle check
        if((coffee.x - coin.x) * 2 + (coffee.y - coin.y) * 2 <= (coffee.width/2 + coin.width/2) * 2)
        {
            stopDrag();
            coin.scaleX = 1;
     coin.scaleY = 1;
            removeChild(coin);
            coin.x = 116;
     coin.y = 380.1;
      addChild(coin);

        }
    }
    else
    {
        trace("Didn't Hit Mug");
    }
   if (this.coin.hitTestObject(target)) {
     if (!hitting) {
         coinSnd.play();
     count++;
       total_count.text = String("$" + count);
       coin.stopDrag();

     removeChild(coin);
     hitting = !hitting;

     coin.x = 116;
     coin.y = 380.1;
      addChild(coin);
     coin.scaleX = 1;
     coin.scaleY = 1;

}
   } else {
    hitting = false;
   }
  }

   }
}

EDIT:

package  {
    import flash.display.MovieClip;
public class PostItNotes extends Sprite{

        public function PostItNotes() {
            // constructor code
        }

    }

}


问:
Rollback to previous commit and make master head on github
I messed up something badly and need to go back to a previous commit. I have looked around and tried lots of things with no success. How do I go back to commit 8add545108ce1a0d6ffebe891c112bb89ccbbae5 and make it my master on github? I can make it master locally but can't seem to get it to sync up with github.

The possible duplicate is not helpful in any way shape or form. I have already seen that and had no luck with it. I did not keep track of which 50 things I tried but I know that was one of them.

答:
This solved it for me, I had to play around till I got it to work though.   </p>

```<code>git revert --no-commit [commit]..HEAD

git commit -m "Revert back to [commit]"
</code>```

Body:
This solved it for me, I had to play around till I got it to work though.

git revert --no-commit [commit]..HEAD

git commit -m "Revert back to [commit]"


问:
How to put fluentd containers behind a load balancer in ECS?
So in ECS, we have ALB's which only route traffic on http/https. As fluentd containers listen on a different tcp port, how can we load balance them in ECS? I know we can use classic loadbalancer in ECS, but I wanted to avoid using classic ELB in ECS.

To give a background, in our SOA architecture there are many services in ECS and I want to use the docker fluentd logging driver to route the logs to the fluentd container.

Is it a good practice to put multiple fluentd containers behind a loadbalancer? Any other suggestions welcome.

答:
I run a number of fluentd services in ECS behind classic ELB load balancers. It works really well and the inability to use dynamic ports hasn't been an issue given the number of hosts in the cluster.

You also now have the option of using the network load balancer. An NLB allows you to use dynamic port mapping with TCP. Read the documentation and see if it works for you. I didn't use it because it doesn't work across VPC peering connections.


问:
Is it possible to set a timer in a Firebase database?
I am creating a mobile app that displays a score of an ongoing soccer game (amateur game, not professional). So, what I am basically doing is, I am creating a data of a soccer game in the Firebase real-time DB which might contain information like:

```<code>Team A: String
Team B: String
Score A: int
Score B: int
isLive: true/false
id: int
currentTime: ???
</code>```

So, when I press the Score Update in my app, it will update the score, and will apply this change to a ListView in my app.

Everything seems clear up to this point, but I am having a trouble of displaying the current game time.

I wanted to work something like:

This is from the web app (http://livescore.com) that I was motivated by. When a game begins, the game time is displayed from 1min to 90min as shown in the image and turns in to FT when it is over.

My question is,

is it possible to make like an automatically incrementing timer in Firebase database, or is it possible to make it work like it is incrementing 1 to its value every 1 minute up to a certain point?

Any kind of advice would be appreciated.

答:
There is no way to achieve what you want using Firebase Realtime Database because it doesn't provide something like this. To solve this, you need to create a custom scheduling mechanism made by yourself that provides you that behaviour.

So unfortunately, in this case you do not get rid of coding.

Body:
I am creating a mobile app that displays a score of an ongoing soccer game (amateur game, not professional). So, what I am basically doing is, I am creating a data of a soccer game in the Firebase real-time DB which might contain information like:

Team A: String
Team B: String
Score A: int
Score B: int
isLive: true/false
id: int
currentTime: ???

So, when I press the Score Update in my app, it will update the score, and will apply this change to a ListView in my app.

Everything seems clear up to this point, but I am having a trouble of displaying the current game time.

I wanted to work something like:

This is from the web app (http://livescore.com) that I was motivated by. When a game begins, the game time is displayed from 1min to 90min as shown in the image and turns in to FT when it is over.

My question is,

is it possible to make like an automatically incrementing timer in Firebase database, or is it possible to make it work like it is incrementing 1 to its value every 1 minute up to a certain point?

Any kind of advice would be appreciated.


问:
Static files in ExpressJS cannot be loaded via Nginx
In short, Nginx and Node JS are both running on the same server 10.0.0.120. I can access a Node app via http://10.0.0.120:3000, all stylesheets are loaded properly.

I want the Node app to be accessed via 10.0.0.120/abc/ so I had the following Nginx setup in /etc/nginx/sites-available/default

```<code>location /abc/ {
  proxy_pass http://localhost:3000/;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
</code>```

}

Now that 10.0.0.120/abc/ can reach the Node app but returns without stylesheet loaded because the relative path maps into 10.0.0.120/stylesheets, which obviously does not exist.

On the NodeJS side, I simply used the Express template,in which public folder is used for serving static files.

```<code>app.use(express.static(path.join(__dirname, 'public')));
</code>```

The Node directory tree is shown below

```<code>Node App
|
|── public
|   ├── images
|   ├── javascripts
│   │   ├── bootstrap.js
│   │   ├── bootstrap.min.js
│   │   └── jquery.min.js
│   └── stylesheets
│       ├── animate.css
│       ├── bootstrap.css
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
</code>```

How should I change the Nginx setting to fix the issue?

答: Try using app.use(express.static('public')). Express should recognize without path.join.

Body:
In short, Nginx and Node JS are both running on the same server 10.0.0.120. I can access a Node app via http://10.0.0.120:3000, all stylesheets are loaded properly.

I want the Node app to be accessed via 10.0.0.120/abc/ so I had the following Nginx setup in /etc/nginx/sites-available/default

location /abc/ {
  proxy_pass http://localhost:3000/;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}

Now that 10.0.0.120/abc/ can reach the Node app but returns without stylesheet loaded because the relative path maps into 10.0.0.120/stylesheets, which obviously does not exist.

On the NodeJS side, I simply used the Express template,in which public folder is used for serving static files.

app.use(express.static(path.join(__dirname, 'public')));

The Node directory tree is shown below

Node App
|
|── public
|   ├── images
|   ├── javascripts
│   │   ├── bootstrap.js
│   │   ├── bootstrap.min.js
│   │   └── jquery.min.js
│   └── stylesheets
│       ├── animate.css
│       ├── bootstrap.css
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js

How should I change the Nginx setting to fix the issue?

ContentLicense: CC BY-SA 4.0


问:
SAS Macro help to loop monthly sas datasets
I have monthly datasets in SAS Library for customers from Jan 2013 onwards with datasets name as CUST_JAN2013,CUST_FEB2013........CUST_OCT2017. These customers datasets have huge records of 2 million members for each month.This monthly datset has two columns (customer number and customer monthly expenses).

I have one input dataset Cust_Expense with customer number and month as columns. This Cust_Expense table has only 250,000 members and want to pull expense data for each member from SPECIFIC monthly SAS dataset by joining customer number.

```<code>Cust_Expense
------------
Customer_Number  Month
111              FEB2014
987              APR2017
784              FEB2014
768              APR2017
.....
145              AUG2017
345              AUG2014
</code>```

I have tried using call execute, but it tries to loop thru each 250,000 records of input dataset (Cust_Expense) and join with corresponding monthly SAS customer tables which takes too much of time.
Is there a way to read input tables (Cust_Expense) by month so that we read all customers for a specific month and then read the same monthly table ONCE to pull all the records from that month, so that it does not loop 250,000 times.

答:
Your first, best answer is to get rid of these monthly separate tables and make them into one large table with ID and month as key.  Then you can simply join on this and go on your way.  Having many separate tables like this where a data element determines what table they're in is never a good idea.  Then index on month to make it faster.

If you can't do that, then try creating a view that is all of those tables unioned.  It may be faster to do that; SAS might decide to materialize the view but maybe not (but if it's extremely slow, then look in your temp table space to see if that's what's happening).

Third option then is probably to make use of SAS formats. Turn the smaller table into a format, using the CNTLIN option.  Then a single large datastep will allow you to perform the join.

```<code>data want;
  set jan feb mar apr ... ;
  where put(id,CUSTEXPF1.) = '1';
run;
</code>```

That only makes one pass through the 250k table and one pass through the monthly tables, plus the very very fast format lookup which is undoubtedly zero cost in this data step (as the disk i/o will be slower).

Body:
I have monthly datasets in SAS Library for customers from Jan 2013 onwards with datasets name as CUST_JAN2013,CUST_FEB2013........CUST_OCT2017. These customers datasets have huge records of 2 million members for each month.This monthly datset has two columns (customer number and customer monthly expenses).

I have one input dataset Cust_Expense with customer number and month as columns. This Cust_Expense table has only 250,000 members and want to pull expense data for each member from SPECIFIC monthly SAS dataset by joining customer number.

Cust_Expense
------------
Customer_Number  Month
111              FEB2014
987              APR2017
784              FEB2014
768              APR2017
.....
145              AUG2017
345              AUG2014

I have tried using call execute, but it tries to loop thru each 250,000 records of input dataset (Cust_Expense) and join with corresponding monthly SAS customer tables which takes too much of time.
Is there a way to read input tables (Cust_Expense) by month so that we read all customers for a specific month and then read the same monthly table ONCE to pull all the records from that month, so that it does not loop 250,000 times.

Body:
Your first, best answer is to get rid of these monthly separate tables and make them into one large table with ID and month as key.  Then you can simply join on this and go on your way.  Having many separate tables like this where a data element determines what table they're in is never a good idea.  Then index on month to make it faster.

If you can't do that, then try creating a view that is all of those tables unioned.  It may be faster to do that; SAS might decide to materialize the view but maybe not (but if it's extremely slow, then look in your temp table space to see if that's what's happening).

Third option then is probably to make use of SAS formats. Turn the smaller table into a format, using the CNTLIN option.  Then a single large datastep will allow you to perform the join.

data want;
  set jan feb mar apr ... ;
  where put(id,CUSTEXPF1.) = '1';
run;

That only makes one pass through the 250k table and one pass through the monthly tables, plus the very very fast format lookup which is undoubtedly zero cost in this data step (as the disk i/o will be slower).


问:
numpy polynomial TypeError
I'm using python 3.6.3. I want to call polynomial with list of values but I got a TypeError.

```<code>Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy.polynomial import Polynomial
>>> p = Polynomial([-3, 2, 0, 1])
>>> p(0)
-3.0
>>> p([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Michel\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\polynomial\_polybase.py", line 292, in __call__
    arg = off + scl*arg
TypeError: 'numpy.float64' object cannot be interpreted as an integer
>>> p([1.0, 2.0, 3.0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Michel\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\polynomial\_polybase.py", line 292, in __call__
    arg = off + scl*arg
TypeError: 'numpy.float64' object cannot be interpreted as an integer
>>>
</code>```

I cannot find any related subject on the Net.
Any idea of what missing ?

答:
Given you've got numpy imported, sticking your list of values into an array should not be a problem:</p>

```<code>>>> p(numpy.array([1, 2, 3]))
array([  0.,   9.,  30.])
</code>```

Title: numpy polynomial TypeError

Body:
I'm using python 3.6.3. I want to call polynomial with list of values but I got a TypeError.

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy.polynomial import Polynomial
>>> p = Polynomial([-3, 2, 0, 1])
>>> p(0)
-3.0
>>> p([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Michel\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\polynomial\_polybase.py", line 292, in __call__
    arg = off + scl*arg
TypeError: 'numpy.float64' object cannot be interpreted as an integer
>>> p([1.0, 2.0, 3.0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Michel\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\polynomial\_polybase.py", line 292, in __call__
    arg = off + scl*arg
TypeError: 'numpy.float64' object cannot be interpreted as an integer
>>>

I cannot find any related subject on the Net.
Any idea of what missing ?

Body:
Given you've got numpy imported, sticking your list of values into an array should not be a problem:

>>> p(numpy.array([1, 2, 3]))
array([  0.,   9.,  30.])


问:
Clarification about UCCAPI in c#

Using UCCAPI is it possible to identify through which client the message is comming for eg : if i am receiving thru Microsoft Office Communicator(MOC) or Custom Client

Say for Ex if 10 people are using the Custom Client if 3 are not signed in. but they signed in MOC is it possible to show they are in offline from custom client?.

答:
1 - In a custom application built using UCCAPI, it is possible to examine the incoming message before MOC gets to it, and decide whether to accept, ignore or reject the message. I believe you can pass some context through from the custom application that is sending the message, and this can be examined by the custom app receiving the message. That would tell you whether it was your custom client or the MOC client that sent the message.

2 - It might be possible to do this using Custom Presence States, although I haven't tried it.

Sorry I can't be more help - you might have more luck with this question on the UCCAPI forum

Title: Clarification about UCCAPI in c#


问:
C# connection string to connect to AWS RDS MySQL through SSL connection
According to AWS RDS documentation, AWS RDS MySQL comes with a SSL certificate, and the public key is in a file called "rds-combined-ca-bundle.pem" downloadable from AWS website.

I also saw documentation from MySQL that this is how you create a SSL client connection in C# (.NET):

```<code>using (MySqlConnection connection = new MySqlConnection("database=test;user=sslclient;CertificateFile=H:\\...\\client.pfx;CertificatePassword=pass;SSL Mode=Required"))
{
    connection.Open();
}
</code>```

But how to convert this "rds-combined-ca-bundle.pem" to this "client.pfx"?

答:
The client certificate is not the same as the CA Bundle.  The CA Bundle is used to verify that the remote server's certificate is trusted. You do this in windows by adding the CA to the certificate store.  That being said, when you specify SSL Mode=Required the MySql Client ignores certificate validation so there is no need to even use the CA PEM File.

If you do want the .Net MySql client to validate the certificate then you must set SSL Mode = VerifyCA or VerifyFull.

To import the PEM CA in to the certificate store.

Open MMC, and go to the Certificates snap-in.
Open Certificates (local computer), double-click the Trusted Root Certification Authorities node.

Right click Certificates , select all tasks - > Import...

Here is a post with more information on MySQL .Net SSL options

Body:
According to AWS RDS documentation, AWS RDS MySQL comes with a SSL certificate, and the public key is in a file called "rds-combined-ca-bundle.pem" downloadable from AWS website.

I also saw documentation from MySQL that this is how you create a SSL client connection in C# (.NET):

using (MySqlConnection connection = new MySqlConnection("database=test;user=sslclient;CertificateFile=H:\\...\\client.pfx;CertificatePassword=pass;SSL Mode=Required"))
{
    connection.Open();
}

But how to convert this "rds-combined-ca-bundle.pem" to this "client.pfx"?


问:
Delay between loop's first execution and the next one
I'm trying to make a simon game and I'm almost done but I got an issue.
In a simon game, when the simon's giving you the order (which represented by blinking lights and audio for each light) which you need to remember and repeat afterwards, there's a short delay between each blink (with it's audio) to the next one.

So now, my simon is making sounds but it's doing them all at once, with no delay. I tried using setIntarvel and setTimeout but still it played all audios at once.

Since adding the blinking shouldn't be that tough I'm keeping it to the end.

Then I built a timer function:

```<code>function timer(delayInMS) {
    var time = new Date();
    var currentTime = time.getTime();
    var nextTime = time.getTime() + delayInMS;
    while (currentTime != nextTime) {
        time = new Date();
        currentTime = time.getTime();
        }
}
</code>```

And used it inside the function which playing the audios, but it's still doing the same thing - playing it all at once.

This is the function which responsible for the audios:

```<code>function playAudio(btnSound) {
    if (btnSound == "c") {
        c.play();
    }
    if (btnSound == "g") {
        g.play();
    }
    if (btnSound == "a") {
        a.play();
    }
    if (btnSound == "d") {
        d.play();
    }
}
</code>```

And this function responsible for the logic of the game:

```<code>var btns = ["c", "g", "a", "d"];
var randomOrder = "";

var playerInputOrder = "";

var timer = 1000;    //For timer()

function randomSimon() {
var randomBtn = btns[Math.floor(Math.random() * 4)];
randomOrder += randomBtn;
for  (i = 0; i <= randomOrder.length - 1; i++) {
    for (s = 0; s <= i; s++) {
        var someText = "";
        someText += randomOrder.charAt(s);
        playAudio(randomOrder.charAt(s));
        document.getElementById('debug').innerHTML = someText; //this is for debugin, should be ignored.
        timer(500);
    }
}
</code>```

}

And this is the whole script for better reading:

```<code>var isGameStarted = false;

var d = new Audio("dSharpNote.wav");
var a = new Audio("aSharpNote.wav");
var g = new Audio("gSharpNote.wav");
var c = new Audio("cNote.wav");

var btns = ["c", "g", "a", "d"];
var randomOrder = "";

var playerInputOrder = "";

var timer = 1000;

function startGame() {
    isGameStarted = true;         //So players won't be able to just press the simon's buttons.
    randomOrder = "";             //A variable to keep the random order given by the simon.
    playerInputOrder = "";        //A variable to keep the random order the player inputs.
    randomSimon();                //Called to give the first button in the order.
}

function randomSimon() {                                       //Adds one random button to the order and saves the order.
    var randomBtn = btns[Math.floor(Math.random() * 4)];       //Adds the random button.
    randomOrder += randomBtn;                                  //Saves the random order.
    for  (i = 0; i <= randomOrder.length - 1; i++) {           //this should play all the audios one by one according the saved order
        for (s = 0; s <= i; s++) {
            var someText = "";
            someText += randomOrder.charAt(s);
            playAudio(randomOrder.charAt(s));
            document.getElementById('debug').innerHTML = someText;         //this is for debugin, should be ignored.
            timer(500);
        }
    }
}

function timer(delayInMS) {
    var time = new Date();
    var currentTime = time.getTime();
    var nextTime = time.getTime() + delayInMS;
    while (currentTime != nextTime) {
        time = new Date();
        currentTime = time.getTime();
    }
}

function playerProgress(btn) {                        //Getting the player's input and checks if it's in the right order.
    if (isGameStarted == true) {
        var btnClicked = btn.id;                      //Gets the id of the button the player clicked.
        playAudio(btnClicked);                        //So this could play it's audio.
        playerInputOrder += btnClicked;
        if (playerInputOrder.length == randomOrder.length) {
            if (playerInputOrder == randomOrder) {
                playerInputOrder = "";
                setTimeout(randomSimon, 1000);
            } else {
                document.getElementById('scoreText').innerHTML = randomOrder + " Game Over!";
                isGameStarted = false;               //Makes the player unable to play the simon's button's audios.
            }
        }
        document.getElementById('debug').innerHTML = playerInputOrder;
    }
}

function playAudio(btnSound) {
    if (btnSound == "c") {
        c.play();
    }
    if (btnSound == "g") {
        g.play();
    }
    if (btnSound == "a") {
        a.play();
    }
    if (btnSound == "d") {
        d.play();
    }
}

function someInterval() {
    var i = 0;
    var anInterval = setInterval(function() {
        i++;
        if (i > 11) {
            clearInterval(anInterval);
            timer *= 2;
        }
    }, timer);
}
</code>```

答:
So you want to have a pause after each playAudio call?

I would still go for timeouts

```<code>var sounds = {};
sounds.a = ...;
sounds.b = ...;

function playAudio(sound, callback) {
    if (typeof sounds[sound] === "undefined") {
        throw "sound not available";
    }
    sounds[sound].play();
    if (typeof callback !== "undefined") {
        window.setTimeout(callback, 500);
    }
}

// play a - pause - b - pause c
playAudio("a", function(){
    playAudio("b", function() {
        playAudio("c");
    });
});
</code>```

if you build the sequence first you can do this dynamic too

```<code>var sequence = ["a", "b", "c"];
var pointer = 0;

playAudio(sequene[pointer], function() {
    pointer += 1;
    if (typeof sequence[pointer] !== "undefined") {
        playAudio(sequence[pointer], this); // this will be bound to the function itself
    } else {
        alert("sequence finished");
    }
});
</code>```

this is not tested but it should work, let me know if not.

Body:
I'm trying to make a simon game and I'm almost done but I got an issue.
In a simon game, when the simon's giving you the order (which represented by blinking lights and audio for each light) which you need to remember and repeat afterwards, there's a short delay between each blink (with it's audio) to the next one.

So now, my simon is making sounds but it's doing them all at once, with no delay. I tried using setIntarvel and setTimeout but still it played all audios at once.

Since adding the blinking shouldn't be that tough I'm keeping it to the end.

Then I built a timer function:

function timer(delayInMS) {
    var time = new Date();
    var currentTime = time.getTime();
    var nextTime = time.getTime() + delayInMS;
    while (currentTime != nextTime) {
        time = new Date();
        currentTime = time.getTime();
        }
}

And used it inside the function which playing the audios, but it's still doing the same thing - playing it all at once.

This is the function which responsible for the audios:

function playAudio(btnSound) {
    if (btnSound == "c") {
        c.play();
    }
    if (btnSound == "g") {
        g.play();
    }
    if (btnSound == "a") {
        a.play();
    }
    if (btnSound == "d") {
        d.play();
    }
}

And this function responsible for the logic of the game:

var btns = ["c", "g", "a", "d"];
var randomOrder = "";

var playerInputOrder = "";

var timer = 1000;    //For timer()

function randomSimon() {
var randomBtn = btns[Math.floor(Math.random() * 4)];
randomOrder += randomBtn;
for  (i = 0; i <= randomOrder.length - 1; i++) {
    for (s = 0; s <= i; s++) {
        var someText = "";
        someText += randomOrder.charAt(s);
        playAudio(randomOrder.charAt(s));
        document.getElementById('debug').innerHTML = someText; //this is for debugin, should be ignored.
        timer(500);
    }
}

}

And this is the whole script for better reading:

var isGameStarted = false;

var d = new Audio("dSharpNote.wav");
var a = new Audio("aSharpNote.wav");
var g = new Audio("gSharpNote.wav");
var c = new Audio("cNote.wav");

var btns = ["c", "g", "a", "d"];
var randomOrder = "";

var playerInputOrder = "";

var timer = 1000;

function startGame() {
    isGameStarted = true;         //So players won't be able to just press the simon's buttons.
    randomOrder = "";             //A variable to keep the random order given by the simon.
    playerInputOrder = "";        //A variable to keep the random order the player inputs.
    randomSimon();                //Called to give the first button in the order.
}

function randomSimon() {                                       //Adds one random button to the order and saves the order.
    var randomBtn = btns[Math.floor(Math.random() * 4)];       //Adds the random button.
    randomOrder += randomBtn;                                  //Saves the random order.
    for  (i = 0; i <= randomOrder.length - 1; i++) {           //this should play all the audios one by one according the saved order
        for (s = 0; s <= i; s++) {
            var someText = "";
            someText += randomOrder.charAt(s);
            playAudio(randomOrder.charAt(s));
            document.getElementById('debug').innerHTML = someText;         //this is for debugin, should be ignored.
            timer(500);
        }
    }
}

function timer(delayInMS) {
    var time = new Date();
    var currentTime = time.getTime();
    var nextTime = time.getTime() + delayInMS;
    while (currentTime != nextTime) {
        time = new Date();
        currentTime = time.getTime();
    }
}

function playerProgress(btn) {                        //Getting the player's input and checks if it's in the right order.
    if (isGameStarted == true) {
        var btnClicked = btn.id;                      //Gets the id of the button the player clicked.
        playAudio(btnClicked);                        //So this could play it's audio.
        playerInputOrder += btnClicked;
        if (playerInputOrder.length == randomOrder.length) {
            if (playerInputOrder == randomOrder) {
                playerInputOrder = "";
                setTimeout(randomSimon, 1000);
            } else {
                document.getElementById('scoreText').innerHTML = randomOrder + " Game Over!";
                isGameStarted = false;               //Makes the player unable to play the simon's button's audios.
            }
        }
        document.getElementById('debug').innerHTML = playerInputOrder;
    }
}

function playAudio(btnSound) {
    if (btnSound == "c") {
        c.play();
    }
    if (btnSound == "g") {
        g.play();
    }
    if (btnSound == "a") {
        a.play();
    }
    if (btnSound == "d") {
        d.play();
    }
}

function someInterval() {
    var i = 0;
    var anInterval = setInterval(function() {
        i++;
        if (i > 11) {
            clearInterval(anInterval);
            timer *= 2;
        }
    }, timer);
}

Body:
So you want to have a pause after each playAudio call?

I would still go for timeouts

var sounds = {};
sounds.a = ...;
sounds.b = ...;

function playAudio(sound, callback) {
    if (typeof sounds[sound] === "undefined") {
        throw "sound not available";
    }
    sounds[sound].play();
    if (typeof callback !== "undefined") {
        window.setTimeout(callback, 500);
    }
}

// play a - pause - b - pause c
playAudio("a", function(){
    playAudio("b", function() {
        playAudio("c");
    });
});

if you build the sequence first you can do this dynamic too

var sequence = ["a", "b", "c"];
var pointer = 0;

playAudio(sequene[pointer], function() {
    pointer += 1;
    if (typeof sequence[pointer] !== "undefined") {
        playAudio(sequence[pointer], this); // this will be bound to the function itself
    } else {
        alert("sequence finished");
    }
});

this is not tested but it should work, let me know if not.


问:
Is it possible to explicitly define a swagger method upfront using swashbuckle for aspnetcore?
I am currently using identityserver middleware in my project to implement an oauth service. I would like to use swagger to define some of the methods available in this middleware such as /Connect/Token which is used to acquire and access token.

Unfortunately since this is middleware I do not have implementations of controllers that handle the http requests - since the requests are handled in the middleware.

Is it possible to explicitly define upfront a swaggerdoc with all the endpoint information (such as url, params etc) if you are using a middleware that handles all http requests?

答:
I was unable to find a method for dynamically generating swagger documentation for the identityserver endpoints.

However as a workaround I created a manual swagger.json file using the swagger editor. I was able to export a swagger.json file from the editor. I added the file to my application and was able generate the swagger ui with the following code.

```<code>// serve static files
app.UseStaticFiles();

// id server middleware
app.UseIdentityServer();

// points to my static swagger.json file
app.UseSwaggerUI(c =>
{
   c.SwaggerEndpoint("/swagger.json", "My API");
});
</code>```

Body:
I was unable to find a method for dynamically generating swagger documentation for the identityserver endpoints.

However as a workaround I created a manual swagger.json file using the swagger editor. I was able to export a swagger.json file from the editor. I added the file to my application and was able generate the swagger ui with the following code.

// serve static files
app.UseStaticFiles();

// id server middleware
app.UseIdentityServer();

// points to my static swagger.json file
app.UseSwaggerUI(c =>
{
   c.SwaggerEndpoint("/swagger.json", "My API");
});


问:
VBA: Can't change Image Control picture after click on element
Setup

I have an Excel VBA UserForm with an Image Control element. When clicking on buttons in the form, the Image Control's Picture source is set / updated with the following code:

```<code>Set MyForm.imgControl.Picture = LoadPicture(pathToFile)
</code>```

Problem

When the user clicks on the Image Control, updating its Picture source doesn't work anymore. The problem occurs, no matter when in the workflow the Image Control is clicked:

Example 1: User clicks a button to set the Picture (and pictures sets correctly). User clicks on Image Control. User clicks a different button to change the Picture -> displayed picture doesn't change.

Example 2: User clicks on Image Control right after Form load. User clicks on button to change the Picture -> displayed picture doesn't change.

If the user never clicks on the Image Control, everything works perfectly smoothly. It's worth noting that clicking on the Image Control doesn't visibly focus it.

Question

Clicking on the Image Control shouldn't make a difference in whether or not the Picture can be updated or not. How can this be done? Or, at least, does anyone know why the explained behavior is happening, or is it just a bug?

The Control does have Click / MouseDown / ... events (which are empty), but they don't take a Cancel parameter.

答:
It does sound like a bug, as you say, but as a workaround, I'd suggest forcing a repaint after changing the picture:</p>

```<code>Set MyForm.imgControl.Picture = LoadPicture(pathToFile)
MyForm.Repaint
</code>```

Body:
Setup

I have an Excel VBA UserForm with an Image Control element. When clicking on buttons in the form, the Image Control's Picture source is set / updated with the following code:

Set MyForm.imgControl.Picture = LoadPicture(pathToFile)

Problem

When the user clicks on the Image Control, updating its Picture source doesn't work anymore. The problem occurs, no matter when in the workflow the Image Control is clicked:

Example 1: User clicks a button to set the Picture (and pictures sets correctly). User clicks on Image Control. User clicks a different button to change the Picture -> displayed picture doesn't change.

Example 2: User clicks on Image Control right after Form load. User clicks on button to change the Picture -> displayed picture doesn't change.

If the user never clicks on the Image Control, everything works perfectly smoothly. It's worth noting that clicking on the Image Control doesn't visibly focus it.

Question

Clicking on the Image Control shouldn't make a difference in whether or not the Picture can be updated or not. How can this be done? Or, at least, does anyone know why the explained behavior is happening, or is it just a bug?

The Control does have Click / MouseDown / ... events (which are empty), but they don't take a Cancel parameter.

Body:
It does sound like a bug, as you say, but as a workaround, I'd suggest forcing a repaint after changing the picture:

Set MyForm.imgControl.Picture = LoadPicture(pathToFile)
MyForm.Repaint


问:
python - How to parse numbers around a specific word/phrase
Suppose that I have a text like this:

Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences.

Let's say I'd like to get favorite numbers only in this text, for instance. I won't be able to know if there's a favorite number in this text, unless the phrase favorite number is present. So I'm basically trying to parse numbers around the phrase favorite number (or favorite numbers). The expected result should be something like this:

['5', '6', '7', '0']
```

<p>I tried using regex for that but I've failed so far. What's the most logical way to do this?</p>

<p>Edit: After reading @LouiseDavies's question, I'll add another example below:</p>

<p><code>Alice has 2 favorite numbers: 11 and 12. Bob has 10 favorite numbers: 0, 100, 1264, 598, 78496, 33546, 1028896, 23, 48, 6.</code></p>

<p>So in this example, my output should be something like this (the order doesn't matter):</p>

```['11', '12', '0', '100', '1264', '598', '78496', '33546', '1028896', '23', '48', '6']
```

答:
I'm in my phone so I can't check my code, in my home I will check it.

```<code>text = "Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences."
sentences = text.split('.')
numbers = set()
for sentence in sentences:
    if "favorite number" in sentence:
        numbers = numbers.union(set(sentence))
numbers = list(numbers.difference(set([*[chr(n) for n in range(32,48)],*[chr(n) for n in range(58,168)]])))
numbers = [int(x) for x in numbers]
print(numbers)
</code>```

Another way could be:

```<code>text = "Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences."
sentences = text.split('.')
numbers = []
for sentence in sentences:
    if "favorite number" in sentence:
        for character in sentence:
            try:
                number.append(int(character))
            except ValueError:
                pass
print(numbers)
</code>```

Using timeit.timeit and checking the function 100000 times (without the print()) it give me 3.614777436797135 for the first way and 12.934136042429973 for the second way. So the first isn't exactly ordered but it's 3.57 times faster.

Body:
Suppose that I have a text like this:

Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences.

Let's say I'd like to get favorite numbers only in this text, for instance. I won't be able to know if there's a favorite number in this text, unless the phrase favorite number is present. So I'm basically trying to parse numbers around the phrase favorite number (or favorite numbers). The expected result should be something like this:

['5', '6', '7', '0']

I tried using regex for that but I've failed so far. What's the most logical way to do this?

Edit: After reading @LouiseDavies's question, I'll add another example below:

Alice has 2 favorite numbers: 11 and 12. Bob has 10 favorite numbers: 0, 100, 1264, 598, 78496, 33546, 1028896, 23, 48, 6.

So in this example, my output should be something like this (the order doesn't matter):

['11', '12', '0', '100', '1264', '598', '78496', '33546', '1028896', '23', '48', '6']

Body:
I'm in my phone so I can't check my code, in my home I will check it.

text = "Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences."
sentences = text.split('.')
numbers = set()
for sentence in sentences:
    if "favorite number" in sentence:
        numbers = numbers.union(set(sentence))
numbers = list(numbers.difference(set([*[chr(n) for n in range(32,48)],*[chr(n) for n in range(58,168)]])))
numbers = [int(x) for x in numbers]
print(numbers)

Another way could be:

text = "Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences."
sentences = text.split('.')
numbers = []
for sentence in sentences:
    if "favorite number" in sentence:
        for character in sentence:
            try:
                number.append(int(character))
            except ValueError:
                pass
print(numbers)

Using timeit.timeit and checking the function 100000 times (without the print()) it give me 3.614777436797135 for the first way and 12.934136042429973 for the second way. So the first isn't exactly ordered but it's 3.57 times faster.


问:
Unable to open debugger port in IntelliJ IDEA
I have a problem that I can not set up my application in debug mode with IntelliJ IDE, but run mode is OK.

My OS is Windows 7, IDE is IntelliJ IDEA, web container is Tomcat 6. I have tried for a long time,  changed the HTTP port and the JMX port, but it did not work.

When I set up the app in debug mode with IntelliJ, it failed and the event log is:

16:05:35 Error running tomcat: Unable to open debugger port :
  java.net.BindException "Address already in use: JVM_Bind".

答:
I had this exact message.

The reason was that some IDE (I use Eclipse and Intellij) failed to shutdown the tomcat server.  Or maybe crashed before it could do so.

The solution was to navigate to C:\...\apache-tomcat-xxx\bin and run shutdown.


问:
Slow code in "inner joins" lists in python
I have seen several posts about lists in python here, but I don't find a correct answer to my question; because it is about optimize a code.

I have a python code to compare two lists. It has to find the same code, and modifying the value of the second positions. It finally works perfectly, but it takes a lot of time. In SQL this query take 2 minuts, no more...., however, here, I spend 15 minutes.... so I don't understand if it is problem of memory or bad code written.

I have two lists.
The first one [code, points]. The second [code, license]
If the first value(code) in the first list, match with the first value of the second list(code); it has to update the second value  of the first list (points) if the license is equal to 'THIS', for example:

```<code>itemswithscore = [5675, 0], [6676, 0], [9898, 0], [4545, 0]
itemswithlicense = [9999, 'ATR'], [9191, 'OPOP'], [9898, 'THIS'], [2222, 'PLPL']

for sublist1 in itemswithscore:
    for sublist2 in itemswithlicense:
        if sublist1[0] == sublist2[0]: #this is the "inner join" :)
            if sublist2[1] == 'THIS': #It has to be license 'THIS'
                sublist1[1] += 50 #I add 50 to the score value
</code>```

Finally, I have this list updated in the code 9868:

```<code>itemswithscore = [5675, 0], [6676, 0], [9898, 50], [4545, 0]
</code>```

It is true that the two lists have 80.000 values everyone.. :(

Thanks in advance!!!

答:
I'll suggest to transform/keep your data structure into/as dicts. In that way, you won't need to iterate over both lists with nested for loops - an O(n2) or O(n x m) operation - searching for where the lists' code numbers align before updating the score value.

You'll simply update the value of the score where the key at the corresponding dict matches the search string:

```<code>dct_score = dict(itemswithscore)
dct_license = dict(itemswithlicense)
for k in dct_score:
    if dct_license.get(k) == 'THIS': # use dict.get in case key does not exist
         dct_score[k] += 50
</code>```

Body:
I have seen several posts about lists in python here, but I don't find a correct answer to my question; because it is about optimize a code.

I have a python code to compare two lists. It has to find the same code, and modifying the value of the second positions. It finally works perfectly, but it takes a lot of time. In SQL this query take 2 minuts, no more...., however, here, I spend 15 minutes.... so I don't understand if it is problem of memory or bad code written.

I have two lists.
The first one [code, points]. The second [code, license]
If the first value(code) in the first list, match with the first value of the second list(code); it has to update the second value  of the first list (points) if the license is equal to 'THIS', for example:

itemswithscore = [5675, 0], [6676, 0], [9898, 0], [4545, 0]
itemswithlicense = [9999, 'ATR'], [9191, 'OPOP'], [9898, 'THIS'], [2222, 'PLPL']

for sublist1 in itemswithscore:
    for sublist2 in itemswithlicense:
        if sublist1[0] == sublist2[0]: #this is the "inner join" :)
            if sublist2[1] == 'THIS': #It has to be license 'THIS'
                sublist1[1] += 50 #I add 50 to the score value

Finally, I have this list updated in the code 9868:

itemswithscore = [5675, 0], [6676, 0], [9898, 50], [4545, 0]

It is true that the two lists have 80.000 values everyone.. :(

Thanks in advance!!!

Body:
I'll suggest to transform/keep your data structure into/as dicts. In that way, you won't need to iterate over both lists with nested for loops - an O(n2) or O(n x m) operation - searching for where the lists' code numbers align before updating the score value.

You'll simply update the value of the score where the key at the corresponding dict matches the search string:

dct_score = dict(itemswithscore)
dct_license = dict(itemswithlicense)
for k in dct_score:
    if dct_license.get(k) == 'THIS': # use dict.get in case key does not exist
         dct_score[k] += 50


问:
how to count up variables in java
my problem is the following: I want to set all panes white, just like this:

```<code>    paneVfeld1.setStyle("-fx-background-color: white");
    paneVfeld2.setStyle("-fx-background-color: white");
    paneVfeld3.setStyle("-fx-background-color: white");
    paneVfeld4.setStyle("-fx-background-color: white");
    paneVfeld5.setStyle("-fx-background-color: white");
    paneVfeld6.setStyle("-fx-background-color: white");
    paneVfeld7.setStyle("-fx-background-color: white");
    paneVfeld8.setStyle("-fx-background-color: white");
    paneVfeld9.setStyle("-fx-background-color: white");
    paneVfeld10.setStyle("-fx-background-color: white");
</code>```

But i seriously can´t do this for all my 42 panes, how can i shorten that, with an Array?, anything else?, thx for the help :)

答:
You can put all your paneVfelds into a List and then iterate over it. For example:

```<code>List<PaneVfeld> paneVfelds = new ArrayList<>();
paneVfelds.forEach(paneVfeld -> paneVfeld.setStyle("-fx-background-color: white"));
</code>```

Title: how to count up variables in java

Body:
my problem is the following: I want to set all panes white, just like this:

    paneVfeld1.setStyle("-fx-background-color: white");
    paneVfeld2.setStyle("-fx-background-color: white");
    paneVfeld3.setStyle("-fx-background-color: white");
    paneVfeld4.setStyle("-fx-background-color: white");
    paneVfeld5.setStyle("-fx-background-color: white");
    paneVfeld6.setStyle("-fx-background-color: white");
    paneVfeld7.setStyle("-fx-background-color: white");
    paneVfeld8.setStyle("-fx-background-color: white");
    paneVfeld9.setStyle("-fx-background-color: white");
    paneVfeld10.setStyle("-fx-background-color: white");

But i seriously can´t do this for all my 42 panes, how can i shorten that, with an Array?, anything else?, thx for the help :)

Body:
You can put all your paneVfelds into a List and then iterate over it. For example:

List<PaneVfeld> paneVfelds = new ArrayList<>();
paneVfelds.forEach(paneVfeld -> paneVfeld.setStyle("-fx-background-color: white"));


问:
Use EXISTS in SQL for multiple select
I have a table STATUSES which contain columns NAME and ACTIVE_FLAG.The column value of NAME may have new, pending, cancel. I want to generate a new output for the count of each NAME with ACTIVE_FLAG=Y

By thinking to use EXISTS to select records for single NAME,

```<code>SELECT COUNT(*) AS PENDING
FROM STATUSES
WHERE EXISTS (select NAME from STATUSES where NAME='Pending' and ACTIVE_FLAG = 'Y')
</code>```

Anyway if I can join other statuses count in a single SQL?

答:
Seems like count and group by

```<code>SELECT
    name
  , count(*)
FROM statuses
WHERE active_flag = 'Y'
GROUP BY name
</code>```

Title: Use EXISTS in SQL for multiple select

Body:
I have a table STATUSES which contain columns NAME and ACTIVE_FLAG.The column value of NAME may have new, pending, cancel. I want to generate a new output for the count of each NAME with ACTIVE_FLAG=Y

By thinking to use EXISTS to select records for single NAME,

SELECT COUNT(*) AS PENDING
FROM STATUSES
WHERE EXISTS (select NAME from STATUSES where NAME='Pending' and ACTIVE_FLAG = 'Y')

Anyway if I can join other statuses count in a single SQL?

Body:
Seems like count and group by

SELECT
    name
  , count(*)
FROM statuses
WHERE active_flag = 'Y'
GROUP BY name


问:
Extend the ClaimsPrincipal and ClaimsIdentity classes in MVC-6
I've been trying to figure this thing out for a few days now, but have to turn to you guys (again).

As the title says, I would like to implement my custom ClaimsPrincipal and ClaimsIdentity, so that I can attach a few more properties to my Identity-instance.

I have done this earlier in MVC-5, using Global.asax.cs and an inherited  BaseController. In MVC-6 it seems like startup.cs would be the entry point for this, but I can't figure it out.

These are my two classes:

```<code>public class BaseIdentity : ClaimsIdentity
{
    public Guid UserId { get; set; }
    public Guid OrgId { get; set; }
    public string OrgName { get; set; }

    public BaseIdentity()
    {
    }
}
</code>```

And..

```<code>public class BasePrincipal : ClaimsPrincipal
{
    private readonly BaseIdentity _identity;

    public BasePrincipal(BaseIdentity identity)
    {
        _identity = identity;
    }

    public new BaseIdentity Identity
    {
        get { return _identity; }
    }
}
</code>```

How can I use these classes, instead of the default, when creating / retrieving Auth cookie?

There is a method called IApplicationBuilder.UseClaimsTransformation() , but can't find any documentation on how to use it - if it's even for this scenario?

Help much appreciated at this point! :)

BTW:  I would like to point out that I've asked a similar question a week ago, when I first encountered this challenge. I got an answer, but this is something that I really have to fix, to make my website usable on MVC-6.

答:
I've done this using extension methods instead of inheritance.</p>

```<code>public static class PrincipalExtensions
{
    public static string GetEmployeeNumber(this ClaimsPrincipal claimsPrincipal)
    {
        return claimsPrincipal.FindFirstValue("EmployeeNumber");
    }
}
</code>```

Body:
I've been trying to figure this thing out for a few days now, but have to turn to you guys (again).

As the title says, I would like to implement my custom ClaimsPrincipal and ClaimsIdentity, so that I can attach a few more properties to my Identity-instance.

I have done this earlier in MVC-5, using Global.asax.cs and an inherited  BaseController. In MVC-6 it seems like startup.cs would be the entry point for this, but I can't figure it out.

These are my two classes:

public class BaseIdentity : ClaimsIdentity
{
    public Guid UserId { get; set; }
    public Guid OrgId { get; set; }
    public string OrgName { get; set; }

    public BaseIdentity()
    {
    }
}

And..

public class BasePrincipal : ClaimsPrincipal
{
    private readonly BaseIdentity _identity;

    public BasePrincipal(BaseIdentity identity)
    {
        _identity = identity;
    }

    public new BaseIdentity Identity
    {
        get { return _identity; }
    }
}

How can I use these classes, instead of the default, when creating / retrieving Auth cookie?

There is a method called IApplicationBuilder.UseClaimsTransformation() , but can't find any documentation on how to use it - if it's even for this scenario?

Help much appreciated at this point! :)

BTW:  I would like to point out that I've asked a similar question a week ago, when I first encountered this challenge. I got an answer, but this is something that I really have to fix, to make my website usable on MVC-6.

Body:
I've done this using extension methods instead of inheritance.

public static class PrincipalExtensions
{
    public static string GetEmployeeNumber(this ClaimsPrincipal claimsPrincipal)
    {
        return claimsPrincipal.FindFirstValue("EmployeeNumber");
    }
}


答:
It would be very efficient if you can use pandas.

So You can make two dataframes and merge them on a single column

Something like this

```<code>itemswithscore = [5675, 0], [6676, 0], [9898, 0], [4545, 0]
itemswithlicense = [9999, 'ATR'], [9191, 'OPOP'], [9898, 'THIS'], [2222, 'PLPL']

df1 = pd.DataFrame(list(itemswithscore), columns =['code', 'points'])
df2 = pd.DataFrame(list(itemswithlicence), columns=['code', 'license'])

df3 = pd.merge(df1, df2 , on='code', how='inner')
df3 = df3.drop('points', axis=1)
</code>```

Hope this helps, accept if correct

Cheers!

Title: Slow code in "inner joins" lists in python

Body:
It would be very efficient if you can use pandas.

So You can make two dataframes and merge them on a single column

Something like this

itemswithscore = [5675, 0], [6676, 0], [9898, 0], [4545, 0]
itemswithlicense = [9999, 'ATR'], [9191, 'OPOP'], [9898, 'THIS'], [2222, 'PLPL']

df1 = pd.DataFrame(list(itemswithscore), columns =['code', 'points'])
df2 = pd.DataFrame(list(itemswithlicence), columns=['code', 'license'])

df3 = pd.merge(df1, df2 , on='code', how='inner')
df3 = df3.drop('points', axis=1)

Hope this helps, accept if correct

Cheers!


问:
Regex: Exact plus wildcard text
I'm looking for regex for my auto suggest key search.

String example:

```<code>universal studio japan
universal
japan
</code>```

basically if user types "universal jap" or "universal japan",
"universal studio japan" should match.

答:
this doesn't feel like a very good question, but anyway here you go:

```<code>/universal .+ japan/gi    => gi for global & case insensitive
</code>```

take a look at https://regex101.com/

Title: Regex: Exact plus wildcard text

Body:
I'm looking for regex for my auto suggest key search.

String example:

universal studio japan
universal
japan

basically if user types "universal jap" or "universal japan",
"universal studio japan" should match.

Body:
this doesn't feel like a very good question, but anyway here you go:

/universal .+ japan/gi    => gi for global & case insensitive

take a look at https://regex101.com/


答:
You can use setTimeout and give it an increasing as you go through the colors:

```<code>function randomSimon() {                                       //Adds one random button to the order and saves the order.
    var randomBtn = btns[Math.floor(Math.random() * 4)];       //Adds the random button.
    randomOrder += randomBtn;                                  //Saves the random order.
    for  (i = 0; i <= randomOrder.length - 1; i++) {           //this should play all the audios one by one according the saved order
        for (s = 0; s <= i; s++) {
            var someText = "";
            someText += randomOrder.charAt(s);
  >>>>>>>   setTimeout(function() { playAudio(randomOrder.charAt(s)); },2000*s);
            document.getElementById('debug').innerHTML = someText;         //this is for debugin, should be ignored.

        }
    }
}
</code>```

This will play first sound instantly, second one after 2s, third after 4s and so on. Hope it helps!

EDIT

There you have a example with a for loop and setTimeout:

for (s = 0; s <= 2; s++) {
  setTimeout(function() { console.log('hello world'); },2000*s);
}```
</div>
</div>
</p>

<hr>

<h2>EDIT 2</h2>

<p>OK It seems that memory accessing is messing a bit around here. Try to do it like this.</p>

<p>First create a function to do what you want to do after waiting:</p>

```var delayedPlay = function(c,delay) {
  setTimeout(
    function() { playAudio(c); },
    delay);
}
```

<p>Then call it inside the <code>for</code> loop:</p>

```function randomSimon() {                                       //Adds one random button to the order and saves the order.
    var randomBtn = btns[Math.floor(Math.random() * 4)];       //Adds the random button.
    randomOrder += randomBtn;                                  //Saves the random order.
    for  (i = 0; i <= randomOrder.length - 1; i++) {           //this should play all the audios one by one according the saved order
        for (s = 0; s <= i; s++) {
            var someText = "";
            someText += randomOrder.charAt(s);
  >>>>>>>   delayedPlay(randomOrder.charAt(s),2000*s);
            document.getElementById('debug').innerHTML = someText;         //this is for debugin, should be ignored.

        }
    }
}
```

Title: Delay between loop's first execution and the next one

Body:
I'm trying to make a simon game and I'm almost done but I got an issue.
In a simon game, when the simon's giving you the order (which represented by blinking lights and audio for each light) which you need to remember and repeat afterwards, there's a short delay between each blink (with it's audio) to the next one.

So now, my simon is making sounds but it's doing them all at once, with no delay. I tried using setIntarvel and setTimeout but still it played all audios at once.

Since adding the blinking shouldn't be that tough I'm keeping it to the end.

Then I built a timer function:

function timer(delayInMS) {
    var time = new Date();
    var currentTime = time.getTime();
    var nextTime = time.getTime() + delayInMS;
    while (currentTime != nextTime) {
        time = new Date();
        currentTime = time.getTime();
        }
}

And used it inside the function which playing the audios, but it's still doing the same thing - playing it all at once.

This is the function which responsible for the audios:

function playAudio(btnSound) {
    if (btnSound == "c") {
        c.play();
    }
    if (btnSound == "g") {
        g.play();
    }
    if (btnSound == "a") {
        a.play();
    }
    if (btnSound == "d") {
        d.play();
    }
}

And this function responsible for the logic of the game:

var btns = ["c", "g", "a", "d"];
var randomOrder = "";

var playerInputOrder = "";

var timer = 1000;    //For timer()

function randomSimon() {
var randomBtn = btns[Math.floor(Math.random() * 4)];
randomOrder += randomBtn;
for  (i = 0; i <= randomOrder.length - 1; i++) {
    for (s = 0; s <= i; s++) {
        var someText = "";
        someText += randomOrder.charAt(s);
        playAudio(randomOrder.charAt(s));
        document.getElementById('debug').innerHTML = someText; //this is for debugin, should be ignored.
        timer(500);
    }
}

}

And this is the whole script for better reading:

var isGameStarted = false;

var d = new Audio("dSharpNote.wav");
var a = new Audio("aSharpNote.wav");
var g = new Audio("gSharpNote.wav");
var c = new Audio("cNote.wav");

var btns = ["c", "g", "a", "d"];
var randomOrder = "";

var playerInputOrder = "";

var timer = 1000;

function startGame() {
    isGameStarted = true;         //So players won't be able to just press the simon's buttons.
    randomOrder = "";             //A variable to keep the random order given by the simon.
    playerInputOrder = "";        //A variable to keep the random order the player inputs.
    randomSimon();                //Called to give the first button in the order.
}

function randomSimon() {                                       //Adds one random button to the order and saves the order.
    var randomBtn = btns[Math.floor(Math.random() * 4)];       //Adds the random button.
    randomOrder += randomBtn;                                  //Saves the random order.
    for  (i = 0; i <= randomOrder.length - 1; i++) {           //this should play all the audios one by one according the saved order
        for (s = 0; s <= i; s++) {
            var someText = "";
            someText += randomOrder.charAt(s);
            playAudio(randomOrder.charAt(s));
            document.getElementById('debug').innerHTML = someText;         //this is for debugin, should be ignored.
            timer(500);
        }
    }
}

function timer(delayInMS) {
    var time = new Date();
    var currentTime = time.getTime();
    var nextTime = time.getTime() + delayInMS;
    while (currentTime != nextTime) {
        time = new Date();
        currentTime = time.getTime();
    }
}

function playerProgress(btn) {                        //Getting the player's input and checks if it's in the right order.
    if (isGameStarted == true) {
        var btnClicked = btn.id;                      //Gets the id of the button the player clicked.
        playAudio(btnClicked);                        //So this could play it's audio.
        playerInputOrder += btnClicked;
        if (playerInputOrder.length == randomOrder.length) {
            if (playerInputOrder == randomOrder) {
                playerInputOrder = "";
                setTimeout(randomSimon, 1000);
            } else {
                document.getElementById('scoreText').innerHTML = randomOrder + " Game Over!";
                isGameStarted = false;               //Makes the player unable to play the simon's button's audios.
            }
        }
        document.getElementById('debug').innerHTML = playerInputOrder;
    }
}

function playAudio(btnSound) {
    if (btnSound == "c") {
        c.play();
    }
    if (btnSound == "g") {
        g.play();
    }
    if (btnSound == "a") {
        a.play();
    }
    if (btnSound == "d") {
        d.play();
    }
}

function someInterval() {
    var i = 0;
    var anInterval = setInterval(function() {
        i++;
        if (i > 11) {
            clearInterval(anInterval);
            timer *= 2;
        }
    }, timer);
}

Body:
You can use setTimeout and give it an increasing as you go through the colors:

function randomSimon() {                                       //Adds one random button to the order and saves the order.
    var randomBtn = btns[Math.floor(Math.random() * 4)];       //Adds the random button.
    randomOrder += randomBtn;                                  //Saves the random order.
    for  (i = 0; i <= randomOrder.length - 1; i++) {           //this should play all the audios one by one according the saved order
        for (s = 0; s <= i; s++) {
            var someText = "";
            someText += randomOrder.charAt(s);
  >>>>>>>   setTimeout(function() { playAudio(randomOrder.charAt(s)); },2000*s);
            document.getElementById('debug').innerHTML = someText;         //this is for debugin, should be ignored.

        }
    }
}

This will play first sound instantly, second one after 2s, third after 4s and so on. Hope it helps!

EDIT

There you have a example with a for loop and setTimeout:

for (s = 0; s <= 2; s++) {
  setTimeout(function() { console.log('hello world'); },2000*s);
}

EDIT 2

OK It seems that memory accessing is messing a bit around here. Try to do it like this.

First create a function to do what you want to do after waiting:

var delayedPlay = function(c,delay) {
  setTimeout(
    function() { playAudio(c); },
    delay);
}

Then call it inside the for loop:

function randomSimon() {                                       //Adds one random button to the order and saves the order.
    var randomBtn = btns[Math.floor(Math.random() * 4)];       //Adds the random button.
    randomOrder += randomBtn;                                  //Saves the random order.
    for  (i = 0; i <= randomOrder.length - 1; i++) {           //this should play all the audios one by one according the saved order
        for (s = 0; s <= i; s++) {
            var someText = "";
            someText += randomOrder.charAt(s);
  >>>>>>>   delayedPlay(randomOrder.charAt(s),2000*s);
            document.getElementById('debug').innerHTML = someText;         //this is for debugin, should be ignored.

        }
    }
}


问:
How to remove the duplicate record while uploading the excel in c# using bulk upload
Here is my query I want to add extra option to remove the duplicate file while upload.

```<code>protected void Page_Load(object sender, EventArgs e)
{ }

protected void Button1_Click(object sender, EventArgs e)
{
    int rollno;
    String sname;
    String fname;
    String mname;

    string path = Path.GetFileName(FileUpload1.FileName);
    path = path.Replace("1", "4");
    FileUpload1.SaveAs(Server.MapPath("~/ExcelFile/") + path);
    String ExcelPath = Server.MapPath("~/ExcelFile/") + path;
    OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
    mycon.Open();
    OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
    OleDbDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        // Response.Write("<br/>"+dr[0].ToString());
        rollno = Convert.ToInt32(dr[0].ToString());
        sname = dr[1].ToString();
        fname = dr[2].ToString();
        mname = dr[3].ToString();

        SqlConnection n = new SqlConnection(@"Data Source=bu1-d22x7n62\sqlexpress;Initial Catalog=dummy;Persist Security Info=True;User ID=sa;Password=P@ssw0rd");
        n.Open();
        savedata(rollno, sname, fname, mname);
    }
    Label3.Text = "Data Has Been Saved Successfully";
}

private void savedata(int rollno1, String sname1, String fname1, String mname1)
{
    String query = "insert into studentdetail(rollno,name,fathername,mothername) values(" + rollno1 + ",'" + sname1 + "','" + fname1 + "','" + mname1 + "')";

    SqlConnection con = new SqlConnection(@"Data Source=bu1-d22x7n62\sqlexpress;Initial Catalog=dummy;Persist Security Info=True;User ID=sa;Password=P@ssw0rd");
    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = query;
    cmd.Connection = con;
    cmd.ExecuteNonQuery();
}
</code>```

In this I have add bulk upload option by clicking on the button and I want to alter in this query for removing duplicate record

答:
```<code> if (System.IO.File.Exists("path to file name"))
        {
            System.IO.File.Delete("path to file name");
        }
        else
        {
            //do you other stuff here
        }
</code>```

Body:
Here is my query I want to add extra option to remove the duplicate file while upload.

protected void Page_Load(object sender, EventArgs e)
{ }

protected void Button1_Click(object sender, EventArgs e)
{
    int rollno;
    String sname;
    String fname;
    String mname;

    string path = Path.GetFileName(FileUpload1.FileName);
    path = path.Replace("1", "4");
    FileUpload1.SaveAs(Server.MapPath("~/ExcelFile/") + path);
    String ExcelPath = Server.MapPath("~/ExcelFile/") + path;
    OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
    mycon.Open();
    OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
    OleDbDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        // Response.Write("
"+dr[0].ToString());
        rollno = Convert.ToInt32(dr[0].ToString());
        sname = dr[1].ToString();
        fname = dr[2].ToString();
        mname = dr[3].ToString();

        SqlConnection n = new SqlConnection(@"Data Source=bu1-d22x7n62\sqlexpress;Initial Catalog=dummy;Persist Security Info=True;User ID=sa;Password=P@ssw0rd");
        n.Open();
        savedata(rollno, sname, fname, mname);
    }
    Label3.Text = "Data Has Been Saved Successfully";
}

private void savedata(int rollno1, String sname1, String fname1, String mname1)
{
    String query = "insert into studentdetail(rollno,name,fathername,mothername) values(" + rollno1 + ",'" + sname1 + "','" + fname1 + "','" + mname1 + "')";

    SqlConnection con = new SqlConnection(@"Data Source=bu1-d22x7n62\sqlexpress;Initial Catalog=dummy;Persist Security Info=True;User ID=sa;Password=P@ssw0rd");
    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = query;
    cmd.Connection = con;
    cmd.ExecuteNonQuery();
}

In this I have add bulk upload option by clicking on the button and I want to alter in this query for removing duplicate record


问:
Numbers aren't displaying for my output
I am trying to get the numbers display as my output from the ArrayList I have created. I asked the user how many numbers do they want in the ArrayList, then used a for loop to generate random numbers between 1-100 and they would be thrown into the ArrayList however many times the user wants the to be. I just can't get the to be displayed, here's my code:

The KNW_MyList class:

```<code>   public class KNW_MyList<T extends Number>
{
  //Create the array list object of type T
  ArrayList<T> al = new ArrayList<T>();

  /**
   * The adds method, add a number of type T to
   * array list.
   * @param number, the number to be added.
   * */
  public void add( T number)
  {
    al.add(number);
  }

  /**
   * The largest method, returns the largest value in the
   * array list.
   * */
  public T largest()
  {
    T large = al.get(0);

    //For-loop to find the largest value
    for(int x = 0; x < al.size(); x++)
    {
      if(al.get(x).toString().compareTo(large.toString()) > 0)
      {
        large = al.get(0);
      }
    }
    return large;
  }

  /**
   * The smallest method, returns the smallest value in the
   * array list.
   * */
  public T smallest()
  {
    T small = al.get(0);

    //For-loop to find the largest value
    for(int x = 0; x < al.size(); x++)
    {
      if(al.get(x).toString().compareTo(small.toString()) < 0)
      {
        small = al.get(0);
      }
    }
    return small;
  }

  /**
   * The show method, wil show the elements in the array
   * list.
   * */
  public void show()
  {
    System.out.println(al);
  }
}
</code>```

Demo:

```<code>import java.util.*;
import java.lang.Math;

public class KNW_MyListDemo
{
  public static void main(String args[])
  {
    //Create random class
    Random rand = new Random();

int numbers;
Scanner scan = new Scanner(System.in);

//Create ArrayList object
KNW_MyList<Number> numList = new KNW_MyList<Number>();

//Ask the user how many numbers they want in the array
System.out.println("How many numbers do you want?: ");
numbers = scan.nextInt();

if(numbers <= 0)
{
  System.out.println("Not Valid!");
}
else
{
  for(int x = 1; x >= numbers; x++)
  {
    int num = rand.nextInt(100) + 1;
    numList.add(num);
    x++;
  }

//Call the show method
System.out.println("Numbers in the array: ");
numList.show();
}

  }
}
</code>```

Is there something wrong with my ArrayList or my forloop? I am not quite sure, am kinda new to array list so maybe this might or might not have any effect? I just wanna get the random numbers to display 'x' amount of times, 'x' being the number of times the user wants.

答:
a few bugs in your loop. It should be</p>

```<code>for(int x = 0; x < numbers; x++)
{
    int num = rand.nextInt(100) + 1;
    numList.add(num);
}
</code>```

Title: Numbers aren't displaying for my output

Body:
I am trying to get the numbers display as my output from the ArrayList I have created. I asked the user how many numbers do they want in the ArrayList, then used a for loop to generate random numbers between 1-100 and they would be thrown into the ArrayList however many times the user wants the to be. I just can't get the to be displayed, here's my code:

The KNW_MyList class:

   public class KNW_MyList<T extends Number>
{
  //Create the array list object of type T
  ArrayList<T> al = new ArrayList<T>();

  /**
   * The adds method, add a number of type T to
   * array list.
   * @param number, the number to be added.
   * */
  public void add( T number)
  {
    al.add(number);
  }

  /**
   * The largest method, returns the largest value in the
   * array list.
   * */
  public T largest()
  {
    T large = al.get(0);

    //For-loop to find the largest value
    for(int x = 0; x < al.size(); x++)
    {
      if(al.get(x).toString().compareTo(large.toString()) > 0)
      {
        large = al.get(0);
      }
    }
    return large;
  }

  /**
   * The smallest method, returns the smallest value in the
   * array list.
   * */
  public T smallest()
  {
    T small = al.get(0);

    //For-loop to find the largest value
    for(int x = 0; x < al.size(); x++)
    {
      if(al.get(x).toString().compareTo(small.toString()) < 0)
      {
        small = al.get(0);
      }
    }
    return small;
  }

  /**
   * The show method, wil show the elements in the array
   * list.
   * */
  public void show()
  {
    System.out.println(al);
  }
}

Demo:

import java.util.*;
import java.lang.Math;

public class KNW_MyListDemo
{
  public static void main(String args[])
  {
    //Create random class
    Random rand = new Random();

int numbers;
Scanner scan = new Scanner(System.in);

//Create ArrayList object
KNW_MyList<Number> numList = new KNW_MyList<Number>();

//Ask the user how many numbers they want in the array
System.out.println("How many numbers do you want?: ");
numbers = scan.nextInt();

if(numbers <= 0)
{
  System.out.println("Not Valid!");
}
else
{
  for(int x = 1; x >= numbers; x++)
  {
    int num = rand.nextInt(100) + 1;
    numList.add(num);
    x++;
  }

//Call the show method
System.out.println("Numbers in the array: ");
numList.show();
}

  }
}

Is there something wrong with my ArrayList or my forloop? I am not quite sure, am kinda new to array list so maybe this might or might not have any effect? I just wanna get the random numbers to display 'x' amount of times, 'x' being the number of times the user wants.

Body:
a few bugs in your loop. It should be

for(int x = 0; x < numbers; x++)
{
    int num = rand.nextInt(100) + 1;
    numList.add(num);
}