问:
Python selection-sort with while loop returns unaltered array—why?
I hate having to ask like this, but I'm at my wits' end. Doesn't help that the assignment I'm doing this for requires a while loop contained in a for loop, rather than a nested for loop that every example I've ever been able to find has used. Very frustrating.

So here's the code, with comments written out for my own reference as best as I can understand what's going on (I'm not a very good programmer as of now).

```<code>def selection_sort(arr):
    for indexvalue in range (0, len(arr) - 1): #we want to start with the 0th item in the index for selection sort and end at the second-to-last one,
        currentmin = indexvalue #establishes the first variable as our lowest looked at so far. This is something that changes every time we go over the array, looking for the next lowest number
        while indexvalue<len(arr):
            if arr[indexvalue] < arr[currentmin]: #allows us to find the new lowest value—anything lower than our currently-located minimum should count as our new lowest value
                arr[indexvalue], arr[currentmin] = arr[currentmin], arr[indexvalue] #exchanges the two values so that our current lowest value is set one to the left in the array, and the new lowest value one to the right
                indexvalue = indexvalue+1 #adds another 1 to our counter so that we can compare the next-indexed items
            else: #should occur when we reach the end of our array
                break #forcibly ends the while loop, and by extension the function
</code>```

Not really sure what's going on—as best as I can process it works, but it clearly doesn't. For example, when I run:

```<code>testlist=[10, 12, 15, 1, 0, 4, 99]
selection_sort(testlist)
print(testlist)
</code>```

I get testlist, unaltered. Any idea why this might be? I'm clearly missing something important, but I have no clue what it might be.

Edit: new, improved code below. Not perfect, but it's sorting something now at least. This set results in a set of data that seems to be replacing elements with their index positions; I'm fairly sure that it's being caused by line 6. Not sure why though.

```<code>def selection_sort(arr):
    for indexvalue in range (0, len(arr) - 1): #we want to start with the 0th item in the index for selection sort and end at the second-to-last one,
        currentmin = indexvalue #establishes the first variable as our lowest looked at so far. This is something that changes every time we go over the array, looking for the next lowest number
        while indexvalue<len(arr):
            if arr[indexvalue] > currentmin: #allows us to find the new lowest value—anything lower than our currently-located minimum should count as our new lowest value
                arr[indexvalue], currentmin = currentmin, arr[indexvalue] #exchanges the two values so that our current lowest value is set one to the left in the array, and the new lowest value one to the right
                indexvalue = indexvalue+1 #adds another 1 to our counter so that we can compare the next-indexed items
                print (arr)
            else: #should occur when we reach the end of our array
                break #forcibly ends the while loop, and by extension the function
</code>```

答:
At the beginning of your while-loop you always compare arr[currentmin] with itself, because currentmin == indexvalue at the time. Since a value is never smaller than itself, the else branch takes over and ends the while-loop before any changes to the list could have been made.

This happens every iteration of the for-loop, thus leaving you with an unaltered list.

Possible solutions incoming!

 Either, you go with if arr[indexvalue] <= arr[currentmin]: in line 5, which is totally fine, since selection sort is not necessarily a stable sorting algorithm

or

 You add a line like indexvalue = indexvalue + 1 before

if arr[indexvalue] < arr[currentmin]:

Hope it helps (and I didn't overdo it with all the formatting ^^' )

Continuation:

Now that we've got that out of our way, we should have a look at what happens within the if-statement:

When an element is found which is smaller than the yet smallest element, selection sort merely remembers this new index.

currentmin = indexvalue

There should be no swapping going on yet.

When indexvalue has reached the end of the list, currentmin should be pointing to the smallest not yet sorted element.

This smallest element is now supposed to be swapped with the first unsorted element which should be at arr[indexvalue]. But since you have used indexvalue to move over the rest of the list, the program does not know where the unsorted elements start. You'll need to define another "running-index" for use within the while-loop, initialized with indexvalue before the head of the while-loop.

Body:
I hate having to ask like this, but I'm at my wits' end. Doesn't help that the assignment I'm doing this for requires a while loop contained in a for loop, rather than a nested for loop that every example I've ever been able to find has used. Very frustrating.

So here's the code, with comments written out for my own reference as best as I can understand what's going on (I'm not a very good programmer as of now).

def selection_sort(arr):
    for indexvalue in range (0, len(arr) - 1): #we want to start with the 0th item in the index for selection sort and end at the second-to-last one,
        currentmin = indexvalue #establishes the first variable as our lowest looked at so far. This is something that changes every time we go over the array, looking for the next lowest number
        while indexvalue<len(arr):
            if arr[indexvalue] < arr[currentmin]: #allows us to find the new lowest value—anything lower than our currently-located minimum should count as our new lowest value
                arr[indexvalue], arr[currentmin] = arr[currentmin], arr[indexvalue] #exchanges the two values so that our current lowest value is set one to the left in the array, and the new lowest value one to the right
                indexvalue = indexvalue+1 #adds another 1 to our counter so that we can compare the next-indexed items
            else: #should occur when we reach the end of our array
                break #forcibly ends the while loop, and by extension the function

Not really sure what's going on—as best as I can process it works, but it clearly doesn't. For example, when I run:

testlist=[10, 12, 15, 1, 0, 4, 99]
selection_sort(testlist)
print(testlist)

I get testlist, unaltered. Any idea why this might be? I'm clearly missing something important, but I have no clue what it might be.

Edit: new, improved code below. Not perfect, but it's sorting something now at least. This set results in a set of data that seems to be replacing elements with their index positions; I'm fairly sure that it's being caused by line 6. Not sure why though.

def selection_sort(arr):
    for indexvalue in range (0, len(arr) - 1): #we want to start with the 0th item in the index for selection sort and end at the second-to-last one,
        currentmin = indexvalue #establishes the first variable as our lowest looked at so far. This is something that changes every time we go over the array, looking for the next lowest number
        while indexvalue<len(arr):
            if arr[indexvalue] > currentmin: #allows us to find the new lowest value—anything lower than our currently-located minimum should count as our new lowest value
                arr[indexvalue], currentmin = currentmin, arr[indexvalue] #exchanges the two values so that our current lowest value is set one to the left in the array, and the new lowest value one to the right
                indexvalue = indexvalue+1 #adds another 1 to our counter so that we can compare the next-indexed items
                print (arr)
            else: #should occur when we reach the end of our array
                break #forcibly ends the while loop, and by extension the function


来源: stackexchange

问:
Remove key from all objects in array
I have the following array of objects:

```<code>[{id:1, value:"100", name:"dog" ...},
{id:2, value:"200", name:"cat" ...},
{id:3, value:"300", name:"fish"....},
{id:4, value:"400", name:"mouse" ...},
{id:5, value:"500", name:"snake"...}]
</code>```

I want to filter the object array and keep only two keys, id and value to get something like this:

```<code>[{id:1, value:"100"},
{id:2, value:"200"},
{id:3, value:"300"},
{id:4, value:"400"},
{id:5, value:"500"}]
</code>```

Currently, I'm traversing through the object array with a for loop and doing a push() to an empty array with the new variables. Is there an easier way to do this?

I wanted to use Lodash like _.pluck(PetList, 'id', 'value'); but lodash extracts the value only, not the key.

答:
Array#filter filters individual items out of the array, not certain keys from an object in the array. You could use the method Array#map to transform the objects and only keeping the keys you want. map is designed to transform each element of an array to something new, "mapping" the old value to a new value:

```<code>let newPetList = PetList.map(pet => ({
    id: pet.id,
    value: pet.value
}));
</code>```

The above traverses the array, and stores the current object in pet. It then returns a new object from an arrow function which will be the corresponding transformed object in newPetList with only keys id and value from pet. The result is that all objects in the old array are mapped to a new object with no name key.

You could also, with object destructuring, filter put unwanted properties like so:

```<code>let newPetList = petList.map(({ name, ...rest }) => rest);
</code>```

This binds the name property to name and keeps the rest in rest, which you can return to remove the name key.

ContentLicense: CC BY-SA 3.0

Title: Remove key from all objects in array

Body:
I have the following array of objects:

[{id:1, value:"100", name:"dog" ...},
{id:2, value:"200", name:"cat" ...},
{id:3, value:"300", name:"fish"....},
{id:4, value:"400", name:"mouse" ...},
{id:5, value:"500", name:"snake"...}]

I want to filter the object array and keep only two keys, id and value to get something like this:

[{id:1, value:"100"},
{id:2, value:"200"},
{id:3, value:"300"},
{id:4, value:"400"},
{id:5, value:"500"}]

Currently, I'm traversing through the object array with a for loop and doing a push() to an empty array with the new variables. Is there an easier way to do this?

I wanted to use Lodash like _.pluck(PetList, 'id', 'value'); but lodash extracts the value only, not the key.

Body:
Array#filter filters individual items out of the array, not certain keys from an object in the array. You could use the method Array#map to transform the objects and only keeping the keys you want. map is designed to transform each element of an array to something new, "mapping" the old value to a new value:

let newPetList = PetList.map(pet => ({
    id: pet.id,
    value: pet.value
}));

The above traverses the array, and stores the current object in pet. It then returns a new object from an arrow function which will be the corresponding transformed object in newPetList with only keys id and value from pet. The result is that all objects in the old array are mapped to a new object with no name key.

You could also, with object destructuring, filter put unwanted properties like so:

let newPetList = petList.map(({ name, ...rest }) => rest);

This binds the name property to name and keeps the rest in rest, which you can return to remove the name key.

ContentLicense: CC BY-SA 4.0


问:
Internet Explorer 8 - Session Shared among Explorer Window
IE 8 sharing session among different Explorer Window for same domain.

Like if you are a logined at hotmail.com in IE 8, and you have open another explorer window for hotmail.com, you will automatically logined.

This was not in IE 7, In IE 7 session has shared in the same explorer tab rather different Explorer Window.

Can anyone have a idea about this, Whether it is bug or something else in IE 8

答: You can prevent new windows from sharing session cookies by File -> New Session, however you cannot prevent new tabs from sharing data by default. </p>

ContentLicense: CC BY-SA 2.5


问:
charAt(0) Not returning first number but second
Piglatin translator. at the end I am trying to get the location of the first vowel. Index is set to be the location of every vowel, but with pig latin you only need the location of the first vowel. When I run the program I don't always get the location of the first vowel. it seems to give me the second number and not the first. </p>

```<code>import java.util.Scanner;
import javax.swing.JOptionPane;

public class Assignment_4_Piglatin {

    public static void main(String[] args) {

        Scanner userWord = new Scanner(System.in);

        System.out.println("K. Caleb Swallow");
        System.out.println("Welcome to the Pig Latin Translator!");

        boolean run = true;
        while (run) {

            System.out.println("Please enter a word(or press Q to quit):");

            String firstLetter = "something";
            String firstVowel = "test";

            String word = userWord.next();
            String vowels = "aeiou";
            if (word.equals("Q")) {
                System.exit(0);
            }

            firstLetter = Character.toString(word.charAt(0));

            if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
                System.out.println(word + "way");
            } else {
                for (int index = 0; index < word.length(); index++) {
                    if (vowels.contains(String.valueOf(word.charAt(index)))) {
                        System.out.print(index);
                        String firstNumber = Integer.toString(index);
                        firstVowel = Character.toString(firstNumber.charAt(0));

                    }
                }

            }
            System.out.println(firstVowel);
</code>```

答:
public static void main(String[] args) {

```<code>            Scanner userWord = new Scanner(System.in);

            System.out.println("K. Caleb Swallow");
            System.out.println("Welcome to the Pig Latin Translator!");

            boolean run = true;
            while (run) {

                System.out.println("Please enter a word(or press Q to quit):");

                String firstLetter = "something";
                String firstVowel = "test";

                String word = userWord.next();
                ArrayList<Character> vowels = new ArrayList<>();
                vowels.add('a');
                vowels.add('e');
                vowels.add('i');
                vowels.add('o');
                vowels.add('u');
                if (word.equals("Q")) {
                    System.exit(0);
                }

                firstLetter = Character.toString(word.charAt(0));

                if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
                    System.out.println(word + "way");
                } else {
                    for (int index = 0; index < word.length(); index++) {
                        char indchar = word.charAt(index);
                        if (vowels.contains(word.charAt(index))) {
                            System.out.println(index);
                            firstVowel = Character.toString(word.charAt(index));
                            System.out.println(firstVowel);
                            index = word.length();

                        }
                    }
                }
            }
        }
</code>```

This is how I would do it. I changed the vowels String to an ArrayList so you can easily check if the char in the String word with the index is a vowel and the code works absolutely fine. It returns you the index where the first vowel is and what vowel it is.

Body:
Piglatin translator. at the end I am trying to get the location of the first vowel. Index is set to be the location of every vowel, but with pig latin you only need the location of the first vowel. When I run the program I don't always get the location of the first vowel. it seems to give me the second number and not the first.

import java.util.Scanner;
import javax.swing.JOptionPane;

public class Assignment_4_Piglatin {

    public static void main(String[] args) {

        Scanner userWord = new Scanner(System.in);

        System.out.println("K. Caleb Swallow");
        System.out.println("Welcome to the Pig Latin Translator!");

        boolean run = true;
        while (run) {

            System.out.println("Please enter a word(or press Q to quit):");

            String firstLetter = "something";
            String firstVowel = "test";

            String word = userWord.next();
            String vowels = "aeiou";
            if (word.equals("Q")) {
                System.exit(0);
            }

            firstLetter = Character.toString(word.charAt(0));

            if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
                System.out.println(word + "way");
            } else {
                for (int index = 0; index < word.length(); index++) {
                    if (vowels.contains(String.valueOf(word.charAt(index)))) {
                        System.out.print(index);
                        String firstNumber = Integer.toString(index);
                        firstVowel = Character.toString(firstNumber.charAt(0));

                    }
                }

            }
            System.out.println(firstVowel);

Body:
public static void main(String[] args) {

            Scanner userWord = new Scanner(System.in);

            System.out.println("K. Caleb Swallow");
            System.out.println("Welcome to the Pig Latin Translator!");

            boolean run = true;
            while (run) {

                System.out.println("Please enter a word(or press Q to quit):");

                String firstLetter = "something";
                String firstVowel = "test";

                String word = userWord.next();
                ArrayList<Character> vowels = new ArrayList<>();
                vowels.add('a');
                vowels.add('e');
                vowels.add('i');
                vowels.add('o');
                vowels.add('u');
                if (word.equals("Q")) {
                    System.exit(0);
                }

                firstLetter = Character.toString(word.charAt(0));

                if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
                    System.out.println(word + "way");
                } else {
                    for (int index = 0; index < word.length(); index++) {
                        char indchar = word.charAt(index);
                        if (vowels.contains(word.charAt(index))) {
                            System.out.println(index);
                            firstVowel = Character.toString(word.charAt(index));
                            System.out.println(firstVowel);
                            index = word.length();

                        }
                    }
                }
            }
        }

This is how I would do it. I changed the vowels String to an ArrayList so you can easily check if the char in the String word with the index is a vowel and the code works absolutely fine. It returns you the index where the first vowel is and what vowel it is.


问:
Alignment of price's location using CSS (Woo commerce Store)
Problem with the alignement of price with the name(heading)

CSS Code

```<code>.mgrt-product-title .price {
 padding-left: 749px;
 font-weight: bold;
 color:#000;
}
</code>```

You can check the present alignment here - my store. How to align prices to be all in the same line?

答:
I would erase the padding-left, use a padding-right instead (for example 100px or whatever you like) and add float: right; so the prices all align to the right side at the same distance.

```<code>.mgrt-product-title .price {
 float: right;
 padding-right: 100px;
 font-weight: bold;
 color:#000;
}
</code>```

Body:
Problem with the alignement of price with the name(heading)

CSS Code

.mgrt-product-title .price {
 padding-left: 749px;
 font-weight: bold;
 color:#000;
}

You can check the present alignment here - my store. How to align prices to be all in the same line?

Body:
I would erase the padding-left, use a padding-right instead (for example 100px or whatever you like) and add float: right; so the prices all align to the right side at the same distance.

.mgrt-product-title .price {
 float: right;
 padding-right: 100px;
 font-weight: bold;
 color:#000;
}


答:
What you are trying to achieve is called mapping rather filtering. Here's a solution

var array = [{id:1, value:"100", name:"dog"},
{id:2, value:"200", name:"cat"},
{id:3, value:"300", name:"fish"},
{id:4, value:"400", name:"mouse"},
{id:5, value:"500", name:"snake"}];
var result = array.map(function(obj) {
    return {id: obj.id, value: obj.value};
});

console.log(result);```

Title: Remove key from all objects in array


问:
stuck with node.js Readline module
I am at very entry level with Node.js and JavaScript , i want to read from a txt file line by line and print every single line with adjusted time interval , i found this module which helped me to read lines "https://nodejs.org/api/readline.html" .
but my code publish all lines once , i want to wait seconds between lines
i added setTimeout function and tried alot of configration with no vail . Thanks </p>

```<code>     const readline = require('readline');
     const fs = require('fs');
  const rl = readline.createInterface({
  input: fs.createReadStream(process.cwd() +'/sample.txt')
 });

 rl.on('line', function(input){
  rl.pause();
  console.log(input);

   setTimeout(() => {
     rl.resume();
    }, 5000);
</code>```

答:
This can be easily done with synchronous executor nsynjs:

```<code>var nsynjs = require('nsynjs');

// following 2 files can be found in nsynjs package
var textFile = require('./wrappers/nodeReadline').textFile;
var wait = require('./wrappers/nsynWait').nsynWait;

function process(textFile,wait) {
    var fh = new textFile();
    fh.open('../data/lorem.txt');
    var s, i = 0;
    while (typeof(s = fh.readLine(nsynjsCtx).data) != 'undefined')
    {
        if(s)
            console.log(s);
        else
            console.log("<empty line>");
        wait(nsynjsCtx,1000);
    }
    fh.close();
}

var ctx = nsynjs.run(process,{},textFile,wait,function () {
    console.log('done');
});
</code>```

Full working example can be found here: https://github.com/amaksr/nsynjs/blob/master/examples/node-readline/index.js

Title: stuck with node.js Readline module

Body:
I am at very entry level with Node.js and JavaScript , i want to read from a txt file line by line and print every single line with adjusted time interval , i found this module which helped me to read lines "https://nodejs.org/api/readline.html" .
but my code publish all lines once , i want to wait seconds between lines
i added setTimeout function and tried alot of configration with no vail . Thanks

     const readline = require('readline');
     const fs = require('fs');
  const rl = readline.createInterface({
  input: fs.createReadStream(process.cwd() +'/sample.txt')
 });

 rl.on('line', function(input){
  rl.pause();
  console.log(input);

   setTimeout(() => {
     rl.resume();
    }, 5000);

Body:
This can be easily done with synchronous executor nsynjs:

var nsynjs = require('nsynjs');

// following 2 files can be found in nsynjs package
var textFile = require('./wrappers/nodeReadline').textFile;
var wait = require('./wrappers/nsynWait').nsynWait;

function process(textFile,wait) {
    var fh = new textFile();
    fh.open('../data/lorem.txt');
    var s, i = 0;
    while (typeof(s = fh.readLine(nsynjsCtx).data) != 'undefined')
    {
        if(s)
            console.log(s);
        else
            console.log("<empty line>");
        wait(nsynjsCtx,1000);
    }
    fh.close();
}

var ctx = nsynjs.run(process,{},textFile,wait,function () {
    console.log('done');
});

Full working example can be found here: https://github.com/amaksr/nsynjs/blob/master/examples/node-readline/index.js


问:
Java Log4j2 converter category plugin add more than one custom fields to log
I tried the examples in Extending Log4j2 and Create Custom Pattern using log4j2 in java and now I want to add two fields to the log. What changes do I need to do to get this?</p>

答:
Refer to this manual https://logging.apache.org/log4j/log4j-2.2/manual/plugins.html#Converters

If you want several fields for example time and name you could create two separate Converters which will provide that data to the log.

For instance you have MyNamePatternConverter, here we can provide alias whatIsMyName and myName. In log pattern we can use any of those.

```<code>@Plugin(name="MyNamePatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys(value = {"whatIsMyName", "myName"})
public class MyNameConverter extends LogEventPatternConverter {

    protected MyNameConverter(String name, String style) {
        super(name, style);
    }

    public static MyNameConverter newInstance(String[] options) {
        return new MyNameConverter("My name Converter", "name");
    }

    public void format(LogEvent event, StringBuilder toAppendTo) {
        toAppendTo.append("Yuriy");
    }
}
</code>```

and TimePatternConverter

```<code>@Plugin(name = "TimePatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys(value = {"timeIsNow", "timeNow", "now"})
public class TimeConverter extends LogEventPatternConverter {
    protected TimeConverter(String name, String style) {
        super(name, style);
    }

    public static TimeConverter newInstance(String[] options) {
        return new TimeConverter("Time Converter", "now");
    }

    public void format(LogEvent logEvent, StringBuilder toAppendTo) {
        toAppendTo.append(new SimpleDateFormat("HH:mm").format(new Date()));
    }
}
</code>```

We will put them two in separate package called converters.

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns="http://logging.apache.org/log4j/2.0/config"
               status="OFF" packages="converters">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="Time is now %timeIsNow and my name is %whatIsMyName, %m%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="org.apache.log4j.xml" level="all" />
        <Root level="all">
            <AppenderRef ref="STDOUT" />
        </Root>
    </Loggers>
</Configuration>
</code>```

Provide log4j2.xml.

And create a sample Main class to test it.

```<code>public class Main {
    private static final Logger logger = LogManager.getLogger(ResolverUtil.Test.class);
    public static void main(String[] args) {
        logger.info("Hello log4j2");
        logger.debug("This is debug message");
    }
}
</code>```

This will produce such an output:

```<code>Time is now 20:40 and my name is Yuriy, Hello log4j2
Time is now 20:40 and my name is Yuriy, This is debug message
</code>```

Body:
Refer to this manual https://logging.apache.org/log4j/log4j-2.2/manual/plugins.html#Converters

If you want several fields for example time and name you could create two separate Converters which will provide that data to the log.

For instance you have MyNamePatternConverter, here we can provide alias whatIsMyName and myName. In log pattern we can use any of those.

@Plugin(name="MyNamePatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys(value = {"whatIsMyName", "myName"})
public class MyNameConverter extends LogEventPatternConverter {

    protected MyNameConverter(String name, String style) {
        super(name, style);
    }

    public static MyNameConverter newInstance(String[] options) {
        return new MyNameConverter("My name Converter", "name");
    }

    public void format(LogEvent event, StringBuilder toAppendTo) {
        toAppendTo.append("Yuriy");
    }
}

and TimePatternConverter

@Plugin(name = "TimePatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys(value = {"timeIsNow", "timeNow", "now"})
public class TimeConverter extends LogEventPatternConverter {
    protected TimeConverter(String name, String style) {
        super(name, style);
    }

    public static TimeConverter newInstance(String[] options) {
        return new TimeConverter("Time Converter", "now");
    }

    public void format(LogEvent logEvent, StringBuilder toAppendTo) {
        toAppendTo.append(new SimpleDateFormat("HH:mm").format(new Date()));
    }
}

We will put them two in separate package called converters.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns="http://logging.apache.org/log4j/2.0/config"
               status="OFF" packages="converters">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="Time is now %timeIsNow and my name is %whatIsMyName, %m%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="org.apache.log4j.xml" level="all" />
        <Root level="all">
            <AppenderRef ref="STDOUT" />
        </Root>
    </Loggers>
</Configuration>

Provide log4j2.xml.

And create a sample Main class to test it.

public class Main {
    private static final Logger logger = LogManager.getLogger(ResolverUtil.Test.class);
    public static void main(String[] args) {
        logger.info("Hello log4j2");
        logger.debug("This is debug message");
    }
}

This will produce such an output:

Time is now 20:40 and my name is Yuriy, Hello log4j2
Time is now 20:40 and my name is Yuriy, This is debug message


问:
Java Web Service framework/library, which is a better one and why?
Currently I am evaluating number of web service frameworks in Java. I need web service framework that will help me to expose some functionality of existent application running on JBoss, The application is mostly developed using Spring and POJOs (no EJBs).

What I need is a framework having following properties:

It should provide tools for automatic generation of boilerplate code and save time by eliminating repetitive tasks, for example tools generating WSDL from Java (java2wsdl), tools generating endpoints etc.

Applications should be easily deployed on existent J2EE platform (JBoss), this means that it should contain as less as possible configuration files (like axis2.xml in axis2 framework).

Also it is preferred to be able to deploy web service within  .war archive of existent application. (it seems that Axis2 need a separate archive for web service app.)

It will be very cool to use a combination of POJOs and Spring.

Generally, the framework should have clean structure and design (for example Spring-WS lacks it), good documentation and whatever else characterizes a good piece of software.

It is preferred that framework incorporates some standard features like JAX-WS etc. instead of vendor specific methods.

I have briefly examined

Axis2

Apache CXF

and Sun's Metro

Spring WS

But still it is difficult to decide what to use in my case:

Axis2 seems to be so low level, it requires separate application archive and lots of configurations

Spring WS seems to be too opaque and "sophisticated for impression purposes (?)"

Apache CXF and Metro probably are two frameworks that I prefer to chose from but still

I need your opinion and experience about usage of some of them in a real-world applications.

答: XFire now Apache CXF was far away easier to use than Axis.  I had something done very quickly using it where Axis seemed overly complicated.  I didn't look at Spring WS.</p>

OwnerDisplayName: Tom H


问:
Multiple join in Entity Framework and include all data
I want to write a query in Entity Framework that has multiple joins.  The only problem is the tables arn't related using their primary / foreign keys (its the Umbraco database), as such I can't use .Include and the Navigation properties.

Essentially the query I would like to run is this:

```<code>select t.*, n.* from cmsContentType t
inner join cmsContentTypeAllowedContentType a on t.nodeId = a.Id
inner join vicinity.DocumentTypeExtendedProperty x on x.UmbracoDocumentTypeId = t.pk
inner join umbracoNode n on n.id = t.nodeId
</code>```

I have two EF entities mapped to cmsContentType and umbracoNode as such I would like them to be populated as if I was running the query like

```<code>var q = from p in cmsContentType.Include("umbracoNode")
</code>```

How can this be done

答:
Above answers are both correct.

However, to simplify things - why not create a view?

The view could do those joins you wanted, then your LINQ query becomes as easy as pie:

```<code>var q = from x in objectContext.myFunkySpecialView
        select x;
</code>```

Body:
I want to write a query in Entity Framework that has multiple joins.  The only problem is the tables arn't related using their primary / foreign keys (its the Umbraco database), as such I can't use .Include and the Navigation properties.

Essentially the query I would like to run is this:

select t.*, n.* from cmsContentType t
inner join cmsContentTypeAllowedContentType a on t.nodeId = a.Id
inner join vicinity.DocumentTypeExtendedProperty x on x.UmbracoDocumentTypeId = t.pk
inner join umbracoNode n on n.id = t.nodeId

I have two EF entities mapped to cmsContentType and umbracoNode as such I would like them to be populated as if I was running the query like

var q = from p in cmsContentType.Include("umbracoNode")

How can this be done

Body:
Above answers are both correct.

However, to simplify things - why not create a view?

The view could do those joins you wanted, then your LINQ query becomes as easy as pie:

var q = from x in objectContext.myFunkySpecialView
        select x;


问:
JavaEE EJB injection cannot be resolved
I set up an Enterprise Application Project with two modules: an EJB Project and a Web Project.

The web project contains a servlet in which I want to inject an EJB from the EJB Project.

The former looks like this:

```<code>@WebServlet("/OutputServlet")
public class OutputServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

@EJB
UserEJB userejb;

.
.
.
</code>```

And the latter like this:

```<code>@Stateless
@LocalBean
public class UserEJB {

/**
 * Default constructor.
 */
public UserEJB() {
    // TODO Auto-generated constructor stub
}
.
.
.
</code>```

The "UserEJB" part in the line UserEJB userejb; is marked as faulty in eclipse, with the message that UserEJB cannot be resolved to a type.

It might be worth mentioning that I am running all this on Wildfly 10.0

Here is the application.xml of the Application Project:

```<code><?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/application_7.xsd" id="Application_ID"
version="7">
  <display-name>SecondTest</display-name>
  <module>
    <ejb>SecondEJB.jar</ejb>
  </module>
  <module>
    <web>
      <web-uri>SecondWeb.war</web-uri>
      <context-root>SecondWeb</context-root>
    </web>
  </module>
</application>
</code>```

答: Apparently eclipse does not add the EJB Project to the build path automatically. Doing it fixes the problem</p>

Title: JavaEE EJB injection cannot be resolved

Body:
I set up an Enterprise Application Project with two modules: an EJB Project and a Web Project.

The web project contains a servlet in which I want to inject an EJB from the EJB Project.

The former looks like this:

@WebServlet("/OutputServlet")
public class OutputServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

@EJB
UserEJB userejb;

.
.
.

And the latter like this:

@Stateless
@LocalBean
public class UserEJB {

/**
 * Default constructor.
 */
public UserEJB() {
    // TODO Auto-generated constructor stub
}
.
.
.

The "UserEJB" part in the line UserEJB userejb; is marked as faulty in eclipse, with the message that UserEJB cannot be resolved to a type.

It might be worth mentioning that I am running all this on Wildfly 10.0

Here is the application.xml of the Application Project:

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/application_7.xsd" id="Application_ID"
version="7">
  <display-name>SecondTest</display-name>
  <module>
    <ejb>SecondEJB.jar</ejb>
  </module>
  <module>
    <web>
      <web-uri>SecondWeb.war</web-uri>
      <context-root>SecondWeb</context-root>
    </web>
  </module>
</application>


问:
Pandas create Foreign ID column based on Name column
I have a simple dataframe like this for example:

```<code>df = pd.DataFrame({'Name': ['John Doe', 'Jane Smith', 'John Doe', 'Jane Smith','Jack Dawson','John Doe']})
df:
        Name
    0   John Doe
    1   Jane Smith
    2   John Doe
    3   Jane Smith
    4   Jack Dawson
    5   John Doe
</code>```

I want to add a column ['foreign_key'] that assigns a unique ID to each unique name (but rows with the same name should have the same 'foreign_key'. So the final output looks like:

```<code>df:
            Name        Foreign_Key
        0   John Doe    foreignkey1
        1   Jane Smith  foreignkey2
        2   John Doe    foreignkey1
        3   Jane Smith  foreignkey2
        4   Jack Dawson foreignkey3
        5   John Doe    foreignkey1
</code>```

I'm trying to use groupby with a custom function that is applied.
So my first step is:

```<code>name_groupby = df.groupby('Name')
</code>```

So that's the splitting, and next comes the apply and combine. There doesn't appear to be anything in the docs like this example and I'm unsure where to go from here.

The custom function I started to apply looks like this:

```<code>def make_foreign_key(groupby_df):
    return groupby_df['Foreign_Key'] = 'foreign_key' + num
</code>```

Any help is greatly appreciated!

答:
I faced the same problem short time ago and my solution looked like the following:

```<code>import pandas as pd
import numpy as np
values = df['Name'].unique()
values = pd.Series(np.arange(len(values)), values)
df['new_column'] = df['Name'].apply(values.get)
</code>```

The output:

```<code>          Name  new_column
0     John Doe           0
1   Jane Smith           1
2     John Doe           0
3   Jane Smith           1
4  Jack Dawson           2
5     John Doe           0
</code>```

Body:
I have a simple dataframe like this for example:

df = pd.DataFrame({'Name': ['John Doe', 'Jane Smith', 'John Doe', 'Jane Smith','Jack Dawson','John Doe']})
df:
        Name
    0   John Doe
    1   Jane Smith
    2   John Doe
    3   Jane Smith
    4   Jack Dawson
    5   John Doe

I want to add a column ['foreign_key'] that assigns a unique ID to each unique name (but rows with the same name should have the same 'foreign_key'. So the final output looks like:

df:
            Name        Foreign_Key
        0   John Doe    foreignkey1
        1   Jane Smith  foreignkey2
        2   John Doe    foreignkey1
        3   Jane Smith  foreignkey2
        4   Jack Dawson foreignkey3
        5   John Doe    foreignkey1

I'm trying to use groupby with a custom function that is applied.
So my first step is:

name_groupby = df.groupby('Name')

So that's the splitting, and next comes the apply and combine. There doesn't appear to be anything in the docs like this example and I'm unsure where to go from here.

The custom function I started to apply looks like this:

def make_foreign_key(groupby_df):
    return groupby_df['Foreign_Key'] = 'foreign_key' + num

Any help is greatly appreciated!

Body:
I faced the same problem short time ago and my solution looked like the following:

import pandas as pd
import numpy as np
values = df['Name'].unique()
values = pd.Series(np.arange(len(values)), values)
df['new_column'] = df['Name'].apply(values.get)

The output:

          Name  new_column
0     John Doe           0
1   Jane Smith           1
2     John Doe           0
3   Jane Smith           1
4  Jack Dawson           2
5     John Doe           0


问:
insert user info into the databasa php and mysql
hi guys please l need some help. lm setting up a user registration sign up form. but l was NOT ABLE TO INSERT THE USER INFO IN TO THE DATABASE. And the code did not display any error message, meaning that everything is fine.
But when l tried to sign up it gives the form's error message "Failed to Register User".

this is the code: (and check at the bottom the connect.php code)

```<code><?php

require_once('connect.php');
//print_r($_POST);
if(isset($_POST) & !empty($_POST)) {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    // storing the sign up info in to the database
    $sql = "INSERT INTO usermanagement (username, email, password) VALUES ('$username', '$email', '$password')";

    //executing the query
    $result = mysqli_query($connection, $sql);

    if($result){
        echo "User Registered Successfully";
    }
    else{
        echo "Failed to Register User";
    }
}

?>

    <div id="form-signup">
                    <form id="signup-form" name="sign-up" action="sign.php" method="POST">
                            <h1>Create your profile</h1>
                            <p>
                                <input type="text" name="username" id="username" class="signup-input" required="required" placeholder="Full name*" >
                            </p>

                            <p>
                                <input type="email" name="email" class="signup-input" required="required" placeholder="Email*" >
                            </p>
                            <p>
                                <input type="password" name="password" class="signup-input" required="required" placeholder="Mot de passe*">
                            </p>
                            <!-- <p>
                                <input type="password" name="confirmpassword" class="signup-input" required="required" placeholder="Confirmez mot de passe*">
                            </p> -->
                            <p class="agree"> By signing up, you agree to Tout-Passe's <br><a href="condition.php"> Terms of use</a><br> and <a href="politic.php">Privacy Policy</a>.
                            </p>
                            <p>
                                <input type="submit" class="signup-btn" name="btn-signup" value="Create Account">
                            </p>
                            <p class="already">Already on Tout-Passe? <a href="log.php"> Log in</a></p>
                        </div><!--END OF PHASE-1-->
                    </form> <!--END OF SIGN-UP-->
                </div><!--END FO ALLFORM-->
</code>```

CONNECT CODE

```<code><?php
$connection = mysqli_connect('localhost', 'root', '');
if(!$connection){
    die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'listing');//listing = database
if(!$select_db){
    die("Failed to select database" . mysqli_error($connection));
}

?>
</code>```

答:
You did a mistake line 4, if(isset($_POST) & !empty($_POST)) { you have only one & you should have two like this: if(isset($_POST) && !empty($_POST)) {

Beside this, when your message tell you that it failed to register the user, it does not explain why, to solve this you have to add a mysqli_error() like this:

```<code>require_once('connect.php');
//print_r($_POST);
if(isset($_POST) && !empty($_POST)) {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    // storing the sign up info in to the database
    $sql = "INSERT INTO usermanagement (username, email, password) VALUES ('$username', '$email', '$password')";

    //executing the query
    $result = mysqli_query($connection, $sql);

    if($result){
        echo "User Registered Successfully";
    }
    else{
        echo "Failed to Register User, reason: " . mysqli_error($connection);
    }
}
</code>```

Also there is two problems with your code:

It is faillibe to SQL injection. What is SQL injection?

You should test each of your global variables are set individually like this: if(isset($_POST['username']) && !empty($_POST['username'])) and not like this: if(isset($_POST) && !empty($_POST))

Body:
hi guys please l need some help. lm setting up a user registration sign up form. but l was NOT ABLE TO INSERT THE USER INFO IN TO THE DATABASE. And the code did not display any error message, meaning that everything is fine.
But when l tried to sign up it gives the form's error message "Failed to Register User".

this is the code: (and check at the bottom the connect.php code)

<?php

require_once('connect.php');
//print_r($_POST);
if(isset($_POST) & !empty($_POST)) {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    // storing the sign up info in to the database
    $sql = "INSERT INTO usermanagement (username, email, password) VALUES ('$username', '$email', '$password')";

    //executing the query
    $result = mysqli_query($connection, $sql);

    if($result){
        echo "User Registered Successfully";
    }
    else{
        echo "Failed to Register User";
    }
}

?>

                    <form id="signup-form" name="sign-up" action="sign.php" method="POST">

Create your profile

                                <input type="text" name="username" id="username" class="signup-input" required="required" placeholder="Full name*" >

                                <input type="email" name="email" class="signup-input" required="required" placeholder="Email*" >

                                <input type="password" name="password" class="signup-input" required="required" placeholder="Mot de passe*">

 By signing up, you agree to Tout-Passe's
 Terms of use
 and Privacy Policy.

                                <input type="submit" class="signup-btn" name="btn-signup" value="Create Account">

Already on Tout-Passe?  Log in

                    </form>

CONNECT CODE

<?php
$connection = mysqli_connect('localhost', 'root', '');
if(!$connection){
    die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'listing');//listing = database
if(!$select_db){
    die("Failed to select database" . mysqli_error($connection));
}

?>

Body:
You did a mistake line 4, if(isset($_POST) & !empty($_POST)) { you have only one & you should have two like this: if(isset($_POST) && !empty($_POST)) {

Beside this, when your message tell you that it failed to register the user, it does not explain why, to solve this you have to add a mysqli_error() like this:

require_once('connect.php');
//print_r($_POST);
if(isset($_POST) && !empty($_POST)) {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    // storing the sign up info in to the database
    $sql = "INSERT INTO usermanagement (username, email, password) VALUES ('$username', '$email', '$password')";

    //executing the query
    $result = mysqli_query($connection, $sql);

    if($result){
        echo "User Registered Successfully";
    }
    else{
        echo "Failed to Register User, reason: " . mysqli_error($connection);
    }
}

Also there is two problems with your code:

It is faillibe to SQL injection. What is SQL injection?

You should test each of your global variables are set individually like this: if(isset($_POST['username']) && !empty($_POST['username'])) and not like this: if(isset($_POST) && !empty($_POST))


问:
Confusion about Printing string arrays in C
This is probably a beginner question but it has been confusing me.  I understand that in c an array is itself a pointer to the first element of the array.  So consider the following example

```<code>char *words[LENGTH];
words[0] = "zero";
words[1] = "one";
words[2] = "two";
printf("%s\n",*words);
</code>```

What ends up printing is zero.  However, my understanding is that words is a pointer to the first element of the words array which is a char pointer => words is a pointer to a pointer to a char.  Therefore *words would be a pointer to char.  Therefore I would expect a memory address to be printed here and not an actual string.  What am I misunderstanding here?

答:
I understand that in c an array is itself a pointer to the first element of the array.

This is not correct - under most circumstances, an expression  of type "N-element array of T" will be converted to an expression of type "pointer to T", but an array object itself is not a pointer.  No storage is set aside for a pointer as part of an array object.

The string literal "zero" has type "5-element array of char", while both "one" and "two" have types "4-element array of char" (because strings are terminated with a zero-valued character, you need N+1 elements to store an N-character string).

Each string literal is an array expression, but since these expressions are not operands of the sizeof or unary & operators, and since they arent being used to initialize a character array, each expression is converted to a pointer expression, and the value of each expression is the address of the first element of the array.

Therefore I would expect a memory address to be printed here and not an actual string. What am I misunderstanding here?

The %s conversion specifer tells printf to print the sequence of characters beginning at the specified address until it sees a string terminator - that's why you see zero as the output and not an address.  To print a pointer value, you'd use the %p conversion specifier like so:

```<code>printf( "%p\n", (void *) *words );
</code>```

Body:
This is probably a beginner question but it has been confusing me.  I understand that in c an array is itself a pointer to the first element of the array.  So consider the following example

char *words[LENGTH];
words[0] = "zero";
words[1] = "one";
words[2] = "two";
printf("%s\n",*words);

What ends up printing is zero.  However, my understanding is that words is a pointer to the first element of the words array which is a char pointer => words is a pointer to a pointer to a char.  Therefore *words would be a pointer to char.  Therefore I would expect a memory address to be printed here and not an actual string.  What am I misunderstanding here?

Body:
I understand that in c an array is itself a pointer to the first element of the array.

This is not correct - under most circumstances, an expression  of type "N-element array of T" will be converted to an expression of type "pointer to T", but an array object itself is not a pointer.  No storage is set aside for a pointer as part of an array object.

The string literal "zero" has type "5-element array of char", while both "one" and "two" have types "4-element array of char" (because strings are terminated with a zero-valued character, you need N+1 elements to store an N-character string).

Each string literal is an array expression, but since these expressions are not operands of the sizeof or unary & operators, and since they arent being used to initialize a character array, each expression is converted to a pointer expression, and the value of each expression is the address of the first element of the array.

Therefore I would expect a memory address to be printed here and not an actual string. What am I misunderstanding here?

The %s conversion specifer tells printf to print the sequence of characters beginning at the specified address until it sees a string terminator - that's why you see zero as the output and not an address.  To print a pointer value, you'd use the %p conversion specifier like so:

printf( "%p\n", (void *) *words );


问:
SQLite-Net-PCL Deadlock issue
I am using SQLite-PCL with Xamarin.Android for data storage. I am using it asynchronously, and am experiencing a deadlock issue because of this.

The implementation is contained in a DataHandler class:

Constructor

```<code>public DataHandler(string path)
{
      _db = new SQLiteAsyncConnection(path);
      Initialize().Wait();
}
</code>```

Initialize Function

```<code>private async Task Initialize()
{
    using (await Lock())
    {
        await _db.CreateTableAsync<Person>();
        await _db.CreateTableAsync<Animal>();
    }
 }
</code>```

And lastly, that Lock() function is an implementation of the answer at the question here: https://stackoverflow.com/a/44127898/3808312

When the object is constructed, Initialize().Wait() is called and deadlocks on the first call to CreateTableAsync() and unfortunately, I can't really debug into the library without touching the disassembly of it. Am I using async pattern wrong or something? And yes, I do know that Wait() is synchronous. That was just to keep the same format as the other methods in the class.

答:
For issues like this, a frequent pattern is to create the affected class using an async factory method.

```<code>public class DataHandler {

    //...other code

    private DataHandler() {

    }

    private async Task InitializeAsync(string path) {
        _db = new SQLiteAsyncConnection(path);
        using (await Lock()) {
            await _db.CreateTableAsync<Person>();
            await _db.CreateTableAsync<Animal>();
        }
    }

    public static async Task<DataHandler> CreateDataHandler(string path) {
        var handler = new DataHandler();
        await handler.InitializeAsync(path);
        return handler;
    }

    //...other code
}
</code>```

and then use it in a manner that allows async calls.

```<code>var handler = await DataHandler.CreateDataHandler("<path here>");
</code>```

Like in the OnAppearing virtual method where you can subscribe to the Appearing event of the page/view

```<code>protected override void OnAppearing() {
    this.Appearing += Page_Appearing;
}
</code>```

and call your async code on an actual even handler

```<code>private async void Page_Appearing(object sender, EventArgs e) {
    //...call async code here
    var handler = await DataHandler.CreateDataHandler("<path here>");
    //..do what you need to do with the handler.

    //unsubscribing from the event
    this.Appearing -= Page_Appearing;
}
</code>```

Title: SQLite-Net-PCL Deadlock issue

Body:
I am using SQLite-PCL with Xamarin.Android for data storage. I am using it asynchronously, and am experiencing a deadlock issue because of this.

The implementation is contained in a DataHandler class:

Constructor

public DataHandler(string path)
{
      _db = new SQLiteAsyncConnection(path);
      Initialize().Wait();
}

Initialize Function

private async Task Initialize()
{
    using (await Lock())
    {
        await _db.CreateTableAsync<Person>();
        await _db.CreateTableAsync<Animal>();
    }
 }

And lastly, that Lock() function is an implementation of the answer at the question here: https://stackoverflow.com/a/44127898/3808312

When the object is constructed, Initialize().Wait() is called and deadlocks on the first call to CreateTableAsync() and unfortunately, I can't really debug into the library without touching the disassembly of it. Am I using async pattern wrong or something? And yes, I do know that Wait() is synchronous. That was just to keep the same format as the other methods in the class.

Body:
For issues like this, a frequent pattern is to create the affected class using an async factory method.

public class DataHandler {

    //...other code

    private DataHandler() {

    }

    private async Task InitializeAsync(string path) {
        _db = new SQLiteAsyncConnection(path);
        using (await Lock()) {
            await _db.CreateTableAsync<Person>();
            await _db.CreateTableAsync<Animal>();
        }
    }

    public static async Task<DataHandler> CreateDataHandler(string path) {
        var handler = new DataHandler();
        await handler.InitializeAsync(path);
        return handler;
    }

    //...other code
}

and then use it in a manner that allows async calls.

var handler = await DataHandler.CreateDataHandler("<path here>");

Like in the OnAppearing virtual method where you can subscribe to the Appearing event of the page/view

protected override void OnAppearing() {
    this.Appearing += Page_Appearing;
}

and call your async code on an actual even handler

private async void Page_Appearing(object sender, EventArgs e) {
    //...call async code here
    var handler = await DataHandler.CreateDataHandler("<path here>");
    //..do what you need to do with the handler.

    //unsubscribing from the event
    this.Appearing -= Page_Appearing;
}


问:
Spring @Scheduled timer accuracy
I'm using spring-boot @Scheduled annotation with fixedDelay in milliseconds as documented in javadoc:

Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.

Code:

```<code>@Scheduled(fixedDelay=1000)
public void task() {
    LOG.info("START: " + System.currentTimeInMillis());
    ....do some work here...
    LOG.info("END: " + System.currentTimeInMillis());
}
</code>```

And sometimes I get such output that time between previous task end and next task starts is less than 1000ms for about 2-30 milliseconds.

Is it normal due to some granularity or why is it happening? Is there any guaranties about this delta value?

答: How @Scheduled(fixedDelay=1000) works is, it will run this void method every 1000 ms(If this task finish execution < 1000 ms or this will run asynchronously). If > 1000ms it the execution task will get into a task queue in the Executor service used. There is no connection with the end of task and the start of next task  but a connection with the start of a task and start of a next task.

Title: Spring @Scheduled timer accuracy

Body:
I'm using spring-boot @Scheduled annotation with fixedDelay in milliseconds as documented in javadoc:

Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.

Code:

@Scheduled(fixedDelay=1000)
public void task() {
    LOG.info("START: " + System.currentTimeInMillis());
    ....do some work here...
    LOG.info("END: " + System.currentTimeInMillis());
}

And sometimes I get such output that time between previous task end and next task starts is less than 1000ms for about 2-30 milliseconds.

Is it normal due to some granularity or why is it happening? Is there any guaranties about this delta value?


问:
How can I center the loading div before load() with jQuery?
I have this code:

```<code>$("#result").html('<div class="loading">Loading results...</div>');
$("#result").load('<?php bloginfo('template_directory'); ?>/GetResults.php?' + $.cookie('nw-query'));
</code>```

It shows the loading div until the load is done. What I want to do here, I want the loading div exactly in the center of the page/document?

That's extra but could be nice - can I also fade the document until the load is done so that the loading div stands out?

Any jquery/css suggestions are welcome.

Thank you :)

答:
```<code>.loading {
    width:200px;
    height:50px;
    background:#CCC;
    position:absolute;
    top:50%;
    left:50%;
    margin:-25px 0 0 -100px; /* Half of height and width */
    }
</code>```

If you don't know width/height or it is dynamic, you can use .width() and .height() functions to get values, which should be divided by 2.

Body:
I have this code:

$("#result").html('
Loading results...
');
$("#result").load('<?php bloginfo('template_directory'); ?>/GetResults.php?' + $.cookie('nw-query'));

It shows the loading div until the load is done. What I want to do here, I want the loading div exactly in the center of the page/document?

That's extra but could be nice - can I also fade the document until the load is done so that the loading div stands out?

Any jquery/css suggestions are welcome.

Thank you :)

Body:
.loading {
    width:200px;
    height:50px;
    background:#CCC;
    position:absolute;
    top:50%;
    left:50%;
    margin:-25px 0 0 -100px; /* Half of height and width */
    }

If you don't know width/height or it is dynamic, you can use .width() and .height() functions to get values, which should be divided by 2.


问:
To find the value of the last element of a panel using it's name in JQuery
I have a panel which has rows of hidden inputs. I need to find the value of the last input. I tried using JQuery but I am getting an error. Basically I should get the value 2. What am I missing?

var test = $(".panel-body  input[name=Organizations.Index]").last().val();

        console.log(test);```
<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>
<div class="panel-body" style="overflow-y:auto;max-height:400px;min-height:50px" id="divSelOrgs">
    <div class="row">
        <input type="hidden" name="Organizations.Index" value="0">
    </div>
    <div class="row">
        <input type="hidden" name="Organizations.Index" value="1">
    </div>
    <div class="row">
         <input type="hidden" name="Organizations.Index" value="2">
     </div>
</div></code>```

答:
You need to quote the attribute like [name="Organizations.Index"]'

var test = $('.panel-body  input[name="Organizations.Index"]').last().val();
console.log(test);```
<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>
<div class="panel-body" style="overflow-y:auto;max-height:400px;min-height:50px" id="divSelOrgs">
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="0">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="1">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="2">
  </div>
</div></code>```

As the documentation on selectors says:

To use any of the meta-characters ( such as
  !"#$%&'()*+,./:;<=>?@[\]^{|}~` ) as a literal part of a name, it must
  be escaped with with two backslashes: \\.

So you could also skip the quotes and escape the . instead (I find the above method easier to read and less error-prone):

var test = $(".panel-body  input[name=Organizations\\.Index]").last().val();
console.log(test);```
<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>
<div class="panel-body" style="overflow-y:auto;max-height:400px;min-height:50px" id="divSelOrgs">
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="0">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="1">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="2">
  </div>
</div></code>```

Body:
I have a panel which has rows of hidden inputs. I need to find the value of the last input. I tried using JQuery but I am getting an error. Basically I should get the value 2. What am I missing?

var test = $(".panel-body  input[name=Organizations.Index]").last().val();

        console.log(test);

        <input type="hidden" name="Organizations.Index" value="0">

        <input type="hidden" name="Organizations.Index" value="1">

         <input type="hidden" name="Organizations.Index" value="2">

Body:
You need to quote the attribute like [name="Organizations.Index"]'

var test = $('.panel-body  input[name="Organizations.Index"]').last().val();
console.log(test);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-body" style="overflow-y:auto;max-height:400px;min-height:50px" id="divSelOrgs">
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="0">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="1">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="2">
  </div>
</div>

As the documentation on selectors says:

To use any of the meta-characters ( such as
  !"#$%&'()*+,./:;<=>?@[\]^{|}~` ) as a literal part of a name, it must
  be escaped with with two backslashes: \\.

So you could also skip the quotes and escape the . instead (I find the above method easier to read and less error-prone):

var test = $(".panel-body  input[name=Organizations\\.Index]").last().val();
console.log(test);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-body" style="overflow-y:auto;max-height:400px;min-height:50px" id="divSelOrgs">
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="0">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="1">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="2">
  </div>
</div>


问:
PointToScreen incorrect using DesktopDPIOverride
Setting the "Change the size of all items" slider of Control Panel\Appearance and Personalization\Display to Larger (which changes this registry entry: HKEY_CURRENT_USER\Control Panel\Desktop\DesktopDPIOverride) causes the Control.PointToScreen() method to miscalculate. This can be reproduced using the following Class1 in a Windows Form:

```<code>public class Class1 : Control
{
  protected override void OnPaint(PaintEventArgs e)
  {
    base.OnPaint(e);

    Draw(e.ClipRectangle, e.Graphics);
  }

  private void Draw(Rectangle rect, Graphics graphics)
  {
    Pen pen = new Pen(Color.Red);
    pen.Width = 2;

    graphics.DrawRectangle(pen, rect);
  }

  protected override void OnMouseDown(MouseEventArgs e)
  {
    base.OnMouseDown(e);

    Point p = this.PointToScreen(new Point(0, 0));

    ControlPaint.DrawReversibleFrame(new Rectangle(p, new Size(e.X, e.Y)), Color.Yellow, FrameStyle.Dashed);
  }

  protected override void OnMouseUp(MouseEventArgs e)
  {
    base.OnMouseUp(e);
    this.Invalidate();
  }
}
</code>```

Using this control in a WinForm and clicking on it works as expected. Now change "Change the size of all items" to "Larger" and run the code again - the code no longer runs as expected, the PointToScreen method is returning an erroneous value for (0, 0).

Does anybody know how to resolve this issue? Many thanks.

答:
Sounds like you need to make it DPI aware. You can do it like so</p>

```<code>[DllImport("user32.dll")]
private static extern bool SetProcessDPIAware();

static void Main()
{
    SetProcessDPIAware();

}
</code>```

Body:
Setting the "Change the size of all items" slider of Control Panel\Appearance and Personalization\Display to Larger (which changes this registry entry: HKEY_CURRENT_USER\Control Panel\Desktop\DesktopDPIOverride) causes the Control.PointToScreen() method to miscalculate. This can be reproduced using the following Class1 in a Windows Form:

public class Class1 : Control
{
  protected override void OnPaint(PaintEventArgs e)
  {
    base.OnPaint(e);

    Draw(e.ClipRectangle, e.Graphics);
  }

  private void Draw(Rectangle rect, Graphics graphics)
  {
    Pen pen = new Pen(Color.Red);
    pen.Width = 2;

    graphics.DrawRectangle(pen, rect);
  }

  protected override void OnMouseDown(MouseEventArgs e)
  {
    base.OnMouseDown(e);

    Point p = this.PointToScreen(new Point(0, 0));

    ControlPaint.DrawReversibleFrame(new Rectangle(p, new Size(e.X, e.Y)), Color.Yellow, FrameStyle.Dashed);
  }

  protected override void OnMouseUp(MouseEventArgs e)
  {
    base.OnMouseUp(e);
    this.Invalidate();
  }
}

Using this control in a WinForm and clicking on it works as expected. Now change "Change the size of all items" to "Larger" and run the code again - the code no longer runs as expected, the PointToScreen method is returning an erroneous value for (0, 0).

Does anybody know how to resolve this issue? Many thanks.

Body:
Sounds like you need to make it DPI aware. You can do it like so

[DllImport("user32.dll")]
private static extern bool SetProcessDPIAware();

static void Main()
{
    SetProcessDPIAware();

}


答:
Use pseudo selector :last.

var test = $("input[name='Organizations.Index']:last").val();
console.log(test);```
<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>
<div class="panel-body" style="overflow-y:auto;max-height:400px;min-height:50px" id="divSelOrgs">
    <div class="row">
        <input type="hidden" name="Organizations.Index" value="0">
    </div>
    <div class="row">
        <input type="hidden" name="Organizations.Index" value="1">
    </div>
    <div class="row">
         <input type="hidden" name="Organizations.Index" value="2">
     </div>
</div></code>```

Title: To find the value of the last element of a panel using it's name in JQuery

Body:
Use pseudo selector :last.

var test = $("input[name='Organizations.Index']:last").val();
console.log(test);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-body" style="overflow-y:auto;max-height:400px;min-height:50px" id="divSelOrgs">
    <div class="row">
        <input type="hidden" name="Organizations.Index" value="0">
    </div>
    <div class="row">
        <input type="hidden" name="Organizations.Index" value="1">
    </div>
    <div class="row">
         <input type="hidden" name="Organizations.Index" value="2">
     </div>
</div>


答:
jQuery() needs to be defined. name attribute value at selector string needs to be quoted or escaped due to special character .

var test = $(".panel-body  input[name='Organizations.Index']").last().val();

console.log(test);```
<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>
<div class="panel-body" style="overflow-y:auto;max-height:400px;min-height:50px" id="divSelOrgs">
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="0">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="1">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="2">
  </div>
</div></code>```

var test = $(".panel-body  input[name=Organizations\\.Index]").last().val();

console.log(test);```
<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>
<div class="panel-body" style="overflow-y:auto;max-height:400px;min-height:50px" id="divSelOrgs">
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="0">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="1">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="2">
  </div>
</div></code>```

Body:
jQuery() needs to be defined. name attribute value at selector string needs to be quoted or escaped due to special character .

var test = $(".panel-body  input[name='Organizations.Index']").last().val();

console.log(test);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-body" style="overflow-y:auto;max-height:400px;min-height:50px" id="divSelOrgs">
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="0">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="1">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="2">
  </div>
</div>

var test = $(".panel-body  input[name=Organizations\\.Index]").last().val();

console.log(test);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-body" style="overflow-y:auto;max-height:400px;min-height:50px" id="divSelOrgs">
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="0">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="1">
  </div>
  <div class="row">
    <input type="hidden" name="Organizations.Index" value="2">
  </div>
</div>


问:
How can I center a tooltip above my control in Silverlight?
I want to be able to display a tooltip centered above my control.

I know how to customize the XAML used to display the tooltip using the TooltipService, however, the placement options the TooltipService makes available only allow you to specify top, bottom, left, right, etc. They don't let you specify an alignment once on the given side.

By simply using the TooltipService, selecting a placement of "Top" puts the tooltip above the control and has it aligned to the left side of the control. If there is not enough room for it to be aligned left, it moves it to be aligned on the right side of the control.

I want the tooltip to be centered on the top of the control. I don't want it to anchor to either the left or the right while on top.

Is this possible? How?

答:
A quick shot: you could create your own TooltipService class to extend the possibilities of the existing one to manipulate a Tooltip instance.

Here you can find a nice class to help position a popup by specifying a list of preferred positions, like the TooltipService does for tooltip. You can specify a Top placement with Center HorizontalAlignment. I know this isn't a tooltip but I thought you could check it out and use it to create a BetterTooltipService.


问:
PHP Database SELECT
I want to show me from the database ID and User (from table users), this is my code but i keep getint an errors.

```<code><?php
$conn = new mysqli('127.0.0.1','S024_V7','S024_V7','S024_V7');

$sql ="SELECT id, user FROM Users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<br> ID: ". $row["id"]. " - Name: ". $row["User"]."<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>
</code>```

Errors:
Parse error: syntax error, unexpected '""' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ';' in /Projekti/S024_V7/index.php on line 9

Notice: Trying to get property of non-object in /Projekti/S024_V7/index.php on line 7
0 results

答:
This is because you have used double quotes "" instead of single '' try this code it will solve your problem

```<code><?php
$conn = new mysqli('127.0.0.1','S024_V7','S024_V7','S024_V7');

$sql ="SELECT id, user FROM Users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<br> ID: ". $row['id']. " - Name: ". $row['user']."<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>
</code>```

Title: PHP Database SELECT

Body:
I want to show me from the database ID and User (from table users), this is my code but i keep getint an errors.

<?php
$conn = new mysqli('127.0.0.1','S024_V7','S024_V7','S024_V7');

$sql ="SELECT id, user FROM Users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "
 ID: ". $row["id"]. " - Name: ". $row["User"]."
";
    }
} else {
    echo "0 results";
}

$conn->close();
?>

Errors:
Parse error: syntax error, unexpected '""' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ';' in /Projekti/S024_V7/index.php on line 9

Notice: Trying to get property of non-object in /Projekti/S024_V7/index.php on line 7
0 results

Body:
This is because you have used double quotes "" instead of single '' try this code it will solve your problem

<?php
$conn = new mysqli('127.0.0.1','S024_V7','S024_V7','S024_V7');

$sql ="SELECT id, user FROM Users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<br> ID: ". $row['id']. " - Name: ". $row['user']."<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>


问:
charAt(0) Not returning first number but second
Piglatin translator. at the end I am trying to get the location of the first vowel. Index is set to be the location of every vowel, but with pig latin you only need the location of the first vowel. When I run the program I don't always get the location of the first vowel. it seems to give me the second number and not the first. </p>

```<code>import java.util.Scanner;
import javax.swing.JOptionPane;

public class Assignment_4_Piglatin {

    public static void main(String[] args) {

        Scanner userWord = new Scanner(System.in);

        System.out.println("K. Caleb Swallow");
        System.out.println("Welcome to the Pig Latin Translator!");

        boolean run = true;
        while (run) {

            System.out.println("Please enter a word(or press Q to quit):");

            String firstLetter = "something";
            String firstVowel = "test";

            String word = userWord.next();
            String vowels = "aeiou";
            if (word.equals("Q")) {
                System.exit(0);
            }

            firstLetter = Character.toString(word.charAt(0));

            if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
                System.out.println(word + "way");
            } else {
                for (int index = 0; index < word.length(); index++) {
                    if (vowels.contains(String.valueOf(word.charAt(index)))) {
                        System.out.print(index);
                        String firstNumber = Integer.toString(index);
                        firstVowel = Character.toString(firstNumber.charAt(0));

                    }
                }

            }
            System.out.println(firstVowel);
</code>```

答:
There are a few problems I can see off the bat, but the one that is likely causing this error is in these lines:

```<code>String firstNumber = Integer.toString(index);
firstVowel = Character.toString(firstNumber.charAt(0));
</code>```

Think about what this is doing. First, you are making a String out of the index value, then you are saying that the first vowel is at the 0th index of that string.

Think of this example: hello

The program will run and assign "4" to firstNumber and firstVowel which isn't what you want.

However, if you only have one vowel, your program will "work".

What happens if you have over ten vowels? I know this isn't a realistic example, but say it happens. Your program will assign the index of the last vowel to firstNumber (say it's 15), then it will assign the first character of that to firstVowel (1). This doesn't make much sense at all, does it, especially if you don't have a vowel in index 1.

The main problem you are encountering for words less than 10 letters in length is that you are not just outputting the second number, you are outputting the last one. One way I like to deal with this is to go through the code and put in print statements where I'm not sure what a certain value is. For example, I'd put another print statement in your loop which tells you what letter you're looking at, like so:

```<code>System.out.println("LETTER: "+ String.valueOf(word.charAt(index)));
</code>```

This will help you avoid confusion. The proper way to do this problem would be to use a break statement, such as in Darshan's answer. Alternatively, you could use the properties of the for loop:

```<code>firstVowel = "";
for (int index = 0; index < word.length() && firstVowel == ""; index++) {
CODE
}
</code>```

Note that the second part of the for loop is a conditional statement. You already know that this can be used to cycle through the word's characters, but you can insert any logical statement there that you want. For this example, I set the default value of firstVowel to "" (setting it to null is a faux-pas, but that's another story). Then, each time the loop runs, it checks to see if the value of firstVowel has been changed, which will of course happen on the first time a vowel is run through the loop.

So in short, you need to modify the two lines at the beginning of my post and you need to find a way to break your loop when you find the first vowel. One solution has been given here, and another in Darshan Mehta's post.

Body:
Piglatin translator. at the end I am trying to get the location of the first vowel. Index is set to be the location of every vowel, but with pig latin you only need the location of the first vowel. When I run the program I don't always get the location of the first vowel. it seems to give me the second number and not the first.

import java.util.Scanner;
import javax.swing.JOptionPane;

public class Assignment_4_Piglatin {

    public static void main(String[] args) {

        Scanner userWord = new Scanner(System.in);

        System.out.println("K. Caleb Swallow");
        System.out.println("Welcome to the Pig Latin Translator!");

        boolean run = true;
        while (run) {

            System.out.println("Please enter a word(or press Q to quit):");

            String firstLetter = "something";
            String firstVowel = "test";

            String word = userWord.next();
            String vowels = "aeiou";
            if (word.equals("Q")) {
                System.exit(0);
            }

            firstLetter = Character.toString(word.charAt(0));

            if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
                System.out.println(word + "way");
            } else {
                for (int index = 0; index < word.length(); index++) {
                    if (vowels.contains(String.valueOf(word.charAt(index)))) {
                        System.out.print(index);
                        String firstNumber = Integer.toString(index);
                        firstVowel = Character.toString(firstNumber.charAt(0));

                    }
                }

            }
            System.out.println(firstVowel);

Body:
There are a few problems I can see off the bat, but the one that is likely causing this error is in these lines:

String firstNumber = Integer.toString(index);
firstVowel = Character.toString(firstNumber.charAt(0));

Think about what this is doing. First, you are making a String out of the index value, then you are saying that the first vowel is at the 0th index of that string.

Think of this example: hello

The program will run and assign "4" to firstNumber and firstVowel which isn't what you want.

However, if you only have one vowel, your program will "work".

What happens if you have over ten vowels? I know this isn't a realistic example, but say it happens. Your program will assign the index of the last vowel to firstNumber (say it's 15), then it will assign the first character of that to firstVowel (1). This doesn't make much sense at all, does it, especially if you don't have a vowel in index 1.

The main problem you are encountering for words less than 10 letters in length is that you are not just outputting the second number, you are outputting the last one. One way I like to deal with this is to go through the code and put in print statements where I'm not sure what a certain value is. For example, I'd put another print statement in your loop which tells you what letter you're looking at, like so:

System.out.println("LETTER: "+ String.valueOf(word.charAt(index)));

This will help you avoid confusion. The proper way to do this problem would be to use a break statement, such as in Darshan's answer. Alternatively, you could use the properties of the for loop:

firstVowel = "";
for (int index = 0; index < word.length() && firstVowel == ""; index++) {
CODE
}

Note that the second part of the for loop is a conditional statement. You already know that this can be used to cycle through the word's characters, but you can insert any logical statement there that you want. For this example, I set the default value of firstVowel to "" (setting it to null is a faux-pas, but that's another story). Then, each time the loop runs, it checks to see if the value of firstVowel has been changed, which will of course happen on the first time a vowel is run through the loop.

So in short, you need to modify the two lines at the beginning of my post and you need to find a way to break your loop when you find the first vowel. One solution has been given here, and another in Darshan Mehta's post.


答:
Solved:</p>

```<code>    $sql = "SELECT idkorisnik, ime FROM korisnik";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<br> ID: ". $row["idkorisnik"]. " - Ime: ". $row["ime"]. " " . "<br>";
    }
} else {
    echo "0 results";
}
</code>```

Title: PHP Database SELECT

Body:
Solved:

    $sql = "SELECT idkorisnik, ime FROM korisnik";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<br> ID: ". $row["idkorisnik"]. " - Ime: ". $row["ime"]. " " . "<br>";
    }
} else {
    echo "0 results";
}


问:
how to profile application startup with visualvm
As far as i can tell, you can only profile a running application using VisualVM.

Does anyone know of a way to profile the launch and startup of a java application using VisualVM?

I'm convinced there must be a way, otherwise it would be a major oversight.

Hoping I've just misread the documentation.

Thanks, p.

答:
Are you setting up the profiling using the `-Xrunjdwp" command-line option? If so, that option has a "suspend" parameter for just this purpose:

True if the target VM is to be suspended immediately before the main class is loaded; false otherwise.

Example from my own config:

```<code>-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
</code>```

I use this with the YourKit profiler, but I think the principle is the same.

Body:
Are you setting up the profiling using the `-Xrunjdwp" command-line option? If so, that option has a "suspend" parameter for just this purpose:

True if the target VM is to be suspended immediately before the main class is loaded; false otherwise.

Example from my own config:

-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

I use this with the YourKit profiler, but I think the principle is the same.


问:
In jquery, what's the difference between '.add()' and ',' (comma)?
I know that many things can be done in different ways, none of which necessarily and always better than others; So, having multiple ways to do the same is generally good: but, the jQuery '.add()' method and the jQuery comma selector are just two ways to do the same thing or differ from one another (in this particular use as selector)?

```<code> $("p").add("span").css("background", "yellow");
 $("p, span").css("background", "yellow");
</code>```

https://jsfiddle.net/rudijuri/gg3vfmcp/3/

(sorry for the external link to jsfiddle, but the snippet doesn't work using touch device, like mine now)

答:
Essentially they're the same. As the jQuery documentation on multiple selectors ((“selector1, selector2, selectorN”)) says (emphasis mine):

You can specify any number of selectors to combine into a single
  result. This multiple expression combinator is an efficient way to
  select disparate elements. The order of the DOM elements in the
  returned jQuery object may not be identical, as they will be in
  document order. An alternative to this combinator is the .add()
  method.

Body:
I know that many things can be done in different ways, none of which necessarily and always better than others; So, having multiple ways to do the same is generally good: but, the jQuery '.add()' method and the jQuery comma selector are just two ways to do the same thing or differ from one another (in this particular use as selector)?

 $("p").add("span").css("background", "yellow");
 $("p, span").css("background", "yellow");

https://jsfiddle.net/rudijuri/gg3vfmcp/3/

(sorry for the external link to jsfiddle, but the snippet doesn't work using touch device, like mine now)


问:
copy bytes without memcpy()
It's a home work. I want to implement memcpy(). I was told memory area must not overlap. Actually I don't understand what that means, because this code works fine, but there is a possibility of memory overlap. How to prevent it?

```<code>void *mem_copy(void *dest, const void *src, unsigned int n) {
    assert((src != NULL) && (n > 0));
    int i = 0;
    char *newsrc = (char*)src;
    char *newdest = (char*)dest;
    while (i < n) {
        newdest[i] = newsrc[i];
        i++;
    }
    newdest[i]='\0';
    return newdest;
}
</code>```

答:
When source and destination memory blocks overlap, and if your loop copies one element after the other starting from index 0, it works for dest < source, but not for dest > source (because you overwrite elements before having copied them) and vice versa.

Your code starts copying from index 0, so you can simply test which situations work and which not. See the following test code; It shows how moving a test string forward fails, whereas moving the string backwards works fine. Further, it shows how moving the test string forward works fine when copying from backward:

```<code>#include <stdio.h>
#include <string.h>

void *mem_copy(void *dest, const void *src, size_t n) {
    size_t i = 0;
    char* newsrc = (char*)src;
    char* newdest = (char*)dest;
    while(i < n) {
        newdest[i] = newsrc[i];
        i++;
    }
    return newdest;
}

void *mem_copy_from_backward(void *dest, const void *src, size_t n) {
    size_t i;
    char* newsrc = (char*)src;
    char* newdest = (char*)dest;
    for (i = n; i-- > 0;) {
        newdest[i] = newsrc[i];
    }
    return newdest;
}

int main() {

    const char* testcontent = "Hello world!";
    char teststr[100] = "";

    printf("move teststring two places forward:\n");
    strcpy(teststr, testcontent);
    size_t length = strlen(teststr);
    printf("teststr before mem_copy: %s\n", teststr);
    mem_copy(teststr+2, teststr, length+1);
    printf("teststr after mem_copy: %s\n", teststr);

    printf("\nmove teststring two places backward:\n");
    strcpy(teststr, testcontent);
    length = strlen(teststr);
    printf("teststr before mem_copy: %s\n", teststr);
    mem_copy(teststr, teststr+2, length+1);
    printf("teststr after mem_copy: %s\n", teststr);

    printf("move teststring two places forward using copy_from_backward:\n");
    strcpy(teststr, testcontent);
    length = strlen(teststr);
    printf("teststr before mem_copy: %s\n", teststr);
    mem_copy_from_backward(teststr+2, teststr, length+1);
    printf("teststr after mem_copy: %s\n", teststr);
}
</code>```

Output:

```<code>move teststring two places forward:
teststr before mem_copy: Hello world!
teststr after mem_copy: HeHeHeHeHeHeHeH

move teststring two places backward:
teststr before mem_copy: Hello world!
teststr after mem_copy: llo world!

move teststring two places forward using copy_from_backward:
teststr before mem_copy: Hello world!
teststr after mem_copy: HeHello world!
</code>```

So one could write one function, which decides whether to start copying from index 0 or from index n depending on whether the caller wants to copy forward or backward. The tricky thing is to find out whether the caller will copy forward or backward, since a pointer arithmetic on src and dest like if (src < dest) copy_from_backward(...) is actually not permitted in every case (cf. the standard, e.g. this draft):

6.5.9 Equality operators

When two pointers are compared, the result depends on the relative
  locations in the address space of the objects pointed to. If two
  pointers to object or incomplete types both point to the same object,
  or both point one past the last element of the same array object, they
  compare equal. If the objects pointed to are members of the same
  aggregate object, pointers to structure members declared later compare
  greater than pointers to members declared earlier in the structure,
  and pointers to array elements with larger subscript values compare
  greater than pointers to elements of the same array with lower
  subscript values. All pointers to members of the same union object
  compare equal. If the expression P points to an element of an array
  object and the expression Q points to the last element of the same
  array object, the pointer expression Q+1 compares greater than P. In
  all other cases, the behavior is undefined.

Though I've never been in a situation where src < dest did not give me the desired results, comparing two pointers this way is actually undefined behaviour if they do not belong to the same array.

Hence, if you ask "how to prevent it?", I think that the only correct answer must be: "It's subject to the caller, because function mem_copy cannot decide whether it may compare src and dest correctly."

Title: copy bytes without memcpy()

Body:
It's a home work. I want to implement memcpy(). I was told memory area must not overlap. Actually I don't understand what that means, because this code works fine, but there is a possibility of memory overlap. How to prevent it?

void *mem_copy(void *dest, const void *src, unsigned int n) {
    assert((src != NULL) && (n > 0));
    int i = 0;
    char *newsrc = (char*)src;
    char *newdest = (char*)dest;
    while (i < n) {
        newdest[i] = newsrc[i];
        i++;
    }
    newdest[i]='\0';
    return newdest;
}

Body:
When source and destination memory blocks overlap, and if your loop copies one element after the other starting from index 0, it works for dest < source, but not for dest > source (because you overwrite elements before having copied them) and vice versa.

Your code starts copying from index 0, so you can simply test which situations work and which not. See the following test code; It shows how moving a test string forward fails, whereas moving the string backwards works fine. Further, it shows how moving the test string forward works fine when copying from backward:

#include <stdio.h>
#include <string.h>

void *mem_copy(void *dest, const void *src, size_t n) {
    size_t i = 0;
    char* newsrc = (char*)src;
    char* newdest = (char*)dest;
    while(i < n) {
        newdest[i] = newsrc[i];
        i++;
    }
    return newdest;
}

void *mem_copy_from_backward(void *dest, const void *src, size_t n) {
    size_t i;
    char* newsrc = (char*)src;
    char* newdest = (char*)dest;
    for (i = n; i-- > 0;) {
        newdest[i] = newsrc[i];
    }
    return newdest;
}

int main() {

    const char* testcontent = "Hello world!";
    char teststr[100] = "";

    printf("move teststring two places forward:\n");
    strcpy(teststr, testcontent);
    size_t length = strlen(teststr);
    printf("teststr before mem_copy: %s\n", teststr);
    mem_copy(teststr+2, teststr, length+1);
    printf("teststr after mem_copy: %s\n", teststr);

    printf("\nmove teststring two places backward:\n");
    strcpy(teststr, testcontent);
    length = strlen(teststr);
    printf("teststr before mem_copy: %s\n", teststr);
    mem_copy(teststr, teststr+2, length+1);
    printf("teststr after mem_copy: %s\n", teststr);

    printf("move teststring two places forward using copy_from_backward:\n");
    strcpy(teststr, testcontent);
    length = strlen(teststr);
    printf("teststr before mem_copy: %s\n", teststr);
    mem_copy_from_backward(teststr+2, teststr, length+1);
    printf("teststr after mem_copy: %s\n", teststr);
}

Output:

move teststring two places forward:
teststr before mem_copy: Hello world!
teststr after mem_copy: HeHeHeHeHeHeHeH

move teststring two places backward:
teststr before mem_copy: Hello world!
teststr after mem_copy: llo world!

move teststring two places forward using copy_from_backward:
teststr before mem_copy: Hello world!
teststr after mem_copy: HeHello world!

So one could write one function, which decides whether to start copying from index 0 or from index n depending on whether the caller wants to copy forward or backward. The tricky thing is to find out whether the caller will copy forward or backward, since a pointer arithmetic on src and dest like if (src < dest) copy_from_backward(...) is actually not permitted in every case (cf. the standard, e.g. this draft):

6.5.9 Equality operators

When two pointers are compared, the result depends on the relative
  locations in the address space of the objects pointed to. If two
  pointers to object or incomplete types both point to the same object,
  or both point one past the last element of the same array object, they
  compare equal. If the objects pointed to are members of the same
  aggregate object, pointers to structure members declared later compare
  greater than pointers to members declared earlier in the structure,
  and pointers to array elements with larger subscript values compare
  greater than pointers to elements of the same array with lower
  subscript values. All pointers to members of the same union object
  compare equal. If the expression P points to an element of an array
  object and the expression Q points to the last element of the same
  array object, the pointer expression Q+1 compares greater than P. In
  all other cases, the behavior is undefined.

Though I've never been in a situation where src < dest did not give me the desired results, comparing two pointers this way is actually undefined behaviour if they do not belong to the same array.

Hence, if you ask "how to prevent it?", I think that the only correct answer must be: "It's subject to the caller, because function mem_copy cannot decide whether it may compare src and dest correctly."