问:
ClassNotFoundException but library present
My Java service running in Google App Engine in the standard environment  is giving me a ClassNotFoundException although I can see through the Stackdriver debug screen that the library was deployed.  The service runs fine locally and the other libraries are being picked up ok.  In fact, other classes in the library are being read okay.  The class in question has java 6 bytecode so it should be readable by google's JDK.  Any ideas of what would cause this or what I should look at?  Thanks</p>

答:
Turns out the 3rd-party library was using a restricted class in the standard environment (the "sandbox").  White-list of classes is here: https://cloud.google.com/appengine/docs/standard/java/jrewhitelist

Didn't see the error message in the logs (maybe it was buried somewhere), but found it in the AppeEngine dashboard page.


来源: stackexchange

问:
How can I generate a random number within a certain range with Java?
I want to generate a random number in Java. It can be of integer, byte or float type, but all I really need it is to generate a random number. This is what I'm doing:

Generate a random number within a certain range (e.g. 5 through 20).

Take the number and store it within a variable.

Perform arithmetic on it.

Here's the code:

```<code>import java.util.HashMap;

public class Attack {
    public static void main(String[] args) {
        HashMap<String, Integer> attacks = new HashMap<String, Integer>();
        attacks.put("Punch", 1);
        attacks.put("Uppercut", 3);
        attacks.put("Roundhouse Kick", 5);

        int actionPoints = // Code for random number generation

        System.out.println("A brigade integrant appeared!");
        System.out.println("What do you do?");
        System.out.println("1: Punch [1 AP], 2: Uppercut [3 AP], 3: Roundhouse Kick [5 AP]");
        System.out.println("You have " + actionPoints + " Action Points.");
        Scanner reader = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = reader.nextInt();
        reader.close();

        if n == 1 {
            System.out.println("The brigade integrant takes 2 HP of damage!");
        }
        else if n == 2 {
            System.out.println("The brigade integrant takes 5 HP of damage!");
        }
        else if n == 3 {
            System.out.println("The brigade integrant takes 8 HP of damage!");
        }
    }
}
</code>```

答:
In Java 1.7+ you can do it in one line (not counting the import statement ;):</p>

```<code>import java.util.concurrent.ThreadLocalRandom;

int actionPoints = ThreadLocalRandom.current().nextInt(5, 21); // 5 to 20 inclusive
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to generate a random number in Java. It can be of integer, byte or float type, but all I really need it is to generate a random number. This is what I'm doing:

Generate a random number within a certain range (e.g. 5 through 20).

Take the number and store it within a variable.

Perform arithmetic on it.

Here's the code:

import java.util.HashMap;

public class Attack {
    public static void main(String[] args) {
        HashMap<String, Integer> attacks = new HashMap<String, Integer>();
        attacks.put("Punch", 1);
        attacks.put("Uppercut", 3);
        attacks.put("Roundhouse Kick", 5);

        int actionPoints = // Code for random number generation

        System.out.println("A brigade integrant appeared!");
        System.out.println("What do you do?");
        System.out.println("1: Punch [1 AP], 2: Uppercut [3 AP], 3: Roundhouse Kick [5 AP]");
        System.out.println("You have " + actionPoints + " Action Points.");
        Scanner reader = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = reader.nextInt();
        reader.close();

        if n == 1 {
            System.out.println("The brigade integrant takes 2 HP of damage!");
        }
        else if n == 2 {
            System.out.println("The brigade integrant takes 5 HP of damage!");
        }
        else if n == 3 {
            System.out.println("The brigade integrant takes 8 HP of damage!");
        }
    }
}

Body:
In Java 1.7+ you can do it in one line (not counting the import statement ;):

import java.util.concurrent.ThreadLocalRandom;

int actionPoints = ThreadLocalRandom.current().nextInt(5, 21); // 5 to 20 inclusive


问:
Is there a way to list all the rpms in an iso image?
I need a way to list all the RPMS in an iso image without booting the iso file and making a live image. Eventually I'm trying to make a very light weight cron job or Jenkins jobs to get the list of RPMS on an iso image.</p>

答:
```<code>mount -o loop your.iso /mnt/cd
find /mnt/cd -type f -name '*.rpm' | wc -l
unmount /mnt/cd
</code>```


问:
Insert variables into a SQL Server table in stored procedure
I am trying to insert variables into SQL Server table dynamically inside a stored procedure but I'm not able to accomplish it because of the syntax. Can someone correct me what am I doing wrong in the below code. Thanks.

Code I have tried:

```<code>SET @SQLStmt1 = N'INSERT INTO TestTable (TableName)
                  VALUES(' + @ResulTableName + N')'
EXEC sp_executesql @SQLStmt1
</code>```

答:
You are close, but you should use a parameter for the value:

```<code>SET @SQLStmt1 = N'INSERT INTO TestTable( TableName )
                              VALUES(@ResulTableName)';

EXEC sp_executesql @SQLStmt1, N'@ResultTableName NVARCHAR(MAX)',
                   @ResulTableName = @ResulTableName;
</code>```

If you printed out @SQLStmt1, you would see that the single quotes are not correct.

Body:
I am trying to insert variables into SQL Server table dynamically inside a stored procedure but I'm not able to accomplish it because of the syntax. Can someone correct me what am I doing wrong in the below code. Thanks.

Code I have tried:

SET @SQLStmt1 = N'INSERT INTO TestTable (TableName)
                  VALUES(' + @ResulTableName + N')'
EXEC sp_executesql @SQLStmt1

Body:
You are close, but you should use a parameter for the value:

SET @SQLStmt1 = N'INSERT INTO TestTable( TableName )
                              VALUES(@ResulTableName)';

EXEC sp_executesql @SQLStmt1, N'@ResultTableName NVARCHAR(MAX)',
                   @ResulTableName = @ResulTableName;

If you printed out @SQLStmt1, you would see that the single quotes are not correct.


问:
Max /28 subnets in a 10.0.0.0/16 VPC
AWS documentation states I can have 200 subnets per VPC without requesting additional capacity. I'm looking to create /28 CIDR subnets that can each provide 16 (or 11 usable) ip addresses and I want to create the maximum number of subnets in the VPC. What CIDR should I assign to the VPC itself? (maybe 10.0.0.0/16?) And what are some example CIDRs to define the subnets? </p>

答:
You could use a /20 network, which would give 4096 addresses.

That would give 256 subnets * 16 addresses (/28) = 4096

But, feel free to use something larger.

You might want to automate the creation of that many subnets.

See: CIDR, Subnet Masks, and Usable IP Addresses Quick Reference Guide (Cheat Sheet)

Title: Max /28 subnets in a 10.0.0.0/16 VPC


问:
Calling a class through an Intent
Main method button onClick:

```<code>public void onClick(View v) {
                Intent numbers = new Intent(MainActivity.this, Questions.class);
                numbers.putExtra("randomNumber", rand);
                startActivity(numbers);
                Intent numbertoAnswer = new Intent(MainActivity.this, Answers.class);
                numbertoAnswer.putExtra("randomnumber", rand);
                startActivity(numbertoAnswer);
            }
        });
</code>```

After this code runs the question class onCreate is fine, but the Answers class does not run.  I used the same button to call intents to both.  I ended up just trying to call the methods from the class in the question class which caused an error.  Is there a problem with an intents or is there a problem with the code in the Answers class?

Question

```<code>    protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.game_view);
            int questionNumber = getIntent().getIntExtra("randomNumber", 1);
            question(questionNumber);

            TextView questiontv = (TextView) findViewById(R.id.Question);
            questiontv.setText(question(questionNumber));

            Answers answers = new Answers();
            answers.createQuestions();
            answers.buttonTextGetter();
}
</code>```

Answers:

```<code>public class Answers extends Activity {

    Button choice1 = (Button) findViewById(R.id.answer_choice1);
    Button choice2 = (Button) findViewById(R.id.answer_choice2);
    Button choice3 = (Button) findViewById(R.id.answer_choice3);
    Button choice4 = (Button) findViewById(R.id.answer_choice4);
    int questionNumber = getIntent().getIntExtra("randomnumber", 1);
    Random rand = new Random();
    int randomCorrectButton = rand.nextInt(3) + 1;

    public void createQuestions() {

        AnswerPeople(questionNumber);
        if (answer == null) {
            AnswerNumbers(questionNumber);
        }
        switch (randomCorrectButton) {
            case 1:
                choice1.setText(answer);
                break;
            case 2:
                choice2.setText(answer);
                break;
            case 3:
                choice3.setText(answer);
                break;
            case 4:
                choice4.setText(answer);
                break;
        }
    }
        String AnswerChoice1 = randomAnswerButton1(randomCorrectButton, questionNumber, rand);
        String AnswerChoice2 = randomAnswerButton2(randomCorrectButton, questionNumber, rand);
        String AnswerChoice3 = randomAnswerButton3(randomCorrectButton, questionNumber, rand);
        String AnswerChoice4 = randomAnswerButton4(randomCorrectButton, questionNumber, rand);

        public void buttonTextGetter(){

        randomAnswerButton1(randomCorrectButton, questionNumber, rand);
        randomAnswerButton2(randomCorrectButton, questionNumber, rand);
        randomAnswerButton3(randomCorrectButton, questionNumber, rand);
        randomAnswerButton4(randomCorrectButton, questionNumber, rand);

        checkForRepeat(AnswerChoice1, AnswerChoice2, AnswerChoice3, AnswerChoice4, randomCorrectButton, questionNumber, rand);

        if (randomCorrectButton != 1) {
            choice1.setText(AnswerChoice1);
        } else if (randomCorrectButton != 2) {
            choice2.setText(AnswerChoice2);
        } else if (randomCorrectButton != 3) {
            choice3.setText(AnswerChoice3);
        } else if (randomCorrectButton != 4) {
            choice4.setText(AnswerChoice4);
        }
        }

    public void checkForRepeat(String AnswerChoice1,String AnswerChoice2, String AnswerChoice3, String AnswerChoice4,
                               int randomCorrectButton, int questionNumber, Random rand) {
        if(AnswerChoice1 == AnswerChoice2 || AnswerChoice1 == AnswerChoice3 || AnswerChoice1 ==
                AnswerChoice4 || AnswerChoice2 == AnswerChoice3 || AnswerChoice2 == AnswerChoice4 || AnswerChoice3 == AnswerChoice4) {
            randomAnswerButton1(randomCorrectButton, questionNumber, rand);
            randomAnswerButton2(randomCorrectButton, questionNumber, rand);
            randomAnswerButton3(randomCorrectButton, questionNumber, rand);
        }
    }

    public String randomAnswerButton1(int randomCorrectButton, int questionNumber, Random rand) {
        if (randomCorrectButton != 1) {
            int answernum = rand.nextInt(19) + 1;
            if (answernum != questionNumber)
                AnswerPeople(answernum);
            if (answer == null) {
                AnswerNumbers(answernum);
            }

        }
        String AnswerChoice1 = answer;
        return AnswerChoice1;
    }

    public String randomAnswerButton2(int randomCorrectButton, int questionNumber, Random rand) {
        if (randomCorrectButton != 2) {
            int answernum2 = rand.nextInt(19) + 1;
            if (answernum2 != questionNumber)
                AnswerPeople(answernum2);
            if (answer == null) {
                AnswerNumbers(answernum2);
            }
        }
        String AnswerChoice2 = answer;
        return AnswerChoice2;
    }

    public String randomAnswerButton3(int randomCorrectButton, int questionNumber, Random rand) {

        if (randomCorrectButton != 3) {
            int answernum3 = rand.nextInt(19) + 1;
            if (answernum3 != questionNumber)
                AnswerPeople(answernum3);
            if (answer == null) {
                AnswerNumbers(answernum3);
            }
        }
        String AnswerChoice3 = answer;
        return AnswerChoice3;

    }

    public String randomAnswerButton4(int randomCorrectButton, int questionNumber, Random rand) {
        if (randomCorrectButton != 4) {
            int answernum4 = rand.nextInt(19) + 1;
            if (answernum4 != questionNumber)
                AnswerPeople(answernum4);
            if (answer == null) {
                AnswerNumbers(answernum4);
            }

        }
        String AnswerChoice4 = answer;
        return AnswerChoice4;
    }
</code>```

答:
Is there a problem with an intents

Yes. There is only ever one Activity active at a time, so this doesn't make sense.

```<code>startActivity(numbers);
...
startActivity(numbertoAnswer);
</code>```

I ended up just trying to call the methods from the class in the question class which caused an error

This code?

```<code>Answers answers = new Answers();
answers.createQuestions();
answers.buttonTextGetter();
</code>```

Right... It probably error because findViewById has no Context because you called new on an Activity (Hint: don't do that).

You probably made Answers extends Activity so that you could call findViewById, which won't work the way you expected, probably.

Plus there is no onCreate that you implemented, so there is no views to find anyway.

the Answers class does not run

It's not really clear what the Answers class is supposed to do, but I don't think you need a separate Activity to hold 4 buttons and calculate the result.

You can put the question and the possible answers in one layout, in one activity. Start with that before you make anything more complex with additional classes.

There is no general solution here, unfortunately. It comes down to learning how to better organize your code.

Possible suggested reading: Activities are not UI elements

Title: Calling a class through an Intent

Body:
Main method button onClick:

public void onClick(View v) {
                Intent numbers = new Intent(MainActivity.this, Questions.class);
                numbers.putExtra("randomNumber", rand);
                startActivity(numbers);
                Intent numbertoAnswer = new Intent(MainActivity.this, Answers.class);
                numbertoAnswer.putExtra("randomnumber", rand);
                startActivity(numbertoAnswer);
            }
        });

After this code runs the question class onCreate is fine, but the Answers class does not run.  I used the same button to call intents to both.  I ended up just trying to call the methods from the class in the question class which caused an error.  Is there a problem with an intents or is there a problem with the code in the Answers class?

Question

    protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.game_view);
            int questionNumber = getIntent().getIntExtra("randomNumber", 1);
            question(questionNumber);

            TextView questiontv = (TextView) findViewById(R.id.Question);
            questiontv.setText(question(questionNumber));

            Answers answers = new Answers();
            answers.createQuestions();
            answers.buttonTextGetter();
}

Answers:

public class Answers extends Activity {

    Button choice1 = (Button) findViewById(R.id.answer_choice1);
    Button choice2 = (Button) findViewById(R.id.answer_choice2);
    Button choice3 = (Button) findViewById(R.id.answer_choice3);
    Button choice4 = (Button) findViewById(R.id.answer_choice4);
    int questionNumber = getIntent().getIntExtra("randomnumber", 1);
    Random rand = new Random();
    int randomCorrectButton = rand.nextInt(3) + 1;

    public void createQuestions() {

        AnswerPeople(questionNumber);
        if (answer == null) {
            AnswerNumbers(questionNumber);
        }
        switch (randomCorrectButton) {
            case 1:
                choice1.setText(answer);
                break;
            case 2:
                choice2.setText(answer);
                break;
            case 3:
                choice3.setText(answer);
                break;
            case 4:
                choice4.setText(answer);
                break;
        }
    }
        String AnswerChoice1 = randomAnswerButton1(randomCorrectButton, questionNumber, rand);
        String AnswerChoice2 = randomAnswerButton2(randomCorrectButton, questionNumber, rand);
        String AnswerChoice3 = randomAnswerButton3(randomCorrectButton, questionNumber, rand);
        String AnswerChoice4 = randomAnswerButton4(randomCorrectButton, questionNumber, rand);

        public void buttonTextGetter(){

        randomAnswerButton1(randomCorrectButton, questionNumber, rand);
        randomAnswerButton2(randomCorrectButton, questionNumber, rand);
        randomAnswerButton3(randomCorrectButton, questionNumber, rand);
        randomAnswerButton4(randomCorrectButton, questionNumber, rand);

        checkForRepeat(AnswerChoice1, AnswerChoice2, AnswerChoice3, AnswerChoice4, randomCorrectButton, questionNumber, rand);

        if (randomCorrectButton != 1) {
            choice1.setText(AnswerChoice1);
        } else if (randomCorrectButton != 2) {
            choice2.setText(AnswerChoice2);
        } else if (randomCorrectButton != 3) {
            choice3.setText(AnswerChoice3);
        } else if (randomCorrectButton != 4) {
            choice4.setText(AnswerChoice4);
        }
        }

    public void checkForRepeat(String AnswerChoice1,String AnswerChoice2, String AnswerChoice3, String AnswerChoice4,
                               int randomCorrectButton, int questionNumber, Random rand) {
        if(AnswerChoice1 == AnswerChoice2 || AnswerChoice1 == AnswerChoice3 || AnswerChoice1 ==
                AnswerChoice4 || AnswerChoice2 == AnswerChoice3 || AnswerChoice2 == AnswerChoice4 || AnswerChoice3 == AnswerChoice4) {
            randomAnswerButton1(randomCorrectButton, questionNumber, rand);
            randomAnswerButton2(randomCorrectButton, questionNumber, rand);
            randomAnswerButton3(randomCorrectButton, questionNumber, rand);
        }
    }

    public String randomAnswerButton1(int randomCorrectButton, int questionNumber, Random rand) {
        if (randomCorrectButton != 1) {
            int answernum = rand.nextInt(19) + 1;
            if (answernum != questionNumber)
                AnswerPeople(answernum);
            if (answer == null) {
                AnswerNumbers(answernum);
            }

        }
        String AnswerChoice1 = answer;
        return AnswerChoice1;
    }

    public String randomAnswerButton2(int randomCorrectButton, int questionNumber, Random rand) {
        if (randomCorrectButton != 2) {
            int answernum2 = rand.nextInt(19) + 1;
            if (answernum2 != questionNumber)
                AnswerPeople(answernum2);
            if (answer == null) {
                AnswerNumbers(answernum2);
            }
        }
        String AnswerChoice2 = answer;
        return AnswerChoice2;
    }

    public String randomAnswerButton3(int randomCorrectButton, int questionNumber, Random rand) {

        if (randomCorrectButton != 3) {
            int answernum3 = rand.nextInt(19) + 1;
            if (answernum3 != questionNumber)
                AnswerPeople(answernum3);
            if (answer == null) {
                AnswerNumbers(answernum3);
            }
        }
        String AnswerChoice3 = answer;
        return AnswerChoice3;

    }

    public String randomAnswerButton4(int randomCorrectButton, int questionNumber, Random rand) {
        if (randomCorrectButton != 4) {
            int answernum4 = rand.nextInt(19) + 1;
            if (answernum4 != questionNumber)
                AnswerPeople(answernum4);
            if (answer == null) {
                AnswerNumbers(answernum4);
            }

        }
        String AnswerChoice4 = answer;
        return AnswerChoice4;
    }

Body:
Is there a problem with an intents

Yes. There is only ever one Activity active at a time, so this doesn't make sense.

startActivity(numbers);
...
startActivity(numbertoAnswer);

I ended up just trying to call the methods from the class in the question class which caused an error

This code?

Answers answers = new Answers();
answers.createQuestions();
answers.buttonTextGetter();

Right... It probably error because findViewById has no Context because you called new on an Activity (Hint: don't do that).

You probably made Answers extends Activity so that you could call findViewById, which won't work the way you expected, probably.

Plus there is no onCreate that you implemented, so there is no views to find anyway.

the Answers class does not run

It's not really clear what the Answers class is supposed to do, but I don't think you need a separate Activity to hold 4 buttons and calculate the result.

You can put the question and the possible answers in one layout, in one activity. Start with that before you make anything more complex with additional classes.

There is no general solution here, unfortunately. It comes down to learning how to better organize your code.

Possible suggested reading: Activities are not UI elements


问:
How do I run shell commands from Swift 3 (Xcode 8) using Interface Builder?
First time using Xcode, typically I stick to AppleScript for simple applications but I'm looking to branch out and make use of a GUI.

I want to be able to execute the system "zip" command from Swift (3) in Xcode 8 with some arguments with a button press.

The code I have below when run produces the following error:

zip error: Nothing to do! ( -r -j ~/Desktop/SystemLogs/iLog.zip ~/Library/Logs/iLog -x *.DS_Store)

What am I doing wrong in trying to run this shell command from swift? Any assistance is appreciated.

```<code>@IBAction func gButton(_ sender: NSButtonCell) {

    let zip1 = Process()
    zip1.launchPath = "/usr/bin/zip"
    zip1.arguments = [" -r -j ~/Desktop/SystemLogs/Logs.zip ~/Library/Logs -x *.DS_Store"]
    zip1.launch()

    sender.isEnabled = false

    zip1.waitUntilExit()

    sender.isEnabled = true
}
</code>```

答:
You are trying to pass a shell command line to zip. It is the shell's job to break a command line into individual arguments, handle pathname expansion, setup I/O redirection, etc., etc. The actual command invoked, zip in your case, is passed an array of the individual arguments after the shell has done its job, any I/O redirection is setup, etc.

You either need to pass an array of the individual arguments, e.g. @[ @"-r", @"-j", ... ] and handle the pathname expansion yourself or you can instead invoke the shell itself and have it do all that work for you. Look up the manual page for the shell you wish to use (bash, tcsh, etc.) and you'll find it has an option, probably -c, which takes a complete command line as a single parameter and parses and executes it.

HTH

Body:
First time using Xcode, typically I stick to AppleScript for simple applications but I'm looking to branch out and make use of a GUI.

I want to be able to execute the system "zip" command from Swift (3) in Xcode 8 with some arguments with a button press.

The code I have below when run produces the following error:

zip error: Nothing to do! ( -r -j ~/Desktop/SystemLogs/iLog.zip ~/Library/Logs/iLog -x *.DS_Store)

What am I doing wrong in trying to run this shell command from swift? Any assistance is appreciated.

@IBAction func gButton(_ sender: NSButtonCell) {

    let zip1 = Process()
    zip1.launchPath = "/usr/bin/zip"
    zip1.arguments = [" -r -j ~/Desktop/SystemLogs/Logs.zip ~/Library/Logs -x *.DS_Store"]
    zip1.launch()

    sender.isEnabled = false

    zip1.waitUntilExit()

    sender.isEnabled = true
}


问:
Order of calling constructors
```<code>class Program
{
    static void Main(string[] args)
    {
        Foo.Calc("Foo");
    }
}

public abstract class Base
{
    protected static Func<string, int> CalcFunction;

    public static void Calc(string str)
    {
        Console.WriteLine(CalcFunction(str));
    }
}

public class Foo : Base
{
    static Foo()
    {
        CalcFunction = s => { return s.Length; };
    }
}
</code>```

When I try to call Foo.Calc("Foo"); I have exception "Object reference not set to an instance of an object."
because static constructor of Foo was not called and CalcFunction is null. I don't want to use Init method for Foo class and call it before calling Calc().

Can I change order of calling constructors?

答:
It seems you've misunderstood the use of static and abstract keywords. Having an abstract class with only static members makes almost no sense. Are you sure this isn't closer to what you were trying:</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo()
        foo.Calc("Foo");
    }
}

public abstract class Base
{
    protected Func<string, int> CalcFunction;

    public void Calc(string str)
    {
        Console.WriteLine(CalcFunction(str));
    }
}

public class Foo : Base
{
    public Foo()
    {
        this.CalcFunction = s => { return s.Length; };
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Order of calling constructors

Body:
class Program
{
    static void Main(string[] args)
    {
        Foo.Calc("Foo");
    }
}

public abstract class Base
{
    protected static Func<string, int> CalcFunction;

    public static void Calc(string str)
    {
        Console.WriteLine(CalcFunction(str));
    }
}

public class Foo : Base
{
    static Foo()
    {
        CalcFunction = s => { return s.Length; };
    }
}

When I try to call Foo.Calc("Foo"); I have exception "Object reference not set to an instance of an object."
because static constructor of Foo was not called and CalcFunction is null. I don't want to use Init method for Foo class and call it before calling Calc().

Can I change order of calling constructors?

Body:
It seems you've misunderstood the use of static and abstract keywords. Having an abstract class with only static members makes almost no sense. Are you sure this isn't closer to what you were trying:

class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo()
        foo.Calc("Foo");
    }
}

public abstract class Base
{
    protected Func<string, int> CalcFunction;

    public void Calc(string str)
    {
        Console.WriteLine(CalcFunction(str));
    }
}

public class Foo : Base
{
    public Foo()
    {
        this.CalcFunction = s => { return s.Length; };
    }
}


问:
How to solve import error for pandas?
I installed Anaconda with python 2.7.7.
 However, whenever I run "import pandas" I get the error:
 "ImportError: C extension: y not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace' to build the C extensions first."
I tried running the suggested command but it stated that

```<code>skipping 'pandas\index.c' Cython extension (up-to-date)
skipping 'pandas\src\period.c' Cython extension (up-to-date)
skipping 'pandas\algos.c' Cython extension (up-to-date)
skipping 'pandas\lib.c' Cython extension (up-to-date)
skipping 'pandas\tslib.c' Cython extension (up-to-date)
skipping 'pandas\parser.c' Cython extension (up-to-date)
skipping 'pandas\hashtable.c' Cython extension (up-to-date)
skipping 'pandas\src\sparse.c' Cython extension (up-to-date)
skipping 'pandas\src\testing.c' Cython extension (up-to-date)
skipping 'pandas\msgpack.cpp' Cython extension (up-to-date)
</code>```

Has anyone encountered this before and found a solution?

答:
Instead of installing it with conda or pip, try to install it with your package manager:

sudo apt-get install python3-pandas

Title: How to solve import error for pandas?

Body:
I installed Anaconda with python 2.7.7.
 However, whenever I run "import pandas" I get the error:
 "ImportError: C extension: y not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace' to build the C extensions first."
I tried running the suggested command but it stated that

skipping 'pandas\index.c' Cython extension (up-to-date)
skipping 'pandas\src\period.c' Cython extension (up-to-date)
skipping 'pandas\algos.c' Cython extension (up-to-date)
skipping 'pandas\lib.c' Cython extension (up-to-date)
skipping 'pandas\tslib.c' Cython extension (up-to-date)
skipping 'pandas\parser.c' Cython extension (up-to-date)
skipping 'pandas\hashtable.c' Cython extension (up-to-date)
skipping 'pandas\src\sparse.c' Cython extension (up-to-date)
skipping 'pandas\src\testing.c' Cython extension (up-to-date)
skipping 'pandas\msgpack.cpp' Cython extension (up-to-date)

Has anyone encountered this before and found a solution?


问:
Return distinct matching and non-matching rows (outer join?)
I know I've done this in the past and I can't think of the solution now... I know it's some sort of full outer join.

I've got 3 tables:

```<code>ACTIVITIES
id   name
---+-------------
1  |  Basketball
2  |  Chess Club

ENROLLMENT
id   activity_id   person_id
---+-------------+-----------
1  | 1           | 1
2  | 1           | 2
3  | 2           | 1

ATTENDANCE
id   date         person_id   activity_id
---+-------------+----------+---------------
1  | 2017-01-01  | 1        | 1
2  | 2017-01-01  | 2        | 1
3  | 2017-01-02  | 1        | 1
</code>```

I'm trying to get attendance by person_id, even when that id doesn't exist for a date:

```<code>date          person_id
------------+---------------
2017-01-01  | 1
2017-01-02  | null
</code>```

Here's something close to what I think I'll need...

```<code>select date, attendance.person_id
from enrollment
**SOME SORT OF JOIN** attendance on enrollment.person_id = attendance.person_id
where person_id = 1
</code>```

But all I can get returned is:

```<code>date          person_id
------------+---------------
2017-01-01  | 1
2017-01-01  | 1
</code>```

...where the number of rows is correct but the values are wrong.

答:
This would seem to result in the results you want:</p>

```<code>select date,
       max(case when person_id = 1 then person_id end) as person_id
from attendance a
group by date
order by date;
</code>```

Body:
I know I've done this in the past and I can't think of the solution now... I know it's some sort of full outer join.

I've got 3 tables:

ACTIVITIES
id   name
---+-------------
1  |  Basketball
2  |  Chess Club

ENROLLMENT
id   activity_id   person_id
---+-------------+-----------
1  | 1           | 1
2  | 1           | 2
3  | 2           | 1

ATTENDANCE
id   date         person_id   activity_id
---+-------------+----------+---------------
1  | 2017-01-01  | 1        | 1
2  | 2017-01-01  | 2        | 1
3  | 2017-01-02  | 1        | 1

I'm trying to get attendance by person_id, even when that id doesn't exist for a date:

date          person_id
------------+---------------
2017-01-01  | 1
2017-01-02  | null

Here's something close to what I think I'll need...

select date, attendance.person_id
from enrollment
**SOME SORT OF JOIN** attendance on enrollment.person_id = attendance.person_id
where person_id = 1

But all I can get returned is:

date          person_id
------------+---------------
2017-01-01  | 1
2017-01-01  | 1

...where the number of rows is correct but the values are wrong.

Body:
This would seem to result in the results you want:

select date,
       max(case when person_id = 1 then person_id end) as person_id
from attendance a
group by date
order by date;


问:
How can I host a create a simple login portal that can be accessed by different users over a same local network?
I'm planning to make an Instagram for web for my school project, but i don't know how to give access to a page from the server to multiple users. Make note that all these things are happening offline and the webpage will be accessed to all those users who are connected to my local hotspot (or the computer hotspot on which I'm going to host the server).I don't know a thing about how to connect two users. please help.
Thanks</p>

答:
this steps are for XAMPP over the same local network:

Get your internal IP or static ip  (ipv4, example: 192.168.1.106).

Open XAMPP>apache>conf>httpd.conf file

Find the line  #Listen 12.34.56.78:80 or #Listen 0.0.0.0:80

Change the IP address in that line and replace it with the static IP (192.168.1.106)

Save the httpd.conf file ensuring that the server is pointed to #Listen
192.168.1.106:80

to connect from another pc just write http://192.168.1.106/myapp

hope it helps.


问:
Trying to call callback after S3.putobject
kinda new to aws and javascript and i am trying to achieve the following, uploading a photo using binary support and on my return value adding status paramater to be later used in API Gateway

```<code>var params = {
  Key: key,
  Body: image,
};
this.s3.putObject(params, function(err, data) {
  if (!err) {
    callback(null,{newValue: "This is my test value"});
  }
});
</code>```

the code works fine if I comment out the callback line, but crashes otherwise.
 Any tips on how to fix it will be greatly appreciated

答:
The call structure should be as mentioned over here

```<code>putObject(params = {}, callback)
</code>```

Your code can be:

```<code>var params = {
  Key: key,
  Body: image,
};
var newValue = ""
this.s3.putObject(params, function(err, data) {
    if (!err) {
        this.newValue = "This is my test value";
    }
});
</code>```

Here 'function(err, data) {}' represents 'callback'

Body:
kinda new to aws and javascript and i am trying to achieve the following, uploading a photo using binary support and on my return value adding status paramater to be later used in API Gateway

var params = {
  Key: key,
  Body: image,
};
this.s3.putObject(params, function(err, data) {
  if (!err) {
    callback(null,{newValue: "This is my test value"});
  }
});

the code works fine if I comment out the callback line, but crashes otherwise.
 Any tips on how to fix it will be greatly appreciated

Body:
The call structure should be as mentioned over here

putObject(params = {}, callback)

Your code can be:

var params = {
  Key: key,
  Body: image,
};
var newValue = ""
this.s3.putObject(params, function(err, data) {
    if (!err) {
        this.newValue = "This is my test value";
    }
});

Here 'function(err, data) {}' represents 'callback'


问:
using ESI slower than EAX?
This piece of asm is much slower than the corresponding piece using the eax register. Why is that?

```<code>jmp .l2
.l1:

   dec ESI
.l2:
   cmp ESI, 0
   jne .l1
</code>```

```<code>jmp .l2
.l1:

   dec EAX
.l2:
   cmp EAX, 0
   jne .l1
</code>```

答:
Performance will depend on what EAX and ESI are being used for, before and after this piece of code runs. Depending on the architecture, the CPU can parallelise instructions that operate on different registers; code that operates on the same register must block.

(I don't have any more specific advice other than to trust the compiler: it knows the right way to allocate registers to take advantage of parallelism, and I don't.)

Title: using ESI slower than EAX?

Body:
This piece of asm is much slower than the corresponding piece using the eax register. Why is that?

jmp .l2
.l1:

   dec ESI
.l2:
   cmp ESI, 0
   jne .l1

jmp .l2
.l1:

   dec EAX
.l2:
   cmp EAX, 0
   jne .l1


问:
replacing list items that fit condition in lambda
I've been stuck on a line of my code for a while, and I'm at a loss as to why it returns as it does.

```<code>guess = 'a'
word = ['a', 'b', 'c']
board = ['_', '_', '_']
board = list(map(lambda x: guess if word[board.index(x)] == guess else x, board))

print(board)
</code>```

This returns

```<code>['a', 'a', 'a']
</code>```

Whereas my goal is a return of

```<code>['a', '_', '_']
</code>```

My previous solution was to loop through the list with an increasing value for the index, and to individually check each entry in word against the guess, and to replace the board list at the same index, but I feel that there is a more concise and pythonic way using lambda, I just can't quite get it.

答:
You can use list comprehension as mentioned in the answers, but in your code board will always reset with every guess. I'm guessing you want to keep track of the guesses till all letters are guessed (or till number of guesses) so your loop should have a temporary list and then loop through board to add the new guesses(if found) something like:

```<code>word = ['a', 'b', 'c']
board = ['_', '_', '_']
tries = 0
while tries != 3:
    guess = raw_input("Enter a guess: ")
    tmp = [x if x == guess else '_' for x in word]
    for i in xrange(len(board)):
        if board[i] == '_':
            try:
                board[i] = tmp[i]
            except IndexError:
                pass
    print(board)
    if '_' not in board:
        print('Solved!')
        break
    tries += 1
    if tries == 3:
        print('Not solved!')
</code>```

Body:
I've been stuck on a line of my code for a while, and I'm at a loss as to why it returns as it does.

guess = 'a'
word = ['a', 'b', 'c']
board = ['_', '_', '_']
board = list(map(lambda x: guess if word[board.index(x)] == guess else x, board))

print(board)

This returns

['a', 'a', 'a']

Whereas my goal is a return of

['a', '_', '_']

My previous solution was to loop through the list with an increasing value for the index, and to individually check each entry in word against the guess, and to replace the board list at the same index, but I feel that there is a more concise and pythonic way using lambda, I just can't quite get it.

Body:
You can use list comprehension as mentioned in the answers, but in your code board will always reset with every guess. I'm guessing you want to keep track of the guesses till all letters are guessed (or till number of guesses) so your loop should have a temporary list and then loop through board to add the new guesses(if found) something like:

word = ['a', 'b', 'c']
board = ['_', '_', '_']
tries = 0
while tries != 3:
    guess = raw_input("Enter a guess: ")
    tmp = [x if x == guess else '_' for x in word]
    for i in xrange(len(board)):
        if board[i] == '_':
            try:
                board[i] = tmp[i]
            except IndexError:
                pass
    print(board)
    if '_' not in board:
        print('Solved!')
        break
    tries += 1
    if tries == 3:
        print('Not solved!')


问:
H2O modelling: stand-alone k-means or regression code
I am very new to H2O and to running models on hives. The reason I am considering H2O at this moment is that my understanding is that H2O helps to optimize data parsing during various modelling processes (such as k-means or logistic regression). My question is: is there a way for me to write my python (or R) k-means code and run it in H2O or the only way would be using the H2O pre-built process? If it's the later, then can I extract the final scoring code in order to schedule it for automated run for a regular scoring?
And if the first option is also possible ( I noticed the option 'import the code"), how would the parsing happen during the process (for instance, during data preparation, variable standardization, actual k-means scoring code, assigning the final segment rules)?

Thank you

Natalie

答:
You will need to use the H2OKMeansEstimator method in Python (or h2o.kmeans() function in R) -- there is no way to "import" your own K-means code into H2O, which I think is what you're asking.  There is more info about H2O's K-means implementation here.

To export an H2O K-means model for use (scoring) in a production environment, you can export the model as a POJO or MOJO (pure Java code with no dependencies), or you can save a binary H2O model which will require to have an H2O cluster running at scoring-time.


问:
org.apache.kafka.common.config.ConfigException: Missing required configuration "bootstrap.servers" which has no default value
I'm getting this error when running my producer class in Eclipse:
org.apache.kafka.common.config.ConfigException: Missing required configuration "bootstrap.servers" which has no default value

Here is my producer class:

```<code>public class SimpleProducer {

  public static void main(String[] args) throws Exception {

    try {
        String topicName = "mytopic";
        String key = "key1";
        String value = "Value-1";

        Properties prop = new Properties();
        prop.put("bootstrap.server","localhost:9092");
        prop.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
        prop.put("value.serializer","org.apache.kafka.cpmmon.serialization.StringSerializer");

        Producer<String, String> producer = new KafkaProducer<>(prop);

        ProducerRecord<String, String> record = new ProducerRecord<>(topicName,key,value);
        producer.send(record);
        producer.close();
        System.out.println("SimpleProducer Completed.");
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
}
</code>```

Any pointers on how to fix it?

答:
Just change the

prop.put("bootstrap.server","localhost:9092");

to

prop.put("bootstrap.servers","localhost:9092");

And in your code

```<code>prop.put("value.serializer",
         "org.apache.kafka.cpmmon.serialization.StringSerializer");
</code>```

the common is not spelled correctly, the right package is

org.apache.kafka.common.serialization.StringSerializer

Body:
I'm getting this error when running my producer class in Eclipse:
org.apache.kafka.common.config.ConfigException: Missing required configuration "bootstrap.servers" which has no default value

Here is my producer class:

public class SimpleProducer {

  public static void main(String[] args) throws Exception {

    try {
        String topicName = "mytopic";
        String key = "key1";
        String value = "Value-1";

        Properties prop = new Properties();
        prop.put("bootstrap.server","localhost:9092");
        prop.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
        prop.put("value.serializer","org.apache.kafka.cpmmon.serialization.StringSerializer");

        Producer<String, String> producer = new KafkaProducer<>(prop);

        ProducerRecord<String, String> record = new ProducerRecord<>(topicName,key,value);
        producer.send(record);
        producer.close();
        System.out.println("SimpleProducer Completed.");
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
}

Any pointers on how to fix it?

Body:
Just change the

prop.put("bootstrap.server","localhost:9092");

to

prop.put("bootstrap.servers","localhost:9092");

And in your code

prop.put("value.serializer",
         "org.apache.kafka.cpmmon.serialization.StringSerializer");

the common is not spelled correctly, the right package is

org.apache.kafka.common.serialization.StringSerializer

ContentLicense: CC BY-SA 4.0


问:
replace a variable's value if it contains a certain string
I have a variable called diagnosis and I want to replace everything that contains the word "pneumonia" with just "pneumonia"

I tried this:

```<code>replace diagnosis = "Pneumonia" if regexm (diagnosis, "pneumonia")
</code>```

But I got an error: unrecognized command: regexm

I have Stata/IC version 12.1 for Windows.

答:
Another approach.</p>

```<code>. clonevar newdiag = diag

. replace newdiag = "pneumonia" if strpos(strlower(diag),"pneumonia")>0
(3 real changes made)

. list, clean noobs

                   diag     newdiag
              pneumonia   pneumonia
              Pneumonia   pneumonia
    Bronchial pneumonia   pneumonia
      Flu and pneumonia   pneumonia
                earache     earache
</code>```

Body:
I have a variable called diagnosis and I want to replace everything that contains the word "pneumonia" with just "pneumonia"

I tried this:

replace diagnosis = "Pneumonia" if regexm (diagnosis, "pneumonia")

But I got an error: unrecognized command: regexm

I have Stata/IC version 12.1 for Windows.

Body:
Another approach.

. clonevar newdiag = diag

. replace newdiag = "pneumonia" if strpos(strlower(diag),"pneumonia")>0
(3 real changes made)

. list, clean noobs

                   diag     newdiag
              pneumonia   pneumonia
              Pneumonia   pneumonia
    Bronchial pneumonia   pneumonia
      Flu and pneumonia   pneumonia
                earache     earache


问:
How does the GSM stack uses the SIM card on android?
I would like to know how the SIM card is used in the Android stack. I am not extremely familiar with the rest of the operating system or the network protocols, therefore I would be glad to have an explanation as detailed as possible. Don't hesitate to give some links to the kernel code, documentation, RFCs and interface specification from telecommunication networks (I have skimmed over  ETSI TS 131 102 and TS 121 111).

If applicable, I am more interested in the standards used in Europe (especially the network authentication part).

As for the reason why I need this information; my android smartphone's SIM card reader is broken, and I do not see a reason why I couldn't use an external one. The ideal solution would be to copy the credentials stored in the SIM card and use them with some software on the Android side, but I would expect them to contain (at least for recent ones) strong, not externally readable cryptographic secrets. Another solution would be to build an external SIM card reader linked to the phone, to perform the authentication on the network (only this part, if possible; but it could also be necessary to perform this when roaming from cell to cell, for example).

Ideally, I would use an external USB card reader, but I am not sure it is possible, at least by default.

This question may sound like it doesn't belong to SO, but I believe it is a programming question, since the answer will determine where the solution will plug in.

答: there is no "gsm stack" nor in android nor in linux. android uses the tty based (AT commands) access to the GSM modem which is external (to the kernel) device. the only way is to fix/replace the SIM connector or use the gsm usb dongle. there are exist the GSM modems with virtual "software" SIM's but I'd not heard any of such used with android.</p>


问:
Display app theme immediately in Flutter app
Given the asynchronous nature of the Flutter shared_prefs plugin, how could one make sure that when an app is launched the correct theme settings are immediately displayed? I.e. no flash of the default theme followed by applying the correct theme once the shared_prefs have finished loading.</p>

答:
One way would be to delay the display of your main app with a loading screen.  A pattern I've seen is:

```<code>main() async {
  runApp(new LoadingScreen());
  runApp(new App(await asyncStuff()));
}
</code>```

You can call runApp as often as you like: https://api.flutter.dev/flutter/widgets/runApp.html

Body:
One way would be to delay the display of your main app with a loading screen.  A pattern I've seen is:

main() async {
  runApp(new LoadingScreen());
  runApp(new App(await asyncStuff()));
}

You can call runApp as often as you like: https://api.flutter.dev/flutter/widgets/runApp.html


问:
malloc() with heap overflow explanation
I have the following code:

```<code>int main(int argc, char *argv[]) {

    int bufferSize = 8;
    //Setting the buffer size here, which can cause a heap overflow
    char *argsStr = malloc(bufferSize);
    char *anotherStr = malloc(bufferSize);

    //If argv[1] is greater than the buffer size, we will have an overflow
    strcpy(argsStr, argv[1]);

    printf("String 1: %s String 2: %s", argsStr, anotherStr);

}
</code>```

I want to cause a heap overflow, so I import the param 'testtesttesttesttesttesttesttesttest'.

I would expect, since argsStr is only of size 8, it would be 'testtest' and the rest would overflow into anotherStr (for 8 bytes), but instead I see:

so argsStr is 'testtesttesttesttesttesttesttesttest' and anotherStr is 'testtesttesttesttest'

Why is this? Am I missing something with heap overflows or malloc()?

答:
printf() doesn't know or care how much memory you allocated for the buffers. When it's printing a string with %s format, it keeps printing until it reaches the terminating zero byte. So when it's printing argsStr, it prints the entire thing, even though it overflows the 8 bytes that were allocated. This is why buffer overflows are a problem -- C pointers don't include any information about how much memory is allocated, so you can easily access memory outside the allocated space if you don't check your lengths correctly.

The memory for anotherStr was apparently allocated 16 bytes after the memory for argsStr. So when you printed that, it started from the location of argsStr[16], and printed the last 20 bytes of that string.

This is all undefined behavior, of course, so you can't depend on any specific result.

Title: malloc() with heap overflow explanation

Body:
I have the following code:

int main(int argc, char *argv[]) {

    int bufferSize = 8;
    //Setting the buffer size here, which can cause a heap overflow
    char *argsStr = malloc(bufferSize);
    char *anotherStr = malloc(bufferSize);

    //If argv[1] is greater than the buffer size, we will have an overflow
    strcpy(argsStr, argv[1]);

    printf("String 1: %s String 2: %s", argsStr, anotherStr);

}

I want to cause a heap overflow, so I import the param 'testtesttesttesttesttesttesttesttest'.

I would expect, since argsStr is only of size 8, it would be 'testtest' and the rest would overflow into anotherStr (for 8 bytes), but instead I see:

so argsStr is 'testtesttesttesttesttesttesttesttest' and anotherStr is 'testtesttesttesttest'

Why is this? Am I missing something with heap overflows or malloc()?


答: It says that your second element in the comparison, @fluent_user_ids, is nil. Which is true as your array is named @fluent_users_ids. So it's just a typo, we have all been there !

Title: Find all the id numbers in both arrays

Body:
I am trying to find all the times the same ID is in both arrays, using the & comparison. When I output the arrays, you can see that there are matches, but when I try to run through them, it throws the error no implicit conversion of nil into Array.

> @fluent_user_ids
 => [2, 4, 5, 5, 6, 9, 8, 8, 7, 7, 12, 165, 166, 171, 174, 176, 177, 142, 206, 207, 208, 209, 214, 215, 216, 10, 229, 230, 232, 234, 236, 237, 238, 233, 233, 240, 241, 242, 243, 244, 250, 251, 252, 253, 254, 255, 256, 257, 258, 260, 261, 262, 264, 265, 266, 267, 268, 269, 270, 273, 274, 276, 233]

 > @nonfluent_user_ids
 => [2, 5, 11, 166, 142, 13, 206, 207, 208, 209, 214, 215, 216, 171, 10, 229, 230, 231, 232, 234, 236, 237, 238, 233, 239, 240, 241, 242, 243, 244, 250, 251, 252, 253, 254, 255, 256, 257, 258, 260, 261, 262, 264, 265, 266, 267, 268, 269, 270, 273, 274, 276]

> @nonfluent_user_ids & @fluent_users_ids

TypeError: no implicit conversion of nil into Array
    from (irb):27:in `&'

Why isn't this working? Thanks in advance!


问:
split a string using javascript
I have a string like ";a;b;c;;e". Notice that there is an extra semicolon before e. I want the string to be split in a, b, c;, e. But it gets split like a, b, c, ;e.

My code is

```<code>var new_arr = str.split(';');
</code>```

What can I do over here to get the result I want?

Regards

答:
Use a Regexp negative lookahead:</p>

```<code>  ";a;b;c;;e".split(/;(?!;)/)
</code>```

Title: split a string using javascript

Body:
I have a string like ";a;b;c;;e". Notice that there is an extra semicolon before e. I want the string to be split in a, b, c;, e. But it gets split like a, b, c, ;e.

My code is

var new_arr = str.split(';');

What can I do over here to get the result I want?

Regards

Body:
Use a Regexp negative lookahead:

  ";a;b;c;;e".split(/;(?!;)/)


问:
Printing tuple instead of three strings
I am trying to learn python, so I downloaded aptanaStudio3 and this happens.

Code:

```<code>print('One', 'Two', 'Three')
</code>```

Output:

```<code>('One', 'Two', 'Three')
</code>```

it should print just

```<code>One Two Three
</code>```

答:
If you want the python3 style print function in python2, you can use the following:

```<code>>>> from __future__ import print_function
>>> print('One', 'Two', 'Three', sep=' ')
One Two Three
</code>```

The sep keyword is the separator used between arguments and defaults to ' '.

By doing this, you can write print related code that will work in both python 2 and 3.

Title: Printing tuple instead of three strings

Body:
I am trying to learn python, so I downloaded aptanaStudio3 and this happens.

Code:

print('One', 'Two', 'Three')

Output:

('One', 'Two', 'Three')

it should print just

One Two Three

Body:
If you want the python3 style print function in python2, you can use the following:

>>> from __future__ import print_function
>>> print('One', 'Two', 'Three', sep=' ')
One Two Three

The sep keyword is the separator used between arguments and defaults to ' '.

By doing this, you can write print related code that will work in both python 2 and 3.


问:
Android Studio Expression Evaluation during debugging
I am new to Android Studio and was trying to get my hands on.

My question is: how can I see the value of any expression which needs to be evaulated?

For instance, in the code below, how can I see the value of Message.getText()?

```<code>    if (Message.getText() == null){
        Message.setError("Invalid Message");flag=true;
    }
</code>```

I have been using Eclipse with PyDev and there I had the option to evaluate any expression while debugging by using the print statement.

I was just wondering if there is any equivalent functionality in Android studio

答:
the option to evaluate any expression while debugging

Yes. You set a breakpoint and debug, then you can see what the expressions evaluate to

Body:
I am new to Android Studio and was trying to get my hands on.

My question is: how can I see the value of any expression which needs to be evaulated?

For instance, in the code below, how can I see the value of Message.getText()?

    if (Message.getText() == null){
        Message.setError("Invalid Message");flag=true;
    }

I have been using Eclipse with PyDev and there I had the option to evaluate any expression while debugging by using the print statement.

I was just wondering if there is any equivalent functionality in Android studio


问:
Printing dissasembly information in Cuda-gdb
I would like to print information from cuda disassembly.

I am able to print registers in cuda using info registers R1 for example however I am not able to figure out how to print  c[0x0][0x20] in  (MOV R1, c[0x0][0x20]) or deferenced [R13+0x9f]  in (STL.U8 [R13+0x9f], RZ)

答:
When using gdb or cuda-gdb you can use the disass command to disassemble the current code or code at a specific location.

```<code>cuda-gdb a.out
</code>```

debug the program

```<code>b main
</code>```

break in main

```<code>r
</code>```

run the program, when the breakpoint is hit

```<code> disass
</code>```

disassemble the following code at the breakpoint

Body:
When using gdb or cuda-gdb you can use the disass command to disassemble the current code or code at a specific location.

cuda-gdb a.out

debug the program

b main

break in main

r

run the program, when the breakpoint is hit

 disass

disassemble the following code at the breakpoint


问:
Mysql join 2 table with same column name without using an alias
I got this example, but I want to know in an overall way, how to fetch 2 column with the same name in MySQL without using an alias?

Example:

```<code> $query = "SELECT app.*, categorie.* FROM app JOIN categorie ON app.id = categorie.id";

 while ($row = mysql_fetch_array($query)) {
     $categorie = $row[categorie.name]; //is there a way to do this?
     $aplicativo = $row[app.name];
 }
</code>```

This example is simply solved with an alias, but is there another way, something like the example? Thank you for your time

答:
Disclaimer: mysql_fetch_array()
I understand this is not what should be recommended theese days, but I havent moved away as of yet since its still running great on any PHP 5.x server around where I'm from. Soon the time is there so I can refactor my codebase, maby even sooner for all I know. That being said...

Back to your question...

I was googling and looking for something else I see after reading, but I am beginning to understand that the entire approach of being able to read what you are asking for has no practical use in real world. That is, compared to changing your query adding some aliases like this:

$query = "SELECT app.name AS appname, categorie.name AS categoriename, app., categorie. FROM app JOIN categorie ON app.id = categorie.id";

This way your returned query returns more fields with unique names so you can access them like you ask for.

But say you were looking for a way to accomplish what you ask without changing your sql-query. You need to know the order of results, especially if there are more than one ambiguous name in the list as you will not be able to reorder the ambiguous fields, MySQL does return all your fields you see its just the way an array works you do not get the answers you want. Or, my disclaimer, this is one of the reasons I should move away from this MYSQL_FUNCTIONS... (I hope so because if so this is a damn great reason alone, mysql_fetch_assoc() should have an option to lay ouu an array of results as for this example would be ['id','name','id','name'])

You do not say anthing about your DB however say they both have two columns id and name for this example. Return results for each database would be id, name or in the case of your query it would be : id, name, id, name

How does this work? A resulted array from mysql_fetch_array() looks like this:

Say app db has values: 1, app name
Say category db has values: 2, category name

```<code>Array
(
    [0] => 1
    [id] => 2
    [1] => 'app name'
    [name] => 'category name'
    [2] => 2
    [3] => 'category name'
)
</code>```

So if you know the order of results you can atleast access the different fields even if they have the same name. However looking at the simple example above it would be hard to say if [2] is [id] or [name] but if you know the order...

Then again, select * and someone changes the database... adds a column...

Body:
I got this example, but I want to know in an overall way, how to fetch 2 column with the same name in MySQL without using an alias?

Example:

 $query = "SELECT app.*, categorie.* FROM app JOIN categorie ON app.id = categorie.id";

 while ($row = mysql_fetch_array($query)) {
     $categorie = $row[categorie.name]; //is there a way to do this?
     $aplicativo = $row[app.name];
 }

This example is simply solved with an alias, but is there another way, something like the example? Thank you for your time

Body:
Disclaimer: mysql_fetch_array()
I understand this is not what should be recommended theese days, but I havent moved away as of yet since its still running great on any PHP 5.x server around where I'm from. Soon the time is there so I can refactor my codebase, maby even sooner for all I know. That being said...

Back to your question...

I was googling and looking for something else I see after reading, but I am beginning to understand that the entire approach of being able to read what you are asking for has no practical use in real world. That is, compared to changing your query adding some aliases like this:

$query = "SELECT app.name AS appname, categorie.name AS categoriename, app., categorie. FROM app JOIN categorie ON app.id = categorie.id";

This way your returned query returns more fields with unique names so you can access them like you ask for.

But say you were looking for a way to accomplish what you ask without changing your sql-query. You need to know the order of results, especially if there are more than one ambiguous name in the list as you will not be able to reorder the ambiguous fields, MySQL does return all your fields you see its just the way an array works you do not get the answers you want. Or, my disclaimer, this is one of the reasons I should move away from this MYSQL_FUNCTIONS... (I hope so because if so this is a damn great reason alone, mysql_fetch_assoc() should have an option to lay ouu an array of results as for this example would be ['id','name','id','name'])

You do not say anthing about your DB however say they both have two columns id and name for this example. Return results for each database would be id, name or in the case of your query it would be : id, name, id, name

How does this work? A resulted array from mysql_fetch_array() looks like this:

Say app db has values: 1, app name
Say category db has values: 2, category name

Array
(
    [0] => 1
    [id] => 2
    [1] => 'app name'
    [name] => 'category name'
    [2] => 2
    [3] => 'category name'
)

So if you know the order of results you can atleast access the different fields even if they have the same name. However looking at the simple example above it would be hard to say if [2] is [id] or [name] but if you know the order...

Then again, select * and someone changes the database... adds a column...


问:
Mysql - duplicate entry error for key with auto increment
Why do I get an error of the form:

Error in query: Duplicate entry '10' for key 1

...when doing an INSERT statement like:

INSERT INTO wp_abk_period  (pricing_id, apartment_id)  VALUES (13, 27)

...with 13 and 27 being valid id-s for existing pricing and apartment rows, and the table is defined as:

```<code>CREATE TABLE `wp_abk_period` (
  `id` int(11) NOT NULL auto_increment,
  `apartment_id` int(11) NOT NULL,
  `pricing_id` int(11) NOT NULL,
  `type` enum('available','booked','unavailable') collate utf8_unicode_ci default NULL,
  `starts` datetime default NULL,
  `ends` datetime default NULL,
  `recur_type` enum('daily','weekly','monthly','yearly') collate utf8_unicode_ci default NULL,
  `recur_every` char(3) collate utf8_unicode_ci default NULL,
  `timedate_significance` char(4) collate utf8_unicode_ci default NULL,
  `check_in_times` varchar(255) collate utf8_unicode_ci default NULL,
  `check_out_times` varchar(255) collate utf8_unicode_ci default NULL,
  PRIMARY KEY  (`id`),
  KEY `fk_period_apartment1_idx` (`apartment_id`),
  KEY `fk_period_pricing1_idx` (`pricing_id`),
  CONSTRAINT `fk_period_apartment1` FOREIGN KEY (`apartment_id`) REFERENCES `wp_abk_apartment` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_period_pricing1` FOREIGN KEY (`pricing_id`) REFERENCES `wp_abk_pricing` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
</code>```

Isn't key 1 id in this case and having it on auto_increment sufficient for being able to not specify it?

Note: If I just provide an unused value for id, like INSERT INTO wp_abk_period  (id, pricing_id, apartment_id)  VALUES (3333333, 13, 27) it works fine, but then again, it is set as auto_increment so I shouldn't need to do this!

Note 2: OK, this is a complete "twilight zone" moment: so after running the query above with the huge number for id, things started working normally, no more duplicate entry errors. Can someone explain me WTF was MySQL doing to produce this weird behavior?

答:
Late to the party, but I just ran into this tonight - duplicate key '472817' and the provided answers didn't help.

On a whim I ran:

```<code>repair table wp_abk_period
</code>```

which output

```<code>Number of rows changed from 472816 to 472817
</code>```

Seems like mysql had the row count wrong, and the issue went away.

My environment:

```<code>mysql  Ver 14.14 Distrib 5.1.73, for Win64 (unknown)
</code>```

Create table syntax:

```
CREATE TABLE `env_events` (
  `tableId` int(11) NOT NULL AUTO_INCREMENT,
  `deviceId` varchar(50) DEFAULT NULL,
  `timestamp` int(11) DEFAULT NULL,
  `temperature` float DEFAULT NULL,
  `humidity` float DEFAULT NULL,
  `pressure` float DEFAULT NULL,
  `motion` int(11) DEFAULT NULL,
  PRIMARY KEY (`tableId`)
) ENGINE=MyISAM AUTO_INCREMENT=528521 DEFAULT CHARSET=latin1
```

Body:
Why do I get an error of the form:

Error in query: Duplicate entry '10' for key 1

...when doing an INSERT statement like:

INSERT INTO wp_abk_period  (pricing_id, apartment_id)  VALUES (13, 27)

...with 13 and 27 being valid id-s for existing pricing and apartment rows, and the table is defined as:

CREATE TABLE `wp_abk_period` (
  `id` int(11) NOT NULL auto_increment,
  `apartment_id` int(11) NOT NULL,
  `pricing_id` int(11) NOT NULL,
  `type` enum('available','booked','unavailable') collate utf8_unicode_ci default NULL,
  `starts` datetime default NULL,
  `ends` datetime default NULL,
  `recur_type` enum('daily','weekly','monthly','yearly') collate utf8_unicode_ci default NULL,
  `recur_every` char(3) collate utf8_unicode_ci default NULL,
  `timedate_significance` char(4) collate utf8_unicode_ci default NULL,
  `check_in_times` varchar(255) collate utf8_unicode_ci default NULL,
  `check_out_times` varchar(255) collate utf8_unicode_ci default NULL,
  PRIMARY KEY  (`id`),
  KEY `fk_period_apartment1_idx` (`apartment_id`),
  KEY `fk_period_pricing1_idx` (`pricing_id`),
  CONSTRAINT `fk_period_apartment1` FOREIGN KEY (`apartment_id`) REFERENCES `wp_abk_apartment` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_period_pricing1` FOREIGN KEY (`pricing_id`) REFERENCES `wp_abk_pricing` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Isn't key 1 id in this case and having it on auto_increment sufficient for being able to not specify it?

Note: If I just provide an unused value for id, like INSERT INTO wp_abk_period  (id, pricing_id, apartment_id)  VALUES (3333333, 13, 27) it works fine, but then again, it is set as auto_increment so I shouldn't need to do this!

Note 2: OK, this is a complete "twilight zone" moment: so after running the query above with the huge number for id, things started working normally, no more duplicate entry errors. Can someone explain me WTF was MySQL doing to produce this weird behavior?

Body:
Late to the party, but I just ran into this tonight - duplicate key '472817' and the provided answers didn't help.

On a whim I ran:

repair table wp_abk_period

which output

Number of rows changed from 472816 to 472817

Seems like mysql had the row count wrong, and the issue went away.

My environment:

mysql  Ver 14.14 Distrib 5.1.73, for Win64 (unknown)

Create table syntax:

CREATE TABLE `env_events` (
  `tableId` int(11) NOT NULL AUTO_INCREMENT,
  `deviceId` varchar(50) DEFAULT NULL,
  `timestamp` int(11) DEFAULT NULL,
  `temperature` float DEFAULT NULL,
  `humidity` float DEFAULT NULL,
  `pressure` float DEFAULT NULL,
  `motion` int(11) DEFAULT NULL,
  PRIMARY KEY (`tableId`)
) ENGINE=MyISAM AUTO_INCREMENT=528521 DEFAULT CHARSET=latin1


问:
Create a MediaWiki template to set font color in pages
I just installed Mediawiki and realized that it is very complicated to configure it for newbie.

As one of my first entry I wanted to change font color with:

```<code>{{ font color | green | green text }}
</code>```

To do that I imported Template:Font color from Wikipedia Special:Export page, but still as the result I don't get coloured text, but:

```<code>{{ safesubst:#if:

| {{ safesubst:#if:
     | {{ safesubst:#ifeq:  | yes
     | [[ {{ safesubst:#if:1|  }}|{{ safesubst:#if:1|  }}]]
     | [[|{{ safesubst:#if:1|  }}]]
     }}
   | {{ safesubst:#if:1|  }}
   }}
| {{ safesubst:#if:
     | {{ safesubst:#ifeq:  | yes
     | [[ {{ safesubst:#if:1|  green text  }} |{{ safesubst:#if:1|  green text  }}]]
     | [[ {{ safesubst:#if:1|  }} |{{ safesubst:#if:1|  green text  }}]]
   }}
 | {{ safesubst:#if:1|  green text  }}
 }}

}}
</code>```

Could you please help me?

答:
You're better off not trying to import templates from Wikipedia. They have grown fiendishly complex over the years, and you pretty much need to be an expert in wiki template markup to be able to change anything.

Instead, I recommend making your own. They can be really simple, and because you own the wiki you can easily add your own custom CSS. For example, if you want text in different colours, you can do the following. First, add some rules to your MediaWiki:Common.css page:

```<code>.text-color-green {
  color: green;
}

.text-color-blue {
  color: blue;
}

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

Then create Template:Font color with this content:

```<code><span class="text-color-{{{1}}}">{{{2}}}</span>
</code>```

Then you can make green text with {{Font color|green|green text}}, red text with {{Font color|red|red text}}, etc.

Doing this in CSS rather than with inline styles makes it easy to update the styles later, and should be faster for browsers to render.

Better still would be to make the templates semantic. For example, if you want to colour text green whenever something has been approved, you can add the following to MediaWiki:Common.css:

```<code>.approved {
  color: green;
}
</code>```

And then create Template:Approved with the following content:

```<code><span class="approved">{{{1}}}</span>
</code>```

Then you can make approved text by calling {{Approved|some approved text}}. Then, in the future, if you decide you need all approved text to be bolded as well, you can just add font-weight: bold; to the approved style and everything will be updated.

Body:
I just installed Mediawiki and realized that it is very complicated to configure it for newbie.

As one of my first entry I wanted to change font color with:

{{ font color | green | green text }}

To do that I imported Template:Font color from Wikipedia Special:Export page, but still as the result I don't get coloured text, but:

{{ safesubst:#if:

| {{ safesubst:#if:
     | {{ safesubst:#ifeq:  | yes
     | [[ {{ safesubst:#if:1|  }}|{{ safesubst:#if:1|  }}]]
     | [[|{{ safesubst:#if:1|  }}]]
     }}
   | {{ safesubst:#if:1|  }}
   }}
| {{ safesubst:#if:
     | {{ safesubst:#ifeq:  | yes
     | [[ {{ safesubst:#if:1|  green text  }} |{{ safesubst:#if:1|  green text  }}]]
     | [[ {{ safesubst:#if:1|  }} |{{ safesubst:#if:1|  green text  }}]]
   }}
 | {{ safesubst:#if:1|  green text  }}
 }}

}}

Could you please help me?

Body:
You're better off not trying to import templates from Wikipedia. They have grown fiendishly complex over the years, and you pretty much need to be an expert in wiki template markup to be able to change anything.

Instead, I recommend making your own. They can be really simple, and because you own the wiki you can easily add your own custom CSS. For example, if you want text in different colours, you can do the following. First, add some rules to your MediaWiki:Common.css page:

.text-color-green {
  color: green;
}

.text-color-blue {
  color: blue;
}

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

Then create Template:Font color with this content:

<span class="text-color-{{{1}}}">{{{2}}}</span>

Then you can make green text with {{Font color|green|green text}}, red text with {{Font color|red|red text}}, etc.

Doing this in CSS rather than with inline styles makes it easy to update the styles later, and should be faster for browsers to render.

Better still would be to make the templates semantic. For example, if you want to colour text green whenever something has been approved, you can add the following to MediaWiki:Common.css:

.approved {
  color: green;
}

And then create Template:Approved with the following content:

<span class="approved">{{{1}}}</span>

Then you can make approved text by calling {{Approved|some approved text}}. Then, in the future, if you decide you need all approved text to be bolded as well, you can just add font-weight: bold; to the approved style and everything will be updated.


问:
Creating different matrices from data frame with R for loop
I've got 2 data frames (df 1 and 2) that have the following structure:

```<code>CHR SNP A1 A2 FAM CA1 CA2
1 rs3818361 A G 0.35 7 13
2 rs7561528 A G 0.2 4 16
2 rs6733839 T C 0.45 9 11
2 rs744373 G A 0.45 9 11
2 rs35349669 T C 0.35 7 13
...
</code>```

They have 7 columns and 41 number of rows (without counting the colnames row). With the columns CA1 and CA2 of each one of the data frames I have to build 2x2 matrices, like this:

```<code>[CA1 from df1] [CA2 from df1] #first row CA1 and CA2 from df1
[CA1 from df2] [CA2 from df2] #first row CA1 and CA2 from df2

[CA1 from df1] [CA2 from df1] #second row CA1 and CA2 from df1
[CA1 from df2] [CA2 from df2] #second row CA1 and CA2 from df2

[CA1 from df1] [CA2 from df1] #third row CA1 and CA2 from df1
[CA1 from df2] [CA2 from df2] #third row CA1 and CA2 from df2
</code>```

I thought about a for loop for (i in 1:41), but i'm having trouble to consolidate the idea.

```<code>for (i in 1:41) {
do
datai <- c(df1[i,7],df1[i,8],df2[i,7],df2[i,8])
matrixi <- matrix(datai, nrow=2, ncol=2, byrow=TRUE)
}
</code>```

I want the loop to generate 41 matrices. The "i" that i put at matrix and data (datai and matrixi) mean "i want 41 of these". Any thoughts?

答:
Even though your answers worked, I also asked someone at my lab for help and it worked, with an alternative. Here i leave you the answer, in case it helps someone:

First, cbind all the columns of all the 7 dfs that i would need into one single data frame: called ¨counts¨. In counts, the structure is like this:

```<code>counts<-cbind(df1$CA1,df1$CA2,df2$CA1,df2$CA2,df3$CA1,df3$CA2,df4$CA1,df4$CA2
,df5$CA1,df5$CA2,df6$CA1,df5$CA2,df6$CA1,df6$CA2)
</code>```

So, i wanted to

```<code>res <- list()

for (i in c(1,3,5,7,9,11,13)) {
  for (k in c(3,5,7,9,11,13)) {
    for (j in 1:41) {
      tmp <- chisq.test(matrix(c(counts[j,i],counts[j,(i+1)],counts[j,k],counts[j,(k+1)]),nrow=2,ncol=2,byrow=TRUE))
      res<-c(res,as.list(c(tmp$p.value))) }}}
</code>```

(I wanted the matrices to do a chisq test... that´s why it´s inside of chisq.test(), but there you can see the answer in the middle of the code).

Body:
I've got 2 data frames (df 1 and 2) that have the following structure:

CHR SNP A1 A2 FAM CA1 CA2
1 rs3818361 A G 0.35 7 13
2 rs7561528 A G 0.2 4 16
2 rs6733839 T C 0.45 9 11
2 rs744373 G A 0.45 9 11
2 rs35349669 T C 0.35 7 13
...

They have 7 columns and 41 number of rows (without counting the colnames row). With the columns CA1 and CA2 of each one of the data frames I have to build 2x2 matrices, like this:

[CA1 from df1] [CA2 from df1] #first row CA1 and CA2 from df1
[CA1 from df2] [CA2 from df2] #first row CA1 and CA2 from df2

[CA1 from df1] [CA2 from df1] #second row CA1 and CA2 from df1
[CA1 from df2] [CA2 from df2] #second row CA1 and CA2 from df2

[CA1 from df1] [CA2 from df1] #third row CA1 and CA2 from df1
[CA1 from df2] [CA2 from df2] #third row CA1 and CA2 from df2

I thought about a for loop for (i in 1:41), but i'm having trouble to consolidate the idea.

for (i in 1:41) {
do
datai <- c(df1[i,7],df1[i,8],df2[i,7],df2[i,8])
matrixi <- matrix(datai, nrow=2, ncol=2, byrow=TRUE)
}

I want the loop to generate 41 matrices. The "i" that i put at matrix and data (datai and matrixi) mean "i want 41 of these". Any thoughts?

Body:
Even though your answers worked, I also asked someone at my lab for help and it worked, with an alternative. Here i leave you the answer, in case it helps someone:

First, cbind all the columns of all the 7 dfs that i would need into one single data frame: called ¨counts¨. In counts, the structure is like this:

counts<-cbind(df1$CA1,df1$CA2,df2$CA1,df2$CA2,df3$CA1,df3$CA2,df4$CA1,df4$CA2
,df5$CA1,df5$CA2,df6$CA1,df5$CA2,df6$CA1,df6$CA2)

So, i wanted to

res <- list()

for (i in c(1,3,5,7,9,11,13)) {
  for (k in c(3,5,7,9,11,13)) {
    for (j in 1:41) {
      tmp <- chisq.test(matrix(c(counts[j,i],counts[j,(i+1)],counts[j,k],counts[j,(k+1)]),nrow=2,ncol=2,byrow=TRUE))
      res<-c(res,as.list(c(tmp$p.value))) }}}

(I wanted the matrices to do a chisq test... that´s why it´s inside of chisq.test(), but there you can see the answer in the middle of the code).


问:
Item count should be 10 but is 0
the items.count should be atlease 10. I have 10 subfolders (Release 1 ..... Release 10) with in this documnent library "Auto Cad" and each subfolder has a file called license.txt. hmmm
Why this is not returning any file(s)?</p>

```<code>private void btnGetFileGuid_Click(object sender, EventArgs e)
{

using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
 {
 using (SPWeb web = site.OpenWeb())
 {
  SPList spList = web.Lists["Auto Cad"];
  string fileName = "license.txt";
  SPQuery query = new SPQuery();
  query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
  SPListItemCollection items = spList.GetItems(query);
  if (items.Count > 0)
   {
    Guid id = items[0].UniqueId;
    lblGuid.Text = id.ToString();
   }
  }
 }
}
</code>```

答:
SPQuery only searches a particular folder - to recursively search through subfolders you need to set

SPQuery.ViewAttributes = "Scope=\"Recursive\"";

So your code should be

```<code>SPQuery query = new SPQuery();
query.ViewAttributes = "Scope=\"Recursive\"";
query.Query=".... REST OF YOUR CODE HERE "
</code>```

Title: Item count should be 10 but is 0

Body:
the items.count should be atlease 10. I have 10 subfolders (Release 1 ..... Release 10) with in this documnent library "Auto Cad" and each subfolder has a file called license.txt. hmmm
Why this is not returning any file(s)?

private void btnGetFileGuid_Click(object sender, EventArgs e)
{

using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
 {
 using (SPWeb web = site.OpenWeb())
 {
  SPList spList = web.Lists["Auto Cad"];
  string fileName = "license.txt";
  SPQuery query = new SPQuery();
  query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
  SPListItemCollection items = spList.GetItems(query);
  if (items.Count > 0)
   {
    Guid id = items[0].UniqueId;
    lblGuid.Text = id.ToString();
   }
  }
 }
}

Body:
SPQuery only searches a particular folder - to recursively search through subfolders you need to set

SPQuery.ViewAttributes = "Scope=\"Recursive\"";

So your code should be

SPQuery query = new SPQuery();
query.ViewAttributes = "Scope=\"Recursive\"";
query.Query=".... REST OF YOUR CODE HERE "


答:
I would expect, since argsStr is only of size 8, it would be testtest and the rest would overflow into anotherStr

In order for the argsStr string to stop after 8 characters on printing, 9-th character must be '\0'. Your string does not have it, hence printf does not know to stop after printing the first 8 characters on %s.

You got your heap overflow, because strcpy blew past the allocated size. It also blew through the "bookkeeping info" stored by malloc, and spills into the next allocation. Of course it does not have to go into the next allocated block, because it's undefined behavior; it just happened to do it on your particular system.

You can tell that there was a heap overflow by running your program through valgrind. Chances are, your program is going to crash when you add calls to free the memory that you allocated.

Title: malloc() with heap overflow explanation

Body:
I have the following code:

int main(int argc, char *argv[]) {

    int bufferSize = 8;
    //Setting the buffer size here, which can cause a heap overflow
    char *argsStr = malloc(bufferSize);
    char *anotherStr = malloc(bufferSize);

    //If argv[1] is greater than the buffer size, we will have an overflow
    strcpy(argsStr, argv[1]);

    printf("String 1: %s String 2: %s", argsStr, anotherStr);

}

I want to cause a heap overflow, so I import the param 'testtesttesttesttesttesttesttesttest'.

I would expect, since argsStr is only of size 8, it would be 'testtest' and the rest would overflow into anotherStr (for 8 bytes), but instead I see:

so argsStr is 'testtesttesttesttesttesttesttesttest' and anotherStr is 'testtesttesttesttest'

Why is this? Am I missing something with heap overflows or malloc()?


问:
jquery .append() method producing unwanted result
I'm working on a project using Wikipedia's API. I have been able to successfully load the API's data.
 However, here is the problem I try to load the API's result into the DOM when an input value is submitted, but each time I try to submit a new value the result is gets appended to the initial result from the first input search.

Here is a fiddle which may show what I mean:

https://jsfiddle.net/aonz929f/1/

```<code>    for( var key in data.query.pages){
        //loop through the JSON data
       }

$("#result").append(htmlContent)/// Then I used the append method to return each returned result to the DOM
</code>```

答:
You have to clear the already existing html before appending new one, like this:</p>

```<code>$("#result").html("")
for( var key in data.query.pages){
   $("#result").append(("<p>" + data.query.pages[key].title) + "</p>")
   //etc..
}
</code>```

Body:
I'm working on a project using Wikipedia's API. I have been able to successfully load the API's data.
 However, here is the problem I try to load the API's result into the DOM when an input value is submitted, but each time I try to submit a new value the result is gets appended to the initial result from the first input search.

Here is a fiddle which may show what I mean:

https://jsfiddle.net/aonz929f/1/

    for( var key in data.query.pages){
        //loop through the JSON data
       }

$("#result").append(htmlContent)/// Then I used the append method to return each returned result to the DOM

Body:
You have to clear the already existing html before appending new one, like this:

$("#result").html("")
for( var key in data.query.pages){
   $("#result").append(("<p>" + data.query.pages[key].title) + "</p>")
   //etc..
}


问:
Azure MSDN Subscription: change the url of the default AD
By default, you get an AD which is associated with your azure subscription which is identified by name on the form XXX.onmicrosoft.com. Does anyone know if it's possible to change the XXX to something else?

Thanks.

Luis

答:
No, it is not possible.

You could create a new AD account or add or custom domain to Azure AD, please check my answer about this.


问:
Insert variables into a SQL Server table in stored procedure
I am trying to insert variables into SQL Server table dynamically inside a stored procedure but I'm not able to accomplish it because of the syntax. Can someone correct me what am I doing wrong in the below code. Thanks.

Code I have tried:

```<code>SET @SQLStmt1 = N'INSERT INTO TestTable (TableName)
                  VALUES(' + @ResulTableName + N')'
EXEC sp_executesql @SQLStmt1
</code>```

答:
you can do it by adding triple quotes '''
this will resolve your problem

```<code>SET @SQLStmt1 = N'INSERT INTO TestTable( TableName )
                              VALUES(''' + @ResulTableName + ''')'
EXEC sp_executesql @SQLStmt1
</code>```

the reason behind that is that triple quote in the dynamic SQL will become a single quote when the code get executed.

Body:
I am trying to insert variables into SQL Server table dynamically inside a stored procedure but I'm not able to accomplish it because of the syntax. Can someone correct me what am I doing wrong in the below code. Thanks.

Code I have tried:

SET @SQLStmt1 = N'INSERT INTO TestTable (TableName)
                  VALUES(' + @ResulTableName + N')'
EXEC sp_executesql @SQLStmt1

Body:
you can do it by adding triple quotes '''
this will resolve your problem

SET @SQLStmt1 = N'INSERT INTO TestTable( TableName )
                              VALUES(''' + @ResulTableName + ''')'
EXEC sp_executesql @SQLStmt1

the reason behind that is that triple quote in the dynamic SQL will become a single quote when the code get executed.