问:
Determine if an adjacency matrix has a cycle and then output that cycle
so I have 2 functions :

UPDATED

```<code>unordered_map<int, bool> visited2;
vector<vector<int>> elements2D;

bool DFSDetectCycle(int vertex){
    s.push(vertex);
    while(!s.empty()){
        int np_vertex = s.top();
        s.pop();
        if (visited2[np_vertex] == true){
            return true;
        }
        visited2[np_vertex] = true;
        for (int i = 0; i<elements2D.size(); i++){
            if(elements2D[np_vertex][i] != 0){
                if(DFSDetectCycle(i)){
                    return true;
                }
            }
        }
    }
    return false;
}

bool hasCycle(vector<vector<int>> v){
    if (v.empty()){
        return false;
    }
    for (int i = 0; i<v.size(); i++){
           if (!visited2[i]){
                      if(DFSDetectCycle(i)){
                          return true;
                      }
           }
    }
    return false;
}
</code>```

And in my main function I call it like this:

```<code>if (hasCycle(elements2D)){
        for (int i = 0; i<elements2D.size(); i++){
            if (!visited2[i]){
                DFSDetectCycle(i);
            }
        }
}else{
        cout << "No cycles." << endl;
}
</code>```

So basically, the input is going to look like this:

```<code>g++ -o GraphProcessor.o GraphProcessor.cpp -std=c++11
./GraphProcessor.o graph1.txt
</code>```

And the output should look like this:

```<code>Connected components:
{0,1,2,4,7}
{3}
{5,6}
A cycle: 0 1 4 2
</code>```

But my output looks like this:

```<code>Connected components:
{0,1,4,2,7}
{3}
{5,6}
No cycles.
</code>```

graph1.txt looks like this:

```<code>0 2 6 0 0 0 0 3
2 0 0 0 4 0 0 1
6 0 0 0 3 0 0 2
0 0 0 0 0 0 0 0
0 4 3 0 0 0 0 0
0 0 0 0 0 0 7 0
0 0 0 0 0 7 0 0
3 1 2 0 0 0 0 0
</code>```

Do not worry about the connected components part, that is not my problem right now. My problem is that my code is not properly detecting cycles in the graph and is not outputting them properly either. It seems as if my hasCycle() function is constantly giving a false statement, but I am not really sure why. elements2D is my matrix I am using, since it was read from a file, I needed somewhere to store it. For my visited2 function, I use an unordered_map in order to keep boolean values on whether or not I have visited the vertices or not. I know that if I have visited a vertex again, then I have a cycle. But I am not sure how to modify my algorithm in order to obtain a result like that.

Thanks again for any help.

答:
You are calling DFSDetectCycle recursively without using it's return value. I suggest you check if recursive call return true, and return it is so.

You are specifically skipping the cycles because you filter the recursive calls with if(elements2D[np_vertex][i] != 0 && !visited2[i]) - which means you will not go into already visit vertexes, skipping the cycles.

In addition, there are no prints in the code that would yield the required output...

Body:
so I have 2 functions :

UPDATED

unordered_map<int, bool> visited2;
vector<vector<int>> elements2D;

bool DFSDetectCycle(int vertex){
    s.push(vertex);
    while(!s.empty()){
        int np_vertex = s.top();
        s.pop();
        if (visited2[np_vertex] == true){
            return true;
        }
        visited2[np_vertex] = true;
        for (int i = 0; i<elements2D.size(); i++){
            if(elements2D[np_vertex][i] != 0){
                if(DFSDetectCycle(i)){
                    return true;
                }
            }
        }
    }
    return false;
}

bool hasCycle(vector<vector<int>> v){
    if (v.empty()){
        return false;
    }
    for (int i = 0; i<v.size(); i++){
           if (!visited2[i]){
                      if(DFSDetectCycle(i)){
                          return true;
                      }
           }
    }
    return false;
}

And in my main function I call it like this:

if (hasCycle(elements2D)){
        for (int i = 0; i<elements2D.size(); i++){
            if (!visited2[i]){
                DFSDetectCycle(i);
            }
        }
}else{
        cout << "No cycles." << endl;
}

So basically, the input is going to look like this:

g++ -o GraphProcessor.o GraphProcessor.cpp -std=c++11
./GraphProcessor.o graph1.txt

And the output should look like this:

Connected components:
{0,1,2,4,7}
{3}
{5,6}
A cycle: 0 1 4 2

But my output looks like this:

Connected components:
{0,1,4,2,7}
{3}
{5,6}
No cycles.

graph1.txt looks like this:

0 2 6 0 0 0 0 3
2 0 0 0 4 0 0 1
6 0 0 0 3 0 0 2
0 0 0 0 0 0 0 0
0 4 3 0 0 0 0 0
0 0 0 0 0 0 7 0
0 0 0 0 0 7 0 0
3 1 2 0 0 0 0 0

Do not worry about the connected components part, that is not my problem right now. My problem is that my code is not properly detecting cycles in the graph and is not outputting them properly either. It seems as if my hasCycle() function is constantly giving a false statement, but I am not really sure why. elements2D is my matrix I am using, since it was read from a file, I needed somewhere to store it. For my visited2 function, I use an unordered_map in order to keep boolean values on whether or not I have visited the vertices or not. I know that if I have visited a vertex again, then I have a cycle. But I am not sure how to modify my algorithm in order to obtain a result like that.

Thanks again for any help.


来源: stackexchange

问:
Is jQuery's "each()" method a for loop?
I tried adding a serialized class to each of a set of objects like this:

```<code>jQuery('#preload img').each(function(){
    jQuery('#thumbs').append('<img class="index' + index + '" src="' + source + '" />');
    index = ++index;
    });
</code>```

And it worked. What resulted was a set of images, each with a class image1, image2, and so on. It's exactly what I wanted. But is this actually a reliable method of looping through a set of objects? Or is it possible that, if this anonymous function took longer to execute, the function might start on the next object before index is incremented?

Anybody know what's actually happening?

答:
http://api.jquery.com/jQuery.each/

http://api.jquery.com/each/

are iterated by numeric index, from 0
  to length-1

ContentLicense: CC BY-SA 2.5

Title: Is jQuery's "each()" method a for loop?

Body:
I tried adding a serialized class to each of a set of objects like this:

jQuery('#preload img').each(function(){
    jQuery('#thumbs').append('');
    index = ++index;
    });

And it worked. What resulted was a set of images, each with a class image1, image2, and so on. It's exactly what I wanted. But is this actually a reliable method of looping through a set of objects? Or is it possible that, if this anonymous function took longer to execute, the function might start on the next object before index is incremented?

Anybody know what's actually happening?


问:
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.Writer.write(java.lang.String)' on a null object reference

java.lang.NullPointerException: Attempt to invoke virtual method 'void
  java.io.Writer.write(java.lang.String)' on a null object reference
  12-09 07:18:35.259 2419-2419/com.end.myapplication W/System.err:

  at
  com.end.myapplication.MainActivity$SendingRunnable.run(MainActivity.java:124)
  12-09 07:18:35.259 2419-2419/com.end.myapplication W/System.err:

  at android.os.Handler.handleCallback(Handler.java:751) 12-09
  07:18:35.259 2419-2419/com.end.myapplication W/System.err:     at
  android.os.Handler.dispatchMessage(Handler.java:95) 12-09 07:18:35.259
  2419-2419/com.end.myapplication W/System.err:     at
  android.os.Looper.loop(Looper.java:154) 12-09 07:18:35.259
  2419-2419/com.end.myapplication W/System.err:     at
  android.app.ActivityThread.main(ActivityThread.java:6119) 12-09
  07:18:35.259 2419-2419/com.end.myapplication W/System.err:     at
  java.lang.reflect.Method.invoke(Native Method) 12-09 07:18:35.259
  2419-2419/com.end.myapplication W/System.err:     at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
  12-09 07:18:35.259 2419-2419/com.end.myapplication W/System.err:

  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

MainActivity

```<code>package com.end.myapplication;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private String html = "";
    private Handler mHandler;

    private Socket socket;

    private BufferedReader networkReader;
    private BufferedWriter networkWriter;

    private String ip = "192.168.56.1"; // IP
    private int port = 5516; // PORT번호

    boolean check=false;

    EditText et;
    TextView tv;
    NetworkThread thread;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et = (EditText) findViewById(R.id.EditText01);
        Button btn = (Button) findViewById(R.id.Button01);
        tv = (TextView) findViewById(R.id.TextView01);

        btn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if (et.getText().toString() != null || !et.getText().toString().equals("")) {
                    check=true;
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Thread(){
            @Override
            public void run(){
                try {
                    socket = new Socket(ip, port);
                    networkWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    networkReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }.start();
        thread = new NetworkThread(networkReader, networkWriter);
        thread.start();
    }

    private class NetworkThread extends Thread {
        BufferedReader br;
        BufferedWriter bw;
        Handler mHandler;
        SendingRunnable sendingRunnable;

        private NetworkThread(BufferedReader br, BufferedWriter bw){
            this.br = br;
            this.bw = bw;
            mHandler = new Handler();
            sendingRunnable = new SendingRunnable(bw);
        }

        @Override
        public void run() {
            super.run();
            boolean isError = false;
            String result = "";
            String error = "";

            try{
                this.bw.write("CONNECTED\n");
                this.bw.flush();
            }catch (Exception e){
                e.printStackTrace();
            }
            while (true){
                try{
                    if (check){
                        mHandler.post(sendingRunnable);

                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    private class SendingRunnable implements Runnable {
        BufferedWriter bw;

        private SendingRunnable(BufferedWriter bw){
            this.bw = bw;
        }

        @Override
        public void run() {
            String formula = et.getText().toString();
            try{
                bw.write(formula+"\n");
                bw.flush();
                et.setText("");
            }catch (Exception e){e.printStackTrace();}
        }
    }
}
</code>```

答:
You are starting two threads simultaneously where the resources in second thread is being initialized by the first thread.

Solution: start the second thread from inside first thread

or

move the socket connection and reader, writer code in NetworkThread thread (no need of two threads)

ContentLicense: CC BY-SA 3.0

Body:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
  java.io.Writer.write(java.lang.String)' on a null object reference
  12-09 07:18:35.259 2419-2419/com.end.myapplication W/System.err:

  at
  com.end.myapplication.MainActivity$SendingRunnable.run(MainActivity.java:124)
  12-09 07:18:35.259 2419-2419/com.end.myapplication W/System.err:

  at android.os.Handler.handleCallback(Handler.java:751) 12-09
  07:18:35.259 2419-2419/com.end.myapplication W/System.err:     at
  android.os.Handler.dispatchMessage(Handler.java:95) 12-09 07:18:35.259
  2419-2419/com.end.myapplication W/System.err:     at
  android.os.Looper.loop(Looper.java:154) 12-09 07:18:35.259
  2419-2419/com.end.myapplication W/System.err:     at
  android.app.ActivityThread.main(ActivityThread.java:6119) 12-09
  07:18:35.259 2419-2419/com.end.myapplication W/System.err:     at
  java.lang.reflect.Method.invoke(Native Method) 12-09 07:18:35.259
  2419-2419/com.end.myapplication W/System.err:     at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
  12-09 07:18:35.259 2419-2419/com.end.myapplication W/System.err:

  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

MainActivity

package com.end.myapplication;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private String html = "";
    private Handler mHandler;

    private Socket socket;

    private BufferedReader networkReader;
    private BufferedWriter networkWriter;

    private String ip = "192.168.56.1"; // IP
    private int port = 5516; // PORT번호

    boolean check=false;

    EditText et;
    TextView tv;
    NetworkThread thread;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et = (EditText) findViewById(R.id.EditText01);
        Button btn = (Button) findViewById(R.id.Button01);
        tv = (TextView) findViewById(R.id.TextView01);

        btn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if (et.getText().toString() != null || !et.getText().toString().equals("")) {
                    check=true;
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Thread(){
            @Override
            public void run(){
                try {
                    socket = new Socket(ip, port);
                    networkWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    networkReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }.start();
        thread = new NetworkThread(networkReader, networkWriter);
        thread.start();
    }

    private class NetworkThread extends Thread {
        BufferedReader br;
        BufferedWriter bw;
        Handler mHandler;
        SendingRunnable sendingRunnable;

        private NetworkThread(BufferedReader br, BufferedWriter bw){
            this.br = br;
            this.bw = bw;
            mHandler = new Handler();
            sendingRunnable = new SendingRunnable(bw);
        }

        @Override
        public void run() {
            super.run();
            boolean isError = false;
            String result = "";
            String error = "";

            try{
                this.bw.write("CONNECTED\n");
                this.bw.flush();
            }catch (Exception e){
                e.printStackTrace();
            }
            while (true){
                try{
                    if (check){
                        mHandler.post(sendingRunnable);

                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    private class SendingRunnable implements Runnable {
        BufferedWriter bw;

        private SendingRunnable(BufferedWriter bw){
            this.bw = bw;
        }

        @Override
        public void run() {
            String formula = et.getText().toString();
            try{
                bw.write(formula+"\n");
                bw.flush();
                et.setText("");
            }catch (Exception e){e.printStackTrace();}
        }
    }
}


问:
Finding an integer key of a Python dict that is closest to a given integer
I have a dictionary where the keys are integers.  I have another integer.  I want to find the value corresponding to the key in the dict that is closest to the given integer.  Is there an efficient way to do this?

Maybe a different data structure (binary tree) would be more efficient?

答:
```<code>In [1]: def lookforkey(mykey, dd):
     ...:     """ returns mykey if present in dd
     ...:         otherwise the nearest key
     ...:         which could be either greater or less
     ...:         than mykey
     ...:     """
     ...:     nearkey = next(iter(dd))
     ...:     bestdist = abs(nearkey - mykey)
     ...:     for ikey in dd:
     ...:             dist = abs(mykey - ikey)
     ...:             if bestdist > dist:
     ...:                 bestdist = dist
     ...:                 nearkey = ikey
     ...:                 if ikey == mykey:
     ...:                     return ikey
     ...:     return nearkey
     ...:

In [2]: dd = {2: 'x', 6: 'y', 77: 'w', 100000: 'z'}
In [3]: lookforkey(-10, dd)
Out[3]: 2
In [4]: lookforkey(6, dd)
Out[4]: 6
In [5]: lookforkey(76, dd)
Out[5]: 77
In [6]: lookforkey(999, dd)
Out[7]: 77
In [8]: lookforkey(999999, dd)
Out[9]: 100000
</code>```

<p>even tho it's longer, this is more efficeint than min/max solutions which still process the keys twice.  here, if there is an exact match there is no need to continue looking </p>

Body:
In [1]: def lookforkey(mykey, dd):
     ...:     """ returns mykey if present in dd
     ...:         otherwise the nearest key
     ...:         which could be either greater or less
     ...:         than mykey
     ...:     """
     ...:     nearkey = next(iter(dd))
     ...:     bestdist = abs(nearkey - mykey)
     ...:     for ikey in dd:
     ...:             dist = abs(mykey - ikey)
     ...:             if bestdist > dist:
     ...:                 bestdist = dist
     ...:                 nearkey = ikey
     ...:                 if ikey == mykey:
     ...:                     return ikey
     ...:     return nearkey
     ...:

In [2]: dd = {2: 'x', 6: 'y', 77: 'w', 100000: 'z'}
In [3]: lookforkey(-10, dd)
Out[3]: 2
In [4]: lookforkey(6, dd)
Out[4]: 6
In [5]: lookforkey(76, dd)
Out[5]: 77
In [6]: lookforkey(999, dd)
Out[7]: 77
In [8]: lookforkey(999999, dd)
Out[9]: 100000

even tho it's longer, this is more efficeint than min/max solutions which still process the keys twice.  here, if there is an exact match there is no need to continue looking


问:
Click event restart
I'm using c# windows form in Visual studio 2017 version

I've made a high low game for practice and it works perfect but what I'm trying to accomplish is once someone hits 10 guesses it starts the application over again.

This was my last resort coming here and asking but i have no one else to turn to. I've tried all kinds of things to make it work when hitting 10 guesses to restart the app but nothing works and i get errors.

here's the start button and the guess button

variables I'm using

```<code>    static int intRandomNumber;
    static int intNumGuesses;
    static int intBestLowScore;
    static int intGuessedNum;
    static int difference = 0;
</code>```

Start Button

```<code>        {
        //Random Numbers//

        Random rnRandomNumber = new Random();
        intRandomNumber = rnRandomNumber.Next(0, 1000);
        lblRandomNumber.Text = intRandomNumber.ToString();
        txtGuess.Enabled = true;
        btnGuess.Enabled = true;
        btnStart.Enabled = false;
        lblAnswer.Text = "".ToString();
        intBestLowScore = intNumGuesses;
        intNumGuesses = 0;
        lblNumGuesses.Text = "0";
        lblBestScore.Text = intBestLowScore.ToString();
        lblAnswer.BackColor = Color.White;
        txtGuess.Focus();
        SoundPlayer audio = new SoundPlayer(High_Low_Game.Properties.Resources.Cheering);
        audio.Stop();
    }
</code>```

Guess Button

```<code>{
        intNumGuesses++;
        lblNumGuesses.Text = intNumGuesses.ToString();

        try
        {
            intGuessedNum = Convert.ToInt32(txtGuess.Text);

            if (intRandomNumber - intGuessedNum < difference)
            {
                lblAnswer.Text = "To High";
                lblAnswer.ForeColor = Color.Red;
                lblAnswer.BackColor = Color.White;
                txtGuess.Text = "";
                txtGuess.Focus();
            }
            else if (intRandomNumber - intGuessedNum > difference)
            {
                lblAnswer.Text = "To Low";
                lblAnswer.ForeColor = Color.Blue;
                lblAnswer.BackColor = Color.White;
                txtGuess.Text = "";
                txtGuess.Focus();
            }
            else
            {
                lblAnswer.Text = "You Guessed it.";
                lblAnswer.ForeColor = Color.Black;
                lblAnswer.BackColor = Color.Green;
                btnGuess.Enabled = false;
                txtGuess.Enabled = false;
                txtGuess.Text = "";
                btnStart.Enabled = true;
                SoundPlayer audio = new SoundPlayer(High_Low_Game.Properties.Resources.Cheering);
                audio.Play();

            }
        }
        catch
        {
            MessageBox.Show("Input your Guess again and Integers Only.  Retry.");
            txtGuess.Focus();
        }

     }
</code>```

答:
In your 'guess-button' handler do the following:</p>

```<code>{
    intNumGuesses++;
    lblNumGuesses.Text = intNumGuesses.ToString();
    bool guessed = false;
    try
    {
        intGuessedNum = Convert.ToInt32(txtGuess.Text);

        if (intRandomNumber - intGuessedNum < difference)
        {
            ...
        }
        else if (intRandomNumber - intGuessedNum > difference)
        {
           ...
        }
        else
        {
           ...
           guessed = true;
        }
        if ((intNumGuesses == 10}&&(!guessed))
        {
           // Show Message "max. nr. of guesses reached'
           // call method to clear values from textBoxes & enable Start-button
        }
    catch
    {
        MessageBox.Show("Input your Guess again and Integers Only.  Retry.");
        txtGuess.Focus();
    }

 }
</code>```

Title: Click event restart

Body:
I'm using c# windows form in Visual studio 2017 version

I've made a high low game for practice and it works perfect but what I'm trying to accomplish is once someone hits 10 guesses it starts the application over again.

This was my last resort coming here and asking but i have no one else to turn to. I've tried all kinds of things to make it work when hitting 10 guesses to restart the app but nothing works and i get errors.

here's the start button and the guess button

variables I'm using

    static int intRandomNumber;
    static int intNumGuesses;
    static int intBestLowScore;
    static int intGuessedNum;
    static int difference = 0;

Start Button

        {
        //Random Numbers//

        Random rnRandomNumber = new Random();
        intRandomNumber = rnRandomNumber.Next(0, 1000);
        lblRandomNumber.Text = intRandomNumber.ToString();
        txtGuess.Enabled = true;
        btnGuess.Enabled = true;
        btnStart.Enabled = false;
        lblAnswer.Text = "".ToString();
        intBestLowScore = intNumGuesses;
        intNumGuesses = 0;
        lblNumGuesses.Text = "0";
        lblBestScore.Text = intBestLowScore.ToString();
        lblAnswer.BackColor = Color.White;
        txtGuess.Focus();
        SoundPlayer audio = new SoundPlayer(High_Low_Game.Properties.Resources.Cheering);
        audio.Stop();
    }

Guess Button

{
        intNumGuesses++;
        lblNumGuesses.Text = intNumGuesses.ToString();

        try
        {
            intGuessedNum = Convert.ToInt32(txtGuess.Text);

            if (intRandomNumber - intGuessedNum < difference)
            {
                lblAnswer.Text = "To High";
                lblAnswer.ForeColor = Color.Red;
                lblAnswer.BackColor = Color.White;
                txtGuess.Text = "";
                txtGuess.Focus();
            }
            else if (intRandomNumber - intGuessedNum > difference)
            {
                lblAnswer.Text = "To Low";
                lblAnswer.ForeColor = Color.Blue;
                lblAnswer.BackColor = Color.White;
                txtGuess.Text = "";
                txtGuess.Focus();
            }
            else
            {
                lblAnswer.Text = "You Guessed it.";
                lblAnswer.ForeColor = Color.Black;
                lblAnswer.BackColor = Color.Green;
                btnGuess.Enabled = false;
                txtGuess.Enabled = false;
                txtGuess.Text = "";
                btnStart.Enabled = true;
                SoundPlayer audio = new SoundPlayer(High_Low_Game.Properties.Resources.Cheering);
                audio.Play();

            }
        }
        catch
        {
            MessageBox.Show("Input your Guess again and Integers Only.  Retry.");
            txtGuess.Focus();
        }

     }

Body:
In your 'guess-button' handler do the following:

{
    intNumGuesses++;
    lblNumGuesses.Text = intNumGuesses.ToString();
    bool guessed = false;
    try
    {
        intGuessedNum = Convert.ToInt32(txtGuess.Text);

        if (intRandomNumber - intGuessedNum < difference)
        {
            ...
        }
        else if (intRandomNumber - intGuessedNum > difference)
        {
           ...
        }
        else
        {
           ...
           guessed = true;
        }
        if ((intNumGuesses == 10}&&(!guessed))
        {
           // Show Message "max. nr. of guesses reached'
           // call method to clear values from textBoxes & enable Start-button
        }
    catch
    {
        MessageBox.Show("Input your Guess again and Integers Only.  Retry.");
        txtGuess.Focus();
    }

 }


问:
How to hide other application's icon from my app
I am making an application. My application gets all the installed applications. What I want is to hide app icons of some selected apps. For hiding app icon I am using below code and that is working as expected.

```<code> public void hideApp(String className) {
    PackageManager p = getPackageManager();
    ComponentName componentName = new ComponentName(this, className);
    p.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
</code>```

Note: I am sending class name with complete pkg name. And this is hiding my app icon perfectly.

But when I try to hide other app icon with complete pakage name is gives exception as mentioned below

```<code>IllegalArgumentException: Component class com.whatsapp.Main does not exist in com.example.abdulwaheed.testingproject
</code>```

My question is what am I doing wrong? As I missing anything? Is it even possible?

答:
I've not had experience with this, but I can at least try to point you in the right direction.

I think the problem is in this line:

```<code>ComponentName componentName = new ComponentName(this, className);
</code>```

According to the documentation,

Two pieces of information, encapsulated here, are required to identify a component: the package (a String) it exists in, and the class (a String) name inside of that package.

So instead of "this", which refers to your activity, you actually need the package name of the application you're trying to hide. Then, you'd put in their className for the second variable.

I hope this helps!

Body:
I am making an application. My application gets all the installed applications. What I want is to hide app icons of some selected apps. For hiding app icon I am using below code and that is working as expected.

 public void hideApp(String className) {
    PackageManager p = getPackageManager();
    ComponentName componentName = new ComponentName(this, className);
    p.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}

Note: I am sending class name with complete pkg name. And this is hiding my app icon perfectly.

But when I try to hide other app icon with complete pakage name is gives exception as mentioned below

IllegalArgumentException: Component class com.whatsapp.Main does not exist in com.example.abdulwaheed.testingproject

My question is what am I doing wrong? As I missing anything? Is it even possible?

Body:
I've not had experience with this, but I can at least try to point you in the right direction.

I think the problem is in this line:

ComponentName componentName = new ComponentName(this, className);

According to the documentation,

Two pieces of information, encapsulated here, are required to identify a component: the package (a String) it exists in, and the class (a String) name inside of that package.

So instead of "this", which refers to your activity, you actually need the package name of the application you're trying to hide. Then, you'd put in their className for the second variable.

I hope this helps!


问:
Fgets only returning '\n' char
I'm trying to use fgets to get a line from stdin. Here's my code

```<code>char* FENString;
printf("Enter FEN Key: ");
fgets(FENString, 50, stdin);
</code>```

FENString only has one char, and that's the new line character. I've tried looking for help and haven't found anything, does anyone know why this is happening?

It's very important to make sure that all variables have some sort of memory allocated to it, at least in some point of its lifecycle. The issue here was that the char pointer didn't have any sort of memory allocated to it. Something that could've fixed it is mallocing the FENString, or perhaps changing the declaration to something like char FENString[50];

答:
You are having Undefined behavior  by providing a unintialized pointer to fgets. Allocate memory of >=50 size to FENString and then pass it to fgets.

Solution-1

```<code>char* FENString;
FENString = malloc(50);
if( FENString == NULL){
    fprintf(stderr,"%s\n","Error in malloc");
    exit(1);
}
printf("Enter FEN Key: ");
if( fgets(FENString, 50, stdin) == NULL){
    fprintf(stderr,"%s\n","Error in input");
    exit(1);
}
// Work with FENString;
...
free(FENString);
</code>```

Solution-2

Simply have a char array like this char FENString[50]; Then the code would be

```<code>char FENString[50];
printf("Enter FEN Key: ");
if( fgets(FENString, sizeof FENString, stdin) == NULL){
    fprintf(stderr,"%s\n","Error in input");
    exit(1);
}
// Work with FENString
</code>```

Instead of 50 here sizeof FENString although it does the same thing this is much better towards a good maintainable solution. In case you letter change it, you don't have to search and replace 50 it will be automaticlaly done due to use of sizeof.(Peter points out)

Title: Fgets only returning '\n' char

Body:
I'm trying to use fgets to get a line from stdin. Here's my code

char* FENString;
printf("Enter FEN Key: ");
fgets(FENString, 50, stdin);

FENString only has one char, and that's the new line character. I've tried looking for help and haven't found anything, does anyone know why this is happening?

It's very important to make sure that all variables have some sort of memory allocated to it, at least in some point of its lifecycle. The issue here was that the char pointer didn't have any sort of memory allocated to it. Something that could've fixed it is mallocing the FENString, or perhaps changing the declaration to something like char FENString[50];

Body:
You are having Undefined behavior  by providing a unintialized pointer to fgets. Allocate memory of >=50 size to FENString and then pass it to fgets.

Solution-1

char* FENString;
FENString = malloc(50);
if( FENString == NULL){
    fprintf(stderr,"%s\n","Error in malloc");
    exit(1);
}
printf("Enter FEN Key: ");
if( fgets(FENString, 50, stdin) == NULL){
    fprintf(stderr,"%s\n","Error in input");
    exit(1);
}
// Work with FENString;
...
free(FENString);

Solution-2

Simply have a char array like this char FENString[50]; Then the code would be

char FENString[50];
printf("Enter FEN Key: ");
if( fgets(FENString, sizeof FENString, stdin) == NULL){
    fprintf(stderr,"%s\n","Error in input");
    exit(1);
}
// Work with FENString

Instead of 50 here sizeof FENString although it does the same thing this is much better towards a good maintainable solution. In case you letter change it, you don't have to search and replace 50 it will be automaticlaly done due to use of sizeof.(Peter points out)


问:
can we use couchdb for web application development?
I was wondering whether we can use java script for application development and use couchdb to serve it. I was also imagining jquery as the java script library. Do you think this is possible?</p>

答:
Sure you can. Following is a link to a blogging project being developed with couchdb as the backend and PHP as the front. Its open source so you might get some ideas by looking at its code.
Arik Blogging Software</p>


问:
How to display value of rating in vue js?
My json data is

```<code>{"status": true, "reviews": [{"review": "scdbgnhvgdbsr", "rating": 5, "by": "aravind", "pid": 8, "review_id": 1}, {"review": "helsocxdxvfbgfnhfgdf", "rating": 2, "by": "ab", "pid": 8, "review_id": 2}], "rating": 3.5}
</code>```

I am able to display all details other than "rating" which is outside the data[]. How can I able to display rating. Here  I NEED TO DISPLAY RATING= 3.5

```<code><div id="feed"> <div v-for="row in reviews">{{row.review}} </div> </div>
</code>```

My vue js script is

```<code> new Vue({
 el: '#feed' ,
 data: {
 data: [],
 reviews: [],
 pid: '{{pid}}',
 },
 mounted() {
var self = this;
 const data = {}
 data['pid'] = this.pid;
 $.ajax({
 url: "http://127.0.0.1:8000/api/post/reviews/",
 data: data,
 type: "POST",
 dataType: "JSON",
 success: function (e) {
 if (e.status == 1) {
  self.reviews = e.reviews;
  console.log(self.reviews);
}
}
});
},
})
</code>```

答:
var obj = jQuery.parseJSON( '{"status": true, "reviews": [{"review": "scdbgnhvgdbsr", "rating": 5, "by": "aravind", "pid": 8, "review_id": 1}, {"review": "helsocxdxvfbgfnhfgdf", "rating": 2, "by": "ab", "pid": 8, "review_id": 2}], "rating": 3.5}' );
alert( obj.rating);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
My json data is

{"status": true, "reviews": [{"review": "scdbgnhvgdbsr", "rating": 5, "by": "aravind", "pid": 8, "review_id": 1}, {"review": "helsocxdxvfbgfnhfgdf", "rating": 2, "by": "ab", "pid": 8, "review_id": 2}], "rating": 3.5}

I am able to display all details other than "rating" which is outside the data[]. How can I able to display rating. Here  I NEED TO DISPLAY RATING= 3.5

{{row.review}}

My vue js script is

 new Vue({
 el: '#feed' ,
 data: {
 data: [],
 reviews: [],
 pid: '{{pid}}',
 },
 mounted() {
var self = this;
 const data = {}
 data['pid'] = this.pid;
 $.ajax({
 url: "http://127.0.0.1:8000/api/post/reviews/",
 data: data,
 type: "POST",
 dataType: "JSON",
 success: function (e) {
 if (e.status == 1) {
  self.reviews = e.reviews;
  console.log(self.reviews);
}
}
});
},
})

Body:
var obj = jQuery.parseJSON( '{"status": true, "reviews": [{"review": "scdbgnhvgdbsr", "rating": 5, "by": "aravind", "pid": 8, "review_id": 1}, {"review": "helsocxdxvfbgfnhfgdf", "rating": 2, "by": "ab", "pid": 8, "review_id": 2}], "rating": 3.5}' );
alert( obj.rating);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


答:
You should remove visited[i] checking from if(elements2D[np_vertex][i] != 0 && !visited2[i]), because if you already visited i, then removing this checking can detect it. And if it finds cycle, you should return it immediately.

```<code>if(elements2D[np_vertex][i] != 0){
    if (DFSDetectCycle(i)) return true;
}
</code>```

Another issue is if there exist edges 0->1 and 1->0, then they make a cycle. You need more work to find largest cycle.

Title: Determine if an adjacency matrix has a cycle and then output that cycle

Body:
You should remove visited[i] checking from if(elements2D[np_vertex][i] != 0 && !visited2[i]), because if you already visited i, then removing this checking can detect it. And if it finds cycle, you should return it immediately.

if(elements2D[np_vertex][i] != 0){
    if (DFSDetectCycle(i)) return true;
}

Another issue is if there exist edges 0->1 and 1->0, then they make a cycle. You need more work to find largest cycle.


答:
.each() is indeed essentially a for loop and it also has a built in index you can use if you pass in an argument like so:

```<code>jQuery('#preload img').each(function(i){
    jQuery('#thumbs').append('<img class="index' + i + '" src="' + source + '" />');
});
</code>```

EDIT: Bonus implementation with Ken Franqueiro's string concatenation suggestion:

```<code>var thumbsAppend = "";
jQuery('#preload img').each(function(i){
    thumbsAppend += '<img class="index' + i + '" src="' + source + '" />';
});
jQuery('#thumbs').append(thumbsAppend);
</code>```

EDIT #2: And rahul's array push suggestion:

```<code>var thumbsAppend = [];
jQuery('#preload img').each(function(i){
    thumbsAppend.push('<img class="index' + i + '" src="' + source + '" />');
});
thumbsAppend = thumbsAppend.join('');
jQuery('#thumbs').append(thumbsAppend);
</code>```

Title: Is jQuery's "each()" method a for loop?

Body:
.each() is indeed essentially a for loop and it also has a built in index you can use if you pass in an argument like so:

jQuery('#preload img').each(function(i){
    jQuery('#thumbs').append('<img class="index' + i + '" src="' + source + '" />');
});

EDIT: Bonus implementation with Ken Franqueiro's string concatenation suggestion:

var thumbsAppend = "";
jQuery('#preload img').each(function(i){
    thumbsAppend += '<img class="index' + i + '" src="' + source + '" />';
});
jQuery('#thumbs').append(thumbsAppend);

EDIT #2: And rahul's array push suggestion:

var thumbsAppend = [];
jQuery('#preload img').each(function(i){
    thumbsAppend.push('<img class="index' + i + '" src="' + source + '" />');
});
thumbsAppend = thumbsAppend.join('');
jQuery('#thumbs').append(thumbsAppend);


答:
You're missing an if statement

Guess Button:

```<code>private void btnGuess_Click(object sender, EventArgs e)
        {
            intNumGuesses++;
            lblNumGuesses.Text = intNumGuesses.ToString();
//This is what you're looking for-v
            if(intNumGuesses==10)
            {
                btnGuess.Enabled = false;
                txtGuess.Enabled = false;
                txtGuess.Text = "";
                btnStart.Enabled = true;
                intNumGuesses=0;
            }
//This is what you're looking for-^
            try
            {
                intGuessedNum = Convert.ToInt32(txtGuess.Text);

                if (intRandomNumber - intGuessedNum < difference)
                {
                    lblAnswer.Text = "To High";
                    lblAnswer.ForeColor = Color.Red;
                    lblAnswer.BackColor = Color.White;
                    txtGuess.Text = "";
                    txtGuess.Focus();
                }
                else if (intRandomNumber - intGuessedNum > difference)
                {
                    lblAnswer.Text = "To Low";
                    lblAnswer.ForeColor = Color.Blue;
                    lblAnswer.BackColor = Color.White;
                    txtGuess.Text = "";
                    txtGuess.Focus();
                }
                else
                {
                    lblAnswer.Text = "You Guessed it.";
                    lblAnswer.ForeColor = Color.Black;
                    lblAnswer.BackColor = Color.Green;
                    btnGuess.Enabled = false;
                    txtGuess.Enabled = false;
                    txtGuess.Text = "";
                    btnStart.Enabled = true;

                }
            }
            catch
            {
                MessageBox.Show("Input your Guess again and Integers Only.  Retry.");
                txtGuess.Focus();
            }
        }
</code>```

Title: Click event restart

Body:
You're missing an if statement

Guess Button:

private void btnGuess_Click(object sender, EventArgs e)
        {
            intNumGuesses++;
            lblNumGuesses.Text = intNumGuesses.ToString();
//This is what you're looking for-v
            if(intNumGuesses==10)
            {
                btnGuess.Enabled = false;
                txtGuess.Enabled = false;
                txtGuess.Text = "";
                btnStart.Enabled = true;
                intNumGuesses=0;
            }
//This is what you're looking for-^
            try
            {
                intGuessedNum = Convert.ToInt32(txtGuess.Text);

                if (intRandomNumber - intGuessedNum < difference)
                {
                    lblAnswer.Text = "To High";
                    lblAnswer.ForeColor = Color.Red;
                    lblAnswer.BackColor = Color.White;
                    txtGuess.Text = "";
                    txtGuess.Focus();
                }
                else if (intRandomNumber - intGuessedNum > difference)
                {
                    lblAnswer.Text = "To Low";
                    lblAnswer.ForeColor = Color.Blue;
                    lblAnswer.BackColor = Color.White;
                    txtGuess.Text = "";
                    txtGuess.Focus();
                }
                else
                {
                    lblAnswer.Text = "You Guessed it.";
                    lblAnswer.ForeColor = Color.Black;
                    lblAnswer.BackColor = Color.Green;
                    btnGuess.Enabled = false;
                    txtGuess.Enabled = false;
                    txtGuess.Text = "";
                    btnStart.Enabled = true;

                }
            }
            catch
            {
                MessageBox.Show("Input your Guess again and Integers Only.  Retry.");
                txtGuess.Focus();
            }
        }


问:
How to apply css in jQuery on variable that is in loop?
Hello guys I search alot but find nothing regarding my problem.
I have one foreach loop in that i have one anchor tag and that will be changed according to my ifelse condition.
Now I want to change color of each if else condition in that. Please help me to do.My code is within jQuery script.

```<code>for(var j=0;j<arrayData.length;j++){
  var country = "";
  if(arrayData[j].key=="40"){
    country = "UK";
  }else if(arrayData[j].key=="41"){
    country = "INDIA";
  }else if(arrayData[j].key=="47"){
    country = "POLAND";
  }else{
    country = "GERMANY";
  }
  check+='<a class="btn btn-success" href="<?php echo base_url()?>uploads/'+arrayData[j].value+'">'+country+
                    '</a>|';
}
check +='</td></tr>';
</code>```

答:
You can just append it on the html string.

```<code>for(var j=0;j<arrayData.length;j++){
   var country = "";
   var color = "";
   if(arrayData[j].key=="40"){
       country = "UK";
       color = "red";
   }else if(arrayData[j].key=="41"){
       country = "INDIA";
       color = "orange";
   }else  if(arrayData[j].key=="47"){
       country = "POLAND";
       color = "yellow";
   }else{
        country = "GERMANY";
       color = "green";
   }

   check+='<a class="btn btn-success" style="background-color:' + color  + ';" href="<?php echo base_url()?>uploads/'+arrayData[j].value+'">'+country+
                    '</a>|';
}

 check +='</td></tr>';
</code>```

Other option: You can also add class to  tag.

Like class="color-red">

CSS:

```<code>.color-red {
   background-color: red;
}
</code>```

Body:
Hello guys I search alot but find nothing regarding my problem.
I have one foreach loop in that i have one anchor tag and that will be changed according to my ifelse condition.
Now I want to change color of each if else condition in that. Please help me to do.My code is within jQuery script.

for(var j=0;j<arrayData.length;j++){
  var country = "";
  if(arrayData[j].key=="40"){
    country = "UK";
  }else if(arrayData[j].key=="41"){
    country = "INDIA";
  }else if(arrayData[j].key=="47"){
    country = "POLAND";
  }else{
    country = "GERMANY";
  }
  check+='<a class="btn btn-success" href="<?php echo base_url()?>uploads/'+arrayData[j].value+'">'+country+
                    '|';
}
check +='
';

Body:
You can just append it on the html string.

for(var j=0;j<arrayData.length;j++){
   var country = "";
   var color = "";
   if(arrayData[j].key=="40"){
       country = "UK";
       color = "red";
   }else if(arrayData[j].key=="41"){
       country = "INDIA";
       color = "orange";
   }else  if(arrayData[j].key=="47"){
       country = "POLAND";
       color = "yellow";
   }else{
        country = "GERMANY";
       color = "green";
   }

   check+='<a class="btn btn-success" style="background-color:' + color  + ';" href="<?php echo base_url()?>uploads/'+arrayData[j].value+'">'+country+
                    '</a>|';
}

 check +='</td></tr>';

Other option: You can also add class to <a> tag.

Like <a class="color-red">

CSS:

.color-red {
   background-color: red;
}


问:
Heroku CLI installation error: "PATH not updated, original length 1585 > 1024"
I use Windows 10. When I run Heroku Cli (64) installation  I get an error "PATH not updated, original length 1585 > 1024". How to solve this problem?</p>

答:
You might have to set Environment variables in Advanced System Settings.
If there is already a path defined, just append your path with ;

ex:
Existing path(It can be anything, just as an example): C:\Program Files (x86)\Google\Chrome\Application

If you want to add heroku path: C:\Program Files (x86)\Google\Chrome\Application;C:\Program Files\Heroku\bin

Hope it works.

ContentLicense: CC BY-SA 4.0


问:
How to increase the font size of the request in postman tool?
I am using Postman tool for hitting the REST api with request and response. I want to increase the font size of the request. Under Settings there seem to be just one option to increase the font size of the response but not for request.

How can the font size of the request be increased?

答:
You can change postman font in Settings->User Interface->Editor Font Size(px) option

see the image


问:
LEFT JOIN returns null
I have following 2 tables, users and userRoles with following records in it:

```<code>userId  userName  firstName  lastName  password  image userRoles_roleId
........................................................................
1       a@a.dk    A          A         1                1
2       b@b.dk    B          B         2                2

roleId  userRole
.................
1       admin
2       user
</code>```

With the following query this is what I get:

```<code>SELECT users.userId, users.userName, users.firstName
     , users.lastName, users.password, users.image
     , userRoles.userRole FROM users
LEFT JOIN userRoles ON users.userID = userRoles.roleId;

userId  userName  firstName  lastName  password image  userRole
................................................................
1       a@a.dk    A          A            1            NULL
2       b@b.d     B          B            2            NULL
</code>```

Of course what I would like to get is admin and user.

Am I am not understanding well what LEFT JOIN it supposed to do or what´s wrong?

答:
A left [outer] join will permit a row from the "right" table to be displayed even if there is no matching row in the "left" table. However if you don't choose the correct columns for the join then you won't get good results. In the users table there is a foreign key column and the name of that column indicates which table it relates to. That column is userRoles_roleId so you need to change the query to this:

```
SELECT users.userId, users.userName, users.firstName
     , users.lastName, users.password, users.image
     , userRoles.userRole
FROM users
LEFT JOIN userRoles ON users.<b>userRoles_roleId</b> = userRoles.roleId;
```

Title: LEFT JOIN returns null

Body:
I have following 2 tables, users and userRoles with following records in it:

userId  userName  firstName  lastName  password  image userRoles_roleId
........................................................................
1       a@a.dk    A          A         1                1
2       b@b.dk    B          B         2                2

roleId  userRole
.................
1       admin
2       user

With the following query this is what I get:

SELECT users.userId, users.userName, users.firstName
     , users.lastName, users.password, users.image
     , userRoles.userRole FROM users
LEFT JOIN userRoles ON users.userID = userRoles.roleId;

userId  userName  firstName  lastName  password image  userRole
................................................................
1       a@a.dk    A          A            1            NULL
2       b@b.d     B          B            2            NULL

Of course what I would like to get is admin and user.

Am I am not understanding well what LEFT JOIN it supposed to do or what´s wrong?

Body:
A left [outer] join will permit a row from the "right" table to be displayed even if there is no matching row in the "left" table. However if you don't choose the correct columns for the join then you won't get good results. In the users table there is a foreign key column and the name of that column indicates which table it relates to. That column is userRoles_roleId so you need to change the query to this:

SELECT users.userId, users.userName, users.firstName
     , users.lastName, users.password, users.image
     , userRoles.userRole
FROM users
LEFT JOIN userRoles ON users.userRoles_roleId = userRoles.roleId;


问:
BroadcastReceiver fires only second time
I am checking Internet Connection by pinging to google.If there is no network or response is not successful I send a broadcast with a message that there is no Internet. Whenever I click a Textview in Navigation Drawer it must check whether there is internet connection.Whenever there is no internet and I click the textview it is not checked, it is checked only second time I click the Textview.The onReceive method of BroadcastReceiver is not called the first time.

Below is the code:

```<code>public void checkInternetConnection()
    {
        connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        networkInfo=connectivityManager.getActiveNetworkInfo();
        try {
            if (networkInfo!=null)
            {
                if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE || networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
                {
                    OkHttpClient okHttpClient = new OkHttpClient.Builder().
                            connectTimeout(30, TimeUnit.SECONDS).
                            writeTimeout(30, TimeUnit.SECONDS).
                            readTimeout(30, TimeUnit.SECONDS).build();
                    Request request = new Request.Builder().url(googleurl).build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("error", "error");
                            e.printStackTrace();
                            hasInternet1 = false;
                            Intent intent=new Intent("itrnt_avl");
                            intent.putExtra("inernet_availability",false);
                            sendBroadcast(intent);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {

                            Log.e("Response", response.body().string());
                            if (response.isSuccessful()) {
                                hasInternet1 = true;
                                Intent intent=new Intent("itrnt_avl");
                                intent.putExtra("inernet_availability",true);
                                sendBroadcast(intent);

                            } else {
                                Log.e("Response", "No response");
                                hasInternet1 = false;
                                Intent intent=new Intent("itrnt_avl");
                                intent.putExtra("inernet_availability",false);
                                sendBroadcast(intent);
                                throw new IOException("Unexpected code " + response.body().string());
                            }
                        }
                    });
                }
                else
                {
                    hasInternet1 = false;
                    Log.e("Response", "No network type");
                    Intent intent=new Intent("itrnt_avl");
                    intent.putExtra("inernet_availability",false);
                    sendBroadcast(intent);
                }
            }
            else {
                hasInternet1=false;
                Log.e("Response", "network null");
                Intent intent=new Intent("itrnt_avl");
                intent.putExtra("inernet_availability",false);
                sendBroadcast(intent);
            }
        }
        catch (NullPointerException e)
        {
            e.printStackTrace();
            Intent intent=new Intent("itrnt_avl");
            intent.putExtra("inernet_availability",false);
            sendBroadcast(intent);
        }
    }

 bad_dates.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    drawerlayout.closeDrawers();
     checkInternetConnection();
     if (broadcastReceiver==null)
     {
     Log.e("Receiver","Not null");

     broadcastReceiver=new BroadcastReceiver() {
     @Override
     public void onReceive(Context context, Intent intent) {
     Log.e("OnReceive","Called");

     hasInternet1=intent.getBooleanExtra("inernet_availability",false);
     unregisterReceiver(broadcastReceiver);
     broadcastReceiver=null;
     if (hasInternet1){
     new BackgroundTask1().execute();
     }
     else {
     Log.e("Internet Status","No Internet");
     Toast.makeText(getApplicationContext(),"Please check your
     InternetConnection and try again later",
     Toast.LENGTH_SHORT).show();
                                    }
                                }
                            };
     registerReceiver(broadcasteceiver,new IntentFilter("itrnt_avl"));
                        }
      });
</code>```

答:
The problem here is you are first calling the checkInternetConnection() which is posting the broadcast and then registering for it. Which means, first time there is no one to receive the broadcast.

When you run the checkInternetConnection() second time, you have already registered the receiver first time, hence it receives the broadcast.

So, you will have to register the broadcast receiver first and then call the method checkInternetConnection().

Also, as asked by you in the comment, the broadcastReceiver is the registered received. The method onReceive() will only get executed when the resisted broadcast is received.

Body:
I am checking Internet Connection by pinging to google.If there is no network or response is not successful I send a broadcast with a message that there is no Internet. Whenever I click a Textview in Navigation Drawer it must check whether there is internet connection.Whenever there is no internet and I click the textview it is not checked, it is checked only second time I click the Textview.The onReceive method of BroadcastReceiver is not called the first time.

Below is the code:

public void checkInternetConnection()
    {
        connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        networkInfo=connectivityManager.getActiveNetworkInfo();
        try {
            if (networkInfo!=null)
            {
                if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE || networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
                {
                    OkHttpClient okHttpClient = new OkHttpClient.Builder().
                            connectTimeout(30, TimeUnit.SECONDS).
                            writeTimeout(30, TimeUnit.SECONDS).
                            readTimeout(30, TimeUnit.SECONDS).build();
                    Request request = new Request.Builder().url(googleurl).build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("error", "error");
                            e.printStackTrace();
                            hasInternet1 = false;
                            Intent intent=new Intent("itrnt_avl");
                            intent.putExtra("inernet_availability",false);
                            sendBroadcast(intent);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {

                            Log.e("Response", response.body().string());
                            if (response.isSuccessful()) {
                                hasInternet1 = true;
                                Intent intent=new Intent("itrnt_avl");
                                intent.putExtra("inernet_availability",true);
                                sendBroadcast(intent);

                            } else {
                                Log.e("Response", "No response");
                                hasInternet1 = false;
                                Intent intent=new Intent("itrnt_avl");
                                intent.putExtra("inernet_availability",false);
                                sendBroadcast(intent);
                                throw new IOException("Unexpected code " + response.body().string());
                            }
                        }
                    });
                }
                else
                {
                    hasInternet1 = false;
                    Log.e("Response", "No network type");
                    Intent intent=new Intent("itrnt_avl");
                    intent.putExtra("inernet_availability",false);
                    sendBroadcast(intent);
                }
            }
            else {
                hasInternet1=false;
                Log.e("Response", "network null");
                Intent intent=new Intent("itrnt_avl");
                intent.putExtra("inernet_availability",false);
                sendBroadcast(intent);
            }
        }
        catch (NullPointerException e)
        {
            e.printStackTrace();
            Intent intent=new Intent("itrnt_avl");
            intent.putExtra("inernet_availability",false);
            sendBroadcast(intent);
        }
    }

 bad_dates.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    drawerlayout.closeDrawers();
     checkInternetConnection();
     if (broadcastReceiver==null)
     {
     Log.e("Receiver","Not null");

     broadcastReceiver=new BroadcastReceiver() {
     @Override
     public void onReceive(Context context, Intent intent) {
     Log.e("OnReceive","Called");

     hasInternet1=intent.getBooleanExtra("inernet_availability",false);
     unregisterReceiver(broadcastReceiver);
     broadcastReceiver=null;
     if (hasInternet1){
     new BackgroundTask1().execute();
     }
     else {
     Log.e("Internet Status","No Internet");
     Toast.makeText(getApplicationContext(),"Please check your
     InternetConnection and try again later",
     Toast.LENGTH_SHORT).show();
                                    }
                                }
                            };
     registerReceiver(broadcasteceiver,new IntentFilter("itrnt_avl"));
                        }
      });


问:
W/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms
well my app working fine getting data from Firebase. but sometimes specially after waiting long time if I open my app again it wont read data from firebase and also it gives this warning at Logcat. until I sing in and sing out it is not working.

```<code>W/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms
</code>```

are there any missing lines on my gradle?

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.restroomgames.whereismydudy.where"
        minSdkVersion 23
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.google.android.gms:play-services-maps:11.6.2'
    implementation 'com.google.firebase:firebase-auth:11.6.2'
    implementation 'com.google.firebase:firebase-database:11.6.2'
    implementation 'com.google.firebase:firebase-messaging:11.6.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.google.android.gms:play-services-location:11.6.2'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.lapism:searchview:5.0.0-alpha7'
    implementation 'agency.tango.android:material-intro-screen:0.0.5'
    implementation 'com.firebase:geofire-android:2.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}
apply plugin: 'com.google.gms.google-services'
</code>```

答: No there is nothing missing in your Gradle, this problem actually has come about since the upgrade to Firebase 11.6.0 Downgrading to 11.4.2 seems to remove the warning messages.

Body:
well my app working fine getting data from Firebase. but sometimes specially after waiting long time if I open my app again it wont read data from firebase and also it gives this warning at Logcat. until I sing in and sing out it is not working.

W/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms

are there any missing lines on my gradle?

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.restroomgames.whereismydudy.where"
        minSdkVersion 23
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.google.android.gms:play-services-maps:11.6.2'
    implementation 'com.google.firebase:firebase-auth:11.6.2'
    implementation 'com.google.firebase:firebase-database:11.6.2'
    implementation 'com.google.firebase:firebase-messaging:11.6.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'com.google.android.gms:play-services-location:11.6.2'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.lapism:searchview:5.0.0-alpha7'
    implementation 'agency.tango.android:material-intro-screen:0.0.5'
    implementation 'com.firebase:geofire-android:2.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}
apply plugin: 'com.google.gms.google-services'


答:
Here

```<code>char* FENString;
printf("Enter FEN Key: ");
fgets(FENString, 50, stdin);
</code>```

FENString is a character pointer and  before putting any data into it, FENString should have valid memory space to store something into it. But in your case FENString doesn't point to valid address which is the issue.

To resolve this you can take FENString either as a character buffer like

```<code>char FENString[1024] = {};
</code>```

or allocate memory dynamically for FENString like

```<code>char* FENString = malloc(sizeof(*FENString) * MAX_BUF_SIZE); /* define the MAX_BUF_SIZE, instead of magic number like 50 use macro */
/* Do error handling malloc() */
if(FENString == NULL){
    fprintf(stderr, "malloc() failed\n");
    exit(1);
}
</code>```

Now store the user input into dynamically created array by calling fgets() . For example

```<code>if(fgets(FENString, MAX_BUF_SIZE, stdin) != NULL){
    /* fgets is success, but if fgets store the \n at the end of buffer if its read */
    /* to remove trailing \n char use strcspn() */
    FENString[strcspn(FENString, "\n")] = 0;
}
</code>```

Title: Fgets only returning '\n' char

Body:
Here

char* FENString;
printf("Enter FEN Key: ");
fgets(FENString, 50, stdin);

FENString is a character pointer and  before putting any data into it, FENString should have valid memory space to store something into it. But in your case FENString doesn't point to valid address which is the issue.

To resolve this you can take FENString either as a character buffer like

char FENString[1024] = {};

or allocate memory dynamically for FENString like

char* FENString = malloc(sizeof(*FENString) * MAX_BUF_SIZE); /* define the MAX_BUF_SIZE, instead of magic number like 50 use macro */
/* Do error handling malloc() */
if(FENString == NULL){
    fprintf(stderr, "malloc() failed\n");
    exit(1);
}

Now store the user input into dynamically created array by calling fgets() . For example

if(fgets(FENString, MAX_BUF_SIZE, stdin) != NULL){
    /* fgets is success, but if fgets store the \n at the end of buffer if its read */
    /* to remove trailing \n char use strcspn() */
    FENString[strcspn(FENString, "\n")] = 0;
}


问:
2D vector segmentation fault
The following code is giving me a segmentation fault and I don't understand the problem. I think there's some mistake in the way I've used vectors but I don't know what that is. Please help.</p>

```<code>#include<iostream>
#include<sstream>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
    int T;
    vector<int>n,m;
    vector<vector<int> >arr;
    int temp;
    cin>>T;
    for(int i=0;i<T;i++)
    {
        cin>>temp;
        n.push_back(temp);
        cin>>temp;
        m.push_back(temp);
        vector<int>temp_vec(temp);
        for(int j=0;j<temp;j++)
        {
            int temp2;
            cin>>temp2;
            temp_vec[j]=(temp2);
        }
        sort(temp_vec.begin(),temp_vec.end());
        arr.push_back(temp_vec);
        cout<<endl;
    }
    return(0);
}
</code>```

答:
When you declare a vector of any type it does not have any elements until you initialize and put the value into it. Your code:

```<code>arr.push_back(temp_vec);
</code>```

is trying to insert temp_vec into a non-existent vector inside the vector arr at position 0.

You should know the size of the vector that you want to use and then initialize that with the size of the constructor:

```<code>vector<vector<int> >arr(size);
</code>```

for example:

```<code>vector<vector<int> >arr(64);
</code>```

This will be initialize the vector arr with 64 or x empty elements.

Same as this

Title: 2D vector segmentation fault

Body:
The following code is giving me a segmentation fault and I don't understand the problem. I think there's some mistake in the way I've used vectors but I don't know what that is. Please help.

#include<iostream>
#include<sstream>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
    int T;
    vector<int>n,m;
    vector<vector<int> >arr;
    int temp;
    cin>>T;
    for(int i=0;i<T;i++)
    {
        cin>>temp;
        n.push_back(temp);
        cin>>temp;
        m.push_back(temp);
        vector<int>temp_vec(temp);
        for(int j=0;j<temp;j++)
        {
            int temp2;
            cin>>temp2;
            temp_vec[j]=(temp2);
        }
        sort(temp_vec.begin(),temp_vec.end());
        arr.push_back(temp_vec);
        cout<<endl;
    }
    return(0);
}

Body:
When you declare a vector of any type it does not have any elements until you initialize and put the value into it. Your code:

arr.push_back(temp_vec);

is trying to insert temp_vec into a non-existent vector inside the vector arr at position 0.

You should know the size of the vector that you want to use and then initialize that with the size of the constructor:

vector<vector<int> >arr(size);

for example:

vector<vector<int> >arr(64);

This will be initialize the vector arr with 64 or x empty elements.

Same as this


问:
How to make a public dictionary in an Excel
I have something like this:

```<code>Private Sub ComboBox1_Change()
'(...do something related to alpha...)
End Sub

Private Sub UserForm_Activate()
Set alpha = CreateObject("Scripting.Dictionary")
'(...do something like add keys and values to the alpha dictionary...)
End Sub
</code>```

I'm really new at VBA and I noticed that alpha dictionary can only be used inside UserForm_Activate, so I want to make a global variable in order to use it also in ComboBox1_Change.

But I can't.

I tried with something more simple, like an integer.

```<code>Public x as Integer

Private Sub ComboBox1_Change()
MsgBox(x)
End Sub

Private Sub UserForm_Activate()
x = 5
End Sub
</code>```

And this work, but if I do something similar but with a dictionary (Public alpha as Scripting.Dictionary), it raise (from spanish) "Compilation error: It wasn't defined the type defined by the user". I don't know what to do.

答:
Having a Public object withing a Form's Class module is a bad idea. Unless the object should be accessible only within the class, thus the accessibility should be changed to Private, consider having it in a Standard module.

You could also expose it by a Public property so you don't have to worry about the object's construction.

```<code>Private objAlpha As Object

Public Property Get Alpha() As Object
    If objAlpha Is Nothing Then Set objAlpha = CreateObject("Scripting.Dictionary")
    Set Alpha = objAlpha
End Property
</code>```

To call it:

```<code>If Alpha.Exists("SomeText") Then
    '...
End If
</code>```

This way it can be referenced anywhere in your project.

Body:
I have something like this:

Private Sub ComboBox1_Change()
'(...do something related to alpha...)
End Sub

Private Sub UserForm_Activate()
Set alpha = CreateObject("Scripting.Dictionary")
'(...do something like add keys and values to the alpha dictionary...)
End Sub

I'm really new at VBA and I noticed that alpha dictionary can only be used inside UserForm_Activate, so I want to make a global variable in order to use it also in ComboBox1_Change.

But I can't.

I tried with something more simple, like an integer.

Public x as Integer

Private Sub ComboBox1_Change()
MsgBox(x)
End Sub

Private Sub UserForm_Activate()
x = 5
End Sub

And this work, but if I do something similar but with a dictionary (Public alpha as Scripting.Dictionary), it raise (from spanish) "Compilation error: It wasn't defined the type defined by the user". I don't know what to do.

Body:
Having a Public object withing a Form's Class module is a bad idea. Unless the object should be accessible only within the class, thus the accessibility should be changed to Private, consider having it in a Standard module.

You could also expose it by a Public property so you don't have to worry about the object's construction.

Private objAlpha As Object

Public Property Get Alpha() As Object
    If objAlpha Is Nothing Then Set objAlpha = CreateObject("Scripting.Dictionary")
    Set Alpha = objAlpha
End Property

To call it:

If Alpha.Exists("SomeText") Then
    '...
End If

This way it can be referenced anywhere in your project.


问:
Programming Language for Berkeley Overmind Starcraft AI competition
Does anyone know which programming language the Berkeley Overmind submission to the Starcraft AI competition this past year was?</p>

答:
You can download all of the bots here.  The Overmind bot is written in Java.

The bot-Overmind directory in the distribution contains a large number of Java class files.  It appears to use bwapi-jbridge to bridge the gap between the C++ BroodWar API and the Java code.


答:
What about this?

```<code>{
  intNumGuesses++;
  if(intNumGuesses >= 10)
  {
    StartButton(); // pseudo call, replace with whatever the name and parameters of your method really are
    return;
  }
  lblNumGuesses.Text = intNumGuesses.ToString();
  // ...
}
</code>```

I would recommend to write an Init()method, that you call either from your StartButton() method or from your GuessButton() method when necessary

Title: Click event restart

Body:
I'm using c# windows form in Visual studio 2017 version

I've made a high low game for practice and it works perfect but what I'm trying to accomplish is once someone hits 10 guesses it starts the application over again.

This was my last resort coming here and asking but i have no one else to turn to. I've tried all kinds of things to make it work when hitting 10 guesses to restart the app but nothing works and i get errors.

here's the start button and the guess button

variables I'm using

    static int intRandomNumber;
    static int intNumGuesses;
    static int intBestLowScore;
    static int intGuessedNum;
    static int difference = 0;

Start Button

        {
        //Random Numbers//

        Random rnRandomNumber = new Random();
        intRandomNumber = rnRandomNumber.Next(0, 1000);
        lblRandomNumber.Text = intRandomNumber.ToString();
        txtGuess.Enabled = true;
        btnGuess.Enabled = true;
        btnStart.Enabled = false;
        lblAnswer.Text = "".ToString();
        intBestLowScore = intNumGuesses;
        intNumGuesses = 0;
        lblNumGuesses.Text = "0";
        lblBestScore.Text = intBestLowScore.ToString();
        lblAnswer.BackColor = Color.White;
        txtGuess.Focus();
        SoundPlayer audio = new SoundPlayer(High_Low_Game.Properties.Resources.Cheering);
        audio.Stop();
    }

Guess Button

{
        intNumGuesses++;
        lblNumGuesses.Text = intNumGuesses.ToString();

        try
        {
            intGuessedNum = Convert.ToInt32(txtGuess.Text);

            if (intRandomNumber - intGuessedNum < difference)
            {
                lblAnswer.Text = "To High";
                lblAnswer.ForeColor = Color.Red;
                lblAnswer.BackColor = Color.White;
                txtGuess.Text = "";
                txtGuess.Focus();
            }
            else if (intRandomNumber - intGuessedNum > difference)
            {
                lblAnswer.Text = "To Low";
                lblAnswer.ForeColor = Color.Blue;
                lblAnswer.BackColor = Color.White;
                txtGuess.Text = "";
                txtGuess.Focus();
            }
            else
            {
                lblAnswer.Text = "You Guessed it.";
                lblAnswer.ForeColor = Color.Black;
                lblAnswer.BackColor = Color.Green;
                btnGuess.Enabled = false;
                txtGuess.Enabled = false;
                txtGuess.Text = "";
                btnStart.Enabled = true;
                SoundPlayer audio = new SoundPlayer(High_Low_Game.Properties.Resources.Cheering);
                audio.Play();

            }
        }
        catch
        {
            MessageBox.Show("Input your Guess again and Integers Only.  Retry.");
            txtGuess.Focus();
        }

     }

Body:
What about this?

{
  intNumGuesses++;
  if(intNumGuesses >= 10)
  {
    StartButton(); // pseudo call, replace with whatever the name and parameters of your method really are
    return;
  }
  lblNumGuesses.Text = intNumGuesses.ToString();
  // ...
}

I would recommend to write an Init()method, that you call either from your StartButton() method or from your GuessButton() method when necessary


问:
Unique username with parsley js
I'm trying to use parsley's js custom validator to check for a unique email address on my form. However it's not stopping the form from submitting when I not matter what I return.

The ajax request checkEmailExists returns true or false depending on if the email exists

```<code>window.Parsley
  .addValidator('uniqueUsername', {
    requirementType: 'string',
    validateString: function(value, requirement) {
      $.ajax({
        url: "checkEmailExists",
        data: {username: value},
        dataType: 'json',
        method: 'POST',
        data: { email: $( "#email" ).val() },
        async: false,
        success: function(data) {
          return data;
        }
      });
    },
    messages: {
      en: 'This email address already exists!'
    }
  });

<input type="text" id="email" name="email" placeholder="Email" data-parsley-uniqueUsername data-parsley-required="true" data-parsley-type="email"/>
</code>```

答:
As Marc said your promise must fail for succeed and also your validator name can't have capital letters or special characters so try something like this:</p>

```<code>// uniqueUsername validator
window.Parsley.addValidator('uniqueusername', {
    validateString: function (value, requirement) {

        xhr = $.ajax({
            url: "users_list_ajax.php",
            dataType: 'json',
            method: 'GET',
            data: {
                action: 'checkUserExists',
                username: value
            }
        });

        return xhr.then(function (data) {
            console.log((data.isUnique == 0));

            if (data.isUnique == 0) {
                return true;
            } else {
                return $.Deferred().reject();
            }
        });
    },
    messages: {
        en: 'Username already exists!',
        ar: 'إسم المستخدم موجود مسبقا'
    },
    priority: 32
});
</code>```

Title: Unique username with parsley js

Body:
I'm trying to use parsley's js custom validator to check for a unique email address on my form. However it's not stopping the form from submitting when I not matter what I return.

The ajax request checkEmailExists returns true or false depending on if the email exists

window.Parsley
  .addValidator('uniqueUsername', {
    requirementType: 'string',
    validateString: function(value, requirement) {
      $.ajax({
        url: "checkEmailExists",
        data: {username: value},
        dataType: 'json',
        method: 'POST',
        data: { email: $( "#email" ).val() },
        async: false,
        success: function(data) {
          return data;
        }
      });
    },
    messages: {
      en: 'This email address already exists!'
    }
  });

<input type="text" id="email" name="email" placeholder="Email" data-parsley-uniqueUsername data-parsley-required="true" data-parsley-type="email"/>

Body:
As Marc said your promise must fail for succeed and also your validator name can't have capital letters or special characters so try something like this:

// uniqueUsername validator
window.Parsley.addValidator('uniqueusername', {
    validateString: function (value, requirement) {

        xhr = $.ajax({
            url: "users_list_ajax.php",
            dataType: 'json',
            method: 'GET',
            data: {
                action: 'checkUserExists',
                username: value
            }
        });

        return xhr.then(function (data) {
            console.log((data.isUnique == 0));

            if (data.isUnique == 0) {
                return true;
            } else {
                return $.Deferred().reject();
            }
        });
    },
    messages: {
        en: 'Username already exists!',
        ar: 'إسم المستخدم موجود مسبقا'
    },
    priority: 32
});


问:
VBA UserForm: SpinButtons not working when TextBoxes are formatted using Class Module
I have a bunch of spinbuttons that control the values in textboxes.  I'm using a Class to allow all of them to use the same change event.  It works great with unformatted boxes.

However when I try to make the textboxes show + and - numbers it doesn't work correctly.  Only the first spin button will work.  It's value needs to be set to a negative number before the next spinbutton will work.  No buttons (other than the first) will work correctly unless the textbox directly above it in order is set to a negative number.

I've tried using .Text instead of .Value but it doesn't make a difference.

Class Module:

```<code>Public WithEvents SpinBtn As MSForms.SpinButton
Public WithEvents StatBox As MSForms.TextBox

Private Sub StatBox_Change()
Call UserForm1.ChangeSpin
End Sub

Private Sub SpinBtn_Change()
Call UserForm1.ChangeStat
End Sub
</code>```

UserForm Module:

```<code>Dim collSpin As New Collection
Dim collStat As New Collection

Public Sub ChangeStat()
    Dim i As Long

    For i = 1 To 4
         Me.Controls("StatBox" & i).Value = Me.Controls("SpinButton" & i).Value
    Next
End Sub

Public Sub ChangeSpin()
    Dim i As Long

    For i = 1 To 4
        Me.Controls("SpinButton" & i).Value = Me.Controls("StatBox" & i).Value
        Me.Controls("StatBox" & i) = Format(Me.Controls("StatBox" & i), "+#;-#;+0")
        'This is the line that breaks things
    Next
End Sub

Private Sub UserForm_Initialize()
    Dim i As Long
    Dim ctl As MSForms.Control
    Dim obEvents As clsSpin

    Call ChangeSpin

    'Collect SpinButtons
    For Each ctl In Me.Controls
        If TypeOf ctl Is MSForms.SpinButton Then
            For i = 1 To 4
                If ctl.Name = "SpinButton" & i Then
                    Set obEvents = New clsSpin
                    Set obEvents.SpinBtn = ctl
                    collSpin.Add obEvents
                End If
            Next
        End If
    Next ctl

    'Collect StatBoxes
    For Each ctl In Me.Controls
        If TypeOf ctl Is MSForms.TextBox Then
            For i = 1 To 4
                If ctl.Name = "StatBox" & i Then
                    Set obEvents = New clsSpin
                    Set obEvents.StatBox = ctl
                    collStat.Add obEvents
                End If
            Next
        End If
    Next ctl
End Sub
</code>```

Edit:
Thanks to @YowE3K for showing me a much easier and cleaner way!

Class:

```<code>Public WithEvents SpinBtn As MSForms.SpinButton
Public WithEvents StatBox As MSForms.TextBox

Private Sub StatBox_Change()
    'prevents error when enter + or -
    If IsNumeric(Me.StatBox.Value) = False Then
    Else
        'defaults to max or min of spinbutton when out of range
        Select Case Me.StatBox.Value
            Case Is < SpinBtn.Min
                Me.SpinBtn.Value = Me.SpinBtn.Min
            Case Is > SpinBtn.Max
                Me.SpinBtn.Value = Me.SpinBtn.Max
            Case Else
                Me.SpinBtn.Value = Me.StatBox.Value
        End Select
    Me.StatBox.Value = Format(Me.StatBox.Value, "+#;-#;+0")
    End If
End Sub

Private Sub SpinBtn_Change()
    Me.StatBox.Value = Format(Me.SpinBtn.Value, "+#;-#;+0")
End Sub

Private Sub StatBox_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    Select Case KeyAscii
        Case 43 '+
        Case 45 '-
        Case 48 To 57 '0-9
        Case Else
            KeyAscii = 0
    End Select
End Sub
</code>```

Userform:

```<code>Dim collSpinStat As New Collection

Private Sub UserForm_Initialize()
    Dim i As Long
    Dim obEvents As clsSpin

    For i = 1 To 4
        Set obEvents = New clsSpin
        Set obEvents.SpinBtn = Me.Controls("SpinButton" & i)
        Set obEvents.StatBox = Me.Controls("StatBox" & i)
        Me.Controls("StatBox" & i) = Format(Me.Controls("StatBox" & i), "+#;-#;+0")
        collSpinStat.Add obEvents
    Next
End Sub
</code>```

答:
It seems like you are trying to link the "StatBox" controls with the "SpinButton" controls.  If so, try the following:

Class "clsSpin":

```<code>Public WithEvents SpinBtn As MSForms.SpinButton
Public WithEvents StatBox As MSForms.TextBox

Private Sub StatBox_Change()
    Me.SpinBtn.Value = Me.StatBox.Value
End Sub

Private Sub SpinBtn_Change()
    Me.StatBox.Value = Format(Me.SpinBtn.Value, "+#;-#;+0")
End Sub
</code>```

UserForm module:

```<code>Dim collSpinStat As New Collection

Private Sub UserForm_Initialize()
    Dim i As Long
    Dim obEvents As clsSpin

    For i = 1 To 4
        Set obEvents = New clsSpin
        Set obEvents.SpinBtn = Me.Controls("SpinButton" & i)
        Set obEvents.StatBox = Me.Controls("StatBox" & i)
        collSpinStat.Add obEvents
    Next
End Sub
</code>```

FWIW, I would suggest using Labels instead of TextBoxes.  Using TextBoxes means you will need to incorporate code into the StatBox_Change event to test whether the value entered by the user in the TextBox is actually valid or not.  Using Labels means the user has to use the SpinButton to make the change.

Body:
I have a bunch of spinbuttons that control the values in textboxes.  I'm using a Class to allow all of them to use the same change event.  It works great with unformatted boxes.

However when I try to make the textboxes show + and - numbers it doesn't work correctly.  Only the first spin button will work.  It's value needs to be set to a negative number before the next spinbutton will work.  No buttons (other than the first) will work correctly unless the textbox directly above it in order is set to a negative number.

I've tried using .Text instead of .Value but it doesn't make a difference.

Class Module:

Public WithEvents SpinBtn As MSForms.SpinButton
Public WithEvents StatBox As MSForms.TextBox

Private Sub StatBox_Change()
Call UserForm1.ChangeSpin
End Sub

Private Sub SpinBtn_Change()
Call UserForm1.ChangeStat
End Sub

UserForm Module:

Dim collSpin As New Collection
Dim collStat As New Collection

Public Sub ChangeStat()
    Dim i As Long

    For i = 1 To 4
         Me.Controls("StatBox" & i).Value = Me.Controls("SpinButton" & i).Value
    Next
End Sub

Public Sub ChangeSpin()
    Dim i As Long

    For i = 1 To 4
        Me.Controls("SpinButton" & i).Value = Me.Controls("StatBox" & i).Value
        Me.Controls("StatBox" & i) = Format(Me.Controls("StatBox" & i), "+#;-#;+0")
        'This is the line that breaks things
    Next
End Sub

Private Sub UserForm_Initialize()
    Dim i As Long
    Dim ctl As MSForms.Control
    Dim obEvents As clsSpin

    Call ChangeSpin

    'Collect SpinButtons
    For Each ctl In Me.Controls
        If TypeOf ctl Is MSForms.SpinButton Then
            For i = 1 To 4
                If ctl.Name = "SpinButton" & i Then
                    Set obEvents = New clsSpin
                    Set obEvents.SpinBtn = ctl
                    collSpin.Add obEvents
                End If
            Next
        End If
    Next ctl

    'Collect StatBoxes
    For Each ctl In Me.Controls
        If TypeOf ctl Is MSForms.TextBox Then
            For i = 1 To 4
                If ctl.Name = "StatBox" & i Then
                    Set obEvents = New clsSpin
                    Set obEvents.StatBox = ctl
                    collStat.Add obEvents
                End If
            Next
        End If
    Next ctl
End Sub

Edit:
Thanks to @YowE3K for showing me a much easier and cleaner way!

Class:

Public WithEvents SpinBtn As MSForms.SpinButton
Public WithEvents StatBox As MSForms.TextBox

Private Sub StatBox_Change()
    'prevents error when enter + or -
    If IsNumeric(Me.StatBox.Value) = False Then
    Else
        'defaults to max or min of spinbutton when out of range
        Select Case Me.StatBox.Value
            Case Is < SpinBtn.Min
                Me.SpinBtn.Value = Me.SpinBtn.Min
            Case Is > SpinBtn.Max
                Me.SpinBtn.Value = Me.SpinBtn.Max
            Case Else
                Me.SpinBtn.Value = Me.StatBox.Value
        End Select
    Me.StatBox.Value = Format(Me.StatBox.Value, "+#;-#;+0")
    End If
End Sub

Private Sub SpinBtn_Change()
    Me.StatBox.Value = Format(Me.SpinBtn.Value, "+#;-#;+0")
End Sub

Private Sub StatBox_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    Select Case KeyAscii
        Case 43 '+
        Case 45 '-
        Case 48 To 57 '0-9
        Case Else
            KeyAscii = 0
    End Select
End Sub

Userform:

Dim collSpinStat As New Collection

Private Sub UserForm_Initialize()
    Dim i As Long
    Dim obEvents As clsSpin

    For i = 1 To 4
        Set obEvents = New clsSpin
        Set obEvents.SpinBtn = Me.Controls("SpinButton" & i)
        Set obEvents.StatBox = Me.Controls("StatBox" & i)
        Me.Controls("StatBox" & i) = Format(Me.Controls("StatBox" & i), "+#;-#;+0")
        collSpinStat.Add obEvents
    Next
End Sub

Body:
It seems like you are trying to link the "StatBox" controls with the "SpinButton" controls.  If so, try the following:

Class "clsSpin":

Public WithEvents SpinBtn As MSForms.SpinButton
Public WithEvents StatBox As MSForms.TextBox

Private Sub StatBox_Change()
    Me.SpinBtn.Value = Me.StatBox.Value
End Sub

Private Sub SpinBtn_Change()
    Me.StatBox.Value = Format(Me.SpinBtn.Value, "+#;-#;+0")
End Sub

UserForm module:

Dim collSpinStat As New Collection

Private Sub UserForm_Initialize()
    Dim i As Long
    Dim obEvents As clsSpin

    For i = 1 To 4
        Set obEvents = New clsSpin
        Set obEvents.SpinBtn = Me.Controls("SpinButton" & i)
        Set obEvents.StatBox = Me.Controls("StatBox" & i)
        collSpinStat.Add obEvents
    Next
End Sub

FWIW, I would suggest using Labels instead of TextBoxes.  Using TextBoxes means you will need to incorporate code into the StatBox_Change event to test whether the value entered by the user in the TextBox is actually valid or not.  Using Labels means the user has to use the SpinButton to make the change.


问:
Log4j2 GC-Free Async loggers: passing mutable objects
I am using log4j version 2.10.0

I am trying to set up gc-free logging with mixed async and sync loggers(so it's configured via xml configuration with some <AsyncLogger> tags). The question is: what if I pass a mutable object to async logger? Would it first create a message and then pass it to background or it will create it only in background, meaning that it could log already changed object? Would the behaviour be different if I make all loggers async(via property using AsyncLoggerContextSelector instead of AsyncLogger xml tag)?

The objects are mutable because I want to reuse them in the future, for example, instead of creating new ones.

I saw this question: slf4j-log4j converts objects to string before passing to Asynchronus logger.
But I believe the gc-free behaviour could be different from just async(As it mentioned in answer on that question).

答:
Log4j2 will render the message in the application thread before returning from the logging method, to ensure that what is written to the log file is the value at the time that the logger was called.

This works out of the box with all async logging methods (async appender as well as both flavours of async loggers).  With garbage free logging this works similarly, the only difference is the data structures used by Log4j2 internally. The fact that the message is rendered before passing it to the background thread is the same.

There is a system property to render the message in the background thread but I would not recommend this unless you are very confident that the application doesn’t modify the objects that were logged.