prompt
stringlengths
48
2.37k
chosen
stringlengths
7
4.28k
rejected
stringlengths
11
4.44k
Question: I'm trying to create a batch file which asks a user a question with multiple (four) options. The options that the user chooses should trigger the batch file to ignore one of the four options. Lets say that the commands that I would normally want to run is ECHO "A", ECHO "B", ECHO "C", ECHO "D". If the person puts A in, I would want them to still run all the other commands except ECHO "A". Currently the solution i have come up with is the following ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( ECHO "B" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==B ( ECHO "A" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==C ( ECHO "A" ECHO "B" ECHO "D" EXIT /b ) else if %choice%==D ( ECHO "A" ECHO "B" ECHO "C" EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) ``` However as you can imagine, i am using the echo commands as an example/abstraction. The actual commands are longer. It seems more efficient to define the commands under A, B, C and D once and then tell the batch file not to doA, B, C or D depending the users choice. Maybe it's because I started working early today but I cannot think of an easier way to do this right now. So I hope to hear your ideas on how to make this batch script less clogged up. Answer:
Something like this : ``` @echo off setlocal enabledelayedexpansion set "$Command=A B C D" set /p "$choice=Do you want not to do: A, B, C or D? " set "$Command=!$Command:%$choice%=!" for %%a in (!$command!) do echo %%a ```
This type of problems may be easily solved using an [array](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990); the code is clearer and more flexible. I also suggest you to use `choice` command instead of `set /P` in order to achieve this type of selections. ``` @echo off setlocal EnableDelayedExpansion rem Define all the options/commands set option[1]=ECHO "A" set option[2]=ECHO "B" set option[3]=ECHO "C" set option[4]=ECHO "D" choice /C ABCD /M "Do you want not to do: A, B, C or D" rem Eliminate the not wanted option set "option[%errorlevel%]=" rem Execute the remaining options for /F "tokens=1* delims==" %%a in ('set option[') do %%b ```
Question: I'm trying to create a batch file which asks a user a question with multiple (four) options. The options that the user chooses should trigger the batch file to ignore one of the four options. Lets say that the commands that I would normally want to run is ECHO "A", ECHO "B", ECHO "C", ECHO "D". If the person puts A in, I would want them to still run all the other commands except ECHO "A". Currently the solution i have come up with is the following ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( ECHO "B" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==B ( ECHO "A" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==C ( ECHO "A" ECHO "B" ECHO "D" EXIT /b ) else if %choice%==D ( ECHO "A" ECHO "B" ECHO "C" EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) ``` However as you can imagine, i am using the echo commands as an example/abstraction. The actual commands are longer. It seems more efficient to define the commands under A, B, C and D once and then tell the batch file not to doA, B, C or D depending the users choice. Maybe it's because I started working early today but I cannot think of an easier way to do this right now. So I hope to hear your ideas on how to make this batch script less clogged up. Answer:
The idea in this code is that it only skips the one that you choose. ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if "%choice%"=="" ( ECHO Please select A, B, C or D! EXIT /b ) if not %choice%==A ( ECHO "A" ) if not %choice%==B ( ECHO "B" ) if not %choice%==C ( ECHO "C" ) if not %choice%==D ( ECHO "D" ) exit /b ```
This should do the trick. After a "CALL" the batch "jumps back" and will do the next step: ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( CALL :B CALL :C CALL :D EXIT /b ) else if %choice%==B ( CALL :A CALL :C CALL :D EXIT /b ) else if %choice%==C ( CALL :A CALL :B CALL :D EXIT /b ) else if %choice%==D ( CALL :A CALL :B CALL :C EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) :A <Function here> GOTO :EOF :B <Function here> GOTO :EOF :C <Function here> GOTO :EOF :D <Function here> GOTO :EOF ```
Question: I'm trying to create a batch file which asks a user a question with multiple (four) options. The options that the user chooses should trigger the batch file to ignore one of the four options. Lets say that the commands that I would normally want to run is ECHO "A", ECHO "B", ECHO "C", ECHO "D". If the person puts A in, I would want them to still run all the other commands except ECHO "A". Currently the solution i have come up with is the following ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if %choice%==A ( ECHO "B" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==B ( ECHO "A" ECHO "C" ECHO "D" EXIT /b ) else if %choice%==C ( ECHO "A" ECHO "B" ECHO "D" EXIT /b ) else if %choice%==D ( ECHO "A" ECHO "B" ECHO "C" EXIT /b ) ELSE ( ECHO Please select A, B, C or D! EXIT /b ) ``` However as you can imagine, i am using the echo commands as an example/abstraction. The actual commands are longer. It seems more efficient to define the commands under A, B, C and D once and then tell the batch file not to doA, B, C or D depending the users choice. Maybe it's because I started working early today but I cannot think of an easier way to do this right now. So I hope to hear your ideas on how to make this batch script less clogged up. Answer:
The idea in this code is that it only skips the one that you choose. ``` @echo off set /p choice="Do you want not to do: A, B, C or D? [A/B/C/D] " [A/B/C/D] if "%choice%"=="" ( ECHO Please select A, B, C or D! EXIT /b ) if not %choice%==A ( ECHO "A" ) if not %choice%==B ( ECHO "B" ) if not %choice%==C ( ECHO "C" ) if not %choice%==D ( ECHO "D" ) exit /b ```
This type of problems may be easily solved using an [array](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990); the code is clearer and more flexible. I also suggest you to use `choice` command instead of `set /P` in order to achieve this type of selections. ``` @echo off setlocal EnableDelayedExpansion rem Define all the options/commands set option[1]=ECHO "A" set option[2]=ECHO "B" set option[3]=ECHO "C" set option[4]=ECHO "D" choice /C ABCD /M "Do you want not to do: A, B, C or D" rem Eliminate the not wanted option set "option[%errorlevel%]=" rem Execute the remaining options for /F "tokens=1* delims==" %%a in ('set option[') do %%b ```
Question: This feels like it should be simple but it's been driving me crazy. I've got a function `indent-or-expand` that I'd like to remap to `tab` but I simply can't get it to work (Emacs v24, OS X). The only help I've been able to get from Emacs itself is: > > error "To bind the key TAB, use \"\\t\", not [TAB]" > > > Doing `(global-set-key [\"\\t\"] 'indent-or-expand)` binds the function to `<"\t">` apparently (whatever that is), and every combination I've tried of `\`, `"`, `[``]`, and `(``)` has failed. I DID manage to bind the function to `t`, though... Answer:
In addition to what others have told you: 1. The Emacs error message you cite told you to use "\t", and if you use that you should be OK: (global-set-key "\t" 'indent-or-expand) 2. Be aware also that `TAB` is one thing and `<tab>` might be another thing. IOW, it depends what code your physical keyboard `Tab` key actually sends to Emacs. `TAB` is the tab character, and it i the same as ACSCII control character `C-i`, that is, `Control` + `i`, which has decimal integer value 9. `<tab>` is (in Emacs) a pseudo function key. (Most likely `TAB` is what you want. Use `C-h k` to see what your physical `Tab` key does.)
Use the `kbd` function, i.e.: ``` (global-set-key (kbd "TAB") ...) ```
Question: In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun? Answer:
You can't, really ----------------- As I was learning French (English is my first language) the idea of gender of objects can be difficult to grasp. Genders are pretty much arbitrary and is something you just have to remember with each word (this means remembering it as *"une fenêtre"* rather than *"fenêtre"*). You can also always listen for a [*liaison*](https://en.wikipedia.org/wiki/Liaison_(French)). But usually when speaking with a fluent speaker this can be quite subtle, and difficult to listen to. General Rules ------------- That said, they are *some general* patterns which can be used to distinguish the gender of a noun but these **are not rules**, and are only generally followed: * Things originating in France *tend* to be feminine. e.g. `une crêpe`, or `une pizza` * Things originating in America *tend* to be masculine e.g. `Un burger` **BIG DISCLAIMER:** These **are not rules at all**, these are just observations I have made. --- ### Spelling Nouns ending in the following tend to be masculine: * `ge` * `le` (that aren't `-lle`, `-ole`, `-ale`, or `-ule`) * `me` * `re` (that isn't `-ure`) * `phe` * `age` source: @bleh Nouns ending in the following tend to be feminine: * `on` * `é` * `eur` [[source]](http://www.languageguide.org/french/grammar/gender/rule.html) Feminine nouns tend to have `e` at the end too but *many* masculine nouns also have `e` at the end --- While some genders *tend* to have certain endings, there isn't any definite cut and dry to determine the gender of a word without memorizing it. You *can* memorize some common endings though to make better guesses. [This question on French.SE](https://french.stackexchange.com/q/2616/7385) might provide more information on this.
### Yes; rules exist, but they predict gender mostly with at least 80% (but not 100%) accuracy.To see what the rules are, please see the Linguistics papers below. [The other answer here](https://languagelearning.stackexchange.com/a/45/90) troubles me because it does not state all the detailed rules discovered in the Linguistics papers below, and so may discourage French learners from benefitting from rules discovered by linguists by possibly misleading them into losing hope and relying on only memorisation. May I repeat my answer to [a similar question on FSE](https://french.stackexchange.com/a/16778/1995): See * [*Predictability in French gender attribution: A corpus analysis* by Roy Lyster](http://personnel.mcgill.ca/files/roy.lyster/Lyster2006_JFLS.pdf) I quote from the last paragraph (from p 22 of the PDF of 24 pages above) which answers your question more optimistically: > >   Gender attribution rules based on noun endings, given their reliability and > systematicity, are worthy of more attention in French reference books and French > L2 > classrooms. The foregoing corpus-based study confirmed that predictive rules for > gender attribution do exist and apply to as many as > 80 > per cent of the nearly > 10,000 > nouns included in the analysis. More importantly, classroom studies have demonstrated that gender attribution rules are both teachable and learnable. Regardless of > age, L2 > learners can benefit from form-focused instructional activities that promote > awareness of gender attribution rules and that provide opportunities for practice > in associating grammatical gender with orthographic representations of constituent > rhymes of literally thousands of nouns—both animate and inanimate alike. > > > * [*Adult L2 Acquisition of French Grammatical Gender: investigating sensitivity to phonological and morphological gender cues*](http://www.cs.cmu.edu/%7Ecsisso/docs/honoursThesis.pdf)
Question: In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun? Answer:
You can't, really ----------------- As I was learning French (English is my first language) the idea of gender of objects can be difficult to grasp. Genders are pretty much arbitrary and is something you just have to remember with each word (this means remembering it as *"une fenêtre"* rather than *"fenêtre"*). You can also always listen for a [*liaison*](https://en.wikipedia.org/wiki/Liaison_(French)). But usually when speaking with a fluent speaker this can be quite subtle, and difficult to listen to. General Rules ------------- That said, they are *some general* patterns which can be used to distinguish the gender of a noun but these **are not rules**, and are only generally followed: * Things originating in France *tend* to be feminine. e.g. `une crêpe`, or `une pizza` * Things originating in America *tend* to be masculine e.g. `Un burger` **BIG DISCLAIMER:** These **are not rules at all**, these are just observations I have made. --- ### Spelling Nouns ending in the following tend to be masculine: * `ge` * `le` (that aren't `-lle`, `-ole`, `-ale`, or `-ule`) * `me` * `re` (that isn't `-ure`) * `phe` * `age` source: @bleh Nouns ending in the following tend to be feminine: * `on` * `é` * `eur` [[source]](http://www.languageguide.org/french/grammar/gender/rule.html) Feminine nouns tend to have `e` at the end too but *many* masculine nouns also have `e` at the end --- While some genders *tend* to have certain endings, there isn't any definite cut and dry to determine the gender of a word without memorizing it. You *can* memorize some common endings though to make better guesses. [This question on French.SE](https://french.stackexchange.com/q/2616/7385) might provide more information on this.
Grammatical gender in French is pretty much arbitrary. There's not much to understand. Sorry. The usual tip when learning a language with (mostly) arbitrary grammatical gender like French or German is to **always learn the article with the noun**. When you learn the word for *car*, learn “la voiture” or “une voiture”. I think I the definite article is taught more often, but it has a downside of hiding the gender if the word starts with a vowel sound: better learn “un arbre” than “l'arbre”. Make sure you understand the pronunciation of the indefinite article though: “une arme” and “un arbre” only differ by the vowel sound (and the noun itself), since the E in *une* is silent and the N in *un* is sounded due to the *liaison* with the following vowel. Nouns that specifically designate male people (or animals) are masculine. Ditto for females and feminine nouns. (There are a few exceptions with professions that are traditionally gendered.) These nouns usually come in pairs, e.g. “père/mère” (father/mother), “acteur/actrice” (actor/actress), “chat/chatte” (male/female cat). With such pairs, apart from a few common words, the male and female forms differ only by a suffix, the female suffix always ends with `-e`, and the suffixes mostly follow the same patterns as for adjectives. Apart from that, you can't rely on the meaning of the word. Even if two nouns are synonyms, that doesn't make it more likely that they have the same gender. You can **sometimes** rely on the **ending** of the word. [Many word endings are strongly gendered](https://french.stackexchange.com/questions/2616/is-there-any-general-rule-to-determine-the-gender-of-a-noun-based-on-its-spellin/16781#16781). You may want to learn the most common ones, but I'm not convinced of the effectiveness of this approach: that's one more arbitrary classification to learn, and most classes have exceptions that you'd need to learn anyway. I think (but I have no data or personal experience to support it) that it would be more effective to learn nouns on an individual basis. Once you know a critical mass of nouns, you can start looking for patterns: if you're unsure about the gender of a noun, try to think of a few words with the same ending; if they all have the same gender then chances are that the noun you're wondering about has the same gender. What works better than endings is **suffixes**. Many suffixes have a single gender. If a word is built from a stem and a suffix, then once you recognize the suffix, you know the gender of the noun. For example, *-tion* is exclusively a feminine suffix, so any word built with that suffix is feminine, e.g. you don't need to learn words like *vasoconstriction* or *mobilisation* to know their gender. But there are a couple of words that just happen to end with those letters (e.g. *cation* is not *ca-* + *-tion*, *gestion* is not *ges-* + *-tion*), and they can be of either gender. (In this case, recognizing the suffix also tells you the pronunciation of the word: the suffix *-tion* is pronounced [sjɔ̃], but the letters “tion” are otherwise pronounced [tjɔ̃].)
Question: In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun? Answer:
You can't, really ----------------- As I was learning French (English is my first language) the idea of gender of objects can be difficult to grasp. Genders are pretty much arbitrary and is something you just have to remember with each word (this means remembering it as *"une fenêtre"* rather than *"fenêtre"*). You can also always listen for a [*liaison*](https://en.wikipedia.org/wiki/Liaison_(French)). But usually when speaking with a fluent speaker this can be quite subtle, and difficult to listen to. General Rules ------------- That said, they are *some general* patterns which can be used to distinguish the gender of a noun but these **are not rules**, and are only generally followed: * Things originating in France *tend* to be feminine. e.g. `une crêpe`, or `une pizza` * Things originating in America *tend* to be masculine e.g. `Un burger` **BIG DISCLAIMER:** These **are not rules at all**, these are just observations I have made. --- ### Spelling Nouns ending in the following tend to be masculine: * `ge` * `le` (that aren't `-lle`, `-ole`, `-ale`, or `-ule`) * `me` * `re` (that isn't `-ure`) * `phe` * `age` source: @bleh Nouns ending in the following tend to be feminine: * `on` * `é` * `eur` [[source]](http://www.languageguide.org/french/grammar/gender/rule.html) Feminine nouns tend to have `e` at the end too but *many* masculine nouns also have `e` at the end --- While some genders *tend* to have certain endings, there isn't any definite cut and dry to determine the gender of a word without memorizing it. You *can* memorize some common endings though to make better guesses. [This question on French.SE](https://french.stackexchange.com/q/2616/7385) might provide more information on this.
On a more practical note, [here](https://drive.google.com/file/d/0B5iHCwiV-v7RLVRLVVZxX0xQQnM/view?pref=2&pli=1) is a cheat sheet for french gender, and [the accompanying article](http://www.languagecrawler.com/2015/06/cheat-sheet-for-learning-gender-of.html) suggests that *"glancing at this seven-page chart every once in a while helped solidify things"*.
Question: In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun? Answer:
You can't, really ----------------- As I was learning French (English is my first language) the idea of gender of objects can be difficult to grasp. Genders are pretty much arbitrary and is something you just have to remember with each word (this means remembering it as *"une fenêtre"* rather than *"fenêtre"*). You can also always listen for a [*liaison*](https://en.wikipedia.org/wiki/Liaison_(French)). But usually when speaking with a fluent speaker this can be quite subtle, and difficult to listen to. General Rules ------------- That said, they are *some general* patterns which can be used to distinguish the gender of a noun but these **are not rules**, and are only generally followed: * Things originating in France *tend* to be feminine. e.g. `une crêpe`, or `une pizza` * Things originating in America *tend* to be masculine e.g. `Un burger` **BIG DISCLAIMER:** These **are not rules at all**, these are just observations I have made. --- ### Spelling Nouns ending in the following tend to be masculine: * `ge` * `le` (that aren't `-lle`, `-ole`, `-ale`, or `-ule`) * `me` * `re` (that isn't `-ure`) * `phe` * `age` source: @bleh Nouns ending in the following tend to be feminine: * `on` * `é` * `eur` [[source]](http://www.languageguide.org/french/grammar/gender/rule.html) Feminine nouns tend to have `e` at the end too but *many* masculine nouns also have `e` at the end --- While some genders *tend* to have certain endings, there isn't any definite cut and dry to determine the gender of a word without memorizing it. You *can* memorize some common endings though to make better guesses. [This question on French.SE](https://french.stackexchange.com/q/2616/7385) might provide more information on this.
The best way to learn the grammatical gender is by practice and by using a French dictionary where *nf* refers to "nom féminin" (feminine noun) and *nm* refers to "nom musculin" (masculine noun). Please note that the grammatical gender is sometimes confusing. I speak French and Arabic (native language), and there are some objects which are feminine in Arabic and masculine in French e.g. airplane, and vice versa e.g. chair.
Question: In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun? Answer:
### Yes; rules exist, but they predict gender mostly with at least 80% (but not 100%) accuracy.To see what the rules are, please see the Linguistics papers below. [The other answer here](https://languagelearning.stackexchange.com/a/45/90) troubles me because it does not state all the detailed rules discovered in the Linguistics papers below, and so may discourage French learners from benefitting from rules discovered by linguists by possibly misleading them into losing hope and relying on only memorisation. May I repeat my answer to [a similar question on FSE](https://french.stackexchange.com/a/16778/1995): See * [*Predictability in French gender attribution: A corpus analysis* by Roy Lyster](http://personnel.mcgill.ca/files/roy.lyster/Lyster2006_JFLS.pdf) I quote from the last paragraph (from p 22 of the PDF of 24 pages above) which answers your question more optimistically: > >   Gender attribution rules based on noun endings, given their reliability and > systematicity, are worthy of more attention in French reference books and French > L2 > classrooms. The foregoing corpus-based study confirmed that predictive rules for > gender attribution do exist and apply to as many as > 80 > per cent of the nearly > 10,000 > nouns included in the analysis. More importantly, classroom studies have demonstrated that gender attribution rules are both teachable and learnable. Regardless of > age, L2 > learners can benefit from form-focused instructional activities that promote > awareness of gender attribution rules and that provide opportunities for practice > in associating grammatical gender with orthographic representations of constituent > rhymes of literally thousands of nouns—both animate and inanimate alike. > > > * [*Adult L2 Acquisition of French Grammatical Gender: investigating sensitivity to phonological and morphological gender cues*](http://www.cs.cmu.edu/%7Ecsisso/docs/honoursThesis.pdf)
On a more practical note, [here](https://drive.google.com/file/d/0B5iHCwiV-v7RLVRLVVZxX0xQQnM/view?pref=2&pli=1) is a cheat sheet for french gender, and [the accompanying article](http://www.languagecrawler.com/2015/06/cheat-sheet-for-learning-gender-of.html) suggests that *"glancing at this seven-page chart every once in a while helped solidify things"*.
Question: In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun? Answer:
### Yes; rules exist, but they predict gender mostly with at least 80% (but not 100%) accuracy.To see what the rules are, please see the Linguistics papers below. [The other answer here](https://languagelearning.stackexchange.com/a/45/90) troubles me because it does not state all the detailed rules discovered in the Linguistics papers below, and so may discourage French learners from benefitting from rules discovered by linguists by possibly misleading them into losing hope and relying on only memorisation. May I repeat my answer to [a similar question on FSE](https://french.stackexchange.com/a/16778/1995): See * [*Predictability in French gender attribution: A corpus analysis* by Roy Lyster](http://personnel.mcgill.ca/files/roy.lyster/Lyster2006_JFLS.pdf) I quote from the last paragraph (from p 22 of the PDF of 24 pages above) which answers your question more optimistically: > >   Gender attribution rules based on noun endings, given their reliability and > systematicity, are worthy of more attention in French reference books and French > L2 > classrooms. The foregoing corpus-based study confirmed that predictive rules for > gender attribution do exist and apply to as many as > 80 > per cent of the nearly > 10,000 > nouns included in the analysis. More importantly, classroom studies have demonstrated that gender attribution rules are both teachable and learnable. Regardless of > age, L2 > learners can benefit from form-focused instructional activities that promote > awareness of gender attribution rules and that provide opportunities for practice > in associating grammatical gender with orthographic representations of constituent > rhymes of literally thousands of nouns—both animate and inanimate alike. > > > * [*Adult L2 Acquisition of French Grammatical Gender: investigating sensitivity to phonological and morphological gender cues*](http://www.cs.cmu.edu/%7Ecsisso/docs/honoursThesis.pdf)
The best way to learn the grammatical gender is by practice and by using a French dictionary where *nf* refers to "nom féminin" (feminine noun) and *nm* refers to "nom musculin" (masculine noun). Please note that the grammatical gender is sometimes confusing. I speak French and Arabic (native language), and there are some objects which are feminine in Arabic and masculine in French e.g. airplane, and vice versa e.g. chair.
Question: In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun? Answer:
Grammatical gender in French is pretty much arbitrary. There's not much to understand. Sorry. The usual tip when learning a language with (mostly) arbitrary grammatical gender like French or German is to **always learn the article with the noun**. When you learn the word for *car*, learn “la voiture” or “une voiture”. I think I the definite article is taught more often, but it has a downside of hiding the gender if the word starts with a vowel sound: better learn “un arbre” than “l'arbre”. Make sure you understand the pronunciation of the indefinite article though: “une arme” and “un arbre” only differ by the vowel sound (and the noun itself), since the E in *une* is silent and the N in *un* is sounded due to the *liaison* with the following vowel. Nouns that specifically designate male people (or animals) are masculine. Ditto for females and feminine nouns. (There are a few exceptions with professions that are traditionally gendered.) These nouns usually come in pairs, e.g. “père/mère” (father/mother), “acteur/actrice” (actor/actress), “chat/chatte” (male/female cat). With such pairs, apart from a few common words, the male and female forms differ only by a suffix, the female suffix always ends with `-e`, and the suffixes mostly follow the same patterns as for adjectives. Apart from that, you can't rely on the meaning of the word. Even if two nouns are synonyms, that doesn't make it more likely that they have the same gender. You can **sometimes** rely on the **ending** of the word. [Many word endings are strongly gendered](https://french.stackexchange.com/questions/2616/is-there-any-general-rule-to-determine-the-gender-of-a-noun-based-on-its-spellin/16781#16781). You may want to learn the most common ones, but I'm not convinced of the effectiveness of this approach: that's one more arbitrary classification to learn, and most classes have exceptions that you'd need to learn anyway. I think (but I have no data or personal experience to support it) that it would be more effective to learn nouns on an individual basis. Once you know a critical mass of nouns, you can start looking for patterns: if you're unsure about the gender of a noun, try to think of a few words with the same ending; if they all have the same gender then chances are that the noun you're wondering about has the same gender. What works better than endings is **suffixes**. Many suffixes have a single gender. If a word is built from a stem and a suffix, then once you recognize the suffix, you know the gender of the noun. For example, *-tion* is exclusively a feminine suffix, so any word built with that suffix is feminine, e.g. you don't need to learn words like *vasoconstriction* or *mobilisation* to know their gender. But there are a couple of words that just happen to end with those letters (e.g. *cation* is not *ca-* + *-tion*, *gestion* is not *ges-* + *-tion*), and they can be of either gender. (In this case, recognizing the suffix also tells you the pronunciation of the word: the suffix *-tion* is pronounced [sjɔ̃], but the letters “tion” are otherwise pronounced [tjɔ̃].)
On a more practical note, [here](https://drive.google.com/file/d/0B5iHCwiV-v7RLVRLVVZxX0xQQnM/view?pref=2&pli=1) is a cheat sheet for french gender, and [the accompanying article](http://www.languagecrawler.com/2015/06/cheat-sheet-for-learning-gender-of.html) suggests that *"glancing at this seven-page chart every once in a while helped solidify things"*.
Question: In French, some nouns are considered male and some female (le/la). Is there a way which can help me understand which grammatical gender to use with which noun? Answer:
Grammatical gender in French is pretty much arbitrary. There's not much to understand. Sorry. The usual tip when learning a language with (mostly) arbitrary grammatical gender like French or German is to **always learn the article with the noun**. When you learn the word for *car*, learn “la voiture” or “une voiture”. I think I the definite article is taught more often, but it has a downside of hiding the gender if the word starts with a vowel sound: better learn “un arbre” than “l'arbre”. Make sure you understand the pronunciation of the indefinite article though: “une arme” and “un arbre” only differ by the vowel sound (and the noun itself), since the E in *une* is silent and the N in *un* is sounded due to the *liaison* with the following vowel. Nouns that specifically designate male people (or animals) are masculine. Ditto for females and feminine nouns. (There are a few exceptions with professions that are traditionally gendered.) These nouns usually come in pairs, e.g. “père/mère” (father/mother), “acteur/actrice” (actor/actress), “chat/chatte” (male/female cat). With such pairs, apart from a few common words, the male and female forms differ only by a suffix, the female suffix always ends with `-e`, and the suffixes mostly follow the same patterns as for adjectives. Apart from that, you can't rely on the meaning of the word. Even if two nouns are synonyms, that doesn't make it more likely that they have the same gender. You can **sometimes** rely on the **ending** of the word. [Many word endings are strongly gendered](https://french.stackexchange.com/questions/2616/is-there-any-general-rule-to-determine-the-gender-of-a-noun-based-on-its-spellin/16781#16781). You may want to learn the most common ones, but I'm not convinced of the effectiveness of this approach: that's one more arbitrary classification to learn, and most classes have exceptions that you'd need to learn anyway. I think (but I have no data or personal experience to support it) that it would be more effective to learn nouns on an individual basis. Once you know a critical mass of nouns, you can start looking for patterns: if you're unsure about the gender of a noun, try to think of a few words with the same ending; if they all have the same gender then chances are that the noun you're wondering about has the same gender. What works better than endings is **suffixes**. Many suffixes have a single gender. If a word is built from a stem and a suffix, then once you recognize the suffix, you know the gender of the noun. For example, *-tion* is exclusively a feminine suffix, so any word built with that suffix is feminine, e.g. you don't need to learn words like *vasoconstriction* or *mobilisation* to know their gender. But there are a couple of words that just happen to end with those letters (e.g. *cation* is not *ca-* + *-tion*, *gestion* is not *ges-* + *-tion*), and they can be of either gender. (In this case, recognizing the suffix also tells you the pronunciation of the word: the suffix *-tion* is pronounced [sjɔ̃], but the letters “tion” are otherwise pronounced [tjɔ̃].)
The best way to learn the grammatical gender is by practice and by using a French dictionary where *nf* refers to "nom féminin" (feminine noun) and *nm* refers to "nom musculin" (masculine noun). Please note that the grammatical gender is sometimes confusing. I speak French and Arabic (native language), and there are some objects which are feminine in Arabic and masculine in French e.g. airplane, and vice versa e.g. chair.
Question: I want to display different types of objects in the same ajax called controller function. I want to render out when I send back an ajax call. The problem is I want the "title" attribute of one object and the "name" attribute of another object. I can't render 2 partials and can seem to figure out how to check the type of object an object is. How do I solve this problem? Here is my current controller setup (NOT CORRECT) ``` @objects = Obj.find(:all,:conditions => ["name Like ?", "#{prefix}%"]) @moreObjects = ObjTwo.find(:all,:conditions => ["title Like ?","#{prefix}%"]) if @objects.empty? render :text => "No Matches" else render :partial => 'one', :collection => @objects end if @moreObjects.empty? render :text => "No Matches" else render :partial => 'two', :collection => @moreObjects end ``` Answer:
try something like ``` <%= obj.title if obj.respond_to?(:title) %> ```
You could use [Object.is\_a?](http://apidock.com/ruby/Object/is_a%3F) but that's not a very clean solution. You could also try mapping your data before presentation to help keep your views lightweight.
Question: I want to display different types of objects in the same ajax called controller function. I want to render out when I send back an ajax call. The problem is I want the "title" attribute of one object and the "name" attribute of another object. I can't render 2 partials and can seem to figure out how to check the type of object an object is. How do I solve this problem? Here is my current controller setup (NOT CORRECT) ``` @objects = Obj.find(:all,:conditions => ["name Like ?", "#{prefix}%"]) @moreObjects = ObjTwo.find(:all,:conditions => ["title Like ?","#{prefix}%"]) if @objects.empty? render :text => "No Matches" else render :partial => 'one', :collection => @objects end if @moreObjects.empty? render :text => "No Matches" else render :partial => 'two', :collection => @moreObjects end ``` Answer:
try something like ``` <%= obj.title if obj.respond_to?(:title) %> ```
Here's one option that doesn't involve checking its type - in your Obj and ObjTwo classes add a new method: ``` def fancy_pants title end def fancy_pants name end ``` Then you can combine `@objects` and `@moreObjects` - you'll only need one if statement and one partial. ``` @search_domination = @objects + @moreObjects if @search_domination.empty? render :text => "No Matches" else render :partial => 'one', :collection => @search_domination end ```
Question: I want to display different types of objects in the same ajax called controller function. I want to render out when I send back an ajax call. The problem is I want the "title" attribute of one object and the "name" attribute of another object. I can't render 2 partials and can seem to figure out how to check the type of object an object is. How do I solve this problem? Here is my current controller setup (NOT CORRECT) ``` @objects = Obj.find(:all,:conditions => ["name Like ?", "#{prefix}%"]) @moreObjects = ObjTwo.find(:all,:conditions => ["title Like ?","#{prefix}%"]) if @objects.empty? render :text => "No Matches" else render :partial => 'one', :collection => @objects end if @moreObjects.empty? render :text => "No Matches" else render :partial => 'two', :collection => @moreObjects end ``` Answer:
Here's one option that doesn't involve checking its type - in your Obj and ObjTwo classes add a new method: ``` def fancy_pants title end def fancy_pants name end ``` Then you can combine `@objects` and `@moreObjects` - you'll only need one if statement and one partial. ``` @search_domination = @objects + @moreObjects if @search_domination.empty? render :text => "No Matches" else render :partial => 'one', :collection => @search_domination end ```
You could use [Object.is\_a?](http://apidock.com/ruby/Object/is_a%3F) but that's not a very clean solution. You could also try mapping your data before presentation to help keep your views lightweight.
Question: I am attempting to write a test case to ensure a Singleton class cannot be instantiated. The constructor for the Singleton is defined to be private so my test is as follows: ``` $this->expectError(); $test = new TestSingletonClassA(); ``` Instead of catching the error and passing the test, I get a 'PHP Fatal error: Call to private Singleton::\_\_construct()'. I've also tried passing a PatternExpectation as a parameter to expectError, but that didn't work either. Do you have any suggestions? Some background: php5.3, simpletest1.1a Answer:
If your php code throws a FATAL ERROR, it will never get to the phpunit, so you have to write "right" code in order to test it. If you call a private method, it will throw an excepcion, so it won't get to the phpunit. You have to change that. I think you have to mock the object. Try [these posts](http://sebastian-bergmann.de/archives/881-Testing-Your-Privates.html) about this subject (it's a series of 4 posts) and [these slides](http://www.slideshare.net/sebastian_bergmann/phpunit-best-practices) (from slide #43) .
i don't think it's possible to do it that way.. fatal errors are not catchable as i've understood it. you could use reflection to get the constructor method, and then make sure it has the access modifier "private". this is hard to test in most languages. for example java, c# and c++ would not even let you compile this code. so it could never be run at all D:
Question: I am attempting to write a test case to ensure a Singleton class cannot be instantiated. The constructor for the Singleton is defined to be private so my test is as follows: ``` $this->expectError(); $test = new TestSingletonClassA(); ``` Instead of catching the error and passing the test, I get a 'PHP Fatal error: Call to private Singleton::\_\_construct()'. I've also tried passing a PatternExpectation as a parameter to expectError, but that didn't work either. Do you have any suggestions? Some background: php5.3, simpletest1.1a Answer:
Unit testing frameworks cannot catch such things. But you can with [PHPT](http://qa.php.net/phpt_details.php) and similar regression test frameworks. You might have to jump through some hoops to hook it into PHPUnit, but there's probably ways to integrate it with the remaining tests. You'll just have to separate assertions and the special case where you expect the fatal error.
i don't think it's possible to do it that way.. fatal errors are not catchable as i've understood it. you could use reflection to get the constructor method, and then make sure it has the access modifier "private". this is hard to test in most languages. for example java, c# and c++ would not even let you compile this code. so it could never be run at all D:
Question: I am writing a function that returns a list of car models. The input is a string of comma separated cars. Duplicate entries are not added to the result. The elements in the list should be in the same order as they appear in the input string. If the input string is empty, the result is an empty list. I modified it to support multiple model names, e.g. `print(car_models("Tesla Model S,Skoda Super Lux Sport))` gives `['Model S', 'Super Lux Sport']`. ``` def car_models(all_cars: str) -> list: if not all_cars: return [] all_models = [] cars = all_cars.split(",") for car in cars: unique_car = car.split(" ") if unique_car[1] not in all_models: all_models.append(" ".join(unique_car[1:])) return all_models ``` While testing the code, an error occurred: [![enter image description here](https://i.stack.imgur.com/QlYDw.png)](https://i.stack.imgur.com/QlYDw.png) And I can't figure out what's wrong, can anyone tell me how to fix it? Answer:
Since you're appending `" ".join(unique_car[1:])` to the list, you need to use the same thing when checking if already exists. Solve this easily by assigning that to a variable, so you can use the same thing in the `in` test and `append()` call. ``` def car_models(all_cars: str) -> list: if not all_cars: return [] all_models = [] cars = all_cars.split(",") for car in cars: car_words = car.split(" ") model = " ".join(car_words[1:]) if model not in all_models: all_models.append(model) return all_models ```
First, I suppose you misspelled the command and should be like: > > print(car\_models("Tesla Model S","Skoda Super Lux Sport")) > > > And then, instead of: ``` unique_car = car.split(" ") ``` I should use something like: ``` unique_car = car[car.find(" ")+1:] ``` to have full name of the model compared. Even with:`unique_brand = car[:car.find(" ")]` you can be able to create a beautiful dictionary like: `{'brand1':[model1, model2], 'brand2':...}` Besides, if the problem is coming from the test, please share your test code.
Question: I am writing a function that returns a list of car models. The input is a string of comma separated cars. Duplicate entries are not added to the result. The elements in the list should be in the same order as they appear in the input string. If the input string is empty, the result is an empty list. I modified it to support multiple model names, e.g. `print(car_models("Tesla Model S,Skoda Super Lux Sport))` gives `['Model S', 'Super Lux Sport']`. ``` def car_models(all_cars: str) -> list: if not all_cars: return [] all_models = [] cars = all_cars.split(",") for car in cars: unique_car = car.split(" ") if unique_car[1] not in all_models: all_models.append(" ".join(unique_car[1:])) return all_models ``` While testing the code, an error occurred: [![enter image description here](https://i.stack.imgur.com/QlYDw.png)](https://i.stack.imgur.com/QlYDw.png) And I can't figure out what's wrong, can anyone tell me how to fix it? Answer:
Since you're appending `" ".join(unique_car[1:])` to the list, you need to use the same thing when checking if already exists. Solve this easily by assigning that to a variable, so you can use the same thing in the `in` test and `append()` call. ``` def car_models(all_cars: str) -> list: if not all_cars: return [] all_models = [] cars = all_cars.split(",") for car in cars: car_words = car.split(" ") model = " ".join(car_words[1:]) if model not in all_models: all_models.append(model) return all_models ```
Checking for the existence of some object in a list will not perform optimally when the list is very large. Better to use a set. Here are two versions. One without a set and the other with: ``` def car_models(all_cars): result = [] for car in all_cars.split(','): if (full_model := ' '.join(car.split()[1:])) not in result: result.append(full_model) return result def car_models(all_cars): result = [] resultset = set() for car in all_cars.split(','): if (full_model := ' '.join(car.split()[1:])) not in resultset: result.append(full_model) resultset.add(full_model) return result ``` **Note:** If order didn't matter (it does in this case) one could just use a set
Question: I am writing a function that returns a list of car models. The input is a string of comma separated cars. Duplicate entries are not added to the result. The elements in the list should be in the same order as they appear in the input string. If the input string is empty, the result is an empty list. I modified it to support multiple model names, e.g. `print(car_models("Tesla Model S,Skoda Super Lux Sport))` gives `['Model S', 'Super Lux Sport']`. ``` def car_models(all_cars: str) -> list: if not all_cars: return [] all_models = [] cars = all_cars.split(",") for car in cars: unique_car = car.split(" ") if unique_car[1] not in all_models: all_models.append(" ".join(unique_car[1:])) return all_models ``` While testing the code, an error occurred: [![enter image description here](https://i.stack.imgur.com/QlYDw.png)](https://i.stack.imgur.com/QlYDw.png) And I can't figure out what's wrong, can anyone tell me how to fix it? Answer:
Checking for the existence of some object in a list will not perform optimally when the list is very large. Better to use a set. Here are two versions. One without a set and the other with: ``` def car_models(all_cars): result = [] for car in all_cars.split(','): if (full_model := ' '.join(car.split()[1:])) not in result: result.append(full_model) return result def car_models(all_cars): result = [] resultset = set() for car in all_cars.split(','): if (full_model := ' '.join(car.split()[1:])) not in resultset: result.append(full_model) resultset.add(full_model) return result ``` **Note:** If order didn't matter (it does in this case) one could just use a set
First, I suppose you misspelled the command and should be like: > > print(car\_models("Tesla Model S","Skoda Super Lux Sport")) > > > And then, instead of: ``` unique_car = car.split(" ") ``` I should use something like: ``` unique_car = car[car.find(" ")+1:] ``` to have full name of the model compared. Even with:`unique_brand = car[:car.find(" ")]` you can be able to create a beautiful dictionary like: `{'brand1':[model1, model2], 'brand2':...}` Besides, if the problem is coming from the test, please share your test code.
Question: I'm getting a weird error when i try to set templateUrl in my component. This works: ``` @Component({ selector: 'buildingInfo', template: ` <html>stuff</html> ` }) ``` But when i do this (with the same content in the html-file): ``` @Component({ selector: 'buildingInfo', templateUrl: 'stuff.component.html' }) ``` the output is this: ``` <span>M</span> <span>M</span> <fakediscoveryelement></fakediscoveryelement> <span>M</span> <fakediscoveryelement></fakediscoveryelement> <span>M</span> <span>M</span> <span>M</span> <span>M</span> <span>M</span> <span>M</span> <span>M</span> <span>M</span> ``` I have no idea why this happens. I get the same output when i try to use a seperate file for html on almost all other components (but not all). Answer:
If you want Angular to find the templates relative to the Component e.g. you have a structure like app/ app/app.component.ts app/app.component.html make sure, you set the module id of the component. That'll cause the System loader to look relative to your current path. Otherwise, it will *always* expect the complete path as URL. Example for SystemJS: ``` declare var __moduleName: string; @Component({ moduleId: __moduleName, selector: 'foo-bar', templateUrl: 'app.component.html', }) ``` Example for others: ``` @Component({ moduleId: module.id, selector: 'foo-bar', templateUrl: 'app.component.html', }) ``` It took me some time to get this one :)
You can't have an `<html>` tag in your template. `<html>` is a top-level tag in an HTML file and an Angular application can only be used on or inside `<body>` and `<body>` can't contain an `<html>` tag.
Question: I am reading in another perl file and trying to find all strings surrounded by quotations within the file, single or multiline. I've matched all the single lines fine but I can't match the mulitlines without printing the entire line out, when I just want the string itself. For example, heres a snippet of what I'm reading in: ``` #!/usr/bin/env perl use warnings; use strict; # assign variable my $string = 'Hello World!'; my $string4 = "chmod"; my $string3 = "This is a fun multiple line string, please match"; ``` so the output I'd like is ``` 'Hello World!'; "chmod"; "This is a fun multiple line string, please match"; ``` but I am getting: ``` 'Hello World!'; my $string4 = "chmod"; my $string3 = "This is a fun multiple line string, please match"; ``` This is the code I am using to find the strings - all file content is stored in @contents: ``` my @strings_found = (); my $line; for(@contents) { $line .= $_; } if($line =~ /(['"](.?)*["'])/s) { push @strings_found,$1; } print @strings_found; ``` I am guessing I am only getting 'Hello World!'; correctly because I am using the $1 but I am not sure how else to find the others without looping line by line, which I would think would make it hard to find the multi line string as it doesn't know what the next line is. I know my regex is reasonably basic and doesn't account for some caveats but I just wanted to get the basic catch most regex working before moving on to more complex situations. Any pointers as to where I am going wrong? Answer:
Couple big things, you need to search in a `while` loop with the `g` modifier on your regex. And you also need to turn off greedy matching for what's inside the quotes by using `.*?`. ``` use strict; use warnings; my $contents = do {local $/; <DATA>}; my @strings_found = (); while ($contents =~ /(['"](.*?)["'])/sg) { push @strings_found, $1; } print "$_\n" for @strings_found; __DATA__ #!/usr/bin/env perl use warnings; use strict; # assign variable my $string = 'Hello World!'; my $string4 = "chmod"; my $string3 = "This is a fun multiple line string, please match"; ``` Outputs ``` 'Hello World!' "chmod" "This is a fun multiple line string, please match" ``` You aren't the first person to search for help with this homework problem. Here's a more detailed answer I gave to ... well ... you ;) [`finding words surround by quotations perl`](https://stackoverflow.com/questions/22418745/finding-words-surround-by-quotations-perl/22418809#22418809)
regexp matching (in perl and generally) are greedy by default. So your regexp will match from 1st ' or " to last. Print the length of your @strings\_found array. I think it will always be just 1 with the code you have. Change it to be not greedy by following \* with a ? /('"\*?["'])/s I think. It will work in a basic way. Regexps are kindof the wrong way to do this if you want a robust solution. You would want to write parsing code instead for that. If you have different quotes inside a string then greedy will give you the 1 biggest string. Non greedy will give you the smallest strings not caring if start or end quote are different. Read about greedy and non greedy. Also note the /m multiline modifier. <http://perldoc.perl.org/perlre.html#Regular-Expressions>
Question: Assume I have a dataframe: ``` Col1 Col2 Col3 Val a 1 a 2 a 1 a 3 a 1 b 5 b 1 a 10 b 1 a 20 b 1 a 25 ``` I want to aggregate across all columns and then attach this to my dataframe so that I have this output: ``` Col1 Col2 Col3 Val Tot a 1 a 2 10 a 1 a 3 10 a 1 b 5 10 b 1 a 10 55 b 1 a 20 55 b 1 a 25 55 ``` Is there something I can do with `tapply` to accomplish this? I'm a little stuck on the most efficient way. Answer:
No guarantees in terms of performance, but for each directory you could check its files to see if it contains any with the matching extension: ``` List<string> imageDirectories = Directory.GetDirectories(sourceTextBox.Text, "*", SearchOption.AllDirectories) .Where(d => Directory.EnumerateFiles(d) .Select(Path.GetExtension) .Where(ext => ext == ".png" || ext == ".jpg") .Any()) .ToList(); ```
There is no built in way of doing it, You can try something like this ``` var directories = Directory .GetDirectories(path, "*", SearchOption.AllDirectories) .Where(x=> Directory.EnumerateFiles(x, "*.jpg").Any() || Directory.EnumerateFiles(x, "*.png").Any()) .ToList(); ```
Question: Assume I have a dataframe: ``` Col1 Col2 Col3 Val a 1 a 2 a 1 a 3 a 1 b 5 b 1 a 10 b 1 a 20 b 1 a 25 ``` I want to aggregate across all columns and then attach this to my dataframe so that I have this output: ``` Col1 Col2 Col3 Val Tot a 1 a 2 10 a 1 a 3 10 a 1 b 5 10 b 1 a 10 55 b 1 a 20 55 b 1 a 25 55 ``` Is there something I can do with `tapply` to accomplish this? I'm a little stuck on the most efficient way. Answer:
No guarantees in terms of performance, but for each directory you could check its files to see if it contains any with the matching extension: ``` List<string> imageDirectories = Directory.GetDirectories(sourceTextBox.Text, "*", SearchOption.AllDirectories) .Where(d => Directory.EnumerateFiles(d) .Select(Path.GetExtension) .Where(ext => ext == ".png" || ext == ".jpg") .Any()) .ToList(); ```
You can use [`Directory.EnumerateFiles`](http://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles(v=vs.110).aspx) method to get the file matching criteria and then you can get their Path minus file name using `Path.GetDirectoryName` and add it to the `HashSet`. `HashSet` would only keep the unique entries. ``` HashSet<string> directories = new HashSet<string>(); foreach(var file in Directory.EnumerateFiles(sourceTextBox.Text, "*.png", SearchOption.AllDirectories)) { directories.Add(Path.GetDirectoryName(file)); } ``` For checking multiple file extensions you have to enumerate all files and then check for extension for each file like: ``` HashSet<string> directories = new HashSet<string>(); string[] allowableExtension = new [] {"jpg", "png"}; foreach(var file in Directory.EnumerateFiles(sourceTextBox.Text, "*", SearchOption.AllDirectories)) { string extension = Path.GetExtension(file); if (allowableExtension.Contains(extension)) { directories.Add(Path.GetDirectoryName(file)); } } ```
Question: Assume I have a dataframe: ``` Col1 Col2 Col3 Val a 1 a 2 a 1 a 3 a 1 b 5 b 1 a 10 b 1 a 20 b 1 a 25 ``` I want to aggregate across all columns and then attach this to my dataframe so that I have this output: ``` Col1 Col2 Col3 Val Tot a 1 a 2 10 a 1 a 3 10 a 1 b 5 10 b 1 a 10 55 b 1 a 20 55 b 1 a 25 55 ``` Is there something I can do with `tapply` to accomplish this? I'm a little stuck on the most efficient way. Answer:
There is no built in way of doing it, You can try something like this ``` var directories = Directory .GetDirectories(path, "*", SearchOption.AllDirectories) .Where(x=> Directory.EnumerateFiles(x, "*.jpg").Any() || Directory.EnumerateFiles(x, "*.png").Any()) .ToList(); ```
You can use [`Directory.EnumerateFiles`](http://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles(v=vs.110).aspx) method to get the file matching criteria and then you can get their Path minus file name using `Path.GetDirectoryName` and add it to the `HashSet`. `HashSet` would only keep the unique entries. ``` HashSet<string> directories = new HashSet<string>(); foreach(var file in Directory.EnumerateFiles(sourceTextBox.Text, "*.png", SearchOption.AllDirectories)) { directories.Add(Path.GetDirectoryName(file)); } ``` For checking multiple file extensions you have to enumerate all files and then check for extension for each file like: ``` HashSet<string> directories = new HashSet<string>(); string[] allowableExtension = new [] {"jpg", "png"}; foreach(var file in Directory.EnumerateFiles(sourceTextBox.Text, "*", SearchOption.AllDirectories)) { string extension = Path.GetExtension(file); if (allowableExtension.Contains(extension)) { directories.Add(Path.GetDirectoryName(file)); } } ```
Question: Hi I know that Flutter still doesn't support SVG files so I used flutter\_svg package, but for some reason, the svg file is not rendering the SVG file I want to use. What I want is use my custom SVG files as Icon in the bottomnavigation bar items. > > I want to use SVG icons so that I can easily change their colors when they are inactive or active (selected) > > > I call it like this: ``` BottomNavigationBarItem( icon: SvgPicture.asset("assets/svg_home.svg"), title: Text("Home"), activeIcon: Icon(Icons.category, color: Color(0xFFEF5123)), ), ``` Answer:
Fixed it ``` height: 20.0, width: 20.0, allowDrawingOutsideViewBox: true, ``` I'm beginning to slowly fall in love with flutter
Use property activeIcon also inside BottomNavigationBarItem ``` BottomNavigationBarItem( icon: SvgPicture.asset( icon, height: 20.0, width: 20.0, ), activeIcon: SvgPicture.asset( icon, height: 20.0, width: 20.0, color: Colors.pinkAccent, ), label: title, ); ``` SVG color changing will work now. Now use label instead of text.
Question: A long, long time ago, in a galaxy far away, I used to write programs in Delphi, and then if I needed something to happen really fast, I'd write those routines in hand-written assembler. It produced much faster code than the compiler did. But is this true **in practice** any more? Obviously hand-written assembler will always be at least as fast **in principle** as compiled high-level code. But CPUs have moved on a long way since those dark times. Now, if you were trying to optimize your assembler, you'd have to take into account ordering of instructions so they could be pipelined or run concurrently, the effect of branch prediction, and a million other things; and I suspect it's impossible to hold them all in human RAM simultaneously. So does this mean that a decent (but not superhuman) programmer will these days produce faster code by writing C than by writing hand-written assembler, at least when coding for a modern CPU? One other possibility that occurs to me. Does the optimization happen *before* the high-level language is turned into assembler, or afterwards? If it's afterwards... might it be faster to produce hand-written assembler, and then put it through the compiler's optimization process? The question arose recently when I was writing some code for a programming challenge, where the essence of it was to produce a routine that should run as fast as possible on a Raspberry Pi. I would have been allowed to write it in assembler; but my guess was that carefully written C would be faster, even though a Pi processor isn't that sophisticated in 2014 terms. To make the question more concrete and specific: * Suppose you're wanting to write blazingly fast (integer) number-crunching code to run on a Raspberry Pi. You've written some very nice C code that runs as a tight loop to solve the problem. Is it worth hand-crafting it in assembler to speed it up, or will that in practice give you something less efficient? Answer:
To me it looks both answers given so far are correct. The answer depends, among other things, on the particular CPU architecture we're talking about. The more complex architecture is, the harder it is to write efficient ASM code by hand. On one end of the spectrum are CISC cores such as x86. They have multiple execution units, long pipelines, variable instruction latencies per instruction, etc. In many cases ASM code that looks "clean" or "optimal" to a human isn't in fact optimal for a CPU and can be improved by using instructions or techniques from dark corners of processor manuals. Compilers "know" about this and can produce decently optimised code. True, in many cases emitted code can be improved by a skilful human, but with the right compiler and optimisations settings code is often already very good. Also, with C code at hand you won't need to re-optimise it manually for every new CPU generation (yes, optimisations often depend on particular CPU family, not only on instruction set), so writing in C is a way of "future-proofing" your code. On another end of the spectrum are simple RISC cores, such as 8051 (or others *simple* 8-bit controllers). They have much simpler scheduling semantics and smaller instruction sets. Compilers still do a decent job of optimisation here, but it's also much simpler to write a decent ASM code by hand (or fix performance issues in emitted code).
In practice decent C code *compiled with an optimizing compiler* is faster than assembler code, in particular once you need more than a few dozen of source code lines. Of course you need a good, recent, optimizing compiler. Cross-compiling with a recent [GCC](http://gcc.gnu.org/) tuned for your particular hardware (and software) system is welcome. So use options like `-O2 -mtune=native` (at least on x86) The point is that recent processors need, even for a "simple" instruction set, sophisticated instruction scheduling and register allocation, and compilers are quite good on that. For a few hundreds of lines, you won't have the patience to code the assembler code better than a good optimizing compiler could emit it. Of course, there might be exceptions (you need to benchmark). The most cost-effective way to add some assembler code is probably to use a few `asm` instructions *inside* some C function. [GCC](http://gcc.gnu.org/) has an [extended `asm` facility](https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html) quite good for that.
Question: A long, long time ago, in a galaxy far away, I used to write programs in Delphi, and then if I needed something to happen really fast, I'd write those routines in hand-written assembler. It produced much faster code than the compiler did. But is this true **in practice** any more? Obviously hand-written assembler will always be at least as fast **in principle** as compiled high-level code. But CPUs have moved on a long way since those dark times. Now, if you were trying to optimize your assembler, you'd have to take into account ordering of instructions so they could be pipelined or run concurrently, the effect of branch prediction, and a million other things; and I suspect it's impossible to hold them all in human RAM simultaneously. So does this mean that a decent (but not superhuman) programmer will these days produce faster code by writing C than by writing hand-written assembler, at least when coding for a modern CPU? One other possibility that occurs to me. Does the optimization happen *before* the high-level language is turned into assembler, or afterwards? If it's afterwards... might it be faster to produce hand-written assembler, and then put it through the compiler's optimization process? The question arose recently when I was writing some code for a programming challenge, where the essence of it was to produce a routine that should run as fast as possible on a Raspberry Pi. I would have been allowed to write it in assembler; but my guess was that carefully written C would be faster, even though a Pi processor isn't that sophisticated in 2014 terms. To make the question more concrete and specific: * Suppose you're wanting to write blazingly fast (integer) number-crunching code to run on a Raspberry Pi. You've written some very nice C code that runs as a tight loop to solve the problem. Is it worth hand-crafting it in assembler to speed it up, or will that in practice give you something less efficient? Answer:
To me it looks both answers given so far are correct. The answer depends, among other things, on the particular CPU architecture we're talking about. The more complex architecture is, the harder it is to write efficient ASM code by hand. On one end of the spectrum are CISC cores such as x86. They have multiple execution units, long pipelines, variable instruction latencies per instruction, etc. In many cases ASM code that looks "clean" or "optimal" to a human isn't in fact optimal for a CPU and can be improved by using instructions or techniques from dark corners of processor manuals. Compilers "know" about this and can produce decently optimised code. True, in many cases emitted code can be improved by a skilful human, but with the right compiler and optimisations settings code is often already very good. Also, with C code at hand you won't need to re-optimise it manually for every new CPU generation (yes, optimisations often depend on particular CPU family, not only on instruction set), so writing in C is a way of "future-proofing" your code. On another end of the spectrum are simple RISC cores, such as 8051 (or others *simple* 8-bit controllers). They have much simpler scheduling semantics and smaller instruction sets. Compilers still do a decent job of optimisation here, but it's also much simpler to write a decent ASM code by hand (or fix performance issues in emitted code).
Hand-written assembler is still faster than decent C code. If you knew how to write assembler you wouldn't believe what cruft some compilers generate. I have seen insane stuff like loading a value from memory and instantly writing it back unmodified (as recent as two years ago, I generally do not look at assembler output anymore). Here is an even more recent rant by Torvalds on a similar issue in gcc [lkml.org](https://lkml.org/lkml/2014/7/24/584). However, even though hand-written assembler is still faster, it generally does not pay off. At the maximum, you'll want to write some very performance critical short routines in assembler. The rest is better left in C for portability.
Question: How do we do this? Does it involve the fact that we know $f$ is continuous, and therefore the limit approaching the endpoint $1$ should be the same coming from both sides? Answer:
If $f(1)<2$ then $\epsilon=2-f(1)$ is positive. Since $f$ is continuous and $f(0)\ge 2$, then there exists some $c\in[0,1)$ such that $f(c)=2-\frac\epsilon2$. Contradiction.
An alternative topological solution: Since $f$ is continuous, $f(\overline{A}) \subset \overline{f(A)}$ for all $A \subset [0,1]$ Applying this to $[0,1)$: $f([0,1]) \subset \overline{f([0,1))} \subset \overline{[2,\infty)} = [2,\infty)$
Question: I am using Grails and I am currently faced with this problem. This is the result of my html table ![enter image description here](https://i.stack.imgur.com/QBAZY.png) And this is my code from the gsp page ``` <tr> <th>Device ID</th> <th>Device Type</th> <th>Status</th> <th>Customer</th> </tr> <tr> <g:each in = "${reqid}"> <td>${it.device_id}</td> </g:each> <g:each in ="${custname}"> <td>${it.type}</td> <td>${it.system_status}</td> <td>${it.username}</td> </g:each> </tr> ``` So the problem is, how do I format the table such that the "LHCT271 , 2 , Thomasyeo " will be shifted down accordingly? I've tried to add the `<tr>` tags here and there but it doesn't work.. any help please? Answer:
I think you problem is not in the view, but in the controller (or maybe even the domain). You must have some way of knowing that `reqid` and `custname` are related if they are in the same table. You must use that to construct an object that can be easily used in a g:each You are looking for a way to mix columns and rows, and still get a nice table. I'm afraid that is not possible. **Edit** (Sorry, I just saw the last comment.) You cannot mix two items in a g:each. Furthermore, if the two things are not related you probably must not put them in the same table. There will be no way for you or for Grails, to know how to properly organize the information
Do you want to display the first reqid against the first custname (three fields), the second againts the second and so on? And are those collections of same length? In such case you could try the following: ``` <tr> <th>Device ID</th> <th>Device Type</th> <th>Status</th> <th>Customer</th> </tr> <g:each var="req" in="${reqid}" status="i"> <tr> <td>${req}</td> <td>${custname[i].type}</td> <td>${custname[i].system_status}</td> <td>${custname[i].username}</td> </tr> </g:each> ```
Question: I have an input that I'd like to put a placeholder text in, but *only if* it's respective value is an empty string. The value that should go in the textbox is echoed from a PHP array, but if this value is empty, the placeholder should be echoed instead. At the moment, I've got this code: ``` <?php echo sponsorData('address0') == '' ? 'Address Line 1' : 'Other'; ?> ``` `sponsorData()` just gets stuff from an array; it's only argument is the key. The important bit here is it returns astring. This code gives odd behaviour; I get stuff like `Hello worldAddress Line 1`, where `Hello world` is the user typed text and `Address Line 1` is obviously the placeholder. Strangely, the placeholder gets stored into the array on submission. My question is this: can someone offer a correction of my ternary operator or, if that won't work, tell me to do an inline `if` statement (blegh)? Thanks Answer:
try the following code: ``` <?php echo ((sponsorData('address0') == '') ? 'Address Line 1' : 'Other'); ?> ``` felix
You seem to have this working ok, I don't think the error lies there. Here is how I would do it: ``` $address0 = sponsorData('address0'); $address0 = !empty($address0) ? $address0 : 'placeholder'; ```
Question: I have an input that I'd like to put a placeholder text in, but *only if* it's respective value is an empty string. The value that should go in the textbox is echoed from a PHP array, but if this value is empty, the placeholder should be echoed instead. At the moment, I've got this code: ``` <?php echo sponsorData('address0') == '' ? 'Address Line 1' : 'Other'; ?> ``` `sponsorData()` just gets stuff from an array; it's only argument is the key. The important bit here is it returns astring. This code gives odd behaviour; I get stuff like `Hello worldAddress Line 1`, where `Hello world` is the user typed text and `Address Line 1` is obviously the placeholder. Strangely, the placeholder gets stored into the array on submission. My question is this: can someone offer a correction of my ternary operator or, if that won't work, tell me to do an inline `if` statement (blegh)? Thanks Answer:
try the following code: ``` <?php echo ((sponsorData('address0') == '') ? 'Address Line 1' : 'Other'); ?> ``` felix
You have to consider that the `sponsorData('address0')` may have spaces, so you can add the `trim` function, like this: ``` <?php echo ((trim(sponsorData('address0')) == '') ? 'Address Line 1' : 'Other'); ?> ```
Question: I have an input that I'd like to put a placeholder text in, but *only if* it's respective value is an empty string. The value that should go in the textbox is echoed from a PHP array, but if this value is empty, the placeholder should be echoed instead. At the moment, I've got this code: ``` <?php echo sponsorData('address0') == '' ? 'Address Line 1' : 'Other'; ?> ``` `sponsorData()` just gets stuff from an array; it's only argument is the key. The important bit here is it returns astring. This code gives odd behaviour; I get stuff like `Hello worldAddress Line 1`, where `Hello world` is the user typed text and `Address Line 1` is obviously the placeholder. Strangely, the placeholder gets stored into the array on submission. My question is this: can someone offer a correction of my ternary operator or, if that won't work, tell me to do an inline `if` statement (blegh)? Thanks Answer:
You're running into operator precedence issues. Try: ``` <?php echo (sponsorData('address0') == '' ? 'Address Line 1' : 'Other'); ?> ``` (put brackets around the ternary operator statement).
You seem to have this working ok, I don't think the error lies there. Here is how I would do it: ``` $address0 = sponsorData('address0'); $address0 = !empty($address0) ? $address0 : 'placeholder'; ```
Question: I have an input that I'd like to put a placeholder text in, but *only if* it's respective value is an empty string. The value that should go in the textbox is echoed from a PHP array, but if this value is empty, the placeholder should be echoed instead. At the moment, I've got this code: ``` <?php echo sponsorData('address0') == '' ? 'Address Line 1' : 'Other'; ?> ``` `sponsorData()` just gets stuff from an array; it's only argument is the key. The important bit here is it returns astring. This code gives odd behaviour; I get stuff like `Hello worldAddress Line 1`, where `Hello world` is the user typed text and `Address Line 1` is obviously the placeholder. Strangely, the placeholder gets stored into the array on submission. My question is this: can someone offer a correction of my ternary operator or, if that won't work, tell me to do an inline `if` statement (blegh)? Thanks Answer:
You're running into operator precedence issues. Try: ``` <?php echo (sponsorData('address0') == '' ? 'Address Line 1' : 'Other'); ?> ``` (put brackets around the ternary operator statement).
You have to consider that the `sponsorData('address0')` may have spaces, so you can add the `trim` function, like this: ``` <?php echo ((trim(sponsorData('address0')) == '') ? 'Address Line 1' : 'Other'); ?> ```
Question: Our .net application supports AD authentication, so our application will read from the GC connection string and credentials. We now have a client who has ADFS in their on-premise and wants to create a trust with our server which hosts the application. Do I need to write a separate code to setup as a claims-aware (or) can I use the same GC after creating the trust between client and our server? Answer:
you've answered your own question : "Our .net application supports AD authentication..." This is not the same s being claims aware, so yes you will need to modify the app. Once your app is claims aware they will create a relying party (that's your app) trust with some data that you will provide after it's been made claims aware. This trust will allow their server to send your app the token with whatever authorization data you require (and was defined when you set up your app). You should reach out to the clients infrastructure team to coordinate what data you would like and what they will provide.
You should ask this on <https://stackoverflow.com/> If you do consider converting the app to be claims aware, I suggest you implement AD FS in your environment and create a trust between your AD FS and the client's ADFS. Your app will then needs to be converted to be claims aware and configure a trust between your app and your AD FS. You would be aiming to do <http://msdn.microsoft.com/en-gb/library/ee517273.aspx> The domain trusts between two AD domains/forests are not the same as federation between two organizations using AD FS. It looks like from your description your app is meant to work by looking up details in AD for users that exist in that AD. Your GC connection to your AD wont work unless that same AD has been populated with user accounts representing the client. Start with the information here on converting your app to be claims aware using WIF <http://msdn.microsoft.com/en-gb/library/ee748475.aspx> <http://www.cloudidentity.com/blog/> is a very good source on the latest guidance/information available on federated application development.
Question: I don't mean collapse, I mean hide. For example for single line comments it'd completely hide it, the editor entirely skipping the comment's line number. I'm entirely self-taught when it comes to programming, so I'm sure I've picked up numerous bad habits, one of which is almost entirely forgoing commenting. I dislike the clutter, and have only coded alone so far. I'm wanting to comment my code more, but prefer to work with distraction-free code, so was wondering if there was a way to completely hide the comments when I don't need them? (Not hiding TODO comments would be a plus). I am using Android Studio 2.2.3 on Ubuntu 16.04 Answer:
I am not sure, whether I would recommend working without comments. However, you could switch between two schemes. The first one would be the one you are currently working with. The other would be a copy of it, but with the -distracting- comments matching the background color. [For instance like this](https://i.stack.imgur.com/s5Jgv.jpg) It would still take the space, though.
"CTRL SLASH" will comment the current line. "CTRL SHIFT SLASH" will comment all that is currently selected. To hide multiple commented lines simply use the minus/minimize arrows on the left side of the code window (right side of the line numbers). To see the hidden lines use the add/maximize blocks.
Question: I upgraded my service to 200 amp from 100 amp, but the new panel is 15 ft. away. In order to connect the existing wires to the new breakers in the new panel, will just a simple connection with higher guage wire and wire nut be fine or does it require a different approach? thanks Answer:
Extending the existing circuits from the old panel to the new one with the same gauge wire is acceptable. There is no need to upsize the wire. If you have an excess of larger gauge wire that you are trying to use up then you can use it, provided the breakers in the new panel are listed for use with that gauge. Your old breaker panel must not have open spaces when you are done. You can leave the old (disconnected) breakers, or you can buy blanks to fill in the openings. Note that some inspectors may not let you leave the old breakers. But using the old breaker panel as an oversized junction box is fine.
Not clear from the question. Is this about *service* or *branch circuits*? ### Service Since you upgraded the *service*, you need larger feed wires to match. Instead of 2 sections of wire and a splice, get wires to go the whole distance. If you are simply putting in a bigger panel (based on a previous question, I think you really do have upgraded service) then: * you can splice inside the old panel * you need to use appropriately sized connectors, which won't be wire nuts at that size ### Branch Circuits It is quite common to reuse the old panel as a giant junction box. You can splice each connection inside the box with wire nuts. However, keep in mind that if you use conduit > 24" (and question says 15 feet), you have limits as to how many circuits per conduit. If you use individual cables, that's fine - but you can't just bundle them all together for the 15' run - they need to spaced out.
Question: I've looked at the [documentation](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs) but I've been unable to find an answer. Is there a way to prevent a row from being highlighted when selected? That or even a way to stop the row being selected at all. I like the "hoverrows: true" option, but ideally I would like to stop a row from being selected on-click. Thanks, **Update:** I've been able to "hackily" implement something which seems to be an interim fix. I don't really like it at all and would idealy like a better solution, if there is one... I have found that if I pass the option ``` onSelectRow: function(rowid, status) { $('#'+rowid).removeClass('ui-state-highlight'); } ``` when I instantiate the jqGrid, I can strip the highlight when it is added. Is there another, more ideal, way to do this? Answer:
try: ``` onSelectRow: function(rowid, status) { $("#grid_id").resetSelection(); //Resets (unselects) the selected row(s). Also works in multiselect mode. } ``` you can read documentations [here](http://www.secondpersonplural.ca/jqgriddocs/index.htm). Hope it helps you...
I suppose you could address this in the CSS directly. Just override the values for ui-state-highlight for your specific table ``` #table_id tr.ui-state-highlight { border: inherit !important; background: inherit !important; color: inherit !important; } #table_id tr.ui-state-highlight a { color: inherit !important; } #table_id tr.ui-state-highlight .ui-icon { background-image: inherit !important; } ``` I used the value `inherit` just as an example - you will likely need to copy some values from your theme.css to make this work.
Question: I've looked at the [documentation](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs) but I've been unable to find an answer. Is there a way to prevent a row from being highlighted when selected? That or even a way to stop the row being selected at all. I like the "hoverrows: true" option, but ideally I would like to stop a row from being selected on-click. Thanks, **Update:** I've been able to "hackily" implement something which seems to be an interim fix. I don't really like it at all and would idealy like a better solution, if there is one... I have found that if I pass the option ``` onSelectRow: function(rowid, status) { $('#'+rowid).removeClass('ui-state-highlight'); } ``` when I instantiate the jqGrid, I can strip the highlight when it is added. Is there another, more ideal, way to do this? Answer:
Use the following code: ``` beforeSelectRow: function(rowid, e) { return false; } ```
I suppose you could address this in the CSS directly. Just override the values for ui-state-highlight for your specific table ``` #table_id tr.ui-state-highlight { border: inherit !important; background: inherit !important; color: inherit !important; } #table_id tr.ui-state-highlight a { color: inherit !important; } #table_id tr.ui-state-highlight .ui-icon { background-image: inherit !important; } ``` I used the value `inherit` just as an example - you will likely need to copy some values from your theme.css to make this work.
Question: I've looked at the [documentation](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs) but I've been unable to find an answer. Is there a way to prevent a row from being highlighted when selected? That or even a way to stop the row being selected at all. I like the "hoverrows: true" option, but ideally I would like to stop a row from being selected on-click. Thanks, **Update:** I've been able to "hackily" implement something which seems to be an interim fix. I don't really like it at all and would idealy like a better solution, if there is one... I have found that if I pass the option ``` onSelectRow: function(rowid, status) { $('#'+rowid).removeClass('ui-state-highlight'); } ``` when I instantiate the jqGrid, I can strip the highlight when it is added. Is there another, more ideal, way to do this? Answer:
If you, like me, have a gazillion jqGrids and don't want to override onSelectRow for every single one, here's a global version of Reigel's solution that worked nicely for me: ``` jQuery.extend(jQuery.jgrid.defaults, { onSelectRow: function(rowid, e) { $('#'+rowid).parents('table').resetSelection(); } }); ```
I suppose you could address this in the CSS directly. Just override the values for ui-state-highlight for your specific table ``` #table_id tr.ui-state-highlight { border: inherit !important; background: inherit !important; color: inherit !important; } #table_id tr.ui-state-highlight a { color: inherit !important; } #table_id tr.ui-state-highlight .ui-icon { background-image: inherit !important; } ``` I used the value `inherit` just as an example - you will likely need to copy some values from your theme.css to make this work.
Question: I've looked at the [documentation](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs) but I've been unable to find an answer. Is there a way to prevent a row from being highlighted when selected? That or even a way to stop the row being selected at all. I like the "hoverrows: true" option, but ideally I would like to stop a row from being selected on-click. Thanks, **Update:** I've been able to "hackily" implement something which seems to be an interim fix. I don't really like it at all and would idealy like a better solution, if there is one... I have found that if I pass the option ``` onSelectRow: function(rowid, status) { $('#'+rowid).removeClass('ui-state-highlight'); } ``` when I instantiate the jqGrid, I can strip the highlight when it is added. Is there another, more ideal, way to do this? Answer:
I suppose you could address this in the CSS directly. Just override the values for ui-state-highlight for your specific table ``` #table_id tr.ui-state-highlight { border: inherit !important; background: inherit !important; color: inherit !important; } #table_id tr.ui-state-highlight a { color: inherit !important; } #table_id tr.ui-state-highlight .ui-icon { background-image: inherit !important; } ``` I used the value `inherit` just as an example - you will likely need to copy some values from your theme.css to make this work.
Yes, use the rowattr callback: ``` rowattr: function (rowData,currentObj,rowId) { if (rowData.SomeField=="SomeValue") { return {"class": "ui-state-disabled"}; } }, ``` This also grays out the row and disables the selection.
Question: I've looked at the [documentation](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs) but I've been unable to find an answer. Is there a way to prevent a row from being highlighted when selected? That or even a way to stop the row being selected at all. I like the "hoverrows: true" option, but ideally I would like to stop a row from being selected on-click. Thanks, **Update:** I've been able to "hackily" implement something which seems to be an interim fix. I don't really like it at all and would idealy like a better solution, if there is one... I have found that if I pass the option ``` onSelectRow: function(rowid, status) { $('#'+rowid).removeClass('ui-state-highlight'); } ``` when I instantiate the jqGrid, I can strip the highlight when it is added. Is there another, more ideal, way to do this? Answer:
Use the following code: ``` beforeSelectRow: function(rowid, e) { return false; } ```
try: ``` onSelectRow: function(rowid, status) { $("#grid_id").resetSelection(); //Resets (unselects) the selected row(s). Also works in multiselect mode. } ``` you can read documentations [here](http://www.secondpersonplural.ca/jqgriddocs/index.htm). Hope it helps you...
Question: I've looked at the [documentation](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs) but I've been unable to find an answer. Is there a way to prevent a row from being highlighted when selected? That or even a way to stop the row being selected at all. I like the "hoverrows: true" option, but ideally I would like to stop a row from being selected on-click. Thanks, **Update:** I've been able to "hackily" implement something which seems to be an interim fix. I don't really like it at all and would idealy like a better solution, if there is one... I have found that if I pass the option ``` onSelectRow: function(rowid, status) { $('#'+rowid).removeClass('ui-state-highlight'); } ``` when I instantiate the jqGrid, I can strip the highlight when it is added. Is there another, more ideal, way to do this? Answer:
If you, like me, have a gazillion jqGrids and don't want to override onSelectRow for every single one, here's a global version of Reigel's solution that worked nicely for me: ``` jQuery.extend(jQuery.jgrid.defaults, { onSelectRow: function(rowid, e) { $('#'+rowid).parents('table').resetSelection(); } }); ```
try: ``` onSelectRow: function(rowid, status) { $("#grid_id").resetSelection(); //Resets (unselects) the selected row(s). Also works in multiselect mode. } ``` you can read documentations [here](http://www.secondpersonplural.ca/jqgriddocs/index.htm). Hope it helps you...
Question: I've looked at the [documentation](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs) but I've been unable to find an answer. Is there a way to prevent a row from being highlighted when selected? That or even a way to stop the row being selected at all. I like the "hoverrows: true" option, but ideally I would like to stop a row from being selected on-click. Thanks, **Update:** I've been able to "hackily" implement something which seems to be an interim fix. I don't really like it at all and would idealy like a better solution, if there is one... I have found that if I pass the option ``` onSelectRow: function(rowid, status) { $('#'+rowid).removeClass('ui-state-highlight'); } ``` when I instantiate the jqGrid, I can strip the highlight when it is added. Is there another, more ideal, way to do this? Answer:
try: ``` onSelectRow: function(rowid, status) { $("#grid_id").resetSelection(); //Resets (unselects) the selected row(s). Also works in multiselect mode. } ``` you can read documentations [here](http://www.secondpersonplural.ca/jqgriddocs/index.htm). Hope it helps you...
Yes, use the rowattr callback: ``` rowattr: function (rowData,currentObj,rowId) { if (rowData.SomeField=="SomeValue") { return {"class": "ui-state-disabled"}; } }, ``` This also grays out the row and disables the selection.
Question: I've looked at the [documentation](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs) but I've been unable to find an answer. Is there a way to prevent a row from being highlighted when selected? That or even a way to stop the row being selected at all. I like the "hoverrows: true" option, but ideally I would like to stop a row from being selected on-click. Thanks, **Update:** I've been able to "hackily" implement something which seems to be an interim fix. I don't really like it at all and would idealy like a better solution, if there is one... I have found that if I pass the option ``` onSelectRow: function(rowid, status) { $('#'+rowid).removeClass('ui-state-highlight'); } ``` when I instantiate the jqGrid, I can strip the highlight when it is added. Is there another, more ideal, way to do this? Answer:
Use the following code: ``` beforeSelectRow: function(rowid, e) { return false; } ```
If you, like me, have a gazillion jqGrids and don't want to override onSelectRow for every single one, here's a global version of Reigel's solution that worked nicely for me: ``` jQuery.extend(jQuery.jgrid.defaults, { onSelectRow: function(rowid, e) { $('#'+rowid).parents('table').resetSelection(); } }); ```
Question: I've looked at the [documentation](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs) but I've been unable to find an answer. Is there a way to prevent a row from being highlighted when selected? That or even a way to stop the row being selected at all. I like the "hoverrows: true" option, but ideally I would like to stop a row from being selected on-click. Thanks, **Update:** I've been able to "hackily" implement something which seems to be an interim fix. I don't really like it at all and would idealy like a better solution, if there is one... I have found that if I pass the option ``` onSelectRow: function(rowid, status) { $('#'+rowid).removeClass('ui-state-highlight'); } ``` when I instantiate the jqGrid, I can strip the highlight when it is added. Is there another, more ideal, way to do this? Answer:
Use the following code: ``` beforeSelectRow: function(rowid, e) { return false; } ```
Yes, use the rowattr callback: ``` rowattr: function (rowData,currentObj,rowId) { if (rowData.SomeField=="SomeValue") { return {"class": "ui-state-disabled"}; } }, ``` This also grays out the row and disables the selection.
Question: I've looked at the [documentation](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs) but I've been unable to find an answer. Is there a way to prevent a row from being highlighted when selected? That or even a way to stop the row being selected at all. I like the "hoverrows: true" option, but ideally I would like to stop a row from being selected on-click. Thanks, **Update:** I've been able to "hackily" implement something which seems to be an interim fix. I don't really like it at all and would idealy like a better solution, if there is one... I have found that if I pass the option ``` onSelectRow: function(rowid, status) { $('#'+rowid).removeClass('ui-state-highlight'); } ``` when I instantiate the jqGrid, I can strip the highlight when it is added. Is there another, more ideal, way to do this? Answer:
If you, like me, have a gazillion jqGrids and don't want to override onSelectRow for every single one, here's a global version of Reigel's solution that worked nicely for me: ``` jQuery.extend(jQuery.jgrid.defaults, { onSelectRow: function(rowid, e) { $('#'+rowid).parents('table').resetSelection(); } }); ```
Yes, use the rowattr callback: ``` rowattr: function (rowData,currentObj,rowId) { if (rowData.SomeField=="SomeValue") { return {"class": "ui-state-disabled"}; } }, ``` This also grays out the row and disables the selection.
Question: I have dual boot with Ubuntu 12.04 and Windows 7, and I would like to upgrade Ubuntu to 14.04 but still retain my windows 7, help! I have a DVD with the ubuntu 14.04 ISO Answer:
If you copy a partition with `dd`, the output file will be as big as the partition. `dd` does a physical copy of the disc, it has no knowledge of blank or used space. If you compress the result file you will save a lot of space, though, given that blank space will compress away very well (beware, this is going to be computationally *very* heavy). You can even compress the output of `dd` on the fly, with something on the line of `dd if=/dev/sdaX | gzip -c > compressed_file.gz`. really important: ----------------- > > Moreover, you **cannot** (never) do a `dd` on a live (mounted) > partition, the data recorded will be totally inconsistent and > absolutely not useful for a backup. Think about it: blocks of data are > continually allocated, moved and deleted; is like shooting a photo > with long exposure time to a moving target. > > > To copy the partition with `dd` you must boot from a different one - > live USB or whatever. > > > What would I do to solve the problem at hand (notice, only generic instruction because you need to know what you are doing) *First option* buy Norton Ghost, or explore the opensource options: [partimage](http://www.partimage.org/Main_Page) and [clonezilla](http://clonezilla.org/) (never tested myself). *Second option* do it manually: 1. create an extra partition for backups, call it /dev/sdX (or use a common data partition, whatever). 2. to backup: * boot with live usb * mount the real root partition in /real * mount the extra partition in /extra * do a big tar, on the line of `(cd /real && tar cvf /extra/mybck.tar.gz)` 3. to restore * boot with live usb * mount the real root partition in /real * mount the extra partition in /extra * restore, on the line of `(cd /real && tar xvpf /extra/mybck.tar.gz)`, beware of the `p` option to preserve metadata * chroot in /real * update grub or the bootloader you are using You can substitute `tar` with your preferred archiver, just be sure it will respect ownership/mode of files. `rsync` is worth exploring.
DD probably isn't the right tool to do a backup. As Rmano said, it's making a direct copy of /dev/sda4 (probably to /dev/sda4). His answer is spot on. Check out rsync for doing backups.
Question: How can I use RichTextBox Target in WPF application? I don't want to have a separate window with log, I want all log messages to be outputted in richTextBox located in WPF dialog. I've tried to use WindowsFormsHost with RichTextBox box inside but that does not worked for me: NLog opened separate Windows Form anyway. Answer:
A workaround in the mean time is to use the 3 classes available [here](http://nlog.codeplex.com/workitem/6272), then follow this procedure: 1. Import the 3 files into your project 2. If not already the case, use `Project > Add Reference` to add references to the WPF assemblies: `WindowsBase, PresentationCore, PresentationFramework`. 3. In `WpfRichTextBoxTarget.cs`, replace lines 188-203 with: ``` //this.TargetRichTextBox.Invoke(new DelSendTheMessageToRichTextBox(this.SendTheMessageToRichTextBox), new object[] { logMessage, matchingRule }); if (System.Windows.Application.Current.Dispatcher.CheckAccess() == false) { System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => { SendTheMessageToRichTextBox(logMessage, matchingRule); })); } else { SendTheMessageToRichTextBox(logMessage, matchingRule); } } private static Color GetColorFromString(string color, Brush defaultColor) { if (defaultColor == null) return Color.FromRgb(255, 255, 255); // This will set default background colour to white. if (color == "Empty") { return (Color)colorConverter.ConvertFrom(defaultColor); } return (Color)colorConverter.ConvertFromString(color); } ``` 4. In your code, configure the new target like this below example: I hope it helps, but it definitely does not seem to be a comprehensive implementation... ``` public void loading() { var target = new WpfRichTextBoxTarget(); target.Name = "console"; target.Layout = "${longdate:useUTC=true}|${level:uppercase=true}|${logger}::${message}"; target.ControlName = "rtbConsole"; // Name of the richtextbox control already on your window target.FormName = "MonitorWindow"; // Name of your window where there is the richtextbox, but it seems it will not really be taken into account, the application mainwindow will be used instead. target.AutoScroll = true; target.MaxLines = 100000; target.UseDefaultRowColoringRules = true; AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper(); asyncWrapper.Name = "console"; asyncWrapper.WrappedTarget = target; SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace); } ```
If you define a RichTextBoxTarget in the config file, a new form is automatically created. This is because NLog initializes before your (named) form and control has been created. Even if you haven't got any rules pointing to the target. Perhaps there is a better solution, but I solved it by creating the target programatically: ``` using NLog; //[...] RichTextBoxTarget target = new RichTextBoxTarget(); target.Name = "RichTextBox"; target.Layout = "${longdate} ${level:uppercase=true} ${logger} ${message}"; target.ControlName = "textbox1"; target.FormName = "Form1"; target.AutoScroll = true; target.MaxLines = 10000; target.UseDefaultRowColoringRules = false; target.RowColoringRules.Add( new RichTextBoxRowColoringRule( "level == LogLevel.Trace", // condition "DarkGray", // font color "Control", // background color FontStyle.Regular ) ); target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Debug", "Gray", "Control")); target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Info", "ControlText", "Control")); target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Warn", "DarkRed", "Control")); target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Error", "White", "DarkRed", FontStyle.Bold)); target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "Yellow", "DarkRed", FontStyle.Bold)); AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper(); asyncWrapper.Name = "AsyncRichTextBox"; asyncWrapper.WrappedTarget = target; SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace); ```
Question: I'm trying to serve API with ***nodeJS***, and database use ***oracle***. I've an object like this that I got from `req.body.detail`: ``` { title: "How to Have", content: "<ol><li><b>Lorem ipsum dolor sit amet.</b></li></ol>" } ``` then I do ``` const data = JSON.stringify(req.body.detail); ``` but the inserted data in table become doesn't has *escape string*, it become likes: ``` {"title":"How to Have","content":"<ol><li><b>Lorem ipsum dolor sit amet.</b></li></ol>} ``` How do I can escape string to whole object and result become like this: ``` {"title":"How to Have","content":"<ol><li><b>Lorem ipsum dolor sit amet.<\/b><\/li><\/ol>} ``` My column in table has datatype `clob`. Answer:
If `public class ClassName1 extends/implements ClassName` than it is perfectly valid. This is how polimorphism works - you can treat given instance as it would be a solely instance of any of its superclasses or interfaces it implements.
`ClassName` is the type of the variable `a`, which means for your problem, that `a` can represents an object of the type `ClassName` (and any other subclass of it). So, the sentence `ClassName a = new ClassName1()` only make sense and is right if the `ClassName1` is a subclass of `ClassName`.
Question: I cannot for the life of me figure this out. I have two monitors. If I'm focused on the left monitor, I cannot use a shortcut to switch spaces on the right monitor. Or (as often happens) I click my right monitor to focus it instead of alt tabbing, and then I cannot switch the left monitor space with my keyboard without clicking on that screen. Is there not a way to control the space of another monitor with your keyboard? Answer:
Ctrl-Left Arrow/Right Arrow let you scroll through spaces from the keyboard in Mavericks. Spaces are only independent if you have "Displays Have Separate Spaces" enabled under `System Preferences > Mission Control` -- with this option enabled, you should be able to switch workspaces on each monitor independently. The monitor that switches when you use the keyboard shortcut should be the monitor where the pointer currently resides.
The free app "CurrentKey Stats" will do just what you want: `https://currentkey.com/` With CKS, you can assign a hotkey to each Desktop/Workspace. Pressing that hotkey will bring up the assigned space no matter which monitor has the mouse or has the active focus. You can be working in the main monitor and press your chosen hotkey to change which desktop is visible in the side monitor, without losing focus in the main monitor or having to move the mouse. CKS has the powerful feature of being able to assign names to each desktop workspace -- and (here's the cool part) the names *persist* if you change the *order* of your desktop spaces, even if you move them to another monitor. That seriously beats the Mission Control names of Desktop 1, Desktop 2, etc., especially if you like to rearrange the order to put things you're working on at the same time into adjacent workspaces. I currently have 21 desktop spaces and I was running out of mnemonic hotkeys that I could type one-handed and didn't have side effects in one app or another, so I created a menu in "Keyboard Maestro". Other apps like QuickKeys or Alfred can probably do the same kind of thing. In my KBM menu, I type a hotkey, Shift+Option+Command+S, that I can do with my left hand and it brings up a menu listing the names of all the desktop workspaces. A second keystroke, this time without any modifiers, picks from the menu. (Actually, the menu items can say whatever I want, I use the CKS name preceded by the menu choice mnemonic letter.) My primary reason for making sure that I can access my Spaces menu (Shift+Option+Command+S) and the menu choices one-handed is that if you change desktop workspace while in the middle of dragging a window, you drag that window to the new workspace.
Question: I cannot for the life of me figure this out. I have two monitors. If I'm focused on the left monitor, I cannot use a shortcut to switch spaces on the right monitor. Or (as often happens) I click my right monitor to focus it instead of alt tabbing, and then I cannot switch the left monitor space with my keyboard without clicking on that screen. Is there not a way to control the space of another monitor with your keyboard? Answer:
The keyboard shortcuts for switching spaces apply to the display that the pointer is on - there isn't really a way of getting round that, as far as I'm aware.
The free app "CurrentKey Stats" will do just what you want: `https://currentkey.com/` With CKS, you can assign a hotkey to each Desktop/Workspace. Pressing that hotkey will bring up the assigned space no matter which monitor has the mouse or has the active focus. You can be working in the main monitor and press your chosen hotkey to change which desktop is visible in the side monitor, without losing focus in the main monitor or having to move the mouse. CKS has the powerful feature of being able to assign names to each desktop workspace -- and (here's the cool part) the names *persist* if you change the *order* of your desktop spaces, even if you move them to another monitor. That seriously beats the Mission Control names of Desktop 1, Desktop 2, etc., especially if you like to rearrange the order to put things you're working on at the same time into adjacent workspaces. I currently have 21 desktop spaces and I was running out of mnemonic hotkeys that I could type one-handed and didn't have side effects in one app or another, so I created a menu in "Keyboard Maestro". Other apps like QuickKeys or Alfred can probably do the same kind of thing. In my KBM menu, I type a hotkey, Shift+Option+Command+S, that I can do with my left hand and it brings up a menu listing the names of all the desktop workspaces. A second keystroke, this time without any modifiers, picks from the menu. (Actually, the menu items can say whatever I want, I use the CKS name preceded by the menu choice mnemonic letter.) My primary reason for making sure that I can access my Spaces menu (Shift+Option+Command+S) and the menu choices one-handed is that if you change desktop workspace while in the middle of dragging a window, you drag that window to the new workspace.
Question: I cannot for the life of me figure this out. I have two monitors. If I'm focused on the left monitor, I cannot use a shortcut to switch spaces on the right monitor. Or (as often happens) I click my right monitor to focus it instead of alt tabbing, and then I cannot switch the left monitor space with my keyboard without clicking on that screen. Is there not a way to control the space of another monitor with your keyboard? Answer:
Yes, if you know applescript. For example, to switch to **Space 1** on the **Secondary Display**. Note: 1) Primary/Secondary Display is defined by where the Menu Bar is (i.e. System Preference -> Display -> Arrangement), not by cursor focus. 2) This script switches to *Space 1*, whether it's a Desktop or fullscreen app. If you want to switch *only* to Desktop 1, it can be done, but not with this script as it is. 3) If you don't mind flashing, remove `delay 0.5` line. 4) The script cannot do without the animation/transition. 5) Enable Accessibility and all the standard applescript spiel. 6) Modify button number to switch to a different Space on that Display. Modify list number to switch a different Display. 7) Switching to a non-existent Space, e.g. Space 100, would leave the UI at mission control. Nothing bad is going in bad to your computer. It just stays there, and user will have to manually drop back to current Space. 8) No relative switching, i.e. move left or right a space. Just absolute switching. 9) Cursor focus doesn't switch display after running this script. That's a plus. 10) No simultaneously switching Spaces on both displays. ``` tell application "System Events" do shell script "/Applications/Mission\\ Control.app/Contents/MacOS/Mission\\ Control" delay 0.5 tell process "Dock" to tell group 1 to tell list 2 to tell button 1 to click end tell ```
The free app "CurrentKey Stats" will do just what you want: `https://currentkey.com/` With CKS, you can assign a hotkey to each Desktop/Workspace. Pressing that hotkey will bring up the assigned space no matter which monitor has the mouse or has the active focus. You can be working in the main monitor and press your chosen hotkey to change which desktop is visible in the side monitor, without losing focus in the main monitor or having to move the mouse. CKS has the powerful feature of being able to assign names to each desktop workspace -- and (here's the cool part) the names *persist* if you change the *order* of your desktop spaces, even if you move them to another monitor. That seriously beats the Mission Control names of Desktop 1, Desktop 2, etc., especially if you like to rearrange the order to put things you're working on at the same time into adjacent workspaces. I currently have 21 desktop spaces and I was running out of mnemonic hotkeys that I could type one-handed and didn't have side effects in one app or another, so I created a menu in "Keyboard Maestro". Other apps like QuickKeys or Alfred can probably do the same kind of thing. In my KBM menu, I type a hotkey, Shift+Option+Command+S, that I can do with my left hand and it brings up a menu listing the names of all the desktop workspaces. A second keystroke, this time without any modifiers, picks from the menu. (Actually, the menu items can say whatever I want, I use the CKS name preceded by the menu choice mnemonic letter.) My primary reason for making sure that I can access my Spaces menu (Shift+Option+Command+S) and the menu choices one-handed is that if you change desktop workspace while in the middle of dragging a window, you drag that window to the new workspace.
Question: **dir1\dir2\dir3\file.aspx.cs**(343,49): error CS0839: Argument missing [**C:\dir\dir\dir\dir\namespace.namespace.namespace.namespace\**project.csproj] I've been trying for hours to create a regular expression to extract just 2 areas of this string. The bold areas are the parts I wish to capture. I need to split this string into two seperate strings: 1. I'd like everything before the first "(" 2. everything between the "[" and "]" but not including the "project.csproj" For #1 the closest i've gotten is `(^.*\()` which will basically capture everything up to the first "(" (*including the bracket though which I don't want*) For #2 the closest i've gotten is `(\[.*\])` which will basically capture everything inside the brackets (*including the brackets which i don't want*). **Any of the words in the above string could change apart from ".csproj" "C:\" and ".cs"** *Context: This is how MSBuild spits errors out when compiling. By capturing these two parts I can concatenate them to provide an exact link to the erroring file and open the file in Visual Studio automatically:* ``` System.Diagnostics.Process.Start("devenv.exe","/edit path"); ``` Answer:
This pattern: ``` (^[^(]*).*\[(.*)project.csproj]$ ``` Captures these groups: 1. `dir1\dir2\dir3\file.aspx.cs` 2. `C:\dir\dir\dir\dir\namespace.namespace.namespace.namespace\` If the name `project.csproj` file could change, you can use this pattern instead: ``` (^[^(]*).*\[(.*\\)[^\\]*]$ ``` This will match everything up to the last path fragment within the brackets.
Well, right now the parentheses aren't doing you any good. Just place them around the parts you are interested in: ``` ^(.*)\( ``` and ``` \[(.*)\] ``` Now to exclude `projects.csproj` from the match, simply include it after the `.*`: ``` \[(.*)projects.csproj\] ``` Then `match.Groups(1)` will give you the desired string in each case (where `match` is your `Match` object). If `projects.csproj` can be any file name (i.e. you only want everything until the last backslash, use: ``` \[(.*?)[^\\]*\] ```
Question: I am working on performance storage. When I am selecting Storage Size 250/500 then no data In IOPS. When I was select storage size `100/20/80/1000/2000gb` then I am getting IOPS. I am facing problem only `250/500gb`. this is the API i am using ``` https://[username]:[apikey]@api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/222/getItemPrices?objectFilter={"itemPrices": { "attributes": { "value": { "operation": 20 } }, "categories": { "categoryCode": { "operation": "performance_storage_iops" } }, "locationGroupId": { "operation": "is null" } } } ``` I am sending screenshot when i was select storage size `50/500gb` what I am getting response. So could you kindly provide the information to me. ![enter image description here](https://i.stack.imgur.com/OI7Tw.png) Answer:
if you have just use three array means just use if condition ``` String arraname=""; if (Arrays.asList(lac1).contains("102")) { arraname="lac1"; } if (Arrays.asList(lac2).contains("102")) { arraname="lac2"; } if (Arrays.asList(lac3).contains("102")) { arraname="lac3"; } ```
I think the best data structure to solve the problem is using dictionary. in java: ``` Map<int, String> dictionary = new HashMap<int, String>(); //put the data in.. //check existence string value = map.get(key); if (value != null) { ... } else { // No such key } ```
Question: I am working on performance storage. When I am selecting Storage Size 250/500 then no data In IOPS. When I was select storage size `100/20/80/1000/2000gb` then I am getting IOPS. I am facing problem only `250/500gb`. this is the API i am using ``` https://[username]:[apikey]@api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/222/getItemPrices?objectFilter={"itemPrices": { "attributes": { "value": { "operation": 20 } }, "categories": { "categoryCode": { "operation": "performance_storage_iops" } }, "locationGroupId": { "operation": "is null" } } } ``` I am sending screenshot when i was select storage size `50/500gb` what I am getting response. So could you kindly provide the information to me. ![enter image description here](https://i.stack.imgur.com/OI7Tw.png) Answer:
if you have just use three array means just use if condition ``` String arraname=""; if (Arrays.asList(lac1).contains("102")) { arraname="lac1"; } if (Arrays.asList(lac2).contains("102")) { arraname="lac2"; } if (Arrays.asList(lac3).contains("102")) { arraname="lac3"; } ```
If you want a better data structure to store these details i will suggest a `Map` with key as `String` and value as `List<String>` ``` Map<String,List<String>> map = new HashMap<String,List<String>>(); map.put("lac1",lac1List); map.put("lac2",lac2List); map.put("lac3",lac3List); ``` You can iterate the map and find the desired key. ``` String val; // value to be search for(Entry<String,List<String>> entry : map.entrySet()){ if(entry.value().contains(val)){ System.out.println(val+" Present in "+entry.key()); break; } } ```
Question: I am working on performance storage. When I am selecting Storage Size 250/500 then no data In IOPS. When I was select storage size `100/20/80/1000/2000gb` then I am getting IOPS. I am facing problem only `250/500gb`. this is the API i am using ``` https://[username]:[apikey]@api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/222/getItemPrices?objectFilter={"itemPrices": { "attributes": { "value": { "operation": 20 } }, "categories": { "categoryCode": { "operation": "performance_storage_iops" } }, "locationGroupId": { "operation": "is null" } } } ``` I am sending screenshot when i was select storage size `50/500gb` what I am getting response. So could you kindly provide the information to me. ![enter image description here](https://i.stack.imgur.com/OI7Tw.png) Answer:
if you have just use three array means just use if condition ``` String arraname=""; if (Arrays.asList(lac1).contains("102")) { arraname="lac1"; } if (Arrays.asList(lac2).contains("102")) { arraname="lac2"; } if (Arrays.asList(lac3).contains("102")) { arraname="lac3"; } ```
For array, you could try just `for` loop ``` public static void main(String[] args) { String[] lac1 = {"1", "101", "1101"}; String[] lac2 = {"2", "102", "1102"}; String[] lac3 = {"3", "103", "1103","8", "108", "1108"}; int pos = -1; if ((pos = getPostion(lac1, "102")) > -1) { System.out.println("array lac1 , pos:" + pos); } else if ((pos = getPostion(lac2, "102")) > -1) { System.out.println("array lac2 , pos:" + pos); } else if ((pos = getPostion(lac3, "102")) > -1) { System.out.println("array lac3 , pos:" + pos); } else { System.out.println("Not Found!"); } } public static int getPostion(String[] arr, String key) { int pos = -1; for (int i = 0; i < arr.length; i++) { if (arr[i].equals(key)) { pos = i; break; } } return pos; } ``` **OUTPUT:** ``` array lac2 , pos:1 ```
Question: I am working on performance storage. When I am selecting Storage Size 250/500 then no data In IOPS. When I was select storage size `100/20/80/1000/2000gb` then I am getting IOPS. I am facing problem only `250/500gb`. this is the API i am using ``` https://[username]:[apikey]@api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/222/getItemPrices?objectFilter={"itemPrices": { "attributes": { "value": { "operation": 20 } }, "categories": { "categoryCode": { "operation": "performance_storage_iops" } }, "locationGroupId": { "operation": "is null" } } } ``` I am sending screenshot when i was select storage size `50/500gb` what I am getting response. So could you kindly provide the information to me. ![enter image description here](https://i.stack.imgur.com/OI7Tw.png) Answer:
if you have just use three array means just use if condition ``` String arraname=""; if (Arrays.asList(lac1).contains("102")) { arraname="lac1"; } if (Arrays.asList(lac2).contains("102")) { arraname="lac2"; } if (Arrays.asList(lac3).contains("102")) { arraname="lac3"; } ```
``` public String checkValueInList(String val){ String arrayName = ""; String[] lac1 = {"1", "101", "1101"}; String[] lac2 = {"2", "102", "1102"}; String[] lac3 = {"3", "103", "1103","8", "108", "1108"}; List<String> list1 = getArrayList(); list1.add("lac1"); List<String> list2 = getArrayList(); list2.add("lac2"); List<String> list3 = getArrayList(); list3.add("lac3"); list1.addAll(Arrays.asList(lac1)); list2.addAll(Arrays.asList(lac2)); list3.addAll(Arrays.asList(lac3)); List<List<String>> allLists = new ArrayList<>(); allLists.add(list1); allLists.add(list2); allLists.add(list3); for(List<String> stringList : allLists){ if(stringList.contains(val)){ arrayName = stringList.get(0); break; } } return arrayName; } ``` Provide with more details like how do get data in arrays is it hardcoded or getting it from database? helps in choosing better collection. Instead of Lists inside List you can create a map with key value pair and return key value. You can try that!
Question: I am working on performance storage. When I am selecting Storage Size 250/500 then no data In IOPS. When I was select storage size `100/20/80/1000/2000gb` then I am getting IOPS. I am facing problem only `250/500gb`. this is the API i am using ``` https://[username]:[apikey]@api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/222/getItemPrices?objectFilter={"itemPrices": { "attributes": { "value": { "operation": 20 } }, "categories": { "categoryCode": { "operation": "performance_storage_iops" } }, "locationGroupId": { "operation": "is null" } } } ``` I am sending screenshot when i was select storage size `50/500gb` what I am getting response. So could you kindly provide the information to me. ![enter image description here](https://i.stack.imgur.com/OI7Tw.png) Answer:
if you have just use three array means just use if condition ``` String arraname=""; if (Arrays.asList(lac1).contains("102")) { arraname="lac1"; } if (Arrays.asList(lac2).contains("102")) { arraname="lac2"; } if (Arrays.asList(lac3).contains("102")) { arraname="lac3"; } ```
A Simple way could be: ``` public class mapList { Map<String,String> map; String[] lac1 = {"1", "101", "1101"}; String[] lac2 = {"2", "102", "1102"}; String[] lac3 = {"3", "103", "1103","8", "108", "1108"}; public mapList(){ map = new HashMap<>(); for(String l1:lac1){ map.put(l1, "lac1"); } for(String l2:lac2){ map.put(l2, "lac2"); } for(String l3:lac3){ map.put(l3, "lac3"); } } public String search(String val){ return map.get(val); } public static void main(String[] args) { mapList d=new mapList(); System.out.println("1102 is in: " + d.search("1102")); System.out.println("8 is in: " + d.search("8")); System.out.println("101 is in: " + d.search("101")); System.out.println("1108 is in: " + d.search("1108")); } } ``` The result: **1102** is in **lac2**; **8** is in **lac3**; **101** is in **lac1**; **1108** is in **lac3**;
Question: Suppose we want to translate the whole of Wikipedia from English into [Lojban](https://jbo.wikipedia.org/), what are the main known big limitations or concerns we should be aware of? In other words, does Lojban as a language have sufficient expressive power for being translated from English? Answer:
Length ====== A few things. First, Lojban often needs longer sentences to express something than it does in, for example, English. Vocabulary ========== Secondly, Lojban's vocabulary isn't that big, especially in the domain of sciences. Words would have to be calqued, adapted from English, French, etc. or completely re-invented. Loaning and naming ================== Thirdly, the English language (and many natural languages) loans words directly (for example, *champagne* could be \*shampain and *buoy* could be \*boy or \*boi) without changing spelling (a slight counterexample would be German, which often changes the letter c pronounced [k] to the letter k, like *Kanada* and *Vokabular*). Lojban doesn't. *.romas.* is Rome (Italy), *.xavanas.* is Havanas (Cuba) and *.lidz.* is Leeds (UK). This makes it confusing in some cases. How would Lojban adapt [Turra Coo](https://en.wikipedia.org/wiki/Turra_Coo) or people like [Nelson Rolihlahla Mandela](https://en.wikipedia.org/wiki/Nelson_Mandela)? The name should stay recognisable but pronounceable.
One of Lojban's most famous features is, of course, its lack of syntactic ambiguity. While this is an advantage in some cases, it can also be a limitation. It wouldn't likely be an issue in something like Wikipedia, but does make certain kinds of wordplay impossible. Take for example this exchange from Lewis Carroll's [*Through the Looking Glass*](http://www.alice-in-wonderland.net/resources/chapters-script/through-the-looking-glass/): > > 'Who did you pass on the road?' the King went on, holding out his hand > to the Messenger for some more hay. > > > 'Nobody,' said the Messenger. > > > 'Quite right,' said the King: 'this young lady saw him too. So of > course Nobody walks slower than you.' > > > 'I do my best,' the Messenger said in a sulky tone. 'I'm sure nobody > walks much faster than I do!' > > > 'He can't do that,' said the King, 'or else he'd have been here first.' > > > In Lojban there is no way to conflate "nobody" meaning "no person" with "Nobody" meaning "someone named Nobody", because proper names are always preceded with the article "la". Other works that rely on wordplay based in syntactic ambiguity would also present major difficulties in translating to Lojban. That said, there *is* a [Lojban translation of *Alice in Wonderland*](http://alis.lojban.org/), so these difficulties aren't necessarily insurmountable.
Question: ``` $(window).bind("beforeunload",function(){ return "cant be seen in ff"; }); ``` The problem is that i can't see the "cant be seen in ff" on the confirm box in my FireFox browser, but works well in other browsers(IE Chrome) Any solutions?? Answer:
See this: <https://bugzilla.mozilla.org/show_bug.cgi?id=588292> It looks like forefox decided to remove the support for the beforeunload as we know it.
do this ``` <script> window.onbeforeunload = function(){ return "cant be seen in ff"; } </script> ```
Question: ``` $(window).bind("beforeunload",function(){ return "cant be seen in ff"; }); ``` The problem is that i can't see the "cant be seen in ff" on the confirm box in my FireFox browser, but works well in other browsers(IE Chrome) Any solutions?? Answer:
``` confirmOnPageExit : function( display ) { if ( true == display ) { var message; /* if unsaved changes exist, display a warning */ if (false !== form_structure.unsaved_changes) { message = 'Warning! Changes to the form builder have not been saved.'; return message; } } }, window.onbeforeunload = confirmOnPageExit( false ); ```
do this ``` <script> window.onbeforeunload = function(){ return "cant be seen in ff"; } </script> ```
Question: ``` $(window).bind("beforeunload",function(){ return "cant be seen in ff"; }); ``` The problem is that i can't see the "cant be seen in ff" on the confirm box in my FireFox browser, but works well in other browsers(IE Chrome) Any solutions?? Answer:
See this: <https://bugzilla.mozilla.org/show_bug.cgi?id=588292> It looks like forefox decided to remove the support for the beforeunload as we know it.
``` confirmOnPageExit : function( display ) { if ( true == display ) { var message; /* if unsaved changes exist, display a warning */ if (false !== form_structure.unsaved_changes) { message = 'Warning! Changes to the form builder have not been saved.'; return message; } } }, window.onbeforeunload = confirmOnPageExit( false ); ```
Question: What is the proper way to fuse and switch a power supply consisting of a bunch of SMPS like the following: [![smps power supply](https://i.stack.imgur.com/qd2vI.jpg)](https://i.stack.imgur.com/qd2vI.jpg) There would be up to 5 separate output voltages. The outputs shown are about 35W each. Other outputs would be less. So currently I have a mockup that has a single fuse and a single switch on the AC load line. Is this safe? Would it be better to use a 2 pole switch to switch in both load an neutral? Why? Should I fuse each SMPS separately? If yes, why and where? Points labelled A, B, C and D are potential locations for reference. Answer:
> > So currently I have a mock-up that has a single fuse and a single switch on the AC load line. Is this safe? > > > The majority of devices found in the home or office are wired this way and there are few issues. The problem is that if you live in a land of non-polarised mains plugs which when reversed, can make the non-switched wire live, then the internal circuitry remains live even when the switch is off. A table lamp, for example, has a single-pole swtich and the terminals are exposed when the lamp is removed. Your setup should be much safer if boxed up properly. > > Would it be better to use a 2 pole switch to switch in both load an neutral? Why? > > > When the switch is off both lines are cut and the circuit is completely dead. > > Should I fuse each SMPS separately? If yes, why and where? > > > Check your SMPS and you should find that there is a fuse on the mains side of each. The main fuse protects the wiring inside your unit in the event of a fault. Your SMPS units will supply a total of about 100 W so will draw a max of 130 to 150 W fully loaded. In 110 V land this will be about 1.5 A and in 230 V land it will be less than 1 A. Use a 2 A or 1 A fuse as appropriate in the common live line, point 'A' as you have correctly shown. This will limit any fault current to a much lower and safer value than your mains wiring can provide.
I would use a single switch and fuse as you have shown, particularly if the supplies have internal fuses. Whether the individual supplies should be switched will depend on the application.
Question: the idea is within class Card I have dict ``` pack_of_cards = {'2': 2,'3': 3,'4': 4,'5': 5,'6': 6, \ '7': 7,'8': 7,'9': 9,'10': 10,'J': 10, \ 'D': 10,'K': 10,'T': 10} ``` I need this class to return a random set of key and value as a dict. For example: ``` Card() == {'T': 10} ``` Thanks to everyone. Answer:
You can do this using a method in the `random` module, but it wouldn't make sense unless your `Card` class implements an `__eq__` method. Example: ``` In [450]: class Card: ...: def __init__(self, suite, num): ...: self.suite = suite ...: self.num = num ...: ...: def __eq__(self, item): ...: k, v = list(item.items())[0] ...: return True if (self.suite == k and self.num == v) else False ...: In [452]: c = Card('T', 10) In [454]: c == {'T' : 10} Out[454]: True ``` Now that you have a working class, you can use `random.choice` to extract a card: ``` In [470]: x = random.choice(list(pack_of_cards.items())) In [471]: dict([x]) Out[471]: {'D': 10} ```
You can use `random.sample()` to return the number of cards you need, e.g.: ``` >>> import random >>> dict(random.sample(pack_of_cards.items(), k=5)) {'10': 10, '5': 5, '9': 9, 'J': 10, 'K': 10} ``` *(not a bad hand for cribbage)*
Question: I have handle that I got via `stdinHandle = GetStdHandle(STD_INPUT_HANDLE)` and I have separate thread which execute such code: ``` while (!timeToExit) { char ch; DWORD readBytes = 0; if (!::ReadFile(stdinHandle, &ch, sizeof(ch), &readBytes, nullptr)) { //report error return; } if (readBytes == 0) break; //handle new byte } ``` where `timeToExit` is `std::atomic<bool>`. I wan to stop this thread from another thread. I tried this: ``` timeToExit = true; CloseHandle(stdinHandle); ``` and code hangs in `CloseHandle`. The code hangs while program is running by other program that uses `CreatePipe` and `DuplicateHandle` to redirect input of my program to pipe. So how should I stop `while (!timeToExit)..` thread in win32 way? Or may be I should some how change `while (!timeToExit)..` thread to make it possible to stop it? **Update** I thought about usage of `WaitForMultipleObjects` before call of `ReadFile` with stdin and event as arguments, and trigger event in other thread, but there is no mention of anonymous pipe as possible input for `WaitForMultipleObjects`, plus I tried when stdin connected to console, and it become useless (always return control without delay) after the first character typed into console, looks like I have to use `ReadConsoleInput` in this case, instead of `ReadFile`? Answer:
When reading from a console's actual STDIN, you can use [`PeekConsoleInput()`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684344.aspx) and [`ReadConsoleInfo()`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684961.aspx) instead of `ReadFile()`. When reading from an (un)named pipe, use [`PeekNamedPipe()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365779.aspx) before calling `ReadFile()`. This will allow you to poll STDIN for new input before actually reading it, and then you can check your thread termination status in between polls. You can use [`GetFileType()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364960.aspx) to detect what kind of device is attached to your `STD_INPUT_HANDLE` handle.
The safest way to do this would be to call [ReadFile](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365467(v=vs.85).aspx) asynchronously (non-blocking) using the OVERLAPPED structure etc. This can be done from your main thread. If/when you need to cancel it, call [CancelIo](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363791(v=vs.85).aspx) (from same thread that called ReadFile) or [CancelIoEx](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363792(v=vs.85).aspx) (if from another thread). You might be able to make your current approach work; if you mark timeToExit as volatile, it may not hang, but that approach commonly creates bigger problems.
Question: Below is my code ``` DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Users\Shahul\Documents\Visual Studio 2010\Projects\TreeView\TreeView\bin\FileExplorer"); private void Form1_Load(object sender, EventArgs e) { if (Directory.Exists("FileExplorer")) { try { DirectoryInfo[] directories = directoryInfo.GetDirectories(); foreach (FileInfo file in directoryInfo.GetFiles()) { if (file.Exists) { TreeNode nodes = treeView.Nodes[0].Nodes.Add(file.Name); } } if (directories.Length > 0) { foreach (DirectoryInfo directory in directories) { TreeNode node = treeView.Nodes[0].Nodes.Add(directory.Name); node.ImageIndex = node.SelectedImageIndex = 0; foreach (FileInfo file in directory.GetFiles()) { if (file.Exists) { TreeNode nodes = treeView.Nodes[0].Nodes[node.Index].Nodes.Add(file.Name); } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } ``` When I run I just get a blank treeview form? Unable to figure out what is the error? Btw this my first post in Stack Overflow. Answer:
This should solve your problem, I tried on WinForm though: ``` public Form1() { InitializeComponent(); DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Users\hikuma\Documents\IR"); if (directoryInfo.Exists) { treeView1.AfterSelect += treeView1_AfterSelect; BuildTree(directoryInfo, treeView1.Nodes); } } private void BuildTree(DirectoryInfo directoryInfo, TreeNodeCollection addInMe) { TreeNode curNode = addInMe.Add(directoryInfo.Name); foreach (FileInfo file in directoryInfo.GetFiles()) { curNode.Nodes.Add(file.FullName, file.Name); } foreach (DirectoryInfo subdir in directoryInfo.GetDirectories()) { BuildTree(subdir, curNode.Nodes); } } private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { if(e.Node.Name.EndsWith("txt")) { this.richTextBox1.Clear(); StreamReader reader = new StreamReader(e.Node.Name); this.richTextBox1.Text = reader.ReadToEnd(); reader.Close(); } } ``` It is a simple example of how you can open file in rich text box, it can be improved a lot :). You might want to mark as answer or vote up if it helped :) !!
Try this: (note make sure your directoryInfo location contains some folders) ``` DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Users\Shahul\Documents\Visual Studio 2010\Projects\TreeView\TreeView\bin\FileExplorer"); private void Form1_Load(object sender, EventArgs e) { if (directoryInfo.Exists) { try { treeView.Nodes.Add(directoryInfo.Name); DirectoryInfo[] directories = directoryInfo.GetDirectories(); foreach (FileInfo file in directoryInfo.GetFiles()) { if (file.Exists) { TreeNode nodes = treeView.Nodes[0].Nodes.Add(file.Name); } } if (directories.Length > 0) { foreach (DirectoryInfo directory in directories) { TreeNode node = treeView.Nodes[0].Nodes.Add(directory.Name); node.ImageIndex = node.SelectedImageIndex = 0; foreach (FileInfo file in directory.GetFiles()) { if (file.Exists) { TreeNode nodes = treeView.Nodes[0].Nodes[node.Index].Nodes.Add(file.Name); } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } ```
Question: Below is my code ``` DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Users\Shahul\Documents\Visual Studio 2010\Projects\TreeView\TreeView\bin\FileExplorer"); private void Form1_Load(object sender, EventArgs e) { if (Directory.Exists("FileExplorer")) { try { DirectoryInfo[] directories = directoryInfo.GetDirectories(); foreach (FileInfo file in directoryInfo.GetFiles()) { if (file.Exists) { TreeNode nodes = treeView.Nodes[0].Nodes.Add(file.Name); } } if (directories.Length > 0) { foreach (DirectoryInfo directory in directories) { TreeNode node = treeView.Nodes[0].Nodes.Add(directory.Name); node.ImageIndex = node.SelectedImageIndex = 0; foreach (FileInfo file in directory.GetFiles()) { if (file.Exists) { TreeNode nodes = treeView.Nodes[0].Nodes[node.Index].Nodes.Add(file.Name); } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } ``` When I run I just get a blank treeview form? Unable to figure out what is the error? Btw this my first post in Stack Overflow. Answer:
This should solve your problem, I tried on WinForm though: ``` public Form1() { InitializeComponent(); DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Users\hikuma\Documents\IR"); if (directoryInfo.Exists) { treeView1.AfterSelect += treeView1_AfterSelect; BuildTree(directoryInfo, treeView1.Nodes); } } private void BuildTree(DirectoryInfo directoryInfo, TreeNodeCollection addInMe) { TreeNode curNode = addInMe.Add(directoryInfo.Name); foreach (FileInfo file in directoryInfo.GetFiles()) { curNode.Nodes.Add(file.FullName, file.Name); } foreach (DirectoryInfo subdir in directoryInfo.GetDirectories()) { BuildTree(subdir, curNode.Nodes); } } private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { if(e.Node.Name.EndsWith("txt")) { this.richTextBox1.Clear(); StreamReader reader = new StreamReader(e.Node.Name); this.richTextBox1.Text = reader.ReadToEnd(); reader.Close(); } } ``` It is a simple example of how you can open file in rich text box, it can be improved a lot :). You might want to mark as answer or vote up if it helped :) !!
DirectoryInfo.Exists("FileExplorer") will check for "C:\Users\Shahul\Documents\Visual Studio 2010\Projects\TreeView\TreeView\bin\debug\FileExplorer", not "C:\Users\Shahul\Documents\Visual Studio 2010\Projects\TreeView\TreeView\bin\FileExplorer", when you are running in debug mode.
Question: Below is my code ``` DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Users\Shahul\Documents\Visual Studio 2010\Projects\TreeView\TreeView\bin\FileExplorer"); private void Form1_Load(object sender, EventArgs e) { if (Directory.Exists("FileExplorer")) { try { DirectoryInfo[] directories = directoryInfo.GetDirectories(); foreach (FileInfo file in directoryInfo.GetFiles()) { if (file.Exists) { TreeNode nodes = treeView.Nodes[0].Nodes.Add(file.Name); } } if (directories.Length > 0) { foreach (DirectoryInfo directory in directories) { TreeNode node = treeView.Nodes[0].Nodes.Add(directory.Name); node.ImageIndex = node.SelectedImageIndex = 0; foreach (FileInfo file in directory.GetFiles()) { if (file.Exists) { TreeNode nodes = treeView.Nodes[0].Nodes[node.Index].Nodes.Add(file.Name); } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } ``` When I run I just get a blank treeview form? Unable to figure out what is the error? Btw this my first post in Stack Overflow. Answer:
This should solve your problem, I tried on WinForm though: ``` public Form1() { InitializeComponent(); DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Users\hikuma\Documents\IR"); if (directoryInfo.Exists) { treeView1.AfterSelect += treeView1_AfterSelect; BuildTree(directoryInfo, treeView1.Nodes); } } private void BuildTree(DirectoryInfo directoryInfo, TreeNodeCollection addInMe) { TreeNode curNode = addInMe.Add(directoryInfo.Name); foreach (FileInfo file in directoryInfo.GetFiles()) { curNode.Nodes.Add(file.FullName, file.Name); } foreach (DirectoryInfo subdir in directoryInfo.GetDirectories()) { BuildTree(subdir, curNode.Nodes); } } private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { if(e.Node.Name.EndsWith("txt")) { this.richTextBox1.Clear(); StreamReader reader = new StreamReader(e.Node.Name); this.richTextBox1.Text = reader.ReadToEnd(); reader.Close(); } } ``` It is a simple example of how you can open file in rich text box, it can be improved a lot :). You might want to mark as answer or vote up if it helped :) !!
Try the following: ``` private void Form1_Load(object sender, EventArgs e) { if (directoryInfo.Exists) { try { treeView.Nodes.Add(LoadDirectory(directoryInfo)); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } private TreeNode LoadDirectory(DirectoryInfo di) { if (!di.Exists) return null; TreeNode output = new TreeNode(di.Name, 0, 0); foreach (var subDir in di.GetDirectories()) { try { output.Nodes.Add(LoadDirectory(subDir)); } catch (IOException ex) { //handle error } catch { } } foreach (var file in di.GetFiles()) { if (file.Exists) { output.Nodes.Add(file.Name); } } return output; } } ``` It's better to split out the directory parsing into a recursive method so that you can go all the way down the tree. This WILL block the UI until it's completely loaded - but fixing that is beyond the scope of this answer... :)
Question: I'm creating an Oracle Report and I would like to display certain results based on when I print the report. There is a field called apply\_date. For example, if I print the report <= sysdate of 3/15 then I only want to display the records that have an apply\_date of 3/1 - 3/15. This also goes for printing on the 30th of each month. If I print the report after 3/15 then it would only show me the results that have an apply\_date of >= 3/16. Answer:
If you don't care much about the fiddly bits of column alignment, this isn't too bad: ``` datapoints = [{'a': 1, 'b': 2, 'c': 6}, {'a': 2, 'd': 8, 'p': 10}, {'c': 9, 'd': 1, 'z': 12}] # get all the keys ever seen keys = sorted(set.union(*(set(dp) for dp in datapoints))) with open("outfile.txt", "wb") as fp: # write the header fp.write("{}\n".format(' '.join([" "] + keys))) # loop over each point, getting the values in order (or 0 if they're absent) for i, datapoint in enumerate(datapoints): out = '{} {}\n'.format(i, ' '.join(str(datapoint.get(k, 0)) for k in keys)) fp.write(out) ``` produces ``` a b c d p z 0 1 2 6 0 0 0 1 2 0 0 8 10 0 2 0 0 9 1 0 12 ``` As mentioned in the comments, the [pandas](http://pandas.pydata.org) solution is pretty nice too: ``` >>> import pandas as pd >>> df = pd.DataFrame(datapoints).fillna(0).astype(int) >>> df a b c d p z 0 1 2 6 0 0 0 1 2 0 0 8 10 0 2 0 0 9 1 0 12 >>> df.to_csv("outfile_pd.csv", sep=" ") >>> !cat outfile_pd.csv a b c d p z 0 1 2 6 0 0 0 1 2 0 0 8 10 0 2 0 0 9 1 0 12 ``` If you really need the columns nicely aligned, then there are ways to do that too, but I never need them so I don't know much about them.
**Program:** ``` data_points = [ {'a': 1, 'b': 2, 'c': 6}, {'a': 2, 'd': 8, 'p': 10}, {'c': 9, 'd': 1, 'z': 12}, {'e': 3, 'f': 6, 'g': 3} ] merged_data_points = { } for data_point in data_points: for k, v in data_point.items(): if k not in merged_data_points: merged_data_points[k] = [] merged_data_points[k].append(v) # print the merged datapoints print '{' for k in merged_data_points: print ' {0}: {1},'.format(k, merged_data_points[k]) print '}' ``` **Output:** ``` { a: [1, 2], c: [6, 9], b: [2], e: [3], d: [8, 1], g: [3], f: [6], p: [10], z: [12], } ```
Question: If you close a GUI using the the little X in the top right of the form, does that kill all your threads as well? If not, how to you catch that event so I can put in some close down code? Answer:
``` setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ``` To execute some code on closing have a look at this. [close window event in java](https://stackoverflow.com/questions/1984195/close-window-event-in-java)
> > If you close a GUI using the the little X in the top right of the form, does that kill all your threads as well? > > > Yes, if the default close operation is `EXIT_ON_CLOSE` as mentioned by Luiggi. OTOH it is best not to simply 'kill' threads arbitrarily. > > If not, how to you catch that event so I can put in some close down code? > > > Set a default close operation of `DO_NOTHING_ON_CLOSE` and add a `WindowListener` or `WindowAdapter`. In the listener, dispose of the GUI and end the threads. See [How to Write Window Listeners](http://docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.html) for details.
Question: How can I get the following effect with FFMPEG? [![enter image description here](https://i.imgur.com/8KeRNk5.gif)](https://i.imgur.com/8KeRNk5.gif) I know I have to do it with Zoompan, but the truth is, I've been trying for a while and I can not! Answer:
The below pom.xml would suffices your requirement and this [tutorial](https://www.journaldev.com/21816/mockito-tutorial) will help you for better understanding how to work with mockito using maven ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>BlackJack</groupId> <artifactId>BlackJack</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.24.0</version> <scope>test</scope> </dependency> </dependencies> <build> <sourceDirectory>src</sourceDirectory> <testSourceDirectory>test</testSourceDirectory> <resources> <resource> <directory>src</directory> <excludes> <exclude>**/*.java</exclude> </excludes> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> ```
Maven has to download the dependencies, so you have to specify the package you're trying to import in the pom file. Go to <https://mvnrepository.com> and search for your package. Find the latest version, and you'll see under the maven tab something like this. ``` <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.24.0</version> <scope>test</scope> </dependency> ``` You put these in between `<dependencies></dependencies>` somewhere in your project tags.
Question: I have run into the problem of sending data, a simple int type, from a dialogue fragment to all the fragments within a viewpager. I have an activity that hosts both the dialogue fragment and the viewpager. I know how to send data from the dialogue fragment to the activity using an interface defined in the dialogue fragment and implementing it within the activity itself. I was thinking maybe it had something to do with the onAttach method but i am not sure. i feel i am overlooking a simple solution here. please help! thanks! Answer:
First of, The `Include()` method is used to load related data, not properties on related data. Which means, to load the name property of the related AplicantCompany and CreditorCompany on the entity Applications, your first query is correct. It will include the name properties of both related entities ``` var result = context.Applications.Include(a=> a.AplicantCompany) .Include(c=>c.CreditorCompany) .ToList(); ``` Then secondly, if you're using the async method ToListAsync() you need to await the task ``` [HttpGet("/api/applications")] public async Task<IActionResult> GetApplications() { var result = await context.Applications.Include(a=> a.AplicantCompany) .Include(c=>c.CreditorCompany) .ToListAsync(); return Ok(result); } ```
Your call to `ToListAsync` is async; but the invocation and the method itself are synchronous. Change to `ToList()` or (better) make everything else asynchronous as well
Question: I have run into the problem of sending data, a simple int type, from a dialogue fragment to all the fragments within a viewpager. I have an activity that hosts both the dialogue fragment and the viewpager. I know how to send data from the dialogue fragment to the activity using an interface defined in the dialogue fragment and implementing it within the activity itself. I was thinking maybe it had something to do with the onAttach method but i am not sure. i feel i am overlooking a simple solution here. please help! thanks! Answer:
Your call to `ToListAsync()` is returning a `Task`, which may not have completed executing by the time you return from the method. The best solution would be to make the method async, like so: ``` public async Task<IActionResult> GetApplications() { var result = await context.Applications.Include(a=> a.AplicantCompany) .Include(c=>c.CreditorCompany) .ToListAsync(); return Ok(result); } ``` These changes will cause the method to wait for all the results before continuing to the `return` statement, while allowing other requests to run while this one is waiting for its data. The second case probably won't work, as EF wants to load the entire entity with `Include`. If you want to load another entity that's referenced by `AplicantCompany`, you can use ``` .Include(a => a.AplicantCompany).ThenInclude(c => c.Entity) ``` Actually, according to [this answer](https://stackoverflow.com/a/46477084/1210520), you might be able to do (I haven't tried it): ``` var result = await context.Applications.Select(a => new { Application = a, CreditorCompany = a.CreditorCompany.Name, ApplicantCompany = a.AplicantCompany.Name}).ToListAsync(); ```
Your call to `ToListAsync` is async; but the invocation and the method itself are synchronous. Change to `ToList()` or (better) make everything else asynchronous as well
Question: I have run into the problem of sending data, a simple int type, from a dialogue fragment to all the fragments within a viewpager. I have an activity that hosts both the dialogue fragment and the viewpager. I know how to send data from the dialogue fragment to the activity using an interface defined in the dialogue fragment and implementing it within the activity itself. I was thinking maybe it had something to do with the onAttach method but i am not sure. i feel i am overlooking a simple solution here. please help! thanks! Answer:
Your call to `ToListAsync()` is returning a `Task`, which may not have completed executing by the time you return from the method. The best solution would be to make the method async, like so: ``` public async Task<IActionResult> GetApplications() { var result = await context.Applications.Include(a=> a.AplicantCompany) .Include(c=>c.CreditorCompany) .ToListAsync(); return Ok(result); } ``` These changes will cause the method to wait for all the results before continuing to the `return` statement, while allowing other requests to run while this one is waiting for its data. The second case probably won't work, as EF wants to load the entire entity with `Include`. If you want to load another entity that's referenced by `AplicantCompany`, you can use ``` .Include(a => a.AplicantCompany).ThenInclude(c => c.Entity) ``` Actually, according to [this answer](https://stackoverflow.com/a/46477084/1210520), you might be able to do (I haven't tried it): ``` var result = await context.Applications.Select(a => new { Application = a, CreditorCompany = a.CreditorCompany.Name, ApplicantCompany = a.AplicantCompany.Name}).ToListAsync(); ```
First of, The `Include()` method is used to load related data, not properties on related data. Which means, to load the name property of the related AplicantCompany and CreditorCompany on the entity Applications, your first query is correct. It will include the name properties of both related entities ``` var result = context.Applications.Include(a=> a.AplicantCompany) .Include(c=>c.CreditorCompany) .ToList(); ``` Then secondly, if you're using the async method ToListAsync() you need to await the task ``` [HttpGet("/api/applications")] public async Task<IActionResult> GetApplications() { var result = await context.Applications.Include(a=> a.AplicantCompany) .Include(c=>c.CreditorCompany) .ToListAsync(); return Ok(result); } ```
Question: I am fairly new to R and I would like to paste the string "exampletext" in front of each file name within the path. ``` csvList <- list.files(path = "./csv_by_subject") %>% paste0("*exampletext") ``` Currently this code renders things like "csv\*exampletext" and I want it to be \*exampletextcsv". I would like to continue to using dplyr and piping - help appreciated! Answer:
As others pointed out, the pipe is not necessary here. But if you do want to use it, you just have to specify that the second argument to `paste0` is "the thing you are piping", which you do using a period (.) ``` list.files(path = "./csv_by_subject") %>% paste0("*exampletext", .) ```
`paste0('exampletext', csvList)` should do the trick. It's not necessarily using `dplyr` and piping, but it's taking advantage of the vectorization features that R provides.
Question: I am fairly new to R and I would like to paste the string "exampletext" in front of each file name within the path. ``` csvList <- list.files(path = "./csv_by_subject") %>% paste0("*exampletext") ``` Currently this code renders things like "csv\*exampletext" and I want it to be \*exampletextcsv". I would like to continue to using dplyr and piping - help appreciated! Answer:
As others pointed out, the pipe is not necessary here. But if you do want to use it, you just have to specify that the second argument to `paste0` is "the thing you are piping", which you do using a period (.) ``` list.files(path = "./csv_by_subject") %>% paste0("*exampletext", .) ```
If you'd like to paste \*exampletext before all of the file names, you can reverse the order of what you're doing now using paste0 and passing the second argument as list.files. paste0 can handle vectors as the second argument and will apply the paste to each element. ``` csvList <- paste0("*exampletext", list.files(path = "./csv_by_subject")) ``` This returns a few examples from a local folder on my machine: ``` csvList [1] "*exampletext_error_metric.m" [2] "*exampletext_get_K_clusters.m" ... ```
Question: The `Devices menu` -> `CD/DVD Devices` contains `VBoxGuestAdditions.iso` **But ticking the above menu option doesn't show any menu to select anything from.** The `kernel-devel` is already there. The host is `openSUSE 11.3` 64 bit. The guest is `Slackware 13.37` 32 bit. What's the way round now? Answer:
You should try [Redmine](http://www.redmine.org/). > > Some of the main features of Redmine are: > > > > ``` > Multiple projects support > Flexible role based access control > Flexible issue tracking system > Gantt chart and calendar > News, documents & files management > Feeds & email notifications > Per project wiki > Per project forums > Time tracking > Custom fields for issues, time-entries, projects and users > SCM integration (SVN, CVS, Git, Mercurial, Bazaar and Darcs) > Issue creation via email > Multiple LDAP authentication support > User self-registration support > Multilanguage support > Multiple databases support > > ``` > > (from Redmine homepage) There is also a lot of plugins to extend it, and if there isn't a plugin that you need you can create your own easily. ;)
"Trac" might be an option for you. <http://trac.edgewall.org/>
Question: I want to validate url before redirect it using Flask. My abstract code is here... ``` @app.before_request def before(): if request.before_url == "http://127.0.0.0:8000": return redirect("http://127.0.0.1:5000") ``` Do you have any idea? Thanks in advance. Answer:
Use [urlparse (builtin module)](http://docs.python.org/2/library/urlparse.html). Then, use the builtin flask [redirection methods](http://flask.pocoo.org/docs/api/?highlight=redirect#flask.redirect) ``` >>> from urlparse import urlparse >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html') >>> o ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', params='', query='', fragment='') >>> o.scheme 'http' >>> o.port 80 >>> o.geturl() 'http://www.cwi.nl:80/%7Eguido/Python.html' ``` You can then check for the parsed out port and reconstruct a url (using the same library) with the correct port or path. This will keep the integrity of your urls, instead of dealing with string manipulation.
You can do something like this (not tested): ``` @app.route('/<path>') def redirection(path): if path == '': # your condition return redirect('redirect URL') ```
Question: I want to validate url before redirect it using Flask. My abstract code is here... ``` @app.before_request def before(): if request.before_url == "http://127.0.0.0:8000": return redirect("http://127.0.0.1:5000") ``` Do you have any idea? Thanks in advance. Answer:
You can use **urlparse** from **urllib** to parse the url. The function below which checks `scheme`, `netloc` and `path` variables which comes after parsing the url. Supports both Python 2 and 3. ``` try: # python 3 from urllib.parse import urlparse except ImportError: from urlparse import urlparse def url_validator(url): try: result = urlparse(url) return all([result.scheme, result.netloc, result.path]) except: return False ```
You can do something like this (not tested): ``` @app.route('/<path>') def redirection(path): if path == '': # your condition return redirect('redirect URL') ```
Question: I want to validate url before redirect it using Flask. My abstract code is here... ``` @app.before_request def before(): if request.before_url == "http://127.0.0.0:8000": return redirect("http://127.0.0.1:5000") ``` Do you have any idea? Thanks in advance. Answer:
Use [urlparse (builtin module)](http://docs.python.org/2/library/urlparse.html). Then, use the builtin flask [redirection methods](http://flask.pocoo.org/docs/api/?highlight=redirect#flask.redirect) ``` >>> from urlparse import urlparse >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html') >>> o ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', params='', query='', fragment='') >>> o.scheme 'http' >>> o.port 80 >>> o.geturl() 'http://www.cwi.nl:80/%7Eguido/Python.html' ``` You can then check for the parsed out port and reconstruct a url (using the same library) with the correct port or path. This will keep the integrity of your urls, instead of dealing with string manipulation.
You can use **urlparse** from **urllib** to parse the url. The function below which checks `scheme`, `netloc` and `path` variables which comes after parsing the url. Supports both Python 2 and 3. ``` try: # python 3 from urllib.parse import urlparse except ImportError: from urlparse import urlparse def url_validator(url): try: result = urlparse(url) return all([result.scheme, result.netloc, result.path]) except: return False ```
Question: I have developed two web services. The main service is a RESTful service (using DB), and another UI service that uses the RESTful service. Say I want to test the UI for now (integration tests), every test will makes changes in the prod DB. More then that, if in the RESTful service, there are one-way functions for security reasons. I mean that functions that can not be revert (Say if mark item as 'done', I can't edit or delete it anymore)? This things are very logical, the most websites I know have the same situation. All these websites are not testable? Answer:
First of all, you shouldn't be testing against your production database. If you ever need to rerun your tests after the application has gone live (and you *will* need to do that), you run a serious risk of losing or corrupting data that is vital to the business. So, instead of testing against the production database, you test against a test database (which should structurally be a copy of the production one). Then you can also add facilities to your test harness to reset that test database to a known state just before or after running a particular test. This way, you can test the correct (inter-)operation of the two web services. If the correct operation of the RESTful service can be presumed, you can also opt for a fake/mock of the RESTful service, which gives all the expected responses for the particular test, but doesn't actually persist anything.
Given HATEOAS, you only need to change the base URL for your RESTful service to point the UI service to another implementation of it. So set up a staging version of your UI and test it against a staging version of the data service, making that one change.
Question: I have developed two web services. The main service is a RESTful service (using DB), and another UI service that uses the RESTful service. Say I want to test the UI for now (integration tests), every test will makes changes in the prod DB. More then that, if in the RESTful service, there are one-way functions for security reasons. I mean that functions that can not be revert (Say if mark item as 'done', I can't edit or delete it anymore)? This things are very logical, the most websites I know have the same situation. All these websites are not testable? Answer:
Since you have to do unit testing for the REST API, I would assume you are using mock objects for those, rather than interact directly with the database. This should give you a framework of proper "valid" responses from the API already - what I'm getting at is that when you test, you should know you're in "test mode" (either through some global environment variable, separate testing environment or an extra parameter you set in the requests r somewhere else in your workflows). So if you are in test mode, your REST API should return mock objects to your client in the response, without affecting your database records in any way. Since these are tests on the client side, your concern should be strictly to test the client interaction, because proper API behavior is tested by the REST server-side unit tests, so you should assume that the API itself behaves as it's supposed to.
Given HATEOAS, you only need to change the base URL for your RESTful service to point the UI service to another implementation of it. So set up a staging version of your UI and test it against a staging version of the data service, making that one change.
Question: I have developed two web services. The main service is a RESTful service (using DB), and another UI service that uses the RESTful service. Say I want to test the UI for now (integration tests), every test will makes changes in the prod DB. More then that, if in the RESTful service, there are one-way functions for security reasons. I mean that functions that can not be revert (Say if mark item as 'done', I can't edit or delete it anymore)? This things are very logical, the most websites I know have the same situation. All these websites are not testable? Answer:
First of all, you shouldn't be testing against your production database. If you ever need to rerun your tests after the application has gone live (and you *will* need to do that), you run a serious risk of losing or corrupting data that is vital to the business. So, instead of testing against the production database, you test against a test database (which should structurally be a copy of the production one). Then you can also add facilities to your test harness to reset that test database to a known state just before or after running a particular test. This way, you can test the correct (inter-)operation of the two web services. If the correct operation of the RESTful service can be presumed, you can also opt for a fake/mock of the RESTful service, which gives all the expected responses for the particular test, but doesn't actually persist anything.
Since you have to do unit testing for the REST API, I would assume you are using mock objects for those, rather than interact directly with the database. This should give you a framework of proper "valid" responses from the API already - what I'm getting at is that when you test, you should know you're in "test mode" (either through some global environment variable, separate testing environment or an extra parameter you set in the requests r somewhere else in your workflows). So if you are in test mode, your REST API should return mock objects to your client in the response, without affecting your database records in any way. Since these are tests on the client side, your concern should be strictly to test the client interaction, because proper API behavior is tested by the REST server-side unit tests, so you should assume that the API itself behaves as it's supposed to.
Question: Conosco che alcune parole, come "dito", hanno due forme ("dito", "dita") e due significati: possono avere due articoli determinativi? Per esempio: > > la dita > > > il dita > > > Answer:
In italiano ogni nome appartiene a un genere, maschile o femminile. Alcuni nomi cambiano genere passando dal singolare al plurale, l'esempio più famoso è > > *il carcere*, *le carceri* > > > e *i carceri* non è comunemente accettato. Più frequente è il doppio genere al plurale: 1. *il braccio*, *le braccia* (del corpo), *i bracci* (in senso figurato); 2. *il dito*, *le dita* (della mano), *i diti* (in senso collettivo); 3. *il muro*, *i muri* (in senso proprio), *le mura* della città. Ci sono vari altri esempi. Una parola che può avere “doppio genere” è *fila* 1. *la fila* è quella che si fa all'ufficio postale; oppure *la fila indiana* quando si cammina uno dietro l'altro; 2. *le fila* è il plurale di *filo* in senso figurato: si dice *i fili del telefono*, ma *le fila della congiura*. Questo *le fila* è proprio il plurale di *filo*, perché si pensa alla congiura come “trama di un tessuto”.
Correggo innanzitutto la tua domanda: > > so che alcune parole, come dita, hanno due forme, dita e dito, e due significati. Ma può una sola parola avere due articoli determinativi? > > > In più ti rispondo: L'articolo determinativo dipende da come inizia una parola, non dalla sua terminazione. Tra singolare e plurale cambia solo la terminazione, quindi, se anche la parola ha due significati diversi tra singolare e plurale, l'articolo è lo stesso (opportunamente declinato). Esistono casi dove l'articolo e il significato cambiano per il genere; Esempio è: > > il boa / la boa > > > **La boa:** buoy, anchored float used as a guide to navigators. > > > **Il boa:** boa constrictor, species of snake. > > > Qui l'articolo cambia, in quanto cambia il genere della parola, e a seconda dell'articolo assume due significati molto differenti. Ho risolto il tuo dubbio?
Question: Conosco che alcune parole, come "dito", hanno due forme ("dito", "dita") e due significati: possono avere due articoli determinativi? Per esempio: > > la dita > > > il dita > > > Answer:
Correggo innanzitutto la tua domanda: > > so che alcune parole, come dita, hanno due forme, dita e dito, e due significati. Ma può una sola parola avere due articoli determinativi? > > > In più ti rispondo: L'articolo determinativo dipende da come inizia una parola, non dalla sua terminazione. Tra singolare e plurale cambia solo la terminazione, quindi, se anche la parola ha due significati diversi tra singolare e plurale, l'articolo è lo stesso (opportunamente declinato). Esistono casi dove l'articolo e il significato cambiano per il genere; Esempio è: > > il boa / la boa > > > **La boa:** buoy, anchored float used as a guide to navigators. > > > **Il boa:** boa constrictor, species of snake. > > > Qui l'articolo cambia, in quanto cambia il genere della parola, e a seconda dell'articolo assume due significati molto differenti. Ho risolto il tuo dubbio?
L'osso, le ossa (del corpo umano), gli ossi (di animale, ad esempio il pollo arrosto ha gli ossi).
Question: Conosco che alcune parole, come "dito", hanno due forme ("dito", "dita") e due significati: possono avere due articoli determinativi? Per esempio: > > la dita > > > il dita > > > Answer:
In italiano ogni nome appartiene a un genere, maschile o femminile. Alcuni nomi cambiano genere passando dal singolare al plurale, l'esempio più famoso è > > *il carcere*, *le carceri* > > > e *i carceri* non è comunemente accettato. Più frequente è il doppio genere al plurale: 1. *il braccio*, *le braccia* (del corpo), *i bracci* (in senso figurato); 2. *il dito*, *le dita* (della mano), *i diti* (in senso collettivo); 3. *il muro*, *i muri* (in senso proprio), *le mura* della città. Ci sono vari altri esempi. Una parola che può avere “doppio genere” è *fila* 1. *la fila* è quella che si fa all'ufficio postale; oppure *la fila indiana* quando si cammina uno dietro l'altro; 2. *le fila* è il plurale di *filo* in senso figurato: si dice *i fili del telefono*, ma *le fila della congiura*. Questo *le fila* è proprio il plurale di *filo*, perché si pensa alla congiura come “trama di un tessuto”.
La parola "pneumatico" può usare sia l'articolo "lo" ("lo pneumatico" è la forma ritenuta corretta dai puristi) che l'articolo "il" ("il pneumatico" è tollerato). Al plurale similmente si ha "gli pneumatici / i pneumatici". Poi a Cremona nessuno direbbe "lo gnocco fritto" ma "il gnocco fritto", ma non lo scriverei mai in un tema a scuola :-)
Question: Conosco che alcune parole, come "dito", hanno due forme ("dito", "dita") e due significati: possono avere due articoli determinativi? Per esempio: > > la dita > > > il dita > > > Answer:
In italiano ogni nome appartiene a un genere, maschile o femminile. Alcuni nomi cambiano genere passando dal singolare al plurale, l'esempio più famoso è > > *il carcere*, *le carceri* > > > e *i carceri* non è comunemente accettato. Più frequente è il doppio genere al plurale: 1. *il braccio*, *le braccia* (del corpo), *i bracci* (in senso figurato); 2. *il dito*, *le dita* (della mano), *i diti* (in senso collettivo); 3. *il muro*, *i muri* (in senso proprio), *le mura* della città. Ci sono vari altri esempi. Una parola che può avere “doppio genere” è *fila* 1. *la fila* è quella che si fa all'ufficio postale; oppure *la fila indiana* quando si cammina uno dietro l'altro; 2. *le fila* è il plurale di *filo* in senso figurato: si dice *i fili del telefono*, ma *le fila della congiura*. Questo *le fila* è proprio il plurale di *filo*, perché si pensa alla congiura come “trama di un tessuto”.
L'osso, le ossa (del corpo umano), gli ossi (di animale, ad esempio il pollo arrosto ha gli ossi).
Question: Conosco che alcune parole, come "dito", hanno due forme ("dito", "dita") e due significati: possono avere due articoli determinativi? Per esempio: > > la dita > > > il dita > > > Answer:
La parola "pneumatico" può usare sia l'articolo "lo" ("lo pneumatico" è la forma ritenuta corretta dai puristi) che l'articolo "il" ("il pneumatico" è tollerato). Al plurale similmente si ha "gli pneumatici / i pneumatici". Poi a Cremona nessuno direbbe "lo gnocco fritto" ma "il gnocco fritto", ma non lo scriverei mai in un tema a scuola :-)
L'osso, le ossa (del corpo umano), gli ossi (di animale, ad esempio il pollo arrosto ha gli ossi).
Question: How does IE register ActiveX controls for use in the browser? Does it just run regsvr32 for the DLL? Answer:
ActiveX components register themselves, triggered by a well known DLL entry point (`DllRegisterServer`). `regsvr32` is just a wrapper around loading the DLL and calling that entry point. Other tools can do this directly. Installers sometimes just directly update the registry (having recorded the changes to make when building the installer).
My understanding is that it uses some of the underlying APIs that regsvr32 uses, but it doesn't call the regsvr.exe. ActiveX controls are composed of a file on disk, typically a .DLL file, and some registry entries. The registry entries are used to lookup the the location of the actual executable code since the browser would not want to specify a particular files. It is possible for the registry entries to be created in a number of ways including the mechanism that regsvr32 uses. Creation of registry entries under Vista requires higher level privileges and must pass UAC. Therefore standard users cannot install ActiveX controls. There is a helper service that can do the registration of controls on behalf of the user.
Question: How does IE register ActiveX controls for use in the browser? Does it just run regsvr32 for the DLL? Answer:
My understanding is that it uses some of the underlying APIs that regsvr32 uses, but it doesn't call the regsvr.exe. ActiveX controls are composed of a file on disk, typically a .DLL file, and some registry entries. The registry entries are used to lookup the the location of the actual executable code since the browser would not want to specify a particular files. It is possible for the registry entries to be created in a number of ways including the mechanism that regsvr32 uses. Creation of registry entries under Vista requires higher level privileges and must pass UAC. Therefore standard users cannot install ActiveX controls. There is a helper service that can do the registration of controls on behalf of the user.
It actually doesn't have to do any of these things; the CAB file specifies what it will actually do. It may use DllRegisterServer, and indeed this is the most common thing, but it could also launch an MSI or EXE installer that may register the ActiveX control in another way.
Question: How does IE register ActiveX controls for use in the browser? Does it just run regsvr32 for the DLL? Answer:
ActiveX components register themselves, triggered by a well known DLL entry point (`DllRegisterServer`). `regsvr32` is just a wrapper around loading the DLL and calling that entry point. Other tools can do this directly. Installers sometimes just directly update the registry (having recorded the changes to make when building the installer).
It actually doesn't have to do any of these things; the CAB file specifies what it will actually do. It may use DllRegisterServer, and indeed this is the most common thing, but it could also launch an MSI or EXE installer that may register the ActiveX control in another way.
Question: I'm using i8n to host a bilingual site and I only like to display the inactive language in the top bar. What php code do I need to detect the current language so I place the inactive language in the template? Thanks: ``` <a href= <?php global $language; if (($language -> name) == 'English') { print "\"http://www.mangallery.net/fr\"".">french"; } else { print '"http://www.mangallery.net"'.">english"; } ?> </a> ``` Answer:
Use the global variable `$language` <https://api.drupal.org/api/drupal/developer%21globals.php/global/language/7>
If you are planning to use the existing **Language switcher** block of Drupal which links directly to the translated page(s) on a multilingual website, here is some sample code to remove the active language from the list. You can add this code in the `template.php` of your theme. Replace `YOURTHEME` with the name of your theme and don't forget to clear the cache. ``` function YOURTHEME_preprocess_links(&$variables) { if (!isset($variables['attributes']['class']['0'])) { return false; } // Only alter links for the language switcher block if ($variables['attributes']['class']['0'] === 'language-switcher-locale-url') { global $language; // Remove active language from the list if (isset($variables['links'][$language->language])) { unset($variables['links'][$language->language]); } } } ```
Question: I have created a channel on Azure Media Services, I correctly configured it as an RTMP channel and streamed a live video with Android + FFMpeg libraries. The problem is the client end-point latency. I need a maximum latency ~2 seconds, but now I have about ~25 seconds! I'm using Azure Media Player in a browser page to stream the content. Do you know a configuration of the client/channel which can reduce the latency? Thanks Answer:
You have used `AutoSize` and explicit label size setting at the same time, this makes no sense. If you want to enable word wrapping in your label text - you have to set `dynamiclabel1.AutoSize = false;` first and then increase its `Height`. Currently it has only 14 pixels of height so it is impossible to make text multiline. Increase it to something about 200 pixels and all the text will be placed inside the label in a few lines.
If you increase the height, and want less rows, set the Width property to something bigger; ``` dynamiclabel1.Width = 150; ```
Question: I have created a channel on Azure Media Services, I correctly configured it as an RTMP channel and streamed a live video with Android + FFMpeg libraries. The problem is the client end-point latency. I need a maximum latency ~2 seconds, but now I have about ~25 seconds! I'm using Azure Media Player in a browser page to stream the content. Do you know a configuration of the client/channel which can reduce the latency? Thanks Answer:
You have used `AutoSize` and explicit label size setting at the same time, this makes no sense. If you want to enable word wrapping in your label text - you have to set `dynamiclabel1.AutoSize = false;` first and then increase its `Height`. Currently it has only 14 pixels of height so it is impossible to make text multiline. Increase it to something about 200 pixels and all the text will be placed inside the label in a few lines.
If you want to select the number of lines depending on font/text size, you can do something like this: ``` Label dynamiclabel1 = new Label(); dynamiclabel1.Location = new Point(280, 90); dynamiclabel1.Name = "lblid"; dynamiclabel1.Size = new Size(150, 100); dynamiclabel1.Text = "Smith had omitted the paragraph in question (an omission which had escaped notice for twenty years) on the ground that it was unnecessary and misplaced; but Magee suspected him of having been influenced by deeper reasons."; dynamiclabel1.Font = new Font("Arial", 10, FontStyle.Regular); int lines = 3; //number of lines you want your text to display in using (Graphics g = CreateGraphics()) { SizeF size = g.MeasureString(dynamiclabel1.Text, dynamiclabel1.Font); float w=size.Width / lines; dynamiclabel1.Height = (int)Math.Ceiling(size.Height*lines); dynamiclabel1.Width = (int)Math.Ceiling(w); } panel1.Controls.Add(dynamiclabel1); ``` **Edit** If what you know is the width you have available and you want your label to adjust height to show all the content, can do this: ``` Label dynamiclabel1 = new Label(); dynamiclabel1.Location = new Point(280, 90); dynamiclabel1.Name = "lblid"; dynamiclabel1.Size = new Size(150, 100); dynamiclabel1.Text = "Smith had omitted the paragraph in question (an omission which had escaped notice for twenty years) on the ground that it was unnecessary and misplaced; but Magee suspected him of having been influenced by deeper reasons."; dynamiclabel1.Font = new Font("Arial", 10, FontStyle.Regular); int width = 600; //Width available to your label using (Graphics g = CreateGraphics()) { SizeF size = g.MeasureString(dynamiclabel1.Text, dynamiclabel1.Font); lines = (int)Math.Ceiling(size.Width / width); dynamiclabel1.Height = (int)Math.Ceiling(size.Height * lines); dynamiclabel1.Width = width; } panel1.Controls.Add(dynamiclabel1); ```
Question: I have created a channel on Azure Media Services, I correctly configured it as an RTMP channel and streamed a live video with Android + FFMpeg libraries. The problem is the client end-point latency. I need a maximum latency ~2 seconds, but now I have about ~25 seconds! I'm using Azure Media Player in a browser page to stream the content. Do you know a configuration of the client/channel which can reduce the latency? Thanks Answer:
``` Label dynamiclabel = new Label(); dynamiclabel.Location = new Point(38, 30); dynamiclabel.Name = "lbl_ques"; dynamiclabel.Text = question; //dynamiclabel.AutoSize = true; dynamiclabel.Size = new System.Drawing.Size(900, 26); dynamiclabel.Font = new Font("Arial", 9, FontStyle.Regular); ```
You have used `AutoSize` and explicit label size setting at the same time, this makes no sense. If you want to enable word wrapping in your label text - you have to set `dynamiclabel1.AutoSize = false;` first and then increase its `Height`. Currently it has only 14 pixels of height so it is impossible to make text multiline. Increase it to something about 200 pixels and all the text will be placed inside the label in a few lines.
Question: I have created a channel on Azure Media Services, I correctly configured it as an RTMP channel and streamed a live video with Android + FFMpeg libraries. The problem is the client end-point latency. I need a maximum latency ~2 seconds, but now I have about ~25 seconds! I'm using Azure Media Player in a browser page to stream the content. Do you know a configuration of the client/channel which can reduce the latency? Thanks Answer:
If you increase the height, and want less rows, set the Width property to something bigger; ``` dynamiclabel1.Width = 150; ```
If you want to select the number of lines depending on font/text size, you can do something like this: ``` Label dynamiclabel1 = new Label(); dynamiclabel1.Location = new Point(280, 90); dynamiclabel1.Name = "lblid"; dynamiclabel1.Size = new Size(150, 100); dynamiclabel1.Text = "Smith had omitted the paragraph in question (an omission which had escaped notice for twenty years) on the ground that it was unnecessary and misplaced; but Magee suspected him of having been influenced by deeper reasons."; dynamiclabel1.Font = new Font("Arial", 10, FontStyle.Regular); int lines = 3; //number of lines you want your text to display in using (Graphics g = CreateGraphics()) { SizeF size = g.MeasureString(dynamiclabel1.Text, dynamiclabel1.Font); float w=size.Width / lines; dynamiclabel1.Height = (int)Math.Ceiling(size.Height*lines); dynamiclabel1.Width = (int)Math.Ceiling(w); } panel1.Controls.Add(dynamiclabel1); ``` **Edit** If what you know is the width you have available and you want your label to adjust height to show all the content, can do this: ``` Label dynamiclabel1 = new Label(); dynamiclabel1.Location = new Point(280, 90); dynamiclabel1.Name = "lblid"; dynamiclabel1.Size = new Size(150, 100); dynamiclabel1.Text = "Smith had omitted the paragraph in question (an omission which had escaped notice for twenty years) on the ground that it was unnecessary and misplaced; but Magee suspected him of having been influenced by deeper reasons."; dynamiclabel1.Font = new Font("Arial", 10, FontStyle.Regular); int width = 600; //Width available to your label using (Graphics g = CreateGraphics()) { SizeF size = g.MeasureString(dynamiclabel1.Text, dynamiclabel1.Font); lines = (int)Math.Ceiling(size.Width / width); dynamiclabel1.Height = (int)Math.Ceiling(size.Height * lines); dynamiclabel1.Width = width; } panel1.Controls.Add(dynamiclabel1); ```
Question: I have created a channel on Azure Media Services, I correctly configured it as an RTMP channel and streamed a live video with Android + FFMpeg libraries. The problem is the client end-point latency. I need a maximum latency ~2 seconds, but now I have about ~25 seconds! I'm using Azure Media Player in a browser page to stream the content. Do you know a configuration of the client/channel which can reduce the latency? Thanks Answer:
``` Label dynamiclabel = new Label(); dynamiclabel.Location = new Point(38, 30); dynamiclabel.Name = "lbl_ques"; dynamiclabel.Text = question; //dynamiclabel.AutoSize = true; dynamiclabel.Size = new System.Drawing.Size(900, 26); dynamiclabel.Font = new Font("Arial", 9, FontStyle.Regular); ```
If you increase the height, and want less rows, set the Width property to something bigger; ``` dynamiclabel1.Width = 150; ```
Question: I have created a channel on Azure Media Services, I correctly configured it as an RTMP channel and streamed a live video with Android + FFMpeg libraries. The problem is the client end-point latency. I need a maximum latency ~2 seconds, but now I have about ~25 seconds! I'm using Azure Media Player in a browser page to stream the content. Do you know a configuration of the client/channel which can reduce the latency? Thanks Answer:
``` Label dynamiclabel = new Label(); dynamiclabel.Location = new Point(38, 30); dynamiclabel.Name = "lbl_ques"; dynamiclabel.Text = question; //dynamiclabel.AutoSize = true; dynamiclabel.Size = new System.Drawing.Size(900, 26); dynamiclabel.Font = new Font("Arial", 9, FontStyle.Regular); ```
If you want to select the number of lines depending on font/text size, you can do something like this: ``` Label dynamiclabel1 = new Label(); dynamiclabel1.Location = new Point(280, 90); dynamiclabel1.Name = "lblid"; dynamiclabel1.Size = new Size(150, 100); dynamiclabel1.Text = "Smith had omitted the paragraph in question (an omission which had escaped notice for twenty years) on the ground that it was unnecessary and misplaced; but Magee suspected him of having been influenced by deeper reasons."; dynamiclabel1.Font = new Font("Arial", 10, FontStyle.Regular); int lines = 3; //number of lines you want your text to display in using (Graphics g = CreateGraphics()) { SizeF size = g.MeasureString(dynamiclabel1.Text, dynamiclabel1.Font); float w=size.Width / lines; dynamiclabel1.Height = (int)Math.Ceiling(size.Height*lines); dynamiclabel1.Width = (int)Math.Ceiling(w); } panel1.Controls.Add(dynamiclabel1); ``` **Edit** If what you know is the width you have available and you want your label to adjust height to show all the content, can do this: ``` Label dynamiclabel1 = new Label(); dynamiclabel1.Location = new Point(280, 90); dynamiclabel1.Name = "lblid"; dynamiclabel1.Size = new Size(150, 100); dynamiclabel1.Text = "Smith had omitted the paragraph in question (an omission which had escaped notice for twenty years) on the ground that it was unnecessary and misplaced; but Magee suspected him of having been influenced by deeper reasons."; dynamiclabel1.Font = new Font("Arial", 10, FontStyle.Regular); int width = 600; //Width available to your label using (Graphics g = CreateGraphics()) { SizeF size = g.MeasureString(dynamiclabel1.Text, dynamiclabel1.Font); lines = (int)Math.Ceiling(size.Width / width); dynamiclabel1.Height = (int)Math.Ceiling(size.Height * lines); dynamiclabel1.Width = width; } panel1.Controls.Add(dynamiclabel1); ```
Question: Can I set some space inside 'EditText' in the beginning and at the end? If possible, then how? Actually, I have done some customization on my 'EditText' view and now it shows like this, as shown in the below image: ![Emulator screen shot](https://i.stack.imgur.com/SoUOZ.png) In my case, as you see, in my "description" field, the word "Description" starts from the very beginning, which doesnt look attractive, I want to keep some space in the beginning and at the end of the EditText's text. And also i want to set this, at the run time as this editText views are set on the runtime after a selection from the spinner. Can i achieve this? Answer:
Use `padding left` like `editText.setPadding (int left, int top, int right, int bottom);`
try this code ``` android:paddingLeft="5dp" ```