Search is not available for this dataset
qid
int64
1
74.7M
question
stringlengths
1
70k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
0
60.5k
20,506,847
How can I retrieve all keys in a Hash in Ruby, also the nested ones. Duplicates should be ignored, e.g. ``` { a: 3, b: { b: 2, b: { c: 5 } } }.soberize => [:a, :b, :c] ``` What would be the fastest implementation?
2013/12/10
[ "https://Stackoverflow.com/questions/20506847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642429/" ]
Simple recursive solution: ``` def recursive_keys(data) data.keys + data.values.map{|value| recursive_keys(value) if value.is_a?(Hash) } end def all_keys(data) recursive_keys(data).flatten.compact.uniq end ``` Usage: ``` all_keys({ a: 3, b: { b: 2, b: { c: 5 } } }) => [:a, :b, :c] ```
What about a recursive method? ``` def nested_keys(hash, array) if hash.is_a?(Hash) array |= hash.keys hash.keys.map do |key| array = nested_keys(hash[key], array) end end array end ```
11,602,072
I'm reading through K&R and the question is to: write a program to copy its input to its output, replacing each string of one or more blanks by a single blank. In my mind I think I know what I need to do, set up a boolean to know when I am in a space or not. I've attempted it and did not succeed. I've found this code and it works, I am struggling to figure out what stops the space from being written. I think I may have it but I need clarification. ``` #include <stdio.h> int main(void) { int c; int inspace; inspace = 0; while((c = getchar()) != EOF) { if(c == ' ') { if(inspace == 0) { inspace = 1; putchar(c); } } /* We haven't met 'else' yet, so we have to be a little clumsy */ if(c != ' ') { inspace = 0; putchar(c); } } return 0; } ``` I have created a text file to work on, the text reads: ``` so this is where you have been ``` After the 's' on 'this' the state changes to 1 because we are in a space. The space gets written and it reads the next space. So now we enter: ``` while((c = getchar()) != EOF) { if(c == ' ') { if(inspace == 0) { inspace = 1; putchar(c); } ``` But inspace is not 0, it is 1. So what happens? Does the code skip to return 0;, not writing anything and just continues the while loop? return 0; is outside of the loop but this is the only way I can see that a value is not returned.
2012/07/22
[ "https://Stackoverflow.com/questions/11602072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1259395/" ]
At this point: ``` if(c == ' ') { if(inspace == 0) // <-- here ``` If inspace is equal to 1, it will not execute the if body, it will jump to: ``` if(c != ' ') { ``` And as long as c == ' ' above will be false, so it will skip the if body and jump to: ``` while((c = getchar()) != EOF) { ``` And this will continue until the end of the file or until `(c != ' ')` evaluates to true. When c is non-space: ``` if(c != ' ') { inspace = 0; putchar(c); ``` inspace is zeroed, and character is printed.
Yeah in the case you mentioned, it does not write anything and continues in the while loop and fetches the next character. If the next character is again space then it will do the same thing i.e go to next iteration without printing. Whenever it will find first non-space it will set inspace to 0 and start printing. While loop will terminate whenever getchar will fetch EOF. Then program will return 0.
11,602,072
I'm reading through K&R and the question is to: write a program to copy its input to its output, replacing each string of one or more blanks by a single blank. In my mind I think I know what I need to do, set up a boolean to know when I am in a space or not. I've attempted it and did not succeed. I've found this code and it works, I am struggling to figure out what stops the space from being written. I think I may have it but I need clarification. ``` #include <stdio.h> int main(void) { int c; int inspace; inspace = 0; while((c = getchar()) != EOF) { if(c == ' ') { if(inspace == 0) { inspace = 1; putchar(c); } } /* We haven't met 'else' yet, so we have to be a little clumsy */ if(c != ' ') { inspace = 0; putchar(c); } } return 0; } ``` I have created a text file to work on, the text reads: ``` so this is where you have been ``` After the 's' on 'this' the state changes to 1 because we are in a space. The space gets written and it reads the next space. So now we enter: ``` while((c = getchar()) != EOF) { if(c == ' ') { if(inspace == 0) { inspace = 1; putchar(c); } ``` But inspace is not 0, it is 1. So what happens? Does the code skip to return 0;, not writing anything and just continues the while loop? return 0; is outside of the loop but this is the only way I can see that a value is not returned.
2012/07/22
[ "https://Stackoverflow.com/questions/11602072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1259395/" ]
At this point: ``` if(c == ' ') { if(inspace == 0) // <-- here ``` If inspace is equal to 1, it will not execute the if body, it will jump to: ``` if(c != ' ') { ``` And as long as c == ' ' above will be false, so it will skip the if body and jump to: ``` while((c = getchar()) != EOF) { ``` And this will continue until the end of the file or until `(c != ' ')` evaluates to true. When c is non-space: ``` if(c != ' ') { inspace = 0; putchar(c); ``` inspace is zeroed, and character is printed.
If a condition in an if-statement is not true, the following expression is not executed. This means that everything inside the corresponding brackets is skipped and the execution resumes 'after' the closing bracket. As the following if-statement is also false, nothing is done inside this iteration of the for-loop.
11,602,072
I'm reading through K&R and the question is to: write a program to copy its input to its output, replacing each string of one or more blanks by a single blank. In my mind I think I know what I need to do, set up a boolean to know when I am in a space or not. I've attempted it and did not succeed. I've found this code and it works, I am struggling to figure out what stops the space from being written. I think I may have it but I need clarification. ``` #include <stdio.h> int main(void) { int c; int inspace; inspace = 0; while((c = getchar()) != EOF) { if(c == ' ') { if(inspace == 0) { inspace = 1; putchar(c); } } /* We haven't met 'else' yet, so we have to be a little clumsy */ if(c != ' ') { inspace = 0; putchar(c); } } return 0; } ``` I have created a text file to work on, the text reads: ``` so this is where you have been ``` After the 's' on 'this' the state changes to 1 because we are in a space. The space gets written and it reads the next space. So now we enter: ``` while((c = getchar()) != EOF) { if(c == ' ') { if(inspace == 0) { inspace = 1; putchar(c); } ``` But inspace is not 0, it is 1. So what happens? Does the code skip to return 0;, not writing anything and just continues the while loop? return 0; is outside of the loop but this is the only way I can see that a value is not returned.
2012/07/22
[ "https://Stackoverflow.com/questions/11602072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1259395/" ]
At this point: ``` if(c == ' ') { if(inspace == 0) // <-- here ``` If inspace is equal to 1, it will not execute the if body, it will jump to: ``` if(c != ' ') { ``` And as long as c == ' ' above will be false, so it will skip the if body and jump to: ``` while((c = getchar()) != EOF) { ``` And this will continue until the end of the file or until `(c != ' ')` evaluates to true. When c is non-space: ``` if(c != ' ') { inspace = 0; putchar(c); ``` inspace is zeroed, and character is printed.
When inspace is 1 and c is ' ' the expression: ``` inspace == 0 ``` evaluates to 0 and the code ``` inspace = 1; putchar(c); ``` does not get executed. The program will then go to the next iteration of the while loop if it can, but it won't return 0 until the while loop has ended. You can simplify the while loop to this code: ``` while((c = getchar()) != EOF) { if(c == ' ') { if(inspace == 0) { inspace = 1; putchar(c); } } else { inspace = 0; putchar(c); } } ```
284,563
I am going to move from Blogger to WordPress and I also don't want to set earlier Blogger Permalink structure in WordPress. Now I want to know if there is any way to redirect URLs as mentioned below. Current (In Blogger): ``` http://www.example.com/2017/10/seba-online-form-fill-up-2018.html ``` After (In WordPress): ``` http://www.example.com/seba-online-form-fill-up-2018.html ``` That means I want to remove my Blogger's year & month from URL from numbers of indexed URL and redirect them to WordPress generated new URLs.
2017/11/01
[ "https://wordpress.stackexchange.com/questions/284563", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
If `/seba-online-form-fill-up-2018.html` is an actual WordPress URL then this is relatively trivial to do in `.htaccess`. For example, the following one-liner using mod\_rewrite could be used. This should be placed *before* the existing WordPress directives in `.htaccess`: ``` RewriteRule ^\d{4}/\d{1,2}/(.+\.html)$ /$1 [R=302,L] ``` This redirects a URL of the form `/NNNN/NN/<anything>.html` to `/<anything>.html`. Where `N` is a digit 0-9 and the month (`NN`) can be either 1 or 2 digits. If your Blogger URLs always have a 2 digit month, then change `\d{1,2}` to `\d\d`. The `$1` in the *substitution* is a backreference to the captured group in the `RewriteRule` *pattern*. ie. `(.+\.html)`. Note that this is a 302 (temporary) redirect. You should change this to 301 (permanent) only when you have confirmed this is working OK. (301s are cached hard by the browser so can make testing problematic.)
Well, there are some Data base migrator plugins for that porpuse like [Migrate DB](https://wordpress.org/plugins/wp-migrate-db/), obviuosly this is for changes inside a SQL data base used for wordpress and basically this plugin will look for the old URL to change it for the new URLS. So you can search and replace like: Search: <http://yoursite.in/2017/10/> replace: <http://yoursite.in/> you will have <http://yoursite.in/xxxxxx.html> Also you can do the same with a text editor like NOTEPAD++ in your backup file. Both method works
36,739,985
Here is my code at the moment ``` percentagesOff = [5,10,15.....] for percentage in percentagesOff: print("Percent off: ",percentage, end= " ") ``` and the output looks like this ``` Percent off: 5 Percent off: 10 Percent off: 15 ``` and so on. This is an example of what I want my code to look like. (have to use nested for loops as part of homework) ``` $10 $100 $1000 Percent off: 5% x x x 10% x x x 15% x x x 20% x x x ``` My question is focusing on this part ``` Percent off: 5% 10% 15% 20% ``` I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
2016/04/20
[ "https://Stackoverflow.com/questions/36739985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027397/" ]
Here ``` percentagesOff = [5, 10, 15, 20] print("Percent off:\t", percentagesOff[0], '%') for percentage in percentagesOff[1:]: print("\t\t", percentage, "%") ``` Output ``` Percent off: 5 % 10 % 15 % 20 % ```
The fact is that python print add line break after your string to be printed. So, Import `import sys` and, before your loop, use that: ``` sys.stdout.write(' $10 $100 $1000\n') sys.stdout.write('Percent off:') ``` And now, you can start using print to write your table entries. You can simply add a if statement with a boolean too.
36,739,985
Here is my code at the moment ``` percentagesOff = [5,10,15.....] for percentage in percentagesOff: print("Percent off: ",percentage, end= " ") ``` and the output looks like this ``` Percent off: 5 Percent off: 10 Percent off: 15 ``` and so on. This is an example of what I want my code to look like. (have to use nested for loops as part of homework) ``` $10 $100 $1000 Percent off: 5% x x x 10% x x x 15% x x x 20% x x x ``` My question is focusing on this part ``` Percent off: 5% 10% 15% 20% ``` I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
2016/04/20
[ "https://Stackoverflow.com/questions/36739985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027397/" ]
I really dislike teachers who tell students to accomplish something without having shown them the *right* tool for the job. I'm guessing you haven't yet been introduced to the `string.format()` method? Without which, lining up your columns will be an utter pain. You're trying to use a hammer when you need a screwdriver. Anyway, regardless of that, I'd say that the right approach is to print a string of spaces the same length as 'Percent off:' when you don't want that string. So: ``` poff = 'Percent off: ' pad = ' '*len(poff) p = poff for percentage in percentagesOff: print(p ,percentage, end= " ") p = pad # for all subsequent trips around the loop ``` Better style would be to allow for the possibility that you might want `poff` output again (say) at the top of each page of output. So a better way to do the second code block is ``` for lineno, percentage in enumerate(percentagesOff): if lineno==0: # can replace later with are-we-at-the-top-of-a-page test? p = poff else p = pad # p = poff if lineno==0 else pad # alternative shorter form print(p ,percentage, end= " ") ```
It is interesting excercise...... You can do something like this. ``` first = True for p in pe: if first == True: print("percent off: ") first = False print(p) else: .... .... ``` But you would not normally do it this way.
36,739,985
Here is my code at the moment ``` percentagesOff = [5,10,15.....] for percentage in percentagesOff: print("Percent off: ",percentage, end= " ") ``` and the output looks like this ``` Percent off: 5 Percent off: 10 Percent off: 15 ``` and so on. This is an example of what I want my code to look like. (have to use nested for loops as part of homework) ``` $10 $100 $1000 Percent off: 5% x x x 10% x x x 15% x x x 20% x x x ``` My question is focusing on this part ``` Percent off: 5% 10% 15% 20% ``` I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
2016/04/20
[ "https://Stackoverflow.com/questions/36739985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027397/" ]
It is interesting excercise...... You can do something like this. ``` first = True for p in pe: if first == True: print("percent off: ") first = False print(p) else: .... .... ``` But you would not normally do it this way.
The fact is that python print add line break after your string to be printed. So, Import `import sys` and, before your loop, use that: ``` sys.stdout.write(' $10 $100 $1000\n') sys.stdout.write('Percent off:') ``` And now, you can start using print to write your table entries. You can simply add a if statement with a boolean too.
36,739,985
Here is my code at the moment ``` percentagesOff = [5,10,15.....] for percentage in percentagesOff: print("Percent off: ",percentage, end= " ") ``` and the output looks like this ``` Percent off: 5 Percent off: 10 Percent off: 15 ``` and so on. This is an example of what I want my code to look like. (have to use nested for loops as part of homework) ``` $10 $100 $1000 Percent off: 5% x x x 10% x x x 15% x x x 20% x x x ``` My question is focusing on this part ``` Percent off: 5% 10% 15% 20% ``` I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
2016/04/20
[ "https://Stackoverflow.com/questions/36739985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027397/" ]
Here ``` percentagesOff = [5, 10, 15, 20] print("Percent off:\t", percentagesOff[0], '%') for percentage in percentagesOff[1:]: print("\t\t", percentage, "%") ``` Output ``` Percent off: 5 % 10 % 15 % 20 % ```
It is interesting excercise...... You can do something like this. ``` first = True for p in pe: if first == True: print("percent off: ") first = False print(p) else: .... .... ``` But you would not normally do it this way.
36,739,985
Here is my code at the moment ``` percentagesOff = [5,10,15.....] for percentage in percentagesOff: print("Percent off: ",percentage, end= " ") ``` and the output looks like this ``` Percent off: 5 Percent off: 10 Percent off: 15 ``` and so on. This is an example of what I want my code to look like. (have to use nested for loops as part of homework) ``` $10 $100 $1000 Percent off: 5% x x x 10% x x x 15% x x x 20% x x x ``` My question is focusing on this part ``` Percent off: 5% 10% 15% 20% ``` I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
2016/04/20
[ "https://Stackoverflow.com/questions/36739985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027397/" ]
Here is one alternate solution: ``` percentagesOff = [1,2,3,4,5,6,7,8,9,10] print 'Percent off: ', percentagesOff[0] #use blanks instead of '\t' for percentage in percentagesOff[1:]: print ' '*len('Percent off: '), percentage ``` The last line, leaves one blank space for every character of the string ''Percent off: '' and then start printing elements of array. Basically, "len('something')" returns how many character does the string 'something' include. Then we muliply ' ' (which is one space) by that number.
The fact is that python print add line break after your string to be printed. So, Import `import sys` and, before your loop, use that: ``` sys.stdout.write(' $10 $100 $1000\n') sys.stdout.write('Percent off:') ``` And now, you can start using print to write your table entries. You can simply add a if statement with a boolean too.
36,739,985
Here is my code at the moment ``` percentagesOff = [5,10,15.....] for percentage in percentagesOff: print("Percent off: ",percentage, end= " ") ``` and the output looks like this ``` Percent off: 5 Percent off: 10 Percent off: 15 ``` and so on. This is an example of what I want my code to look like. (have to use nested for loops as part of homework) ``` $10 $100 $1000 Percent off: 5% x x x 10% x x x 15% x x x 20% x x x ``` My question is focusing on this part ``` Percent off: 5% 10% 15% 20% ``` I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
2016/04/20
[ "https://Stackoverflow.com/questions/36739985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027397/" ]
I really dislike teachers who tell students to accomplish something without having shown them the *right* tool for the job. I'm guessing you haven't yet been introduced to the `string.format()` method? Without which, lining up your columns will be an utter pain. You're trying to use a hammer when you need a screwdriver. Anyway, regardless of that, I'd say that the right approach is to print a string of spaces the same length as 'Percent off:' when you don't want that string. So: ``` poff = 'Percent off: ' pad = ' '*len(poff) p = poff for percentage in percentagesOff: print(p ,percentage, end= " ") p = pad # for all subsequent trips around the loop ``` Better style would be to allow for the possibility that you might want `poff` output again (say) at the top of each page of output. So a better way to do the second code block is ``` for lineno, percentage in enumerate(percentagesOff): if lineno==0: # can replace later with are-we-at-the-top-of-a-page test? p = poff else p = pad # p = poff if lineno==0 else pad # alternative shorter form print(p ,percentage, end= " ") ```
Here is one alternate solution: ``` percentagesOff = [1,2,3,4,5,6,7,8,9,10] print 'Percent off: ', percentagesOff[0] #use blanks instead of '\t' for percentage in percentagesOff[1:]: print ' '*len('Percent off: '), percentage ``` The last line, leaves one blank space for every character of the string ''Percent off: '' and then start printing elements of array. Basically, "len('something')" returns how many character does the string 'something' include. Then we muliply ' ' (which is one space) by that number.
36,739,985
Here is my code at the moment ``` percentagesOff = [5,10,15.....] for percentage in percentagesOff: print("Percent off: ",percentage, end= " ") ``` and the output looks like this ``` Percent off: 5 Percent off: 10 Percent off: 15 ``` and so on. This is an example of what I want my code to look like. (have to use nested for loops as part of homework) ``` $10 $100 $1000 Percent off: 5% x x x 10% x x x 15% x x x 20% x x x ``` My question is focusing on this part ``` Percent off: 5% 10% 15% 20% ``` I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
2016/04/20
[ "https://Stackoverflow.com/questions/36739985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027397/" ]
I really dislike teachers who tell students to accomplish something without having shown them the *right* tool for the job. I'm guessing you haven't yet been introduced to the `string.format()` method? Without which, lining up your columns will be an utter pain. You're trying to use a hammer when you need a screwdriver. Anyway, regardless of that, I'd say that the right approach is to print a string of spaces the same length as 'Percent off:' when you don't want that string. So: ``` poff = 'Percent off: ' pad = ' '*len(poff) p = poff for percentage in percentagesOff: print(p ,percentage, end= " ") p = pad # for all subsequent trips around the loop ``` Better style would be to allow for the possibility that you might want `poff` output again (say) at the top of each page of output. So a better way to do the second code block is ``` for lineno, percentage in enumerate(percentagesOff): if lineno==0: # can replace later with are-we-at-the-top-of-a-page test? p = poff else p = pad # p = poff if lineno==0 else pad # alternative shorter form print(p ,percentage, end= " ") ```
You can just pull it out of the for loop, then it gets printed only once, or you could "remember" that you already printed it by setting some boolean variable to `True`(initialized at `False`) and then checking whether that variable is `True` or `False` before printing that part of the string.
36,739,985
Here is my code at the moment ``` percentagesOff = [5,10,15.....] for percentage in percentagesOff: print("Percent off: ",percentage, end= " ") ``` and the output looks like this ``` Percent off: 5 Percent off: 10 Percent off: 15 ``` and so on. This is an example of what I want my code to look like. (have to use nested for loops as part of homework) ``` $10 $100 $1000 Percent off: 5% x x x 10% x x x 15% x x x 20% x x x ``` My question is focusing on this part ``` Percent off: 5% 10% 15% 20% ``` I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
2016/04/20
[ "https://Stackoverflow.com/questions/36739985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027397/" ]
I really dislike teachers who tell students to accomplish something without having shown them the *right* tool for the job. I'm guessing you haven't yet been introduced to the `string.format()` method? Without which, lining up your columns will be an utter pain. You're trying to use a hammer when you need a screwdriver. Anyway, regardless of that, I'd say that the right approach is to print a string of spaces the same length as 'Percent off:' when you don't want that string. So: ``` poff = 'Percent off: ' pad = ' '*len(poff) p = poff for percentage in percentagesOff: print(p ,percentage, end= " ") p = pad # for all subsequent trips around the loop ``` Better style would be to allow for the possibility that you might want `poff` output again (say) at the top of each page of output. So a better way to do the second code block is ``` for lineno, percentage in enumerate(percentagesOff): if lineno==0: # can replace later with are-we-at-the-top-of-a-page test? p = poff else p = pad # p = poff if lineno==0 else pad # alternative shorter form print(p ,percentage, end= " ") ```
The fact is that python print add line break after your string to be printed. So, Import `import sys` and, before your loop, use that: ``` sys.stdout.write(' $10 $100 $1000\n') sys.stdout.write('Percent off:') ``` And now, you can start using print to write your table entries. You can simply add a if statement with a boolean too.
36,739,985
Here is my code at the moment ``` percentagesOff = [5,10,15.....] for percentage in percentagesOff: print("Percent off: ",percentage, end= " ") ``` and the output looks like this ``` Percent off: 5 Percent off: 10 Percent off: 15 ``` and so on. This is an example of what I want my code to look like. (have to use nested for loops as part of homework) ``` $10 $100 $1000 Percent off: 5% x x x 10% x x x 15% x x x 20% x x x ``` My question is focusing on this part ``` Percent off: 5% 10% 15% 20% ``` I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
2016/04/20
[ "https://Stackoverflow.com/questions/36739985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027397/" ]
Here is one alternate solution: ``` percentagesOff = [1,2,3,4,5,6,7,8,9,10] print 'Percent off: ', percentagesOff[0] #use blanks instead of '\t' for percentage in percentagesOff[1:]: print ' '*len('Percent off: '), percentage ``` The last line, leaves one blank space for every character of the string ''Percent off: '' and then start printing elements of array. Basically, "len('something')" returns how many character does the string 'something' include. Then we muliply ' ' (which is one space) by that number.
It is interesting excercise...... You can do something like this. ``` first = True for p in pe: if first == True: print("percent off: ") first = False print(p) else: .... .... ``` But you would not normally do it this way.
36,739,985
Here is my code at the moment ``` percentagesOff = [5,10,15.....] for percentage in percentagesOff: print("Percent off: ",percentage, end= " ") ``` and the output looks like this ``` Percent off: 5 Percent off: 10 Percent off: 15 ``` and so on. This is an example of what I want my code to look like. (have to use nested for loops as part of homework) ``` $10 $100 $1000 Percent off: 5% x x x 10% x x x 15% x x x 20% x x x ``` My question is focusing on this part ``` Percent off: 5% 10% 15% 20% ``` I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
2016/04/20
[ "https://Stackoverflow.com/questions/36739985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027397/" ]
You can just pull it out of the for loop, then it gets printed only once, or you could "remember" that you already printed it by setting some boolean variable to `True`(initialized at `False`) and then checking whether that variable is `True` or `False` before printing that part of the string.
The fact is that python print add line break after your string to be printed. So, Import `import sys` and, before your loop, use that: ``` sys.stdout.write(' $10 $100 $1000\n') sys.stdout.write('Percent off:') ``` And now, you can start using print to write your table entries. You can simply add a if statement with a boolean too.
22,105,306
So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing? <http://jsfiddle.net/8TVn5/> ``` window.onload = function () { var currentPercent = 0; var showPercent = window.setInterval(function() { $('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) { currentPercent= 0;}); if (currentPercent < 100) { currentPercent += 1; } else { currentPercent = 0; } if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');} document.getElementById('result').innerHTML = currentPercent; }, 200); }; ```
2014/02/28
[ "https://Stackoverflow.com/questions/22105306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355076/" ]
You can't append a `list` to a `tuple` because tuples are ["immutable"](http://docs.python.org/2/library/functions.html#tuple) (they can't be changed). It is however easy to append a *tuple* to a *list*: ``` vertices = [(0, 0), (0, 0), (0, 0)] for x in range(10): vertices.append((x, y)) ``` You can add tuples together to create a *new*, longer tuple, but that strongly goes against the purpose of tuples, and will slow down as the number of elements gets larger. Using a list in this case is preferred.
You can't modify a tuple. You'll either need to replace the tuple with a new one containing the additional vertex, or change it to a list. A list is simply a modifiable tuple. ``` vertices = [[0,0],[0,0],[0,0]] for ...: vertices.append([x, y]) ```
22,105,306
So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing? <http://jsfiddle.net/8TVn5/> ``` window.onload = function () { var currentPercent = 0; var showPercent = window.setInterval(function() { $('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) { currentPercent= 0;}); if (currentPercent < 100) { currentPercent += 1; } else { currentPercent = 0; } if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');} document.getElementById('result').innerHTML = currentPercent; }, 200); }; ```
2014/02/28
[ "https://Stackoverflow.com/questions/22105306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355076/" ]
You can't modify a tuple. You'll either need to replace the tuple with a new one containing the additional vertex, or change it to a list. A list is simply a modifiable tuple. ``` vertices = [[0,0],[0,0],[0,0]] for ...: vertices.append([x, y]) ```
Not sure I understand you, but if you want to append x,y to each vertex you can do something like : ``` vertices = ([0,0],[0,0],[0,0]) for v in vertices: v[0] += x v[1] += y ```
22,105,306
So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing? <http://jsfiddle.net/8TVn5/> ``` window.onload = function () { var currentPercent = 0; var showPercent = window.setInterval(function() { $('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) { currentPercent= 0;}); if (currentPercent < 100) { currentPercent += 1; } else { currentPercent = 0; } if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');} document.getElementById('result').innerHTML = currentPercent; }, 200); }; ```
2014/02/28
[ "https://Stackoverflow.com/questions/22105306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355076/" ]
You can't append a `list` to a `tuple` because tuples are ["immutable"](http://docs.python.org/2/library/functions.html#tuple) (they can't be changed). It is however easy to append a *tuple* to a *list*: ``` vertices = [(0, 0), (0, 0), (0, 0)] for x in range(10): vertices.append((x, y)) ``` You can add tuples together to create a *new*, longer tuple, but that strongly goes against the purpose of tuples, and will slow down as the number of elements gets larger. Using a list in this case is preferred.
You can concatenate two tuples: ``` >>> vertices = ([0,0],[0,0],[0,0]) >>> lst = [10, 20] >>> vertices = vertices + tuple([lst]) >>> vertices ([0, 0], [0, 0], [0, 0], [10, 20]) ```
22,105,306
So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing? <http://jsfiddle.net/8TVn5/> ``` window.onload = function () { var currentPercent = 0; var showPercent = window.setInterval(function() { $('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) { currentPercent= 0;}); if (currentPercent < 100) { currentPercent += 1; } else { currentPercent = 0; } if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');} document.getElementById('result').innerHTML = currentPercent; }, 200); }; ```
2014/02/28
[ "https://Stackoverflow.com/questions/22105306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355076/" ]
You can't append a `list` to a `tuple` because tuples are ["immutable"](http://docs.python.org/2/library/functions.html#tuple) (they can't be changed). It is however easy to append a *tuple* to a *list*: ``` vertices = [(0, 0), (0, 0), (0, 0)] for x in range(10): vertices.append((x, y)) ``` You can add tuples together to create a *new*, longer tuple, but that strongly goes against the purpose of tuples, and will slow down as the number of elements gets larger. Using a list in this case is preferred.
You probably want a list, as mentioned above. But if you really need a tuple, you can create a new tuple by concatenating tuples: ``` vertices = ([0,0],[0,0],[0,0]) for x in (1, 2): for y in (3, 4): vertices += ([x,y],) ``` Alternatively, and for more efficiency, use a list while you're building the tuple and convert it at the end: ``` vertices = ([0,0],[0,0],[0,0]) #... vlist = list(vertices) for x in (1, 2): for y in (3, 4): vlist.append([x, y]) vertices = tuple(vlist) ``` At the end of either one, `vertices` is: ``` ([0, 0], [0, 0], [0, 0], [1, 3], [1, 4], [2, 3], [2, 4]) ```
22,105,306
So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing? <http://jsfiddle.net/8TVn5/> ``` window.onload = function () { var currentPercent = 0; var showPercent = window.setInterval(function() { $('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) { currentPercent= 0;}); if (currentPercent < 100) { currentPercent += 1; } else { currentPercent = 0; } if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');} document.getElementById('result').innerHTML = currentPercent; }, 200); }; ```
2014/02/28
[ "https://Stackoverflow.com/questions/22105306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355076/" ]
You can't append a `list` to a `tuple` because tuples are ["immutable"](http://docs.python.org/2/library/functions.html#tuple) (they can't be changed). It is however easy to append a *tuple* to a *list*: ``` vertices = [(0, 0), (0, 0), (0, 0)] for x in range(10): vertices.append((x, y)) ``` You can add tuples together to create a *new*, longer tuple, but that strongly goes against the purpose of tuples, and will slow down as the number of elements gets larger. Using a list in this case is preferred.
Not sure I understand you, but if you want to append x,y to each vertex you can do something like : ``` vertices = ([0,0],[0,0],[0,0]) for v in vertices: v[0] += x v[1] += y ```
22,105,306
So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing? <http://jsfiddle.net/8TVn5/> ``` window.onload = function () { var currentPercent = 0; var showPercent = window.setInterval(function() { $('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) { currentPercent= 0;}); if (currentPercent < 100) { currentPercent += 1; } else { currentPercent = 0; } if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');} document.getElementById('result').innerHTML = currentPercent; }, 200); }; ```
2014/02/28
[ "https://Stackoverflow.com/questions/22105306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355076/" ]
You can concatenate two tuples: ``` >>> vertices = ([0,0],[0,0],[0,0]) >>> lst = [10, 20] >>> vertices = vertices + tuple([lst]) >>> vertices ([0, 0], [0, 0], [0, 0], [10, 20]) ```
Not sure I understand you, but if you want to append x,y to each vertex you can do something like : ``` vertices = ([0,0],[0,0],[0,0]) for v in vertices: v[0] += x v[1] += y ```
22,105,306
So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing? <http://jsfiddle.net/8TVn5/> ``` window.onload = function () { var currentPercent = 0; var showPercent = window.setInterval(function() { $('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) { currentPercent= 0;}); if (currentPercent < 100) { currentPercent += 1; } else { currentPercent = 0; } if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');} document.getElementById('result').innerHTML = currentPercent; }, 200); }; ```
2014/02/28
[ "https://Stackoverflow.com/questions/22105306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355076/" ]
You probably want a list, as mentioned above. But if you really need a tuple, you can create a new tuple by concatenating tuples: ``` vertices = ([0,0],[0,0],[0,0]) for x in (1, 2): for y in (3, 4): vertices += ([x,y],) ``` Alternatively, and for more efficiency, use a list while you're building the tuple and convert it at the end: ``` vertices = ([0,0],[0,0],[0,0]) #... vlist = list(vertices) for x in (1, 2): for y in (3, 4): vlist.append([x, y]) vertices = tuple(vlist) ``` At the end of either one, `vertices` is: ``` ([0, 0], [0, 0], [0, 0], [1, 3], [1, 4], [2, 3], [2, 4]) ```
Not sure I understand you, but if you want to append x,y to each vertex you can do something like : ``` vertices = ([0,0],[0,0],[0,0]) for v in vertices: v[0] += x v[1] += y ```
7,233,392
Is there any way I can authenticate a Facebook user without requiring them to connect in the front end? I'm trying to report the number of "likes" for an alcohol-gated page and will need to access the information with an over-21 access token, but do not want to have to log in every time I access the data. Or is there a way to generate an access token that doesn't expire? I'm really not that much of an expert with facebook, so any alternatives to these ideas would be greatly appreciated.
2011/08/29
[ "https://Stackoverflow.com/questions/7233392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402606/" ]
When you're requesting the access token you're going to use to check the Page, request the `offline_access` extended permission and the token won't expire when you/the user logs out.
If you're using the [Graph API](https://developers.facebook.com/docs/reference/api/), when you initially get the `access_token`, add `offline_access` to the list of permissions you're requesting via the `scope` parameter. From the [permissions](https://developers.facebook.com/docs/reference/api/permissions/) documentation: > > The set of permissions below basically explain what types of permissions you can ask a u ser in the scope parameter of your auth dialog to get the permissions you need for your app. > > > So add `offline_access` to the permissions you're requesting in the `scope` parameter: ``` $config = array( ... "scope" => "offline_access,...", ... ); ... ```
23,673,577
I have an object that is apparently double deleted despite being kept track of by smart pointers. I am new to using smart pointers so I made a simple function to test whether I am using the object correctly. ``` int *a = new int(2); std::shared_ptr<int> b(a); std::shared_ptr<int> c(a); ``` This set of lines in the main function causes a runtime error as the pointers go out of scope, why? Aren't smart pointers supposed to be able to handle the deletion of a by themselves?
2014/05/15
[ "https://Stackoverflow.com/questions/23673577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3639950/" ]
A `shared_ptr` expects to *own* the pointed-at object. What you've done is to create *two* separate smart pointers, each of which thinks it has exclusive ownership of the underlying `int`. They don't know about each other's existence, they don't talk to each other. Therefore, when they go out of scope, both pointers delete the underlying resource, with the obvious result. When you create a `shared_ptr`, it creates a sort of "management object" which is responsible for the resource's lifetime. When you *copy* a `shared_ptr`, both copies reference the same management object. The management object keeps track of how many `shared_ptr` instances are pointing at this resource. An `int*` by itself has no such "management object", so copying it does not keep track of references. Here's a minimal rewrite of your code: ``` // incidentally, "make_shared" is the best way to do this, but I'll leave your // original code intact for now. int *a = new int(2); std::shared_ptr<int> b(a); std::shared_ptr<int> c = b; ``` Now, they both reference the same underlying management object. As each `shared_ptr` is destroyed, the number of references on the `int*` is reduced and when the last reference goes ther object is deleted.
Correct usage is: ``` std::shared_ptr<int> b = std::make_shared<int>(2); std::shared_ptr<int> c = b; ```
23,673,577
I have an object that is apparently double deleted despite being kept track of by smart pointers. I am new to using smart pointers so I made a simple function to test whether I am using the object correctly. ``` int *a = new int(2); std::shared_ptr<int> b(a); std::shared_ptr<int> c(a); ``` This set of lines in the main function causes a runtime error as the pointers go out of scope, why? Aren't smart pointers supposed to be able to handle the deletion of a by themselves?
2014/05/15
[ "https://Stackoverflow.com/questions/23673577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3639950/" ]
You are only allowd to make a smartpointer once from a raw pointer. All other shared pointers have to be copies of the first one in order for them to work correctly. Even better: use make shared: ``` std::shared_ptr<int> sp1 = std::make_shared<int>(2); std::shared_ptr<int> sp2 = sp1; ``` EDIT: forgot to add the second pointer
Correct usage is: ``` std::shared_ptr<int> b = std::make_shared<int>(2); std::shared_ptr<int> c = b; ```
23,673,577
I have an object that is apparently double deleted despite being kept track of by smart pointers. I am new to using smart pointers so I made a simple function to test whether I am using the object correctly. ``` int *a = new int(2); std::shared_ptr<int> b(a); std::shared_ptr<int> c(a); ``` This set of lines in the main function causes a runtime error as the pointers go out of scope, why? Aren't smart pointers supposed to be able to handle the deletion of a by themselves?
2014/05/15
[ "https://Stackoverflow.com/questions/23673577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3639950/" ]
A `shared_ptr` expects to *own* the pointed-at object. What you've done is to create *two* separate smart pointers, each of which thinks it has exclusive ownership of the underlying `int`. They don't know about each other's existence, they don't talk to each other. Therefore, when they go out of scope, both pointers delete the underlying resource, with the obvious result. When you create a `shared_ptr`, it creates a sort of "management object" which is responsible for the resource's lifetime. When you *copy* a `shared_ptr`, both copies reference the same management object. The management object keeps track of how many `shared_ptr` instances are pointing at this resource. An `int*` by itself has no such "management object", so copying it does not keep track of references. Here's a minimal rewrite of your code: ``` // incidentally, "make_shared" is the best way to do this, but I'll leave your // original code intact for now. int *a = new int(2); std::shared_ptr<int> b(a); std::shared_ptr<int> c = b; ``` Now, they both reference the same underlying management object. As each `shared_ptr` is destroyed, the number of references on the `int*` is reduced and when the last reference goes ther object is deleted.
You are only allowd to make a smartpointer once from a raw pointer. All other shared pointers have to be copies of the first one in order for them to work correctly. Even better: use make shared: ``` std::shared_ptr<int> sp1 = std::make_shared<int>(2); std::shared_ptr<int> sp2 = sp1; ``` EDIT: forgot to add the second pointer
230,264
I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible?
2014/02/25
[ "https://softwareengineering.stackexchange.com/questions/230264", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/121236/" ]
Sure - you can program whatever you like. Whether it makes any sense is a different question. As for whether having an ERP/CMS hybrid makes sense or already exists - I don't think so. There are some vague similarities and overlaps in that both will typically allow you to define your own entities with fields ("document types" in a CMS, "business objects" in an ERP) and present a web interface for data entry and publishing, but at heart they have completely different purposes.
An example, though maybe a contrived one but one I encounterd in the wild a long time ago: An application was built that would store incoming documents pertaining to required reports sent in by customers of a financial services company. The same application also served to automatically send out reminder letters to customers who were late sending in those documents, and as an entry point for the telephone support people in the company to look up customer information if customer called (or had to be called). In that case both functionalities were closely intertwined. In other systems both functionalities might exist but not be as tightly linked (think something like SAP or Lotus Notes).
230,264
I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible?
2014/02/25
[ "https://softwareengineering.stackexchange.com/questions/230264", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/121236/" ]
In a very theoretical sense yes. But in most cases this would not make very much sense. The basic functionality of an ERP system is business management. The data produced here may become part of the data displayed on a web site. But normally the data here is pure text and numbers, like definitions of products, orders, invoices and some statistical information. An CMS main task is to provide information in a way that not only the content as such can be edited but often enough the representation and styling too. Its functionality is much more limited and the amount of data normally far less than in an ERP system. In our company for example all our product and customer data is kept in an ERP system. Customers can login and search products, order them and see shipment and invoice data. All this they get directly from the ERP system. Some information in the ERP is specifically there for the web site (for example our product categories for the web site are slightly different from those used internally for statistical purposes). But this data is purely information. In theory this ERP system would have a lot of options to store even more information, even combined with some styling information. We don't use this. Information that we do not actually need for business purposes is edited in a small CMS system for the web site. This includes things like a news section, some pages with company information and similar more text/style oriented data. We could store this in the ERP too, there are tables for such things, but it is more effort to code in the ERP area and then we would have more effort to display on the web.
An example, though maybe a contrived one but one I encounterd in the wild a long time ago: An application was built that would store incoming documents pertaining to required reports sent in by customers of a financial services company. The same application also served to automatically send out reminder letters to customers who were late sending in those documents, and as an entry point for the telephone support people in the company to look up customer information if customer called (or had to be called). In that case both functionalities were closely intertwined. In other systems both functionalities might exist but not be as tightly linked (think something like SAP or Lotus Notes).
230,264
I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible?
2014/02/25
[ "https://softwareengineering.stackexchange.com/questions/230264", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/121236/" ]
In a very theoretical sense yes. But in most cases this would not make very much sense. The basic functionality of an ERP system is business management. The data produced here may become part of the data displayed on a web site. But normally the data here is pure text and numbers, like definitions of products, orders, invoices and some statistical information. An CMS main task is to provide information in a way that not only the content as such can be edited but often enough the representation and styling too. Its functionality is much more limited and the amount of data normally far less than in an ERP system. In our company for example all our product and customer data is kept in an ERP system. Customers can login and search products, order them and see shipment and invoice data. All this they get directly from the ERP system. Some information in the ERP is specifically there for the web site (for example our product categories for the web site are slightly different from those used internally for statistical purposes). But this data is purely information. In theory this ERP system would have a lot of options to store even more information, even combined with some styling information. We don't use this. Information that we do not actually need for business purposes is edited in a small CMS system for the web site. This includes things like a news section, some pages with company information and similar more text/style oriented data. We could store this in the ERP too, there are tables for such things, but it is more effort to code in the ERP area and then we would have more effort to display on the web.
Sure - you can program whatever you like. Whether it makes any sense is a different question. As for whether having an ERP/CMS hybrid makes sense or already exists - I don't think so. There are some vague similarities and overlaps in that both will typically allow you to define your own entities with fields ("document types" in a CMS, "business objects" in an ERP) and present a web interface for data entry and publishing, but at heart they have completely different purposes.
230,264
I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible?
2014/02/25
[ "https://softwareengineering.stackexchange.com/questions/230264", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/121236/" ]
Sure - you can program whatever you like. Whether it makes any sense is a different question. As for whether having an ERP/CMS hybrid makes sense or already exists - I don't think so. There are some vague similarities and overlaps in that both will typically allow you to define your own entities with fields ("document types" in a CMS, "business objects" in an ERP) and present a web interface for data entry and publishing, but at heart they have completely different purposes.
In most cases this would not make very much sense,ERP system generally use in business management.An CMS able to edit not only content but the entire design can be edited.Information that is not important for business prospective are edited by CMS.
230,264
I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible?
2014/02/25
[ "https://softwareengineering.stackexchange.com/questions/230264", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/121236/" ]
In a very theoretical sense yes. But in most cases this would not make very much sense. The basic functionality of an ERP system is business management. The data produced here may become part of the data displayed on a web site. But normally the data here is pure text and numbers, like definitions of products, orders, invoices and some statistical information. An CMS main task is to provide information in a way that not only the content as such can be edited but often enough the representation and styling too. Its functionality is much more limited and the amount of data normally far less than in an ERP system. In our company for example all our product and customer data is kept in an ERP system. Customers can login and search products, order them and see shipment and invoice data. All this they get directly from the ERP system. Some information in the ERP is specifically there for the web site (for example our product categories for the web site are slightly different from those used internally for statistical purposes). But this data is purely information. In theory this ERP system would have a lot of options to store even more information, even combined with some styling information. We don't use this. Information that we do not actually need for business purposes is edited in a small CMS system for the web site. This includes things like a news section, some pages with company information and similar more text/style oriented data. We could store this in the ERP too, there are tables for such things, but it is more effort to code in the ERP area and then we would have more effort to display on the web.
In most cases this would not make very much sense,ERP system generally use in business management.An CMS able to edit not only content but the entire design can be edited.Information that is not important for business prospective are edited by CMS.
286,606
In the application there is a dialog where only numeric string entries are valid. Therefore I would like to set the numeric keyboard layout. Does anyone know how to simulate key press on the keyboard or any other method to change the keyboard layout? Thanks!
2008/11/13
[ "https://Stackoverflow.com/questions/286606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
You don't need to. Just like full windows, you can set the edit control to be numeric input only. You can either do it [manually](http://msdn.microsoft.com/en-us/library/bb761655(VS.85).aspx) or in the dialog editor in the properites for the edit control. The SIP should automatically display the numeric keyboard when the numeric only edit control goes into focus.
You can use the InputModeEditor: ``` InputModeEditor.SetInputMode(textBox1,InputMode.Numeric); ```
286,606
In the application there is a dialog where only numeric string entries are valid. Therefore I would like to set the numeric keyboard layout. Does anyone know how to simulate key press on the keyboard or any other method to change the keyboard layout? Thanks!
2008/11/13
[ "https://Stackoverflow.com/questions/286606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
You don't need to. Just like full windows, you can set the edit control to be numeric input only. You can either do it [manually](http://msdn.microsoft.com/en-us/library/bb761655(VS.85).aspx) or in the dialog editor in the properites for the edit control. The SIP should automatically display the numeric keyboard when the numeric only edit control goes into focus.
There is only one way to do this (edit: this is referring to the SIP in non-smartphone Windows Mobile, so I'm not sure it's relevant to your question), and it does involve simulating a mouse click on the 123 button. This is only half the problem, however, since you also need to know whether the keyboard is already in numeric mode or not. The way to do this is to peek a pixel near the upper left corner of the keypad - if you look at how the 123 button works, you'll see that it's system text on windows background, and then inverted in numeric mode (so the pixel will be the system text color only when in numeric mode). There's one more bit of weirdness you have to do to guarantee it will work on all devices (you have to draw a pixel on the keyboard, too). Lucky for you, I have an easy-to-use code sample that does all this. Unlucky for you, it's in C#, but I think it should at least point you in the right direction.
844,323
If $\cos{(A-B)}=\frac{3}{5}$ and $\sin{(A+B)}=\frac{12}{13}$, then find $\cos{(2B)}$. Correct answer = 63/65. I tried all identities I know but I have no idea how to proceed.
2014/06/23
[ "https://math.stackexchange.com/questions/844323", "https://math.stackexchange.com", "https://math.stackexchange.com/users/159625/" ]
Every $B(4,k)$ admits a graceful labeling. We prove this by induction on $k$. Our induction hypothesis is: every $B(4,k)$ admits a graceful labeling where the vertex of degree 1 has label 0. For $k=1$ we cyclically assign the labels $1,4,3,5$ to the vertices of the cycle. Then add one pending edge to the vertex with label $5$ and give the last vertex label 0. It is trivially verified that this defines a graceful labeling. For the induction step: take a $B(4,k)$ with a graceful labeling where the vertex of degree 1 has label 0. Now prolong the path with one more edge and give the new vertex label $k+5$. We now have a graceful labeling of $B(4,k+1)$. Finally invert that labeling (i.e. replace each label $x$ by $k+5-x$ and we end up with a graceful labeling of $B(4,k+1)$ with $0$ on the vertex of degree 1. Note that this procedure generalizes to all $B(n,k)$, where $C\_n$ is graceful.
Unfortunately I do not know how to access the referred document, so I have done some (computer-assisted) research on this, specifically for $B(5,k)$. This graph has $k+5$ vertices, so it will use vertex labels from $[0,k+5]$ (omitting only one of them). In the arrays following the vertices along the cycle have index $0,1,2,3,4$ and the vertices of the path start at index 5 which is connected to the cycle-vertex with index 0. The first 6 vertices always get labels $[0,1,k+3,2,k+5,k+4]$ and then the 7th vertex *must* have label 4, This creates the edge labels $1,k,k+1,k+2,k+3,k+4,k+5$ on the first 7 edges. Now you can fix these edge labels and run a computer program that finishes the labeling for you. The number of possibilities soon gets large, but if you focus on the edge labels you will soon detect that final sequences reappear. More concretely: if we have an edge list for $B(5,k)$ as above, then the last $n+k-7$ entries on this list reappear as the end of an edge list for $B(5,k+3)$. And once this is detected, it is not very hard to explain. Let $L=[0,1,k+3,2,k+5,k+4,4,a\_1,\ldots,a\_{5+k-7}]$ a graceful labeling for $B(5,k)$, and $k'=k+3$. We claim that $L'=[0,1,k'+3,2,k'+5,k'+4,4,k'+2,3,k',a'\_1,\ldots,a'\_{5+k-7}]$ (where $a'\_i=k'+4-a\_i$) is a graceful labeling for $B(5,k')$. Note that we replaced the first 7 labels by the defined start pattern for $k'$, then inserted 3 vertex labels ($k'+2,3,k'$) and finally 'inverted' the rest of the pattern. Of course we need to prove this claim. Because $L$ is a graceful labeling the last $5+k-7$ vertex labels are in $\{3,5,\ldots,k+2\}$ and all different, so the last $5+k-7$ vertex labels of $L'$ are in $\{k'+4-3,k'+4-5,\ldots,k'+4-(k+2)\}=\{5,\ldots,k'-1,k'+1\}$ (and still all different). Now straight inspection shows that $L'$ has all different labels from $[0,k'+5]$. The edge labels for the first seven edges of $L$ were $1,k,k+1,k+2,k+3,k+4,k+5$, the next edge label is $a\_1-4$ and the other edge labels are the missing ones from $[1,k+5]$. The first seven edge labels of $L'$ are $1,k',k'+1,k'+2,k'+3,k'+4,k'+5$, the next four edge labels are $\{(k'+2)-4,(k'+2)-3,k'-3,k'-a'\_1\}=\{k'-2,k'-1,k'-3,a\_1-4\}$ (remember that $a'\_i=k'+4-a\_i$) and the rest are identical to the rest of $L$, since our 'inversion' does not change the absolute value of the differences. Again straight inspection shows that we have found all possible values exactly once, which finishes the proof of our claim. To finish our proof we provide explicit graceful labelings for ``` $B(5,1)$: [0,1,4,2,6,5] $B(5,2)$: [0,1,5,2,7,6,4] $B(5,3)$: [0,1,6,3,7,8,2,4] $B(5,4)$: [0,1,7,2,9,8,4,6,3] $B(5,5)$: [0,1,8,2,10,9,4,6,3,7] $B(5,6)$: [0,1,9,2,11,10,4,7,3,8,6] ``` and the cyclic nature (period 3) of these labelings will provide a proof by induction. Note that for $k\leq 3$, $B(5,k)$ is still graceful, but the labeling is not always in the format we desire, so we start our induction at $k=4,5,6$. TODO: check if this mechanism can be generalized (not sure if I will continue working on this: the problem is not very important). Remark: it turned out that the value for $k$ I used was one off compared to the one used in the question. I hope I fixed them all, but let me know if you find an 'off by one' error.
51,548,884
``` try: folderSizeInMB= int(subprocess.check_output('du -csh --block-size=1M', shell=True).decode().split()[0]) print('\t\tTotal download progress (MB):\t' + str(folderSizeInMB), end = '\r') except Exception as e: print('\t\tDownloading' + '.'*(loopCount - gv.parallelDownloads + 3), end = '\r') ``` I have this code in my script because for some reason my unix decided to not find 'du' command. It throws an error `/bin/sh: du: command not found`. My hope with this code was that even though my program runs into this error, it will just display the message in the `except` block and move-along. However, it prints the error before displaying the message in the `except` block. Why is it doing so? Is there a way for me to suppress the error message displayed by the `try` block? Thanks. EDIT: I rewrote the code after receiving the answer like shown below and it works. I had to rewrite only one line: ``` folderSizeInMB= int(subprocess.check_output('du -csh --block-size=1M', shell=True, stederr=subprocess.DEVNULL).decode().split()[0]) ```
2018/07/26
[ "https://Stackoverflow.com/questions/51548884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2868465/" ]
The error is being shown by the shell, printing to stderr. Because you’re not redirecting its stderr, it just goes straight through to your own program’s stderr, which goes to your terminal. If you don’t want this—or any other shell features—then the simplest solution is to just not use the shell. Pass a list of arguments instead of a command line, and get rid of that `shell=True`, and the error will become a normal Python exception that you can handle with the code you already have. If you just use the shell for some reason, you will need to redirect its stderr. You can pass `stderr=subprocess.STDOUT` to make it merge in with the stdout that you’re already capturing, or `subprocess.DEVNULL` to ignore it. The `subprocess` module docs explain all of the options nicely, so read them, decide which behavior you want, and do that.
You can try redirecting the stderr to null to prevent the error from displaying. ``` import sys class DevNull: def write(self, msg): pass sys.stderr = DevNull() ```
81,247
I work with reconstructing fossil skeletons of human ancestors. Bones are usually incomplete and I need to assemble whole virtual bones from laser scans of different fossil parts of the bone I have scanned. How can I efficiently delete parts I don't need so that I can assemble whole virtual bones? I know it's easy to delete by bisecting, but that's not enough for what I need [![enter image description here](https://i.stack.imgur.com/zYOwO.jpg)](https://i.stack.imgur.com/zYOwO.jpg)Does this image help explain what I wantto do?
2017/06/12
[ "https://blender.stackexchange.com/questions/81247", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/40161/" ]
Hope this helps: You can try centering the mesh in an axis (X or Y most commonly) and then use `numpad 1` or `numpad 3` to get an isometric view of the mesh along that axis. (Depending on your blender config, you might need to also press `numpad 5`) Then you can press `z` and `tab` to go into wireframe mode and edit mode respectively. Once there, you can select whatever vertices are not needed (To select vertices you can use the hotkey `ctrl`+`shift`+`tab` and select vertices in the popup menu) and delete them. Then press `tab` again to go back to object mode and add a mirror modifier to mirror the whole "correct" side of the mesh along the axis you need. Fiddle around with the merge and clipping options to get whatever desired effect you were looking for.
You can use `Shift`+`Ctrl`+`Alt`+`M` to select non manifold vertices, essentially finding all holes and floating vertices in a mesh.
6,527,788
In Objective C I want to create a simple application that posts a string to a php file using ASIHTTPRequest. I have no need for an interface and am finding it hard to find any example code. Does anyone know where I can find code, or can anyone give me an example of such code?
2011/06/29
[ "https://Stackoverflow.com/questions/6527788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/559142/" ]
The ASIHTTPRequest documentation covers this. Specifically, [Sending a form POST with ASIFormDataRequest](http://allseeing-i.com/ASIHTTPRequest/How-to-use#sending_a_form_post_with_ASIFormDataRequest).
[This site](http://www.webdesignideas.org/2011/08/18/simple-login-app-for-iphone-tutorial/comment-page-1/#comment-34811) has a really great walkthrough on how to use ASIHTTPREQUEST to authenticate data against a database. the walkthrough breaks the entire process down file by file for you.
451,792
I am using Survival Analysis to analyse a data set, but i'm having a bit of trouble. The data consists of everyone who has/has not been terminated from employment within a 4 year period. The aim of the analysis is to uncover the median time to termination. The data includes 400 people who has experienced the event and 2275 people who have not. Looking at the raw data, 150 people have remained employed between 30-48 years. The remaining 2525 people have been employed for less than 30 years. The average time spent working in the organisation is 4 years. However, the median time to survival using survival analysis is 40 years. I'm very familiar with the organisation and this median time to leaving is counter intuitive. Am I missing something? My code is below You will see, I start by calculating the length of time from when they began working in the organisation and when they leave (variable name is 'yrs'). If they have not been terminated, today's date is used as they are still employed in the organisation (perhaps this is where i'm going wrong?). Then I create a survival curve using 'yrs' and 'termid', where termid is an indicator variable, indicating if the observation has been terminated or not. The median survival time of 40 years is then returned Is there an issue with my code? Or is it expected that so few observations could carry this much weight in a Survival Analysis. ``` #find survival time #calculating the number of days between last follow up date and date of starting in the organisation leaversanalysis = leaversanalysis %>% mutate( yrs = as.numeric( difftime(Term.Date, Date.Joined.Organisation, units = "days")) / 365.25 ) #Indicator variable for termination is 'termid' #Kaplan Meier estimator for any termination (termination =1, no termination =0) a <- Surv(leaversanalysis$yrs, leaversanalysis$termid) #Create survival curve surv_curvleave <- survfit(Surv(yrs, termid) ~ 1 , data = leaversanalysis) surv_curvleave ```
2020/02/28
[ "https://stats.stackexchange.com/questions/451792", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/237783/" ]
Median survival here is the time at which 50% of your participants would still be non-terminated. The lower the risk (hazard) of an event (in your case being "terminated"), the longer it will take to get to the point where 50% of participants have had that event. An example: simulate data similar to yours: ``` set.seed(129) yrs1 <- round(rbeta(n=2225, shape1 = 1.3, shape2 = 8)*48,1) yrs2 <- runif(450, min=0, max=48) yrs <- c(yrs1,yrs2) termid <- sample(x = c(rep(1, each = 400), rep(0,each=2275)), size = 2675) data <- data.frame(yrs,termid) sum(yrs>30) # 167 people employed over 30 yrs hist(yrs, breaks = 20) ``` [![enter image description here](https://i.stack.imgur.com/zcjOW.png)](https://i.stack.imgur.com/zcjOW.png) Your code is fine. The survival plot below should reveal why the "median survival" is what it is. ``` fit <- survfit(Surv(yrs,termid) ~1, data = data) plot(fit, xlab = "years", ylab = "probability of not being terminated") abline(h=0.5); abline(v=43.3) fit ``` [![Survival plot](https://i.stack.imgur.com/UOE0C.png)](https://i.stack.imgur.com/UOE0C.png) ``` Call: survfit(formula = Surv(yrs, termid) ~ 1, data = data) n events median 0.95LCL 0.95UCL 2675.0 400.0 43.3 40.1 46.2 ``` The reported median survival here is 43.3 years. You have said "this median time to leaving is counter intuitive". What you are studying is the median time to being terminated. If people are **leaving** for other reasons, then using these methods, they are censored, and so do not affect the position of the survival curve.
The name of the statistic "median survival time" can be a bit misleading - the median survival time of a population is *not* simply the median of survival times. That is, you can't simply take all the tenure lengths, find the median one, and be done. This is because many people leave for other reasons than being fired, so they drop out of the population (they are censored). If a person leaves voluntarily after 1 year, you know they would have survived *at least* 1 year without termination, but you can't use that 1 year as a data point for time-to-termination itself. In a population where no one is fired, you never reach median survival, but you will always be able to find a median of tenure times (which isn't nearly as useful). Rather, the median survival time is the time at which 50% of the uncensored population remains. You note that in your data, you have 400 people who were terminated, and 2275 who were not - only 15% of the population is ever terminated, so it makes sense that you either never see a time when 50% of your workforce has been fired, or see it only very late (when the remaining population is small). It would be *possible* to see this earlier on, as you could have 1875 people quit over the years, leaving 800 people, 400 of which are later fired. But that would require a very unusual skewing of voluntary quitting in the beginning, followed by a rash of firings at the end. In a population where the overall event rate is well below 50%, you typically won't hit median survival, barring unusual patterns in early censors and late events. Your median survival time is very long, which suggests there are only a handful of people who remain after a 40-year tenure, and half of them get fired.
69,224
I have this metric: $$ds^2=-dt^2+e^tdx^2$$ and I want to find the equation of motion (of x). for that i thought I have two options: 1. using E.L. with the Lagrangian: $L=-\dot t ^2+e^t\dot x ^2 $. 2. using the fact that for a photon $ds^2=0$ to get: $0=-dt^2+e^tdx^2$ and then: $dt=\pm e^{t/2} dx$. The problem is that (1) gives me $x=ae^{-t}+b$ and (2) gives me $x=ae^{-t/2} +b$.
2013/06/26
[ "https://physics.stackexchange.com/questions/69224", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/26299/" ]
If your solution is not a null geodesic then it is wrong for a massless particle. The reason you go astray is that Lagrangian you give in (1) is incorrect for massless particles. The general action for a particle (massive or massless) is: $$ S = -\frac{1}{2} \int \mathrm{d}\xi\ \left( \sigma(\xi) \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2 + \frac{m^2}{\sigma(\xi)}\right), $$ where $\xi$ is an arbitrary worldline parameter and $\sigma(\xi)$ an auxiliary variable that must be eliminated by its equation of motion. Also note the notation $$ \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2\equiv \pm g\_{\mu\nu} \frac{\mathrm{d}X^\mu}{\mathrm{d}\xi}\frac{\mathrm{d}X^\nu}{\mathrm{d}\xi}, $$ modulo your metric sign convention (I haven't checked which one is right for your convention). Check that for $m\neq 0$ this action reduces to the usual action for a massive particle. For the massless case however, you get $$ S = -\frac{1}{2} \int \mathrm{d}\xi\ \sigma(\xi) \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2. $$ The equation of motion for $\sigma$ gives the constraint $$ \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2 = 0, $$ for a null geodesic. This is necessary and consistent for massless particles, as you know. The equation of motion for $X^\mu$ is (**EDIT**: Oops, I forgot a term here. Note that $g\_{\mu\nu}$ depends on $X$ so a term involving $\partial\_\rho g\_{\mu\nu}$ comes into the variation. Try working it out for yourself. I'll fix the following equations up later): $$ \frac{\mathrm{d}}{\mathrm{d}\xi}\left(\sigma g\_{\mu\nu}\frac{\mathrm{d}X^{\mu}}{\mathrm{d}\xi}\right)=0, $$ but you can change the parameter $\xi\to\lambda$ so that $\sigma \frac{\mathrm{d}}{\mathrm{d}\xi} = \frac{\mathrm{d}}{\mathrm{d}\lambda}$, so the equation of motion simplifies to $$ \frac{\mathrm{d}}{\mathrm{d}\lambda}\left(g\_{\mu\nu}\frac{\mathrm{d}X^{\mu}}{\mathrm{d}\lambda}\right)=0, $$ which you should be able to solve to get something satisfying the null constraint.
There is an elegant way of doing this using symmetries. Notice that this metric is space translation invariant, so it has a killing vector $\partial\_x$. There is a corresponding conserved quantity $c\_x$ along geodesics $x^\mu(\lambda)$ given by \begin{align} c\_x = g\_{\mu\nu}\dot x^\mu(\partial\_x)^\nu = e^t\dot x \end{align} Where an overdot denotes differentiation with respect to affine parameter. On the other hand, the fact that the desired geodesic is a (null) photon geodesic along which $ds^2 = 0$ gives \begin{align} 0=-\dot t^2 + e^t\dot x^2 \end{align} This forms a set of coupled differential equations that is not actually that hard to solve. Hint: Try solving the first equation for $\dot x$, and then plugging it into the second equation.
69,224
I have this metric: $$ds^2=-dt^2+e^tdx^2$$ and I want to find the equation of motion (of x). for that i thought I have two options: 1. using E.L. with the Lagrangian: $L=-\dot t ^2+e^t\dot x ^2 $. 2. using the fact that for a photon $ds^2=0$ to get: $0=-dt^2+e^tdx^2$ and then: $dt=\pm e^{t/2} dx$. The problem is that (1) gives me $x=ae^{-t}+b$ and (2) gives me $x=ae^{-t/2} +b$.
2013/06/26
[ "https://physics.stackexchange.com/questions/69224", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/26299/" ]
If your solution is not a null geodesic then it is wrong for a massless particle. The reason you go astray is that Lagrangian you give in (1) is incorrect for massless particles. The general action for a particle (massive or massless) is: $$ S = -\frac{1}{2} \int \mathrm{d}\xi\ \left( \sigma(\xi) \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2 + \frac{m^2}{\sigma(\xi)}\right), $$ where $\xi$ is an arbitrary worldline parameter and $\sigma(\xi)$ an auxiliary variable that must be eliminated by its equation of motion. Also note the notation $$ \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2\equiv \pm g\_{\mu\nu} \frac{\mathrm{d}X^\mu}{\mathrm{d}\xi}\frac{\mathrm{d}X^\nu}{\mathrm{d}\xi}, $$ modulo your metric sign convention (I haven't checked which one is right for your convention). Check that for $m\neq 0$ this action reduces to the usual action for a massive particle. For the massless case however, you get $$ S = -\frac{1}{2} \int \mathrm{d}\xi\ \sigma(\xi) \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2. $$ The equation of motion for $\sigma$ gives the constraint $$ \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2 = 0, $$ for a null geodesic. This is necessary and consistent for massless particles, as you know. The equation of motion for $X^\mu$ is (**EDIT**: Oops, I forgot a term here. Note that $g\_{\mu\nu}$ depends on $X$ so a term involving $\partial\_\rho g\_{\mu\nu}$ comes into the variation. Try working it out for yourself. I'll fix the following equations up later): $$ \frac{\mathrm{d}}{\mathrm{d}\xi}\left(\sigma g\_{\mu\nu}\frac{\mathrm{d}X^{\mu}}{\mathrm{d}\xi}\right)=0, $$ but you can change the parameter $\xi\to\lambda$ so that $\sigma \frac{\mathrm{d}}{\mathrm{d}\xi} = \frac{\mathrm{d}}{\mathrm{d}\lambda}$, so the equation of motion simplifies to $$ \frac{\mathrm{d}}{\mathrm{d}\lambda}\left(g\_{\mu\nu}\frac{\mathrm{d}X^{\mu}}{\mathrm{d}\lambda}\right)=0, $$ which you should be able to solve to get something satisfying the null constraint.
I) Well, in 1+1 dimensions the light-cone (based at some point) is just two intersecting curves, which are precisely determined by the condition $$\tag{1} g\_{\mu\nu}\dot{x}^{\mu}\dot{x}^{\nu}~=~0,$$ and an initial condition cf. OP's second method. However, this eq. (1) will not determine light-like geodesics in higher dimensions. II) OP's first method, namely to vary the Lagrangian $$\tag{2} L~:=~ g\_{\mu\nu}(x)\dot{x}^{\mu}\dot{x}^{\nu} $$ is in principle also correct. It is a nice exercise to show that Euler-Lagrange equations are the [geodesic](http://en.wikipedia.org/wiki/Geodesic) equation. However, it seems that OP mistakenly identifies the parameter $\lambda$ of the geodesic with the $x^0$-coordinate. These are two different things! In 1+1 dimensions, we have two coordinates $x^0$ and $x^1$. There are two Euler-Lagrange equations. The complete solution for $\lambda\mapsto x^0(\lambda)$ and $\lambda\mapsto x^1(\lambda)$ will be *all* geodesics: time-like, light-like and space-like. Since we are only interested in *light-like* geodesics, we would also have to impose eq. (1) in the Euler-Lagrange method. III) If one makes a coordinate transformation $$\tag{3} u~=~\exp(-\frac{x^0}{2})\quad\text{and}\quad v~=~\frac{x^1}{2}, $$ then OP's metric becomes $$\tag{4} \frac{4}{u^2}(-du^2+dv^2)$$ which is e.g. also considered in [this](https://physics.stackexchange.com/q/64468/2451) Phys.SE post (up to an overall constant factor). Obviously, the light-like geodesics are of the form $$\tag{5} v-v\_0~=~ \pm (u-u\_0). $$
72,924,818
I've been trying for a long time to write the results to my file, but since it's a multithreaded task, the files are written in a mixed way The task that adds the file is in the get\_url function And this fonction is launched via pool.submit(get\_url,line) ``` import requests from concurrent.futures import ThreadPoolExecutor import fileinput from bs4 import BeautifulSoup import traceback import threading from requests.packages.urllib3.exceptions import InsecureRequestWarning import warnings requests.packages.urllib3.disable_warnings(InsecureRequestWarning) warnings.filterwarnings("ignore", category=UserWarning, module='bs4') count_requests = 0 host_error = 0 def get_url(url): try: global count_requests result_request = requests.get(url, verify=False) soup = BeautifulSoup(result_request.text, 'html.parser') with open('outfile.txt', 'a', encoding="utf-8") as f: f.write(soup.title.get_text()) count_requests = count_requests + 1 except: global host_error host_error = host_error + 1 with ThreadPoolExecutor(max_workers=100) as pool: for line in fileinput.input(['urls.txt']): pool.submit(get_url,line) print(str("requests success : ") + str(count_requests) + str(" | requests error ") + str(host_error), end='\r') ``` This is what the output looks like : google.com - Google w3schools.com - W3Schools Online Web Tutorials
2022/07/09
[ "https://Stackoverflow.com/questions/72924818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19518180/" ]
You can use [`multiprocessing.Pool`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool) and `pool.imap_unordered` to receive processed results and write it to the file. That way the results are written only inside main thread and won't be interleaved. For example: ```py import requests import multiprocessing from bs4 import BeautifulSoup def get_url(url): # do your processing here: soup = BeautifulSoup(requests.get(url).content, "html.parser") return soup.title.text if __name__ == "__main__": # read urls from file or other source: urls = ["http://google.com", "http://yahoo.com"] with multiprocessing.Pool() as p, open("result.txt", "a") as f_out: for result in p.imap_unordered(get_url, urls): print(result, file=f_out) ```
I agree with Andrej Kesely that we should not write to file within `get_url`. Here is my approach: ```py from concurrent.futures import ThreadPoolExecutor, as_completed def get_url(url): # Processing... title = ... return url, title if __name__ == "__main__": with open("urls.txt") as stream: urls = [line.strip() for line in stream] with ThreadPoolExecutor() as executor: urls_and_titles = executor.map(get_url, urls) # Exiting the with block: all tasks are done with open("outfile.txt", "w", encoding="utf-8") as stream: for url, title in urls_and_titles: stream.write(f"{url},{title}\n") ``` This approach waits until all tasks completed before writing out the result. If we want to write out the tasks as soon as possible: ```py from concurrent.futures import ThreadPoolExecutor, as_completed ... if __name__ == "__main__": with open("urls.txt") as stream: urls = [line.strip() for line in stream] with ThreadPoolExecutor() as executor, open("outfile.txt", "w", encoding="utf-8") as stream: futures = [ executor.submit(get_url, url) for url in urls ] for future in as_completed(futures): url, title = future.result() stream.write(f"{url},{title}\n") ``` The `as_completed()` function will take care to order the `Futures` object so the ones completed first is at the beginning of the queue. In conclusion, the key here is for the worker function `get_url` to return some value and do not write to file. That task will be done in the main thread.
13,869,060
I have the following code that is trying to remove some JSESSIONID cookies from my browser. ``` String[] cookieList = "/App1/,/App2/,/App3/".split(","); for (int i = 0; i < cookieList.length; i++) { String cookiePathString = cookieList[i]; response.setContentType("text/html"); Cookie cookieToKill = new Cookie("JSESSIONID", "No Data"); cookieToKill.setDomain(getCookieDomainName("myDomain.com")); cookieToKill.setMaxAge(0); cookieToKill.setPath(cookiePathString); cookieToKill.setComment("EXPIRING COOKIE at " + System.currentTimeMillis()); response.addCookie(cookieToKill); } ``` The code works fine in Firefox, and deletes the JSESSIONID. In Chrome and IE it does not. What do you have to do to expire these session cookies from IE and Chrome? This is running in an Spring MVC Application on Tomcat running Java 7
2012/12/13
[ "https://Stackoverflow.com/questions/13869060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1408524/" ]
Cookie is completely messed up. The best practices for a server: 1. use Set-Cookie, not Set-Cookie2. 2. if there are multiple cookies, use a separate Set-Cookie header for each cookie. 3. use Expires, not Max-Age. 4. use the date format: `Sun, 06 Nov 1994 08:49:37 GMT` For example: ``` Set-Cookie: JSESSIONID=NO_DATA; Path=/App1/; Domain=myDomain.com; Expires=Thu, 01 Jan 1970 00:00:00 GMT ``` What I can recommend you to do: 1. Don't have spaces in cookie values. 2. Call `cookie.setVersion(0);` If still no luck, forget the `Cookie` class, try set the http header manually ``` response.addHeader("Set-Cookie", "JSESSIONID=NO_DATA; Path=/App1/; Domain=myDomain.com; Expires=Thu, 01 Jan 1970 00:00:00 GMT"); ```
[This SO question](https://stackoverflow.com/questions/1716555/setting-persistent-cookie-from-java-doesnt-work-in-ie) indicates that the solution may be to call `setHttpOnly(true)`.
62,853
Also, if there is truth behind Republican support to make voting more restrictive for people in general, how long ago might this party have started advocating legislation with more restrictions? Why --- Listening to the video on [this post](https://www.cnn.com/2021/03/02/politics/supreme-court-brnovich-v-dnc-case-analysis-john-roberts/index.html), there are different Republican and Democrat views on voting access. It seems to be portrayed that... 1. Democrats want more people to have access to their voting rights by fewer disqualifying restrictions. 2. Republicans want fewer people to have access to their voting rights by more disqualifying restrictions. I found the end of the audio most interesting where [Amy Coney Barrett](https://en.wikipedia.org/wiki/Amy_Coney_Barrett) asked the RNC attorney about the interest to the RNC in keeping the out-of-precinct voter ballot disqualification rule in place in Arizona. The RNC attorney's response was "*Because it puts us at a competitive disadvantage relative to Democrats. Politics is a zero-sum game*".
2021/03/03
[ "https://politics.stackexchange.com/questions/62853", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/7229/" ]
Speaking nationally, Democrats currently have a 6%-7% advantage over Republicans in terms of voter representation. In fact, Democrats have a lead among every demographic group except *white males without a college education*. However, Democratic voters tend to be clustered in urban and suburban areas, which attenuates their voting power somewhat and leaves them vulnerable to manipulations like gerrymandering. Further, they have lower SES (socio-economic status) as a group, meaning they are more affected by restrictions on registration and voting. And that's not mentioning the Electoral College, which gives a significant advantage to parties that control smaller states (which currently — for the most part — lean Republican). So yes: making voting more restrictive mainly impacts low income voters in urban areas, those who have the least free time and fewest material and financial resources to jump through bureaucratic hoops. At least some Republicans and conservatives explicitly advocate for this kind of implicit disenfranchisement in order to maintain power. I cannot speak to the intentions of the GOP as a whole, except to note that anyone in the political universe with any minimal competence is aware of the fact that there are material conditions to voting which can present obstacles. This has been well-known and thoroughly argued since the Jim Crow days, back when the Supreme Court struck down poll taxes, so anyone who talks about voting restrictions without also considering the issue of structural disenfranchisement is either deeply ignorant or purely Machiavellian. Granting that some conservatives do argue that there should be a 'civic commitment' standard applied to voting — akin to the ancient Greek practice of restricting the democratic participation to established property owners and native sons, on the grounds that such people have a firm commitment to the welfare of the community — the GOP itself has never raised that *explicitly* as a platform, for the obvious 'optics' reasons. And note that the situation is more complex than it appears on the surface. The GOP could (for instance) work to increase its voter base, thus obviating the need for voting restrictions. But that would involve creating a forward-thinking platform meant to appeal to a broader coalition, which risks insulting certain die-hard, single-issue voting blocks that the GOP has catered to since the 70s. Those voting blocks are not exactly unified, but they represent some of the most readily mobilized elements of the GOP base, so the GOP prefers a fragmented, decentered, 'talking point' style of politics, one which allows them to play both ends against the middle without committing themselves to anything. Squeezing out unwanted voters is simpler and safer.
> > How long ago might this party have started advocating legislation with more restrictions? > > > For the Republican party in particular it began with [the Southern strategy](https://en.wikipedia.org/wiki/Southern_strategy) to wrest control of southern states from the Democrats by attracting conservative white voters who were afraid of desegregation and the Civil Rights movement. Prior to this, [southern states were Democratic strongholds](https://en.wikipedia.org/wiki/Solid_South). The Republicans came out strongly against desegregation and the Civil Rights Act by [nominating Barry Goldwater in 1964](https://en.wikipedia.org/wiki/1964_United_States_presidential_election) who opposed the Civil Rights Act. He lost in a landslide to Lyndon Johnson who championed it, but they won five southern states. [In 1968 Nixon won](https://en.wikipedia.org/wiki/1968_United_States_presidential_election) on a less overtly racist platform than Goldwater. Moving away from increasingly unpopular opposition to desegregation, he ran on what we now call ["dog-whistles"](https://en.wikipedia.org/wiki/Dog-whistle_politics) emphasizing the same cloaked terms we use today: ["law and order"](https://en.wikipedia.org/wiki/Law_and_order_(politics)) and ["the war on drugs"](https://en.wikipedia.org/wiki/War_on_drugs). These targeted a set of minor offenses committed more often by minorities, particularly drug convictions, and elevated them to felonies. A [loophole in the 13th Amendment](https://en.wikipedia.org/wiki/Thirteenth_Amendment_to_the_United_States_Constitution#Penal_labor_exemption) then allows [felons to be disenfranchised](https://en.wikipedia.org/wiki/Felony_disenfranchisement_in_the_United_States). After dropping from 1960 to 1976, [felony disenfranchisement has ballooned from 1 million to 6 million people](https://www.sentencingproject.org/publications/felony-disenfranchisement-a-primer/). As of 2016 1-in-13 black citizens had their right to vote revoked compared to 1-in-56 non-black. However, it's useful to recognize that the positions of the parties inverted. The US has [a very long history of black voter suppression](https://en.wikipedia.org/wiki/Disenfranchisement_after_the_Reconstruction_era) going back to the post-Civil War [Black Codes](https://en.wikipedia.org/wiki/Black_Codes_(United_States)) and [Jim Crow laws](https://en.wikipedia.org/wiki/Jim_Crow_laws) designed to continue to use black people as cheap labor and keep them from voting. [Poll taxes](https://en.wikipedia.org/wiki/Poll_tax_(United_States)), [literacy tests](https://en.wikipedia.org/wiki/Literacy_tests), residency requirements, and record requirements seemed like they affected everyone while carefully crafted [grandfather clauses](https://en.wikipedia.org/wiki/Grandfather_clause) excused people whose fathers or grandfathers had been eligible to vote ensured that white voters were less affected. Measures such as the [24th Amendment](https://en.wikipedia.org/wiki/Twenty-fourth_Amendment_to_the_United_States_Constitution), the aforementioned Civil Rights Act, and the [Voter Rights Act of 1965](https://en.wikipedia.org/wiki/Voting_Rights_Act_of_1965) made such overt tactics more difficult, voter suppression has become increasingly cloaked. For example, [as of 2016 10% of Florida is disenfranchised including over 20% of the black population](https://felonvoting.procon.org/wp-content/uploads/sites/48/sentencing-project-felony-disenfranchisement-2016.pdf). After the people overwhelmingly [voted to restore voting rights to released felons in Florida](https://en.wikipedia.org/wiki/2018_Florida_Amendment_4), the legislature passed [SB 7066](https://www.flsenate.gov/Session/Bill/2019/7066/BillText/er/PDF) requiring they first pay off all "fines and fees" first: [a modern poll tax](https://www.salon.com/2019/08/03/modern-day-poll-taxes-disenfranchise-millions-of-low-income-voters_partner/).
62,853
Also, if there is truth behind Republican support to make voting more restrictive for people in general, how long ago might this party have started advocating legislation with more restrictions? Why --- Listening to the video on [this post](https://www.cnn.com/2021/03/02/politics/supreme-court-brnovich-v-dnc-case-analysis-john-roberts/index.html), there are different Republican and Democrat views on voting access. It seems to be portrayed that... 1. Democrats want more people to have access to their voting rights by fewer disqualifying restrictions. 2. Republicans want fewer people to have access to their voting rights by more disqualifying restrictions. I found the end of the audio most interesting where [Amy Coney Barrett](https://en.wikipedia.org/wiki/Amy_Coney_Barrett) asked the RNC attorney about the interest to the RNC in keeping the out-of-precinct voter ballot disqualification rule in place in Arizona. The RNC attorney's response was "*Because it puts us at a competitive disadvantage relative to Democrats. Politics is a zero-sum game*".
2021/03/03
[ "https://politics.stackexchange.com/questions/62853", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/7229/" ]
Speaking nationally, Democrats currently have a 6%-7% advantage over Republicans in terms of voter representation. In fact, Democrats have a lead among every demographic group except *white males without a college education*. However, Democratic voters tend to be clustered in urban and suburban areas, which attenuates their voting power somewhat and leaves them vulnerable to manipulations like gerrymandering. Further, they have lower SES (socio-economic status) as a group, meaning they are more affected by restrictions on registration and voting. And that's not mentioning the Electoral College, which gives a significant advantage to parties that control smaller states (which currently — for the most part — lean Republican). So yes: making voting more restrictive mainly impacts low income voters in urban areas, those who have the least free time and fewest material and financial resources to jump through bureaucratic hoops. At least some Republicans and conservatives explicitly advocate for this kind of implicit disenfranchisement in order to maintain power. I cannot speak to the intentions of the GOP as a whole, except to note that anyone in the political universe with any minimal competence is aware of the fact that there are material conditions to voting which can present obstacles. This has been well-known and thoroughly argued since the Jim Crow days, back when the Supreme Court struck down poll taxes, so anyone who talks about voting restrictions without also considering the issue of structural disenfranchisement is either deeply ignorant or purely Machiavellian. Granting that some conservatives do argue that there should be a 'civic commitment' standard applied to voting — akin to the ancient Greek practice of restricting the democratic participation to established property owners and native sons, on the grounds that such people have a firm commitment to the welfare of the community — the GOP itself has never raised that *explicitly* as a platform, for the obvious 'optics' reasons. And note that the situation is more complex than it appears on the surface. The GOP could (for instance) work to increase its voter base, thus obviating the need for voting restrictions. But that would involve creating a forward-thinking platform meant to appeal to a broader coalition, which risks insulting certain die-hard, single-issue voting blocks that the GOP has catered to since the 70s. Those voting blocks are not exactly unified, but they represent some of the most readily mobilized elements of the GOP base, so the GOP prefers a fragmented, decentered, 'talking point' style of politics, one which allows them to play both ends against the middle without committing themselves to anything. Squeezing out unwanted voters is simpler and safer.
Not necessarily. If any once dominant political party wishes to win more elections without imposing "voting restrictions", they might also consider changing with the times to better represent the wider preferences of the general public.
62,853
Also, if there is truth behind Republican support to make voting more restrictive for people in general, how long ago might this party have started advocating legislation with more restrictions? Why --- Listening to the video on [this post](https://www.cnn.com/2021/03/02/politics/supreme-court-brnovich-v-dnc-case-analysis-john-roberts/index.html), there are different Republican and Democrat views on voting access. It seems to be portrayed that... 1. Democrats want more people to have access to their voting rights by fewer disqualifying restrictions. 2. Republicans want fewer people to have access to their voting rights by more disqualifying restrictions. I found the end of the audio most interesting where [Amy Coney Barrett](https://en.wikipedia.org/wiki/Amy_Coney_Barrett) asked the RNC attorney about the interest to the RNC in keeping the out-of-precinct voter ballot disqualification rule in place in Arizona. The RNC attorney's response was "*Because it puts us at a competitive disadvantage relative to Democrats. Politics is a zero-sum game*".
2021/03/03
[ "https://politics.stackexchange.com/questions/62853", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/7229/" ]
> > How long ago might this party have started advocating legislation with more restrictions? > > > For the Republican party in particular it began with [the Southern strategy](https://en.wikipedia.org/wiki/Southern_strategy) to wrest control of southern states from the Democrats by attracting conservative white voters who were afraid of desegregation and the Civil Rights movement. Prior to this, [southern states were Democratic strongholds](https://en.wikipedia.org/wiki/Solid_South). The Republicans came out strongly against desegregation and the Civil Rights Act by [nominating Barry Goldwater in 1964](https://en.wikipedia.org/wiki/1964_United_States_presidential_election) who opposed the Civil Rights Act. He lost in a landslide to Lyndon Johnson who championed it, but they won five southern states. [In 1968 Nixon won](https://en.wikipedia.org/wiki/1968_United_States_presidential_election) on a less overtly racist platform than Goldwater. Moving away from increasingly unpopular opposition to desegregation, he ran on what we now call ["dog-whistles"](https://en.wikipedia.org/wiki/Dog-whistle_politics) emphasizing the same cloaked terms we use today: ["law and order"](https://en.wikipedia.org/wiki/Law_and_order_(politics)) and ["the war on drugs"](https://en.wikipedia.org/wiki/War_on_drugs). These targeted a set of minor offenses committed more often by minorities, particularly drug convictions, and elevated them to felonies. A [loophole in the 13th Amendment](https://en.wikipedia.org/wiki/Thirteenth_Amendment_to_the_United_States_Constitution#Penal_labor_exemption) then allows [felons to be disenfranchised](https://en.wikipedia.org/wiki/Felony_disenfranchisement_in_the_United_States). After dropping from 1960 to 1976, [felony disenfranchisement has ballooned from 1 million to 6 million people](https://www.sentencingproject.org/publications/felony-disenfranchisement-a-primer/). As of 2016 1-in-13 black citizens had their right to vote revoked compared to 1-in-56 non-black. However, it's useful to recognize that the positions of the parties inverted. The US has [a very long history of black voter suppression](https://en.wikipedia.org/wiki/Disenfranchisement_after_the_Reconstruction_era) going back to the post-Civil War [Black Codes](https://en.wikipedia.org/wiki/Black_Codes_(United_States)) and [Jim Crow laws](https://en.wikipedia.org/wiki/Jim_Crow_laws) designed to continue to use black people as cheap labor and keep them from voting. [Poll taxes](https://en.wikipedia.org/wiki/Poll_tax_(United_States)), [literacy tests](https://en.wikipedia.org/wiki/Literacy_tests), residency requirements, and record requirements seemed like they affected everyone while carefully crafted [grandfather clauses](https://en.wikipedia.org/wiki/Grandfather_clause) excused people whose fathers or grandfathers had been eligible to vote ensured that white voters were less affected. Measures such as the [24th Amendment](https://en.wikipedia.org/wiki/Twenty-fourth_Amendment_to_the_United_States_Constitution), the aforementioned Civil Rights Act, and the [Voter Rights Act of 1965](https://en.wikipedia.org/wiki/Voting_Rights_Act_of_1965) made such overt tactics more difficult, voter suppression has become increasingly cloaked. For example, [as of 2016 10% of Florida is disenfranchised including over 20% of the black population](https://felonvoting.procon.org/wp-content/uploads/sites/48/sentencing-project-felony-disenfranchisement-2016.pdf). After the people overwhelmingly [voted to restore voting rights to released felons in Florida](https://en.wikipedia.org/wiki/2018_Florida_Amendment_4), the legislature passed [SB 7066](https://www.flsenate.gov/Session/Bill/2019/7066/BillText/er/PDF) requiring they first pay off all "fines and fees" first: [a modern poll tax](https://www.salon.com/2019/08/03/modern-day-poll-taxes-disenfranchise-millions-of-low-income-voters_partner/).
Not necessarily. If any once dominant political party wishes to win more elections without imposing "voting restrictions", they might also consider changing with the times to better represent the wider preferences of the general public.
19,585,979
I'm using ant to package a JavaFX-based application. No problem with doing the actual JavaFX stuff, except that `fx:jar` doesn't support the `if` or `condition` tags. I want to dynamically include some platform-specific libraries, depending on a variable i set. Currently I have this: ``` <fx:fileset dir="/my/classes/folder"> <include name="**/*lib1.dylib" if="??"/> <include name="**/*lib2.dll" if="??" /> <include name="**/*lib3.dll" if="??" /> </fx:fileset> ``` I want to run this target multiple times, with a different variable value depending on the platform. It seems you can not do something like: ``` <include name="**/*lib3.dll" if="platform=mac" /> ``` So I'm stuck. Please help!
2013/10/25
[ "https://Stackoverflow.com/questions/19585979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568355/" ]
Many readers of this forum expect to see *some* code that you tried.... ``` program flow version 8 // will work on almost all Stata in current use gettoken what garbage : 0 if "`what'" == "" | "`garbage'" != "" | !inlist("`what'", "e", "i") { di as err "syntax is flow e or flow i" exit 198 } if "`what'" == "e" { <code for e> } else if "`what'" == "i" { <code for i> } end ``` The last `if` condition is redundant as we've already established that the user typed `e` or `i`. Edit it out according to taste.
Given your comment on the answer by @NickCox, I assume you tried something like this: ``` program flow version 8 syntax [, i e] if "`i'`e'" == "" { di as err "either the i or the e option needs to be specified" exit 198 } if "`i'" != "" & "`e'" != "" { di as err "the i and e options cannot be specified together" exit 198 } if "`e'" != "" { <code for e> } if "`i'" != "" { <code for i> } end ``` After that you call `flow` like this: `flow, i` or `flow, e`. Notice the comma, this is now necessary (but not in the command by @NickCox) because you made them options.
19,585,979
I'm using ant to package a JavaFX-based application. No problem with doing the actual JavaFX stuff, except that `fx:jar` doesn't support the `if` or `condition` tags. I want to dynamically include some platform-specific libraries, depending on a variable i set. Currently I have this: ``` <fx:fileset dir="/my/classes/folder"> <include name="**/*lib1.dylib" if="??"/> <include name="**/*lib2.dll" if="??" /> <include name="**/*lib3.dll" if="??" /> </fx:fileset> ``` I want to run this target multiple times, with a different variable value depending on the platform. It seems you can not do something like: ``` <include name="**/*lib3.dll" if="platform=mac" /> ``` So I'm stuck. Please help!
2013/10/25
[ "https://Stackoverflow.com/questions/19585979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568355/" ]
Many readers of this forum expect to see *some* code that you tried.... ``` program flow version 8 // will work on almost all Stata in current use gettoken what garbage : 0 if "`what'" == "" | "`garbage'" != "" | !inlist("`what'", "e", "i") { di as err "syntax is flow e or flow i" exit 198 } if "`what'" == "e" { <code for e> } else if "`what'" == "i" { <code for i> } end ``` The last `if` condition is redundant as we've already established that the user typed `e` or `i`. Edit it out according to taste.
If you want `i` and `e` to be mutually exclusive options, then this is yet another alternative: ``` program flow version 8 capture syntax , e if _rc == 0 { // syntax matched what was typed <code for e> } else { syntax , i // error message and program exit if syntax is incorrect <code for i> } end ``` If the code in each branch is at all long, many would prefer subprograms for each case as a matter of good style, but that would be consistent with the sketch here. Note that in each `syntax` statement the option is declared compulsory. The effect of `capture` is this: errors are not fatal, but are "eaten" by `capture`. So you need to look at the return code, accessible in `_rc`. 0 for `_rc` always means that the command was successful. Non-zero always means that the command was unsuccessful. Here, and often elsewhere, there are only two ways for the command to be right, so we don't need to know what `_rc` was; we just need to check for the other legal syntax. Note that even my two answers here differ in style on whether a user typing an illegal command gets an informative error message or just "invalid syntax". The context to this is an expectation that every Stata command comes with a help file. Some programmers write on the assumption that the help file explains the syntax; others want their error messages to be as helpful as possible.
19,585,979
I'm using ant to package a JavaFX-based application. No problem with doing the actual JavaFX stuff, except that `fx:jar` doesn't support the `if` or `condition` tags. I want to dynamically include some platform-specific libraries, depending on a variable i set. Currently I have this: ``` <fx:fileset dir="/my/classes/folder"> <include name="**/*lib1.dylib" if="??"/> <include name="**/*lib2.dll" if="??" /> <include name="**/*lib3.dll" if="??" /> </fx:fileset> ``` I want to run this target multiple times, with a different variable value depending on the platform. It seems you can not do something like: ``` <include name="**/*lib3.dll" if="platform=mac" /> ``` So I'm stuck. Please help!
2013/10/25
[ "https://Stackoverflow.com/questions/19585979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568355/" ]
Given your comment on the answer by @NickCox, I assume you tried something like this: ``` program flow version 8 syntax [, i e] if "`i'`e'" == "" { di as err "either the i or the e option needs to be specified" exit 198 } if "`i'" != "" & "`e'" != "" { di as err "the i and e options cannot be specified together" exit 198 } if "`e'" != "" { <code for e> } if "`i'" != "" { <code for i> } end ``` After that you call `flow` like this: `flow, i` or `flow, e`. Notice the comma, this is now necessary (but not in the command by @NickCox) because you made them options.
If you want `i` and `e` to be mutually exclusive options, then this is yet another alternative: ``` program flow version 8 capture syntax , e if _rc == 0 { // syntax matched what was typed <code for e> } else { syntax , i // error message and program exit if syntax is incorrect <code for i> } end ``` If the code in each branch is at all long, many would prefer subprograms for each case as a matter of good style, but that would be consistent with the sketch here. Note that in each `syntax` statement the option is declared compulsory. The effect of `capture` is this: errors are not fatal, but are "eaten" by `capture`. So you need to look at the return code, accessible in `_rc`. 0 for `_rc` always means that the command was successful. Non-zero always means that the command was unsuccessful. Here, and often elsewhere, there are only two ways for the command to be right, so we don't need to know what `_rc` was; we just need to check for the other legal syntax. Note that even my two answers here differ in style on whether a user typing an illegal command gets an informative error message or just "invalid syntax". The context to this is an expectation that every Stata command comes with a help file. Some programmers write on the assumption that the help file explains the syntax; others want their error messages to be as helpful as possible.
1,362,991
Let $\sum a\_n=a$ with terms non-negative. Let $ s\_n$ the n-nth partial sum. Prove $\sum na\_n$ converge if $\sum (a-s\_n)$ converge
2015/07/16
[ "https://math.stackexchange.com/questions/1362991", "https://math.stackexchange.com", "https://math.stackexchange.com/users/254420/" ]
$$ \begin{align} \sum\_{k=1}^nka\_k &=\sum\_{k=1}^n\sum\_{j=1}^ka\_k\\ &=\sum\_{j=1}^n\sum\_{k=j}^na\_k\\ &=\sum\_{j=1}^n(s\_n-s\_{j-1}) \end{align} $$ Taking limits, we get by [Monotone Convergence](https://en.wikipedia.org/wiki/Monotone_convergence_theorem) that $$ \begin{align} \sum\_{k=1}^\infty ka\_k &=\sum\_{j=1}^\infty(a-s\_{j-1})\\ &=a+\sum\_{j=1}^\infty(a-s\_j)\\ \end{align} $$
It is easy to prove the following fact: If $(a\_n) $ is decreasing sequence and $\sum\_{j=1}^{\infty } a\_j $ converges then $\lim\_{j\to \infty } ja\_j =0.$ Now let $r\_n =\sum\_{k=n+1}^{\infty } a\_n $ and assume that $\sum\_{i=1}^{\infty} r\_n <\infty .$ Observe that $(r\_n )$ is an decreasing sequence, hence by the fact $\lim\_{n\to\infty} nr\_n =0.$ Take any $\varepsilon >0$ and let $n\_0 $ by such a big that $nr\_n <\varepsilon $ and $\sum\_{k=n}^{\infty} r\_k <\varepsilon $ for $n\geqslant n\_0 -1$ then we have $$\sum\_{j=n\_0}^{\infty} ja\_j = n\_0 r\_{n\_0 -1} + \sum\_{k=n\_0}^{\infty } r\_k\leqslant \varepsilon +\varepsilon =2\varepsilon .$$ Thus the series $$\sum\_{j=1}^{\infty} ja\_j $$ converges.
1,362,991
Let $\sum a\_n=a$ with terms non-negative. Let $ s\_n$ the n-nth partial sum. Prove $\sum na\_n$ converge if $\sum (a-s\_n)$ converge
2015/07/16
[ "https://math.stackexchange.com/questions/1362991", "https://math.stackexchange.com", "https://math.stackexchange.com/users/254420/" ]
$$ \begin{align} \sum\_{k=1}^nka\_k &=\sum\_{k=1}^n\sum\_{j=1}^ka\_k\\ &=\sum\_{j=1}^n\sum\_{k=j}^na\_k\\ &=\sum\_{j=1}^n(s\_n-s\_{j-1}) \end{align} $$ Taking limits, we get by [Monotone Convergence](https://en.wikipedia.org/wiki/Monotone_convergence_theorem) that $$ \begin{align} \sum\_{k=1}^\infty ka\_k &=\sum\_{j=1}^\infty(a-s\_{j-1})\\ &=a+\sum\_{j=1}^\infty(a-s\_j)\\ \end{align} $$
This is less rigorous than the other answer but more intuitive to me (and tells us a neat thing). $\displaystyle \sum\_1^{N} (a-s\_n)=Na-\sum\_1^N(N+1-n)a\_n$. As $N \to \infty$, $\displaystyle Na-\sum\_1^N(N+1-n)a\_n \to -\sum\_1^{\infty}(1-n)a\_n = \sum\_1^{\infty} na\_n-a$. Hence $\displaystyle \sum\_1^{\infty} (a-s\_n)$ converges $\displaystyle \iff \sum\_1^{\infty} na\_n$ converges. The neat thing is that assuming convergence, $\displaystyle \sum\_1^{\infty} (a-s\_n) = \sum\_1^{\infty} na\_n-a$
1,362,991
Let $\sum a\_n=a$ with terms non-negative. Let $ s\_n$ the n-nth partial sum. Prove $\sum na\_n$ converge if $\sum (a-s\_n)$ converge
2015/07/16
[ "https://math.stackexchange.com/questions/1362991", "https://math.stackexchange.com", "https://math.stackexchange.com/users/254420/" ]
$$ \begin{align} \sum\_{k=1}^nka\_k &=\sum\_{k=1}^n\sum\_{j=1}^ka\_k\\ &=\sum\_{j=1}^n\sum\_{k=j}^na\_k\\ &=\sum\_{j=1}^n(s\_n-s\_{j-1}) \end{align} $$ Taking limits, we get by [Monotone Convergence](https://en.wikipedia.org/wiki/Monotone_convergence_theorem) that $$ \begin{align} \sum\_{k=1}^\infty ka\_k &=\sum\_{j=1}^\infty(a-s\_{j-1})\\ &=a+\sum\_{j=1}^\infty(a-s\_j)\\ \end{align} $$
Simply note $$ \sum\_n (a-s\_n)=\sum\_n \sum\_{k=n+1}^\infty a\_k = \sum\_{k=2}^\infty \sum\_{n=1}^{k-1} a\_k =\sum\_{k=2}^\infty (k-1)a\_k. $$ Here, we can interchange the same since all commands are nonnegative. Using the assumption that $\sum\_n a\_n$ converges, this easily implies the claim (even with if and only if).
7,530,329
I am using jQuery and jQuery UI and i am trying to read a checkbox state through the addition of the "aria-pressed" property that jQuery UI Button toggle between false and true. ``` $('.slideButton').live('click', function() { alert($(this).attr('aria-pressed')); }); ``` This code however seems to read the aria-pressed before jQuery UI has updated aria-pressed. So i unreliable values. Can i schedule it to execute after the UI has updated or can i make it wait? [Live example here!](http://jonasbengtson.se/projects/dh/admin/)
2011/09/23
[ "https://Stackoverflow.com/questions/7530329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/961325/" ]
Can't you add a listener to the actual checkbox behind the label or span? ``` $("#days_list li div div div input[type='checkbox']").change(function(){ alert("Someone just clicked checkbox with id"+$(this).attr("id")); }); ``` This should work since, once you click the label, you change the value in the checkbox. --- Alright, I've composed a [live example](http://jsfiddle.net/S5NEf/4/) for you that demonstrates the general idea of how it works, and how you retrieve the status of the checkbox. ``` $("#checkbox_container input").change(function(){ if($(this).is(":checked")) alert("Checked!"); else alert("Unchecked!"); }); ``` In your case, since the checkbox is added dynamically by JQuery you have to use the live event, but it is basically the same thing ``` $("#checkbox_container input").live("changed".... ``` [Here's an example](http://jsfiddle.net/S5NEf/8/) with some additional scripting and checking, mostly for demonstrative purposes.
You can use a callback to execute the `alert($(this).attr('aria-pressed'));` after the toggle has completed. ``` $('.slidebutton').toggle(1000, function(){ alert($(this).attr('aria-pressed')); }); ``` I'm not too sure if your using `.toggle()` or not but you would need to use a callback either way to ensure sequential execution.
7,420,940
I have a vbscript that runs on the command line in xp. It accepts one argument for the path to a directory. Is there a simple way to prompt the user in the command line box for this? If not, I can just echo what was passed in to show the user what they actually typed in case of typos. Thanks, James Aftermath: Here is the code I ended up with: On Error Resume Next strDirectory = InputBox(Message, Title, "For example - P:\Windows\") ``` If strDirectory = "" Then 'Wscript.Echo cancelledText Else 'Wscript.Echo enteredText & strDirectory etc... ``` I found some snippets and it turned out to be really simple to work with the inputBox. HTH. James
2011/09/14
[ "https://Stackoverflow.com/questions/7420940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/543572/" ]
You can use the [`WScript.StdIn`](http://msdn.microsoft.com/en-us/library/1y8934a7%28v=VS.85%29.aspx) property to read from the the standard input. If you want to supply the path when invoking the script, you can pass the path as a parameter. You'll find it in the [`WScript.Arguments`](http://msdn.microsoft.com/en-us/library/z2b05k8s%28v=VS.85%29.aspx) property.
you can use the choice command, [choice](http://www.robvanderwoude.com/choice.php) it sets errorlevel to the value selected. I think it comes with DOS, Windows 95,98, then MS dropped it and then came back again in Windows 7 and probably Vista P.D. oh never mind, I read again and you're in XP. There are other options, like `set /p name= What is your name?` would create a variable %name% you can use
19,946,041
I recently discovered this script: [JS fiddle text swapper](http://jsfiddle.net/PMKDG/) - but I'd like to add a nice fade in and fade out. I guess this is a 2 part question. 1. Can I add fadeIn the way this is structured? 2. I'm guessing I'll also need a FadeOut? Help would be greatly appreciated! Thanks ``` $(function() { $("#all-iso, #date-iso, #actor-iso, #film-iso").on("click", function(e) { var txt = ""; switch ($(this).prop("id")) { case "all-iso": txt = "ALLE NEWS"; break; case "date-iso": txt = "DATUM"; break; case "actor-iso": txt = "SCHAUSPIELER"; break; case "film-iso": txt = "FILM"; break; } $("#news-h3-change").text(txt); }) }) ```
2013/11/13
[ "https://Stackoverflow.com/questions/19946041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572316/" ]
Try ``` $("#news-h3-change").fadeOut(function(){ $(this).text(txt) }).fadeIn(); ``` Demo: [Fiddle](http://jsfiddle.net/arunpjohny/93WG6/) I might suggest to use `data-*` to make it little more nice, like ``` <ul id="iso"> <li data-txt="ALLE NEWS">all-iso</li> <li data-txt="DATUM">date-iso</li> <li data-txt="SCHAUSPIELER">actor-iso</li> <li data-txt="FILM">film-iso</li> </ul> <h3 id="news-h3-change"></h3> ``` then ``` $(function () { $("#iso > li").on("click", function (e) { var txt = $(this).data('txt'); $("#news-h3-change").stop(true, true).fadeOut(function () { $(this).text(txt) }).fadeIn('slow'); }) }) ``` Demo: [Fiddle](http://jsfiddle.net/arunpjohny/dmZ5W/)
Here is another way to do it [JSFiddle](http://jsfiddle.net/PMKDG/29/) ``` $(function() { $("#all-iso, #date-iso, #actor-iso, #film-iso").on("click", function(e) { var txt = "", id = $(this).prop("id"); $('#news-h3-change').fadeOut('slow', function() { switch (id) { case "all-iso": txt = "ALLE NEWS"; break; case "date-iso": txt = "DATUM"; break; case "actor-iso": txt = "SCHAUSPIELER"; break; case "film-iso": txt = "FILM"; break; } $(this).text(txt); $("#news-h3-change").fadeIn('slow'); }); }) }) ```
51,249,250
I'm trying to edit this code to be dynamic as I'm going to schedule it to run. Normally I would input the date in the where statement as 'YYYY-MM-DD' and so to make it dynamic I changed it to DATE(). I'm not erroring out, but I'm also not pulling data. I just need help with format and my google searching isn't helping. ``` PROC SQL; CONNECT TO Hadoop (server=disregard this top part); CREATE TABLE raw_daily_fcast AS SELECT * FROM connection to Hadoop( SELECT DISTINCT a.RUN_DATE, a.SCHEDSHIPDATE, a.SOURCE, a.DEST , a.ITEM, b.U_OPSTUDY, a.QTY, c.case_pack_qty FROM CSO.RECSHIP a LEFT JOIN CSO.UDT_ITEMPARAM b ON a.ITEM = b.ITEM LEFT JOIN SCM.DIM_PROD_PLN c ON a.ITEM = c.PLN_NBR WHERE a.RUN_DATE = DATE() AND a.SOURCE IN ('88001', '88003', '88004', '88006', '88008', '88010', '88011', '88012', '88017', '88018', '88024', '88035', '88040', '88041', '88042', '88047') ); DISCONNECT FROM Hadoop; QUIT; ```
2018/07/09
[ "https://Stackoverflow.com/questions/51249250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7257430/" ]
Try command ``` ionic cordova build android --prod --release ```
Any one still having this issue, a big cause of this problem is PLUGINS run `ionic cordova plugin` And have a look at your list of plugins, and uninstall All the dodgy ones, and those you arent SURE are working by running `ionic cordova plugin rm your-plugin-name` This is the problem 98% of the time.
165,197
I was once asked the following question by a student I was tutoring; and I was stumped by it: When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground? * One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case. * One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere. * It's because of the nature of the force. It's independent of the motion of the stone. I prefer the last explanation - but is it true? And is this the best explanation?
2015/02/15
[ "https://physics.stackexchange.com/questions/165197", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/7993/" ]
> > When one throws a stone.... > > > Your arm is capable of propelling an object at up to around 150km/h (and that's with some practice). At that speed the many factors like air resistance are negligible. Let’s load a 16-inch shell into a gun (you will find several on the USS Iowa), aim it 45 degrees up and press the button. The shell is going to go up at an initial rate of Mach 1.7 (vertical vector), decreasing to zero at apogee, and it will come down accelerating at *g* until it reaches its terminal velocity. Things tend not to fall at supersonic speeds so it should be clear that the up time will not equal the down time.
**Assuming that the only forces acting on the stone are the initial force exerted by the hand on the stone AND the force of gravity**, we have the following situation: Immediately after throwing, the stone has a kinetic energy in the x-direction that never changes (**conservation of energy**) and the stone has a kinetic energy in the y-direction that is constantly being depleted by gravity as it rises to its apex. Once the stone is at its apex (vertical kinetic energy = 0), gravity **works** to restore all of the stone's original vertical kinetic energy as it falls back to its original height. So, the x-direction **kinetic energy** remained constant throughout the flight and the y-direction **total energy (kinetic + potential)** remained constant throughout the flight, independent of each other. This combination causes the symmetry of the situation. If air resistance and terminal velocity are introduced into the problem, the character of the problem is completely changed. Even a very simple situation as the one you described can become very complex and confusing to most people. Most people would be stymied by the complexity of the math involved even in this simple situation, let alone the complexity of putting a probe into orbit about Earth.
165,197
I was once asked the following question by a student I was tutoring; and I was stumped by it: When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground? * One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case. * One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere. * It's because of the nature of the force. It's independent of the motion of the stone. I prefer the last explanation - but is it true? And is this the best explanation?
2015/02/15
[ "https://physics.stackexchange.com/questions/165197", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/7993/" ]
I would consider that since acceleration is a constant vector pointing downward, that the time the projectiles downward component takes to accelerate from V(initial) to 0 would be the same as the time it takes to accelerate the object from 0 to V(final)
Asking "Why" in physics often leads out of physics and into philosophy. Why is there light? Because God said so. Physics only answers questions about how the universe behaves and how to describe that behavior. If a why question can be answered with physics, the answer is "because it follows from a law of physics." A law is just a mathematical description of behavior that has been verified with experiments. In this case, the answer follows from $F = ma$. If $a$ is constant, this leads to $x = 1/2at^2 + v\_0t + x\_0$. Since you are a physics tutor, you can set up the initial and final conditions and solve for t. This may well lead to more questions. Why is $F = ma$? Why is there gravity? You could fall back on philosophy, or you could say "I don't know. But experiments show that it works this way." Why questions are usually about things that are unfamiliar. A young child will ask "Why is there gravity?" A high school student is more likely to ask "Why is $F = ma$?" He may not know the answer to the first question, but he has become used to it. So the way to answer $F = ma$ questions is to show how it applies to familiar situations. This is why high school physics is full of pictures of springs and ropes and pulleys.
165,197
I was once asked the following question by a student I was tutoring; and I was stumped by it: When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground? * One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case. * One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere. * It's because of the nature of the force. It's independent of the motion of the stone. I prefer the last explanation - but is it true? And is this the best explanation?
2015/02/15
[ "https://physics.stackexchange.com/questions/165197", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/7993/" ]
I think its because both halves of a projectile's trajectory are symmetric in every aspect. The projectile going from its apex position to the ground is just the time reversed version of the projectile going from its initial position to the apex position.
A lot of things have to hold to get that symmetry. You have to neglect air resistance. You either have to throw it straight up, or the ground over there has to be at the the same altitude as the ground over here. You have to through it slowly enough that it comes back down (watch out for escape velocity) But if you have that, then the simplest explanation in the simplest case is that the acceleration is constant. So you keep going up until you have zero (vertical) velocity, which takes time $v\_0/g$, during which you travel up a certain distance. On the way down, the acceleration is still constant, so now the velocity becomes more down over time, but that just makes it the time reverse (when looking at the vertical component alone) so it takes an equal amount of time. If you want to throw it high enough that the acceleration starts to vary, an energy argument is quicker, though you can study the kinematics on the way back down as the time reverse (gaining just as much as you lost before, in just as much time, going just as far, etc.).
165,197
I was once asked the following question by a student I was tutoring; and I was stumped by it: When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground? * One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case. * One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere. * It's because of the nature of the force. It's independent of the motion of the stone. I prefer the last explanation - but is it true? And is this the best explanation?
2015/02/15
[ "https://physics.stackexchange.com/questions/165197", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/7993/" ]
> > One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case. > > > This is not hypothetical once you take air resistance into account. > > One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent. > > > Assuming constant horizontal velocity, the height vs time diagram will essentially look the same as the height vs horizontal distance diagram. Under that assumption, it is valid to argue about time-of-flight from the symmetry of the trajectory; in general, it's not. > > It's because of the nature of the force. It's independent of the motion of the stone. > > > The motion of the stone depends on the force, so it's hardly independent. Under constant vertical acceleration, the change in vertical velocity is linear in time. This means that it takes the same amount of time to go from initial velocity $+v$ to 0 as it takes going from 0 to $-v$. In fact, the velocity profiles will be mirror images, and the same distance will have been covered.
Asking "Why" in physics often leads out of physics and into philosophy. Why is there light? Because God said so. Physics only answers questions about how the universe behaves and how to describe that behavior. If a why question can be answered with physics, the answer is "because it follows from a law of physics." A law is just a mathematical description of behavior that has been verified with experiments. In this case, the answer follows from $F = ma$. If $a$ is constant, this leads to $x = 1/2at^2 + v\_0t + x\_0$. Since you are a physics tutor, you can set up the initial and final conditions and solve for t. This may well lead to more questions. Why is $F = ma$? Why is there gravity? You could fall back on philosophy, or you could say "I don't know. But experiments show that it works this way." Why questions are usually about things that are unfamiliar. A young child will ask "Why is there gravity?" A high school student is more likely to ask "Why is $F = ma$?" He may not know the answer to the first question, but he has become used to it. So the way to answer $F = ma$ questions is to show how it applies to familiar situations. This is why high school physics is full of pictures of springs and ropes and pulleys.
165,197
I was once asked the following question by a student I was tutoring; and I was stumped by it: When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground? * One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case. * One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere. * It's because of the nature of the force. It's independent of the motion of the stone. I prefer the last explanation - but is it true? And is this the best explanation?
2015/02/15
[ "https://physics.stackexchange.com/questions/165197", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/7993/" ]
I would say that it is a result of time reversal symmetry. If you consider the projectile at the apex of its trajectory then all that changes under time reversal is the direction of the horizontal component of motion. This means that the trajectory of the particle to get to that point and its trajectory after that point should be identical apart from a mirror inversion.
Conservation of momentum! ========================= ### Force × Time = Impulse = Δ Momentum Since the average force is the same going up and down, and since the momentum change is the same going up and down as well, the time during which the force is applied must also be the same.
165,197
I was once asked the following question by a student I was tutoring; and I was stumped by it: When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground? * One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case. * One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere. * It's because of the nature of the force. It's independent of the motion of the stone. I prefer the last explanation - but is it true? And is this the best explanation?
2015/02/15
[ "https://physics.stackexchange.com/questions/165197", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/7993/" ]
(Non-kinematics math attempt but just some principles) It is a partial observation in that * It hits the ground with same speed. * Angle by which it hits the ground is the same (maybe a direction change) * It takes equal time to reach to the peak and then hit the ground They are equally strange coincidences. Which are more fundamental? Consider the following setup: There are two smooth surfaces of a mountain with different angles. You kick a ball from the ground along a surface towards the hill top so that it just reaches the peak. Now if it rolls back from the same surface, all the above entities will be preserved (including the angle as the ball rolls down on the same surface). But if the ball just goes over the peak (with almost zero speed) and rolls down via the other surface, it will reach the ground at in shorter or longer time and with a different angle. But the speed will be the same (conservation of energy!). So, once an entity is conserved, there we can find a symmetry. The opposite is also true. If there are symmetries, then some thing must be preserved. I heard this is proved mathematically long ago. In your setup you have all the symmetries and it is no wonder you have conserved entities in the process.
**Assuming that the only forces acting on the stone are the initial force exerted by the hand on the stone AND the force of gravity**, we have the following situation: Immediately after throwing, the stone has a kinetic energy in the x-direction that never changes (**conservation of energy**) and the stone has a kinetic energy in the y-direction that is constantly being depleted by gravity as it rises to its apex. Once the stone is at its apex (vertical kinetic energy = 0), gravity **works** to restore all of the stone's original vertical kinetic energy as it falls back to its original height. So, the x-direction **kinetic energy** remained constant throughout the flight and the y-direction **total energy (kinetic + potential)** remained constant throughout the flight, independent of each other. This combination causes the symmetry of the situation. If air resistance and terminal velocity are introduced into the problem, the character of the problem is completely changed. Even a very simple situation as the one you described can become very complex and confusing to most people. Most people would be stymied by the complexity of the math involved even in this simple situation, let alone the complexity of putting a probe into orbit about Earth.
165,197
I was once asked the following question by a student I was tutoring; and I was stumped by it: When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground? * One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case. * One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere. * It's because of the nature of the force. It's independent of the motion of the stone. I prefer the last explanation - but is it true? And is this the best explanation?
2015/02/15
[ "https://physics.stackexchange.com/questions/165197", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/7993/" ]
I would consider that since acceleration is a constant vector pointing downward, that the time the projectiles downward component takes to accelerate from V(initial) to 0 would be the same as the time it takes to accelerate the object from 0 to V(final)
**Assuming that the only forces acting on the stone are the initial force exerted by the hand on the stone AND the force of gravity**, we have the following situation: Immediately after throwing, the stone has a kinetic energy in the x-direction that never changes (**conservation of energy**) and the stone has a kinetic energy in the y-direction that is constantly being depleted by gravity as it rises to its apex. Once the stone is at its apex (vertical kinetic energy = 0), gravity **works** to restore all of the stone's original vertical kinetic energy as it falls back to its original height. So, the x-direction **kinetic energy** remained constant throughout the flight and the y-direction **total energy (kinetic + potential)** remained constant throughout the flight, independent of each other. This combination causes the symmetry of the situation. If air resistance and terminal velocity are introduced into the problem, the character of the problem is completely changed. Even a very simple situation as the one you described can become very complex and confusing to most people. Most people would be stymied by the complexity of the math involved even in this simple situation, let alone the complexity of putting a probe into orbit about Earth.
165,197
I was once asked the following question by a student I was tutoring; and I was stumped by it: When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground? * One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case. * One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere. * It's because of the nature of the force. It's independent of the motion of the stone. I prefer the last explanation - but is it true? And is this the best explanation?
2015/02/15
[ "https://physics.stackexchange.com/questions/165197", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/7993/" ]
I think its because both halves of a projectile's trajectory are symmetric in every aspect. The projectile going from its apex position to the ground is just the time reversed version of the projectile going from its initial position to the apex position.
Conservation of momentum! ========================= ### Force × Time = Impulse = Δ Momentum Since the average force is the same going up and down, and since the momentum change is the same going up and down as well, the time during which the force is applied must also be the same.
165,197
I was once asked the following question by a student I was tutoring; and I was stumped by it: When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground? * One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case. * One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere. * It's because of the nature of the force. It's independent of the motion of the stone. I prefer the last explanation - but is it true? And is this the best explanation?
2015/02/15
[ "https://physics.stackexchange.com/questions/165197", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/7993/" ]
Asking "Why" in physics often leads out of physics and into philosophy. Why is there light? Because God said so. Physics only answers questions about how the universe behaves and how to describe that behavior. If a why question can be answered with physics, the answer is "because it follows from a law of physics." A law is just a mathematical description of behavior that has been verified with experiments. In this case, the answer follows from $F = ma$. If $a$ is constant, this leads to $x = 1/2at^2 + v\_0t + x\_0$. Since you are a physics tutor, you can set up the initial and final conditions and solve for t. This may well lead to more questions. Why is $F = ma$? Why is there gravity? You could fall back on philosophy, or you could say "I don't know. But experiments show that it works this way." Why questions are usually about things that are unfamiliar. A young child will ask "Why is there gravity?" A high school student is more likely to ask "Why is $F = ma$?" He may not know the answer to the first question, but he has become used to it. So the way to answer $F = ma$ questions is to show how it applies to familiar situations. This is why high school physics is full of pictures of springs and ropes and pulleys.
**Assuming that the only forces acting on the stone are the initial force exerted by the hand on the stone AND the force of gravity**, we have the following situation: Immediately after throwing, the stone has a kinetic energy in the x-direction that never changes (**conservation of energy**) and the stone has a kinetic energy in the y-direction that is constantly being depleted by gravity as it rises to its apex. Once the stone is at its apex (vertical kinetic energy = 0), gravity **works** to restore all of the stone's original vertical kinetic energy as it falls back to its original height. So, the x-direction **kinetic energy** remained constant throughout the flight and the y-direction **total energy (kinetic + potential)** remained constant throughout the flight, independent of each other. This combination causes the symmetry of the situation. If air resistance and terminal velocity are introduced into the problem, the character of the problem is completely changed. Even a very simple situation as the one you described can become very complex and confusing to most people. Most people would be stymied by the complexity of the math involved even in this simple situation, let alone the complexity of putting a probe into orbit about Earth.
165,197
I was once asked the following question by a student I was tutoring; and I was stumped by it: When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground? * One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case. * One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere. * It's because of the nature of the force. It's independent of the motion of the stone. I prefer the last explanation - but is it true? And is this the best explanation?
2015/02/15
[ "https://physics.stackexchange.com/questions/165197", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/7993/" ]
I think its because both halves of a projectile's trajectory are symmetric in every aspect. The projectile going from its apex position to the ground is just the time reversed version of the projectile going from its initial position to the apex position.
**Assuming that the only forces acting on the stone are the initial force exerted by the hand on the stone AND the force of gravity**, we have the following situation: Immediately after throwing, the stone has a kinetic energy in the x-direction that never changes (**conservation of energy**) and the stone has a kinetic energy in the y-direction that is constantly being depleted by gravity as it rises to its apex. Once the stone is at its apex (vertical kinetic energy = 0), gravity **works** to restore all of the stone's original vertical kinetic energy as it falls back to its original height. So, the x-direction **kinetic energy** remained constant throughout the flight and the y-direction **total energy (kinetic + potential)** remained constant throughout the flight, independent of each other. This combination causes the symmetry of the situation. If air resistance and terminal velocity are introduced into the problem, the character of the problem is completely changed. Even a very simple situation as the one you described can become very complex and confusing to most people. Most people would be stymied by the complexity of the math involved even in this simple situation, let alone the complexity of putting a probe into orbit about Earth.
22,594,048
How do I apply css styles to HTML tags within a class at once instead of repeating the class name each time. ``` .container h1,.container p,.container a,.container ol,.container ul,.container li, .container fieldset,.container form,.container label,.container legend, .container table { some css rules here } ``` how do I reduce repetition of the class name?
2014/03/23
[ "https://Stackoverflow.com/questions/22594048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1106398/" ]
Use [LESS](http://lesscss.org/). It would come out looking like this. ``` .container { h1, p, a, ol, ul, li, fieldset, form, label, legend, table { your styles here } } ``` Otherwise, you're SOL. Sorry.
You cannot reduce the current selector of yours as far as pure CSS goes. You might want to take a look at [LESS](http://lesscss.org/) or [SASS](http://sass-lang.com/) for doing that. Also, I just read your selector, seems like *you are covering almost every tag*, so if you are looking to target few properties to each tag, the best you can do with CSS is to use a `*` selector *(Universal selector)* which will match any type of element nested under an element having a `class` of `.container` ``` .container * { /* Styles goes here */ } ``` Apart from the above, some properties are inherited by few child elements from their parent such as `font-size`, `color`, `font-family` etc. So you don't need to write those for each, because I saw you using `.container ul, .container li` which didn't make much sense to me.
31,234,459
I am trying to get the latitude and longitude values from a JSON array - `$response`, returned from Google, from their Geocoding services. The JSON array is returned as such (random address): ``` { "results":[ { "address_components":[ { "long_name":"57", "short_name":"57", "types":[ "street_number" ] }, { "long_name":"Polo Gardens", "short_name":"Polo Gardens", "types":[ "route" ] }, { "long_name":"Bucksburn", "short_name":"Bucksburn", "types":[ "sublocality_level_1", "sublocality", "political" ] }, { "long_name":"Aberdeen", "short_name":"Aberdeen", "types":[ "locality", "political" ] }, { "long_name":"Aberdeen", "short_name":"Aberdeen", "types":[ "postal_town" ] }, { "long_name":"Aberdeen City", "short_name":"Aberdeen City", "types":[ "administrative_area_level_2", "political" ] }, { "long_name":"United Kingdom", "short_name":"GB", "types":[ "country", "political" ] }, { "long_name":"AB21 9JU", "short_name":"AB21 9JU", "types":[ "postal_code" ] } ], "formatted_address":"57 Polo Gardens, Aberdeen, Aberdeen City AB21 9JU, UK", "geometry":{ "location":{ "lat":57.1912463, "lng":-2.1790257 }, "location_type":"ROOFTOP", "viewport":{ "northeast":{ "lat":57.19259528029149, "lng":-2.177676719708498 }, "southwest":{ "lat":57.18989731970849, "lng":-2.180374680291502 } } }, "partial_match":true, "place_id":"ChIJLTex1jQShEgR5UJ2DNc6N9s", "types":[ "street_address" ] } ], "status":"OK" } ``` I have tried the following: ``` json_decode($response->results->geometry->location->lat) ``` But it returns 'trying to access the property of a non-object'. Any help would be hugely appreciated.
2015/07/05
[ "https://Stackoverflow.com/questions/31234459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` var_dump(json_decode($response)->results[0]->geometry->location->lat); ```
Try this: `$jsonArray = json_decode($response,true);` It's just, first you got to convert whole json string into array or object with `json_decode` function, then work with structure.
31,234,459
I am trying to get the latitude and longitude values from a JSON array - `$response`, returned from Google, from their Geocoding services. The JSON array is returned as such (random address): ``` { "results":[ { "address_components":[ { "long_name":"57", "short_name":"57", "types":[ "street_number" ] }, { "long_name":"Polo Gardens", "short_name":"Polo Gardens", "types":[ "route" ] }, { "long_name":"Bucksburn", "short_name":"Bucksburn", "types":[ "sublocality_level_1", "sublocality", "political" ] }, { "long_name":"Aberdeen", "short_name":"Aberdeen", "types":[ "locality", "political" ] }, { "long_name":"Aberdeen", "short_name":"Aberdeen", "types":[ "postal_town" ] }, { "long_name":"Aberdeen City", "short_name":"Aberdeen City", "types":[ "administrative_area_level_2", "political" ] }, { "long_name":"United Kingdom", "short_name":"GB", "types":[ "country", "political" ] }, { "long_name":"AB21 9JU", "short_name":"AB21 9JU", "types":[ "postal_code" ] } ], "formatted_address":"57 Polo Gardens, Aberdeen, Aberdeen City AB21 9JU, UK", "geometry":{ "location":{ "lat":57.1912463, "lng":-2.1790257 }, "location_type":"ROOFTOP", "viewport":{ "northeast":{ "lat":57.19259528029149, "lng":-2.177676719708498 }, "southwest":{ "lat":57.18989731970849, "lng":-2.180374680291502 } } }, "partial_match":true, "place_id":"ChIJLTex1jQShEgR5UJ2DNc6N9s", "types":[ "street_address" ] } ], "status":"OK" } ``` I have tried the following: ``` json_decode($response->results->geometry->location->lat) ``` But it returns 'trying to access the property of a non-object'. Any help would be hugely appreciated.
2015/07/05
[ "https://Stackoverflow.com/questions/31234459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Either pass true as the second parameter to json\_decode function and use the array notation: ``` $obj = json_decode($json_string2, true); foreach ($obj['geometry'] as $key => $value) { $lat = $value['location']['lat']; $long = $value['location']['lng']; } ```
Try this: `$jsonArray = json_decode($response,true);` It's just, first you got to convert whole json string into array or object with `json_decode` function, then work with structure.
31,234,459
I am trying to get the latitude and longitude values from a JSON array - `$response`, returned from Google, from their Geocoding services. The JSON array is returned as such (random address): ``` { "results":[ { "address_components":[ { "long_name":"57", "short_name":"57", "types":[ "street_number" ] }, { "long_name":"Polo Gardens", "short_name":"Polo Gardens", "types":[ "route" ] }, { "long_name":"Bucksburn", "short_name":"Bucksburn", "types":[ "sublocality_level_1", "sublocality", "political" ] }, { "long_name":"Aberdeen", "short_name":"Aberdeen", "types":[ "locality", "political" ] }, { "long_name":"Aberdeen", "short_name":"Aberdeen", "types":[ "postal_town" ] }, { "long_name":"Aberdeen City", "short_name":"Aberdeen City", "types":[ "administrative_area_level_2", "political" ] }, { "long_name":"United Kingdom", "short_name":"GB", "types":[ "country", "political" ] }, { "long_name":"AB21 9JU", "short_name":"AB21 9JU", "types":[ "postal_code" ] } ], "formatted_address":"57 Polo Gardens, Aberdeen, Aberdeen City AB21 9JU, UK", "geometry":{ "location":{ "lat":57.1912463, "lng":-2.1790257 }, "location_type":"ROOFTOP", "viewport":{ "northeast":{ "lat":57.19259528029149, "lng":-2.177676719708498 }, "southwest":{ "lat":57.18989731970849, "lng":-2.180374680291502 } } }, "partial_match":true, "place_id":"ChIJLTex1jQShEgR5UJ2DNc6N9s", "types":[ "street_address" ] } ], "status":"OK" } ``` I have tried the following: ``` json_decode($response->results->geometry->location->lat) ``` But it returns 'trying to access the property of a non-object'. Any help would be hugely appreciated.
2015/07/05
[ "https://Stackoverflow.com/questions/31234459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` var_dump(json_decode($response)->results[0]->geometry->location->lat); ```
Either pass true as the second parameter to json\_decode function and use the array notation: ``` $obj = json_decode($json_string2, true); foreach ($obj['geometry'] as $key => $value) { $lat = $value['location']['lat']; $long = $value['location']['lng']; } ```
19,125
How can I implement a hook in my template file that will change the label of a field for the "group" content type from "author" to "created by"? ![screenshot of author field](https://i.stack.imgur.com/jDhMv.png)
2012/01/08
[ "https://drupal.stackexchange.com/questions/19125", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/3846/" ]
To rename the label of a field add the preprocess function [template\_preprocess\_node](http://api.drupal.org/api/drupal/modules--node--node.module/function/template_preprocess_node/7) to your *template.php* file: ``` function *YOUR THEME*_preprocess_node(&$vars){ //Supposing that your content type name is "group" if($vars['type'] == 'group'){ //Supposing that your field name is "field_txt_group" $vars['content']['field_txt_author']['#title'] = 'created by'; } } ```
I'll take a guess that there are a few different ways you can do this. 1. Use jQuery to target the element and use text replacement. You could so something like: ``` $("#my-element").each(function () { var s=$(this).text(); //get text $(this).text(s.replace('Author', 'created by')); //set the text to the replaced version }); ``` Of course you will need to add on Drupal specific jQuery code depending on what version of Drupal you are using (6 or 7). See: [JavaScript in Drupal 5 and Drupal 6](http://drupal.org/node/121997) and [Managing JavaScript in Drupal 7](http://drupal.org/node/756722). 1. Try the [String Overrides](http://drupal.org/project/stringoverrides) module 2. Write a template pre-process function (template.php in your theme folder) to replace that text.
19,125
How can I implement a hook in my template file that will change the label of a field for the "group" content type from "author" to "created by"? ![screenshot of author field](https://i.stack.imgur.com/jDhMv.png)
2012/01/08
[ "https://drupal.stackexchange.com/questions/19125", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/3846/" ]
To rename the label of a field add the preprocess function [template\_preprocess\_node](http://api.drupal.org/api/drupal/modules--node--node.module/function/template_preprocess_node/7) to your *template.php* file: ``` function *YOUR THEME*_preprocess_node(&$vars){ //Supposing that your content type name is "group" if($vars['type'] == 'group'){ //Supposing that your field name is "field_txt_group" $vars['content']['field_txt_author']['#title'] = 'created by'; } } ```
You can also change the label from a field preprocess ``` function THEMENAME_preprocess_field(&$variables, $hook) { $field_name = $variables['element']['#field_name']; $view_mode = $variables['element']['#view_mode']; switch ($field_name) { case 'YOUR_FIELD_NAME': $variables['label'] = t('FIELD LABEL EVERYWHERE'); // Possible to restrict by view mode if ($view_mode == 'teaser') { $variables['label'] = t('TEASER LABEL HERE'); } break; // Duplicate for other fields case 'OTHER_FIELD_MACHINE_NAMES': // ...code break; } } ```
52,679,318
I have a class Application with EmbeddedId and second column in embbbedID is forgein key and having many to one relationship with offer. ``` @Entity public class Application implements Serializable{ private Integer id; @EmbeddedId private MyKey mykey; private String resume; @Enumerated(EnumType.STRING) @NotNull private ApplicationStatus applicationStatus; @Embeddable public class MyKey implements Serializable{ private static final long serialVersionUID = 1L; @NotNull private String emailId; @ManyToOne(fetch = FetchType.LAZY) @NotNull private Offer offer; ``` in Offer class mapping is done on jobTitle. ``` @Repository interface ApplicationRepository extends JpaRepository <Application,MyKey> ``` { ``` List<Application> findAllByMyKey_Offer(String jobTitle); } ``` Trying this but getting no success... I want to fetch All application regarding a specific jobTitle. What shud be my method name in ApplicationRepository class.
2018/10/06
[ "https://Stackoverflow.com/questions/52679318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9498745/" ]
Your methode name is wrong, the right one is `findAllByMykey_Offer` or `findAllByMykeyOffer`, as your field is named mykey. As mentionned in the documentation <https://docs.spring.io/spring-data/jpa/docs/2.1.0.RELEASE/reference/html/> using `List<Application> findAllByMykey_Offer(String jobTitle);` is better than `List<Application> findAllByMykeyOffer(String jobTitle);`
With composite key, your field name should include name of the field of embedded id. In you case it would be like this (I haven't tested it) ``` List<Application> findAllByMykeyOffer(String jobTitle); ``` Notice that `k` is lower-case here, because your field in class `Application` is named `mykey`, not `myKey`
13,009,911
I want to create a list with my database field values. There are 2 columns, name and surname. I want to create a list that stores all names in name column in a field and then add to my DTO. Is this possible?
2012/10/22
[ "https://Stackoverflow.com/questions/13009911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1759247/" ]
**Steps you can follow**: - * First you need to have a `List<String>` that will store all your names. Declare it like this: - ``` List<String> nameList = new ArrayList<String>(); ``` * Now, you have all the records fetched and stored in `ResultSet`. So I assume that you can iterate over `ResultSet` and get each `values` from it. You need to use `ResultSet#getString` to fetch the `name`. * Now, each time you fetch one record, get the `name` field and add it to your list. ``` while(resultSet.next()) { nameList.add(resultSet.getString("name")); } ``` * Now, since you haven't given enough information about your `DTO`, so that part you need to find out, how to add this `ArrayList` to your `DTO`. * The above `list` only contains `name` and not `surname` as you wanted only `name`. But if you want both, you need to create a custom DTO `(FullName)`, that contains `name` and `surname` as fields. And instantiate it from every `ResultSet` and add it to the `List<FullName>`
It is. What have you tried ? To access the database, you need to [use JDBC](http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) and execute a query, giving you a `ResultSet`. I would create an class called `FullName` with 2 String fields `name` and `surname`. Just populate these in a loop using ``` rs.getString("NAME"); // column name rs.getString("SURNAME"); ``` e.g. ``` List<FullName> fullnames = new ArrayList<FullName>(); while (rs.next()) { fullnames.add(new FullName(rs)); } ``` Note that I'm populating the object via the `ResultSet` object directly. You may choose instead to implement a constructor taking the 2 name fields. Note also that I'm creating a `Fullname` object. So the firstname/surname are kept separate and you have the freedom to add initials etc. later. You may prefer to rename this `Person` and that will give you the freedom to add additional attributes going forwards.
13,009,911
I want to create a list with my database field values. There are 2 columns, name and surname. I want to create a list that stores all names in name column in a field and then add to my DTO. Is this possible?
2012/10/22
[ "https://Stackoverflow.com/questions/13009911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1759247/" ]
It is. What have you tried ? To access the database, you need to [use JDBC](http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) and execute a query, giving you a `ResultSet`. I would create an class called `FullName` with 2 String fields `name` and `surname`. Just populate these in a loop using ``` rs.getString("NAME"); // column name rs.getString("SURNAME"); ``` e.g. ``` List<FullName> fullnames = new ArrayList<FullName>(); while (rs.next()) { fullnames.add(new FullName(rs)); } ``` Note that I'm populating the object via the `ResultSet` object directly. You may choose instead to implement a constructor taking the 2 name fields. Note also that I'm creating a `Fullname` object. So the firstname/surname are kept separate and you have the freedom to add initials etc. later. You may prefer to rename this `Person` and that will give you the freedom to add additional attributes going forwards.
What worked for me is: ``` ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); ArrayList<String> resultList= new ArrayList<>(columnCount); while (rs.next()) { int i = 1; while(i <= columnCount) { resultList.add(rs.getString(i++)); } } return resultList; ```
13,009,911
I want to create a list with my database field values. There are 2 columns, name and surname. I want to create a list that stores all names in name column in a field and then add to my DTO. Is this possible?
2012/10/22
[ "https://Stackoverflow.com/questions/13009911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1759247/" ]
**Steps you can follow**: - * First you need to have a `List<String>` that will store all your names. Declare it like this: - ``` List<String> nameList = new ArrayList<String>(); ``` * Now, you have all the records fetched and stored in `ResultSet`. So I assume that you can iterate over `ResultSet` and get each `values` from it. You need to use `ResultSet#getString` to fetch the `name`. * Now, each time you fetch one record, get the `name` field and add it to your list. ``` while(resultSet.next()) { nameList.add(resultSet.getString("name")); } ``` * Now, since you haven't given enough information about your `DTO`, so that part you need to find out, how to add this `ArrayList` to your `DTO`. * The above `list` only contains `name` and not `surname` as you wanted only `name`. But if you want both, you need to create a custom DTO `(FullName)`, that contains `name` and `surname` as fields. And instantiate it from every `ResultSet` and add it to the `List<FullName>`
JDBC unfortunately doesn't offer any ways to conveniently do this in a one-liner. But there are other APIs, such as [jOOQ](http://www.jooq.org) (disclaimer: I work for the company behind jOOQ): ``` List<DTO> list = DSL.using(connection) .fetch("SELECT first_name, last_name FROM table") .into(DTO.class); ``` Or [Spring JDBC](http://projects.spring.io/spring-data/) ``` List<DTO> list = new JdbcTemplate(new SingleConnectionDataSource(connection, true)) .query("SELECT first_name, last_name FROM table", (rs, rowNum) -> new DTO(rs.getString(1), rs.getString(2)); ``` Or [Apache DbUtils](http://commons.apache.org/proper/commons-dbutils/): ``` List<DTO> list = new QueryRunner() .query(connection, "SELECT first_name, last_name FROM table", new ArrayListHandler()) .stream() .map(array -> new DTO((String) array[0], (String) array[1])) .collect(Collectors.toList()); ``` I've used Java 8 for the Spring JDBC / Apache DbUtils examples, but it can be done with older versions of Java as well.
13,009,911
I want to create a list with my database field values. There are 2 columns, name and surname. I want to create a list that stores all names in name column in a field and then add to my DTO. Is this possible?
2012/10/22
[ "https://Stackoverflow.com/questions/13009911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1759247/" ]
**Steps you can follow**: - * First you need to have a `List<String>` that will store all your names. Declare it like this: - ``` List<String> nameList = new ArrayList<String>(); ``` * Now, you have all the records fetched and stored in `ResultSet`. So I assume that you can iterate over `ResultSet` and get each `values` from it. You need to use `ResultSet#getString` to fetch the `name`. * Now, each time you fetch one record, get the `name` field and add it to your list. ``` while(resultSet.next()) { nameList.add(resultSet.getString("name")); } ``` * Now, since you haven't given enough information about your `DTO`, so that part you need to find out, how to add this `ArrayList` to your `DTO`. * The above `list` only contains `name` and not `surname` as you wanted only `name`. But if you want both, you need to create a custom DTO `(FullName)`, that contains `name` and `surname` as fields. And instantiate it from every `ResultSet` and add it to the `List<FullName>`
What worked for me is: ``` ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); ArrayList<String> resultList= new ArrayList<>(columnCount); while (rs.next()) { int i = 1; while(i <= columnCount) { resultList.add(rs.getString(i++)); } } return resultList; ```
13,009,911
I want to create a list with my database field values. There are 2 columns, name and surname. I want to create a list that stores all names in name column in a field and then add to my DTO. Is this possible?
2012/10/22
[ "https://Stackoverflow.com/questions/13009911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1759247/" ]
JDBC unfortunately doesn't offer any ways to conveniently do this in a one-liner. But there are other APIs, such as [jOOQ](http://www.jooq.org) (disclaimer: I work for the company behind jOOQ): ``` List<DTO> list = DSL.using(connection) .fetch("SELECT first_name, last_name FROM table") .into(DTO.class); ``` Or [Spring JDBC](http://projects.spring.io/spring-data/) ``` List<DTO> list = new JdbcTemplate(new SingleConnectionDataSource(connection, true)) .query("SELECT first_name, last_name FROM table", (rs, rowNum) -> new DTO(rs.getString(1), rs.getString(2)); ``` Or [Apache DbUtils](http://commons.apache.org/proper/commons-dbutils/): ``` List<DTO> list = new QueryRunner() .query(connection, "SELECT first_name, last_name FROM table", new ArrayListHandler()) .stream() .map(array -> new DTO((String) array[0], (String) array[1])) .collect(Collectors.toList()); ``` I've used Java 8 for the Spring JDBC / Apache DbUtils examples, but it can be done with older versions of Java as well.
What worked for me is: ``` ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); ArrayList<String> resultList= new ArrayList<>(columnCount); while (rs.next()) { int i = 1; while(i <= columnCount) { resultList.add(rs.getString(i++)); } } return resultList; ```
31,674
Keccak/SHA-3 is new NIST standard for cryptographic hash functions. However, it is much slower than BLAKE2 in software implementations. Does Keccak have compensating advantages?
2016/01/04
[ "https://crypto.stackexchange.com/questions/31674", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/29901/" ]
(Disclosure: I'm one of the authors of BLAKE2, but not BLAKE.) Here are the [slides from a presentation](https://blake2.net/acns/slides.html) I gave at Applied Cryptography and Network Security 2013 about this. (Note: the performance numbers in those slides are obsolete — BLAKE2 is even faster now than it was then.) The slides include quotes from NIST's 3rd-round Report on the SHA-3 Competition which show some of the advantages and disadvantages of BLAKE (not BLAKE2) compared to Keccak, in NIST's opinion. Here's a [blog post](https://leastauthority.com/blog/BLAKE2-harder-better-faster-stronger-than-MD5/) I wrote to accompany the slides. The main reason that NIST gave was that BLAKE was more similar to SHA-2 than Keccak was. When the SHA-3 contest was designed, the whole point of it was to provide a new hash function that would be ready in case SHA-2 got broken, so it made sense to require the winner to be different from SHA-2. However now, with almost a decade more of research and SHA-2 looking no weaker, a hash function being similar to SHA-2 doesn't seem bad, and might even be good. There was another reason that NIST gave that I omitted from the slides, which was that Keccak is more efficient in ASIC implementation. That reason may be more important if you are a large organization, like the U.S. military or U.S. government, who is going have special hardware built for your project, but more flexible/general-purpose performance is more important to me. (See Adam Langley's [blog post](https://www.imperialviolet.org/2012/10/21/nist.html) on this topic.) Besides, *everything* is fast in hardware! See [this catalog of hardware implementations of secure hash functions](http://ehash.iaik.tugraz.at/wiki/SHA-3_Hardware_Implementations#High-Speed_Implementations_.28ASIC.29). ASIC implementations of BLAKE can process about 12.5 GB/s, compared to Keccak, which can process about 44 GB/s. An ASIC implementation of BLAKE2 would be probably about 40% faster than a similar implementation of BLAKE, i.e. around 17.5 GB/s. But even 12.5 GB/s seems more than sufficient for most uses of a secure hash function.
Blake-2 was not part of the SHA-3 competition, Blake, its predecessor was. Blake-2 is approx 1.3 to 1.7 times faster than Blake in software, with the advantage best for the 512-bit digests. ### Performance A [software performance](http://bench.cr.yp.to/results-sha3.html) comparison between the two SHA-3 finalists shows that Blake is about 3 times faster than Keccak on a modern CPU for a 512-bit hash, and only 1.26 times faster for a 256-bit hash. Performance listed in cycles per byte. ``` Algorithm 512-bit 256-bit --------------------------------------- Blake 5.18 cpb 6.79 cpb Keccak 15.99 cpb 8.56 cpb ``` [Hardware designs](http://scholar.lib.vt.edu/theses/available/etd-05172011-141328/unrestricted/Huang_S_T_2011.pdf) however show a substantial win for Keccak. Performance listed in gigabits per second on an ASIC with identical power draw, but different frequencies and transistor counts. ``` Algorithm 256-bit --------------------------- Blake 2.06 Gbps Keccak 10.28 Gbps ``` Here Keccak is 5 times faster at the same power budget. On FPGA platforms, Keccak offers a similar advantage of at least 4X the performance with only 10% more power budget, and the same circuit count or less than Blake. As part of the standardization process, implementing the Keccak core permutation in future commodity processors such as ARM, Intel, and AMD was discussed. This would use up to 25 128-bit registers to hold the state and all round constants, processing rounds individually, or 13 128-bit registers to hold just the state, and processing a group of rounds, with the round constants generated on the fly. There could also be a special 1600-bit register just for the Keccak state. This would give Keccak a similar performance advantage as AES was given with appropriate CPU instructions, and could make it faster than Blake-2, almost certainly so for a 256-bit hash, where the performance is already quite close. ### Security Keccak has a round count that is high enough to give it a massive security margin, and the sponge construction it uses gives very good security proofs, which have only been proven better with time. Blake also has a high security margin, which allowed Blake-2 to have a lower round count and still retain the expected security from a hash function of a given size. The construction used by Blake was also changed for Blake-2, in order to simplify padding and memory access in software platforms, but also locked it to byte processing only. Blake and Keccak can process bitstreams. The round constants in Keccak are probably its weakest point, due to the low hamming weights and structural similarity. Blake-2 has less constants than Blake as well. This may make some attacks have lower complexity, however the attack complexities were already higher than the expected security of the hash functions. There have been no attacks on either hash function that even come close to breaking them. The only practical attacks on Keccak work on reduced round variants with less than 10 rounds, and on Blake with less than 7 rounds. Blake-2b is a superior choice for password based key derivation functions, because of the low attacker advantage at a high budget, which is much greater with Keccak. ### Other As part of the standardization process, the flexible sponge construction of Keccak resulted in the SHAKE XOFs which can generate arbitrary length bitstreams for various applications. There was also talk of authenticated encryption based on the Keccak permutation, [Keyak](http://keyak.noekeon.org/) is a 2nd round [CAESAR](http://competitions.cr.yp.to/index.html) candidate based on the Keccak permutation used in SHA-3. Blake and derivatives are not nearly as flexible, NORX is as close Blake as anything, but they are still not really similar as a package, and the core functions are different.
39,788,564
I want for the click on the item menu, this item will change the icon. Selector for the item: button\_add\_to\_wishlist.xml ``` <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="false" android:drawable="@drawable/ic_add_fav" /> <item android:state_checked="true" android:drawable="@drawable/ic_add_fav_fill" /> ``` Menu ``` <item android:id="@+id/add_to_wishlist" android:title="@string/book_btn_text_add_to_wishlist" android:icon="@drawable/button_add_to_wishlist" android:checkable="true" app:showAsAction="always"/> ```
2016/09/30
[ "https://Stackoverflow.com/questions/39788564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6640003/" ]
There is no command to tell Amazon S3 to archive a specific object to Amazon Glacier. Instead, [Lifecycle Rules](https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html) are used to identify objects. The [Lifecycle Configuration Elements](https://docs.aws.amazon.com/AmazonS3/latest/dev/intro-lifecycle-rules.html) documentation shows each rule consisting of: * **Rule metadata** that include a rule ID, and status indicating whether the rule is enabled or disabled. If a rule is disabled, Amazon S3 will not perform any actions specified in the rule. * **Prefix** identifying objects by the key prefix to which the rule applies. * One or more **transition/expiration actions with a date or a time period** in the object's lifetime when you want Amazon S3 to perform the specified action. The only way to identify *which* objects are transitioned is via the **prefix** parameter. Therefore, you would need to specify a separate rule for each object. (The prefix can include the full object name.) However, there is a **limit of 1000 rules** per lifecycle configuration. Yes, you could move objects one-at-a-time to Amazon Glacier, but this would actually involve uploading archives to Glacier rather than 'moving' them from S3. Also, be careful -- there are **higher 'per request' charges for Glacier than S3** that might actually cost you more than the savings you'll gain in storage costs. In the meantime, consider using [Amazon S3 Standard - Infrequent Access storage class](https://aws.amazon.com/s3/storage-classes/), which can **save around 50% of S3 storage costs** for infrequently-accessed data.
You can programmatically archive a specific object on S3 to Glacier using [Lifecycle Rules](https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html) (with a prefix of the exact object you wish to archive). There is a [PUT lifecycle](http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlifecycle.html) API. This API replaces the *entire* lifecycle configuration, so if you have rules outside of this process you will need to add them to each lifecycle you upload. If you want to archive specific files, you can either: * For each file, create a lifecycle with one rule, wait until the file has transferred, then do the same for the next file * Create a lifecycle configuration with one rule per file The second will finish faster (as you do not need to wait between files), but requires that you know all the files you want to archive in advance. There is a limit of 1,000 rules per lifecycle configuration, so if you have an awful lot of files that you want to archive, you will need to split them into separate lifecycle configurations.
618,373
I'm unable to get the following table to have even row heights with vertical alignment ``` \renewcommand\tabularxcolumn[1]{m{#1}} ... \begin{table} \renewcommand*{\arraystretch}{1} \begin{tabularx}{\textwidth}{X X} \toprule \textbf{Route} & \textbf{Funzione} \\ \midrule \lstinline$/device/:id$ & Carica menu di navigazione e toolbar principale \\ \midrule \lstinline$/device/:id/dids$ & Mostra la lista dei DID document posseduti dal device \verb+id+ \\ \midrule \lstinline$/device/:id/keys$ & Mostra la lista delle chiavi pubbliche contenute nei DID document posseduti dal dispositivo \verb+id+ \\ \midrule \lstinline$/device/:id/credentials$ & Mostra la lista delle credenziali rilasciate al dispositivo \verb+id+ \\ \midrule \lstinline$/device/:id/credentials/:id/use$ & Consente di accedere al servizio di un Verifier utilizzando la credenziale \verb+id+ \\ \midrule \lstinline$/device/:id/credentials/:id/revoke$ & Consente di inviare una richiesta di revoca della credenziale \verb+id+ \\ \midrule \lstinline$/device/:id/issuers$ & Mostra la lista degli Issuer di cui il dispositivo \verb+id+ si fida \\ \midrule \lstinline$/device/:id/verifiers$ & Mostra la lista di Verifier conosciuti dal dispositivo \verb+id+ \\ \midrule \lstinline$/device/:id/status-lists$ & Mostra la lista delle status list \\ \midrule \lstinline$/device/:id/settings$ & Espone metodi d'utilità \\ \end{tabularx} \caption{Lista delle route con relative funzionalità.} \end{table} ``` By increasing the number in `\arraystretch` the result will always be to have uneven row heights. Is there a way to have all the row heights to be set with the height of the higher one? [![enter image description here](https://i.stack.imgur.com/oDIWr.png)](https://i.stack.imgur.com/oDIWr.png)
2021/10/09
[ "https://tex.stackexchange.com/questions/618373", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/166526/" ]
By use of the `tabularray` package this is relative simple to accomplish: ``` \documentclass{article} \usepackage[skip=1ex]{caption} \usepackage{tabularray} \begin{document} \begin{table} \begin{tblr}{hline{1,Z}=1pt, hline{2}=0.8pt, hline{3-Y}=solid, colspec = {@{} Q[m, font=\ttfamily] X[m,j] @{}}, row{1} = {font=\bfseries}, row{2-Z} = {ht=3\baselineskip} } Route & Funzione \\ /device/:id & Carica menu di navigazione e toolbar principale \\ /device/:id/dids & Mostra la lista dei DID document posseduti dal device \texttt{id} \\ /device/:id/keys & Mostra la lista delle chiavi pubbliche contenute nei DID document posseduti dal dispositivo \texttt{id} \\ /device/:id/credentials & Mostra la lista delle credenziali rilasciate al dispositivo \texttt{id} \\ /device/:id/credentials/:id/use & Consente di accedere al servizio di un Verifier utilizzando la credenziale \texttt{id} \\ /device/:id/credentials/:id/revoke & Consente di inviare una richiesta di revoca della credenziale \texttt{id} \\ /device/:id/issuers & Mostra la lista degli Issuer di cui il dispositivo \texttt{id} si fida \\ /device/:id/verifiers & Mostra la lista di Verifier conosciuti dal dispositivo \texttt{id} \\ /device/:id/status-lists & Mostra la lista delle status list \\ /device/:id/settings & Espone metodi d'utilità \\ \end{tblr} \caption{Lista delle route con relative funzionalità.} \end{table} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/n221i.png)](https://i.stack.imgur.com/n221i.png)
Here is a solution with classical packages. ``` \documentclass{article} \usepackage[skip=1ex]{caption} \usepackage{booktabs,tabularx} \begin{document} \begin{table} \renewcommand{\tabularxcolumn}[1]{m{#1}} \begin{tabularx}{\textwidth}{@{}>{\rule[-16pt]{0pt}{40pt}\ttfamily}lX@{}} \toprule \multicolumn{1}{@{}l}{\bfseries Route} & \bfseries Funzione \\ \hline /device/:id & Carica menu di navigazione e toolbar principale \\ \hline /device/:id/dids & Mostra la lista dei DID document posseduti dal device \texttt{id} \\ \hline /device/:id/keys & Mostra la lista delle chiavi pubbliche contenute nei DID document posseduti dal dispositivo \texttt{id} \\ \hline /device/:id/credentials & Mostra la lista delle credenziali rilasciate al dispositivo \texttt{id} \\ \hline /device/:id/credentials/:id/use & Consente di accedere al servizio di un Verifier utilizzando la credenziale \texttt{id} \\ \hline /device/:id/credentials/:id/revoke & Consente di inviare una richiesta di revoca della credenziale \texttt{id} \\ \hline /device/:id/issuers & Mostra la lista degli Issuer di cui il dispositivo \texttt{id} si fida \\ \hline /device/:id/verifiers & Mostra la lista di Verifier conosciuti dal dispositivo \texttt{id} \\ \hline /device/:id/status-lists& Mostra la lista delle status list \\ \hline /device/:id/settings & Espone metodi d'utilità \\ \bottomrule \end{tabularx} \caption{Lista delle route con relative funzionalità.} \end{table} \end{document} ``` [![Output of the above code](https://i.stack.imgur.com/aMP9L.png)](https://i.stack.imgur.com/aMP9L.png)
618,373
I'm unable to get the following table to have even row heights with vertical alignment ``` \renewcommand\tabularxcolumn[1]{m{#1}} ... \begin{table} \renewcommand*{\arraystretch}{1} \begin{tabularx}{\textwidth}{X X} \toprule \textbf{Route} & \textbf{Funzione} \\ \midrule \lstinline$/device/:id$ & Carica menu di navigazione e toolbar principale \\ \midrule \lstinline$/device/:id/dids$ & Mostra la lista dei DID document posseduti dal device \verb+id+ \\ \midrule \lstinline$/device/:id/keys$ & Mostra la lista delle chiavi pubbliche contenute nei DID document posseduti dal dispositivo \verb+id+ \\ \midrule \lstinline$/device/:id/credentials$ & Mostra la lista delle credenziali rilasciate al dispositivo \verb+id+ \\ \midrule \lstinline$/device/:id/credentials/:id/use$ & Consente di accedere al servizio di un Verifier utilizzando la credenziale \verb+id+ \\ \midrule \lstinline$/device/:id/credentials/:id/revoke$ & Consente di inviare una richiesta di revoca della credenziale \verb+id+ \\ \midrule \lstinline$/device/:id/issuers$ & Mostra la lista degli Issuer di cui il dispositivo \verb+id+ si fida \\ \midrule \lstinline$/device/:id/verifiers$ & Mostra la lista di Verifier conosciuti dal dispositivo \verb+id+ \\ \midrule \lstinline$/device/:id/status-lists$ & Mostra la lista delle status list \\ \midrule \lstinline$/device/:id/settings$ & Espone metodi d'utilità \\ \end{tabularx} \caption{Lista delle route con relative funzionalità.} \end{table} ``` By increasing the number in `\arraystretch` the result will always be to have uneven row heights. Is there a way to have all the row heights to be set with the height of the higher one? [![enter image description here](https://i.stack.imgur.com/oDIWr.png)](https://i.stack.imgur.com/oDIWr.png)
2021/10/09
[ "https://tex.stackexchange.com/questions/618373", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/166526/" ]
By use of the `tabularray` package this is relative simple to accomplish: ``` \documentclass{article} \usepackage[skip=1ex]{caption} \usepackage{tabularray} \begin{document} \begin{table} \begin{tblr}{hline{1,Z}=1pt, hline{2}=0.8pt, hline{3-Y}=solid, colspec = {@{} Q[m, font=\ttfamily] X[m,j] @{}}, row{1} = {font=\bfseries}, row{2-Z} = {ht=3\baselineskip} } Route & Funzione \\ /device/:id & Carica menu di navigazione e toolbar principale \\ /device/:id/dids & Mostra la lista dei DID document posseduti dal device \texttt{id} \\ /device/:id/keys & Mostra la lista delle chiavi pubbliche contenute nei DID document posseduti dal dispositivo \texttt{id} \\ /device/:id/credentials & Mostra la lista delle credenziali rilasciate al dispositivo \texttt{id} \\ /device/:id/credentials/:id/use & Consente di accedere al servizio di un Verifier utilizzando la credenziale \texttt{id} \\ /device/:id/credentials/:id/revoke & Consente di inviare una richiesta di revoca della credenziale \texttt{id} \\ /device/:id/issuers & Mostra la lista degli Issuer di cui il dispositivo \texttt{id} si fida \\ /device/:id/verifiers & Mostra la lista di Verifier conosciuti dal dispositivo \texttt{id} \\ /device/:id/status-lists & Mostra la lista delle status list \\ /device/:id/settings & Espone metodi d'utilità \\ \end{tblr} \caption{Lista delle route con relative funzionalità.} \end{table} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/n221i.png)](https://i.stack.imgur.com/n221i.png)
A solution with `{NiceTabular}` of `nicematrix`. ``` \documentclass{article} \usepackage[skip=1ex]{caption} \usepackage{nicematrix,booktabs} \begin{document} \begin{table} \begin{NiceTabular}{@{}>{\rule[-16pt]{0pt}{40pt}\ttfamily}lX[m]@{}}[hlines={2-11}] \toprule \multicolumn{1}{@{}l}{\bfseries Route} & \bfseries Funzione \\ /device/:id & Carica menu di navigazione e toolbar principale \\ /device/:id/dids & Mostra la lista dei DID document posseduti dal device \texttt{id} \\ /device/:id/keys & Mostra la lista delle chiavi pubbliche contenute nei DID document posseduti dal dispositivo \texttt{id} \\ /device/:id/credentials & Mostra la lista delle credenziali rilasciate al dispositivo \texttt{id} \\ /device/:id/credentials/:id/use & Consente di accedere al servizio di un Verifier utilizzando la credenziale \texttt{id} \\ /device/:id/credentials/:id/revoke & Consente di inviare una richiesta di revoca della credenziale \texttt{id} \\ /device/:id/issuers & Mostra la lista degli Issuer di cui il dispositivo \texttt{id} si fida \\ /device/:id/verifiers & Mostra la lista di Verifier conosciuti dal dispositivo \texttt{id} \\ /device/:id/status-lists& Mostra la lista delle status list \\ /device/:id/settings & Espone metodi d'utilità \\ \bottomrule \end{NiceTabular} \caption{Lista delle route con relative funzionalità.} \end{table} \end{document} ``` You need several compilations (because `nicematrix` uses PGF/Tikz nodes under the hood). [![Output of the above code](https://i.stack.imgur.com/Co1x0.png)](https://i.stack.imgur.com/Co1x0.png)
10,925,268
In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing
2012/06/07
[ "https://Stackoverflow.com/questions/10925268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47633/" ]
well, this is the best I've found so far ``` class MissingConfigurationException private(ex: RuntimeException) extends RuntimeException(ex) { def this(message:String) = this(new RuntimeException(message)) def this(message:String, throwable: Throwable) = this(new RuntimeException(message, throwable)) } object MissingConfigurationException { def apply(message:String) = new MissingConfigurationException(message) def apply(message:String, throwable: Throwable) = new MissingConfigurationException(message, throwable) } ``` this way you may use the "new MissingConfigurationException" or the apply method from the companion object Anyway, I'm still surprised that there isn't a simpler way to achieve it
Here is a similar approach to the one of @roman-borisov but more typesafe. ``` case class ShortException(message: String = "", cause: Option[Throwable] = None) extends Exception(message) { cause.foreach(initCause) } ``` Then, you can create Exceptions in the Java manner: ``` throw ShortException() throw ShortException(message) throw ShortException(message, Some(cause)) throw ShortException(cause = Some(cause)) ```
10,925,268
In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing
2012/06/07
[ "https://Stackoverflow.com/questions/10925268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47633/" ]
You can use `Throwable.initCause`. ``` class MyException (message: String, cause: Throwable) extends RuntimeException(message) { if (cause != null) initCause(cause) def this(message: String) = this(message, null) } ```
Scala pattern matching in try/catch blocks works on interfaces. My solution is to use an interface for the exception name then use separate class instances. ``` trait MyException extends RuntimeException class MyExceptionEmpty() extends RuntimeException with MyException class MyExceptionStr(msg: String) extends RuntimeException(msg) with MyException class MyExceptionEx(t: Throwable) extends RuntimeException(t) with MyException object MyException { def apply(): MyException = new MyExceptionEmpty() def apply(msg: String): MyException = new MyExceptionStr(msg) def apply(t: Throwable): MyException = new MyExceptionEx(t) } class MyClass { try { throw MyException("oops") } catch { case e: MyException => println(e.getMessage) case _: Throwable => println("nope") } } ``` Instantiating MyClass will output "oops".
10,925,268
In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing
2012/06/07
[ "https://Stackoverflow.com/questions/10925268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47633/" ]
well, this is the best I've found so far ``` class MissingConfigurationException private(ex: RuntimeException) extends RuntimeException(ex) { def this(message:String) = this(new RuntimeException(message)) def this(message:String, throwable: Throwable) = this(new RuntimeException(message, throwable)) } object MissingConfigurationException { def apply(message:String) = new MissingConfigurationException(message) def apply(message:String, throwable: Throwable) = new MissingConfigurationException(message, throwable) } ``` this way you may use the "new MissingConfigurationException" or the apply method from the companion object Anyway, I'm still surprised that there isn't a simpler way to achieve it
You can use `Throwable.initCause`. ``` class MyException (message: String, cause: Throwable) extends RuntimeException(message) { if (cause != null) initCause(cause) def this(message: String) = this(message, null) } ```
10,925,268
In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing
2012/06/07
[ "https://Stackoverflow.com/questions/10925268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47633/" ]
You can use `Throwable.initCause`. ``` class MyException (message: String, cause: Throwable) extends RuntimeException(message) { if (cause != null) initCause(cause) def this(message: String) = this(message, null) } ```
Here is a similar approach to the one of @roman-borisov but more typesafe. ``` case class ShortException(message: String = "", cause: Option[Throwable] = None) extends Exception(message) { cause.foreach(initCause) } ``` Then, you can create Exceptions in the Java manner: ``` throw ShortException() throw ShortException(message) throw ShortException(message, Some(cause)) throw ShortException(cause = Some(cause)) ```
10,925,268
In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing
2012/06/07
[ "https://Stackoverflow.com/questions/10925268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47633/" ]
well, this is the best I've found so far ``` class MissingConfigurationException private(ex: RuntimeException) extends RuntimeException(ex) { def this(message:String) = this(new RuntimeException(message)) def this(message:String, throwable: Throwable) = this(new RuntimeException(message, throwable)) } object MissingConfigurationException { def apply(message:String) = new MissingConfigurationException(message) def apply(message:String, throwable: Throwable) = new MissingConfigurationException(message, throwable) } ``` this way you may use the "new MissingConfigurationException" or the apply method from the companion object Anyway, I'm still surprised that there isn't a simpler way to achieve it
Scala pattern matching in try/catch blocks works on interfaces. My solution is to use an interface for the exception name then use separate class instances. ``` trait MyException extends RuntimeException class MyExceptionEmpty() extends RuntimeException with MyException class MyExceptionStr(msg: String) extends RuntimeException(msg) with MyException class MyExceptionEx(t: Throwable) extends RuntimeException(t) with MyException object MyException { def apply(): MyException = new MyExceptionEmpty() def apply(msg: String): MyException = new MyExceptionStr(msg) def apply(t: Throwable): MyException = new MyExceptionEx(t) } class MyClass { try { throw MyException("oops") } catch { case e: MyException => println(e.getMessage) case _: Throwable => println("nope") } } ``` Instantiating MyClass will output "oops".
10,925,268
In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing
2012/06/07
[ "https://Stackoverflow.com/questions/10925268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47633/" ]
To me, it appears there are three different needs which have a dynamic tension with each other: 1. The convenience of the extender of `RuntimeException`; i.e. minimal code to be written to create a descendant of `RuntimeException` 2. Client's perceived ease of use; i.e. minimal code to be written at the call-site 3. Client's preference to avoiding leaking the dreaded Java `null` into their code If one doesn't care about number 3, then [this answer](https://stackoverflow.com/a/10925402/501113) (a peer to this one) seems pretty succinct. However, if one values number 3 while trying to get as close to number 1 and 2 as possible, the solution below effectively encapsulates the Java `null` leak into your Scala API. ``` class MyRuntimeException ( val optionMessage: Option[String], val optionCause: Option[Throwable], val isEnableSuppression: Boolean, val isWritableStackTrace: Boolean ) extends RuntimeException( optionMessage match { case Some(string) => string case None => null }, optionCause match { case Some(throwable) => throwable case None => null }, isEnableSuppression, isWritableStackTrace ) { def this() = this(None, None, false, false) def this(message: String) = this(Some(message), None, false, false) def this(cause: Throwable) = this(None, Some(cause), false, false) def this(message: String, cause: Throwable) = this(Some(message), Some(cause), false, false) } ``` And if you would like to eliminate having to use `new` where `MyRuntimeException` is actually used, add this companion object (which just forwards all of the apply calls to the existing "master" class constructor): ``` object MyRuntimeException { def apply: MyRuntimeException = MyRuntimeException() def apply(message: String): MyRuntimeException = MyRuntimeException(optionMessage = Some(message)) def apply(cause: Throwable): MyRuntimeException = MyRuntimeException(optionCause = Some(cause)) def apply(message: String, cause: Throwable): MyRuntimeException = MyRuntimeException(optionMessage = Some(message), optionCause = Some(cause)) def apply( optionMessage: Option[String] = None, optionCause: Option[Throwable] = None, isEnableSuppression: Boolean = false, isWritableStackTrace: Boolean = false ): MyRuntimeException = new MyRuntimeException( optionMessage, optionCause, isEnableSuppression, isWritableStackTrace ) } ``` Personally, I prefer to actually suppress the use of the `new` operator in as much code as possible so as to ease possible future refactorings. It is especially helpful if said refactoring happens to strongly to the Factory pattern. My final result, while more verbose, should be quite nice for clients to use. ``` object MyRuntimeException { def apply: MyRuntimeException = MyRuntimeException() def apply(message: String): MyRuntimeException = MyRuntimeException(optionMessage = Some(message)) def apply(cause: Throwable): MyRuntimeException = MyRuntimeException(optionCause = Some(cause)) def apply(message: String, cause: Throwable): MyRuntimeException = MyRuntimeException(optionMessage = Some(message), optionCause = Some(cause)) def apply( optionMessage: Option[String] = None, optionCause: Option[Throwable] = None, isEnableSuppression: Boolean = false, isWritableStackTrace: Boolean = false ): MyRuntimeException = new MyRuntimeException( optionMessage, optionCause, isEnableSuppression, isWritableStackTrace ) } class MyRuntimeException private[MyRuntimeException] ( val optionMessage: Option[String], val optionCause: Option[Throwable], val isEnableSuppression: Boolean, val isWritableStackTrace: Boolean ) extends RuntimeException( optionMessage match { case Some(string) => string case None => null }, optionCause match { case Some(throwable) => throwable case None => null }, isEnableSuppression, isWritableStackTrace ) ``` --- --- **Exploring a more sophisticated RuntimeException pattern:** It's only a small leap from the original question to desire to create an ecosystem of specialized `RuntimeException`s for a package or API. The idea is to define a "root" `RuntimeException` from which a new ecosystem of specific descendant exceptions can be created. For me, it was important to make using `catch` and `match` much easier to exploit for specific types of errors. For example, I have a `validate` method defined which verifies a set of conditions prior to allowing a case class to be created. Each condition that fails generates a `RuntimeException` instance. And then the List of `RuntimeInstance`s are returned by the method. This gives the client the ability to decide how they would like to handle the response; `throw` the list holding exception, scan the list for something specific and `throw` that or just push the entire thing up the call chain without engaging the very expensive JVM `throw` command. This particular problem space has three different descendants of `RuntimeException`, one abstract (`FailedPrecondition`) and two concrete (`FailedPreconditionMustBeNonEmptyList` and `FailedPreconditionsException`). The first, `FailedPrecondition`, is a direct descendant to `RuntimeException`, very similar to `MyRuntimeException`, and is abstract (to prevent direct instantiations). `FailedPrecondition` has a "companion object trait", `FailedPreconditionObject` which acts as the instantiation factory (suppressing the `new` operator). ``` trait FailedPreconditionObject[F <: FailedPrecondition] { def apply: F = apply() def apply(message: String): F = apply(optionMessage = Some(message)) def apply(cause: Throwable): F = apply(optionCause = Some(cause)) def apply(message: String, cause: Throwable): F = apply(optionMessage = Some(message), optionCause = Some(cause)) def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): F } abstract class FailedPrecondition ( val optionMessage: Option[String], val optionCause: Option[Throwable], val isEnableSuppression: Boolean, val isWritableStackTrace: Boolean ) extends RuntimeException( optionMessage match { case Some(string) => string case None => null }, optionCause match { case Some(throwable) => throwable case None => null }, isEnableSuppression, isWritableStackTrace ) ``` The second, `FailedPreconditionMustBeNonEmptyList`, is an indirect `RuntimeException` descendant and a direct concrete implementation of `FailedPrecondition`. It defines both a companion object and a class. The companion object extends the trait `FailedPreconditionObject`. And the class simply extends the abstract class `FailedPrecondition` and marks it `final` to prevent any further extensions. ``` object FailedPreconditionMustBeNonEmptyList extends FailedPreconditionObject[FailedPreconditionMustBeNonEmptyList] { def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): FailedPreconditionMustBeNonEmptyList = new FailedPreconditionMustBeNonEmptyList( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) } final class FailedPreconditionMustBeNonEmptyList private[FailedPreconditionMustBeNonEmptyList] ( optionMessage: Option[String] , optionCause: Option[Throwable] , isEnableSuppression: Boolean , isWritableStackTrace: Boolean ) extends FailedPrecondition( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) ``` The third, `FailedPreconditionsException`, is a direct descendant to `RuntimeException` which wraps a `List` of `FailedPrecondition`s and then dynamically manages the emitting of the exception message. ``` object FailedPreconditionsException { def apply(failedPrecondition: FailedPrecondition): FailedPreconditionsException = FailedPreconditionsException(List(failedPrecondition)) def apply(failedPreconditions: List[FailedPrecondition]): FailedPreconditionsException = tryApply(failedPreconditions).get def tryApply(failedPrecondition: FailedPrecondition): Try[FailedPreconditionsException] = tryApply(List(failedPrecondition)) def tryApply(failedPreconditions: List[FailedPrecondition]): Try[FailedPreconditionsException] = if (failedPreconditions.nonEmpty) Success(new FailedPreconditionsException(failedPreconditions)) else Failure(FailedPreconditionMustBeNonEmptyList()) private def composeMessage(failedPreconditions: List[FailedPrecondition]): String = if (failedPreconditions.size > 1) s"failed preconditions [${failedPreconditions.size}] have occurred - ${failedPreconditions.map(_.optionMessage.getOrElse("")).mkString("|")}" else s"failed precondition has occurred - ${failedPreconditions.head.optionMessage.getOrElse("")}" } final class FailedPreconditionsException private[FailedPreconditionsException] ( val failedPreconditions: List[FailedPrecondition] ) extends RuntimeException(FailedPreconditionsException.composeMessage(failedPreconditions)) ``` And then bringing all of that together as a whole and tidy things up, I place both `FailedPrecondition` and `FailedPreconditionMustBeNonEmptyList` within object `FailedPreconditionsException`. And this is what the final result looks like: ``` object FailedPreconditionsException { trait FailedPreconditionObject[F <: FailedPrecondition] { def apply: F = apply() def apply(message: String): F = apply(optionMessage = Some(message)) def apply(cause: Throwable): F = apply(optionCause = Some(cause)) def apply(message: String, cause: Throwable): F = apply(optionMessage = Some(message), optionCause = Some(cause)) def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): F } abstract class FailedPrecondition ( val optionMessage: Option[String] , val optionCause: Option[Throwable] , val isEnableSuppression: Boolean , val isWritableStackTrace: Boolean ) extends RuntimeException( optionMessage match { case Some(string) => string case None => null }, optionCause match { case Some(throwable) => throwable case None => null }, isEnableSuppression, isWritableStackTrace ) object FailedPreconditionMustBeNonEmptyList extends FailedPreconditionObject[FailedPreconditionMustBeNonEmptyList] { def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): FailedPreconditionMustBeNonEmptyList = new FailedPreconditionMustBeNonEmptyList( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) } final class FailedPreconditionMustBeNonEmptyList private[FailedPreconditionMustBeNonEmptyList] ( optionMessage: Option[String] , optionCause: Option[Throwable] , isEnableSuppression: Boolean , isWritableStackTrace: Boolean ) extends FailedPrecondition( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) def apply(failedPrecondition: FailedPrecondition): FailedPreconditionsException = FailedPreconditionsException(List(failedPrecondition)) def apply(failedPreconditions: List[FailedPrecondition]): FailedPreconditionsException = tryApply(failedPreconditions).get def tryApply(failedPrecondition: FailedPrecondition): Try[FailedPreconditionsException] = tryApply(List(failedPrecondition)) def tryApply(failedPreconditions: List[FailedPrecondition]): Try[FailedPreconditionsException] = if (failedPreconditions.nonEmpty) Success(new FailedPreconditionsException(failedPreconditions)) else Failure(FailedPreconditionMustBeNonEmptyList()) private def composeMessage(failedPreconditions: List[FailedPrecondition]): String = if (failedPreconditions.size > 1) s"failed preconditions [${failedPreconditions.size}] have occurred - ${failedPreconditions.map(_.optionMessage.getOrElse("")).mkString("|")}" else s"failed precondition has occurred - ${failedPreconditions.head.optionMessage.getOrElse("")}" } final class FailedPreconditionsException private[FailedPreconditionsException] ( val failedPreconditions: List[FailedPreconditionsException.FailedPrecondition] ) extends RuntimeException(FailedPreconditionsException.composeMessage(failedPreconditions)) ``` And this is what it would look like for a client to use the above code to create their own exception derivation called `FailedPreconditionMustBeNonEmptyString`: ``` object FailedPreconditionMustBeNonEmptyString extends FailedPreconditionObject[FailedPreconditionMustBeNonEmptyString] { def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): FailedPreconditionMustBeNonEmptyString = new FailedPreconditionMustBeNonEmptyString( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) } final class FailedPreconditionMustBeNonEmptyString private[FailedPreconditionMustBeNonEmptyString] ( optionMessage: Option[String] , optionCause: Option[Throwable] , isEnableSuppression: Boolean , isWritableStackTrace: Boolean ) extends FailedPrecondition( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) ``` And then the use of this exception looks like this: ``` throw FailedPreconditionMustBeNonEmptyString() ``` I went well beyond answering the original question because I found it so difficult to locate anything close to being both specific and comprehensive in Scala-ifying `RuntimeException` in specific or extending into the more general "exception ecosystem" with which I grew so comfortable when in Java. I'd love to hear feedback (other than variations on, "Wow! That's way too verbose for me.") on my solution set. And I would love any additional optimizations or ways to reduce the verbosity WITHOUT LOSING any of the value or terseness I have generated for the clients of this pattern.
Scala pattern matching in try/catch blocks works on interfaces. My solution is to use an interface for the exception name then use separate class instances. ``` trait MyException extends RuntimeException class MyExceptionEmpty() extends RuntimeException with MyException class MyExceptionStr(msg: String) extends RuntimeException(msg) with MyException class MyExceptionEx(t: Throwable) extends RuntimeException(t) with MyException object MyException { def apply(): MyException = new MyExceptionEmpty() def apply(msg: String): MyException = new MyExceptionStr(msg) def apply(t: Throwable): MyException = new MyExceptionEx(t) } class MyClass { try { throw MyException("oops") } catch { case e: MyException => println(e.getMessage) case _: Throwable => println("nope") } } ``` Instantiating MyClass will output "oops".
10,925,268
In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing
2012/06/07
[ "https://Stackoverflow.com/questions/10925268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47633/" ]
Default value for `cause` is null. And for `message` it is either `cause.toString()` or null: ``` val e1 = new RuntimeException() e.getCause // res1: java.lang.Throwable = null e.getMessage //res2: java.lang.String = null val cause = new RuntimeException("cause msg") val e2 = new RuntimeException(cause) e.getMessage() //res3: String = java.lang.RuntimeException: cause msg ``` So you can just use default values: ``` class MyException(message: String = null, cause: Throwable = null) extends RuntimeException(MyException.defaultMessage(message, cause), cause) object MyException { def defaultMessage(message: String, cause: Throwable) = if (message != null) message else if (cause != null) cause.toString() else null } // usage: new MyException(cause = myCause) // res0: MyException = MyException: java.lang.RuntimeException: myCause msg ```
Scala pattern matching in try/catch blocks works on interfaces. My solution is to use an interface for the exception name then use separate class instances. ``` trait MyException extends RuntimeException class MyExceptionEmpty() extends RuntimeException with MyException class MyExceptionStr(msg: String) extends RuntimeException(msg) with MyException class MyExceptionEx(t: Throwable) extends RuntimeException(t) with MyException object MyException { def apply(): MyException = new MyExceptionEmpty() def apply(msg: String): MyException = new MyExceptionStr(msg) def apply(t: Throwable): MyException = new MyExceptionEx(t) } class MyClass { try { throw MyException("oops") } catch { case e: MyException => println(e.getMessage) case _: Throwable => println("nope") } } ``` Instantiating MyClass will output "oops".
10,925,268
In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing
2012/06/07
[ "https://Stackoverflow.com/questions/10925268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47633/" ]
Default value for `cause` is null. And for `message` it is either `cause.toString()` or null: ``` val e1 = new RuntimeException() e.getCause // res1: java.lang.Throwable = null e.getMessage //res2: java.lang.String = null val cause = new RuntimeException("cause msg") val e2 = new RuntimeException(cause) e.getMessage() //res3: String = java.lang.RuntimeException: cause msg ``` So you can just use default values: ``` class MyException(message: String = null, cause: Throwable = null) extends RuntimeException(MyException.defaultMessage(message, cause), cause) object MyException { def defaultMessage(message: String, cause: Throwable) = if (message != null) message else if (cause != null) cause.toString() else null } // usage: new MyException(cause = myCause) // res0: MyException = MyException: java.lang.RuntimeException: myCause msg ```
You can use `Throwable.initCause`. ``` class MyException (message: String, cause: Throwable) extends RuntimeException(message) { if (cause != null) initCause(cause) def this(message: String) = this(message, null) } ```
10,925,268
In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing
2012/06/07
[ "https://Stackoverflow.com/questions/10925268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47633/" ]
To me, it appears there are three different needs which have a dynamic tension with each other: 1. The convenience of the extender of `RuntimeException`; i.e. minimal code to be written to create a descendant of `RuntimeException` 2. Client's perceived ease of use; i.e. minimal code to be written at the call-site 3. Client's preference to avoiding leaking the dreaded Java `null` into their code If one doesn't care about number 3, then [this answer](https://stackoverflow.com/a/10925402/501113) (a peer to this one) seems pretty succinct. However, if one values number 3 while trying to get as close to number 1 and 2 as possible, the solution below effectively encapsulates the Java `null` leak into your Scala API. ``` class MyRuntimeException ( val optionMessage: Option[String], val optionCause: Option[Throwable], val isEnableSuppression: Boolean, val isWritableStackTrace: Boolean ) extends RuntimeException( optionMessage match { case Some(string) => string case None => null }, optionCause match { case Some(throwable) => throwable case None => null }, isEnableSuppression, isWritableStackTrace ) { def this() = this(None, None, false, false) def this(message: String) = this(Some(message), None, false, false) def this(cause: Throwable) = this(None, Some(cause), false, false) def this(message: String, cause: Throwable) = this(Some(message), Some(cause), false, false) } ``` And if you would like to eliminate having to use `new` where `MyRuntimeException` is actually used, add this companion object (which just forwards all of the apply calls to the existing "master" class constructor): ``` object MyRuntimeException { def apply: MyRuntimeException = MyRuntimeException() def apply(message: String): MyRuntimeException = MyRuntimeException(optionMessage = Some(message)) def apply(cause: Throwable): MyRuntimeException = MyRuntimeException(optionCause = Some(cause)) def apply(message: String, cause: Throwable): MyRuntimeException = MyRuntimeException(optionMessage = Some(message), optionCause = Some(cause)) def apply( optionMessage: Option[String] = None, optionCause: Option[Throwable] = None, isEnableSuppression: Boolean = false, isWritableStackTrace: Boolean = false ): MyRuntimeException = new MyRuntimeException( optionMessage, optionCause, isEnableSuppression, isWritableStackTrace ) } ``` Personally, I prefer to actually suppress the use of the `new` operator in as much code as possible so as to ease possible future refactorings. It is especially helpful if said refactoring happens to strongly to the Factory pattern. My final result, while more verbose, should be quite nice for clients to use. ``` object MyRuntimeException { def apply: MyRuntimeException = MyRuntimeException() def apply(message: String): MyRuntimeException = MyRuntimeException(optionMessage = Some(message)) def apply(cause: Throwable): MyRuntimeException = MyRuntimeException(optionCause = Some(cause)) def apply(message: String, cause: Throwable): MyRuntimeException = MyRuntimeException(optionMessage = Some(message), optionCause = Some(cause)) def apply( optionMessage: Option[String] = None, optionCause: Option[Throwable] = None, isEnableSuppression: Boolean = false, isWritableStackTrace: Boolean = false ): MyRuntimeException = new MyRuntimeException( optionMessage, optionCause, isEnableSuppression, isWritableStackTrace ) } class MyRuntimeException private[MyRuntimeException] ( val optionMessage: Option[String], val optionCause: Option[Throwable], val isEnableSuppression: Boolean, val isWritableStackTrace: Boolean ) extends RuntimeException( optionMessage match { case Some(string) => string case None => null }, optionCause match { case Some(throwable) => throwable case None => null }, isEnableSuppression, isWritableStackTrace ) ``` --- --- **Exploring a more sophisticated RuntimeException pattern:** It's only a small leap from the original question to desire to create an ecosystem of specialized `RuntimeException`s for a package or API. The idea is to define a "root" `RuntimeException` from which a new ecosystem of specific descendant exceptions can be created. For me, it was important to make using `catch` and `match` much easier to exploit for specific types of errors. For example, I have a `validate` method defined which verifies a set of conditions prior to allowing a case class to be created. Each condition that fails generates a `RuntimeException` instance. And then the List of `RuntimeInstance`s are returned by the method. This gives the client the ability to decide how they would like to handle the response; `throw` the list holding exception, scan the list for something specific and `throw` that or just push the entire thing up the call chain without engaging the very expensive JVM `throw` command. This particular problem space has three different descendants of `RuntimeException`, one abstract (`FailedPrecondition`) and two concrete (`FailedPreconditionMustBeNonEmptyList` and `FailedPreconditionsException`). The first, `FailedPrecondition`, is a direct descendant to `RuntimeException`, very similar to `MyRuntimeException`, and is abstract (to prevent direct instantiations). `FailedPrecondition` has a "companion object trait", `FailedPreconditionObject` which acts as the instantiation factory (suppressing the `new` operator). ``` trait FailedPreconditionObject[F <: FailedPrecondition] { def apply: F = apply() def apply(message: String): F = apply(optionMessage = Some(message)) def apply(cause: Throwable): F = apply(optionCause = Some(cause)) def apply(message: String, cause: Throwable): F = apply(optionMessage = Some(message), optionCause = Some(cause)) def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): F } abstract class FailedPrecondition ( val optionMessage: Option[String], val optionCause: Option[Throwable], val isEnableSuppression: Boolean, val isWritableStackTrace: Boolean ) extends RuntimeException( optionMessage match { case Some(string) => string case None => null }, optionCause match { case Some(throwable) => throwable case None => null }, isEnableSuppression, isWritableStackTrace ) ``` The second, `FailedPreconditionMustBeNonEmptyList`, is an indirect `RuntimeException` descendant and a direct concrete implementation of `FailedPrecondition`. It defines both a companion object and a class. The companion object extends the trait `FailedPreconditionObject`. And the class simply extends the abstract class `FailedPrecondition` and marks it `final` to prevent any further extensions. ``` object FailedPreconditionMustBeNonEmptyList extends FailedPreconditionObject[FailedPreconditionMustBeNonEmptyList] { def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): FailedPreconditionMustBeNonEmptyList = new FailedPreconditionMustBeNonEmptyList( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) } final class FailedPreconditionMustBeNonEmptyList private[FailedPreconditionMustBeNonEmptyList] ( optionMessage: Option[String] , optionCause: Option[Throwable] , isEnableSuppression: Boolean , isWritableStackTrace: Boolean ) extends FailedPrecondition( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) ``` The third, `FailedPreconditionsException`, is a direct descendant to `RuntimeException` which wraps a `List` of `FailedPrecondition`s and then dynamically manages the emitting of the exception message. ``` object FailedPreconditionsException { def apply(failedPrecondition: FailedPrecondition): FailedPreconditionsException = FailedPreconditionsException(List(failedPrecondition)) def apply(failedPreconditions: List[FailedPrecondition]): FailedPreconditionsException = tryApply(failedPreconditions).get def tryApply(failedPrecondition: FailedPrecondition): Try[FailedPreconditionsException] = tryApply(List(failedPrecondition)) def tryApply(failedPreconditions: List[FailedPrecondition]): Try[FailedPreconditionsException] = if (failedPreconditions.nonEmpty) Success(new FailedPreconditionsException(failedPreconditions)) else Failure(FailedPreconditionMustBeNonEmptyList()) private def composeMessage(failedPreconditions: List[FailedPrecondition]): String = if (failedPreconditions.size > 1) s"failed preconditions [${failedPreconditions.size}] have occurred - ${failedPreconditions.map(_.optionMessage.getOrElse("")).mkString("|")}" else s"failed precondition has occurred - ${failedPreconditions.head.optionMessage.getOrElse("")}" } final class FailedPreconditionsException private[FailedPreconditionsException] ( val failedPreconditions: List[FailedPrecondition] ) extends RuntimeException(FailedPreconditionsException.composeMessage(failedPreconditions)) ``` And then bringing all of that together as a whole and tidy things up, I place both `FailedPrecondition` and `FailedPreconditionMustBeNonEmptyList` within object `FailedPreconditionsException`. And this is what the final result looks like: ``` object FailedPreconditionsException { trait FailedPreconditionObject[F <: FailedPrecondition] { def apply: F = apply() def apply(message: String): F = apply(optionMessage = Some(message)) def apply(cause: Throwable): F = apply(optionCause = Some(cause)) def apply(message: String, cause: Throwable): F = apply(optionMessage = Some(message), optionCause = Some(cause)) def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): F } abstract class FailedPrecondition ( val optionMessage: Option[String] , val optionCause: Option[Throwable] , val isEnableSuppression: Boolean , val isWritableStackTrace: Boolean ) extends RuntimeException( optionMessage match { case Some(string) => string case None => null }, optionCause match { case Some(throwable) => throwable case None => null }, isEnableSuppression, isWritableStackTrace ) object FailedPreconditionMustBeNonEmptyList extends FailedPreconditionObject[FailedPreconditionMustBeNonEmptyList] { def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): FailedPreconditionMustBeNonEmptyList = new FailedPreconditionMustBeNonEmptyList( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) } final class FailedPreconditionMustBeNonEmptyList private[FailedPreconditionMustBeNonEmptyList] ( optionMessage: Option[String] , optionCause: Option[Throwable] , isEnableSuppression: Boolean , isWritableStackTrace: Boolean ) extends FailedPrecondition( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) def apply(failedPrecondition: FailedPrecondition): FailedPreconditionsException = FailedPreconditionsException(List(failedPrecondition)) def apply(failedPreconditions: List[FailedPrecondition]): FailedPreconditionsException = tryApply(failedPreconditions).get def tryApply(failedPrecondition: FailedPrecondition): Try[FailedPreconditionsException] = tryApply(List(failedPrecondition)) def tryApply(failedPreconditions: List[FailedPrecondition]): Try[FailedPreconditionsException] = if (failedPreconditions.nonEmpty) Success(new FailedPreconditionsException(failedPreconditions)) else Failure(FailedPreconditionMustBeNonEmptyList()) private def composeMessage(failedPreconditions: List[FailedPrecondition]): String = if (failedPreconditions.size > 1) s"failed preconditions [${failedPreconditions.size}] have occurred - ${failedPreconditions.map(_.optionMessage.getOrElse("")).mkString("|")}" else s"failed precondition has occurred - ${failedPreconditions.head.optionMessage.getOrElse("")}" } final class FailedPreconditionsException private[FailedPreconditionsException] ( val failedPreconditions: List[FailedPreconditionsException.FailedPrecondition] ) extends RuntimeException(FailedPreconditionsException.composeMessage(failedPreconditions)) ``` And this is what it would look like for a client to use the above code to create their own exception derivation called `FailedPreconditionMustBeNonEmptyString`: ``` object FailedPreconditionMustBeNonEmptyString extends FailedPreconditionObject[FailedPreconditionMustBeNonEmptyString] { def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): FailedPreconditionMustBeNonEmptyString = new FailedPreconditionMustBeNonEmptyString( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) } final class FailedPreconditionMustBeNonEmptyString private[FailedPreconditionMustBeNonEmptyString] ( optionMessage: Option[String] , optionCause: Option[Throwable] , isEnableSuppression: Boolean , isWritableStackTrace: Boolean ) extends FailedPrecondition( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) ``` And then the use of this exception looks like this: ``` throw FailedPreconditionMustBeNonEmptyString() ``` I went well beyond answering the original question because I found it so difficult to locate anything close to being both specific and comprehensive in Scala-ifying `RuntimeException` in specific or extending into the more general "exception ecosystem" with which I grew so comfortable when in Java. I'd love to hear feedback (other than variations on, "Wow! That's way too verbose for me.") on my solution set. And I would love any additional optimizations or ways to reduce the verbosity WITHOUT LOSING any of the value or terseness I have generated for the clients of this pattern.
Here is a similar approach to the one of @roman-borisov but more typesafe. ``` case class ShortException(message: String = "", cause: Option[Throwable] = None) extends Exception(message) { cause.foreach(initCause) } ``` Then, you can create Exceptions in the Java manner: ``` throw ShortException() throw ShortException(message) throw ShortException(message, Some(cause)) throw ShortException(cause = Some(cause)) ```
10,925,268
In java exceptions have at least these four constructors: ``` Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause) ``` If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor How can you achieve the same thing in scala? so far now I saw [this article](https://lizdouglass.wordpress.com/2010/12/15/scala-multiple-constructors/) and this [SO answer](https://stackoverflow.com/a/3300046/47633), but I suspect there must be an easier way to achieve such a common thing
2012/06/07
[ "https://Stackoverflow.com/questions/10925268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47633/" ]
well, this is the best I've found so far ``` class MissingConfigurationException private(ex: RuntimeException) extends RuntimeException(ex) { def this(message:String) = this(new RuntimeException(message)) def this(message:String, throwable: Throwable) = this(new RuntimeException(message, throwable)) } object MissingConfigurationException { def apply(message:String) = new MissingConfigurationException(message) def apply(message:String, throwable: Throwable) = new MissingConfigurationException(message, throwable) } ``` this way you may use the "new MissingConfigurationException" or the apply method from the companion object Anyway, I'm still surprised that there isn't a simpler way to achieve it
To me, it appears there are three different needs which have a dynamic tension with each other: 1. The convenience of the extender of `RuntimeException`; i.e. minimal code to be written to create a descendant of `RuntimeException` 2. Client's perceived ease of use; i.e. minimal code to be written at the call-site 3. Client's preference to avoiding leaking the dreaded Java `null` into their code If one doesn't care about number 3, then [this answer](https://stackoverflow.com/a/10925402/501113) (a peer to this one) seems pretty succinct. However, if one values number 3 while trying to get as close to number 1 and 2 as possible, the solution below effectively encapsulates the Java `null` leak into your Scala API. ``` class MyRuntimeException ( val optionMessage: Option[String], val optionCause: Option[Throwable], val isEnableSuppression: Boolean, val isWritableStackTrace: Boolean ) extends RuntimeException( optionMessage match { case Some(string) => string case None => null }, optionCause match { case Some(throwable) => throwable case None => null }, isEnableSuppression, isWritableStackTrace ) { def this() = this(None, None, false, false) def this(message: String) = this(Some(message), None, false, false) def this(cause: Throwable) = this(None, Some(cause), false, false) def this(message: String, cause: Throwable) = this(Some(message), Some(cause), false, false) } ``` And if you would like to eliminate having to use `new` where `MyRuntimeException` is actually used, add this companion object (which just forwards all of the apply calls to the existing "master" class constructor): ``` object MyRuntimeException { def apply: MyRuntimeException = MyRuntimeException() def apply(message: String): MyRuntimeException = MyRuntimeException(optionMessage = Some(message)) def apply(cause: Throwable): MyRuntimeException = MyRuntimeException(optionCause = Some(cause)) def apply(message: String, cause: Throwable): MyRuntimeException = MyRuntimeException(optionMessage = Some(message), optionCause = Some(cause)) def apply( optionMessage: Option[String] = None, optionCause: Option[Throwable] = None, isEnableSuppression: Boolean = false, isWritableStackTrace: Boolean = false ): MyRuntimeException = new MyRuntimeException( optionMessage, optionCause, isEnableSuppression, isWritableStackTrace ) } ``` Personally, I prefer to actually suppress the use of the `new` operator in as much code as possible so as to ease possible future refactorings. It is especially helpful if said refactoring happens to strongly to the Factory pattern. My final result, while more verbose, should be quite nice for clients to use. ``` object MyRuntimeException { def apply: MyRuntimeException = MyRuntimeException() def apply(message: String): MyRuntimeException = MyRuntimeException(optionMessage = Some(message)) def apply(cause: Throwable): MyRuntimeException = MyRuntimeException(optionCause = Some(cause)) def apply(message: String, cause: Throwable): MyRuntimeException = MyRuntimeException(optionMessage = Some(message), optionCause = Some(cause)) def apply( optionMessage: Option[String] = None, optionCause: Option[Throwable] = None, isEnableSuppression: Boolean = false, isWritableStackTrace: Boolean = false ): MyRuntimeException = new MyRuntimeException( optionMessage, optionCause, isEnableSuppression, isWritableStackTrace ) } class MyRuntimeException private[MyRuntimeException] ( val optionMessage: Option[String], val optionCause: Option[Throwable], val isEnableSuppression: Boolean, val isWritableStackTrace: Boolean ) extends RuntimeException( optionMessage match { case Some(string) => string case None => null }, optionCause match { case Some(throwable) => throwable case None => null }, isEnableSuppression, isWritableStackTrace ) ``` --- --- **Exploring a more sophisticated RuntimeException pattern:** It's only a small leap from the original question to desire to create an ecosystem of specialized `RuntimeException`s for a package or API. The idea is to define a "root" `RuntimeException` from which a new ecosystem of specific descendant exceptions can be created. For me, it was important to make using `catch` and `match` much easier to exploit for specific types of errors. For example, I have a `validate` method defined which verifies a set of conditions prior to allowing a case class to be created. Each condition that fails generates a `RuntimeException` instance. And then the List of `RuntimeInstance`s are returned by the method. This gives the client the ability to decide how they would like to handle the response; `throw` the list holding exception, scan the list for something specific and `throw` that or just push the entire thing up the call chain without engaging the very expensive JVM `throw` command. This particular problem space has three different descendants of `RuntimeException`, one abstract (`FailedPrecondition`) and two concrete (`FailedPreconditionMustBeNonEmptyList` and `FailedPreconditionsException`). The first, `FailedPrecondition`, is a direct descendant to `RuntimeException`, very similar to `MyRuntimeException`, and is abstract (to prevent direct instantiations). `FailedPrecondition` has a "companion object trait", `FailedPreconditionObject` which acts as the instantiation factory (suppressing the `new` operator). ``` trait FailedPreconditionObject[F <: FailedPrecondition] { def apply: F = apply() def apply(message: String): F = apply(optionMessage = Some(message)) def apply(cause: Throwable): F = apply(optionCause = Some(cause)) def apply(message: String, cause: Throwable): F = apply(optionMessage = Some(message), optionCause = Some(cause)) def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): F } abstract class FailedPrecondition ( val optionMessage: Option[String], val optionCause: Option[Throwable], val isEnableSuppression: Boolean, val isWritableStackTrace: Boolean ) extends RuntimeException( optionMessage match { case Some(string) => string case None => null }, optionCause match { case Some(throwable) => throwable case None => null }, isEnableSuppression, isWritableStackTrace ) ``` The second, `FailedPreconditionMustBeNonEmptyList`, is an indirect `RuntimeException` descendant and a direct concrete implementation of `FailedPrecondition`. It defines both a companion object and a class. The companion object extends the trait `FailedPreconditionObject`. And the class simply extends the abstract class `FailedPrecondition` and marks it `final` to prevent any further extensions. ``` object FailedPreconditionMustBeNonEmptyList extends FailedPreconditionObject[FailedPreconditionMustBeNonEmptyList] { def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): FailedPreconditionMustBeNonEmptyList = new FailedPreconditionMustBeNonEmptyList( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) } final class FailedPreconditionMustBeNonEmptyList private[FailedPreconditionMustBeNonEmptyList] ( optionMessage: Option[String] , optionCause: Option[Throwable] , isEnableSuppression: Boolean , isWritableStackTrace: Boolean ) extends FailedPrecondition( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) ``` The third, `FailedPreconditionsException`, is a direct descendant to `RuntimeException` which wraps a `List` of `FailedPrecondition`s and then dynamically manages the emitting of the exception message. ``` object FailedPreconditionsException { def apply(failedPrecondition: FailedPrecondition): FailedPreconditionsException = FailedPreconditionsException(List(failedPrecondition)) def apply(failedPreconditions: List[FailedPrecondition]): FailedPreconditionsException = tryApply(failedPreconditions).get def tryApply(failedPrecondition: FailedPrecondition): Try[FailedPreconditionsException] = tryApply(List(failedPrecondition)) def tryApply(failedPreconditions: List[FailedPrecondition]): Try[FailedPreconditionsException] = if (failedPreconditions.nonEmpty) Success(new FailedPreconditionsException(failedPreconditions)) else Failure(FailedPreconditionMustBeNonEmptyList()) private def composeMessage(failedPreconditions: List[FailedPrecondition]): String = if (failedPreconditions.size > 1) s"failed preconditions [${failedPreconditions.size}] have occurred - ${failedPreconditions.map(_.optionMessage.getOrElse("")).mkString("|")}" else s"failed precondition has occurred - ${failedPreconditions.head.optionMessage.getOrElse("")}" } final class FailedPreconditionsException private[FailedPreconditionsException] ( val failedPreconditions: List[FailedPrecondition] ) extends RuntimeException(FailedPreconditionsException.composeMessage(failedPreconditions)) ``` And then bringing all of that together as a whole and tidy things up, I place both `FailedPrecondition` and `FailedPreconditionMustBeNonEmptyList` within object `FailedPreconditionsException`. And this is what the final result looks like: ``` object FailedPreconditionsException { trait FailedPreconditionObject[F <: FailedPrecondition] { def apply: F = apply() def apply(message: String): F = apply(optionMessage = Some(message)) def apply(cause: Throwable): F = apply(optionCause = Some(cause)) def apply(message: String, cause: Throwable): F = apply(optionMessage = Some(message), optionCause = Some(cause)) def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): F } abstract class FailedPrecondition ( val optionMessage: Option[String] , val optionCause: Option[Throwable] , val isEnableSuppression: Boolean , val isWritableStackTrace: Boolean ) extends RuntimeException( optionMessage match { case Some(string) => string case None => null }, optionCause match { case Some(throwable) => throwable case None => null }, isEnableSuppression, isWritableStackTrace ) object FailedPreconditionMustBeNonEmptyList extends FailedPreconditionObject[FailedPreconditionMustBeNonEmptyList] { def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): FailedPreconditionMustBeNonEmptyList = new FailedPreconditionMustBeNonEmptyList( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) } final class FailedPreconditionMustBeNonEmptyList private[FailedPreconditionMustBeNonEmptyList] ( optionMessage: Option[String] , optionCause: Option[Throwable] , isEnableSuppression: Boolean , isWritableStackTrace: Boolean ) extends FailedPrecondition( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) def apply(failedPrecondition: FailedPrecondition): FailedPreconditionsException = FailedPreconditionsException(List(failedPrecondition)) def apply(failedPreconditions: List[FailedPrecondition]): FailedPreconditionsException = tryApply(failedPreconditions).get def tryApply(failedPrecondition: FailedPrecondition): Try[FailedPreconditionsException] = tryApply(List(failedPrecondition)) def tryApply(failedPreconditions: List[FailedPrecondition]): Try[FailedPreconditionsException] = if (failedPreconditions.nonEmpty) Success(new FailedPreconditionsException(failedPreconditions)) else Failure(FailedPreconditionMustBeNonEmptyList()) private def composeMessage(failedPreconditions: List[FailedPrecondition]): String = if (failedPreconditions.size > 1) s"failed preconditions [${failedPreconditions.size}] have occurred - ${failedPreconditions.map(_.optionMessage.getOrElse("")).mkString("|")}" else s"failed precondition has occurred - ${failedPreconditions.head.optionMessage.getOrElse("")}" } final class FailedPreconditionsException private[FailedPreconditionsException] ( val failedPreconditions: List[FailedPreconditionsException.FailedPrecondition] ) extends RuntimeException(FailedPreconditionsException.composeMessage(failedPreconditions)) ``` And this is what it would look like for a client to use the above code to create their own exception derivation called `FailedPreconditionMustBeNonEmptyString`: ``` object FailedPreconditionMustBeNonEmptyString extends FailedPreconditionObject[FailedPreconditionMustBeNonEmptyString] { def apply( optionMessage: Option[String] = None , optionCause: Option[Throwable] = None , isEnableSuppression: Boolean = false , isWritableStackTrace: Boolean = false ): FailedPreconditionMustBeNonEmptyString = new FailedPreconditionMustBeNonEmptyString( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) } final class FailedPreconditionMustBeNonEmptyString private[FailedPreconditionMustBeNonEmptyString] ( optionMessage: Option[String] , optionCause: Option[Throwable] , isEnableSuppression: Boolean , isWritableStackTrace: Boolean ) extends FailedPrecondition( optionMessage , optionCause , isEnableSuppression , isWritableStackTrace ) ``` And then the use of this exception looks like this: ``` throw FailedPreconditionMustBeNonEmptyString() ``` I went well beyond answering the original question because I found it so difficult to locate anything close to being both specific and comprehensive in Scala-ifying `RuntimeException` in specific or extending into the more general "exception ecosystem" with which I grew so comfortable when in Java. I'd love to hear feedback (other than variations on, "Wow! That's way too verbose for me.") on my solution set. And I would love any additional optimizations or ways to reduce the verbosity WITHOUT LOSING any of the value or terseness I have generated for the clients of this pattern.
1,451,306
Attempting to do something very simple - compile basic win 32 c programs through windows cmd. This is something I should be able to do myself, but I am just so stuck here.. I keep stumbling into weird problems, vague errors. I dunno whether I should go into details. Using tcc ( tiny c compiler) 1. One simple hellowin.c example from a book required winmm.lib. How do I import it ? can someone give me the exact command for gcc/tcc /any command line compiler for windows(except cygwin) ? I did try various options after reading help , but it kept giving me a can't find stupid error. 2. a sample from platform sdk that I tried to compile gave a - winnt.h "( expected" error. this after a #define \_M\_IX86 . what it means ? 3. any general guide for compiling c programs for windows(win32 api) through command line ? . explaining what all should be #defined ..etc.. I have googled a lot but most of the c compiling guidelines for win32 programs focus on vb .I wanna do it manually , on the command line. Thanks
2009/09/20
[ "https://Stackoverflow.com/questions/1451306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161179/" ]
If I create a new project using Visual Studio it #defines the following preprocessor symbols using compiler command-line options: * `WIN32` * `_WINDOWS` * one of either `_DEBUG` or `NDEBUG` * `UNICODE` and `_UNICODE` (although the Windows headers and libraries also support non-Unicode-enabled applications, if your compiler doesn't support Unicode). <http://bellard.org/tcc/tcc-doc.html> says "For usage on Windows, see also tcc-win32.txt".
Sounds like the kind of compiler that might be looking for INCLUDE and LIB paths in the environment. If you do "set" on the command line and don't see those vars listed, you could try setting them to the paths your compiler is using. Not sure where you would have installed this tcc tool, but look for directories named 'include' and 'lib' and try assigning those to the aforementioned environment variables.
1,451,306
Attempting to do something very simple - compile basic win 32 c programs through windows cmd. This is something I should be able to do myself, but I am just so stuck here.. I keep stumbling into weird problems, vague errors. I dunno whether I should go into details. Using tcc ( tiny c compiler) 1. One simple hellowin.c example from a book required winmm.lib. How do I import it ? can someone give me the exact command for gcc/tcc /any command line compiler for windows(except cygwin) ? I did try various options after reading help , but it kept giving me a can't find stupid error. 2. a sample from platform sdk that I tried to compile gave a - winnt.h "( expected" error. this after a #define \_M\_IX86 . what it means ? 3. any general guide for compiling c programs for windows(win32 api) through command line ? . explaining what all should be #defined ..etc.. I have googled a lot but most of the c compiling guidelines for win32 programs focus on vb .I wanna do it manually , on the command line. Thanks
2009/09/20
[ "https://Stackoverflow.com/questions/1451306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161179/" ]
Download the Windows PlatformSDK and it comes with its own command line compiler. It creates a shortcut Start->Programs->... to open a command prompt for either 32bit or 64bit. Select the 32bit variant and you get a fully initialized command prompt with compiler in your PATH and all INCLUDE, LIB and LIBPATH set. cmd> cl hello.c This should give you hello.exe. For more help on compiler "cl /?", for linker "link /?"
Sounds like the kind of compiler that might be looking for INCLUDE and LIB paths in the environment. If you do "set" on the command line and don't see those vars listed, you could try setting them to the paths your compiler is using. Not sure where you would have installed this tcc tool, but look for directories named 'include' and 'lib' and try assigning those to the aforementioned environment variables.
1,451,306
Attempting to do something very simple - compile basic win 32 c programs through windows cmd. This is something I should be able to do myself, but I am just so stuck here.. I keep stumbling into weird problems, vague errors. I dunno whether I should go into details. Using tcc ( tiny c compiler) 1. One simple hellowin.c example from a book required winmm.lib. How do I import it ? can someone give me the exact command for gcc/tcc /any command line compiler for windows(except cygwin) ? I did try various options after reading help , but it kept giving me a can't find stupid error. 2. a sample from platform sdk that I tried to compile gave a - winnt.h "( expected" error. this after a #define \_M\_IX86 . what it means ? 3. any general guide for compiling c programs for windows(win32 api) through command line ? . explaining what all should be #defined ..etc.. I have googled a lot but most of the c compiling guidelines for win32 programs focus on vb .I wanna do it manually , on the command line. Thanks
2009/09/20
[ "https://Stackoverflow.com/questions/1451306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161179/" ]
If I create a new project using Visual Studio it #defines the following preprocessor symbols using compiler command-line options: * `WIN32` * `_WINDOWS` * one of either `_DEBUG` or `NDEBUG` * `UNICODE` and `_UNICODE` (although the Windows headers and libraries also support non-Unicode-enabled applications, if your compiler doesn't support Unicode). <http://bellard.org/tcc/tcc-doc.html> says "For usage on Windows, see also tcc-win32.txt".
You can try gcc from [equation.com](http://www.equation.com/). It's a mingw wrapped compiler, but you don't have to worry about mingw: just download, install and use. There's no IDE either. The download page is at [<http://www.equation.com/servlet/equation.cmd?fa=fortran>](http://www.equation.com/servlet/equation.cmd?fa=fortran).
1,451,306
Attempting to do something very simple - compile basic win 32 c programs through windows cmd. This is something I should be able to do myself, but I am just so stuck here.. I keep stumbling into weird problems, vague errors. I dunno whether I should go into details. Using tcc ( tiny c compiler) 1. One simple hellowin.c example from a book required winmm.lib. How do I import it ? can someone give me the exact command for gcc/tcc /any command line compiler for windows(except cygwin) ? I did try various options after reading help , but it kept giving me a can't find stupid error. 2. a sample from platform sdk that I tried to compile gave a - winnt.h "( expected" error. this after a #define \_M\_IX86 . what it means ? 3. any general guide for compiling c programs for windows(win32 api) through command line ? . explaining what all should be #defined ..etc.. I have googled a lot but most of the c compiling guidelines for win32 programs focus on vb .I wanna do it manually , on the command line. Thanks
2009/09/20
[ "https://Stackoverflow.com/questions/1451306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161179/" ]
Download the Windows PlatformSDK and it comes with its own command line compiler. It creates a shortcut Start->Programs->... to open a command prompt for either 32bit or 64bit. Select the 32bit variant and you get a fully initialized command prompt with compiler in your PATH and all INCLUDE, LIB and LIBPATH set. cmd> cl hello.c This should give you hello.exe. For more help on compiler "cl /?", for linker "link /?"
You can try gcc from [equation.com](http://www.equation.com/). It's a mingw wrapped compiler, but you don't have to worry about mingw: just download, install and use. There's no IDE either. The download page is at [<http://www.equation.com/servlet/equation.cmd?fa=fortran>](http://www.equation.com/servlet/equation.cmd?fa=fortran).
6,875,109
First of all: I want to use Java EE not Spring! I have some self defined annotations which are acting as interceptor bindings. I use the annotations on my methods like this: ```java @Logged @Secured @RequestParsed @ResultHandled public void doSomething() { // ... } ``` For some methods I want to use a single of these annotations but most methods I want to use like this: ```java @FunctionMethod public void doSomething() { // ... } ``` Can I bundle these set of annotations to a single one? I cannot write the code in a single interceptor because for some methods I want to use them seperately too. I know that there is a @Stereotype definition possible, but as far as I know, this is used to define a whole class not a single method.
2011/07/29
[ "https://Stackoverflow.com/questions/6875109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/868859/" ]
The `position: absolute;` and the `right:-100px;` is pushing your element past the right edge of the viewport. Floating does not affect absolutely positioned elements. If you want the element to be `100px` away from the edge, make that a positive `100px`. Or, if you want it right up against the edge, make it `0`. If you truly want to float it, remove the absolute positioning. Hopefully I understood the question, and I hope this helps! Edit: I re-read the question and think an even better solution would be to add `position: relative;` to the wrapper. Right now, your absolutely position element is positioned relative to the viewport. If you give `wrapper` relative positioning, it will cause `imageright` to be positioned relative to `wrapper`.
you *can* apply `overflow:hidden;` to the body, which is how you get what you're after, but it's highly inadvisable. Another way to take the div "out of flow" is to make it `position: fixed;` but that will mean it will be visible as you scroll down.
20,883,696
I'm using Sitecore Webforms For Marketers in a multi-language environment (e.g. .com, .be, .nl en .de). There are 3 servers: 2 Content Delivery Servers (CDS) en 1 Content Management Server (CMS). On the CDS servers is no possibility to write data, so i have configured a webservice to forward the form data from the CDS to the CMS server. My problem is that the Web service communicates with the .com domain. By using the .com domein for webservice communication, the CMS doesn't have any know how what the site context is from the submitting domain. For example, a user submits a form on the .nl domain, the CMS server thinks it's coming form the .com domain. Does anyone know how i can get the site context (e.g. NL-nl) from the submit? Thanks a lot! Jordy
2014/01/02
[ "https://Stackoverflow.com/questions/20883696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3129164/" ]
Similar question was asked [here](https://stackoverflow.com/questions/20800966/how-to-get-the-sitecore-current-site-object-inside-custom-save-action-wffm) and answered by [@TwentyGotoTen](https://stackoverflow.com/users/2124993/twentygototen). The place where you need to get the current site is different than in linked question, but the answer is the same. Use the code which is used by Sitecore to resolve site: ``` var url = System.Web.HttpContext.Current.Request.Url; var siteContext = Sitecore.Sites.SiteContextFactory.GetSiteContext(url.Host, url.PathAndQuery); ``` The extended version of the code for resolving sites (linked in the same question by [@MarkUrsino](https://stackoverflow.com/users/134360/mark-ursino)) can be found in article [Sitecore Context Site Resolution](http://firebreaksice.com/sitecore-context-site-resolution/). Can you use the proper domain for each web service call? If you have to call web service using `.com` domain only, maybe you can try to check `UrlReferrer` instead of current request `Url` host?
Update your web service to pass an extra parameter for the host name (via the CD clients) and then on the service (on your CM) get the context site from that.
20,883,696
I'm using Sitecore Webforms For Marketers in a multi-language environment (e.g. .com, .be, .nl en .de). There are 3 servers: 2 Content Delivery Servers (CDS) en 1 Content Management Server (CMS). On the CDS servers is no possibility to write data, so i have configured a webservice to forward the form data from the CDS to the CMS server. My problem is that the Web service communicates with the .com domain. By using the .com domein for webservice communication, the CMS doesn't have any know how what the site context is from the submitting domain. For example, a user submits a form on the .nl domain, the CMS server thinks it's coming form the .com domain. Does anyone know how i can get the site context (e.g. NL-nl) from the submit? Thanks a lot! Jordy
2014/01/02
[ "https://Stackoverflow.com/questions/20883696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3129164/" ]
Similar question was asked [here](https://stackoverflow.com/questions/20800966/how-to-get-the-sitecore-current-site-object-inside-custom-save-action-wffm) and answered by [@TwentyGotoTen](https://stackoverflow.com/users/2124993/twentygototen). The place where you need to get the current site is different than in linked question, but the answer is the same. Use the code which is used by Sitecore to resolve site: ``` var url = System.Web.HttpContext.Current.Request.Url; var siteContext = Sitecore.Sites.SiteContextFactory.GetSiteContext(url.Host, url.PathAndQuery); ``` The extended version of the code for resolving sites (linked in the same question by [@MarkUrsino](https://stackoverflow.com/users/134360/mark-ursino)) can be found in article [Sitecore Context Site Resolution](http://firebreaksice.com/sitecore-context-site-resolution/). Can you use the proper domain for each web service call? If you have to call web service using `.com` domain only, maybe you can try to check `UrlReferrer` instead of current request `Url` host?
I created for each domain a custom save action. This solves the problem.
20,883,696
I'm using Sitecore Webforms For Marketers in a multi-language environment (e.g. .com, .be, .nl en .de). There are 3 servers: 2 Content Delivery Servers (CDS) en 1 Content Management Server (CMS). On the CDS servers is no possibility to write data, so i have configured a webservice to forward the form data from the CDS to the CMS server. My problem is that the Web service communicates with the .com domain. By using the .com domein for webservice communication, the CMS doesn't have any know how what the site context is from the submitting domain. For example, a user submits a form on the .nl domain, the CMS server thinks it's coming form the .com domain. Does anyone know how i can get the site context (e.g. NL-nl) from the submit? Thanks a lot! Jordy
2014/01/02
[ "https://Stackoverflow.com/questions/20883696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3129164/" ]
I created for each domain a custom save action. This solves the problem.
Update your web service to pass an extra parameter for the host name (via the CD clients) and then on the service (on your CM) get the context site from that.
22,069,390
My Flash plugin just won't work for Firefox on Linux Mint. I am running Linux Mint 14 Nadia 64bit. * Downloaded firefox-27.0.1.tar.bz2 * Extracted it * Ran ./firefox it works fine * Downloaded install\_flash\_player\_11\_linux.x86\_64.tar.gz * Extracted it * Copied the plugin: **cp libflashplayer.so /home/gary/.mozilla/plugins/** * Copied the Flash Player Local Settings configurations: **sudo cp -r usr/\* /usr** * Generated dependency lists for Flash Player: **ldd /home/gary/.mozilla/plugins/libflashplayer.so** Plugin still doesn't work. Any help would be appreciated.
2014/02/27
[ "https://Stackoverflow.com/questions/22069390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2818846/" ]
Rather than delay initialising the whole page it would be better to allow it all to be initialised, then initialise just the new code. In jQm v1.3.2 and earlier you could do this by adding the following code to your success callback. ``` $('#newsDescription table').trigger('create'); ``` This will allow the whole page to initialise and prevent a flash of an unstyled page to the user if they have a slow network connection which could cause your ajax request to take a while.
I have put `$.mobile.initializePage();` inside success callback every thing works then.