问:
Where is the memory leak?
my dear friends. Could you help me to figure out where do I have memory leak in my application.

There are two activities.

In first activity I'v got a rather big static ArrayList consists of bitmaps and another needed information. I made it static, because I need to take it from another activity, and It's loading takes to much time.

In another activity, I also have one static field, using as a key for getting data which present in an Intent from previous activity.

If I try to start one activity from another and go back several times, I get shutting down VM.

To be more clear, here is a snippet of my code:

```<code>public class MoviesGallery extends Activity
{
...
private static ArrayList<Movie> films = new ArrayList<Movie>();
...
public void contextButtonsClickHandler(View v)
{
    switch(v.getId())
    {
        case R.id.play_button:
            Log.d("Context Button", "Play button has clicked");
            mContextButtonHasPressed = true;
            Intent filmData = new Intent(MoviesGallery.this, MovieInfo.class);
            filmData.putExtra(MovieInfo.mPOS,mPOSITION_OF_CLICKED_ITEM);
            startActivityForResult(filmData, 1);
            break;
...
}
</code>```

And this is another activity:

```<code>public class FilmInfo extends Activity
{
    public static String mPOS = "pos";
    private int mNumOfFilm = -1;
    private LinearLayout mWall;
...
protected void onCreate(Bundle savedInstanceState)
{
        Bundle extra = getIntent().getExtras();
    mNumOfFilm=extra.getInt(mPOS);
...
        Drawable d = new BitmapDrawable(MoviesGallery.getMoviesArray().get(mNumOfFilm).getWall()));
    mWall = (LinearLayout) findViewById(R.id.Wall);
    mWall.setBackgroundDrawable(d);
    ...
        setResult(0);
    }
</code>```

答:
I would suggest that potentially memory-leak point is in FilmInfo class member:

```<code>private LinearLayout mWall;
</code>```

Layout has reference to Activity, which each time changes.
So to avoid keeping reference to dead Activity just use in FilmInfo class

```<code>@Override
 public boolean onContextItemSelected(MenuItem item)
{
     //blah-blah
     mWall=null;
}
</code>```

Anyway recipe is simple - try to avoid keeping objects which might contain references to Activity/Context objects.

ContentLicense: CC BY-SA 2.5

Title: Where is the memory leak?

Body:
my dear friends. Could you help me to figure out where do I have memory leak in my application.

There are two activities.

In first activity I'v got a rather big static ArrayList consists of bitmaps and another needed information. I made it static, because I need to take it from another activity, and It's loading takes to much time.

In another activity, I also have one static field, using as a key for getting data which present in an Intent from previous activity.

If I try to start one activity from another and go back several times, I get shutting down VM.

To be more clear, here is a snippet of my code:

public class MoviesGallery extends Activity
{
...
private static ArrayList<Movie> films = new ArrayList<Movie>();
...
public void contextButtonsClickHandler(View v)
{
    switch(v.getId())
    {
        case R.id.play_button:
            Log.d("Context Button", "Play button has clicked");
            mContextButtonHasPressed = true;
            Intent filmData = new Intent(MoviesGallery.this, MovieInfo.class);
            filmData.putExtra(MovieInfo.mPOS,mPOSITION_OF_CLICKED_ITEM);
            startActivityForResult(filmData, 1);
            break;
...
}

And this is another activity:

public class FilmInfo extends Activity
{
    public static String mPOS = "pos";
    private int mNumOfFilm = -1;
    private LinearLayout mWall;
...
protected void onCreate(Bundle savedInstanceState)
{
        Bundle extra = getIntent().getExtras();
    mNumOfFilm=extra.getInt(mPOS);
...
        Drawable d = new BitmapDrawable(MoviesGallery.getMoviesArray().get(mNumOfFilm).getWall()));
    mWall = (LinearLayout) findViewById(R.id.Wall);
    mWall.setBackgroundDrawable(d);
    ...
        setResult(0);
    }

Body:
I would suggest that potentially memory-leak point is in FilmInfo class member:

private LinearLayout mWall;

Layout has reference to Activity, which each time changes.
So to avoid keeping reference to dead Activity just use in FilmInfo class

@Override
 public boolean onContextItemSelected(MenuItem item)
{
     //blah-blah
     mWall=null;
}

Anyway recipe is simple - try to avoid keeping objects which might contain references to Activity/Context objects.


来源: stackexchange

问:
ERROR TypeError: Cannot read property 'unread' of undefined
I keep getting the error below when the page first loads, but I can just exit out of it and everything keeps working as expected.

```<code>ERROR TypeError: Cannot read property 'unread'
of undefined
at listing-element.ts:34
at Array.forEach (<anonymous>)
at SafeSubscriber._next (listing-element.ts:33)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
at SafeSubscriber.next (Subscriber.js:185)
at Subscriber._next (Subscriber.js:125)
at Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
</code>```

I am currently using Angular 4.4.3, Ionic-Angular 3.9.2, AngularFire2 5.0.0.

When I run the code below, everything works as expected, but I can't seem to get rid of the Cannot read property 'unread' error that pops up on init no matter how many if statements I wrap the offending bit of code in. It's like I have Schrodinger's Observable; I am simultaneously getting the data I am expecting, yet it's coming back undefined. I realize it's due to the async nature of Observables, but I did not have any issues with this until my team switched our database to Google Firestore and therefore had to upgrade AngularFire 2.

We're having similar issues with our pipes and HTML. For our HTML, usually wrapping the code within an
 will work, so that it will only appear once we get the listing data. However, wrapping the TypeScript within something like if (threads.length > 0 && threads) does nothing, as the data still console logs with the expected result.

```<code>    //listing-element.ts
    this.userId = this.auth.getUser().uid;
    this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads => {
          threads.forEach(thread => {
            if (thread[this.userId].unread) { // <-Line 34 is here
              this.unread = true;
            }
          })
        })

    //listing-provider
      checkUnreadThreads(listingId) {
        return this.afs.collection(`listings/${listingId}/threads`)
          .snapshotChanges()
          .map(actions => {
            return actions.map(action => {
              const id = action.payload.doc.id;
              const data = action.payload.doc.data();
              return { id, ...data }
            });
          })
      }

    //listing-element.html
    <notification-badge *ngIf="userId === listingUserId && page.activity === true && unread"></notification-badge>
</code>```

This is all the information I thought was pertinent, but if anyone needs more information, I'm more than happy to provide whatever I can.

答:
return { id, ...data } will concat the id and all data fields in to one.

now your thread look like this

```<code>id:....,
unread:....,
fieldx:....,
fieldy:..... etc
</code>```

try this code

```<code>this.userId = this.auth.getUser().uid;
this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads => {
      threads.forEach(thread => {
        if (thread.id == this.userId && thread.unread) {
          this.unread = true;
        }
      })
    })
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I keep getting the error below when the page first loads, but I can just exit out of it and everything keeps working as expected.

ERROR TypeError: Cannot read property 'unread'
of undefined
at listing-element.ts:34
at Array.forEach (<anonymous>)
at SafeSubscriber._next (listing-element.ts:33)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
at SafeSubscriber.next (Subscriber.js:185)
at Subscriber._next (Subscriber.js:125)
at Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)

I am currently using Angular 4.4.3, Ionic-Angular 3.9.2, AngularFire2 5.0.0.

When I run the code below, everything works as expected, but I can't seem to get rid of the Cannot read property 'unread' error that pops up on init no matter how many if statements I wrap the offending bit of code in. It's like I have Schrodinger's Observable; I am simultaneously getting the data I am expecting, yet it's coming back undefined. I realize it's due to the async nature of Observables, but I did not have any issues with this until my team switched our database to Google Firestore and therefore had to upgrade AngularFire 2.

We're having similar issues with our pipes and HTML. For our HTML, usually wrapping the code within an
 will work, so that it will only appear once we get the listing data. However, wrapping the TypeScript within something like if (threads.length > 0 && threads) does nothing, as the data still console logs with the expected result.

    //listing-element.ts
    this.userId = this.auth.getUser().uid;
    this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads => {
          threads.forEach(thread => {
            if (thread[this.userId].unread) { // <-Line 34 is here
              this.unread = true;
            }
          })
        })

    //listing-provider
      checkUnreadThreads(listingId) {
        return this.afs.collection(`listings/${listingId}/threads`)
          .snapshotChanges()
          .map(actions => {
            return actions.map(action => {
              const id = action.payload.doc.id;
              const data = action.payload.doc.data();
              return { id, ...data }
            });
          })
      }

    //listing-element.html
    <notification-badge *ngIf="userId === listingUserId && page.activity === true && unread"></notification-badge>

This is all the information I thought was pertinent, but if anyone needs more information, I'm more than happy to provide whatever I can.

Body:
return { id, ...data } will concat the id and all data fields in to one.

now your thread look like this

id:....,
unread:....,
fieldx:....,
fieldy:..... etc

try this code

this.userId = this.auth.getUser().uid;
this.listingProvider.checkUnreadThreads(this.listing.id).subscribe(threads => {
      threads.forEach(thread => {
        if (thread.id == this.userId && thread.unread) {
          this.unread = true;
        }
      })
    })


问:
I cannot run more than 4 threads on an i5 CPU?
I have made a program that is running 5 threads simultaneously. These 5 threads each will be running multiple time-consuming operations that can last around 3 hours in total.

Before the 2 hour mark, the UI seems to run fine. But I have discovered that after around 2 hours has passed, the UI becomes unresponsive and lags.
Furthermore, the results from the 5th thread becomes wrong or have bogus value. I have tried my best in optimising my coding but this still happens.

My company computer has an i5-6500 CPU and 8 GB of RAM. I have checked online that this CPU can only run 4 threads at a time. To run 5 or more threads, an i7-7700 with hyperthreading will be needed which can run 8 at a time.

Am I right about this hardware limitation? Or is there something I can do with my C# coding to overcome this problem? FYI, I'm using BackgroundWorker to handle my multithreading.

I have to confirm that it is absolutely a hardware problem before proposing to my boss that the company has to invest in a new CPU and motherboard.

Any advice is greatly appreciated. :)

```<code>private void Form1_Load(object sender, EventArgs e)
{
  using (StreamReader sr = new StreamReader(string.Concat(Directory.GetCurrentDirectory(), "\\limit.txt"), true))
       {
          String input; //read value limits from textfile and storing it in array
          int i = 1;
          while ((input = sr.ReadLine()) != null)
             {
                limit_memory[i]= input;
                i++;
             }
        }
    }

}
private void button1_Click(object sender, EventArgs e)
{
  //shows some textboxes that user has to fill and press enter to continue
}
private void button2_Click(object sender, EventArgs e)
{
  //shows some textboxes that user has to fill and press enter to continue
}
private void button3_Click(object sender, EventArgs e)
{
  //shows some textboxes that user has to fill and press enter to continue
}
private void button4_Click(object sender, EventArgs e)
{
  //shows some textboxes that user has to fill and press enter to continue
}
private void button5_Click(object sender, EventArgs e)
{
  //shows some textboxes that user has to fill and press enter to continue
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '\r')
      {
        if (backgroundWorker1.IsBusy != true)
           {
              object[] button1_var = { sentry1, terminal1, txtBox1_serial};
              backgroundWorker1.RunWorkerAsync(button1_var); //pass some arguments with an object
           }
      }
}

private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '\r')
      {
        if (backgroundWorker2.IsBusy != true)
           {
              object[] button2_var = { sentry2, terminal2, txtBox2_serial};
              backgroundWorker2.RunWorkerAsync(button2_var); //pass some arguments with an object
           }
      }
}
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '\r')
      {
        if (backgroundWorker3.IsBusy != true)
           {
              object[] button3_var = { sentry3, terminal3, txtBox3_serial};
              backgroundWorker3.RunWorkerAsync(button3_var); //pass some arguments with an object
           }
      }
}
private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '\r')
      {
        if (backgroundWorker4.IsBusy != true)
           {
              object[] button4_var = { sentry4, terminal4, txtBox4_serial};
              backgroundWorker4.RunWorkerAsync(button4_var); //pass some arguments with an object
           }
      }
}
private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '\r')
      {
        if (backgroundWorker5.IsBusy != true)
           {
              object[] button5_var = { sentry5, terminal5, txtBox5_serial};
              backgroundWorker5.RunWorkerAsync(button5_var); //pass some arguments with an object
           }
      }
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
  try
    {
      //uses the arguments passed and perform long operations
      //prints results to textFile1
    }
  catch
    {
      throw new BackgroundWorkerException(sernum, ex);//pass the unit's serial number to the error handler
    }
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
  try
    {
      //uses the arguments passed and perform long operations
      //prints results to textFile2
    }
  catch
    {
      throw new BackgroundWorkerException(sernum, ex);//pass the unit's serial number to the error handler
    }
}
private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
{
  try
    {
      //uses the arguments passed and perform long operations
      //prints results to textFile3
    }
  catch
    {
      throw new BackgroundWorkerException(sernum, ex);//pass the unit's serial number to the error handler
    }
}
private void backgroundWorker4_DoWork(object sender, DoWorkEventArgs e)
{
  try
    {
      //uses the arguments passed and perform long operations
      //prints results to textFile4
    }
  catch
    {
      throw new BackgroundWorkerException(sernum, ex);//pass the unit's serial number to the error handler
    }
}
private void backgroundWorker5_DoWork(object sender, DoWorkEventArgs e)
{
  try
    {
      //uses the arguments passed and perform long operations
      //prints results to textFile5
    }
  catch
    {
      throw new BackgroundWorkerException(sernum, ex);//pass the unit's serial number to the error handler
    }
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  //updates the UI on what operations are being run
}
private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  //updates the UI on what operations are being run
}
private void backgroundWorker3_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  //updates the UI on what operations are being run
}
private void backgroundWorker4_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  //updates the UI on what operations are being run
}
private void backgroundWorker5_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  //updates the UI on what operations are being run
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled == true) //if user cancels thread
    {
     //disconnect unit from PC, clears UI
    }
  else if(e.Error != null) //if error occurs in thread
    {
     string sernum = ((BackgroundWorkerException)e.Error).Sernum;
     //logs the serial number and error into a log text file
    }
  else //the program ends normally
    {
      //disconnect unit from PC, clears UI
    }
}
private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled == true) //if user cancels thread
    {
     //disconnect unit from PC, clears UI
    }
  else if(e.Error != null) //if error occurs in thread
    {
     string sernum = ((BackgroundWorkerException)e.Error).Sernum;
     //logs the serial number and error into a log text file
    }
  else //the program ends normally
    {
      //disconnect unit from PC, clears UI
    }
}
private void backgroundWorker3_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled == true) //if user cancels thread
    {
     //disconnect unit from PC, clears UI
    }
  else if(e.Error != null) //if error occurs in thread
    {
     string sernum = ((BackgroundWorkerException)e.Error).Sernum;
     //logs the serial number and error into a log text file
    }
  else //the program ends normally
    {
      //disconnect unit from PC, clears UI
    }
}
private void backgroundWorker4_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled == true) //if user cancels thread
    {
     //disconnect unit from PC, clears UI
    }
  else if(e.Error != null) //if error occurs in thread
    {
     string sernum = ((BackgroundWorkerException)e.Error).Sernum;
     //logs the serial number and error into a log text file
    }
  else //the program ends normally
    {
      //disconnect unit from PC, clears UI
    }
}
private void backgroundWorker5_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled == true) //if user cancels thread
    {
     //disconnect unit from PC, clears UI
    }
  else if(e.Error != null) //if error occurs in thread
    {
     string sernum = ((BackgroundWorkerException)e.Error).Sernum;
     //logs the serial number and error into a log text file
    }
  else //the program ends normally
    {
      //disconnect unit from PC, clears UI
    }
}
public class BackgroundWorkerException : Exception //to pass serial number to error handler
    {
        public string Sernum { get; set; }

        public BackgroundWorkerException(string sernum, Exception ex)

        {
            Sernum = sernum;
        }
    }
</code>```

Edit: Added coding to show how I structure my Backgroundworker.

答:
i5-6500 got 4 hardwarethreads, which means that the usage of the core got splittet and optimized to 4 threads. You can start as many treads as you want on every CPU, but then they will run like:
Singlecore example:

start A, stop A, start b, stop b, start a again, stop a, starb b
  again.

Body:
I have made a program that is running 5 threads simultaneously. These 5 threads each will be running multiple time-consuming operations that can last around 3 hours in total.

Before the 2 hour mark, the UI seems to run fine. But I have discovered that after around 2 hours has passed, the UI becomes unresponsive and lags.
Furthermore, the results from the 5th thread becomes wrong or have bogus value. I have tried my best in optimising my coding but this still happens.

My company computer has an i5-6500 CPU and 8 GB of RAM. I have checked online that this CPU can only run 4 threads at a time. To run 5 or more threads, an i7-7700 with hyperthreading will be needed which can run 8 at a time.

Am I right about this hardware limitation? Or is there something I can do with my C# coding to overcome this problem? FYI, I'm using BackgroundWorker to handle my multithreading.

I have to confirm that it is absolutely a hardware problem before proposing to my boss that the company has to invest in a new CPU and motherboard.

Any advice is greatly appreciated. :)

private void Form1_Load(object sender, EventArgs e)
{
  using (StreamReader sr = new StreamReader(string.Concat(Directory.GetCurrentDirectory(), "\\limit.txt"), true))
       {
          String input; //read value limits from textfile and storing it in array
          int i = 1;
          while ((input = sr.ReadLine()) != null)
             {
                limit_memory[i]= input;
                i++;
             }
        }
    }

}
private void button1_Click(object sender, EventArgs e)
{
  //shows some textboxes that user has to fill and press enter to continue
}
private void button2_Click(object sender, EventArgs e)
{
  //shows some textboxes that user has to fill and press enter to continue
}
private void button3_Click(object sender, EventArgs e)
{
  //shows some textboxes that user has to fill and press enter to continue
}
private void button4_Click(object sender, EventArgs e)
{
  //shows some textboxes that user has to fill and press enter to continue
}
private void button5_Click(object sender, EventArgs e)
{
  //shows some textboxes that user has to fill and press enter to continue
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '\r')
      {
        if (backgroundWorker1.IsBusy != true)
           {
              object[] button1_var = { sentry1, terminal1, txtBox1_serial};
              backgroundWorker1.RunWorkerAsync(button1_var); //pass some arguments with an object
           }
      }
}

private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '\r')
      {
        if (backgroundWorker2.IsBusy != true)
           {
              object[] button2_var = { sentry2, terminal2, txtBox2_serial};
              backgroundWorker2.RunWorkerAsync(button2_var); //pass some arguments with an object
           }
      }
}
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '\r')
      {
        if (backgroundWorker3.IsBusy != true)
           {
              object[] button3_var = { sentry3, terminal3, txtBox3_serial};
              backgroundWorker3.RunWorkerAsync(button3_var); //pass some arguments with an object
           }
      }
}
private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '\r')
      {
        if (backgroundWorker4.IsBusy != true)
           {
              object[] button4_var = { sentry4, terminal4, txtBox4_serial};
              backgroundWorker4.RunWorkerAsync(button4_var); //pass some arguments with an object
           }
      }
}
private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '\r')
      {
        if (backgroundWorker5.IsBusy != true)
           {
              object[] button5_var = { sentry5, terminal5, txtBox5_serial};
              backgroundWorker5.RunWorkerAsync(button5_var); //pass some arguments with an object
           }
      }
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
  try
    {
      //uses the arguments passed and perform long operations
      //prints results to textFile1
    }
  catch
    {
      throw new BackgroundWorkerException(sernum, ex);//pass the unit's serial number to the error handler
    }
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
  try
    {
      //uses the arguments passed and perform long operations
      //prints results to textFile2
    }
  catch
    {
      throw new BackgroundWorkerException(sernum, ex);//pass the unit's serial number to the error handler
    }
}
private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
{
  try
    {
      //uses the arguments passed and perform long operations
      //prints results to textFile3
    }
  catch
    {
      throw new BackgroundWorkerException(sernum, ex);//pass the unit's serial number to the error handler
    }
}
private void backgroundWorker4_DoWork(object sender, DoWorkEventArgs e)
{
  try
    {
      //uses the arguments passed and perform long operations
      //prints results to textFile4
    }
  catch
    {
      throw new BackgroundWorkerException(sernum, ex);//pass the unit's serial number to the error handler
    }
}
private void backgroundWorker5_DoWork(object sender, DoWorkEventArgs e)
{
  try
    {
      //uses the arguments passed and perform long operations
      //prints results to textFile5
    }
  catch
    {
      throw new BackgroundWorkerException(sernum, ex);//pass the unit's serial number to the error handler
    }
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  //updates the UI on what operations are being run
}
private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  //updates the UI on what operations are being run
}
private void backgroundWorker3_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  //updates the UI on what operations are being run
}
private void backgroundWorker4_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  //updates the UI on what operations are being run
}
private void backgroundWorker5_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  //updates the UI on what operations are being run
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled == true) //if user cancels thread
    {
     //disconnect unit from PC, clears UI
    }
  else if(e.Error != null) //if error occurs in thread
    {
     string sernum = ((BackgroundWorkerException)e.Error).Sernum;
     //logs the serial number and error into a log text file
    }
  else //the program ends normally
    {
      //disconnect unit from PC, clears UI
    }
}
private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled == true) //if user cancels thread
    {
     //disconnect unit from PC, clears UI
    }
  else if(e.Error != null) //if error occurs in thread
    {
     string sernum = ((BackgroundWorkerException)e.Error).Sernum;
     //logs the serial number and error into a log text file
    }
  else //the program ends normally
    {
      //disconnect unit from PC, clears UI
    }
}
private void backgroundWorker3_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled == true) //if user cancels thread
    {
     //disconnect unit from PC, clears UI
    }
  else if(e.Error != null) //if error occurs in thread
    {
     string sernum = ((BackgroundWorkerException)e.Error).Sernum;
     //logs the serial number and error into a log text file
    }
  else //the program ends normally
    {
      //disconnect unit from PC, clears UI
    }
}
private void backgroundWorker4_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled == true) //if user cancels thread
    {
     //disconnect unit from PC, clears UI
    }
  else if(e.Error != null) //if error occurs in thread
    {
     string sernum = ((BackgroundWorkerException)e.Error).Sernum;
     //logs the serial number and error into a log text file
    }
  else //the program ends normally
    {
      //disconnect unit from PC, clears UI
    }
}
private void backgroundWorker5_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled == true) //if user cancels thread
    {
     //disconnect unit from PC, clears UI
    }
  else if(e.Error != null) //if error occurs in thread
    {
     string sernum = ((BackgroundWorkerException)e.Error).Sernum;
     //logs the serial number and error into a log text file
    }
  else //the program ends normally
    {
      //disconnect unit from PC, clears UI
    }
}
public class BackgroundWorkerException : Exception //to pass serial number to error handler
    {
        public string Sernum { get; set; }

        public BackgroundWorkerException(string sernum, Exception ex)

        {
            Sernum = sernum;
        }
    }

Edit: Added coding to show how I structure my Backgroundworker.


问:
Is passing objects to constructor better left as object or as serialized object in pageparameters?
I need to pass an object A to a constructor of class B. Usually its best practice to use Wickets PageParameters class to pass arguments, but PageParameters saves its parameter values as Strings, so an error accurs if the object is passed as it is. A solution I thought of is serializing the object A and saving it as a string parameter. So my question is which of the two sulutions is better practice concerning performance and security, passing directly an object A to class B or serializing it and passing the PageParameters. </p>

答:
Passing it as serialized parameter (in PageParameters) is a requirement only when you want your page to be fully instantiate-able by requesting a predefined url.

If this page will be reachable only after navigating to another/previous page then passing a plain Object is better. This way it is definitely more secure because no one can see it from outside. And it is more performant too because there is no need to serialize it and later load.


问:
Xamarin, Animation via XML: Hand over a vari
I am having an animated slider via XML in my code:

```<code>    private void MoveSlider()
    {
        if (blNewestSelected)
        {
            var moveIt = AnimationUtils.LoadAnimation(this.BaseContext,
                Resource.Animation.Profile_MoveSliderToLeft);
            btnItemSelected.StartAnimation(moveIt);
        }
        else if (blMostApSelected)
        {
            var moveIt = AnimationUtils.LoadAnimation(this.BaseContext,
                Resource.Animation.Profile_MoveSliderToCenter);
            btnItemSelected.StartAnimation(moveIt);
        }
        else if (blMostUpvotedSelected)
        {
            var moveIt = AnimationUtils.LoadAnimation(this.BaseContext,
                Resource.Animation.Profile_MoveSliderToRight);
            btnItemSelected.StartAnimation(moveIt);
        }

    }
</code>```

The XML looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<set
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:fillAfter="true">
  <translate
    android:fromXDelta="0%p"
    android:toXDelta="62%p"
    android:duration="400" />

</set>
</code>```

The problem is, that the animation always starts at 0 x-delta.
I need to however hand over a varibale of the current delta, so that
the animation starts from where the object currently is and not ALWAYS from 0.
I have not been able to find out, how to do that. It is probably pretty easy...
Any help be awesome :)

THANK YOU!

答:
You could use ObjectAnimation which actually moves an object. This works fine, but you need to target your app for minimum API level 11 :

```<code>IInterpolator interpolators = AnimationUtils.LoadInterpolator(this, Android.Resource.Interpolator.AccelerateDecelerate);

ObjectAnimator transAnimation = ObjectAnimator.OfFloat(view, propertyName, fromX, toX);
transAnimation.SetDuration(400);
transAnimation.SetInterpolator(interpolators);
transAnimation.Start();
</code>```

view  - this is the view on which animation is to be applied

propertyName - The property being animated, for your situation is "translationX".

FromX,toX -  A set of values that the animation will animate between over time.

Body:
I am having an animated slider via XML in my code:

    private void MoveSlider()
    {
        if (blNewestSelected)
        {
            var moveIt = AnimationUtils.LoadAnimation(this.BaseContext,
                Resource.Animation.Profile_MoveSliderToLeft);
            btnItemSelected.StartAnimation(moveIt);
        }
        else if (blMostApSelected)
        {
            var moveIt = AnimationUtils.LoadAnimation(this.BaseContext,
                Resource.Animation.Profile_MoveSliderToCenter);
            btnItemSelected.StartAnimation(moveIt);
        }
        else if (blMostUpvotedSelected)
        {
            var moveIt = AnimationUtils.LoadAnimation(this.BaseContext,
                Resource.Animation.Profile_MoveSliderToRight);
            btnItemSelected.StartAnimation(moveIt);
        }

    }

The XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
<set
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:fillAfter="true">
  <translate
    android:fromXDelta="0%p"
    android:toXDelta="62%p"
    android:duration="400" />

</set>

The problem is, that the animation always starts at 0 x-delta.
I need to however hand over a varibale of the current delta, so that
the animation starts from where the object currently is and not ALWAYS from 0.
I have not been able to find out, how to do that. It is probably pretty easy...
Any help be awesome :)

THANK YOU!

Body:
You could use ObjectAnimation which actually moves an object. This works fine, but you need to target your app for minimum API level 11 :

IInterpolator interpolators = AnimationUtils.LoadInterpolator(this, Android.Resource.Interpolator.AccelerateDecelerate);

ObjectAnimator transAnimation = ObjectAnimator.OfFloat(view, propertyName, fromX, toX);
transAnimation.SetDuration(400);
transAnimation.SetInterpolator(interpolators);
transAnimation.Start();

view  - this is the view on which animation is to be applied

propertyName - The property being animated, for your situation is "translationX".

FromX,toX -  A set of values that the animation will animate between over time.


问:
Magento 1.9 - Multi Store Product URL Issue
I had Magento 1.9 website which runs with default store only.

Now I have created 1 more store for USA customers with currency $.

Now issue is why every product have 2 urls, different URL for both stores. There is an issue and duplicate content issue with SEO, So I want only 1 URL for both stores.

Ex:

Product: XYZ

Store India URL: xyz.html with price in INR

Store USA URL: xyz.html with price in $

I have used one extension which redirect me on specific store based on user IP.

Thank you.

答:
you could go for two stores using hreflang. this would solve dc issue.
https://support.google.com/webmasters/answer/189077?hl=en</p>


问:
mysql: What is the ROW_COUNT() information function for SELECT?
I'm looking for the built-in MySQL information function that returns the number of rows just selected, like ROW_COUNT() does for INSERT, UPDATE, etc.

In a stored procedure I wish to do this:

```<code>...
select episode_name from bestLOSTepisodes
set _episodes_found = SELECTED_ROWS();
...
</code>```

I've done a fair amount of digging and have been unable to find such a function like SELECTED_ROWS().

答:
You can try FOUND_ROWS() function.</p>

```<code>CREATE TABLE Emp(EmpID int,EMPNAME varchar(20),SALARY int);
INSERT INTO Emp VALUES (1,'Astin',6500);
INSERT INTO Emp VALUES (2,'Blade',4500);
INSERT INTO Emp VALUES (3,'Cabal',6500);
INSERT INTO Emp VALUES (4,'Brant',5200);
INSERT INTO Emp VALUES (5,'Sunny',7000);
SELECT * FROM EMP WHERE SALARY=6500;
SELECT FOUND_ROWS() as SelectedRowCount;
</code>```

Body:
I'm looking for the built-in MySQL information function that returns the number of rows just selected, like ROW_COUNT() does for INSERT, UPDATE, etc.

In a stored procedure I wish to do this:

...
select episode_name from bestLOSTepisodes
set _episodes_found = SELECTED_ROWS();
...

I've done a fair amount of digging and have been unable to find such a function like SELECTED_ROWS().

Body:
You can try FOUND_ROWS() function.

CREATE TABLE Emp(EmpID int,EMPNAME varchar(20),SALARY int);
INSERT INTO Emp VALUES (1,'Astin',6500);
INSERT INTO Emp VALUES (2,'Blade',4500);
INSERT INTO Emp VALUES (3,'Cabal',6500);
INSERT INTO Emp VALUES (4,'Brant',5200);
INSERT INTO Emp VALUES (5,'Sunny',7000);
SELECT * FROM EMP WHERE SALARY=6500;
SELECT FOUND_ROWS() as SelectedRowCount;


问:
VSTS File Copy Issue
I am using Microsoft VSTS and as part of a release I am uploading artefacts to an Azure Storage account.  I am uploading 3 files:

RELEASES

setup.exe

setup.nupkg

Strangely enough, it copies the first two files but seems to have an issue with the last one.  I get this less-than-helpful error message:

Upload to container: 'releases' in storage account: 'mystorage' with
  blob prefix: '' failed with error: '' For more info please refer to
  https://aka.ms/azurefilecopyreadme

答: I found the source of this problem. Basically, I had cancelled an upload to the blob container from Microsoft Azure Storage Explorer earlier in the day.  When trying to upload a file of the same name as the one that I had cancelled, this error was being thrown.  I re-created the container and it's all fine now.</p>

Title: VSTS File Copy Issue


问:
How to shutdown udp socket in python
I have a socket listener thread running and it supposed to close when a particular condition is met.here is my code snippet.

```<code> def __init__(self, arg):

        threading.Thread.__init__(self)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        receiver_port = int(<port>)
        listen_addr = (<some ip>, receiver_port)
        self.socket.bind(listen_addr)
        self.shutdown = threading.Event()
        self.shutdown.set()

 def kill_function():

       self.socket.shutdown(socket.SOCK_DGRAM)
       self.shutdown.clear()
       self.socket.close()
</code>```

I am facing

```<code>OSError: [Errno 107] Transport endpoint is not connected error when I try to
kill the socket.
</code>```

The same issue is observing if I user SHUT_RD, SHUT_RDWR.
can anyone please help me how to call shutdown() function, while using UDP sockets.

Thanks in advance.

答:
```<code>self.socket.shutdown(socket.SOCK_DGRAM)
</code>```

shutdown is not relevant for UDP sockets but for TCP.  And, shutdown takes only arguments on how to shutdown (SHUT_RD, SHUT_WR, SHUT_RDWR) and not a protocol as you do.

Apart from that, your code binds the UDP socket to a local address but does not connect it to another address, i.e. it can send anywhere using socket.sendto. Thus you get the message that the socket is not connected when trying to shut a non-existing connection down.

Title: How to shutdown udp socket in python

Body:
I have a socket listener thread running and it supposed to close when a particular condition is met.here is my code snippet.

 def __init__(self, arg):

        threading.Thread.__init__(self)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        receiver_port = int(<port>)
        listen_addr = (<some ip>, receiver_port)
        self.socket.bind(listen_addr)
        self.shutdown = threading.Event()
        self.shutdown.set()

 def kill_function():

       self.socket.shutdown(socket.SOCK_DGRAM)
       self.shutdown.clear()
       self.socket.close()

I am facing

OSError: [Errno 107] Transport endpoint is not connected error when I try to
kill the socket.

The same issue is observing if I user SHUT_RD, SHUT_RDWR.
can anyone please help me how to call shutdown() function, while using UDP sockets.

Thanks in advance.

Body:
self.socket.shutdown(socket.SOCK_DGRAM)

shutdown is not relevant for UDP sockets but for TCP.  And, shutdown takes only arguments on how to shutdown (SHUT_RD, SHUT_WR, SHUT_RDWR) and not a protocol as you do.

Apart from that, your code binds the UDP socket to a local address but does not connect it to another address, i.e. it can send anywhere using socket.sendto. Thus you get the message that the socket is not connected when trying to shut a non-existing connection down.


问:
why i can't parse xml in javascript?
hello i have problem to parse xml..
i have xml like this :

```<code><tejemahan>
  <kategori> komputer </kategori>
  <hasil> aplikasi komputer </hasil>
</terjemahan>
</code>```

Edited:

xml above I get in that way :

```<code>   var url="http://localhost:8080/inlinetrans/api/translate/"+userSelection+"/"+hasilStemSel+"/"+hasilStem;
   var client = new XMLHttpRequest();
   client.open("GET", url, false);
   client.setRequestHeader("Content-Type", "text/plain");
   client.send(null);

   if(client.status == 200)
       alert("the request success"+client.responseText);
   else
       alert("the request isn't success"+client.status+""+client.statusText)

  }
</code>```

and this is my code to parse an xml file above :

```<code>this.loadXML = function (){
   var url = http://localhost:8080/coba/api/artikan/"+sel+"/"+hasilStemSel+"/"+hasilStem
   xmlDoc=document.implementation.createDocument("","",null);
   xmlDoc.load("url");
   xmlDoc.onload= this.readXML;
  }

  this.readXML = function() {
        alert(xmlDoc.documentElement.tagName);
 alert(xmlDoc.documentElement.childNodes[0].tagName);
 alert(xmlDoc.documentElement.childNodes[1].tagName);
 alert(xmlDoc.documentElement.childNodes[0].textContent);
 alert(xmlDoc.documentElement.childNodes[1].textContent);

     }
</code>```

i can execute this code

```<code>xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.load("url");
</code>```

but why i can't execute this code
 xmlDoc.load = this.readXML ???

答:
Try putting the onload handler assignment before the load() call. If you call load() first, the onload event will happen before you have assigned a handler to handle it. Like this:</p>

```<code>xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.onload= this.readXML;
xmlDoc.load("url");
</code>```

Title: why i can't parse xml in javascript?

Body:
hello i have problem to parse xml..
i have xml like this :

<tejemahan>
  <kategori> komputer </kategori>
  <hasil> aplikasi komputer </hasil>
</terjemahan>

Edited:

xml above I get in that way :

   var url="http://localhost:8080/inlinetrans/api/translate/"+userSelection+"/"+hasilStemSel+"/"+hasilStem;
   var client = new XMLHttpRequest();
   client.open("GET", url, false);
   client.setRequestHeader("Content-Type", "text/plain");
   client.send(null);

   if(client.status == 200)
       alert("the request success"+client.responseText);
   else
       alert("the request isn't success"+client.status+""+client.statusText)

  }

and this is my code to parse an xml file above :

this.loadXML = function (){
   var url = http://localhost:8080/coba/api/artikan/"+sel+"/"+hasilStemSel+"/"+hasilStem
   xmlDoc=document.implementation.createDocument("","",null);
   xmlDoc.load("url");
   xmlDoc.onload= this.readXML;
  }

  this.readXML = function() {
        alert(xmlDoc.documentElement.tagName);
 alert(xmlDoc.documentElement.childNodes[0].tagName);
 alert(xmlDoc.documentElement.childNodes[1].tagName);
 alert(xmlDoc.documentElement.childNodes[0].textContent);
 alert(xmlDoc.documentElement.childNodes[1].textContent);

     }

i can execute this code

xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.load("url");

but why i can't execute this code
 xmlDoc.load = this.readXML ???

Body:
Try putting the onload handler assignment before the load() call. If you call load() first, the onload event will happen before you have assigned a handler to handle it. Like this:

xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.onload= this.readXML;
xmlDoc.load("url");


问:
"XamlCTask" task failed unexpectedly" error when building with the new Xamarin Forms
After I've updated to the latest Xamarin.Forms (2.3.4.224) I keep getting build errors. anyone knows what this could be?

I suspect it might have to do with the new behavior changes they have introduced with the new version regarding Attached Properties (but I don't know that that means)

more info here https://forums.xamarin.com/discussion/92455/xamarin-forms-2-3-4-224

and here is my build log

```<code>Error       The "XamlCTask" task failed unexpectedly.
System.ArgumentException: An item with the same key has already been added.

Server stack trace:
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ParseXaml(RootNode rootNode, XmlReader reader)
   at Xamarin.Forms.Build.Tasks.XamlTask.ParseXaml(Stream stream, TypeReference typeReference)
   at Xamarin.Forms.Build.Tasks.XamlCTask.Execute(IList`1& thrownExceptions)
   at Xamarin.Forms.Build.Tasks.XamlTask.Execute()
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Build.Framework.ITask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() Shared
</code>```

答:
I'm not exactly sure if this is the same case, but I ran into the same problem.

I had different version of Forms installed. After I updated all nuget packages and deleted all obj and bin folders I was able to make a build without errors.

Body:
After I've updated to the latest Xamarin.Forms (2.3.4.224) I keep getting build errors. anyone knows what this could be?

I suspect it might have to do with the new behavior changes they have introduced with the new version regarding Attached Properties (but I don't know that that means)

more info here https://forums.xamarin.com/discussion/92455/xamarin-forms-2-3-4-224

and here is my build log

Error       The "XamlCTask" task failed unexpectedly.
System.ArgumentException: An item with the same key has already been added.

Server stack trace:
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ParseXaml(RootNode rootNode, XmlReader reader)
   at Xamarin.Forms.Build.Tasks.XamlTask.ParseXaml(Stream stream, TypeReference typeReference)
   at Xamarin.Forms.Build.Tasks.XamlCTask.Execute(IList`1& thrownExceptions)
   at Xamarin.Forms.Build.Tasks.XamlTask.Execute()
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Build.Framework.ITask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() Shared


问:
How to wait until loading window close or visible false
I have developed selenium automation framework using JAVA and I facing a problem.
When I click on any button say Filter or clear filter application display a loading window and after that, we are able to perform next action.
i have added following code to wait until loading window visible false but its not working.

```<code>wait.until(ExpectedConditions.invisibilityOf(webElement));
                    System.out.println("Wait Untill Loading Window Closed");
                    existFlag=true;
</code>```

in web element i passing that loading window XPATH. Every time code not wait for window to be closed start clicking on button and  throw exception

unknown error: Element ... is not clickable at point (178, 391). Other element would receive the click:

I also added code for click

```<code>wait.until(ExpectedConditions.elementToBeClickable(webElement));
             webElement.click();
             return true;
</code>```

Please help how i can wait till loading window close.

答:
You should use implicit wait for this purpose. Add this statement for setting Implicit wait on driver object , after initialising the driver instance. </p>

```<code>driver.manage().timeouts().implicitlyWait(Integer.parseInt("30"),TimeUnit.SECONDS);
</code>```

Body:
I have developed selenium automation framework using JAVA and I facing a problem.
When I click on any button say Filter or clear filter application display a loading window and after that, we are able to perform next action.
i have added following code to wait until loading window visible false but its not working.

wait.until(ExpectedConditions.invisibilityOf(webElement));
                    System.out.println("Wait Untill Loading Window Closed");
                    existFlag=true;

in web element i passing that loading window XPATH. Every time code not wait for window to be closed start clicking on button and  throw exception

unknown error: Element ... is not clickable at point (178, 391). Other element would receive the click:

I also added code for click

wait.until(ExpectedConditions.elementToBeClickable(webElement));
             webElement.click();
             return true;

Please help how i can wait till loading window close.

Body:
You should use implicit wait for this purpose. Add this statement for setting Implicit wait on driver object , after initialising the driver instance.

driver.manage().timeouts().implicitlyWait(Integer.parseInt("30"),TimeUnit.SECONDS);


问:
Google adwords: "An error occurred. Please try again later." message
I am trying to upload a new campaign but always get a message:
"An error occurred. Please try again later."

On all fields:

Does anyone know this kind of error?

答:
I had the same issue.
Removing any exclamation mark from the "Ad text ideas" fields did the job.</p>


问:
Is C++11 is faster than C++03 in terms of efficiency?
I work in trading firm and here latency matters a lot. The project assigns to me is developed using a mix of c and c++98 parts, But I believe we can make same project using C++11 without losing efficiency. As discussed with my seniors, they say you should stick with C and c++03 as they are efficient compare to C++11 at micro level.
Can anyone highlight me If I go with C++11, will I get better results?</p>

答:
C++11 is faster, because moving of objects was introduced. Mainly the usage of this feature in the STL speeds up some applications a lot without any code change in user code. Applications can be programmed much more efficient then before. Also constexpr construction can result in much faster application startup, because objects can reside in flash space on small controllers instead copy them into ram. There are a lot more features which help to get the code more efficient. For example emplace_back for conatainers help to generate objects in place instead of creating & copy them.

C++17 introduces guaranteed copy elision, which speeds up also in a lot of use cases.


问:
Is there a variable evaluator in Rust?
I have a JSON object as a configuration file with strings. These strings represent attributes of an object.

How can I interpret strings of the format json.id.value by a function as variables or references?

I have seen the eval crate, but I don't think it is what I need.

答:
Rust is a compiled language. What you want isn't directly possible, because names don't exist in the compiled code anymore.

But if you want to go from JSON to Rust structs, that's what the serialization library Serde is for.

Title: Is there a variable evaluator in Rust?


问:
Implement github.com file seamless file navigation
I just noticed a recent change when browsing github repositorys. When you select a file or folder, the new file slides in and pushed the old file out. This is easy enough to do with jquery, but what's really different is that the URL itself actually changes so that bookmarks still work. I've been struggling to create this for a book navigating site I'm working on but haven't been able to update the url without a full page refresh. Any ideas on how github does this?</p>

答:
I haven't looked at the underlying code, but I believe it is a combination of the new HTML5 spec of web history and location (well, location is old, but it's an updated spec).

Mozilla docs

W3C history spec

W3C location spec

The W3C specs are very verbose (after all, they are specs), so that can be hard to read. I think this other answer on Stack Overflow is in the right direction.

You have to keep in mind that this is part of the HTML5 specs, so not every browser will be able to handle this functionality. We are building this type of navigation out on a project at work, and if the browser doesn't support this feature, it's just a regular page refresh.

ContentLicense: CC BY-SA 4.0


问:
Most efficient way to find the index of the only '1' bit in a char variable (in C)
This is an interview question:

You are given a char variable named ch, when you know that it represents a number that in its binary form, only one of its eight bits will be equal to '1'. I.E. , the only possible values for ch are: 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80.

Given the variable ch, I need to write the most efficient code to get the index of that '1' bit. For example: if ch == 0x1 -> result is 0. if ch == 0x4 -> result is 2.

The obvious way is to use switch-case, but I need something more efficient.

Is there any bit manipulation you can do here for efficient implementation?

答:
A fast and quite portable solution is:

```<code>int charindex(unsigned char c){
    union {   /* Assume both float and int are 32 bits, assume IEEE 754 floating point. */
        int i;
        float f;
    } x;
    x.f = (float)c;
    return (x.i >> 23) - 127;
}
</code>```

Note that many processors have hardware support for counting the number of leading or trailing zeros
of an integer. With gcc it is easy to access these particular instructions: gcc has the builtin function __builtin_ctz() which is probably more efficient  than charindex on platforms with suitable hardware support.

Body:
A fast and quite portable solution is:

int charindex(unsigned char c){
    union {   /* Assume both float and int are 32 bits, assume IEEE 754 floating point. */
        int i;
        float f;
    } x;
    x.f = (float)c;
    return (x.i >> 23) - 127;
}

Note that many processors have hardware support for counting the number of leading or trailing zeros
of an integer. With gcc it is easy to access these particular instructions: gcc has the builtin function __builtin_ctz() which is probably more efficient  than charindex on platforms with suitable hardware support.


问:
Is there a better way to round float number with n decimals in C++?
I known the common way is to multiply 10^n and then divide 10^n. round a float with one digit number
But due to the double precision accuracy problem, I found the solution above doesn't fully work for my case:

```<code>0.965 * 0.9 = 0.8685

std::round(0.8685 * 1000) / 1000 = 0.869
// expects it to be 0.869
std::round(0.965 * 0.9 * 1000) / 1000 = 0.868
</code>```

If I want to get 0.869 from std::round(0.965 * 0.9 * 1000) / 1000 directly, I have to change the statement to

```<code>std::round((0.965 * 0.9 + std::numeric_limits<double>::epsilon()) * 1000) / 1000 = 0.869
</code>```

Is there a simpler way to do the rounding without add an epsilon for every calculation?

Edit: The problem is that, intuitively the value of std::round(0.965 * 0.9 * 1000) / 1000 shall be 0.869 (because 0.965 * 0.9 = 0.8685), but it actually give 0.868. I want to find common way get the accurate math value with 3 decimal precision.

答:
You could make a new function specifically for that calculation:</p>

```<code>#include <iostream>
#include <limits>
#include <cmath>

using namespace std;

double roundDec(double var) {
    var = round((var + std::numeric_limits<double>::epsilon()) * 1000) / 1000;

    return var;
}

int main() {

    double var = 0.8685;

    cout << roundDec(var);

    return 0;
}
</code>```

Body:
I known the common way is to multiply 10^n and then divide 10^n. round a float with one digit number
But due to the double precision accuracy problem, I found the solution above doesn't fully work for my case:

0.965 * 0.9 = 0.8685

std::round(0.8685 * 1000) / 1000 = 0.869
// expects it to be 0.869
std::round(0.965 * 0.9 * 1000) / 1000 = 0.868

If I want to get 0.869 from std::round(0.965 * 0.9 * 1000) / 1000 directly, I have to change the statement to

std::round((0.965 * 0.9 + std::numeric_limits<double>::epsilon()) * 1000) / 1000 = 0.869

Is there a simpler way to do the rounding without add an epsilon for every calculation?

Edit: The problem is that, intuitively the value of std::round(0.965 * 0.9 * 1000) / 1000 shall be 0.869 (because 0.965 * 0.9 = 0.8685), but it actually give 0.868. I want to find common way get the accurate math value with 3 decimal precision.

Body:
You could make a new function specifically for that calculation:

#include <iostream>
#include <limits>
#include <cmath>

using namespace std;

double roundDec(double var) {
    var = round((var + std::numeric_limits<double>::epsilon()) * 1000) / 1000;

    return var;
}

int main() {

    double var = 0.8685;

    cout << roundDec(var);

    return 0;
}


问:
TFS Build Server 2017 Ignores Project Dependencies
I am using TFS 2017 to build a solution that has three projects linked to it. Two of the projects are located elsewhere in TFS. When I build the main project which depends on the other two projects I get errors because the other two projects are not being build. How can I force TFS to build all dependent projects?</p>

答:
With Visual Studio Build task you could either build the whole solution by select .sln or only build MSBuild project (.*proj) files.

If you select the .proj file in the build task, for building three different  projects, you also need to add three tasks.

In your case, since you have selected .sln file, TFS will auto build the whole solution including all projects under it. But in the workspace mappings, you need to make sure that you Map all folders that contain files that your build process requires. For example, if you add another project, you might have to add another mapping to the workspace.

So it would not be automatically done by scanning the dependencies
  of the solution. You have to also add Folder B mappings in the get
  sources of the definition.

Besides if this is a CI build, in most cases you should make sure
that these mappings match the filter settings of your CI trigger on
the Triggers tab.

For more information on how to optimize a TFVC workspace, see
Optimize your workspace.


问:
Not able to get response from PATCH API call for webservice in Swift 3 by Alamofire
I am trying to make call by PATCH method. I am using Alamofire library for making networking calls. For GET/POST its working fine, but while trying to make call PATCH getting following errors.

```<code>ResponseSerializationFailed
Code 3840 from network
</code>```

I am calling request like by following

```<code>    Alamofire.request(urlString, method: .patch, parameters: params as? [String:Any], encoding: JSONEncoding.default, headers: nil).responseJSON { response in

        requestVC.removeLoader()
        switch (response.result) {
        case .success:
            if response.result.value != nil{
                completionHandler (response.result.value)
            }
            break
        case .failure(let error):
            failureHandler (error as NSError?)
            break
        }
    }
</code>```

答: Its happening due to some internal issue for calling api request. Fixed.</p>

Body:
I am trying to make call by PATCH method. I am using Alamofire library for making networking calls. For GET/POST its working fine, but while trying to make call PATCH getting following errors.

ResponseSerializationFailed
Code 3840 from network

I am calling request like by following

    Alamofire.request(urlString, method: .patch, parameters: params as? [String:Any], encoding: JSONEncoding.default, headers: nil).responseJSON { response in

        requestVC.removeLoader()
        switch (response.result) {
        case .success:
            if response.result.value != nil{
                completionHandler (response.result.value)
            }
            break
        case .failure(let error):
            failureHandler (error as NSError?)
            break
        }
    }


问:
javascript execution order
I am starting to learn Javascript and jQuery.
I wanted to make a simple slide show with jQuery which displays list unordered list items one by one.

My code is here: on jsfiddle

I thought that I'd make the slideshow by iterating over list items in a for loop and display them with fadeIn and fadeOut effects like below:

```<code>for(var i = 0; i < 3; i++)
{
    $('#slider li:nth-child('+ i +')')
        .fadeIn()
        .delay(1000)
        .fadeOut();
}
</code>```

But it only shows the last item in the list.

I read that I need to close the value of i variable in a separate function because of the Javascript scope that it sees the value of i is being increased to 2 in the loop. So, I made a separate function which closes the value of i and called the function. But it was still same, displaying the last item of the list.

So, I just wanted to try without the loop by making two separate effects on list items like below:

```<code>$('#slider li:first-child')
    .fadeIn()
    .delay(1000)
    .fadeOut();
$('#slider li:nth-child(2)')
    .fadeIn()
    .delay(1000)
    .fadeOut();
</code>```

But it doesn't display the list items sequentially like written above. When you run the code, it seems like the first item is shown really fast and the last item is displayed as intended.

I have written it like a C or Java code, thinking that it would execute from top to bottom. But it seems like Javascript is different and I didn't understand a key concept of Javascript.

So, my question is why it is not displaying the list items in order and only displaying the last item, and what should I need to know to make it work as intented.

Thank you.

答:
A much simpler method will be

```<code>$(document).ready(function () {
    $('#slider li:gt(0)').hide();
    setInterval(
        function () {
            $('#slider li:first-child')
                .fadeOut()
                .next('li')
                .fadeIn()
                .end()
                .appendTo('#slider');
        }
    , 3000);
});
</code>```

It uses JavaScript SetInterval method.

You can view the code in action here

P.S:  jQuery's implementation of :nth-child(n) is strictly derived from the CSS specification, the value of n is "1-indexed"

Title: javascript execution order

Body:
I am starting to learn Javascript and jQuery.
I wanted to make a simple slide show with jQuery which displays list unordered list items one by one.

My code is here: on jsfiddle

I thought that I'd make the slideshow by iterating over list items in a for loop and display them with fadeIn and fadeOut effects like below:

for(var i = 0; i < 3; i++)
{
    $('#slider li:nth-child('+ i +')')
        .fadeIn()
        .delay(1000)
        .fadeOut();
}

But it only shows the last item in the list.

I read that I need to close the value of i variable in a separate function because of the Javascript scope that it sees the value of i is being increased to 2 in the loop. So, I made a separate function which closes the value of i and called the function. But it was still same, displaying the last item of the list.

So, I just wanted to try without the loop by making two separate effects on list items like below:

$('#slider li:first-child')
    .fadeIn()
    .delay(1000)
    .fadeOut();
$('#slider li:nth-child(2)')
    .fadeIn()
    .delay(1000)
    .fadeOut();

But it doesn't display the list items sequentially like written above. When you run the code, it seems like the first item is shown really fast and the last item is displayed as intended.

I have written it like a C or Java code, thinking that it would execute from top to bottom. But it seems like Javascript is different and I didn't understand a key concept of Javascript.

So, my question is why it is not displaying the list items in order and only displaying the last item, and what should I need to know to make it work as intented.

Thank you.

Body:
A much simpler method will be

$(document).ready(function () {
    $('#slider li:gt(0)').hide();
    setInterval(
        function () {
            $('#slider li:first-child')
                .fadeOut()
                .next('li')
                .fadeIn()
                .end()
                .appendTo('#slider');
        }
    , 3000);
});

It uses JavaScript SetInterval method.

You can view the code in action here

P.S:  jQuery's implementation of :nth-child(n) is strictly derived from the CSS specification, the value of n is "1-indexed"


问:
Maven `help:effective-pom` only generating for a single project, not all projects
I want to generate an effective pom for all the subprojects in a multi-module build.

The help:effective-pom documentation here states

It will iterate over all projects in the current build session, printing the effective POM for each

I'm running mvn help:effective-pom in the root directory of this maven project and it's only generating for the root and not for the subprojects.

Why isn't the effective pom being generated for all projects. Note: I have another real world maven project where mvn help:effective-pom is correctly generating a <projects> tag with nested <project> for each submodule. I am unsure why it is not working for this maven project

Here is the effective pom generated

```<code><!-- ====================================================================== -->
<!--                                                                        -->
<!-- Generated by Maven Help Plugin on 2017-11-12T09:56:26                  -->
<!-- See: http://maven.apache.org/plugins/maven-help-plugin/                -->
<!--                                                                        -->
<!-- ====================================================================== -->

<!-- ====================================================================== -->
<!--                                                                        -->
<!-- Effective POM for project                                              -->
<!-- 'org.gradle.test.performance:project:pom:1.0'                          -->
<!--                                                                        -->
<!-- ====================================================================== -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.gradle.test.performance</groupId>
  <artifactId>project</artifactId>
  <version>1.0</version>
  <packaging>pom</packaging>
  <modules>
    <module>project0</module>
    <module>project1</module>
    <module>project2</module>
    <module>project3</module>
    <module>project4</module>
    <module>project5</module>
    <module>project6</module>
    <module>project7</module>
    <module>project8</module>
    <module>project9</module>
  </modules>
  <repositories>
    <repository>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </repository>
  </repositories>
  <pluginRepositories>
    <pluginRepository>
      <releases>
        <updatePolicy>never</updatePolicy>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </pluginRepository>
  </pluginRepositories>
  <build>
    <sourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\java</sourceDirectory>
    <scriptSourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\scripts</scriptSourceDirectory>
    <testSourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\test\java</testSourceDirectory>
    <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\classes</outputDirectory>
    <testOutputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\test-classes</testOutputDirectory>
    <resources>
      <resource>
        <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\test\resources</directory>
      </testResource>
    </testResources>
    <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target</directory>
    <finalName>project-1.0</finalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-antrun-plugin</artifactId>
          <version>1.3</version>
        </plugin>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>2.2-beta-5</version>
        </plugin>
        <plugin>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>2.8</version>
        </plugin>
        <plugin>
          <artifactId>maven-release-plugin</artifactId>
          <version>2.3.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>2.5</version>
        <executions>
          <execution>
            <id>default-clean</id>
            <phase>clean</phase>
            <goals>
              <goal>clean</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.4</version>
        <executions>
          <execution>
            <id>default-install</id>
            <phase>install</phase>
            <goals>
              <goal>install</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.7</version>
        <executions>
          <execution>
            <id>default-deploy</id>
            <phase>deploy</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.3</version>
        <executions>
          <execution>
            <id>default-site</id>
            <phase>site</phase>
            <goals>
              <goal>site</goal>
            </goals>
            <configuration>
              <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
              <reportPlugins>
                <reportPlugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-project-info-reports-plugin</artifactId>
                </reportPlugin>
              </reportPlugins>
            </configuration>
          </execution>
          <execution>
            <id>default-deploy</id>
            <phase>site-deploy</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
            <configuration>
              <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
              <reportPlugins>
                <reportPlugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-project-info-reports-plugin</artifactId>
                </reportPlugin>
              </reportPlugins>
            </configuration>
          </execution>
        </executions>
        <configuration>
          <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
          <reportPlugins>
            <reportPlugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-project-info-reports-plugin</artifactId>
            </reportPlugin>
          </reportPlugins>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <reporting>
    <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
  </reporting>
</project>
</code>```

答:
I ended up with a different solution in the end. Rather than accepting a single root pom.xml as input, I instead require a collection of pom.xml to be resolved. I also now embed the maven-model-builder and invoke the DefaultModelBuilder via a DefaultModelBuildingRequest

Eg:

```<code>DefaultModelBuilderFactory factory = new DefaultModelBuilderFactory();
DefaultModelBuilder builder = factory.newInstance();
ModelBuildingRequest req = new DefaultModelBuildingRequest();
req.setProcessPlugins(false);
req.setModelResolver(createModelResolver());
req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
for (File pomFile : pomFiles) {
   req.setPomFile(pomFile);
   Model effectivePom = builder.build(req).getEffectiveModel();
   ...
}
</code>```

Code here for anyone interested

Body:
I want to generate an effective pom for all the subprojects in a multi-module build.

The help:effective-pom documentation here states

It will iterate over all projects in the current build session, printing the effective POM for each

I'm running mvn help:effective-pom in the root directory of this maven project and it's only generating for the root and not for the subprojects.

Why isn't the effective pom being generated for all projects. Note: I have another real world maven project where mvn help:effective-pom is correctly generating a <projects> tag with nested <project> for each submodule. I am unsure why it is not working for this maven project

Here is the effective pom generated

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.gradle.test.performance</groupId>
  <artifactId>project</artifactId>
  <version>1.0</version>
  <packaging>pom</packaging>
  <modules>
    <module>project0</module>
    <module>project1</module>
    <module>project2</module>
    <module>project3</module>
    <module>project4</module>
    <module>project5</module>
    <module>project6</module>
    <module>project7</module>
    <module>project8</module>
    <module>project9</module>
  </modules>
  <repositories>
    <repository>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </repository>
  </repositories>
  <pluginRepositories>
    <pluginRepository>
      <releases>
        <updatePolicy>never</updatePolicy>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
    </pluginRepository>
  </pluginRepositories>
  <build>
    <sourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\java</sourceDirectory>

    <testSourceDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\test\java</testSourceDirectory>
    <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\classes</outputDirectory>
    <testOutputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\test-classes</testOutputDirectory>
    <resources>
      <resource>
        <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\main\resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\src\test\resources</directory>
      </testResource>
    </testResources>
    <directory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target</directory>
    <finalName>project-1.0</finalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-antrun-plugin</artifactId>
          <version>1.3</version>
        </plugin>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>2.2-beta-5</version>
        </plugin>
        <plugin>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>2.8</version>
        </plugin>
        <plugin>
          <artifactId>maven-release-plugin</artifactId>
          <version>2.3.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>2.5</version>
        <executions>
          <execution>
            <id>default-clean</id>
            <phase>clean</phase>
            <goals>
              <goal>clean</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.4</version>
        <executions>
          <execution>
            <id>default-install</id>
            <phase>install</phase>
            <goals>
              <goal>install</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.7</version>
        <executions>
          <execution>
            <id>default-deploy</id>
            <phase>deploy</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.3</version>
        <executions>
          <execution>
            <id>default-site</id>
            <phase>site</phase>
            <goals>
              <goal>site</goal>
            </goals>
            <configuration>
              <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
              <reportPlugins>
                <reportPlugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-project-info-reports-plugin</artifactId>
                </reportPlugin>
              </reportPlugins>
            </configuration>
          </execution>
          <execution>
            <id>default-deploy</id>
            <phase>site-deploy</phase>
            <goals>
              <goal>deploy</goal>
            </goals>
            <configuration>
              <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
              <reportPlugins>
                <reportPlugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-project-info-reports-plugin</artifactId>
                </reportPlugin>
              </reportPlugins>
            </configuration>
          </execution>
        </executions>
        <configuration>
          <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
          <reportPlugins>
            <reportPlugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-project-info-reports-plugin</artifactId>
            </reportPlugin>
          </reportPlugins>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <reporting>
    <outputDirectory>C:\code\gradle-maven-transform\example\smallJavaMultiProject\target\site</outputDirectory>
  </reporting>
</project>

Body:
I ended up with a different solution in the end. Rather than accepting a single root pom.xml as input, I instead require a collection of pom.xml to be resolved. I also now embed the maven-model-builder and invoke the DefaultModelBuilder via a DefaultModelBuildingRequest

Eg:

DefaultModelBuilderFactory factory = new DefaultModelBuilderFactory();
DefaultModelBuilder builder = factory.newInstance();
ModelBuildingRequest req = new DefaultModelBuildingRequest();
req.setProcessPlugins(false);
req.setModelResolver(createModelResolver());
req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
for (File pomFile : pomFiles) {
   req.setPomFile(pomFile);
   Model effectivePom = builder.build(req).getEffectiveModel();
   ...
}

Code here for anyone interested


问:
Sending the PUT request with Content-Type:application/x-www-form-urlencoded and sending image file not working
When I send PUT request with content-type:application/x-www-form-urlencoded and wrong content like image; the request is not getting handled by server properly and it sends back following exception without any processing by server:

ERROR;Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception;
  java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "h�"
      at java.net.URLDecoder.decode(URLDecoder.java:194)
      at org.springframework.http.converter.FormHttpMessageConverter.read(FormHttpMessageConverter.java:241)
      at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:100)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      at java.lang.Thread.run(Thread.java:745)

Is their any way in Spring through which we can handle the scenario ?

答:
Files need to be multipart/form-data content-type

You basically have three choices:

Base64 encode the file, at the expense of increasing the data size by around 33%.

Send the file first in a multipart/form-data POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata.

Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.


问:
I can't get the right rotation of my transform in unity 3D
Hi everyone I have some little problem in Unity 3D. I am trying to do some walking simulation I have character and I have joints while she was walking I want to get the rotation of y. But when I try it I get some results like (transform of rotation in unity is -60 for example the value I get in program 0.059871 something like that how can I read the -60 the right value?)</p>

答:
Maybe you take the wrong properties, the Quaternion.y is a value from 0 to 1 (CMIIW)
but if you want to get you rotation in degree you can use Vector3.y by taking

```<code>var y = gameObject.transform.localEulerAngles.y;
</code>```

Also, please attach your code before asking some code related issue

Body:
Maybe you take the wrong properties, the Quaternion.y is a value from 0 to 1 (CMIIW)
but if you want to get you rotation in degree you can use Vector3.y by taking

var y = gameObject.transform.localEulerAngles.y;

Also, please attach your code before asking some code related issue


问:
How to store javascript array or JSON into php
I have a javaScript array which I need to store in PHP so that later I can store it to MySQL database.

index.php

```<code><form method="post">
<button type="submit" class="btn btn-default" id="php-submit" name="php-submit"><span class="glyphicon glyphicon-upload"></span></button>
<table class="table" id="table-1">
  <-- my finalArray gets generated by selecting some of these table cell values -->
</table>
</form>
</code>```

app.js

```<code>$('#php-submit').click(function()
{   // For demo purpose, I have written hardcoded array values here
    var finalArray = ["Nov 2017 0:00 - 0:59", "Dec 2017 0:00 - 0:59", "Nov 2017 1:00 - 1:59", "Dec 2017 1:00 - 1:59"];
    // console.log(finalArray);
    str_json = JSON.stringify(finalArray);
    console.log(str_json);

    $.ajax({
      type: "POST",
      url: "script.php",
      data: {data : str_json},
      cache: false,
      success: function(){
        alert("OK");
      }
    });

    // $.post('script.php', { data: finalArray }, function (data) {
    //  alert("OK");
    // });

});
</code>```

After user clicks ('#php-submit') button,
I want to be display 'finalArray' or 'str_json' on my script.php.

Below are 4 different approaches that I have tried.

script.php

```<code>// approach 1: output --> blank page

   $data = json_decode(stripslashes($_POST['data']));
   foreach($data as $d){
      echo $d;
   }

// approach 2: ouptut --> null

   $data = json_decode(stripslashes($_POST['data']));
   var_dump($data);

// approach 3: output --> null

   header('Content-type: application/json; charset=utf-8');
   $json = file_get_contents('php://input');
   $json_decode = json_decode($json, true);
   $json_encode = json_encode($json_decode);
   echo $json_encode;

// approach 4: output --> array(1) { [0]=> string(4) "null" }

   $data = $_POST['data'];
   $json_encode = json_encode($data);
   $ar = explode(',', $json_encode);
   var_dump($ar);
</code>```

答:
Not change app.js!
Then, you must type this code in script.php:

```<code>$array = json_decode($_POST['data']);
//To array iteration elements
foreach ($array as $element){
   echo $element;
}
</code>```

Hope It helps you!

Body:
I have a javaScript array which I need to store in PHP so that later I can store it to MySQL database.

index.php

<form method="post">
<button type="submit" class="btn btn-default" id="php-submit" name="php-submit"></button>

  <-- my finalArray gets generated by selecting some of these table cell values -->

</form>

app.js

$('#php-submit').click(function()
{   // For demo purpose, I have written hardcoded array values here
    var finalArray = ["Nov 2017 0:00 - 0:59", "Dec 2017 0:00 - 0:59", "Nov 2017 1:00 - 1:59", "Dec 2017 1:00 - 1:59"];
    // console.log(finalArray);
    str_json = JSON.stringify(finalArray);
    console.log(str_json);

    $.ajax({
      type: "POST",
      url: "script.php",
      data: {data : str_json},
      cache: false,
      success: function(){
        alert("OK");
      }
    });

    // $.post('script.php', { data: finalArray }, function (data) {
    //  alert("OK");
    // });

});

After user clicks ('#php-submit') button,
I want to be display 'finalArray' or 'str_json' on my script.php.

Below are 4 different approaches that I have tried.

script.php

// approach 1: output --> blank page

   $data = json_decode(stripslashes($_POST['data']));
   foreach($data as $d){
      echo $d;
   }

// approach 2: ouptut --> null

   $data = json_decode(stripslashes($_POST['data']));
   var_dump($data);

// approach 3: output --> null

   header('Content-type: application/json; charset=utf-8');
   $json = file_get_contents('php://input');
   $json_decode = json_decode($json, true);
   $json_encode = json_encode($json_decode);
   echo $json_encode;

// approach 4: output --> array(1) { [0]=> string(4) "null" }

   $data = $_POST['data'];
   $json_encode = json_encode($data);
   $ar = explode(',', $json_encode);
   var_dump($ar);

Body:
Not change app.js!
Then, you must type this code in script.php:

$array = json_decode($_POST['data']);
//To array iteration elements
foreach ($array as $element){
   echo $element;
}

Hope It helps you!


问:
How to serialize Json object into System.Net.WebClient (.NET 3.5)
How can you serialize a json object and pass it on to an api call, like the one in the example posted as an answer here Call web APIs in C# using .NET framework 3.5

```<code>System.Net.WebClient client = new System.Net.WebClient();
 client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers
 string s = Encoding.ASCII.GetString(client.UploadData("http://localhost:1111/Service.svc/SignIn", "POST", Encoding.Default.GetBytes("{\"EmailId\": \"admin@admin.com\",\"Password\": \"pass#123\"}")));
</code>```

In Postman I would just do this

```<code> var client = new RestClient("");
 var request = new RestRequest(Method.POST);
 request.JsonSerializer = new RestSharpJsonNetSerializer();
 request.AddJsonBody(JsonObject);
</code>```

However, as Postman is not supported in .net framework 3.5, I have to use System.Net.WebClient.

答:
You can do what you want with WebClient (and Json.NET package) like this:

```<code>var yourObject = new YourObject {
    Email = "email",
    Password = "password"
};
string s = client.UploadString("http://localhost:1111/Service.svc/SignIn","POST", JsonConvert.SerializeObject(yourObject));
</code>```

Body:
How can you serialize a json object and pass it on to an api call, like the one in the example posted as an answer here Call web APIs in C# using .NET framework 3.5

System.Net.WebClient client = new System.Net.WebClient();
 client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers
 string s = Encoding.ASCII.GetString(client.UploadData("http://localhost:1111/Service.svc/SignIn", "POST", Encoding.Default.GetBytes("{\"EmailId\": \"admin@admin.com\",\"Password\": \"pass#123\"}")));

In Postman I would just do this

 var client = new RestClient("");
 var request = new RestRequest(Method.POST);
 request.JsonSerializer = new RestSharpJsonNetSerializer();
 request.AddJsonBody(JsonObject);

However, as Postman is not supported in .net framework 3.5, I have to use System.Net.WebClient.

Body:
You can do what you want with WebClient (and Json.NET package) like this:

var yourObject = new YourObject {
    Email = "email",
    Password = "password"
};
string s = client.UploadString("http://localhost:1111/Service.svc/SignIn","POST", JsonConvert.SerializeObject(yourObject));


问:
Need to join multiple (Apache) server logs into one chronological log
Apache log in long format, stored on multiple servers, relating to the same domain. I need to merge them together in chronological order so AWstats or something similar can create a log.

Of course, telling me how to just throw them randomly at a parsing tool to generate an access log would be a sufficient answer as well.

答:
http://awstats.sourceforge.net/docs/awstats_faq.html#LOADLOG

AWstats includes a script to do this. For people running load balancers and multiple app servers, AWstats just kind of handles it for you. It's quite cool.


问:
How can I join two tables but only return rows that don't match specific column which include NULL as well?
I have two tables which look like this:

```<code>T1:  ID  |  oldID

T2:  ID  |  newID
</code>```

I basically need to join these tables when their IDs match. However, I only want to return the results like: ID  |  oldID  |  newID where oldID do not equal to newID.

Example data:

T1: 1  |  100
     2  |  NULL
     3  |  200
     4  |  500

T2: 1  |  NULL
     2  |  300
     3  |  200
     4  |  400

My expected result:

T3: 1 | 100  | NULL
     2 | NULL | 300
     4 | 500  | 400

Can anyone point me on the right track?

答:
Try this answer, Hope this helps</p>

```<code>CREATE TABLE #T1 (ID INT, oldID INT)
INSERT INTO #T1 VALUES(1,100)
INSERT INTO #T1 VALUES(2,NULL)
INSERT INTO #T1 VALUES(3,200)
INSERT INTO #T1 VALUES(4,500)

CREATE TABLE #T2 (ID INT, [NewId] INT)
INSERT INTO #T2 VALUES(1,NULL)
INSERT INTO #T2 VALUES(2,300)
INSERT INTO #T2 VALUES(3,200)
INSERT INTO #T2 VALUES(4,400)

select T1.ID,T1.oldID,T2.[NewId]
FROM #T1 T1, #T2 T2
WHERE T1.id=T2.id and ISNULL(T1.oldID,0) != ISNULL(T2.[NewId],0)

DROP TABLE #T1
DROP TABLE #T2
</code>```

Body:
I have two tables which look like this:

T1:  ID  |  oldID

T2:  ID  |  newID

I basically need to join these tables when their IDs match. However, I only want to return the results like: ID  |  oldID  |  newID where oldID do not equal to newID.

Example data:

T1: 1  |  100
     2  |  NULL
     3  |  200
     4  |  500

T2: 1  |  NULL
     2  |  300
     3  |  200
     4  |  400

My expected result:

T3: 1 | 100  | NULL
     2 | NULL | 300
     4 | 500  | 400

Can anyone point me on the right track?

Body:
Try this answer, Hope this helps

CREATE TABLE #T1 (ID INT, oldID INT)
INSERT INTO #T1 VALUES(1,100)
INSERT INTO #T1 VALUES(2,NULL)
INSERT INTO #T1 VALUES(3,200)
INSERT INTO #T1 VALUES(4,500)

CREATE TABLE #T2 (ID INT, [NewId] INT)
INSERT INTO #T2 VALUES(1,NULL)
INSERT INTO #T2 VALUES(2,300)
INSERT INTO #T2 VALUES(3,200)
INSERT INTO #T2 VALUES(4,400)

select T1.ID,T1.oldID,T2.[NewId]
FROM #T1 T1, #T2 T2
WHERE T1.id=T2.id and ISNULL(T1.oldID,0) != ISNULL(T2.[NewId],0)

DROP TABLE #T1
DROP TABLE #T2