问:
how to stop a java spell checker program from correcting repetitive words
I've implemented a program that does the following:

scan all of the words in a web page into a string (using jsoup)

Filter out all of the HTML markup and code

Put these words into a spell checking program and offer suggestions

The spell checking program loads a dictionary.txt file into an array and compares the string input to the words inside the dictionary.

My current problem is that when the input contains the same word multiple times, such as "teh program is teh worst", the code will print out

```<code>You entered 'teh', did you mean 'the'?
You entered 'teh', did you mean 'the'?
</code>```

Sometimes a website will have multiple words over and over again and this can become messy.

If it's possible, printing the word along with how many times it was spelled incorrectly would be perfect, but putting a limit to each word being printed once would be good enough.

My program has a handful of methods and two classes, but the spell checking method is below:

Note: the original code contains some 'if' statements that remove punctuation marks but I've removed them for clarity.

```<code>static boolean suggestWord;

public static String checkWord(String wordToCheck) {
        String wordCheck;
        String word = wordToCheck.toLowerCase();

    if ((wordCheck = (String) dictionary.get(word)) != null) {
        suggestWord = false; // no need to ask for suggestion for a correct
                                // word.
        return wordCheck;
    }

    // If after all of these checks a word could not be corrected, return as
    // a misspelled word.
    return word;
}
</code>```

TEMPORARY EDIT: As requested, the complete code:

Class 1:

```<code>public class ParseCleanCheck {

        static Hashtable<String, String> dictionary;// To store all the  words of the
        // dictionary
        static boolean suggestWord;// To indicate whether the word is spelled
                                    // correctly or not.

        static Scanner urlInput = new Scanner(System.in);
        public static String cleanString;
        public static String url = "";
        public static boolean correct = true;

        /**
         * PARSER METHOD
         */
        public static void PageScanner() throws IOException {
            System.out.println("Pick an english website to scan.");

            // This do-while loop allows the user to try again after a mistake
            do {
                try {
                    System.out.println("Enter a URL, starting with http://");
                    url = urlInput.nextLine();
                    // This creates a document out of the HTML on the web page
                    Document doc = Jsoup.connect(url).get();
                    // This converts the document into a string to be cleaned
                    String htmlToClean = doc.toString();
                    cleanString = Jsoup.clean(htmlToClean, Whitelist.none());

                    correct = false;
                } catch (Exception e) {
                    System.out.println("Incorrect format for a URL. Please try again.");
                }
            } while (correct);
        }

        /**
         * SPELL CHECKER METHOD
         */
        public static void SpellChecker() throws IOException {
            dictionary = new Hashtable<String, String>();
            System.out.println("Searching for spelling errors ... ");

            try {
                // Read and store the words of the dictionary
                BufferedReader dictReader = new BufferedReader(new FileReader("dictionary.txt"));

                while (dictReader.ready()) {
                    String dictInput = dictReader.readLine();
                    String[] dict = dictInput.split("\\s"); // create an array of
                                                            // dictionary words

                    for (int i = 0; i < dict.length; i++) {
                        // key and value are identical
                        dictionary.put(dict[i], dict[i]);
                    }
                }
                dictReader.close();
                String user_text = "";

                // Initializing a spelling suggestion object based on probability
                SuggestSpelling suggest = new SuggestSpelling("wordprobabilityDatabase.txt");

                // get user input for correction
                {

                    user_text = cleanString;
                    String[] words = user_text.split(" ");

                    int error = 0;

                    for (String word : words) {
                        if(!dictionary.contains(word)) {
                            checkWord(word);

                            dictionary.put(word, word);
                        }
                        suggestWord = true;
                        String outputWord = checkWord(word);

                        if (suggestWord) {
                            System.out.println("Suggestions for " + word + " are:  " + suggest.correct(outputWord) + "\n");
                            error++;
                        }
                    }

                    if (error == 0) {
                        System.out.println("No mistakes found");
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
                System.exit(-1);
            }
        }

        /**
         * METHOD TO SPELL CHECK THE WORDS IN A STRING. IS USED IN SPELL CHECKER
         * METHOD THROUGH THE "WORD" STRING
         */

        public static String checkWord(String wordToCheck) {
            String wordCheck;
            String word = wordToCheck.toLowerCase();

        if ((wordCheck = (String) dictionary.get(word)) != null) {
            suggestWord = false; // no need to ask for suggestion for a correct
                                    // word.
            return wordCheck;
        }

        // If after all of these checks a word could not be corrected, return as
        // a misspelled word.
        return word;
    }
    }
</code>```

There is a second class (SuggestSpelling.java) which holds a probability calculator but that isn't relevant right now, unless you planned on running the code for yourself.

答:
Use a HashSet to detect duplicates -

```<code>Set<String> wordSet = new HashSet<>();
</code>```

And store each word of the input sentence. If any word already exist during inserting into the HashSet, don't call checkWord(String wordToCheck) for that word. Something like this -

```<code>String[] words = // split input sentence into words
for(String word: words) {
    if(!wordSet.contains(word)) {
        checkWord(word);
        // do stuff
        wordSet.add(word);
    }
}
</code>```

Edit

```<code>// ....
{

    user_text = cleanString;
    String[] words = user_text.split(" ");
    Set<String> wordSet = new HashSet<>();

    int error = 0;

    for (String word : words) {
        // wordSet is another data-structure. Its only for duplicates checking, don't mix it with dictionary
        if(!wordSet.contains(word)) {

            // put all your logic here

            wordSet.add(word);
        }
    }

    if (error == 0) {
        System.out.println("No mistakes found");
    }
}
// ....
</code>```

You have other bugs as well like you are passing String wordCheck as argument of checkWord and re-declare it inside checkWord() again String wordCheck; which is not right. Please check the other parts as well.

Body:
I've implemented a program that does the following:

scan all of the words in a web page into a string (using jsoup)

Filter out all of the HTML markup and code

Put these words into a spell checking program and offer suggestions

The spell checking program loads a dictionary.txt file into an array and compares the string input to the words inside the dictionary.

My current problem is that when the input contains the same word multiple times, such as "teh program is teh worst", the code will print out

You entered 'teh', did you mean 'the'?
You entered 'teh', did you mean 'the'?

Sometimes a website will have multiple words over and over again and this can become messy.

If it's possible, printing the word along with how many times it was spelled incorrectly would be perfect, but putting a limit to each word being printed once would be good enough.

My program has a handful of methods and two classes, but the spell checking method is below:

Note: the original code contains some 'if' statements that remove punctuation marks but I've removed them for clarity.

static boolean suggestWord;

public static String checkWord(String wordToCheck) {
        String wordCheck;
        String word = wordToCheck.toLowerCase();

    if ((wordCheck = (String) dictionary.get(word)) != null) {
        suggestWord = false; // no need to ask for suggestion for a correct
                                // word.
        return wordCheck;
    }

    // If after all of these checks a word could not be corrected, return as
    // a misspelled word.
    return word;
}

TEMPORARY EDIT: As requested, the complete code:

Class 1:

public class ParseCleanCheck {

        static Hashtable<String, String> dictionary;// To store all the  words of the
        // dictionary
        static boolean suggestWord;// To indicate whether the word is spelled
                                    // correctly or not.

        static Scanner urlInput = new Scanner(System.in);
        public static String cleanString;
        public static String url = "";
        public static boolean correct = true;

        /**
         * PARSER METHOD
         */
        public static void PageScanner() throws IOException {
            System.out.println("Pick an english website to scan.");

            // This do-while loop allows the user to try again after a mistake
            do {
                try {
                    System.out.println("Enter a URL, starting with http://");
                    url = urlInput.nextLine();
                    // This creates a document out of the HTML on the web page
                    Document doc = Jsoup.connect(url).get();
                    // This converts the document into a string to be cleaned
                    String htmlToClean = doc.toString();
                    cleanString = Jsoup.clean(htmlToClean, Whitelist.none());

                    correct = false;
                } catch (Exception e) {
                    System.out.println("Incorrect format for a URL. Please try again.");
                }
            } while (correct);
        }

        /**
         * SPELL CHECKER METHOD
         */
        public static void SpellChecker() throws IOException {
            dictionary = new Hashtable<String, String>();
            System.out.println("Searching for spelling errors ... ");

            try {
                // Read and store the words of the dictionary
                BufferedReader dictReader = new BufferedReader(new FileReader("dictionary.txt"));

                while (dictReader.ready()) {
                    String dictInput = dictReader.readLine();
                    String[] dict = dictInput.split("\\s"); // create an array of
                                                            // dictionary words

                    for (int i = 0; i < dict.length; i++) {
                        // key and value are identical
                        dictionary.put(dict[i], dict[i]);
                    }
                }
                dictReader.close();
                String user_text = "";

                // Initializing a spelling suggestion object based on probability
                SuggestSpelling suggest = new SuggestSpelling("wordprobabilityDatabase.txt");

                // get user input for correction
                {

                    user_text = cleanString;
                    String[] words = user_text.split(" ");

                    int error = 0;

                    for (String word : words) {
                        if(!dictionary.contains(word)) {
                            checkWord(word);

                            dictionary.put(word, word);
                        }
                        suggestWord = true;
                        String outputWord = checkWord(word);

                        if (suggestWord) {
                            System.out.println("Suggestions for " + word + " are:  " + suggest.correct(outputWord) + "\n");
                            error++;
                        }
                    }

                    if (error == 0) {
                        System.out.println("No mistakes found");
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
                System.exit(-1);
            }
        }

        /**
         * METHOD TO SPELL CHECK THE WORDS IN A STRING. IS USED IN SPELL CHECKER
         * METHOD THROUGH THE "WORD" STRING
         */

        public static String checkWord(String wordToCheck) {
            String wordCheck;
            String word = wordToCheck.toLowerCase();

        if ((wordCheck = (String) dictionary.get(word)) != null) {
            suggestWord = false; // no need to ask for suggestion for a correct
                                    // word.
            return wordCheck;
        }

        // If after all of these checks a word could not be corrected, return as
        // a misspelled word.
        return word;
    }
    }

There is a second class (SuggestSpelling.java) which holds a probability calculator but that isn't relevant right now, unless you planned on running the code for yourself.

Body:
Use a HashSet to detect duplicates -

Set<String> wordSet = new HashSet<>();

And store each word of the input sentence. If any word already exist during inserting into the HashSet, don't call checkWord(String wordToCheck) for that word. Something like this -

String[] words = // split input sentence into words
for(String word: words) {
    if(!wordSet.contains(word)) {
        checkWord(word);
        // do stuff
        wordSet.add(word);
    }
}

Edit

// ....
{

    user_text = cleanString;
    String[] words = user_text.split(" ");
    Set<String> wordSet = new HashSet<>();

    int error = 0;

    for (String word : words) {
        // wordSet is another data-structure. Its only for duplicates checking, don't mix it with dictionary
        if(!wordSet.contains(word)) {

            // put all your logic here

            wordSet.add(word);
        }
    }

    if (error == 0) {
        System.out.println("No mistakes found");
    }
}
// ....

You have other bugs as well like you are passing String wordCheck as argument of checkWord and re-declare it inside checkWord() again String wordCheck; which is not right. Please check the other parts as well.


来源: stackexchange

问:
Javascript: How can I use the filter() to filter out specific objects with a certain value?
I have an object with accounts, example:

```<code>    {
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }
</code>```

Let's say I want to filter out only the objects with the states of "FL" and "OH", how could I use the filter() to do that? Thanks.

答:
use array.filter(callback) which takes a function with one argument and return the value that meets the condition you want :

```<code>var testArray = [ {
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }];
  var filtered = testArray.filter(isStateFLorOH);
</code>```

and the fucntion callback should be like this :

```<code>function isStateFLorOH(value){

if(value.state == "FL" || value.satate == "OH")
return value;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an object with accounts, example:

    {
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }

Let's say I want to filter out only the objects with the states of "FL" and "OH", how could I use the filter() to do that? Thanks.

Body:
use array.filter(callback) which takes a function with one argument and return the value that meets the condition you want :

var testArray = [ {
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }];
  var filtered = testArray.filter(isStateFLorOH);

and the fucntion callback should be like this :

function isStateFLorOH(value){

if(value.state == "FL" || value.satate == "OH")
return value;
}


问:
How to deselect all selected rows in a DataGridView control?
I'd like to deselect all selected rows in a DataGridView control when the user clicks on a blank (non-row) part of the control.

How can I do this?

答:
C# version:</p>
```<code>if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            DataGridView.HitTestInfo hit = dgv_track.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.None)
            {
                dgv_track.ClearSelection();
                dgv_track.CurrentCell = null;
            }
        }
</code>```

Body:
C# version:

if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            DataGridView.HitTestInfo hit = dgv_track.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.None)
            {
                dgv_track.ClearSelection();
                dgv_track.CurrentCell = null;
            }
        }

ContentLicense: CC BY-SA 4.0


问:
How to check type compatibility when using the typing module?
I'm using Python PEP484 type hints to write a type-checker for a DSL I've written in Python. If I have a function expecting type T for one of its arguments, and it's being called with an expression of type S, how can I check whether the call is valid? Is using issubclass(S, T) enough? If so, why does mypy have such a complicated is_subtype check? Or should I just use the mypy version?

Edit: Here's an example to clarify what I mean. The DSL has a function defined as:

```<code>T = TypeVar('T', float, str)
def op_add(operand1: T, operand2: T) -> T:
    "Number addition or string concatenation."
    # In this DSL, `+` cannot be used with lists
    return operand1 + operand2  # Rely on Python overloading of `+`
</code>```

Then a user types in an expression which is parsed into a syntax tree, with a branch that could be: node = OperatorNode('+', Literal([5.0]), Variable("abc")). We don't know the value of the abc variable yet, but lists can never be used with +, so I want to raise a TypeError to alert the user.

If I do issubclass(typing.List[float], var), that gives me False, so I can raise an error right away. My question is whether this check is guaranteed to work across cases as I build out the DSL, or if I need to use a more complex check like mypy

答:
issubclass check is sufficient if neither argument to issubclass includes constructs from typing module such as Union, Callable, Any, generics, etc.

typing constructs exist in python runtime as a shadow of their true form, that is they don't support many of the operations that make sense conceptually:

```<code>issubclass(List[int], List[int])  # runtimem error
issubclass(List[int], List) # True (as expected)
issubclass(str, Union[str]) # runtime error
issubclass(Union[str], str) # True (as expected)
issubclass(Union[int, str], str) # runtime error
</code>```

Sometimes issubclass will work with typing constructs, but in general, it may raise an exception or give an incorrect answer; you'll need to figure out what to do on a case by case basis.

mypy has a more complicated is_subtype because it does need to handle all the typing constructs, and even then there is still some work to be done there.

Body:
I'm using Python PEP484 type hints to write a type-checker for a DSL I've written in Python. If I have a function expecting type T for one of its arguments, and it's being called with an expression of type S, how can I check whether the call is valid? Is using issubclass(S, T) enough? If so, why does mypy have such a complicated is_subtype check? Or should I just use the mypy version?

Edit: Here's an example to clarify what I mean. The DSL has a function defined as:

T = TypeVar('T', float, str)
def op_add(operand1: T, operand2: T) -> T:
    "Number addition or string concatenation."
    # In this DSL, `+` cannot be used with lists
    return operand1 + operand2  # Rely on Python overloading of `+`

Then a user types in an expression which is parsed into a syntax tree, with a branch that could be: node = OperatorNode('+', Literal([5.0]), Variable("abc")). We don't know the value of the abc variable yet, but lists can never be used with +, so I want to raise a TypeError to alert the user.

If I do issubclass(typing.List[float], var), that gives me False, so I can raise an error right away. My question is whether this check is guaranteed to work across cases as I build out the DSL, or if I need to use a more complex check like mypy

Body:
issubclass check is sufficient if neither argument to issubclass includes constructs from typing module such as Union, Callable, Any, generics, etc.

typing constructs exist in python runtime as a shadow of their true form, that is they don't support many of the operations that make sense conceptually:

issubclass(List[int], List[int])  # runtimem error
issubclass(List[int], List) # True (as expected)
issubclass(str, Union[str]) # runtime error
issubclass(Union[str], str) # True (as expected)
issubclass(Union[int, str], str) # runtime error

Sometimes issubclass will work with typing constructs, but in general, it may raise an exception or give an incorrect answer; you'll need to figure out what to do on a case by case basis.

mypy has a more complicated is_subtype because it does need to handle all the typing constructs, and even then there is still some work to be done there.


问:
How to use `setTimeout` in ClojureScript?
I'm trying to make a sleep function in ClojureScript (w/ Reagent):

(ns cljweb.webpage
  (:require [reagent.core :as reagent]))

(def temp-atom (reagent/atom 0))

(defn sleep [msec]
  (js/setTimeout (fn []) msec))

(defn page []
  [:div
   [:p @temp-atom]
   [:button
    {:on-click
      (fn []
        (sleep 3000)
        (swap! temp-atom inc))}
    "Click me!"]])
```

<p>For some reason, this doesn't sleep properly - when I click the "Click me!" button, <code>temp-atom</code> increments instantly - when I time it, by putting this after in <code>page</code>:</p>

<pre class="lang-clj prettyprint-override"><code>[:p (time (sleep 3000))]
</code>```

I get this in the console:

"Elapsed time: 0.015000 msecs"
```

What did I do wrong in the code?

答:
With ClojureScript, the best way to write asynchronous code is with the CoreAsync library. In your case, take a look at the timeout function:</p>

```<code>(ns cljweb.webpage
  (:use-macros [cljs.core.async.macros :only [go]]
  (:require [reagent.core :as reagent]
            [cljs.core.async :refer [<! timeout]]))

(def temp-atom (reagent/atom 0))

(defn page []
   [:div
     [:p @temp-atom]
     [:button
       {:on-click
         (fn []
          (go
            (<! (timeout 3000))
            (swap! temp-atom inc)))}
         "Click me!"]])
</code>```

Body:
I'm trying to make a sleep function in ClojureScript (w/ Reagent):

(ns cljweb.webpage
  (:require [reagent.core :as reagent]))

(def temp-atom (reagent/atom 0))

(defn sleep [msec]
  (js/setTimeout (fn []) msec))

(defn page []
  [:div
   [:p @temp-atom]
   [:button
    {:on-click
      (fn []
        (sleep 3000)
        (swap! temp-atom inc))}
    "Click me!"]])

For some reason, this doesn't sleep properly - when I click the "Click me!" button, temp-atom increments instantly - when I time it, by putting this after in page:

[:p (time (sleep 3000))]

I get this in the console:

"Elapsed time: 0.015000 msecs"

What did I do wrong in the code?

Body:
With ClojureScript, the best way to write asynchronous code is with the CoreAsync library. In your case, take a look at the timeout function:

(ns cljweb.webpage
  (:use-macros [cljs.core.async.macros :only [go]]
  (:require [reagent.core :as reagent]
            [cljs.core.async :refer [<! timeout]]))

(def temp-atom (reagent/atom 0))

(defn page []
   [:div
     [:p @temp-atom]
     [:button
       {:on-click
         (fn []
          (go
            (<! (timeout 3000))
            (swap! temp-atom inc)))}
         "Click me!"]])


问:
How to add a second vertical line in R package forestplot
I'd like to distinguish between statistical significance (OR = 1.0) and clinical significance (OR = 1.5) in my forest plot. I created this plot using the forestplot package, sample code below. Is adding a vertical line possible (while maintaining the line of no difference)?</p>

```<code>library(forestplot)
test_data <- structure(list(
   mean = c(NA, NA, 1, 0.5, 2),
   lower = c(NA, NA, .5, .25, 1.5),
   upper = c(NA, NA, 1.5, .75, 2.5)),
   .Names = c("mean", "lower", "upper"),
   row.names = c(NA, -5L),
   class = "data.frame")

tabletext <- cbind(
   c("", "Outcome", "Outcome 1", "Outcome 2", "Outcome 3"),
   c("", "OR", "1 (0.5 - 1.5)", "0.5 (0.25 - 0.75)", "2.0 (1.5 - 2.5)"))

forestplot(tabletext,
       test_data,
       new_page = TRUE,
       xlog = TRUE,
       boxsize = .25
       )
</code>```

答: A suboptimal (and not very elegant) solution could be: 1- creating an empty plot with no axis or labels, 2- then plot a vertical line (abline(v=1.5)) and 3- call your forestplot with new_page = F.

Body:
I'd like to distinguish between statistical significance (OR = 1.0) and clinical significance (OR = 1.5) in my forest plot. I created this plot using the forestplot package, sample code below. Is adding a vertical line possible (while maintaining the line of no difference)?

library(forestplot)
test_data <- structure(list(
   mean = c(NA, NA, 1, 0.5, 2),
   lower = c(NA, NA, .5, .25, 1.5),
   upper = c(NA, NA, 1.5, .75, 2.5)),
   .Names = c("mean", "lower", "upper"),
   row.names = c(NA, -5L),
   class = "data.frame")

tabletext <- cbind(
   c("", "Outcome", "Outcome 1", "Outcome 2", "Outcome 3"),
   c("", "OR", "1 (0.5 - 1.5)", "0.5 (0.25 - 0.75)", "2.0 (1.5 - 2.5)"))

forestplot(tabletext,
       test_data,
       new_page = TRUE,
       xlog = TRUE,
       boxsize = .25
       )


问:
How to Use Split in perl with regular expression
I want to Split the Content from a number followed by .

```<code>my $info = "8. 9         Run
       Keywords :- RUN;

    9. 10        spreadsheet
       Keywords :- spreadsheet;

   10. 11        Book
       Keywords :- Book;

   11. 15        Hide
       Keywords :- Hide;

   12. 132        Pick
       Keywords :- Pick;
</code>```

This the string that i have split the content according to the numbers like 8., 9., 10., 11.,12.
Any suggestion how to do this in Perl and make sure that numbers like 8. does't appear after spiting.

答:
It's not quite clear what you want, but splitting on the numbers seems like a poor approach to accomplishing anything.

At the very least, you want to make per-record changes and/or extract per-record information, so it would be far better to split the data into records. Each record is separated by a blank line, so we can use

```<code>my @items = split /\n\n/, $info;
</code>```

This gives:

```<code>my @items = (
   "8. 9         Run\n       Keywords :- RUN;",
   "    9. 10        spreadshee\n       Keywords :- spreadsheet;",
   "   10. 11        Book\n       Keywords :- Book;",
   "   11. 15        Hide\n       Keywords :- Hide;",
   "   12. 132        Pick\n       Keywords :- Pick;",
);
</code>```

Now, it seems you want to remove the numbers.

```<code>s/^\s*\K\d+\.\s*// for @items;   # Preserves the leading whitespace.

s/^\s*\d+\.\s*// for @items;     # Removes the leading whitespace.
</code>```

The latter gives:

```<code>my @items = (
   "9         Run\n       Keywords :- RUN;",
   "10        spreadshee\n       Keywords :- spreadsheet;",
   "11        Book\n       Keywords :- Book;",
   "15        Hide\n       Keywords :- Hide;",
   "132        Pick\n       Keywords :- Pick;",
);
</code>```

You could reconstruct $info minus the numbers by using

```<code>$info = join("\n\n", @items);
</code>```

This gives:

```<code>9         Run
       Keywords :- RUN;

10        spreadshee
       Keywords :- spreadsheet;

11        Book
       Keywords :- Book;

15        Hide
       Keywords :- Hide;

132        Pick
       Keywords :- Pick;
</code>```

If this doesn't answer your question, but clarify what output you expect from your example.

Body:
I want to Split the Content from a number followed by .

my $info = "8. 9         Run
       Keywords :- RUN;

    9. 10        spreadsheet
       Keywords :- spreadsheet;

   10. 11        Book
       Keywords :- Book;

   11. 15        Hide
       Keywords :- Hide;

   12. 132        Pick
       Keywords :- Pick;

This the string that i have split the content according to the numbers like 8., 9., 10., 11.,12.
Any suggestion how to do this in Perl and make sure that numbers like 8. does't appear after spiting.

Body:
It's not quite clear what you want, but splitting on the numbers seems like a poor approach to accomplishing anything.

At the very least, you want to make per-record changes and/or extract per-record information, so it would be far better to split the data into records. Each record is separated by a blank line, so we can use

my @items = split /\n\n/, $info;

This gives:

my @items = (
   "8. 9         Run\n       Keywords :- RUN;",
   "    9. 10        spreadshee\n       Keywords :- spreadsheet;",
   "   10. 11        Book\n       Keywords :- Book;",
   "   11. 15        Hide\n       Keywords :- Hide;",
   "   12. 132        Pick\n       Keywords :- Pick;",
);

Now, it seems you want to remove the numbers.

s/^\s*\K\d+\.\s*// for @items;   # Preserves the leading whitespace.

s/^\s*\d+\.\s*// for @items;     # Removes the leading whitespace.

The latter gives:

my @items = (
   "9         Run\n       Keywords :- RUN;",
   "10        spreadshee\n       Keywords :- spreadsheet;",
   "11        Book\n       Keywords :- Book;",
   "15        Hide\n       Keywords :- Hide;",
   "132        Pick\n       Keywords :- Pick;",
);

You could reconstruct $info minus the numbers by using

$info = join("\n\n", @items);

This gives:

9         Run
       Keywords :- RUN;

10        spreadshee
       Keywords :- spreadsheet;

11        Book
       Keywords :- Book;

15        Hide
       Keywords :- Hide;

132        Pick
       Keywords :- Pick;

If this doesn't answer your question, but clarify what output you expect from your example.


问:
Python - Automatically generate lists to stay under 100 song limit in spotify request
I'm working on a little program using Spotipy to add the top 5 songs from every artist in a text file to a playlist. I like to listen to every band at a music festival and generating the playlist manually takes a LONG time.

So this seemed like a great solution! And it works great - except there is a 100 song limit per request. I have about 690 songs to add.

So basically, I could hard code 7 lists of 99 songs and then submit 7 requests using those lists (I think that will work right? splitting up the requests to get around the limit?) but I'd like the program to be able to work with more/less bands.

So is there a way to generate individual lists based on need? I'm new to python and programming in general (obviously). Or any other advice to accomplish this?

Thanks

import pprint
import sys

import spotipy
import spotipy.util as util

tracks = []
lineupfile = open('lineup.txt','r')
lineup = [x.strip('\n') for x in lineupfile.readlines()]

numberofbands = len(lineup)
if(number)

if len(sys.argv) > 2:
    username = sys.argv[1]
    playlist_id = sys.argv[2]
else:
    print("Usage: %s username playlist_id ..." % (sys.argv[0],))
    sys.exit()

scope = 'playlist-modify-public'
token = util.prompt_for_user_token(username, scope, redirect_uri = 'https://example.com/callback/')

if token:
    sp = spotipy.Spotify(auth=token)
    sp.trace = False

    for x in range(0,len(lineup)):
        results = sp.search(q=str(lineup[x]), limit=5)
        for i, t in enumerate(results['tracks']['items']):
            tracks.append(str(t['id'].strip( 'u' )))
            print("adding ",t['id'],t['name'])
    results = sp.user_playlist_add_tracks(username, playlist_id, tracks, position=None)

else:
    print("Can't get token for", username)

print "Playlist Complete!"
```

答:
Change this:

```<code>    results = sp.user_playlist_add_tracks(username, playlist_id, tracks, position=None)
</code>```

To this:

```<code>while tracks:
    results = sp.user_playlist_add_tracks(username, playlist_id, tracks[:100], position=None)
    tracks = tracks[100:]
</code>```

Body:
Change this:

    results = sp.user_playlist_add_tracks(username, playlist_id, tracks, position=None)

To this:

while tracks:
    results = sp.user_playlist_add_tracks(username, playlist_id, tracks[:100], position=None)
    tracks = tracks[100:]


问:
Can all if statements be converted to equivalent switch statements?
I think that all if statements like this

```<code>if(condition){statements;}
</code>```

can be converted to a switch statement like this

```<code>switch(!(same condition as in if)){case 0:statements;}
</code>```

Am I correct or is there some exception that cannot be converted from if to switch ?

答:
Any condition within a if() statement evaluates to either 0 or 1(it is actually any value other than 0).
 So writing it in switch() statement is equivalent to writing switch(a), where a can be either 1 or 0.

 So, you are absolutely correct!

Body:
I think that all if statements like this

if(condition){statements;}

can be converted to a switch statement like this

switch(!(same condition as in if)){case 0:statements;}

Am I correct or is there some exception that cannot be converted from if to switch ?


问:
How can I add List in poi word, ordered number or other symbol for list symbol?
everyone!
first, I want to add list in my poi word(XWPF),
second, I want to using black cube as the list symbol like picture as below.
third, what I should to do if ordered number instead of the black cube symbol. Could someone give me some advice? Thanks so lot!

答:
Since for new adding a new AbstractNum in XWPFNumbering, XWPFAbstractNum is needed and this is not able to create without using underlaying low level objects until now, at least org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum is needed.

There are methods in CTAbstractNum for creating the single sub objects therein. But the resulting code would be very small part code and so much many code lines would be necessary. So the best way in my opinion is parsing XML for creating the  AbstractNum. To get this XML one can create a simple Worddocument having numbering and then unzip the *.docx file and have a look at /word/numbering.xml. There you will find something like:

```<code><w:numbering>
 <w:abstractNum w:abstractNumId="0">
  <w:multiLevelType w:val="hybridMultilevel"/>
  <w:lvl w:ilvl="0">
   <w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1"/><w:lvlJc w:val="left"/>
   <w:pPr>
    <w:ind w:hanging="360" w:left="720"/>
   </w:pPr>
  </w:lvl>
  <w:lvl w:ilvl="1" w:tentative="1">
   <w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2"/><w:lvlJc w:val="left"/>
   <w:pPr>
    <w:ind w:hanging="360" w:left="1440"/>
   </w:pPr>
  </w:lvl>
  <w:lvl w:ilvl="2" w:tentative="1">
   <w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2.%3"/><w:lvlJc w:val="left"/>
   <w:pPr>
    <w:ind w:hanging="360" w:left="2160"/>
   </w:pPr>
  </w:lvl>
 </w:abstractNum>
...
</w:numbering>
</code>```

for a 3 level decimal numbering for example.

This XML is self explained in my opinion. There is a lvl definition for each numbering level having definitions for it's appearance and indention.

For a bullet numbering the XMLwill be similar but the glyphs for the bullet characters used will be additional defined using Font definition. The "black cube" for example is a glyph from font Wingdings.

```<code>...
<w:lvl w:ilvl="0">
 <w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val=" "/><w:lvlJc w:val="left"/>
 <w:pPr>
  <w:ind w:hanging="360" w:left="720"/>
 </w:pPr>
 <w:rPr>
  <w:rFonts w:ascii="Wingdings" w:hAnsi="Wingdings" w:hint="default"/>
 </w:rPr>
</w:lvl>
...
</code>```

The space in w:val=" " is the default font glyph representation for the unicode code point F06E. This is used because the ASCII code point 6E is showing the glyph "black cube" in Wingdings but the glyph n in normal fonts. That couls lead to irritations if the font Wingdings is not available. Thats why unicode F06E is used instaed of ASCII 6E.

Knowing this we can code:

```<code>import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumbering;

import java.math.BigInteger;

public class CreateWordBulletOrDecimalList {

 static String cTAbstractNumBulletXML =
  "<w:abstractNum xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" w:abstractNumId=\"0\">"
+ "<w:multiLevelType w:val=\"hybridMultilevel\"/>"
+ "<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"\uF06E\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr><w:rPr><w:rFonts w:ascii=\"Wingdings\" w:hAnsi=\"Wingdings\" w:hint=\"default\"/></w:rPr></w:lvl>"
+ "<w:lvl w:ilvl=\"1\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"\u2013\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"1440\" w:hanging=\"360\"/></w:pPr><w:rPr><w:rFonts w:ascii=\"Courier New\" w:hAnsi=\"Courier New\" w:cs=\"Courier New\" w:hint=\"default\"/></w:rPr></w:lvl>"
+ "<w:lvl w:ilvl=\"2\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"\u26Ac\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"2160\" w:hanging=\"360\"/></w:pPr><w:rPr><w:rFonts w:ascii=\"Courier New\" w:hAnsi=\"Courier New\" w:hint=\"default\"/></w:rPr></w:lvl>"
+ "</w:abstractNum>";

 static String cTAbstractNumDecimalXML =
  "<w:abstractNum xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" w:abstractNumId=\"0\">"
+ "<w:multiLevelType w:val=\"hybridMultilevel\"/>"
+ "<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr></w:lvl>"
+ "<w:lvl w:ilvl=\"1\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1.%2\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"1440\" w:hanging=\"360\"/></w:pPr></w:lvl>"
+ "<w:lvl w:ilvl=\"2\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1.%2.%3\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"2160\" w:hanging=\"360\"/></w:pPr></w:lvl>"
+ "</w:abstractNum>";

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

  XWPFDocument document = new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run=paragraph.createRun();
  run.setText("The List:");

  CTNumbering cTNumbering = CTNumbering.Factory.parse(cTAbstractNumBulletXML);
  //CTNumbering cTNumbering = CTNumbering.Factory.parse(cTAbstractNumDecimalXML);

  CTAbstractNum cTAbstractNum = cTNumbering.getAbstractNumArray(0);

  XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);

  XWPFNumbering numbering = document.createNumbering();

  BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);

  BigInteger numID = numbering.addNum(abstractNumID);

  for (int i = 0; i < 5; i++) {
   paragraph = document.createParagraph();
   paragraph.setNumID(numID);
   run = paragraph.createRun();
   run.setText("List item " + (i+1));
   if (i < 4) paragraph.setSpacingAfter(0);
   if (i == 0) {
    for (int j = 0; j < 2; j++) {
     paragraph = document.createParagraph();
     paragraph.setNumID(numID);
     paragraph.getCTP().getPPr().getNumPr().addNewIlvl().setVal(BigInteger.valueOf(1));
     run = paragraph.createRun();
     run.setText("Sub list item " + (i+1) + " " + (char)(97+j));
     paragraph.setSpacingAfter(0);
    }
   }
   if (i == 1 || i == 3) {
    paragraph = document.createParagraph();
    paragraph.setNumID(numID);
    paragraph.getCTP().getPPr().getNumPr().addNewIlvl().setVal(BigInteger.valueOf(1));
    run = paragraph.createRun();
    run.setText("Sub list item " + (i+1) + " a");
    paragraph.setSpacingAfter(0);
   }
  }

  paragraph = document.createParagraph();
  run=paragraph.createRun();
  run.setText("Paragraph after the list.");

  FileOutputStream out = new FileOutputStream("CreateWordBulletOrDecimalList.docx");
  document.write(out);
  out.close();
  document.close();

  System.out.println("CreateWordBulletOrDecimalList written successully");
 }
}
</code>```

Code for using both kind of lists in one document:

```<code>import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumbering;

import java.math.BigInteger;

public class CreateWordBulletAndDecimalList {

 static String cTAbstractNumBulletXML =
  "<w:abstractNum xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" w:abstractNumId=\"0\">"
+ "<w:multiLevelType w:val=\"hybridMultilevel\"/>"
+ "<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"\uF06E\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr><w:rPr><w:rFonts w:ascii=\"Wingdings\" w:hAnsi=\"Wingdings\" w:hint=\"default\"/></w:rPr></w:lvl>"
+ "<w:lvl w:ilvl=\"1\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"\u2013\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"1440\" w:hanging=\"360\"/></w:pPr><w:rPr><w:rFonts w:ascii=\"Courier New\" w:hAnsi=\"Courier New\" w:cs=\"Courier New\" w:hint=\"default\"/></w:rPr></w:lvl>"
+ "<w:lvl w:ilvl=\"2\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"\u26Ac\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"2160\" w:hanging=\"360\"/></w:pPr><w:rPr><w:rFonts w:ascii=\"Courier New\" w:hAnsi=\"Courier New\" w:hint=\"default\"/></w:rPr></w:lvl>"
+ "</w:abstractNum>";

 static String cTAbstractNumDecimalXML =
  "<w:abstractNum xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" w:abstractNumId=\"1\">"
+ "<w:multiLevelType w:val=\"hybridMultilevel\"/>"
+ "<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr></w:lvl>"
+ "<w:lvl w:ilvl=\"1\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1.%2\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"1440\" w:hanging=\"360\"/></w:pPr></w:lvl>"
+ "<w:lvl w:ilvl=\"2\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1.%2.%3\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"2160\" w:hanging=\"360\"/></w:pPr></w:lvl>"
+ "</w:abstractNum>";

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

  XWPFDocument document = new XWPFDocument();

  CTNumbering cTNumbering = CTNumbering.Factory.parse(cTAbstractNumBulletXML);
  CTAbstractNum cTAbstractNum = cTNumbering.getAbstractNumArray(0);
  XWPFAbstractNum abstractNum1 = new XWPFAbstractNum(cTAbstractNum);

  cTNumbering = CTNumbering.Factory.parse(cTAbstractNumDecimalXML);
  cTAbstractNum = cTNumbering.getAbstractNumArray(0);
  XWPFAbstractNum abstractNum2 = new XWPFAbstractNum(cTAbstractNum);

  XWPFNumbering numbering = document.createNumbering();

  BigInteger abstractNumID1 = numbering.addAbstractNum(abstractNum1);
  BigInteger numID1 = numbering.addNum(abstractNumID1);

  BigInteger abstractNumID2 = numbering.addAbstractNum(abstractNum2);
  BigInteger numID2 = numbering.addNum(abstractNumID2);

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run=paragraph.createRun();
  run.setText("The lists:");
  paragraph = document.createParagraph();

  paragraph = document.createParagraph();
  run=paragraph.createRun();
  run.setText("The bullet list:");

  for (int i = 0; i < 5; i++) {
   paragraph = document.createParagraph();
   paragraph.setNumID(numID1);
   run = paragraph.createRun();
   run.setText("List item " + (i+1));
   if (i < 4) paragraph.setSpacingAfter(0);
   if (i == 0) {
    for (int j = 0; j < 2; j++) {
     paragraph = document.createParagraph();
     paragraph.setNumID(numID1);
     paragraph.getCTP().getPPr().getNumPr().addNewIlvl().setVal(BigInteger.valueOf(1));
     run = paragraph.createRun();
     run.setText("Sub list item " + (i+1) + " " + (char)(97+j));
     paragraph.setSpacingAfter(0);
    }
   }
   if (i == 1 || i == 3) {
    paragraph = document.createParagraph();
    paragraph.setNumID(numID1);
    paragraph.getCTP().getPPr().getNumPr().addNewIlvl().setVal(BigInteger.valueOf(1));
    run = paragraph.createRun();
    run.setText("Sub list item " + (i+1) + " a");
    paragraph.setSpacingAfter(0);
   }
  }

  paragraph = document.createParagraph();
  paragraph = document.createParagraph();
  run=paragraph.createRun();
  run.setText("The decimal list:");

  for (int i = 0; i < 5; i++) {
   paragraph = document.createParagraph();
   paragraph.setNumID(numID2);
   run = paragraph.createRun();
   run.setText("List item " + (i+1));
   if (i < 4) paragraph.setSpacingAfter(0);
   if (i == 0) {
    for (int j = 0; j < 2; j++) {
     paragraph = document.createParagraph();
     paragraph.setNumID(numID2);
     paragraph.getCTP().getPPr().getNumPr().addNewIlvl().setVal(BigInteger.valueOf(1));
     run = paragraph.createRun();
     run.setText("Sub list item " + (i+1) + " " + (char)(97+j));
     paragraph.setSpacingAfter(0);
    }
   }
   if (i == 1 || i == 3) {
    paragraph = document.createParagraph();
    paragraph.setNumID(numID2);
    paragraph.getCTP().getPPr().getNumPr().addNewIlvl().setVal(BigInteger.valueOf(1));
    run = paragraph.createRun();
    run.setText("Sub list item " + (i+1) + " a");
    paragraph.setSpacingAfter(0);
   }
  }

  paragraph = document.createParagraph();
  paragraph = document.createParagraph();
  run=paragraph.createRun();
  run.setText("Paragraph after the lists.");

  FileOutputStream out = new FileOutputStream("CreateWordBulletAndDecimalList.docx");
  document.write(out);
  out.close();
  document.close();

  System.out.println("CreateWordBulletAndDecimalList written successully");
 }
}
</code>```

Body:
Since for new adding a new AbstractNum in XWPFNumbering, XWPFAbstractNum is needed and this is not able to create without using underlaying low level objects until now, at least org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum is needed.

There are methods in CTAbstractNum for creating the single sub objects therein. But the resulting code would be very small part code and so much many code lines would be necessary. So the best way in my opinion is parsing XML for creating the  AbstractNum. To get this XML one can create a simple Worddocument having numbering and then unzip the *.docx file and have a look at /word/numbering.xml. There you will find something like:

<w:numbering>
 <w:abstractNum w:abstractNumId="0">
  <w:multiLevelType w:val="hybridMultilevel"/>
  <w:lvl w:ilvl="0">
   <w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1"/><w:lvlJc w:val="left"/>
   <w:pPr>
    <w:ind w:hanging="360" w:left="720"/>
   </w:pPr>
  </w:lvl>
  <w:lvl w:ilvl="1" w:tentative="1">
   <w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2"/><w:lvlJc w:val="left"/>
   <w:pPr>
    <w:ind w:hanging="360" w:left="1440"/>
   </w:pPr>
  </w:lvl>
  <w:lvl w:ilvl="2" w:tentative="1">
   <w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2.%3"/><w:lvlJc w:val="left"/>
   <w:pPr>
    <w:ind w:hanging="360" w:left="2160"/>
   </w:pPr>
  </w:lvl>
 </w:abstractNum>
...
</w:numbering>

for a 3 level decimal numbering for example.

This XML is self explained in my opinion. There is a lvl definition for each numbering level having definitions for it's appearance and indention.

For a bullet numbering the XMLwill be similar but the glyphs for the bullet characters used will be additional defined using Font definition. The "black cube" for example is a glyph from font Wingdings.

...
<w:lvl w:ilvl="0">
 <w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val=" "/><w:lvlJc w:val="left"/>
 <w:pPr>
  <w:ind w:hanging="360" w:left="720"/>
 </w:pPr>
 <w:rPr>
  <w:rFonts w:ascii="Wingdings" w:hAnsi="Wingdings" w:hint="default"/>
 </w:rPr>
</w:lvl>
...

The space in w:val=" " is the default font glyph representation for the unicode code point F06E. This is used because the ASCII code point 6E is showing the glyph "black cube" in Wingdings but the glyph n in normal fonts. That couls lead to irritations if the font Wingdings is not available. Thats why unicode F06E is used instaed of ASCII 6E.

Knowing this we can code:

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumbering;

import java.math.BigInteger;

public class CreateWordBulletOrDecimalList {

 static String cTAbstractNumBulletXML =
  "<w:abstractNum xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" w:abstractNumId=\"0\">"
+ "<w:multiLevelType w:val=\"hybridMultilevel\"/>"
+ "<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"\uF06E\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr><w:rPr><w:rFonts w:ascii=\"Wingdings\" w:hAnsi=\"Wingdings\" w:hint=\"default\"/></w:rPr></w:lvl>"
+ "<w:lvl w:ilvl=\"1\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"\u2013\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"1440\" w:hanging=\"360\"/></w:pPr><w:rPr><w:rFonts w:ascii=\"Courier New\" w:hAnsi=\"Courier New\" w:cs=\"Courier New\" w:hint=\"default\"/></w:rPr></w:lvl>"
+ "<w:lvl w:ilvl=\"2\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"\u26Ac\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"2160\" w:hanging=\"360\"/></w:pPr><w:rPr><w:rFonts w:ascii=\"Courier New\" w:hAnsi=\"Courier New\" w:hint=\"default\"/></w:rPr></w:lvl>"
+ "</w:abstractNum>";

 static String cTAbstractNumDecimalXML =
  "<w:abstractNum xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" w:abstractNumId=\"0\">"
+ "<w:multiLevelType w:val=\"hybridMultilevel\"/>"
+ "<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr></w:lvl>"
+ "<w:lvl w:ilvl=\"1\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1.%2\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"1440\" w:hanging=\"360\"/></w:pPr></w:lvl>"
+ "<w:lvl w:ilvl=\"2\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1.%2.%3\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"2160\" w:hanging=\"360\"/></w:pPr></w:lvl>"
+ "</w:abstractNum>";

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

  XWPFDocument document = new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run=paragraph.createRun();
  run.setText("The List:");

  CTNumbering cTNumbering = CTNumbering.Factory.parse(cTAbstractNumBulletXML);
  //CTNumbering cTNumbering = CTNumbering.Factory.parse(cTAbstractNumDecimalXML);

  CTAbstractNum cTAbstractNum = cTNumbering.getAbstractNumArray(0);

  XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);

  XWPFNumbering numbering = document.createNumbering();

  BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);

  BigInteger numID = numbering.addNum(abstractNumID);

  for (int i = 0; i < 5; i++) {
   paragraph = document.createParagraph();
   paragraph.setNumID(numID);
   run = paragraph.createRun();
   run.setText("List item " + (i+1));
   if (i < 4) paragraph.setSpacingAfter(0);
   if (i == 0) {
    for (int j = 0; j < 2; j++) {
     paragraph = document.createParagraph();
     paragraph.setNumID(numID);
     paragraph.getCTP().getPPr().getNumPr().addNewIlvl().setVal(BigInteger.valueOf(1));
     run = paragraph.createRun();
     run.setText("Sub list item " + (i+1) + " " + (char)(97+j));
     paragraph.setSpacingAfter(0);
    }
   }
   if (i == 1 || i == 3) {
    paragraph = document.createParagraph();
    paragraph.setNumID(numID);
    paragraph.getCTP().getPPr().getNumPr().addNewIlvl().setVal(BigInteger.valueOf(1));
    run = paragraph.createRun();
    run.setText("Sub list item " + (i+1) + " a");
    paragraph.setSpacingAfter(0);
   }
  }

  paragraph = document.createParagraph();
  run=paragraph.createRun();
  run.setText("Paragraph after the list.");

  FileOutputStream out = new FileOutputStream("CreateWordBulletOrDecimalList.docx");
  document.write(out);
  out.close();
  document.close();

  System.out.println("CreateWordBulletOrDecimalList written successully");
 }
}

Code for using both kind of lists in one document:

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumbering;

import java.math.BigInteger;

public class CreateWordBulletAndDecimalList {

 static String cTAbstractNumBulletXML =
  "<w:abstractNum xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" w:abstractNumId=\"0\">"
+ "<w:multiLevelType w:val=\"hybridMultilevel\"/>"
+ "<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"\uF06E\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr><w:rPr><w:rFonts w:ascii=\"Wingdings\" w:hAnsi=\"Wingdings\" w:hint=\"default\"/></w:rPr></w:lvl>"
+ "<w:lvl w:ilvl=\"1\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"\u2013\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"1440\" w:hanging=\"360\"/></w:pPr><w:rPr><w:rFonts w:ascii=\"Courier New\" w:hAnsi=\"Courier New\" w:cs=\"Courier New\" w:hint=\"default\"/></w:rPr></w:lvl>"
+ "<w:lvl w:ilvl=\"2\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"bullet\"/><w:lvlText w:val=\"\u26Ac\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"2160\" w:hanging=\"360\"/></w:pPr><w:rPr><w:rFonts w:ascii=\"Courier New\" w:hAnsi=\"Courier New\" w:hint=\"default\"/></w:rPr></w:lvl>"
+ "</w:abstractNum>";

 static String cTAbstractNumDecimalXML =
  "<w:abstractNum xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" w:abstractNumId=\"1\">"
+ "<w:multiLevelType w:val=\"hybridMultilevel\"/>"
+ "<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr></w:lvl>"
+ "<w:lvl w:ilvl=\"1\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1.%2\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"1440\" w:hanging=\"360\"/></w:pPr></w:lvl>"
+ "<w:lvl w:ilvl=\"2\" w:tentative=\"1\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/><w:lvlText w:val=\"%1.%2.%3\"/><w:lvlJc w:val=\"left\"/><w:pPr><w:ind w:left=\"2160\" w:hanging=\"360\"/></w:pPr></w:lvl>"
+ "</w:abstractNum>";

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

  XWPFDocument document = new XWPFDocument();

  CTNumbering cTNumbering = CTNumbering.Factory.parse(cTAbstractNumBulletXML);
  CTAbstractNum cTAbstractNum = cTNumbering.getAbstractNumArray(0);
  XWPFAbstractNum abstractNum1 = new XWPFAbstractNum(cTAbstractNum);

  cTNumbering = CTNumbering.Factory.parse(cTAbstractNumDecimalXML);
  cTAbstractNum = cTNumbering.getAbstractNumArray(0);
  XWPFAbstractNum abstractNum2 = new XWPFAbstractNum(cTAbstractNum);

  XWPFNumbering numbering = document.createNumbering();

  BigInteger abstractNumID1 = numbering.addAbstractNum(abstractNum1);
  BigInteger numID1 = numbering.addNum(abstractNumID1);

  BigInteger abstractNumID2 = numbering.addAbstractNum(abstractNum2);
  BigInteger numID2 = numbering.addNum(abstractNumID2);

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run=paragraph.createRun();
  run.setText("The lists:");
  paragraph = document.createParagraph();

  paragraph = document.createParagraph();
  run=paragraph.createRun();
  run.setText("The bullet list:");

  for (int i = 0; i < 5; i++) {
   paragraph = document.createParagraph();
   paragraph.setNumID(numID1);
   run = paragraph.createRun();
   run.setText("List item " + (i+1));
   if (i < 4) paragraph.setSpacingAfter(0);
   if (i == 0) {
    for (int j = 0; j < 2; j++) {
     paragraph = document.createParagraph();
     paragraph.setNumID(numID1);
     paragraph.getCTP().getPPr().getNumPr().addNewIlvl().setVal(BigInteger.valueOf(1));
     run = paragraph.createRun();
     run.setText("Sub list item " + (i+1) + " " + (char)(97+j));
     paragraph.setSpacingAfter(0);
    }
   }
   if (i == 1 || i == 3) {
    paragraph = document.createParagraph();
    paragraph.setNumID(numID1);
    paragraph.getCTP().getPPr().getNumPr().addNewIlvl().setVal(BigInteger.valueOf(1));
    run = paragraph.createRun();
    run.setText("Sub list item " + (i+1) + " a");
    paragraph.setSpacingAfter(0);
   }
  }

  paragraph = document.createParagraph();
  paragraph = document.createParagraph();
  run=paragraph.createRun();
  run.setText("The decimal list:");

  for (int i = 0; i < 5; i++) {
   paragraph = document.createParagraph();
   paragraph.setNumID(numID2);
   run = paragraph.createRun();
   run.setText("List item " + (i+1));
   if (i < 4) paragraph.setSpacingAfter(0);
   if (i == 0) {
    for (int j = 0; j < 2; j++) {
     paragraph = document.createParagraph();
     paragraph.setNumID(numID2);
     paragraph.getCTP().getPPr().getNumPr().addNewIlvl().setVal(BigInteger.valueOf(1));
     run = paragraph.createRun();
     run.setText("Sub list item " + (i+1) + " " + (char)(97+j));
     paragraph.setSpacingAfter(0);
    }
   }
   if (i == 1 || i == 3) {
    paragraph = document.createParagraph();
    paragraph.setNumID(numID2);
    paragraph.getCTP().getPPr().getNumPr().addNewIlvl().setVal(BigInteger.valueOf(1));
    run = paragraph.createRun();
    run.setText("Sub list item " + (i+1) + " a");
    paragraph.setSpacingAfter(0);
   }
  }

  paragraph = document.createParagraph();
  paragraph = document.createParagraph();
  run=paragraph.createRun();
  run.setText("Paragraph after the lists.");

  FileOutputStream out = new FileOutputStream("CreateWordBulletAndDecimalList.docx");
  document.write(out);
  out.close();
  document.close();

  System.out.println("CreateWordBulletAndDecimalList written successully");
 }
}


问:
Redirecting ".local" subdomain to unicast DNS
I regularly access Windows domains that have been set up to use a domain under the .local top level name. This conflicts with Bonjour/Zeroconf which reserves .local for it's own use. A number of platforms support Bonjour out of the box (including Mac OS, iPhone, and Ubuntu) and there's numerous name resolution issues when this confict occurs.

I have a manual (per workstation) workaround in place for Mac OS by creating an /etc/resolver/ntdomain.local as per resolver(5) which works well. Unfortunately this requires manual changes on every workstation and does not work on the iPhone.

What I'm looking for is a way to redirect requests for *.ntdomain.local coming in via mDNS to a specific unicast DNS server. I don't mind writing some code if required. I can deploy on either preferably Debian or alternatively Windows 2003. It looks like Avahi may be the library I'm looking for.

Can this be done without registering every address in the subdomain or is it possible to register a single NS record of ntdomain.local that points to the Windows DNS server?

答:
You can "merge" the unicast and multicast .local namespaces (with unicast taking precedence) as explained on Avahi and Unicast .local. Apple has instructions for doing the same on Mac OS X.

Another option is to add domain-name=.localnet to /etc/avahi/avahi-daemon.conf to have it use .localnet instead of .local for the multicast DNS namespace.

OwnerDisplayName: Jason W

LastEditorDisplayName: Orion Edwards

OwnerDisplayName: Ted Percival

LastEditorDisplayName: Ted Percival


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答: Most definitely the FOR loop - at 6 years old, having that lil' LOGO Turtle go from drawing a line to drawing a square to drawing a circle was all it took to turn me from a user into a programmer.</p>

OwnerDisplayName: Michael Buen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Triptych

OwnerDisplayName: Greg Hurlman


问:
iTextSharp: Tile Image in Table Cell
I'm trying to tile an image or background image in a table cell in iTextSharp. The closest I have gotten is to attach an image directly to the cell using a PdfPTable and PdfPCell.

```<code>tempCell = new PdfPCell();
tempCell.Image = iTextSharp.text.Image.GetInstance(Path.Combine(GetImageDirectory(), "my_image.gif"));
table.AddCell(tempCell);
</code>```

This has its issues, though. The cells are never the same size in my tables, so the images are scaled automatically by width. This can make some of the cells extra tall comparatively to other cells, or only half full of the image if they are narrow.

Any suggestions on how to get the images tiling, if it is even possible with iTextSharp? Thanks!

答:
Try reusing the following

Image imgLogo = Image.GetInstance(_pathToCustomLogo);

```<code>            if (imgLogo != null)
            {
                imgLogo.ScaleToFit(desiredLogoWidth, imgLogo.Height);
                Cell cellWithImage = new Cell();
                cellWithImage.Add(imgLogo);
                maintableHeader.AddCell(cellWithImage);
            }
</code>```

Ciao

Title: iTextSharp: Tile Image in Table Cell

Body:
I'm trying to tile an image or background image in a table cell in iTextSharp. The closest I have gotten is to attach an image directly to the cell using a PdfPTable and PdfPCell.

tempCell = new PdfPCell();
tempCell.Image = iTextSharp.text.Image.GetInstance(Path.Combine(GetImageDirectory(), "my_image.gif"));
table.AddCell(tempCell);

This has its issues, though. The cells are never the same size in my tables, so the images are scaled automatically by width. This can make some of the cells extra tall comparatively to other cells, or only half full of the image if they are narrow.

Any suggestions on how to get the images tiling, if it is even possible with iTextSharp? Thanks!

Body:
Try reusing the following

Image imgLogo = Image.GetInstance(_pathToCustomLogo);

            if (imgLogo != null)
            {
                imgLogo.ScaleToFit(desiredLogoWidth, imgLogo.Height);
                Cell cellWithImage = new Cell();
                cellWithImage.Add(imgLogo);
                maintableHeader.AddCell(cellWithImage);
            }

Ciao


问:
RHEL Environment Variable Path To Mongo Shell
I have installed mongodb in one of our environments & this has been done using MongoDb Operations Manager. Though i have my PATH variable set correctly i'm unable to connect mongo shell with my user account but able to connect as a sudo. could someone help me if i'm missing anything here.

Details:

```<code>[user01@west.company.com@rhel01 /]$ echo $PATH
> /var/lib/mongodb-mms-automation/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/nfs/home/user01/.local/bin:/nfs/home/user01/bin
[user01@west.company.com@rhel01 /]$ mongo
> -bash: mongo: command not found

[user01@west.company.com@rhel01 /]$ sudo -i
[sudo] password for user01@west.company.com:
[root@rhel01 ~]# echo $PATH
> /var/lib/mongodb-mms-automation/bin:/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
[root@rhel01 ~]# mongo
> MongoDB shell
> version: 3.2.10 connecting to: test
> MongoDB Enterprise MYMONGOREPLSET01:PRIMARY>
</code>```

Which Mongo Output:

```<code>[user01@west.company.com@rhel01 /]$ which mongo
/usr/bin/which: no mongo in (/var/lib/mongodb-mms-automation/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/nfs/home/user01/.local/bin:/nfs/home/user01/bin)

[root@rhel01 ~]# which mongo
/var/lib/mongodb-mms-automation/bin/mongo
</code>```

Observation:

i just noticed the bin location is set like this ...

```<code>[root@rhel01 mongodb-mms-automation]# pwd
/var/lib/mongodb-mms-automation
[root@rhel01 mongodb-mms-automation]# ls -la
total 32
drwxr-xr-x   3 mongod mongod  4096 Mar 30 13:58 .
drwxr-xr-x. 57 root   root    4096 Apr  1 03:23 ..
lrwxrwxrwx   1 mongod mongod    67 Nov  4 13:45 bin -> /var/lib/mongodb-mms-automation/mongodb-linux-x86_64-3.2.10-ent/bin
-rw-------   1 mongod mongod  1024 Mar 27 15:07 keyfile
-rw-------   1 mongod mongod 10686 Mar 30 13:58 mms-cluster-config-backup.json
drwxr-x---   4 mongod mongod  4096 Nov  4 13:45 mongodb-linux-x86_64-3.2.10-ent
</code>```

答:
Try this</p>

```<code>sudo chmod -R 777 /var/lib/mongodb-mms-automation/mongodb-linux-x86_64-3.2.10-ent/bin/
</code>```

Body:
I have installed mongodb in one of our environments & this has been done using MongoDb Operations Manager. Though i have my PATH variable set correctly i'm unable to connect mongo shell with my user account but able to connect as a sudo. could someone help me if i'm missing anything here.

Details:

[user01@west.company.com@rhel01 /]$ echo $PATH
> /var/lib/mongodb-mms-automation/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/nfs/home/user01/.local/bin:/nfs/home/user01/bin
[user01@west.company.com@rhel01 /]$ mongo
> -bash: mongo: command not found

[user01@west.company.com@rhel01 /]$ sudo -i
[sudo] password for user01@west.company.com:
[root@rhel01 ~]# echo $PATH
> /var/lib/mongodb-mms-automation/bin:/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
[root@rhel01 ~]# mongo
> MongoDB shell
> version: 3.2.10 connecting to: test
> MongoDB Enterprise MYMONGOREPLSET01:PRIMARY>

Which Mongo Output:

[user01@west.company.com@rhel01 /]$ which mongo
/usr/bin/which: no mongo in (/var/lib/mongodb-mms-automation/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/nfs/home/user01/.local/bin:/nfs/home/user01/bin)

[root@rhel01 ~]# which mongo
/var/lib/mongodb-mms-automation/bin/mongo

Observation:

i just noticed the bin location is set like this ...

[root@rhel01 mongodb-mms-automation]# pwd
/var/lib/mongodb-mms-automation
[root@rhel01 mongodb-mms-automation]# ls -la
total 32
drwxr-xr-x   3 mongod mongod  4096 Mar 30 13:58 .
drwxr-xr-x. 57 root   root    4096 Apr  1 03:23 ..
lrwxrwxrwx   1 mongod mongod    67 Nov  4 13:45 bin -> /var/lib/mongodb-mms-automation/mongodb-linux-x86_64-3.2.10-ent/bin
-rw-------   1 mongod mongod  1024 Mar 27 15:07 keyfile
-rw-------   1 mongod mongod 10686 Mar 30 13:58 mms-cluster-config-backup.json
drwxr-x---   4 mongod mongod  4096 Nov  4 13:45 mongodb-linux-x86_64-3.2.10-ent

Body:
Try this

sudo chmod -R 777 /var/lib/mongodb-mms-automation/mongodb-linux-x86_64-3.2.10-ent/bin/


问:
Convert double to int inaccuracy (1 off)
I have the following situation that gives me 27 instead of 28:

```<code>double d = 0.35;
int i = 80;

int ans = (int)(d * i);

printf("%d", ans);
</code>```

But I get the right answer if I use this:

```<code>int ans = (int)(0.35 * 80);
printf("%d", ans);
</code>```

or:

```<code>double ans = d * i;
printf("%d", (int) ans);
</code>```

Can someone explain why the first situation is 1 off and the others work?

I did some research and people say that double stores a number like 28 as 27.999..., but I'm confused as in what scenarios this would occur in.

Thanks!

答:
Value of 0.35 does not have an exact binary floating-point representation. So on typical platforms using IEEE 754-based floating-point support, your double d = 0.35; is not really 0.35 at all, but rather something like 0.34999999999999998 - a value that in this case happens to be smaller than the original 0.35. The rest follows: multiplication produces less than 28, which gets truncated to 27 by your (int). End of story.

If someone is getting 28 from this example it probably means that their compiler uses a different floating-point evaluation model, in which the original 0.35 might be represented either precisely or as some value slightly greater than 0.35 (say, 0.35000000000012 or something like that). Compilers that optimized the calculations and performed them at compile time also fall into that category.

The difference between

```<code>int ans = (int)(d * i);
printf("%d", ans);
</code>```

and

```<code>double ans = d * i;
printf("%d", (int) ans);
</code>```

might easily be caused by the compiler literally storing the intermediate result in a double variable ans in the second case.

The actual multiplication might be performed in a high-precision floating-point register of the CPU (whose precision is higher than double). In the first case the result gets stored directly into an int. In the second case it is first converted to lower-precision double and only then that double gets converted to int. This extra intermediate conversion to double can easily change the result.

Body:
I have the following situation that gives me 27 instead of 28:

double d = 0.35;
int i = 80;

int ans = (int)(d * i);

printf("%d", ans);

But I get the right answer if I use this:

int ans = (int)(0.35 * 80);
printf("%d", ans);

or:

double ans = d * i;
printf("%d", (int) ans);

Can someone explain why the first situation is 1 off and the others work?

I did some research and people say that double stores a number like 28 as 27.999..., but I'm confused as in what scenarios this would occur in.

Thanks!

Body:
Value of 0.35 does not have an exact binary floating-point representation. So on typical platforms using IEEE 754-based floating-point support, your double d = 0.35; is not really 0.35 at all, but rather something like 0.34999999999999998 - a value that in this case happens to be smaller than the original 0.35. The rest follows: multiplication produces less than 28, which gets truncated to 27 by your (int). End of story.

If someone is getting 28 from this example it probably means that their compiler uses a different floating-point evaluation model, in which the original 0.35 might be represented either precisely or as some value slightly greater than 0.35 (say, 0.35000000000012 or something like that). Compilers that optimized the calculations and performed them at compile time also fall into that category.

The difference between

int ans = (int)(d * i);
printf("%d", ans);

and

double ans = d * i;
printf("%d", (int) ans);

might easily be caused by the compiler literally storing the intermediate result in a double variable ans in the second case.

The actual multiplication might be performed in a high-precision floating-point register of the CPU (whose precision is higher than double). In the first case the result gets stored directly into an int. In the second case it is first converted to lower-precision double and only then that double gets converted to int. This extra intermediate conversion to double can easily change the result.


问:
Ajax not working with Node js - Express js
Im trying to send data from my server side to my client side with ajax but when i use res.send(data) in node, it show me a empty html with the data and i want to get data from my client side without reloading the page and edit something in my actual html

Here's my server-side code

```<code>    app.post('/',(req,res)=>{
    var userName = req.body.username;
    var password = req.body.password;

    connection.query('SELECT * from admin',(err, rows, fields)=> {
      if (!err){
        if((userName == rows[0].usuario) && (password == rows[0].contraseña)){
            res.sendStatus(200);

        }else{
            res.send('Incorrect username or password')
        }
      }else{
        res.send('Error while performing Query.');
      }

    });

});
</code>```

Here's my client-side code

```<code>$(document).ready(function(){
$('#login-form').submit(function (e) {
        setTimeout(function () {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/',
            dataType: 'jsonp',
            data: ({username: $('input[name=username]'),password: $('input[name=password]')}),
            success: function(data,textStatus){
                if(textStatus.statusCode == 200) {
                    $('.error-user').html('Succes');
                }else{
                    $('.error-user').html('Not Success');
                }

            },
        });
        }, 1000);

});
});
</code>```

UPDATE: I removed the setTimeOut() but when I submit the form the page freeze like two seconds and then nothing happen, I get this 'error Maximum call stack size exceeded', dont get me data just stay in the same view if like post method was never called

UPDATE-FINAL: I got values from input outside of the ajax and it works nice,thanks :#

答:
You forgot : .val() to send the value of inputs :

```<code>data: ({username: $('input[name=username]').val(), password: $('input[name=password]').val() }),
</code>```

and NOT :

```<code>data: ({username: $('input[name=username]'),password: $('input[name=password]')}),
</code>```

Body:
Im trying to send data from my server side to my client side with ajax but when i use res.send(data) in node, it show me a empty html with the data and i want to get data from my client side without reloading the page and edit something in my actual html

Here's my server-side code

    app.post('/',(req,res)=>{
    var userName = req.body.username;
    var password = req.body.password;

    connection.query('SELECT * from admin',(err, rows, fields)=> {
      if (!err){
        if((userName == rows[0].usuario) && (password == rows[0].contraseña)){
            res.sendStatus(200);

        }else{
            res.send('Incorrect username or password')
        }
      }else{
        res.send('Error while performing Query.');
      }

    });

});

Here's my client-side code

$(document).ready(function(){
$('#login-form').submit(function (e) {
        setTimeout(function () {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/',
            dataType: 'jsonp',
            data: ({username: $('input[name=username]'),password: $('input[name=password]')}),
            success: function(data,textStatus){
                if(textStatus.statusCode == 200) {
                    $('.error-user').html('Succes');
                }else{
                    $('.error-user').html('Not Success');
                }

            },
        });
        }, 1000);

});
});

UPDATE: I removed the setTimeOut() but when I submit the form the page freeze like two seconds and then nothing happen, I get this 'error Maximum call stack size exceeded', dont get me data just stay in the same view if like post method was never called

UPDATE-FINAL: I got values from input outside of the ajax and it works nice,thanks :#

Body:
You forgot : .val() to send the value of inputs :

data: ({username: $('input[name=username]').val(), password: $('input[name=password]').val() }),

and NOT :

data: ({username: $('input[name=username]'),password: $('input[name=password]')}),


问:
How to set the width of the ListView in a PopupWindow on Android?
I inflated a ListView as the contentView in a PopupWindow.
If I don't set the width & height, I can't see the PopupWindow.
If I set them like this:

```<code>setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
</code>```

The layout is being set like "fill_parent". Why?

The layout attributes of the ListView and ListView item are all set to "wrap_content".
Any suggestion? Thanks.

答:
I faced the same problem. The only solution I found is to set the PopupWindow width to the exact width of the ListView:

```<code>listView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
final PopupWindow popup = new PopupWindow(listView, listView.getMeasuredWidth(),
    ViewGroup.LayoutParams.WRAP_CONTENT, true);
popup.showAsDropDown(anchor);
</code>```

Unfortunately, it doesn't solve the problem entirely. The ListView measures itself so that it can wrap only its first child. If for example the second child is wider than the first one, the second child will be clipped.

I'm not sure, but the only way to change the way the ListView measures itself is to subclass it and override the onMeasure() method. I'm trying to do it now and I'll write a comment here if I succeed in it.

Body:
I inflated a ListView as the contentView in a PopupWindow.
If I don't set the width & height, I can't see the PopupWindow.
If I set them like this:

setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

The layout is being set like "fill_parent". Why?

The layout attributes of the ListView and ListView item are all set to "wrap_content".
Any suggestion? Thanks.

Body:
I faced the same problem. The only solution I found is to set the PopupWindow width to the exact width of the ListView:

listView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
final PopupWindow popup = new PopupWindow(listView, listView.getMeasuredWidth(),
    ViewGroup.LayoutParams.WRAP_CONTENT, true);
popup.showAsDropDown(anchor);

Unfortunately, it doesn't solve the problem entirely. The ListView measures itself so that it can wrap only its first child. If for example the second child is wider than the first one, the second child will be clipped.

I'm not sure, but the only way to change the way the ListView measures itself is to subclass it and override the onMeasure() method. I'm trying to do it now and I'll write a comment here if I succeed in it.


问:
How to safely downgrade apache version to one not suitable for current gnome state?
I want to downgrade apache2-bin package from 2.4 version to 2.2.22-1 from some snapshot repository. But there is gnome-user-share pack that depends on apache2-bin 2.4 and, as I understood, the part of gnome-core packet. And the last revers-depends on gnome.

So I have dependency: apache2-bin (2.4) < gnome-user-share < gnome-core < gnome

How can I accurately change version of apache2-bin pack to 2.2.22-1 but staying at as less changes as possible in the system (desktop environment)?

答:
The gnome core and gnome packages are empty , it's removing does nothing harmful.

It can be removed freely and forwardly instaled apache2.2-bin.