qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
44,811,928 | I'm looking to make a method which detects if the following value in an array is a duplicate, and deletes it if so. It should work for both strings and integers.
For example, given the Array:
```
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
```
Return:
```
arr = ["A", "B", "C", "c", "A", "D"]
```
I tried creating an empty Array `a`, and shovelling the values in, providing the following value was not equal to the current one. I attempted this like so:
```
arr.each do |x|
following_value = arr.index(x) + 1
a << x unless x == arr[following_value]
end
```
Unfortunately, instead of shovelling one of the duplicate values into the array, it shovelled neither.
```
arr = ["A", "C", "c", "A"]
```
Can anybody help? Bonus points for telling me exactly what went wrong with my method.
Thanks! | 2017/06/28 | [
"https://Stackoverflow.com/questions/44811928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6831572/"
] | First at all, here is simpler solution:
```
> arr.delete_if.with_index { |e, ind| e == arr[ind+1] }
#=> ["A", "B", "C", "c", "A", "D"]
```
But, this solution will mutate `arr`.
Here are one-line solutions without mutates:
```
arr.each_with_index.with_object([]) { |(e, ind), res| res << e if e != arr[ind+1] }
arr.each_with_object([]) { |e, res| res << e if res.last != e }
```
Your problem in this line: `a << x unless x == arr[following_value]`
You say: put this `element` into `result` if `next element` isn't equal to it. So, instead, you can say something like: *put this element to result if the last element of the result isn't equal to it*:
```
arr.each do |x|
a << x unless a.last == x
end
``` | Here's a succinct alternative:
```
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
arr.chunk(&:itself).map(&:first)
# => ["A", "B", "C", "c", "A", "D"]
```
See it on repl.it: <https://repl.it/JGV4/1> |
44,811,928 | I'm looking to make a method which detects if the following value in an array is a duplicate, and deletes it if so. It should work for both strings and integers.
For example, given the Array:
```
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
```
Return:
```
arr = ["A", "B", "C", "c", "A", "D"]
```
I tried creating an empty Array `a`, and shovelling the values in, providing the following value was not equal to the current one. I attempted this like so:
```
arr.each do |x|
following_value = arr.index(x) + 1
a << x unless x == arr[following_value]
end
```
Unfortunately, instead of shovelling one of the duplicate values into the array, it shovelled neither.
```
arr = ["A", "C", "c", "A"]
```
Can anybody help? Bonus points for telling me exactly what went wrong with my method.
Thanks! | 2017/06/28 | [
"https://Stackoverflow.com/questions/44811928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6831572/"
] | First at all, here is simpler solution:
```
> arr.delete_if.with_index { |e, ind| e == arr[ind+1] }
#=> ["A", "B", "C", "c", "A", "D"]
```
But, this solution will mutate `arr`.
Here are one-line solutions without mutates:
```
arr.each_with_index.with_object([]) { |(e, ind), res| res << e if e != arr[ind+1] }
arr.each_with_object([]) { |e, res| res << e if res.last != e }
```
Your problem in this line: `a << x unless x == arr[following_value]`
You say: put this `element` into `result` if `next element` isn't equal to it. So, instead, you can say something like: *put this element to result if the last element of the result isn't equal to it*:
```
arr.each do |x|
a << x unless a.last == x
end
``` | Derived from [this](https://stackoverflow.com/a/44788219/5101493 "How do I find the first two consecutive elements in my array of numbers?") answer by [Cary Swoveland](https://stackoverflow.com/users/256970, "The Legend"):
```
def remove_consecs ar
enum = ar.each
loop.with_object([]) do |_, arr|
curr = enum.next
nxt = arr.last || enum.peek
arr << curr if curr != nxt
end
end
remove_consecs ["A", "B", "B", 'D', "C", "c", "A", "D", "D"]
#=> ["A", "B", "D", "C", "c", "A", "D"]
``` |
44,811,928 | I'm looking to make a method which detects if the following value in an array is a duplicate, and deletes it if so. It should work for both strings and integers.
For example, given the Array:
```
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
```
Return:
```
arr = ["A", "B", "C", "c", "A", "D"]
```
I tried creating an empty Array `a`, and shovelling the values in, providing the following value was not equal to the current one. I attempted this like so:
```
arr.each do |x|
following_value = arr.index(x) + 1
a << x unless x == arr[following_value]
end
```
Unfortunately, instead of shovelling one of the duplicate values into the array, it shovelled neither.
```
arr = ["A", "C", "c", "A"]
```
Can anybody help? Bonus points for telling me exactly what went wrong with my method.
Thanks! | 2017/06/28 | [
"https://Stackoverflow.com/questions/44811928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6831572/"
] | I would use [select](https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-select), so you could do something like:
```
a = ["A", "B", "B", "C", "c", "A", "D", "D"]
# without mutation
b = a.select.with_index { |e, i| a[i+1] != e }
a #=> ["A", "B", "B", "C", "c", "A", "D", "D"]
b #=> ["A", "B", "C", "c", "A", "D"]
# with mutation
a.select!.with_index { |e, i| a[i+1] != e }
a #=> ["A", "B", "C", "c", "A", "D"]
```
BTW your method is not working because `arr.index(x)` [returns index of first object for which block is true](https://apidock.com/ruby/Array/index):
```
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
arr.each do |x|
puts "#{x} has index #{arr.index(x)}"
end
A has index 0
B has index 1
B has index 1 # you were expecting 2
C has index 3
c has index 4
A has index 0 # you were expecting 5
D has index 6
D has index 6 # you were expecting 7
``` | Here's a succinct alternative:
```
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
arr.chunk(&:itself).map(&:first)
# => ["A", "B", "C", "c", "A", "D"]
```
See it on repl.it: <https://repl.it/JGV4/1> |
44,811,928 | I'm looking to make a method which detects if the following value in an array is a duplicate, and deletes it if so. It should work for both strings and integers.
For example, given the Array:
```
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
```
Return:
```
arr = ["A", "B", "C", "c", "A", "D"]
```
I tried creating an empty Array `a`, and shovelling the values in, providing the following value was not equal to the current one. I attempted this like so:
```
arr.each do |x|
following_value = arr.index(x) + 1
a << x unless x == arr[following_value]
end
```
Unfortunately, instead of shovelling one of the duplicate values into the array, it shovelled neither.
```
arr = ["A", "C", "c", "A"]
```
Can anybody help? Bonus points for telling me exactly what went wrong with my method.
Thanks! | 2017/06/28 | [
"https://Stackoverflow.com/questions/44811928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6831572/"
] | I would use [select](https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-select), so you could do something like:
```
a = ["A", "B", "B", "C", "c", "A", "D", "D"]
# without mutation
b = a.select.with_index { |e, i| a[i+1] != e }
a #=> ["A", "B", "B", "C", "c", "A", "D", "D"]
b #=> ["A", "B", "C", "c", "A", "D"]
# with mutation
a.select!.with_index { |e, i| a[i+1] != e }
a #=> ["A", "B", "C", "c", "A", "D"]
```
BTW your method is not working because `arr.index(x)` [returns index of first object for which block is true](https://apidock.com/ruby/Array/index):
```
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
arr.each do |x|
puts "#{x} has index #{arr.index(x)}"
end
A has index 0
B has index 1
B has index 1 # you were expecting 2
C has index 3
c has index 4
A has index 0 # you were expecting 5
D has index 6
D has index 6 # you were expecting 7
``` | Derived from [this](https://stackoverflow.com/a/44788219/5101493 "How do I find the first two consecutive elements in my array of numbers?") answer by [Cary Swoveland](https://stackoverflow.com/users/256970, "The Legend"):
```
def remove_consecs ar
enum = ar.each
loop.with_object([]) do |_, arr|
curr = enum.next
nxt = arr.last || enum.peek
arr << curr if curr != nxt
end
end
remove_consecs ["A", "B", "B", 'D', "C", "c", "A", "D", "D"]
#=> ["A", "B", "D", "C", "c", "A", "D"]
``` |
44,000,699 | In Wordpress editor (TinyMCE), whenever I switch between 'Visual' and 'Text' mode, all my HTML formatting gets removed. That includes tabs (indents) and line breaks. Sometimes, even elements and elements attributes are removed.
I searched a lot about this issue, wich is actually a pretty common problem for many users, but after browsing 10 pages of Google, I got nothing but a plugin called **[Preserved HTML Editor Markup Plus](https://wordpress.org/plugins/preserved-html-editor-markup-plus/)**. The problem is this **[plugin conflicts with Yoast SEO plugin](https://wordpress.org/support/topic/conflict-when-using-with-yoast-seo/)**.
Is there any thing I can do to preserve the HTML formatting, allowing both modes (Visual and Text) and not knowingly compromising other plugins? | 2017/05/16 | [
"https://Stackoverflow.com/questions/44000699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1301123/"
] | You should try TinyMCE Advanced Plugin.
[TinyMCE Advanced](https://wordpress.org/plugins/tinymce-advanced/) have set to Stop removing the `<p> and <br /> tags` when saving and show them in the HTML editor.
Try it after removing another editor plugin which you have installed to prevent conflict with other.
The second option is [Raw HTML](https://wordpress.org/plugins/raw-html/) plugin. It has also a good feature to prevent HTML formatting. You can use `[raw]` shortcode like `[raw] YOUR HTML [/raw]` to prevent HTML formating.
You can try this both plugin once. Hope one of from these option work for you.
Thanks. | Wordperss has **wp\_kses** function that only allow certain html tag in post content.
If you want to certain html tag / attributes allowed in your post content , you need to remove kses filter ( **kses\_remove\_filter** ) functions added in your theme / plugin.
**Reference**
<https://codex.wordpress.org/Function_Reference/wp_kses>
<https://developer.wordpress.org/reference/functions/kses_remove_filters/> |
26,225,066 | I have tried many options both in Mac and in Ubuntu.
I read the Rserve documentation
```
http://rforge.net/Rserve/doc.html
```
and that for the Rserve and RSclient packages:
<http://cran.r-project.org/web/packages/RSclient/RSclient.pdf>
<http://cran.r-project.org/web/packages/Rserve/Rserve.pdf>
I cannot figure out what is the correct workflow for opening/closing a connection within Rserve and for shutting down Rserve 'gracefully'.
For example, in Ubuntu, I installed R from source with the ./config --enable-R-shlib (following the Rserve documentation) and also added the 'control enable' line in /etc/Rserve.conf.
In an Ubuntu terminal:
```
library(Rserve)
library(RSclient)
Rserve()
c<-RS.connect()
c ## this is an Rserve QAP1 connection
## Trying to shutdown the server
RSshutdown(c)
Error in writeBin(as.integer....): invalid connection
RS.server.shutdown(c)
Error in RS.server.shutdown(c): command failed with satus code 0x4e: no control line present (control commands disabled or server shutdown)
```
I can, however, CLOSE the connection:
```
RS.close(c)
>NULL
c ## Closed Rserve connection
```
After closing the connection, I also tried the options (also tried with argument 'c', even though the connection is closed):
```
RS.server.shutdown()
RSshutdown()
```
So, my questions are:
1- How can I close Rserve gracefully?
2- Can Rserve be used without RSclient?
I also looked at
[How to Shutdown Rserve(), running in DEBUG](https://stackoverflow.com/questions/24004257/how-to-shutdown-rserve-running-in-debug)
but the question refers to the debug mode and is also unresolved. (I don't have enough reputation to comment/ask whether the shutdown works in the non-debug mode).
Also looked at:
[how to connect to Rserve with an R client](https://stackoverflow.com/questions/15314880/how-to-connect-to-rserve-with-an-r-client)
Thanks so much! | 2014/10/06 | [
"https://Stackoverflow.com/questions/26225066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3570398/"
] | Load Rserve and RSclient packages, then connect to the instances.
```
> library(Rserve)
> library(RSclient)
> Rserve(port = 6311, debug = FALSE)
> Rserve(port = 6312, debug = TRUE)
Starting Rserve...
"C:\..\Rserve.exe" --RS-port 6311
Starting Rserve...
"C:\..\Rserve_d.exe" --RS-port 6312
> rsc <- RSconnect(port = 6311)
> rscd <- RSconnect(port = 6312)
```
Looks like they're running...
```
> system('tasklist /FI "IMAGENAME eq Rserve.exe"')
> system('tasklist /FI "IMAGENAME eq Rserve_d.exe"')
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
Rserve.exe 8600 Console 1 39,312 K
Rserve_d.exe 12652 Console 1 39,324 K
```
Let's shut 'em down.
```
> RSshutdown(rsc)
> RSshutdown(rscd)
```
And they're gone...
```
> system('tasklist /FI "IMAGENAME eq Rserve.exe"')
> system('tasklist /FI "IMAGENAME eq Rserve_d.exe"')
INFO: No tasks are running which match the specified criteria.
```
Rserve can be used w/o RSclient by starting it with args and/or a config script. Then you can connect to it from some other program (like Tableau) or with your own code. RSclient provides a way to pass commands/data to Rserve from an instance of R.
Hope this helps :) | On a Windows system, if you want to close an `RServe` instance, you can use the `system` function in `R` to close it down.
For example in `R`:
```
library(Rserve)
Rserve() # run without any arguments or ports specified
system('tasklist /FI "IMAGENAME eq Rserve.exe"') # run this to see RServe instances and their PIDs
system('TASKKILL /PID {yourPID} /F') # run this to kill off the RServe instance with your selected PID
```
If you have closed your RServe instance with that PID correctly, the following message will appear:
>
> SUCCESS: The process with PID xxxx has been terminated.
>
>
>
You can check the RServe instance has been closed down by entering
`system('tasklist /FI "IMAGENAME eq Rserve.exe"')`
again. If there are no RServe instances running any more, you will get the message
>
> INFO: No tasks are running which match the specified criteria.
>
>
>
More help and info on this topic can be seen in [this related question](https://stackoverflow.com/questions/27066588/rserve-server-how-to-terminate-a-blocking-instance-eval-taking-forever?rq=1).
Note that the 'RSClient' approach mentioned in an earlier answer is tidier and easier than this one, but I put it forward anyway for those who start `RServe` without knowing how to stop it. |
26,225,066 | I have tried many options both in Mac and in Ubuntu.
I read the Rserve documentation
```
http://rforge.net/Rserve/doc.html
```
and that for the Rserve and RSclient packages:
<http://cran.r-project.org/web/packages/RSclient/RSclient.pdf>
<http://cran.r-project.org/web/packages/Rserve/Rserve.pdf>
I cannot figure out what is the correct workflow for opening/closing a connection within Rserve and for shutting down Rserve 'gracefully'.
For example, in Ubuntu, I installed R from source with the ./config --enable-R-shlib (following the Rserve documentation) and also added the 'control enable' line in /etc/Rserve.conf.
In an Ubuntu terminal:
```
library(Rserve)
library(RSclient)
Rserve()
c<-RS.connect()
c ## this is an Rserve QAP1 connection
## Trying to shutdown the server
RSshutdown(c)
Error in writeBin(as.integer....): invalid connection
RS.server.shutdown(c)
Error in RS.server.shutdown(c): command failed with satus code 0x4e: no control line present (control commands disabled or server shutdown)
```
I can, however, CLOSE the connection:
```
RS.close(c)
>NULL
c ## Closed Rserve connection
```
After closing the connection, I also tried the options (also tried with argument 'c', even though the connection is closed):
```
RS.server.shutdown()
RSshutdown()
```
So, my questions are:
1- How can I close Rserve gracefully?
2- Can Rserve be used without RSclient?
I also looked at
[How to Shutdown Rserve(), running in DEBUG](https://stackoverflow.com/questions/24004257/how-to-shutdown-rserve-running-in-debug)
but the question refers to the debug mode and is also unresolved. (I don't have enough reputation to comment/ask whether the shutdown works in the non-debug mode).
Also looked at:
[how to connect to Rserve with an R client](https://stackoverflow.com/questions/15314880/how-to-connect-to-rserve-with-an-r-client)
Thanks so much! | 2014/10/06 | [
"https://Stackoverflow.com/questions/26225066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3570398/"
] | Load Rserve and RSclient packages, then connect to the instances.
```
> library(Rserve)
> library(RSclient)
> Rserve(port = 6311, debug = FALSE)
> Rserve(port = 6312, debug = TRUE)
Starting Rserve...
"C:\..\Rserve.exe" --RS-port 6311
Starting Rserve...
"C:\..\Rserve_d.exe" --RS-port 6312
> rsc <- RSconnect(port = 6311)
> rscd <- RSconnect(port = 6312)
```
Looks like they're running...
```
> system('tasklist /FI "IMAGENAME eq Rserve.exe"')
> system('tasklist /FI "IMAGENAME eq Rserve_d.exe"')
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
Rserve.exe 8600 Console 1 39,312 K
Rserve_d.exe 12652 Console 1 39,324 K
```
Let's shut 'em down.
```
> RSshutdown(rsc)
> RSshutdown(rscd)
```
And they're gone...
```
> system('tasklist /FI "IMAGENAME eq Rserve.exe"')
> system('tasklist /FI "IMAGENAME eq Rserve_d.exe"')
INFO: No tasks are running which match the specified criteria.
```
Rserve can be used w/o RSclient by starting it with args and/or a config script. Then you can connect to it from some other program (like Tableau) or with your own code. RSclient provides a way to pass commands/data to Rserve from an instance of R.
Hope this helps :) | If you are not able to shut it down within R, run the codes below to kill it in terminal. These codes work on Mac.
```
$ ps ax | grep Rserve # get active Rserve sessions
```
You will see outputs like below. 29155 is job id of the active Rserve session.
```
29155 /Users/userid/Library/R/3.5/library/Rserve/libs/Rserve
38562 0:00.00 grep Rserve
```
Then run
```
$ kill 29155
``` |
26,225,066 | I have tried many options both in Mac and in Ubuntu.
I read the Rserve documentation
```
http://rforge.net/Rserve/doc.html
```
and that for the Rserve and RSclient packages:
<http://cran.r-project.org/web/packages/RSclient/RSclient.pdf>
<http://cran.r-project.org/web/packages/Rserve/Rserve.pdf>
I cannot figure out what is the correct workflow for opening/closing a connection within Rserve and for shutting down Rserve 'gracefully'.
For example, in Ubuntu, I installed R from source with the ./config --enable-R-shlib (following the Rserve documentation) and also added the 'control enable' line in /etc/Rserve.conf.
In an Ubuntu terminal:
```
library(Rserve)
library(RSclient)
Rserve()
c<-RS.connect()
c ## this is an Rserve QAP1 connection
## Trying to shutdown the server
RSshutdown(c)
Error in writeBin(as.integer....): invalid connection
RS.server.shutdown(c)
Error in RS.server.shutdown(c): command failed with satus code 0x4e: no control line present (control commands disabled or server shutdown)
```
I can, however, CLOSE the connection:
```
RS.close(c)
>NULL
c ## Closed Rserve connection
```
After closing the connection, I also tried the options (also tried with argument 'c', even though the connection is closed):
```
RS.server.shutdown()
RSshutdown()
```
So, my questions are:
1- How can I close Rserve gracefully?
2- Can Rserve be used without RSclient?
I also looked at
[How to Shutdown Rserve(), running in DEBUG](https://stackoverflow.com/questions/24004257/how-to-shutdown-rserve-running-in-debug)
but the question refers to the debug mode and is also unresolved. (I don't have enough reputation to comment/ask whether the shutdown works in the non-debug mode).
Also looked at:
[how to connect to Rserve with an R client](https://stackoverflow.com/questions/15314880/how-to-connect-to-rserve-with-an-r-client)
Thanks so much! | 2014/10/06 | [
"https://Stackoverflow.com/questions/26225066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3570398/"
] | On a Windows system, if you want to close an `RServe` instance, you can use the `system` function in `R` to close it down.
For example in `R`:
```
library(Rserve)
Rserve() # run without any arguments or ports specified
system('tasklist /FI "IMAGENAME eq Rserve.exe"') # run this to see RServe instances and their PIDs
system('TASKKILL /PID {yourPID} /F') # run this to kill off the RServe instance with your selected PID
```
If you have closed your RServe instance with that PID correctly, the following message will appear:
>
> SUCCESS: The process with PID xxxx has been terminated.
>
>
>
You can check the RServe instance has been closed down by entering
`system('tasklist /FI "IMAGENAME eq Rserve.exe"')`
again. If there are no RServe instances running any more, you will get the message
>
> INFO: No tasks are running which match the specified criteria.
>
>
>
More help and info on this topic can be seen in [this related question](https://stackoverflow.com/questions/27066588/rserve-server-how-to-terminate-a-blocking-instance-eval-taking-forever?rq=1).
Note that the 'RSClient' approach mentioned in an earlier answer is tidier and easier than this one, but I put it forward anyway for those who start `RServe` without knowing how to stop it. | If you are not able to shut it down within R, run the codes below to kill it in terminal. These codes work on Mac.
```
$ ps ax | grep Rserve # get active Rserve sessions
```
You will see outputs like below. 29155 is job id of the active Rserve session.
```
29155 /Users/userid/Library/R/3.5/library/Rserve/libs/Rserve
38562 0:00.00 grep Rserve
```
Then run
```
$ kill 29155
``` |
14,016,192 | >
> **Possible Duplicate:**
>
> [Ideal way to cancel an executing AsyncTask](https://stackoverflow.com/questions/2735102/ideal-way-to-cancel-an-executing-asynctask)
>
>
>
When I developed an Android application, I used an `AsyncTask` to download something, I used a `progressDialog` to show the progress of this AsyncTask, now **When I press the back button, I want to cancel this AsycTask**, I invoked the `AsycTask.cancel()`, but it doesn't work. How can I cancel a running AsyncTask ? | 2012/12/24 | [
"https://Stackoverflow.com/questions/14016192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1685245/"
] | The most correct way to do it would be to check periodically inside `doInBackground` if the task was cancelled (i.e. by calling `isCancelled`). From <http://developer.android.com/reference/android/os/AsyncTask.html>:
**Cancelling a task :**
A task can be cancelled at any time by invoking
`cancel(boolean)`. Invoking this method will cause subsequent calls to
`isCancelled()` to return `true`. After invoking this method,
`onCancelled(Object)`, instead of `onPostExecute(Object)` will be invoked
after `doInBackground(Object[])` returns. To ensure that a task is
cancelled as quickly as possible, you should always check the return
value of isCancelled() periodically from `doInBackground(Object[])`, if
possible (inside a loop for instance.)
Check also this blog post if you need more information: <http://vikaskanani.wordpress.com/2011/08/03/android-proper-way-to-cancel-asynctask/> | do the following on click of back button:
declare your Aynctask as global variable like this:
```
//AysncTask class
private contactListAsync async;
if(async != null){
async.cancel(true);
async= null;
}
``` |
14,016,192 | >
> **Possible Duplicate:**
>
> [Ideal way to cancel an executing AsyncTask](https://stackoverflow.com/questions/2735102/ideal-way-to-cancel-an-executing-asynctask)
>
>
>
When I developed an Android application, I used an `AsyncTask` to download something, I used a `progressDialog` to show the progress of this AsyncTask, now **When I press the back button, I want to cancel this AsycTask**, I invoked the `AsycTask.cancel()`, but it doesn't work. How can I cancel a running AsyncTask ? | 2012/12/24 | [
"https://Stackoverflow.com/questions/14016192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1685245/"
] | ```
class ImplementAsynctask extends AsyncTask implements OnDismissListener{
ProgressDialog dialog = new ProgressDialog(ActivityName.this);
protected onPreExecute() {
//do something and show progress dialog
}
protected onPostExecute() {
//cancel dialog after completion
}
@Override
public void onDismiss(DialogInterface dialog) {
//cancel AsycTask in between.
this.cancel(true);
}
};
``` | do the following on click of back button:
declare your Aynctask as global variable like this:
```
//AysncTask class
private contactListAsync async;
if(async != null){
async.cancel(true);
async= null;
}
``` |
23,309,861 | I'm new to android and am not familiar with using asynctask, I am performing login into my webservice but it fails on trying to read the inputstream on the line
```
InputStream in = urlConnection.getInputStream();
```
here's my code:
```
package com.test.connector;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import android.content.Context;
import android.os.AsyncTask;
public class TestConnection extends AsyncTask<String, String, String> {
static InputStream firstCertificate = null;
static InputStream secondCertificate = null;
static InputStream thirdCertificate = null;
private static String htmlString;
public void passCertificates(Context c){
c.getAssets();
try {
firstCertificate = c.getAssets().open("certificate1.crt");
} catch (IOException e) {
e.printStackTrace();
}
try {
secondCertificate=c.getAssets().open("certificate2.crt");
} catch (IOException e) {
e.printStackTrace();
}
try {
thirdCertificate=c.getAssets().open("certificate3");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(String... params) {
String webHtmlData=null;
String inpUrl=params[0];
final String username=params[1];
final String password=params[2];
CertificateFactory cf = null;
try {
cf = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
e.printStackTrace();
}
Certificate ca1 = null;
Certificate ca2 = null;
Certificate ca3 = null;
try {
ca1 = cf.generateCertificate(firstCertificate);
ca2 = cf.generateCertificate(secondCertificate);
ca3 = cf.generateCertificate(thirdCertificate);
} catch (CertificateException e) {
e.printStackTrace();
}
finally {
try {
firstCertificate.close();
secondCertificate.close();
thirdCertificate.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(keyStoreType);
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
keyStore.load(null, null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
keyStore.setCertificateEntry("ca1", ca1);
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
keyStore.load(null, null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
keyStore.setCertificateEntry("ca2", ca2);
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
keyStore.load(null, null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
keyStore.setCertificateEntry("ca3", ca3);
} catch (KeyStoreException e) {
e.printStackTrace();
}
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = null;
try {
tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
tmf.init(keyStore);
} catch (KeyStoreException e) {
e.printStackTrace();
}
// Create an SSLContext that uses our TrustManager
SSLContext context = null;
try {
context = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
context.init(null, tmf.getTrustManagers(), null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
//authentication credentials
Authenticator myAuth = new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password.toCharArray());
}
};
Authenticator.setDefault(myAuth);
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = null;
try {
url = new URL(inpUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpsURLConnection urlConnection = null;
try {
urlConnection = (HttpsURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.setSSLSocketFactory(context.getSocketFactory());
try {
InputStream in = urlConnection.getInputStream();// my code fails here
webHtmlData=readStream(in);
} catch (IOException e) {
e.printStackTrace();
}
return webHtmlData;
}
public String readStream(InputStream in) {
StringBuilder response = null;
try {
BufferedReader is =
new BufferedReader(new InputStreamReader(in));
String inputLine;
response = new StringBuilder();
while ((inputLine = is.readLine()) != null) {
response.append(inputLine);
}
is.close();
}
catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
```
I'm executing doInBackground by using the following command through the mainActivity class
```
TestConnection tc=new TestConnection;
tc.passCertificates(this);
String[] param[]={"example.com","username","password"}
tc.doInBackground(param);
```
but the same code works as a java application without the asyncTask.
here's my Logcat
```
04-26 07:30:03.535: D/dalvikvm(1446): GC_FOR_ALLOC freed 37K, 4% free 2949K/3064K, paused 47ms, total 50ms
04-26 07:30:03.535: I/dalvikvm-heap(1446): Grow heap (frag case) to 3.558MB for 635812-byte allocation
04-26 07:30:03.585: D/dalvikvm(1446): GC_FOR_ALLOC freed 2K, 4% free 3567K/3688K, paused 40ms, total 40ms
04-26 07:30:03.935: W/System.err(1446): android.os.NetworkOnMainThreadException
04-26 07:30:03.945: W/System.err(1446): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
04-26 07:30:03.945: W/System.err(1446): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
04-26 07:30:03.955: W/System.err(1446): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-26 07:30:03.955: W/System.err(1446): at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-26 07:30:03.955: W/System.err(1446): at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
04-26 07:30:03.955: W/System.err(1446): at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:246)
04-26 07:30:03.965: W/System.err(1446): at com.ovid.connector.Connector.downloadWebData(Connector.java:209)
04-26 07:30:03.965: W/System.err(1446): at com.ovid.connector.Connector.doInBackground(Connector.java:245)
04-26 07:30:03.965: W/System.err(1446): at com.ovid.connector.Connector.connectAndGetHtmlData(Connector.java:48)
04-26 07:30:03.965: W/System.err(1446): at com.ovid.expandablelistview.MainActivity.onCreate(MainActivity.java:70)
04-26 07:30:03.965: W/System.err(1446): at android.app.Activity.performCreate(Activity.java:5231)
04-26 07:30:03.965: W/System.err(1446): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-26 07:30:03.965: W/System.err(1446): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 07:30:03.965: W/System.err(1446): at android.os.Looper.loop(Looper.java:136)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-26 07:30:03.995: W/System.err(1446): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 07:30:03.995: W/System.err(1446): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 07:30:03.995: W/System.err(1446): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-26 07:30:03.995: W/System.err(1446): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-26 07:30:03.995: W/System.err(1446): at dalvik.system.NativeStart.main(Native Method)
04-26 07:30:04.035: D/AndroidRuntime(1446): Shutting down VM
04-26 07:30:04.035: W/dalvikvm(1446): threadid=1: thread exiting with uncaught exception (group=0xb2ae0ba8)
04-26 07:30:04.055: E/AndroidRuntime(1446): FATAL EXCEPTION: main
04-26 07:30:04.055: E/AndroidRuntime(1446): Process: com.example.expandablelistview, PID: 1446
04-26 07:30:04.055: E/AndroidRuntime(1446): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.expandablelistview/com.ovid.expandablelistview.MainActivity}: java.lang.IllegalArgumentException: String input must not be null
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.os.Looper.loop(Looper.java:136)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-26 07:30:04.055: E/AndroidRuntime(1446): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 07:30:04.055: E/AndroidRuntime(1446): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 07:30:04.055: E/AndroidRuntime(1446): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-26 07:30:04.055: E/AndroidRuntime(1446): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-26 07:30:04.055: E/AndroidRuntime(1446): at dalvik.system.NativeStart.main(Native Method)
04-26 07:30:04.055: E/AndroidRuntime(1446): Caused by: java.lang.IllegalArgumentException: String input must not be null
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.helper.Validate.notNull(Validate.java:26)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.parser.TreeBuilder.initialiseParse(TreeBuilder.java:24)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.parser.TreeBuilder.parse(TreeBuilder.java:40)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.parser.HtmlTreeBuilder.parse(HtmlTreeBuilder.java:54)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.parser.Parser.parse(Parser.java:90)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.Jsoup.parse(Jsoup.java:58)
04-26 07:30:04.055: E/AndroidRuntime(1446): at com.ovid.utils.ListProvider.getJournalName(ListProvider.java:15)
04-26 07:30:04.055: E/AndroidRuntime(1446): at com.ovid.expandablelistview.MainActivity.onCreate(MainActivity.java:73)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.Activity.performCreate(Activity.java:5231)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-26 07:30:04.055: E/AndroidRuntime(1446): ... 11 more
``` | 2014/04/26 | [
"https://Stackoverflow.com/questions/23309861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3556095/"
] | Try this..
```
new TestConnection().execute();
``` | ```
new TestConnection().execute(params);
```
and in extend line,
```
AsyncTask<String[],Void,String>
``` |
23,309,861 | I'm new to android and am not familiar with using asynctask, I am performing login into my webservice but it fails on trying to read the inputstream on the line
```
InputStream in = urlConnection.getInputStream();
```
here's my code:
```
package com.test.connector;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import android.content.Context;
import android.os.AsyncTask;
public class TestConnection extends AsyncTask<String, String, String> {
static InputStream firstCertificate = null;
static InputStream secondCertificate = null;
static InputStream thirdCertificate = null;
private static String htmlString;
public void passCertificates(Context c){
c.getAssets();
try {
firstCertificate = c.getAssets().open("certificate1.crt");
} catch (IOException e) {
e.printStackTrace();
}
try {
secondCertificate=c.getAssets().open("certificate2.crt");
} catch (IOException e) {
e.printStackTrace();
}
try {
thirdCertificate=c.getAssets().open("certificate3");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(String... params) {
String webHtmlData=null;
String inpUrl=params[0];
final String username=params[1];
final String password=params[2];
CertificateFactory cf = null;
try {
cf = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
e.printStackTrace();
}
Certificate ca1 = null;
Certificate ca2 = null;
Certificate ca3 = null;
try {
ca1 = cf.generateCertificate(firstCertificate);
ca2 = cf.generateCertificate(secondCertificate);
ca3 = cf.generateCertificate(thirdCertificate);
} catch (CertificateException e) {
e.printStackTrace();
}
finally {
try {
firstCertificate.close();
secondCertificate.close();
thirdCertificate.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(keyStoreType);
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
keyStore.load(null, null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
keyStore.setCertificateEntry("ca1", ca1);
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
keyStore.load(null, null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
keyStore.setCertificateEntry("ca2", ca2);
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
keyStore.load(null, null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
keyStore.setCertificateEntry("ca3", ca3);
} catch (KeyStoreException e) {
e.printStackTrace();
}
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = null;
try {
tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
tmf.init(keyStore);
} catch (KeyStoreException e) {
e.printStackTrace();
}
// Create an SSLContext that uses our TrustManager
SSLContext context = null;
try {
context = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
context.init(null, tmf.getTrustManagers(), null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
//authentication credentials
Authenticator myAuth = new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password.toCharArray());
}
};
Authenticator.setDefault(myAuth);
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = null;
try {
url = new URL(inpUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpsURLConnection urlConnection = null;
try {
urlConnection = (HttpsURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.setSSLSocketFactory(context.getSocketFactory());
try {
InputStream in = urlConnection.getInputStream();// my code fails here
webHtmlData=readStream(in);
} catch (IOException e) {
e.printStackTrace();
}
return webHtmlData;
}
public String readStream(InputStream in) {
StringBuilder response = null;
try {
BufferedReader is =
new BufferedReader(new InputStreamReader(in));
String inputLine;
response = new StringBuilder();
while ((inputLine = is.readLine()) != null) {
response.append(inputLine);
}
is.close();
}
catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
```
I'm executing doInBackground by using the following command through the mainActivity class
```
TestConnection tc=new TestConnection;
tc.passCertificates(this);
String[] param[]={"example.com","username","password"}
tc.doInBackground(param);
```
but the same code works as a java application without the asyncTask.
here's my Logcat
```
04-26 07:30:03.535: D/dalvikvm(1446): GC_FOR_ALLOC freed 37K, 4% free 2949K/3064K, paused 47ms, total 50ms
04-26 07:30:03.535: I/dalvikvm-heap(1446): Grow heap (frag case) to 3.558MB for 635812-byte allocation
04-26 07:30:03.585: D/dalvikvm(1446): GC_FOR_ALLOC freed 2K, 4% free 3567K/3688K, paused 40ms, total 40ms
04-26 07:30:03.935: W/System.err(1446): android.os.NetworkOnMainThreadException
04-26 07:30:03.945: W/System.err(1446): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
04-26 07:30:03.945: W/System.err(1446): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
04-26 07:30:03.955: W/System.err(1446): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-26 07:30:03.955: W/System.err(1446): at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-26 07:30:03.955: W/System.err(1446): at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
04-26 07:30:03.955: W/System.err(1446): at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
04-26 07:30:03.965: W/System.err(1446): at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:246)
04-26 07:30:03.965: W/System.err(1446): at com.ovid.connector.Connector.downloadWebData(Connector.java:209)
04-26 07:30:03.965: W/System.err(1446): at com.ovid.connector.Connector.doInBackground(Connector.java:245)
04-26 07:30:03.965: W/System.err(1446): at com.ovid.connector.Connector.connectAndGetHtmlData(Connector.java:48)
04-26 07:30:03.965: W/System.err(1446): at com.ovid.expandablelistview.MainActivity.onCreate(MainActivity.java:70)
04-26 07:30:03.965: W/System.err(1446): at android.app.Activity.performCreate(Activity.java:5231)
04-26 07:30:03.965: W/System.err(1446): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-26 07:30:03.965: W/System.err(1446): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 07:30:03.965: W/System.err(1446): at android.os.Looper.loop(Looper.java:136)
04-26 07:30:03.965: W/System.err(1446): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-26 07:30:03.995: W/System.err(1446): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 07:30:03.995: W/System.err(1446): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 07:30:03.995: W/System.err(1446): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-26 07:30:03.995: W/System.err(1446): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-26 07:30:03.995: W/System.err(1446): at dalvik.system.NativeStart.main(Native Method)
04-26 07:30:04.035: D/AndroidRuntime(1446): Shutting down VM
04-26 07:30:04.035: W/dalvikvm(1446): threadid=1: thread exiting with uncaught exception (group=0xb2ae0ba8)
04-26 07:30:04.055: E/AndroidRuntime(1446): FATAL EXCEPTION: main
04-26 07:30:04.055: E/AndroidRuntime(1446): Process: com.example.expandablelistview, PID: 1446
04-26 07:30:04.055: E/AndroidRuntime(1446): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.expandablelistview/com.ovid.expandablelistview.MainActivity}: java.lang.IllegalArgumentException: String input must not be null
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.os.Looper.loop(Looper.java:136)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-26 07:30:04.055: E/AndroidRuntime(1446): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 07:30:04.055: E/AndroidRuntime(1446): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 07:30:04.055: E/AndroidRuntime(1446): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-26 07:30:04.055: E/AndroidRuntime(1446): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-26 07:30:04.055: E/AndroidRuntime(1446): at dalvik.system.NativeStart.main(Native Method)
04-26 07:30:04.055: E/AndroidRuntime(1446): Caused by: java.lang.IllegalArgumentException: String input must not be null
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.helper.Validate.notNull(Validate.java:26)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.parser.TreeBuilder.initialiseParse(TreeBuilder.java:24)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.parser.TreeBuilder.parse(TreeBuilder.java:40)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.parser.HtmlTreeBuilder.parse(HtmlTreeBuilder.java:54)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.parser.Parser.parse(Parser.java:90)
04-26 07:30:04.055: E/AndroidRuntime(1446): at org.jsoup.Jsoup.parse(Jsoup.java:58)
04-26 07:30:04.055: E/AndroidRuntime(1446): at com.ovid.utils.ListProvider.getJournalName(ListProvider.java:15)
04-26 07:30:04.055: E/AndroidRuntime(1446): at com.ovid.expandablelistview.MainActivity.onCreate(MainActivity.java:73)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.Activity.performCreate(Activity.java:5231)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 07:30:04.055: E/AndroidRuntime(1446): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-26 07:30:04.055: E/AndroidRuntime(1446): ... 11 more
``` | 2014/04/26 | [
"https://Stackoverflow.com/questions/23309861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3556095/"
] | Overload `onPostExecute` method of `AsyncTask`. And call `tc.execute()` instead of `tc.doInBackground()`:
```
@Override
protected void onPostExecute(Void result) {
//Move your code of reading inputStream here
}
```
`execute()` calls `doInBackground` and the `onPostEcecute` gets called. | ```
new TestConnection().execute(params);
```
and in extend line,
```
AsyncTask<String[],Void,String>
``` |
42,540,991 | I'm trying to make a shell "bosh>" which takes in Unix commands and keep getting a bad address error. I know my code reads in the commands and parses them but for some reason, I cannot get them to execute, instead, I get a "bad address" error.
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#define MAX_LINE 128
#define MAX_ARGS 10
int main(){
pid_t pid;
char command[MAX_LINE]; /*command line buffer*/
char *commandArgs[MAX_ARGS]; /*command line arg*/
int i;
char *sPtr=strtok(command," ");
int n=0;
printf("bosh>");
fgets(command, MAX_LINE-1,stdin);
command[strlen(command)-1]='\0';
while(strcmp(command,"quit")!=0)
{
n=0;
sPtr=strtok(command," ");
while(sPtr&&n<MAX_ARGS)
{
sPtr=strtok(NULL," ");
n++;
}
commandArgs[0]=malloc(strlen(command)+1);
strcpy(commandArgs[0],command);
if(fork()==0)
{
execvp(commandArgs[0],commandArgs);
perror("execvp failed");
exit(2);
}
pid=wait(NULL);
printf("%s",">" );
fgets(command, MAX_LINE-1,stdin);
command[strlen(command)-1]='\0';
}
printf("Command (%d) done\n", pid);
return 0;
}
``` | 2017/03/01 | [
"https://Stackoverflow.com/questions/42540991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7643500/"
] | These two lines are the culprit:
```
commandArgs[0]=malloc(strlen(command)+1);
strcpy(commandArgs[0],command);
```
First of all, `malloc(strlen(...))` followed by `strcpy` is what the POSIX function [`strdup`](https://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c) already does. But then, you don't need to even copy the string - it is enough to just store the pointer to the original string into `commandArgs[0]`:
```
commandArgs[0] = command;
```
But then, how does [`execvp`](https://linux.die.net/man/3/execvp) how many arguments the command is going to take? If you read the manuals carefully, they'd say something like:
>
> The `execv()`, `execvp()`, and `execvpe()` functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. ***The array of pointers* MUST *be terminated by a NULL pointer.***
>
>
>
Your argument array is not NULL-terminated. To fix it, use
```
commandArgs[0] = command;
commandArgs[1] = NULL; // !!!!
```
---
(Then you'd notice that you'd actually want to assign the arguments *within* the `strtok` parsing loop, so that you can actually assign all of the arguments into the `commandArgs` array; and compile with all warnings enabled and address those, and so forth). | You initialize `sPtr` in its declaration, which you do not need to do because you never use the initial value. But the initialization produces undefined behavior because it depends on the contents of the `command` array, which at that point are indeterminate.
The array passed as the second argument to `execvp()` is expected to contain a NULL pointer after the last argument. You do not ensure that yours does.
You furthermore appear to drop all arguments to the input command by failing to assign tokens to `commandArgs[]`. After tokenizing you do copy the first token (only) and assign the copy to the first element of `commandArgs`, but any other tokens are ignored. |
19,461,360 | I am a complete Haskell n00b, but I would like to define a new data type that is simple a list of numbers. How would I go about doing this? I've read Haskell wikibook on type declarations, as well as other online resources, but I cannot seem to figure it out. Here is, in essence, what I've tried:
```
type NumList = [Num]
```
That didn't work, so how can I do this? Thanks for the help. | 2013/10/19 | [
"https://Stackoverflow.com/questions/19461360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887128/"
] | `Num` is a class, not a type. Choose a type instead; e.g. `Integer` or `Rational` are probably good choices.
```
type NumList = [Integer]
```
However, this does *not* create a new type; it just creates a new name for an old type. If you actually want a new type, you can use `newtype`, as in
```
newtype NumList = MkNumList [Integer]
```
which defines a new type named `NumList` and a new data constructor named `MkNumList`. | There is several answers depending on your exact need. If you just want a list of number for specific applications you probably know what exact type of numbers you'll use in this case and should just use :
```
type DoubleList = [Double]
```
(With a more explicit name I hope since DoubleList presents no advantage whatsoever compared to [Double])
If you want to force every function that use NumList to use a `Num a` context (but it won't be automatic which is why this method is deprecated) you can use :
```
data Num a => NumList a = NL [a]
```
though that's probably a bad idea, it doesn't bring you anything over the use of `(Num a) => ...[a]....` in your code.
If you don't care what exact type of numbers is in your list, only that you can make operations between them (but not between two NumList), you can use existential types :
```
data NumList = forall a . (Num a) => NL [a]
```
This is most analogous to objects though with type erasure and no reflexion you won't be able to do much with your NumList (that can be added but by this point I'm pretty sure you're just piling difficulties you don't need just because you're trying to write Java/C++/Other in Haskell).
Note that if you want to create Num instances for list of numbers, you could just do :
```
instance (Num a) => Num [a] where ...
```
My ultimate recommendation would really be to use `[a]` with the appropriate `Num a` context but should you believe that to be erroneous you'll have to give more details on your use of this type if you are to receive further guidance. |
19,461,360 | I am a complete Haskell n00b, but I would like to define a new data type that is simple a list of numbers. How would I go about doing this? I've read Haskell wikibook on type declarations, as well as other online resources, but I cannot seem to figure it out. Here is, in essence, what I've tried:
```
type NumList = [Num]
```
That didn't work, so how can I do this? Thanks for the help. | 2013/10/19 | [
"https://Stackoverflow.com/questions/19461360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887128/"
] | The `type` keyword is just for type synonyms (new names of types that already exist), so you can't use a class like `Num`.
Instead, you might use the `data` keyword together with Haskell's context notation:
```
data Num a => NumList a = NumList [a]
```
Except when I try that in ghci, it scolds me because [datatype contexts are deprecated](https://stackoverflow.com/questions/7438600/datatypecontexts-deprecated-in-latest-ghc-why). Apparently you're better off using a GADT. Perhaps something like:
```
data NumList a where
Empty :: Num a => NumList a
Singleton :: Num a => a -> NumList a
Append :: Num a => NumList a -> NumList a -> NumList a
``` | There is several answers depending on your exact need. If you just want a list of number for specific applications you probably know what exact type of numbers you'll use in this case and should just use :
```
type DoubleList = [Double]
```
(With a more explicit name I hope since DoubleList presents no advantage whatsoever compared to [Double])
If you want to force every function that use NumList to use a `Num a` context (but it won't be automatic which is why this method is deprecated) you can use :
```
data Num a => NumList a = NL [a]
```
though that's probably a bad idea, it doesn't bring you anything over the use of `(Num a) => ...[a]....` in your code.
If you don't care what exact type of numbers is in your list, only that you can make operations between them (but not between two NumList), you can use existential types :
```
data NumList = forall a . (Num a) => NL [a]
```
This is most analogous to objects though with type erasure and no reflexion you won't be able to do much with your NumList (that can be added but by this point I'm pretty sure you're just piling difficulties you don't need just because you're trying to write Java/C++/Other in Haskell).
Note that if you want to create Num instances for list of numbers, you could just do :
```
instance (Num a) => Num [a] where ...
```
My ultimate recommendation would really be to use `[a]` with the appropriate `Num a` context but should you believe that to be erroneous you'll have to give more details on your use of this type if you are to receive further guidance. |
184,785 | I'm new to Drupal Commerce.
I have created new product type and added custom fields everything and it's working fine.
I want to theme the Add a Product (form page). Please suggest me how to do that.
Thanks,
Selva | 2015/12/23 | [
"https://drupal.stackexchange.com/questions/184785",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/55616/"
] | It depends what part of the page you want to theme, simple CSS, change the layout, or adjust the form.
To add CSS, you could attach your CSS file in `hook_page_build` for that path.
To change the page template, you could override the `page.tpl.php` file as `page--node--add--product.tpl.php`
You could also set a custom template in `hook_preprocess_page` by checking for the relevant path and setting `theme_hook_suggestions` to your template (e.g node/add/product and node/[nid]/edit)
Another option is using `hook_custom_theme` to specify a whole new theme for that specific path.
Lastly, you can theme the form itself using `hook_form_alter` and using either a template for the form, or adjusting the form elements there. | If you are afraid of codes, download the module "themekey" and install . then download the theme you want to use for the path. After that, go to the themekey admin link to set the theme for the specific path. |
65,477,452 | When I click text fields on the main page (main.dart) which is the default dart given by the flutter. I can see a glitch when soft keyboard appears and there is no delay when soft keyboard disappears.I have attached a gif below for this case.
```
void main() {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: primaryColor, //blue
statusBarIconBrightness: Brightness.dark,
));
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.pink,
primaryColor: primaryColor,
primaryColorBrightness: Brightness.dark,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
// setState(() {
// // This call to setState tells the Flutter framework that something has
// // changed in this State, which causes it to rerun the build method below
// // so that the display can reflect the updated values. If we changed
// // _counter without calling setState(), then the build method would not be
// // called again, and so nothing would appear to happen.
// _counter++;
// });
setState(() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => PhoneAuth()));
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
backgroundColor: Colors.red,
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text('hell0000000'),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Container(
color: Colors.white,
child: ListView(
children: [
Column(
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
SizedBox(
height: 200,
),
Align(
alignment: Alignment.bottomCenter,
child: new Container(
child: TextField(
decoration: new InputDecoration(
hintText: 'Chat message',
),
),
),
),
],
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
```
**main.dart** **glich**
[](https://i.stack.imgur.com/KfqU5.gif)
---
2.
Also, When I click text fields on the other page (UserChatView.dart). I can see a glitch when soft keyboard appearing and disappearing. In this dart file, That glitch happening for both actions(Keyboard opening and closing). I have attached a gif below for this case.
```
class UserChatView extends StatelessWidget{
@override
Widget build(BuildContext context) {
return UserChatViewPage();
}
}
class UserChatViewPage extends StatefulWidget {
UserChatViewPage({Key key}) : super(key: key);
@override
_UserChatViewPageState createState() => _UserChatViewPageState();
}
class _UserChatViewPageState extends State<UserChatViewPage> {
final TextEditingController _textController = new TextEditingController();
@override
Widget build(BuildContext context) {
final focus = FocusNode();
return new Scaffold(
backgroundColor: Colors.red, // Scaffold background Color
appBar: new AppBar(
title: Row(
children: <Widget>[
// new Container(
// child: CircleAvatar(
// backgroundImage: AssetImage("assets/male_icon.png"),
// )
// ),
new SizedBox(
width: 5.00,
),
new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget> [
new Container(
child: new Text("Alex Marko",
style: TextStyle(color: Colors.white,
fontFamily: 'Roboto_Bold',
letterSpacing: 1.00
),
),
),
new Container(
child: new Text("Online",
style: TextStyle(color: Colors.white,
fontFamily: 'Roboto_Medium',
letterSpacing: 1.00,
fontSize: 12.00,
),
),
),
],
),
],
),
centerTitle: false,
titleSpacing: 0.0,
backgroundColor: primaryColor,
elevation: 0.0,
bottomOpacity: 0.0,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.expand_more_rounded,
color: Colors.white,
),
onPressed: () {
// do something
},
),
],
),
body: Center(
child: new Container(
color: Colors.grey,
child: new Column(
children: <Widget>[
new Expanded(
child: _PageListView(),
),
new Container(
color: Colors.yellow,
padding: new EdgeInsets.all(10.0),
child: _buildTextComposer(),
),
],
),
),
),
);
}
Widget _buildTextComposer() {
return new Container(
color: Colors.yellow,//modified
margin: const EdgeInsets.symmetric(horizontal: 8.0),
child: new Row(
children: <Widget>[
new Flexible(
child: new TextField(
controller: _textController,
onSubmitted: _handleSubmitted,
decoration: new InputDecoration.collapsed(
hintText: "Send a message"),
),
),
new Container(
margin: new EdgeInsets.symmetric(horizontal: 4.0),
child: new IconButton(
icon: new Icon(Icons.send),
onPressed: () => _handleSubmitted(_textController.text)),
),
],
),
);
}
Widget _PageListView(){
return new Container(
child: ListView.builder(
reverse: true,
itemCount: 20,
itemBuilder: (context, position) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(position.toString(), style: TextStyle(fontSize: 22.0),),
),
);
},
),
);
}
```
**UserChatView.dart Glich**
[](https://i.stack.imgur.com/QPlXN.gif) | 2020/12/28 | [
"https://Stackoverflow.com/questions/65477452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779017/"
] | The reason of this so called `Glitch` is that the default behaviour of the flutter `scaffold` widget is to resize it's body when soft keyboard opens up or closes down.
While the flutter scaffold is notified of any of the above two events, it will start resizing the widgets under its `body` to match the new state. The speed of resizing may differ based on the comlplexity of build process of the widget on screen & processing speed of the device itself.
What you can do is add a flag called `resizeToAvoidBottomInset` in the scaffold widget in your app, like this:
```dart
Scaffold(
...
resizeToAvoidBottomInset: false,
)
```
What this does is, It notifies the scaffole to not resize the widget under its `body` on keyboard up or down states.
So, unless you want to explicitely resize the content of the screen on keyboard state, this is a solution to your glitch.
On the other hand, if you want to resize the content, you can choose to `modularize`/`breakdown` the widgets that you have on screen `to smallest possible combination` & `make the layout simpler` so that the `glitch` portion of the resizing is taken care of by the speed of rebuild process. | Your keyboard is producing that effect because of the `ListView.builder`. Add extra properties to your `ListView` like this
```
Widget _PageListView(){
return new Container(
child: ListView.builder(
addAutomaticKeepAlives: true, // Add this property
cacheExtent: double.infinity, // And this one
reverse: true,
itemCount: 20,
itemBuilder: (context, position) {
return Card( /* It's better to have here a separated StatefulWidget with AutomaticKeepAliveClientMixin */
// ...
);
},
),
);
}
``` |
28,193,935 | I see this examples:
<https://openui5.hana.ondemand.com/#docs/guide/25ab54b0113c4914999c43d07d3b71fe.html>
I have this my formatter function:
```
rowVisibility: function (oRow, sGrid) {
var oModel = new sap.ui.model.json.JSONModel();
oModel.loadData("model/file/mapping/map.json", "", false);
var oGridInfo = oModel.getProperty("/elements")[sGrid];
var bVisible = true;
_.forEach(oGridInfo.fields, function (fld) {
if (oRow[fld] == null)
bVisible = false;
});
return bVisible;
}
```
And in XML view I try to pass more than one param:
```
visible="{parts:[{path: 'model>'}, {'MY_GRID_NAME'} ], formatter:'ui5bp.Formatter.rowVisibility'}"
```
but it don't work...
How can I send sGrid param? I want create only one formatter function, not one for each sGrid!
Example: the rowVisibility formatter function is called from 3 different context ("context\_a", "context\_b" and "context\_c"). I want have one function called from 3 context (the behavior will different based on the context)
```
visible="{parts:[{path: 'model>'}, {"context_a"} ], formatter:'ui5bp.Formatter.rowVisibility'}"
visible="{parts:[{path: 'model>'}, {"context_b"} ], formatter:'ui5bp.Formatter.rowVisibility'}"
visible="{parts:[{path: 'model>'}, {"context_c"} ], formatter:'ui5bp.Formatter.rowVisibility'}"
```
this is the unique function
```
rowVisibility: function (oRow) {
...
}
```
Now instead I have 3 different functions:
```
rowVisibility_contextA: function (oRow) {
...
}
rowVisibility_contextB: function (oRow) {
...
}
rowVisibility_contextC: function (oRow) {
...
}
``` | 2015/01/28 | [
"https://Stackoverflow.com/questions/28193935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3224058/"
] | You're mixing iteration with recursion, which is usually not a good idea.
(Your compiler should have warned about possibly not returning a value from the function. )
You're also possibly dereferencing a null pointer here:
```
int current = p->age;
```
and comparing the wrong thing here:
```
if (p->age == NULL)
```
(The fact that the program doesn't crash makes me suspect that you have an object with zero age somewhere, causing you to return that zero instead of recursing.)
If you read the loop carefully, you'll notice that it always returns a value on the first iteration, so `temp` is never advanced, and the `while` could be replaced with `if`.
You should rewrite the function to be either iterative or recursive.
An iterative solution would look like this:
```
int findLargest (StudentCard *p)
{
int current = std::numeric_limits<int>::min();
while (p != NULL){
if (p->age > current) {
current = p->age;
}
p = p->next;
}
return current;
}
```
and a recursive solution would look like this:
```
int findLargest (StudentCard *p)
{
if (p == NULL) {
return std::numeric_limits<int>::min();
}
return std::max(p->age, findLargest(p->next));
}
``` | First of all, you should `return -1` at the end of your function to inform that nothing was found.
Then secondly, you are sending the `p->next` as the parameter of `findLargest` function without checking `NULL` in following code:
```
//Recur to find the highest value from the rest of the LinkedList
next = findLargest(p->next);
```
And also, when you are using recursion function call, you don't need the `while(temp != NULL)` loop at all. You could replace the `while` with a `if` and remove the `temp = temp->next;` statement. Either recursion or iteration is enough for solving your problem.
Your `findLargest` function should be as following code:
```
int findLargest (StudentCard *p)
{
if (p != NULL)
{
int current = p->age;
int next = findLargest(p->next);
if (current > next) {
return current;
}
else {
return next;
}
}
return -1;
}
```
For getting the oldest student node pointer, use following definition:
```
StudentCard * findLargestNode(StudentCard *p)
{
if (p != NULL)
{
int curAge = p->age;
StudentCard *next = findLargestNode(p->next);
if (next && (next->age > curAge)) {
return next;
}
else {
return p;
}
}
return NULL;
}
```
And for printing the oldest student ID, use the function as following
```
{
StudentCard *pOld = findLargestNode(listHead); // `listHead` is HEAD node of your link-list
if ( pOld )
cout << pOld->id << endl;
}
``` |
21,140,683 | In iOS 7, when navigating back using the new swipe-from-edge-of-screen gesture, the title of the Back button ("Artists") fades from being pink (in the example below) and having regular font weight to being black and having bold font weight.

It seems to me that the animation uses two different labels in order to achieve this effect; one fading out as the other fades in. However, Apple has somehow adjusted the font so that the regular label perfectly overlays the bold one, thus creating the illusion of a single label morphing between two different weights and colors.
Have they simply adjusted the letter spacing on the regular font so that it matches onto the bold one? In that case, how would that be achieved in iOS 7? Does Text Kit have any awesome features for doing this or how should I go about it? | 2014/01/15 | [
"https://Stackoverflow.com/questions/21140683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381416/"
] | You can adjust letter spacing like this, using `NSAttributedString`.
In Objective-C:
```objectivec
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"The Clash"];
[attributedString addAttribute:NSKernAttributeName
value:@(1.4)
range:NSMakeRange(0, 9)];
self.label.attributedText = attributedString;
```
In Swift 3:
```swift
let attributedString = NSMutableAttributedString(string: "The Clash")
attributedString.addAttribute(NSKernAttributeName, value: CGFloat(1.4), range: NSRange(location: 0, length: 9))
label.attributedText = attributedString
```
In Swift 4 and later:
```
label.attributedText = NSAttributedString(string: "The Clash", attributes: [.kern: 1.4])
```
More info on kerning is available in [Typographical Concepts from the Text Programming Guide](https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/TypoFeatures/TextSystemFeatures.html#//apple_ref/doc/uid/TP40009542-CH6-BBCFAEGE).
I don't think there's a TextKit feature that will automatically match font spacing between bold and regular text. | With Swift 5.3 and iOS 14, `NSAttributedString.Key` has a static property called `kern`. `kern` has the following [declaration](https://developer.apple.com/documentation/foundation/nsattributedstring/key/1527891-kern):
```
static let kern: NSAttributedString.Key
```
>
> The value of this attribute is an `NSNumber` object containing a floating-point value. This value specifies the number of points by which to adjust kern-pair characters. Kerning prevents unwanted space from occurring between specific characters and depends on the font. The value 0 means kerning is disabled. The default value for this attribute is 0.
>
>
>
The following Playground code shows a possible implementation of `kern` in order to have some letter spacing in your `NSAttributedString`:
```swift
import PlaygroundSupport
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let string = "Some text"
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.kern: 10,
NSAttributedString.Key.paragraphStyle: paragraph
]
let attributedString = NSMutableAttributedString(
string: string,
attributes: attributes
)
let label = UILabel()
label.attributedText = attributedString
view.backgroundColor = .white
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
label.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
PlaygroundPage.current.liveView = ViewController()
``` |
21,140,683 | In iOS 7, when navigating back using the new swipe-from-edge-of-screen gesture, the title of the Back button ("Artists") fades from being pink (in the example below) and having regular font weight to being black and having bold font weight.

It seems to me that the animation uses two different labels in order to achieve this effect; one fading out as the other fades in. However, Apple has somehow adjusted the font so that the regular label perfectly overlays the bold one, thus creating the illusion of a single label morphing between two different weights and colors.
Have they simply adjusted the letter spacing on the regular font so that it matches onto the bold one? In that case, how would that be achieved in iOS 7? Does Text Kit have any awesome features for doing this or how should I go about it? | 2014/01/15 | [
"https://Stackoverflow.com/questions/21140683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381416/"
] | You can adjust letter spacing like this, using `NSAttributedString`.
In Objective-C:
```objectivec
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"The Clash"];
[attributedString addAttribute:NSKernAttributeName
value:@(1.4)
range:NSMakeRange(0, 9)];
self.label.attributedText = attributedString;
```
In Swift 3:
```swift
let attributedString = NSMutableAttributedString(string: "The Clash")
attributedString.addAttribute(NSKernAttributeName, value: CGFloat(1.4), range: NSRange(location: 0, length: 9))
label.attributedText = attributedString
```
In Swift 4 and later:
```
label.attributedText = NSAttributedString(string: "The Clash", attributes: [.kern: 1.4])
```
More info on kerning is available in [Typographical Concepts from the Text Programming Guide](https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/TypoFeatures/TextSystemFeatures.html#//apple_ref/doc/uid/TP40009542-CH6-BBCFAEGE).
I don't think there's a TextKit feature that will automatically match font spacing between bold and regular text. | For **Swift** 4+ the syntax is as simple as:
```
let text = NSAttributedString(string: "text", attributes: [.kern: 1.4])
``` |
21,140,683 | In iOS 7, when navigating back using the new swipe-from-edge-of-screen gesture, the title of the Back button ("Artists") fades from being pink (in the example below) and having regular font weight to being black and having bold font weight.

It seems to me that the animation uses two different labels in order to achieve this effect; one fading out as the other fades in. However, Apple has somehow adjusted the font so that the regular label perfectly overlays the bold one, thus creating the illusion of a single label morphing between two different weights and colors.
Have they simply adjusted the letter spacing on the regular font so that it matches onto the bold one? In that case, how would that be achieved in iOS 7? Does Text Kit have any awesome features for doing this or how should I go about it? | 2014/01/15 | [
"https://Stackoverflow.com/questions/21140683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381416/"
] | For **Swift** 4+ the syntax is as simple as:
```
let text = NSAttributedString(string: "text", attributes: [.kern: 1.4])
``` | With Swift 5.3 and iOS 14, `NSAttributedString.Key` has a static property called `kern`. `kern` has the following [declaration](https://developer.apple.com/documentation/foundation/nsattributedstring/key/1527891-kern):
```
static let kern: NSAttributedString.Key
```
>
> The value of this attribute is an `NSNumber` object containing a floating-point value. This value specifies the number of points by which to adjust kern-pair characters. Kerning prevents unwanted space from occurring between specific characters and depends on the font. The value 0 means kerning is disabled. The default value for this attribute is 0.
>
>
>
The following Playground code shows a possible implementation of `kern` in order to have some letter spacing in your `NSAttributedString`:
```swift
import PlaygroundSupport
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let string = "Some text"
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.kern: 10,
NSAttributedString.Key.paragraphStyle: paragraph
]
let attributedString = NSMutableAttributedString(
string: string,
attributes: attributes
)
let label = UILabel()
label.attributedText = attributedString
view.backgroundColor = .white
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
label.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
PlaygroundPage.current.liveView = ViewController()
``` |
95,387 | I have changed the language from my MacOS system and now it won't save the screenshots anymore. Is there a way to fix it?
Thanks. | 2013/07/02 | [
"https://apple.stackexchange.com/questions/95387",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/48696/"
] | I found this, and it works:
Say you restore your iPhone with a full wipe and restore. Then you choose a previous backup to restore all of your settings and applications. When your iPhone is done restoring to your backup, all your icons are mixed up on the SpringBoard.... what the heck? You want to get them back don't you? Well, I know a trick and I don't think it's documented anywhere. Here it goes.
\*\*Important: Before starting these instructions, backup your iPhone. Then go into iTunes preferences and turn on "Disable automatic syncing for iPhones and iPods" This way your backup won't get overwritten after your iPhone gets restored.
1. Restore your iPhone and let it restart and activate.
2. Then iTunes will happily ask you if you want to restore from a previous backup (with all of your settings and Applications). Click the backup you want to restore to and let it restore and reboot.
(Here's where things get messed up. Your iPhone backup actually restored the correct icon positions except none of your apps were installed before the restore was complete, so iTunes has to copy all of your apps back to your iPhone. When it does this, it copys them in alphabetical order, thus messing up the location of all your 3rd party icons). Here's how to fix this without memorizing where all your icons went.
1. Right click (or Control-click) on the iPhone icon in iTunes and choose "Restore from Backup" and choose the backup you chose in step 2 again.
2. Let your iPhone restore for a second time and when it reboots, all of your icons will be in their original places. (This is because iTunes didn't have to install the Apps because they were already there, thus keeping them in their original locations according to the backup).
3. Return your iTunes preferences and uncheck "Disable automatic syncing for iPhone and iPod" | The arrangement of icons and folders is backed up to iTunes and iCloud, so unless you are doing something out of the normal, a simple restore from the backup will restore the position of the icons, the user data and allow all of the apps to download from the store once your settings are restored. |
31,494,101 | We have a optimized Apache 2.2 setting which works fine, but after upgrading to Apache 2.4 it seems not reflecting. Both Apache were enabled with worker module, have shared the details below.
>
> Apache 2.2 Settings
> -------------------
>
>
>
> ```
> <IfModule worker.c>
> ServerLimit 40
> StartServers 40
> MaxClients 2000
> MinSpareThreads 2000
> ThreadsPerChild 50
> </IfModule>
>
> ```
>
> Apache 2.2 Server-Status output
> -------------------------------
>
>
>
> ```
> 35 requests currently being processed, 1965 idle workers
>
> ```
>
> Apache 2.4 Settings
> -------------------
>
>
>
> ```
> <IfModule worker.c>
> ServerLimit 40
> StartServers 40
> MaxRequestWorkers 2000
> MinSpareThreads 2000
> ThreadsPerChild 50
> </IfModule>
>
> ```
>
> Apache 2.4 Server-Status output
> -------------------------------
>
>
>
> ```
> 1 requests currently being processed, 99 idle workers
>
> ```
>
>
Need someone's help to point out me the missing setting so that I can have my Apache 2.4 to create 2000 threads at the startup of Apache service.
Thanks. | 2015/07/18 | [
"https://Stackoverflow.com/questions/31494101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943986/"
] | Thanks Daniel for your response.
I just found the issue few hours back. The conf '00-mpm.conf' (which has the modules to enable prefork / worker / event) was called below the worker.c module setting which seems to have caused the issue. Moving it above the worker setting made apache to pick up the worker setting mentioned. | First off, **if** you need IfModule, you should use as that is the actual name of the module. Secondly, you should not be using IfModule *if you know that module is going to be there*. Just use the configuration options, don't sugarcoat it with IfModule.
Secondly, I would recommend you switch from the worker mpm to the event mpm, especially if you have a high load on your server, as the event mpm is geared towards solving the c10k problem, whereas worker mpm just "throws more threads at it".
Having said all that, it does not appear that your configuration, as shown, is the cause of this, so the problem is elsewhere. To better get a look at what's going on, you should:
* Remove the IfModule stuff around your directives, let the directives be applied unconditionally
* Check the first entries of your error log (which will tell you whether httpd is overriding your settings itself) or check the output from when you manually start httpd. If httpd strongly disagrees with your settings, it will let you know why.
* Grep, within your configuration file space, for the directives you have above, and see if any other configuration files are overriding them.
I would have posted this as just a comment, but eh...not enough karma :( |
9,750,355 | I have an object with a Flag enum with several possible "uses". The flag enum uses the proper power of 2.
Checking if a variable has a certain flag on, I can do it using the .NET 4 `HasFlag()`
BUT:
If I store that flag combination as a int in database... how can I retrive the objects that have certain flag on using Entity Framework?
For example, if my object is a "`Contact`" type, I would like to query those of them that are actually "Customers and Friends", being Customers and Friends flags in the `ContactType` Enum. | 2012/03/17 | [
"https://Stackoverflow.com/questions/9750355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7720/"
] | I doubt any ORM is going to have a way to adapt the HasFlags down to the appropriate SQL code for your DBMS.
What you are likely going to need to do is either write a stored procedure, or hand-crank the SQL Statement to be executed for this.
You don't mention what DBMS you're using - but if I assume you're using SQL Server, you are in luck as it has the [& (Bitwise AND) operator](http://msdn.microsoft.com/en-us/library/ms174965.aspx).
Practical example as T-SQL:
```
-- Setup Test Data
DECLARE @Contacts TABLE (id int, contactType int, name nvarchar(MAX))
INSERT INTO @Contacts VALUES (1, 0, 'Fred'); -- Not Wanted
INSERT INTO @Contacts VALUES (2, 3, 'Jim'); -- Wanted
INSERT INTO @Contacts VALUES (3, 36, 'Mary'); -- Not wanted
INSERT INTO @Contacts VALUEs (4, 78, 'Jo'); -- Wanted
-- Execute Query
SELECT *
FROM @Contacts
WHERE ContactType & 2 = 2
``` | ```
db.Contacts.Where(c => (c.Flag & MyEnum.Flag3) != 0).ToList();
``` |
9,750,355 | I have an object with a Flag enum with several possible "uses". The flag enum uses the proper power of 2.
Checking if a variable has a certain flag on, I can do it using the .NET 4 `HasFlag()`
BUT:
If I store that flag combination as a int in database... how can I retrive the objects that have certain flag on using Entity Framework?
For example, if my object is a "`Contact`" type, I would like to query those of them that are actually "Customers and Friends", being Customers and Friends flags in the `ContactType` Enum. | 2012/03/17 | [
"https://Stackoverflow.com/questions/9750355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7720/"
] | I doubt any ORM is going to have a way to adapt the HasFlags down to the appropriate SQL code for your DBMS.
What you are likely going to need to do is either write a stored procedure, or hand-crank the SQL Statement to be executed for this.
You don't mention what DBMS you're using - but if I assume you're using SQL Server, you are in luck as it has the [& (Bitwise AND) operator](http://msdn.microsoft.com/en-us/library/ms174965.aspx).
Practical example as T-SQL:
```
-- Setup Test Data
DECLARE @Contacts TABLE (id int, contactType int, name nvarchar(MAX))
INSERT INTO @Contacts VALUES (1, 0, 'Fred'); -- Not Wanted
INSERT INTO @Contacts VALUES (2, 3, 'Jim'); -- Wanted
INSERT INTO @Contacts VALUES (3, 36, 'Mary'); -- Not wanted
INSERT INTO @Contacts VALUEs (4, 78, 'Jo'); -- Wanted
-- Execute Query
SELECT *
FROM @Contacts
WHERE ContactType & 2 = 2
``` | You can get the combined bit value as int and store that value in the db as a column here is a sample:
```
public enum MessagingProperties
{
// No options selected (value is 0)
None = 0x00,
// messages are not discarded if subscriber is slow (value is 1)
Durable = 0x01,
// messages are saved to disk in case messaging crashes (value is 2)
Persistent = 0x02,
// messages are buffered at send/receive point so not blocking (value is 4)
Buffered = 0x04
}
```
In order to combine these flag enums you do:
```
// combine the bit flags
var combinedFlags = MessagingProperties.Durable | MessagingProperties.Persistent |
MessagingProperties.Buffered;
// this will be equal 7, no other combination can sum up to seven so it is unique, that's how bit flags work
int combinedFlagsInt = (int)combinedFlags;
```
You can now go ahead and store this value in the db. If you want to query for multiple bit flags you:
* combine them
* cast them into an int
* and use the resulting variable/value as a filter in the `Where` clause. |
76,999 | apache ask for passphrase redirects to plymouth even when I'm remoted in using SSH and away from console.
How can I disabled plymouth?
Update: I did learn that I can `sudo plymouth --quit` and that will shutdown plymouth. I would like to know the recommended way to disable plymouth on boot. | 2011/11/08 | [
"https://askubuntu.com/questions/76999",
"https://askubuntu.com",
"https://askubuntu.com/users/1668/"
] | plymouth should be stopping on its own when the boot is finished.. on a GUI that is when kdm/xdm/gdm/lxdm start. On servers, that is when runlevel 2 is finished (ls /etc/rc2.d). If it is not stopped, this is likely a bug in the bootup, and should be reported with
```
apport-bug plymouth
```
Additional Resources:
* [How do I report a bug?](https://askubuntu.com/questions/5121/how-do-i-report-a-bug) | The [How can I disable the purple splash screen at boot?](https://askubuntu.com/questions/5065/how-can-i-disable-the-purple-splash-screen-at-boot) has been mentioned.
You could also edit the plymouth /1/ upstart /2/ config files and prevent the plymouth start-up. I think that the /etc/init/plymouth.conf will do the trick.
Links:
1. <https://wiki.ubuntu.com/Plymouth>
2. <http://upstart.ubuntu.com/> |
12,473,821 | What is difference between.
what is best?
Do you **drain** same **release** but different in drain don't save **retain**, while release save retain?
**autorelease** save object in memory some time. | 2012/09/18 | [
"https://Stackoverflow.com/questions/12473821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1667650/"
] | What is best? The answer, of course, is 'it depends'.
For most newcomers to Cocoa, my opinion is 'none of the above' - it is ARC. Although even with ARC, some understanding of reference-counted memory management is important, you need not worry about missing a `release` or `autorelease`, over over-releasing.
In the situation described by @Anshuk Garg above where you are creating numerous temporary objects before the thread's autorelease pool would be drained, you can wrap the code in question in an `@autorelease { ... }` block. Instruments can tell you whether your memory footprint is an issue in these settings. | **release**:
In a reference-counted environment, since an autorelease pool cannot be retained , this method decrements the retain count. When an autorelease pool is deallocated, it sends a 'release' message to all its autoreleased objects. Also, In a garbage-collected environment, this method is a no no.
```
- (void)release
```
**drain**:
In a reference-counted environment, releases and pops the receiver; in a garbage-collected environment, triggers garbage collection if the memory allocated since the last collection is greater than the current threshold.
```
- (void)drain
```
Conclusion:
From the above brief discussion it is clear that, we should always use 'drain' over 'release' for an autorelease pool(be the Cocoa or Cocoa touch).
**release vs autorelease**
In most cases, it wont really matter either way. Since -autorelease simply means that the object will be released at the end of the current iteration of the run loop, the object will get released either way.
The biggest benefit of using -autorelease is that you don't have to worry about the lifetime of the object in the context of your method. So, if you decide later that you want to do something with an object several lines after it was last used, you don't need to worry about moving your call to -release.
The main instance when using -release will make a noticeable difference vs. using -autorelease is if you're creating a lot of temporary objects in your method. |
12,473,821 | What is difference between.
what is best?
Do you **drain** same **release** but different in drain don't save **retain**, while release save retain?
**autorelease** save object in memory some time. | 2012/09/18 | [
"https://Stackoverflow.com/questions/12473821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1667650/"
] | drain same release but different in drain don't save retain, while release save retain,, autorelease save object in memory some time. | **release**:
In a reference-counted environment, since an autorelease pool cannot be retained , this method decrements the retain count. When an autorelease pool is deallocated, it sends a 'release' message to all its autoreleased objects. Also, In a garbage-collected environment, this method is a no no.
```
- (void)release
```
**drain**:
In a reference-counted environment, releases and pops the receiver; in a garbage-collected environment, triggers garbage collection if the memory allocated since the last collection is greater than the current threshold.
```
- (void)drain
```
Conclusion:
From the above brief discussion it is clear that, we should always use 'drain' over 'release' for an autorelease pool(be the Cocoa or Cocoa touch).
**release vs autorelease**
In most cases, it wont really matter either way. Since -autorelease simply means that the object will be released at the end of the current iteration of the run loop, the object will get released either way.
The biggest benefit of using -autorelease is that you don't have to worry about the lifetime of the object in the context of your method. So, if you decide later that you want to do something with an object several lines after it was last used, you don't need to worry about moving your call to -release.
The main instance when using -release will make a noticeable difference vs. using -autorelease is if you're creating a lot of temporary objects in your method. |
370,830 | I just realized that the directions in "UPload" and "DOWNload" seem arbitrary to me as a non-native English speaker. I took a look at a couple of dictionaries and they said that this word is a result of merging "down" and "load", which doesn't seem to explain anything. Where could those two directions come from? | 2017/01/29 | [
"https://english.stackexchange.com/questions/370830",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/53295/"
] | OED noticed the word for the first time in 1976, it seems.
1976 was very early in the development of computers. FTP (File Transfer Protocol) was designed 1971 and TCP/ IP followed in 1973. These two protocols made any transfer of data possible for the first time.
Servers or internet wasn't something anyone could imagine yet. Instead scientist were still hammering out the basic how of a data transfer.
In these years, several conceptual models for the transfer of data were developed. Most used and known nowadays is the OSI model with 7 layers - and these layers have an up / down direction.
Now, if I want to get data from another computer, I technically send the other computer a request, which then converts said data "down" to the physical layer, until all is left is a physical signal. This signal is then send to my computer, and I convert it again (this time "upwards").
This also is a likely explanation why "upload" appeared years later, in 1980 according to OED. Upload was coined as the simple opposite of download.
Though, while this is what I first thought of, it might be that there is also a hierarchy meaning in play as well. | Looking at the OED first use, "1976 [Science 7 May 518/1](http://science.sciencemag.org/content/192/4239/511) Software at any level can be developed on a host minicomputer and ‘down-loaded’ without code conversion", it appears to be talking about loading code from a host to a microprocessor. No real help there but I wonder if the author was thinking of taking reference books down in a library to copy out texts and then putting them back up on the shelves? |
370,830 | I just realized that the directions in "UPload" and "DOWNload" seem arbitrary to me as a non-native English speaker. I took a look at a couple of dictionaries and they said that this word is a result of merging "down" and "load", which doesn't seem to explain anything. Where could those two directions come from? | 2017/01/29 | [
"https://english.stackexchange.com/questions/370830",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/53295/"
] | Initially, "download" and "upload" were used in aviation, especially by the US military. "Download" meant to remove items such as weapons from the aircraft, while "upload" meant to load items onto the aircraft.
For example, the [August 1963 *Aerospace Maintenance Safety*](https://books.google.com/books?id=SNvGD-_SKL0C&pg=RA4-PA18&dq=download%20missile&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwi2zLC2qeXlAhUhc98KHRAbAPIQ6AEwAHoECAAQAg#v=snippet&q=%22download%22&f=false) (a publication of the US Air Force) says at page 18:
>
> Failure to follow written procedures and **download** the missiles...
>
>
>
(meaning failure to remove the missiles from the aircraft)
There are earlier examples of "download", "downloading" and "uploading" in the January 1961 [Aerospace Accident and Maintenance Review](https://books.google.com/books?id=Myb32suKp-EC&pg=RA1-PA23&dq=%22downloading%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwjX1JaMu-XlAhXBxFkKHQVBBaUQ6AEwA3oECAcQAg#v=snippet&q=%22download%22&f=false), also a USAF publication.
And still earlier in the October 1959 [Aircraft Accident and Maintenance Review](https://books.google.com/books?id=jlyg_p7KuQUC&pg=RA9-PA27&dq=%22downloading%22%20%22usaf%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwj1sZqviOblAhVmuVkKHd52DL4Q6AEwAnoECAEQAg#v=onepage&q=%22downloading%22%20%22usaf%22&f=false), USAF, at page 27:
>
> During **downloading** of armament for a routine check, it was discovered that all the missiles aboard the F-102 had their internal power source activated.
>
>
>
(There was also an even earlier meaning relating to the direction of load on an aircraft component, such as on the tail of the aircraft. See "download on tail" in the April 1957 NACA [Technical Note 3961](https://books.google.com/books?id=oNAjAQAAMAAJ&pg=RA5-PA8&dq=%22download%22%20%22tail%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwiWut3bruXlAhXIV98KHaNdDZoQ6AEwAHoECAUQAg#v=onepage&q=%22download%22%20%22tail%22&f=false) and ""download applied to the horizontal tail surface" in the [1952 US Code of Federal Regulations](https://books.google.com/books?id=hviyAAAAIAAJ&pg=PA83&dq=%22download%22%20%22tail%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwj55sL9sOXlAhWjVN8KHWVZAUkQ6AEwAXoECAUQAg#v=onepage&q=%22download%22%20%22tail%22&f=false) ).
Then, within the US Air Force, the concept was extended to computers.
The July 1968 [IMPLEMENTATION OF THE USAF STANDARD BASE SUPPLY SYSTEM: A QUANTITATIVE STUDY](https://pdfs.semanticscholar.org/1927/53b84b808edefd05faac90b7f215214599a2.pdf) says:
>
> ADC provided a three-man team, which visited the bases
> some 30 days prior to conversion and conducted a full-scale **download**
> of the 305 and **upload** of the 1050, requiring 10 to 15 days.
>
>
> ...
>
>
> 2. **Download** records from the previous computer
> 3. **Upload** records on the 1050 computer
>
>
> | Looking at the OED first use, "1976 [Science 7 May 518/1](http://science.sciencemag.org/content/192/4239/511) Software at any level can be developed on a host minicomputer and ‘down-loaded’ without code conversion", it appears to be talking about loading code from a host to a microprocessor. No real help there but I wonder if the author was thinking of taking reference books down in a library to copy out texts and then putting them back up on the shelves? |
370,830 | I just realized that the directions in "UPload" and "DOWNload" seem arbitrary to me as a non-native English speaker. I took a look at a couple of dictionaries and they said that this word is a result of merging "down" and "load", which doesn't seem to explain anything. Where could those two directions come from? | 2017/01/29 | [
"https://english.stackexchange.com/questions/370830",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/53295/"
] | Looking at the OED first use, "1976 [Science 7 May 518/1](http://science.sciencemag.org/content/192/4239/511) Software at any level can be developed on a host minicomputer and ‘down-loaded’ without code conversion", it appears to be talking about loading code from a host to a microprocessor. No real help there but I wonder if the author was thinking of taking reference books down in a library to copy out texts and then putting them back up on the shelves? | Download and Upload are far from arbitrary, they are entirely rational:
A **[Download](https://en.wikipedia.org/wiki/Download)** refers to data that is brought '**down**' from a network, the World Wide Web (Or Cloud) to reside on a local drive / computer.
**Upload** is data that is sent '**up**' to the World Wide Web (Or Cloud) from a local drive of computer.
The term originated as others have described from the pre-personal computer era, and is a Networking term.
In the good o'l days [1970's],all computing power was housed exclusively in remote Server or mainframe computers - it was too expensive for an individual to buy.
Other than a local terminal directly wired to the 'glowing mass' of the mainframe, any other connections were "*Down the wire*", outside of a large company with a LAN, typically this would be the public telephone system. I remember visiting my Secondary School during the summer holidays in 1977 to play "Lunar Lander" via the dial-up telephone-cradle modem link to the local council mainframe computer.
[](https://i.stack.imgur.com/gDmHv.jpg)
As an aside: The game required the player to type in a numerical value, which was sent 'up' the telephone line to the mainframe, which would respond to the teleprinter with a message like:
>
> "You are at 3,000' and descending at 50m/sec."
>
>
>
The player would type another value and so on until you received the message:
>
> "Congratulations, you have crashed!"
>
>
>
Tv monitors and video displays were but a distant dream...
All local drives were "down the wire".
Any keyboard inputs were sent "up the wire"...
See also: [Downstream](https://en.wikipedia.org/wiki/Downstream_(networking)) |
370,830 | I just realized that the directions in "UPload" and "DOWNload" seem arbitrary to me as a non-native English speaker. I took a look at a couple of dictionaries and they said that this word is a result of merging "down" and "load", which doesn't seem to explain anything. Where could those two directions come from? | 2017/01/29 | [
"https://english.stackexchange.com/questions/370830",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/53295/"
] | Initially, "download" and "upload" were used in aviation, especially by the US military. "Download" meant to remove items such as weapons from the aircraft, while "upload" meant to load items onto the aircraft.
For example, the [August 1963 *Aerospace Maintenance Safety*](https://books.google.com/books?id=SNvGD-_SKL0C&pg=RA4-PA18&dq=download%20missile&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwi2zLC2qeXlAhUhc98KHRAbAPIQ6AEwAHoECAAQAg#v=snippet&q=%22download%22&f=false) (a publication of the US Air Force) says at page 18:
>
> Failure to follow written procedures and **download** the missiles...
>
>
>
(meaning failure to remove the missiles from the aircraft)
There are earlier examples of "download", "downloading" and "uploading" in the January 1961 [Aerospace Accident and Maintenance Review](https://books.google.com/books?id=Myb32suKp-EC&pg=RA1-PA23&dq=%22downloading%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwjX1JaMu-XlAhXBxFkKHQVBBaUQ6AEwA3oECAcQAg#v=snippet&q=%22download%22&f=false), also a USAF publication.
And still earlier in the October 1959 [Aircraft Accident and Maintenance Review](https://books.google.com/books?id=jlyg_p7KuQUC&pg=RA9-PA27&dq=%22downloading%22%20%22usaf%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwj1sZqviOblAhVmuVkKHd52DL4Q6AEwAnoECAEQAg#v=onepage&q=%22downloading%22%20%22usaf%22&f=false), USAF, at page 27:
>
> During **downloading** of armament for a routine check, it was discovered that all the missiles aboard the F-102 had their internal power source activated.
>
>
>
(There was also an even earlier meaning relating to the direction of load on an aircraft component, such as on the tail of the aircraft. See "download on tail" in the April 1957 NACA [Technical Note 3961](https://books.google.com/books?id=oNAjAQAAMAAJ&pg=RA5-PA8&dq=%22download%22%20%22tail%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwiWut3bruXlAhXIV98KHaNdDZoQ6AEwAHoECAUQAg#v=onepage&q=%22download%22%20%22tail%22&f=false) and ""download applied to the horizontal tail surface" in the [1952 US Code of Federal Regulations](https://books.google.com/books?id=hviyAAAAIAAJ&pg=PA83&dq=%22download%22%20%22tail%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwj55sL9sOXlAhWjVN8KHWVZAUkQ6AEwAXoECAUQAg#v=onepage&q=%22download%22%20%22tail%22&f=false) ).
Then, within the US Air Force, the concept was extended to computers.
The July 1968 [IMPLEMENTATION OF THE USAF STANDARD BASE SUPPLY SYSTEM: A QUANTITATIVE STUDY](https://pdfs.semanticscholar.org/1927/53b84b808edefd05faac90b7f215214599a2.pdf) says:
>
> ADC provided a three-man team, which visited the bases
> some 30 days prior to conversion and conducted a full-scale **download**
> of the 305 and **upload** of the 1050, requiring 10 to 15 days.
>
>
> ...
>
>
> 2. **Download** records from the previous computer
> 3. **Upload** records on the 1050 computer
>
>
> | OED noticed the word for the first time in 1976, it seems.
1976 was very early in the development of computers. FTP (File Transfer Protocol) was designed 1971 and TCP/ IP followed in 1973. These two protocols made any transfer of data possible for the first time.
Servers or internet wasn't something anyone could imagine yet. Instead scientist were still hammering out the basic how of a data transfer.
In these years, several conceptual models for the transfer of data were developed. Most used and known nowadays is the OSI model with 7 layers - and these layers have an up / down direction.
Now, if I want to get data from another computer, I technically send the other computer a request, which then converts said data "down" to the physical layer, until all is left is a physical signal. This signal is then send to my computer, and I convert it again (this time "upwards").
This also is a likely explanation why "upload" appeared years later, in 1980 according to OED. Upload was coined as the simple opposite of download.
Though, while this is what I first thought of, it might be that there is also a hierarchy meaning in play as well. |
370,830 | I just realized that the directions in "UPload" and "DOWNload" seem arbitrary to me as a non-native English speaker. I took a look at a couple of dictionaries and they said that this word is a result of merging "down" and "load", which doesn't seem to explain anything. Where could those two directions come from? | 2017/01/29 | [
"https://english.stackexchange.com/questions/370830",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/53295/"
] | OED noticed the word for the first time in 1976, it seems.
1976 was very early in the development of computers. FTP (File Transfer Protocol) was designed 1971 and TCP/ IP followed in 1973. These two protocols made any transfer of data possible for the first time.
Servers or internet wasn't something anyone could imagine yet. Instead scientist were still hammering out the basic how of a data transfer.
In these years, several conceptual models for the transfer of data were developed. Most used and known nowadays is the OSI model with 7 layers - and these layers have an up / down direction.
Now, if I want to get data from another computer, I technically send the other computer a request, which then converts said data "down" to the physical layer, until all is left is a physical signal. This signal is then send to my computer, and I convert it again (this time "upwards").
This also is a likely explanation why "upload" appeared years later, in 1980 according to OED. Upload was coined as the simple opposite of download.
Though, while this is what I first thought of, it might be that there is also a hierarchy meaning in play as well. | Download and Upload are far from arbitrary, they are entirely rational:
A **[Download](https://en.wikipedia.org/wiki/Download)** refers to data that is brought '**down**' from a network, the World Wide Web (Or Cloud) to reside on a local drive / computer.
**Upload** is data that is sent '**up**' to the World Wide Web (Or Cloud) from a local drive of computer.
The term originated as others have described from the pre-personal computer era, and is a Networking term.
In the good o'l days [1970's],all computing power was housed exclusively in remote Server or mainframe computers - it was too expensive for an individual to buy.
Other than a local terminal directly wired to the 'glowing mass' of the mainframe, any other connections were "*Down the wire*", outside of a large company with a LAN, typically this would be the public telephone system. I remember visiting my Secondary School during the summer holidays in 1977 to play "Lunar Lander" via the dial-up telephone-cradle modem link to the local council mainframe computer.
[](https://i.stack.imgur.com/gDmHv.jpg)
As an aside: The game required the player to type in a numerical value, which was sent 'up' the telephone line to the mainframe, which would respond to the teleprinter with a message like:
>
> "You are at 3,000' and descending at 50m/sec."
>
>
>
The player would type another value and so on until you received the message:
>
> "Congratulations, you have crashed!"
>
>
>
Tv monitors and video displays were but a distant dream...
All local drives were "down the wire".
Any keyboard inputs were sent "up the wire"...
See also: [Downstream](https://en.wikipedia.org/wiki/Downstream_(networking)) |
370,830 | I just realized that the directions in "UPload" and "DOWNload" seem arbitrary to me as a non-native English speaker. I took a look at a couple of dictionaries and they said that this word is a result of merging "down" and "load", which doesn't seem to explain anything. Where could those two directions come from? | 2017/01/29 | [
"https://english.stackexchange.com/questions/370830",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/53295/"
] | Initially, "download" and "upload" were used in aviation, especially by the US military. "Download" meant to remove items such as weapons from the aircraft, while "upload" meant to load items onto the aircraft.
For example, the [August 1963 *Aerospace Maintenance Safety*](https://books.google.com/books?id=SNvGD-_SKL0C&pg=RA4-PA18&dq=download%20missile&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwi2zLC2qeXlAhUhc98KHRAbAPIQ6AEwAHoECAAQAg#v=snippet&q=%22download%22&f=false) (a publication of the US Air Force) says at page 18:
>
> Failure to follow written procedures and **download** the missiles...
>
>
>
(meaning failure to remove the missiles from the aircraft)
There are earlier examples of "download", "downloading" and "uploading" in the January 1961 [Aerospace Accident and Maintenance Review](https://books.google.com/books?id=Myb32suKp-EC&pg=RA1-PA23&dq=%22downloading%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwjX1JaMu-XlAhXBxFkKHQVBBaUQ6AEwA3oECAcQAg#v=snippet&q=%22download%22&f=false), also a USAF publication.
And still earlier in the October 1959 [Aircraft Accident and Maintenance Review](https://books.google.com/books?id=jlyg_p7KuQUC&pg=RA9-PA27&dq=%22downloading%22%20%22usaf%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwj1sZqviOblAhVmuVkKHd52DL4Q6AEwAnoECAEQAg#v=onepage&q=%22downloading%22%20%22usaf%22&f=false), USAF, at page 27:
>
> During **downloading** of armament for a routine check, it was discovered that all the missiles aboard the F-102 had their internal power source activated.
>
>
>
(There was also an even earlier meaning relating to the direction of load on an aircraft component, such as on the tail of the aircraft. See "download on tail" in the April 1957 NACA [Technical Note 3961](https://books.google.com/books?id=oNAjAQAAMAAJ&pg=RA5-PA8&dq=%22download%22%20%22tail%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwiWut3bruXlAhXIV98KHaNdDZoQ6AEwAHoECAUQAg#v=onepage&q=%22download%22%20%22tail%22&f=false) and ""download applied to the horizontal tail surface" in the [1952 US Code of Federal Regulations](https://books.google.com/books?id=hviyAAAAIAAJ&pg=PA83&dq=%22download%22%20%22tail%22&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwj55sL9sOXlAhWjVN8KHWVZAUkQ6AEwAXoECAUQAg#v=onepage&q=%22download%22%20%22tail%22&f=false) ).
Then, within the US Air Force, the concept was extended to computers.
The July 1968 [IMPLEMENTATION OF THE USAF STANDARD BASE SUPPLY SYSTEM: A QUANTITATIVE STUDY](https://pdfs.semanticscholar.org/1927/53b84b808edefd05faac90b7f215214599a2.pdf) says:
>
> ADC provided a three-man team, which visited the bases
> some 30 days prior to conversion and conducted a full-scale **download**
> of the 305 and **upload** of the 1050, requiring 10 to 15 days.
>
>
> ...
>
>
> 2. **Download** records from the previous computer
> 3. **Upload** records on the 1050 computer
>
>
> | Download and Upload are far from arbitrary, they are entirely rational:
A **[Download](https://en.wikipedia.org/wiki/Download)** refers to data that is brought '**down**' from a network, the World Wide Web (Or Cloud) to reside on a local drive / computer.
**Upload** is data that is sent '**up**' to the World Wide Web (Or Cloud) from a local drive of computer.
The term originated as others have described from the pre-personal computer era, and is a Networking term.
In the good o'l days [1970's],all computing power was housed exclusively in remote Server or mainframe computers - it was too expensive for an individual to buy.
Other than a local terminal directly wired to the 'glowing mass' of the mainframe, any other connections were "*Down the wire*", outside of a large company with a LAN, typically this would be the public telephone system. I remember visiting my Secondary School during the summer holidays in 1977 to play "Lunar Lander" via the dial-up telephone-cradle modem link to the local council mainframe computer.
[](https://i.stack.imgur.com/gDmHv.jpg)
As an aside: The game required the player to type in a numerical value, which was sent 'up' the telephone line to the mainframe, which would respond to the teleprinter with a message like:
>
> "You are at 3,000' and descending at 50m/sec."
>
>
>
The player would type another value and so on until you received the message:
>
> "Congratulations, you have crashed!"
>
>
>
Tv monitors and video displays were but a distant dream...
All local drives were "down the wire".
Any keyboard inputs were sent "up the wire"...
See also: [Downstream](https://en.wikipedia.org/wiki/Downstream_(networking)) |
43,578,466 | So I got this
```
itemIds1 = ('2394328')
itemIds2 = ('6546345')
count2 = 1
itemIdsCount = ('itemIds' + count2)
while (count2 < 2):
#Do stuff
count2 = count2 + 1
```
I'm not sure if I explained this correct. But in line 4 I want to make the string to equal itemIds1 then once it looks make it equal itemsIds2.
If you don't know I'm clearly new to python so if you can explain what to do clearly that would be awesome. | 2017/04/24 | [
"https://Stackoverflow.com/questions/43578466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7147212/"
] | Here are possible options:
1. Use `%s`
>
> itemIdsCount = 'itemIds%s' + count
>
>
>
2. Cast integer to string first
>
> itemIdsCount = 'itemIds' + str(count)
>
>
>
3. Use `.format()` method
>
> itemIdsCount = 'itemIds{}'.format(count)
>
>
>
4. If you have python 3.6, you can use F-string (Literal String Interpolation)
>
> count = 1
>
>
> itemIdsCount = f'itemIds{count}'
>
>
> | The following will create the string you need:
```
itemIdsCount = "itemIds%d" % count2
```
so you can look up python for strings, and see how you can use %s,%d and others to inject what comes after.
As an additionalNote, if you need to append multiple items you would need to say something like this:
```
itemIdsCount = "Id:%d Name:%s" % (15, "Misha")
``` |
43,578,466 | So I got this
```
itemIds1 = ('2394328')
itemIds2 = ('6546345')
count2 = 1
itemIdsCount = ('itemIds' + count2)
while (count2 < 2):
#Do stuff
count2 = count2 + 1
```
I'm not sure if I explained this correct. But in line 4 I want to make the string to equal itemIds1 then once it looks make it equal itemsIds2.
If you don't know I'm clearly new to python so if you can explain what to do clearly that would be awesome. | 2017/04/24 | [
"https://Stackoverflow.com/questions/43578466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7147212/"
] | The following will create the string you need:
```
itemIdsCount = "itemIds%d" % count2
```
so you can look up python for strings, and see how you can use %s,%d and others to inject what comes after.
As an additionalNote, if you need to append multiple items you would need to say something like this:
```
itemIdsCount = "Id:%d Name:%s" % (15, "Misha")
``` | if you need to equal string and integer maybe you should use str(x) or int(x). in this case itemIdsCount = ('itemIds' + str(count2)) |
43,578,466 | So I got this
```
itemIds1 = ('2394328')
itemIds2 = ('6546345')
count2 = 1
itemIdsCount = ('itemIds' + count2)
while (count2 < 2):
#Do stuff
count2 = count2 + 1
```
I'm not sure if I explained this correct. But in line 4 I want to make the string to equal itemIds1 then once it looks make it equal itemsIds2.
If you don't know I'm clearly new to python so if you can explain what to do clearly that would be awesome. | 2017/04/24 | [
"https://Stackoverflow.com/questions/43578466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7147212/"
] | You can use `format`, i.e.:
```
count2 = 1
itemIdsCount = ('itemIds{}'.format(count2))
while (count2 < 2):
#Do stuff
count2 += 1 # it's simpler like this
``` | The following will create the string you need:
```
itemIdsCount = "itemIds%d" % count2
```
so you can look up python for strings, and see how you can use %s,%d and others to inject what comes after.
As an additionalNote, if you need to append multiple items you would need to say something like this:
```
itemIdsCount = "Id:%d Name:%s" % (15, "Misha")
``` |
43,578,466 | So I got this
```
itemIds1 = ('2394328')
itemIds2 = ('6546345')
count2 = 1
itemIdsCount = ('itemIds' + count2)
while (count2 < 2):
#Do stuff
count2 = count2 + 1
```
I'm not sure if I explained this correct. But in line 4 I want to make the string to equal itemIds1 then once it looks make it equal itemsIds2.
If you don't know I'm clearly new to python so if you can explain what to do clearly that would be awesome. | 2017/04/24 | [
"https://Stackoverflow.com/questions/43578466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7147212/"
] | Here are possible options:
1. Use `%s`
>
> itemIdsCount = 'itemIds%s' + count
>
>
>
2. Cast integer to string first
>
> itemIdsCount = 'itemIds' + str(count)
>
>
>
3. Use `.format()` method
>
> itemIdsCount = 'itemIds{}'.format(count)
>
>
>
4. If you have python 3.6, you can use F-string (Literal String Interpolation)
>
> count = 1
>
>
> itemIdsCount = f'itemIds{count}'
>
>
> | if you need to equal string and integer maybe you should use str(x) or int(x). in this case itemIdsCount = ('itemIds' + str(count2)) |
43,578,466 | So I got this
```
itemIds1 = ('2394328')
itemIds2 = ('6546345')
count2 = 1
itemIdsCount = ('itemIds' + count2)
while (count2 < 2):
#Do stuff
count2 = count2 + 1
```
I'm not sure if I explained this correct. But in line 4 I want to make the string to equal itemIds1 then once it looks make it equal itemsIds2.
If you don't know I'm clearly new to python so if you can explain what to do clearly that would be awesome. | 2017/04/24 | [
"https://Stackoverflow.com/questions/43578466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7147212/"
] | Here are possible options:
1. Use `%s`
>
> itemIdsCount = 'itemIds%s' + count
>
>
>
2. Cast integer to string first
>
> itemIdsCount = 'itemIds' + str(count)
>
>
>
3. Use `.format()` method
>
> itemIdsCount = 'itemIds{}'.format(count)
>
>
>
4. If you have python 3.6, you can use F-string (Literal String Interpolation)
>
> count = 1
>
>
> itemIdsCount = f'itemIds{count}'
>
>
> | You can use `format`, i.e.:
```
count2 = 1
itemIdsCount = ('itemIds{}'.format(count2))
while (count2 < 2):
#Do stuff
count2 += 1 # it's simpler like this
``` |
43,578,466 | So I got this
```
itemIds1 = ('2394328')
itemIds2 = ('6546345')
count2 = 1
itemIdsCount = ('itemIds' + count2)
while (count2 < 2):
#Do stuff
count2 = count2 + 1
```
I'm not sure if I explained this correct. But in line 4 I want to make the string to equal itemIds1 then once it looks make it equal itemsIds2.
If you don't know I'm clearly new to python so if you can explain what to do clearly that would be awesome. | 2017/04/24 | [
"https://Stackoverflow.com/questions/43578466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7147212/"
] | You can use `format`, i.e.:
```
count2 = 1
itemIdsCount = ('itemIds{}'.format(count2))
while (count2 < 2):
#Do stuff
count2 += 1 # it's simpler like this
``` | if you need to equal string and integer maybe you should use str(x) or int(x). in this case itemIdsCount = ('itemIds' + str(count2)) |
18,879 | I want to be able to grab multiple media clips from my project window all at once, then drag and drop them to a timeline stacked on top of each other as opposed to side by side. Each track would take its own track in the timeline.
Sort of like keyframe assisting in after effects.
Is there a way for this to be done, maybe by holding down a particular keyboard command? | 2016/07/11 | [
"https://avp.stackexchange.com/questions/18879",
"https://avp.stackexchange.com",
"https://avp.stackexchange.com/users/16118/"
] | I dont believe there is any native built in way to do this. The easiest way would likely to build a simple keyboard mouse macro which can be run to repeat the action of selecting the next clip down, and adding to a new track at the start of the sequence. | Adobe Premiere Pro CC 2015 has a thing called a Multi-Camera Source Sequence. This is kind of a combination of both a multicam clip and a sequence. I believe it is enough of a sequence that it can behave like a sequence, meaning that if you were to composite the layers together instead of switching between them, you'd get the expected result. Such sequences can be created by selecting a number of Project items, as you wish to do. When you create such a sequence, choose "In" points to sync everything, which means everything starts with each clip's first frame. For more about this new feature, read the [relevant section](https://helpx.adobe.com/premiere-pro/using/create-multi-camera-source-sequence.html#UsetheMulticameraSourceSequencedialogbox) of the Adobe manual. |
59,955,394 | I got somme issue with Symfony to convert a DateTime into string. I use a DataTransformer to format my Datetime but in the form, there is an error that say : "This value should be of type string".
Here is my code:
My Entity : Shift.php (only the necessary)
```php
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="datetime")
* @Assert\DateTime(message="La date de début doit être au format DateTime")
*/
private $start_at;
```
My ShiftType :
```php
$builder
->add('start_at', TextType::class, ['attr' => [ 'class' => 'dateTimePicker']])
->add('end_at', TextType::class, ['attr' => [ 'class' => 'dateTimePicker']])
->add('has_eat')
->add('break_duration')
->add('comment')
;
$builder->get('start_at')->addModelTransformer($this->transformer);
$builder->get('end_at')->addModelTransformer($this->transformer);
```
And my DataTransformer :
```php
/**
* @param DateTime|null $datetime
* @return string
*/
public function transform($datetime)
{
if ($datetime === null)
{
return '';
}
return $datetime->format('Y-m-d H:i');
}
/**
* @param string $dateString
* @return Datetime|null
*/
public function reverseTransform($dateString)
{
if (!$dateString)
{
throw new TransformationFailedException('Pas de date(string) passé');
return;
}
$date = \Datetime::createFromFormat('Y-m-d H:i', $dateString);
if($date === false){
throw new TransformationFailedException("Le format n'est pas le bon (fonction reverseTransform)" . "$dateString");
}
return $date;
}
```
As i said, when i want submit the form, there are errors with the form.
It said "This value should be of type string." and it's caused by :
```
Symfony\Component\Validator\ConstraintViolation {#1107 ▼
root: Symfony\Component\Form\Form {#678 …}
path: "data.start_at"
value: DateTime @1578465000 {#745 ▶}
}
```
Something weard, when i want to edit a shift, Symfony get the date from the db and transform it into string with no error message. But as i want to save the edit, i got the same issue
Could you help me please ?
Thanks | 2020/01/28 | [
"https://Stackoverflow.com/questions/59955394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11013169/"
] | You can group by product and use conditional aggregation:
```
SELECT
[Product_ID/No], [Product_Name],
SUM(IIF(DATESERIAL(YEAR(DATE()), MONTH(DATE()), 1) = DATESERIAL(YEAR([Date]), MONTH([Date]), 1), Revenue, NULL)) AS Current_Month,
SUM(IIF(DATESERIAL(YEAR(DATEADD("m", -1, DATE())), MONTH(DATEADD("m", -1, DATE())), 1) = DATESERIAL(YEAR([Date]), MONTH([Date]), 1), Revenue, NULL)) AS Previous_Month,
Nz(Current_Month)- Nz(Previous_Month) AS Variance
FROM Sales
GROUP BY [Product_ID/No], [Product_Name]
```
Results:
```
Product_ID/No Product_Name Current_Month Previous_Month Variance
A APPLE 110 50 60
B BANANA 100 150 -50
C CHERRY 50 -50
``` | this query is for SQL Server :
```
WITH Temp
AS (SELECT [Product_ID/No],
[Product_Name],
ISNULL(SUM(IIF(DATEPART(MONTH, GETDATE()) = DATEPART(MONTH, [Date]), Revenue, NULL)), 0) AS Current_Month,
ISNULL(SUM(IIF(DATEPART(MONTH, DATEADD(MONTH, -1, GETDATE())) = DATEPART(MONTH, [Date]), Revenue, NULL)), 0) AS Previous_Month
FROM dbo.Sales
GROUP BY [Product_ID/No],
[Product_Name])
SELECT *,
(Temp.Current_Month - Temp.Previous_Month) AS Variance
FROM Temp;
``` |
132,170 | So, every time I switch to orthographic mode in Blender 2.8 (Didn't use to happen in 2.79) my model starts clipping (as shown in the video). I've tried changing the "clip start" value, but that just ruins it when I switch back over to the dynamic view.
Any ideas?
Video: <https://youtu.be/EuOuOvNPw78> | 2019/02/18 | [
"https://blender.stackexchange.com/questions/132170",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/69387/"
] | I've been having the same problem and fortunately we are not alone and somebody has already reported this bug. You can find the current state of it at the link below. It looks like it's been resolved and we're just waiting on an update now.
Bug report
<https://developer.blender.org/T61632>
Specific commit with the fix
<https://developer.blender.org/rB4bbd1b9610f6d85079ea5bc31fc1949f8409a1a4> | set it up like in this capture, thats its the right values [](https://i.stack.imgur.com/NTHDG.png) |
66,190,751 | Problem Description:
--------------------
I am looking for a way to access the `li`-elements between two specific heading-tags only (e.g.from 2nd `h3` to 3rd `h3` or from 3rd `h3` to next `h4`) in order to create a table of historical events listed on <https://de.wikipedia.org/wiki/1._Januar> structured along the criteria mentioned in the headings.
A major problem (for me ...) is that - other than the `h1`-heading - the subtitles of the lower levels have no `className` or `id`.
Sample of HTML:
---------------
```html
<div class="mw-parser-output">
[...]
</h3>
<ul>
<li><a href="/wiki/153_v._Chr." title="153 v. Chr.">153 v. Chr.</a>: Die <a href="/wiki/Consulat" title="Consulat">Konsuln</a> der <a href="/wiki/R%C3%B6mische_Republik" title="Römische Republik">römischen Republik</a> beginnen ihre Amtszeit erstmals
am 1. Januar statt am 1. März; daher ist der 1. Januar heute der Jahresanfang.</li>
<li><span style="visibility:hidden;">0</span><a href="/wiki/45_v._Chr." title="45 v. Chr.">45 v. Chr.</a>: <a href="/wiki/Kalenderreform_des_Gaius_Iulius_Caesar" title="Kalenderreform des Gaius Iulius Caesar">Caesars Reform</a> des <a href="/wiki/R%C3%B6mischer_Kalender"
title="Römischer Kalender">römischen Kalenders</a> endet. Dieser wird ab 2. Januar 709 <a href="/wiki/Ab_urbe_condita_(Chronologie)" title="Ab urbe condita (Chronologie)">a. u. c.</a> durch den <a href="/wiki/Julianischer_Kalender" title="Julianischer Kalender">julianischen Kalender</a> ersetzt.</li>
<li><span style="visibility:hidden;">0</span><a href="/wiki/32_v._Chr." title="32 v. Chr.">32 v. Chr.</a>: <a href="/wiki/Augustus" title="Augustus">Oktavian</a> lässt sich vom <a href="/wiki/R%C3%B6mischer_Senat" title="Römischer Senat">Senat</a> zum
„Führer Italiens“ (<i><a href="/wiki/Dux_(Titel)" title="Dux (Titel)">dux Italiae</a></i>) ausrufen. Er erklärt <a href="/wiki/Kleopatra_VII." title="Kleopatra VII.">Kleopatra</a> und damit <i><a href="/wiki/De_jure/de_facto" title="De jure/de facto">de facto</a></i> auch <a href="/wiki/Marcus_Antonius" title="Marcus Antonius">Marcus Antonius</a> den Krieg.</li>
</ul>
[...]
</ul>
<h4><span id="Inkrafttreten_von_Gesetzen_und_Staatsvertr.C3.A4gen"></span><span class="mw-headline" id="Inkrafttreten_von_Gesetzen_und_Staatsverträgen">Inkrafttreten von Gesetzen und Staatsverträgen</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span>
<a href="/w/index.php?title=1._Januar&veaction=edit&section=3" class="mw-editsection-visualeditor" title="Abschnitt bearbeiten: Inkrafttreten von Gesetzen und Staatsverträgen">Bearbeiten</a><span class="mw-editsection-divider"> | </span>
<a href="/w/index.php?title=1._Januar&action=edit&section=3" title="Abschnitt bearbeiten: Inkrafttreten von Gesetzen und Staatsverträgen">Quelltext bearbeiten</a><span class="mw-editsection-bracket">]</span></span>
</h4>
<p><i>Der 1. Januar wird oft für das Inkrafttreten von Gesetzen und Staatsverträgen verwendet. Das gilt unter anderem für:</i>
</p>
<ul>
<li><a href="/wiki/1812" title="1812">1812</a>: das <i><a href="/wiki/Allgemeines_b%C3%BCrgerliches_Gesetzbuch" title="Allgemeines bürgerliches Gesetzbuch">Allgemeine bürgerliche Gesetzbuch</a></i> <i>(ABGB)</i> in den <a href="/wiki/Habsburgermonarchie#Erblande"
title="Habsburgermonarchie">habsburgischen Erblanden</a>.</li>
</ul>
[...]
</h4>
<p><i>Folgende Staaten erhalten am 1. Januar ihre Unabhängigkeit:</i>
</p>
<ul>
[...]
</ul>
<h3><span class="mw-headline" id="Wirtschaft">Wirtschaft</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=1._Januar&veaction=edit&section=6" class="mw-editsection-visualeditor" title="Abschnitt bearbeiten: Wirtschaft">Bearbeiten</a>
<span class="mw-editsection-divider"> | </span><a href="/w/index.php?title=1._Januar&action=edit&section=6" title="Abschnitt bearbeiten: Wirtschaft">Quelltext bearbeiten</a><span class="mw-editsection-bracket">]</span></span>
</h3>
<h4><span class="mw-headline" id="Wichtige_Ereignisse_in_der_Weltwirtschaft">Wichtige Ereignisse in der Weltwirtschaft</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=1._Januar&veaction=edit&section=7"
class="mw-editsection-visualeditor" title="Abschnitt bearbeiten: Wichtige Ereignisse in der Weltwirtschaft">Bearbeiten</a><span class="mw-editsection-divider"> | </span><a href="/w/index.php?title=1._Januar&action=edit&section=7" title="Abschnitt bearbeiten: Wichtige Ereignisse in der Weltwirtschaft">Quelltext bearbeiten</a>
<span class="mw-editsection-bracket">]</span>
</span>
</h4>
<ul>
<li><a href="/wiki/1780" title="1780">1780</a>: In <a href="/wiki/Geschichte_Bratislavas" title="Geschichte Bratislavas">Preßburg</a> erscheint die erste ungarische Zeitung <i>Magyar hírmondó</i> („Ungarischer Kurier“).</li>
```
So far, I only managed to access **all** the `li`-elements (more than 1000!) that are not part of the table of contents with the following code:
Experimental Code Example:
--------------------------
```
Sub HistoricalEvents_Test()
Dim http As Object, html As New MSHTML.HTMLDocument
Dim oLiList As MSHTML.IHTMLDOMChildrenCollection
Dim data As String
Dim r As Integer
Dim oWord As Object, oWordDoc As Object
Dim wordApp As New Word.Application
Dim iFirstRow As Integer, iLastRow As Integer
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://de.wikipedia.org/wiki/1._Januar", False
http.send
html.body.innerHTML = http.responseText
Dim lLiResultList As Long
Dim lLiResultLoop As Long
Set oLiList = html.querySelectorAll("#toc ~ ul li")
For lLiResultLoop = 0 To oLiList.Length - 1
Dim oLiChild As Object
Set oLiChild = oIlList.Item(lLilResultLoop)
data = oLiChild.innerText 'data = data & vbCrLf & oLiChild.innerText
Range("B" & lLiResultLoop +1).Value = data
data = vbNullString
Next lLiResultLoop
Dim j As Long
Dim Ws As Worksheet
Dim rngDB As Range
Set Ws = ActiveSheet
Set oWord = CreateObject("Word.Application")
Set oWordDoc = oWord.Documents.Open("D:\Jahrestage Geschichte.docx")
iFirstRow = 1 ' "Ws.Cells(1, 2).End(xlDown).Row" used to work fine but suddenly gives same as iLastRow!
'Debug.Print iFirstRow
iLastRow = Ws.Cells(ActiveSheet.Rows.Count, "B").End(xlUp).Row
'Debug.Print iLastRow
oWord.Visible = True
With wordApp
With Ws
Set rngDB = Ws.Range(.Cells(iFirstRow, 2), .Cells(iLastRow, 2))
End With
rngDB.Cut
oWord.Selection.PasteSpecial DataType:=wdPasteText
oWord.Selection.TypeParagraph
oWord.Selection = ""
End With
oWordDoc.Close savechanges:=True
wordApp.Quit 'it doesn't :(
End Sub
```
Description of General Idea/Final Project
-----------------------------------------
The final project is supposed to have a worksheet for every month, each containing a table with a row for every day of the respective month and columns for the different categories according to the (sub-)titles. The Word-output in the code is just an early-stage by-product and something I will round off only if/when the main problem can be solved.
Further Remarks
---------------
This is my first contribution on SO. I'm an absolute beginner when it comes to vba and web-scraping (or any kind of coding, scripting or programming for that matter), but I kind of got sucked into it and spent the better part of my winter holiday just to figure out the above code. I wouldn't have been able to accomplish even that poor piece of scripting without the invaluable knowledge shared with noobs like me by the cracks of SO. I've tried out various approaches but I always got stuck at some point, VBA triggering runtime errors and often Excel crashing. In particular, I wasn't able to implement the `nextSibling`/`previousSibling` methods or the `nodeName` selector successfully which I figure might be a promising approach to the problem. So any help or hint would be greatly appreciated!
Working Solution:
-----------------
Thanks to the feedback on my question I finally managed to figure out a solution that does the job, although maybe not in the most elegant way. The only remaining problem is that strangely the `li-elements` of the last column are duplicated. So if anyone has a clue how to deal with that ...
```
Sub SliceHtmlByHeaderTypes4()
Dim http As Object, html As MSHTML.HTMLDocument
Dim sh As Worksheet
Set sh = ThisWorkbook.ActiveSheet
Set http = CreateObject("MSXML2.XMLHTTP"): Set html = New MSHTML.HTMLDocument
http.Open "GET", "https://de.wikipedia.org/wiki/1._Januar", False
http.send
html.body.innerHTML = http.responseText
Dim hNodeList As Object
Dim startPos As Long, endPos As Long
Dim s As Integer, e As Integer
Set hNodeList = html.querySelectorAll("#toc ~ h2, #toc ~ h3, #toc ~ h4")
Debug.Print hNodeList.Length
Do While s < hNodeList.Length - 1
http.Open "GET", "https://de.wikipedia.org/wiki/1._Januar", False
http.send
html.body.innerHTML = http.responseText
Set hNodeList = html.querySelectorAll("#toc ~ h2, #toc ~ h3, #toc ~ h4")
startPos = InStr(html.body.outerHTML, hNodeList.Item(s).outerHTML)
endPos = InStr(html.body.outerHTML, hNodeList.Item(s + 1).outerHTML)
If startPos > 0 And endPos > 0 And endPos > startPos Then
Dim strS As String
strS = Mid$(html.body.outerHTML, startPos, endPos - startPos + 1)
Else
MsgBox "Problem slicing string"
Stop
Exit Sub
End If
Dim liList As Object
html.body.innerHTML = strS
Set liList = html.getElementsByTagName("li")
If liList.Length > 0 Then
Dim i As Integer
Dim liText As String
Dim lc As Integer
Dim liRange As Range
lc = (Cells(2, Columns.Count).End(xlToLeft).Column) + 1
Set liRange = sh.Range(Cells(2, lc), Cells(2, lc))
For i = 0 To liList.Length - 1
On Error Resume Next
liText = liList.Item(i).innerText
liRange.Value = liRange.Value & liText & vbNewLine
liText = vbNullString
Next i
strS = vbNullString
startPos = 0
endPos = 0
hNodeList = ""
i = 0
End If
s = s + 1
Loop
End Sub
``` | 2021/02/13 | [
"https://Stackoverflow.com/questions/66190751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11779702/"
] | Please verify your cproj file and check if they're being excluded. You can add this to your csproj file to have the content of `wwwroot` copied over:
```
<ItemGroup>
<None Include="wwwroot\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
``` | I had the same/similar issue which was resolved by deleting the folders
projectroot/bin
projectroot/obj
please also set the file properties in solution explorer to "copy if newer" as shown in the image below
[](https://i.stack.imgur.com/voPzG.png) |
41,655,412 | What I'm trying to do is to center the text (and image that will be side by side or on top of the text) but the command justify-content:center doesn't work for me. It centers horizontally but not vertically. Could you tell me what went wrong? I'm actually a beginner and that's my first website.
Here's the code:
```css
body {
font-family: Gotham A,Gotham B,Helvetica,Arial,sans-serif;
}
h1 {
font-size: 3em;
text-transform:uppercase;
}
h4 {
font-size: 1.5em;
color:#9e9e9e;
}
section {
width: 100%;
display: inline-block;
margin: 0;
max-width: 960;
height:100vh;
vertical-align: middle;
}
#welcome-screen {
width: 100%;
display: table;
margin: 0;
max-width: none;
height:100vh;
background-color:#ebebeb;
padding:0 7%;
}
.heading {
display:table-cell;
vertical-align: middle;
}
.heading-span {
display: block;
color: #8e8e8e;
font-size: 18px;
margin-top: 0px;
text-transform:none;
}
.scrolldown-button {
position: absolute;
display: table;
text-align: center;
bottom: 30px;
left: 0;
right: 0;
margin: 0 auto 0 auto;
width: 48px;
height: 48px;
font-size:20px;
}
a {
color:#000000;
transition: ease-in-out 0.15s
}
a:hover{
color:#fbd505;
}
#content {
width: 100%;
height:100vh;
}
.wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
p {
display:column;
vertical-align: middle;
max-width: 960px;
}
.content-heading-span {
display: block;
font-size: 32px;
margin-top: 0px;
text-transform:uppercase;
margin-left:-20px;
}
```
```html
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cloud.typography.com/6493094/7214972/css/fonts.css">
</head>
<body>
<section id="welcome-screen">
<div class="heading">
<h1><span class="heading-span">Hi! My name is</span>
<strong>John Doe</strong>
</h1>
</div>
<div class="scrolldown-button">
<a href="#content"><span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span></a>
</div>
</section>
<section>
<div id="content">
<div class="wrapper">
<p><span class="content-heading-span"><strong>O Mnie</strong></span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget bibendum odio, eget varius tortor. Etiam imperdiet, sem in faucibus convallis, justo purus rutrum magna, ut lacinia ex tellus sit amet lectus. Curabitur tempor imperdiet laoreet. Quisque magna magna, tempus a nibh vitae, maximus malesuada mi. Nulla a justo dolor. Nullam risus nisl, vulputate vel arcu id, viverra finibus mauris. Donec porttitor lectus ut augue vehicula, vitae vehicula turpis eleifend. Proin eu quam at odio consectetur tincidunt. Proin eget elit id purus lacinia tincidunt. Nam at urna est. Quisque viverra nisi eu molestie accumsan. Ut at porttitor sem, quis viverra massa. Nulla odio libero, dictum a diam euismod, rhoncus efficitur lectus. Suspendisse eu mi vel diam euismod fermentum at et.</p>
<p><span class="content-heading-span"><strong>O Mnie</strong></span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget bibendum odio, eget varius tortor. Etiam imperdiet, sem in faucibus convallis, justo purus rutrum magna, ut lacinia ex tellus sit amet lectus. Curabitur tempor imperdiet laoreet. Quisque magna magna, tempus a nibh vitae, maximus malesuada mi. Nulla a justo dolor. Nullam risus nisl, vulputate vel arcu id, viverra finibus mauris. Donec porttitor lectus ut augue vehicula, vitae vehicula turpis eleifend. Proin eu quam at odio consectetur tincidunt. Proin eget elit id purus lacinia tincidunt. Nam at urna est. Quisque viverra nisi eu molestie accumsan. Ut at porttitor sem, quis viverra massa. Nulla odio libero, dictum a diam euismod, rhoncus efficitur lectus. Suspendisse eu mi vel diam euismod fermentum at et.</p>
</div>
</div>
</body>
</html>
``` | 2017/01/14 | [
"https://Stackoverflow.com/questions/41655412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7419823/"
] | This JS Bin is a working example of converting a File to base64: <http://jsbin.com/piqiqecuxo/1/edit?js,console,output> . The main addition seems to be reading the file using a `FileReader`, where `FileReader.readAsDataURL()` returns a base64 encoded string
```
document.getElementById('button').addEventListener('click', function() {
var files = document.getElementById('file').files;
if (files.length > 0) {
getBase64(files[0]);
}
});
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
``` | If you want it in a neat method that works with async / await, you can do it this way
```
const getBase64 = async (file: Blob): Promise<string | undefined> => {
var reader = new FileReader();
reader.readAsDataURL(file as Blob);
return new Promise((reslove, reject) => {
reader.onload = () => reslove(reader.result as any);
reader.onerror = (error) => reject(error);
})
}
``` |
29,934,126 | sorry, I need some help finding the right regular expression for this.
Basically I want to recognize via regex if the following format is in a string:
artist - title (something)
examples:
```
"ellie goulding - good gracious (the chainsmokers remix)"
"the xx - you got the love (florence and the machine cover)"
"neneh cherry - everything (loco dice remix)"
"my chemical romance - famous last words (video)"
```
I have been trying but haven't been able to find the right regular expression.
```
regex = "[A-Za-z0-9\s]+[\-]{1}[A-Za-z0-9\s]+[\(]{1}[\s]*[A-Za-z0-9\s]*[\)]{1}"
```
help please! | 2015/04/29 | [
"https://Stackoverflow.com/questions/29934126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4844612/"
] | Well for storing images you can try this
* If you want to save images which are not coming from server and are stored in drawable/mipmap folder just store their id like
initialValues.put(COLUMN\_IMAGE, R.mipmap.demp);
* And if they are coming from server or api call just save their url and load them using any library such as picaso or something.
I tried the same in one of my app it worked. | Convert your image into base64 encoded string and then insert that string into database:
```
Bitmap bm = BitmapFactory.decodeFile("<path to your image>");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedString = Base64.encodeToString(b, Base64.DEFAULT);
```
When your fetch the string then convert it like this:
```
byte[] b= Base64.decode(encodedString , Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(b,0,b.length);
``` |
29,934,126 | sorry, I need some help finding the right regular expression for this.
Basically I want to recognize via regex if the following format is in a string:
artist - title (something)
examples:
```
"ellie goulding - good gracious (the chainsmokers remix)"
"the xx - you got the love (florence and the machine cover)"
"neneh cherry - everything (loco dice remix)"
"my chemical romance - famous last words (video)"
```
I have been trying but haven't been able to find the right regular expression.
```
regex = "[A-Za-z0-9\s]+[\-]{1}[A-Za-z0-9\s]+[\(]{1}[\s]*[A-Za-z0-9\s]*[\)]{1}"
```
help please! | 2015/04/29 | [
"https://Stackoverflow.com/questions/29934126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4844612/"
] | Well for storing images you can try this
* If you want to save images which are not coming from server and are stored in drawable/mipmap folder just store their id like
initialValues.put(COLUMN\_IMAGE, R.mipmap.demp);
* And if they are coming from server or api call just save their url and load them using any library such as picaso or something.
I tried the same in one of my app it worked. | This is a method to store your bitmap image into database, you need to assign a type of column as Blob for image in database table
```
protected long saveBitmap(SQLiteDatabase database, Bitmap bmp) {
Log.d("ImageDatabase", ":: Method Called");
int bytes = bmp.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes);
bmp.copyPixelsToBuffer(buffer);
byte[] array = buffer.array();
Log.d("ImageDatabase", ":: ByteArray Created");
ContentValues cv = new ContentValues();
cv.put("img", bytes);
Log.d("ImageDatabase", ":: Before Insert");
long rs = database.insert("images", null, cv);
Log.d("ImageDatabase", ":: After Insert");
return rs;
}
``` |
29,934,126 | sorry, I need some help finding the right regular expression for this.
Basically I want to recognize via regex if the following format is in a string:
artist - title (something)
examples:
```
"ellie goulding - good gracious (the chainsmokers remix)"
"the xx - you got the love (florence and the machine cover)"
"neneh cherry - everything (loco dice remix)"
"my chemical romance - famous last words (video)"
```
I have been trying but haven't been able to find the right regular expression.
```
regex = "[A-Za-z0-9\s]+[\-]{1}[A-Za-z0-9\s]+[\(]{1}[\s]*[A-Za-z0-9\s]*[\)]{1}"
```
help please! | 2015/04/29 | [
"https://Stackoverflow.com/questions/29934126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4844612/"
] | The simplest technique you can follow is to store your Image path in the database table as a String and then you can get it back whenever you need that image and decode it using `BitmapFactory.decodeFile`. Storing Base64String is fine but the string will have too large so, if you will see the path of image it is comparatively a shorter string
**For Example:**
* define another parameter in your `createRecipe()` method named `String imagePath` like:
`public void createRecipe(String name,String type, String ingred,String imgPath){}`
* When you make a call to this function you will pass the image path what ever you have like:
`createRecipe(name,type,ingred,path_of_image)`
To get ImagePath you can do something like that:
```
String destination = new File(Environment.getExternalStorageDirectory(), name_of_your_image+ ".jpg");
FileInputStream in = new FileInputStream(destination);
String photoPath = destination.getAbsolutePath();
```
* Finally when you call your `fetchRecipesByName()` or `fetchAllRecipes()` method the `Cursor` will now have your path stored against each entry you can get this path as a String and pass it to the below function you will get Bitmap in return.
>
>
> ```
> private Bitmap getBitmapFromPath(String path)
> {
> BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
>
> btmapOptions.inSampleSize = 2;
>
> Bitmap bm = BitmapFactory.decodeFile(path, btmapOptions);
>
> return bm;
> }
>
> ```
>
>
**Note:** You should also take care if you are storing path of image and it could be deleted from gallery so in return you cannot have any bitmap against this path so you should manage if image dosen't exist then use an alternative image. | Convert your image into base64 encoded string and then insert that string into database:
```
Bitmap bm = BitmapFactory.decodeFile("<path to your image>");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedString = Base64.encodeToString(b, Base64.DEFAULT);
```
When your fetch the string then convert it like this:
```
byte[] b= Base64.decode(encodedString , Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(b,0,b.length);
``` |
29,934,126 | sorry, I need some help finding the right regular expression for this.
Basically I want to recognize via regex if the following format is in a string:
artist - title (something)
examples:
```
"ellie goulding - good gracious (the chainsmokers remix)"
"the xx - you got the love (florence and the machine cover)"
"neneh cherry - everything (loco dice remix)"
"my chemical romance - famous last words (video)"
```
I have been trying but haven't been able to find the right regular expression.
```
regex = "[A-Za-z0-9\s]+[\-]{1}[A-Za-z0-9\s]+[\(]{1}[\s]*[A-Za-z0-9\s]*[\)]{1}"
```
help please! | 2015/04/29 | [
"https://Stackoverflow.com/questions/29934126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4844612/"
] | The simplest technique you can follow is to store your Image path in the database table as a String and then you can get it back whenever you need that image and decode it using `BitmapFactory.decodeFile`. Storing Base64String is fine but the string will have too large so, if you will see the path of image it is comparatively a shorter string
**For Example:**
* define another parameter in your `createRecipe()` method named `String imagePath` like:
`public void createRecipe(String name,String type, String ingred,String imgPath){}`
* When you make a call to this function you will pass the image path what ever you have like:
`createRecipe(name,type,ingred,path_of_image)`
To get ImagePath you can do something like that:
```
String destination = new File(Environment.getExternalStorageDirectory(), name_of_your_image+ ".jpg");
FileInputStream in = new FileInputStream(destination);
String photoPath = destination.getAbsolutePath();
```
* Finally when you call your `fetchRecipesByName()` or `fetchAllRecipes()` method the `Cursor` will now have your path stored against each entry you can get this path as a String and pass it to the below function you will get Bitmap in return.
>
>
> ```
> private Bitmap getBitmapFromPath(String path)
> {
> BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
>
> btmapOptions.inSampleSize = 2;
>
> Bitmap bm = BitmapFactory.decodeFile(path, btmapOptions);
>
> return bm;
> }
>
> ```
>
>
**Note:** You should also take care if you are storing path of image and it could be deleted from gallery so in return you cannot have any bitmap against this path so you should manage if image dosen't exist then use an alternative image. | This is a method to store your bitmap image into database, you need to assign a type of column as Blob for image in database table
```
protected long saveBitmap(SQLiteDatabase database, Bitmap bmp) {
Log.d("ImageDatabase", ":: Method Called");
int bytes = bmp.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes);
bmp.copyPixelsToBuffer(buffer);
byte[] array = buffer.array();
Log.d("ImageDatabase", ":: ByteArray Created");
ContentValues cv = new ContentValues();
cv.put("img", bytes);
Log.d("ImageDatabase", ":: Before Insert");
long rs = database.insert("images", null, cv);
Log.d("ImageDatabase", ":: After Insert");
return rs;
}
``` |
597,089 | I dual booted windows 8.0 x86 with ubuntu 14.04. Then tried accessing the volume containing windows but I got this error message:
```
Error mounting /dev/sda2 at /media/van/BE96C17E96C13823: Command-line `mount -t "ntfs" -o "uhelper=udisks2,nodev,nosuid,uid=1000,gid=1000,dmask=0077,fmask=0177" "/dev/sda2" "/media/van/BE96C17E96C13823"' exited with non-zero exit status 14: Windows is hibernated, refused to mount.
Failed to mount '/dev/sda2': Operation not permitted
The NTFS partition is in an unsafe state. Please resume and shutdown
Windows fully (no hibernation or fast restarting), or mount the volume
read-only with the 'ro' mount option.
```
I would really appreciate the solution I can take to solve this problem. | 2015/03/15 | [
"https://askubuntu.com/questions/597089",
"https://askubuntu.com",
"https://askubuntu.com/users/388274/"
] | two things can cause this problem:
1. dont start Ubuntu after you hibernate windows. Always do proper shutdown before you start Ubuntu.
2. Disable *Hybird Shutdown* in windows. [Here](http://www.maketecheasier.com/disable-hybrid-boot-and-shutdown-in-windows-8/) is how you can do that.
now all you can do is shutdown Ubuntu and start windows then follow the second method and restart and switch to Ubuntu
Hint: Please read the last sentence from the error you got:
*Please resume and shutdown Windows fully (no hibernation or fast restarting), or mount the volume read-only with the 'ro' mount option.* | You ***must*** shutdown Windows completely - not just hibernate - before you try to mount it in Ubuntu. |
21,004,823 | I would like to know how can I send a swipe gesture programmatically without actually swiping the phone. For instance, I have button that in the `onClick` event I would call `swipeGestureRecognizer`? Is this possible? | 2014/01/08 | [
"https://Stackoverflow.com/questions/21004823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2823451/"
] | You can call the method you are calling on Swipe, when user taps on button. For examaple, you have a method for swipe gesture, call it `onSwipe` . Now call onSwipe methos when user taps on the button. Thats it
**EDIT**
Here is the code for you:
```
-(void)myMethod{
//Write the logic you want to implement for swipe gesture here.
}
-(IBAction)onClick(UIButton *)sender{
[self myMethod];
}
-(IBAction)onSwipe:(UISwipeGestureRecognizer *)recognizer{
[self myMethod];
}
```
There might be bugs on the code as I am just typing the code using windows. Correct it for yourself in MAC & edit the answer too. it would definitely work for you | If you need to pass the gesture event to the handler, then
```
UISwipeGestureRecognizer *gesture = [[UISwipeGestureRecognizer alloc] init];
gesture.direction = UISwipeGestureRecognizerDirectionLeft;
[self handleSwipe:gesture];
``` |
49,689,536 | I have an overlay `(UIImageView)` which should have a transparent background and alpha. How can I set the `imageview` such that it covers the entire screen? Currently, it covers the screen but not the `UIStatusBar`. I am adding the view in `AppDelegate's` main `window` as a `subview`.
The code:
```
let overlay1 = UIImageView(image: UIImage(named: "overlay-image"))
overlay1.contentMode = .scaleAspectFit
overlay1.backgroundColor = UIColor.black
overlay1.alpha = 0.87
overlay1.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
overlay1.isUserInteractionEnabled = true
overlay1.layer.zPosition = 1
(UIApplication.shared.delegate as? AppDelegate).window.addSubview(overlay1)
``` | 2018/04/06 | [
"https://Stackoverflow.com/questions/49689536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8403513/"
] | After discussion in comments found that changing the `backgroundColor` of `statusBar` is the reason why your code is not working properly.
By printing the `superView` of `statusBar` I found that `statusBar` is not added on `UIWindow` instead it is on `UIStatusBarWindow` which is probably above the `mainWindow`.
Also please don't use force unwrapping it can be cause of crash. At last I put a `guard` to fetch the `statusBar`, to check if it responds to `backgroundColor` property, to fetch its `superView` and adding the overlay on this `superView` got it working.
Your check for `respondToSelector` is also wrong. See below code it works as per your requirement.
```
guard let statusBar = UIApplication.shared.value(forKey: "statusBar") as? UIView, statusBar.responds(to: NSSelectorFromString("backgroundColor")), let superView = statusBar.superview else {return}
statusBar.backgroundColor = UIColor.red
let overlay1 = UIImageView(image: UIImage(named: "overlay-image"))
overlay1.contentMode = .scaleAspectFit
overlay1.backgroundColor = UIColor.black
overlay1.alpha = 0.87
overlay1.frame = superView.bounds
overlay1.isUserInteractionEnabled = true
overlay1.layer.zPosition = 1
superView.addSubview(overlay1)
```
**Note: Changing the `statusBar` color is not recommended. You can set its style to `default` or `light`.** | Okay I just tried with something and it worked. Just use it in your `ViewController` like:
```
// You should be using viewDidAppear(_:)
override func viewDidAppear(_ animated: Bool) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let window = appDelegate.window {
let windowFrame = window.frame
let imageView = UIImageView(frame: windowFrame)
imageView.image = #imageLiteral(resourceName: "TakeOff") // use your image
imageView.contentMode = .scaleAspectFit
imageView.backgroundColor = UIColor.green.withAlphaComponent(0.2) // replace green with the color you want
window.addSubview(imageView)
}
}
```
>
> But, remember one thing. It's not a good idea to add an image view as
> an overlay. You should always use a `UIView` as an overlay and add the
> image view as a sub view to that overlay.
>
>
>
**Screenshot:**
[](https://i.stack.imgur.com/VVFEC.png) |
65,971,168 | I have some lines of text, and then their relevance weight.
```
Weight, Text
10, "I like apples"
20, "Someone needs apples"
```
Is it possible to get the combinations, keeping the values in the weights column? Something like:
```
weight, combinations
10, [I like]
10, [I apples]
10, [like apples]
20, [someone needs]
20, [someone apples]
20, [needs apples]
```
"Generate n-grams from Pandas column while persisting another column" (unsolved) is a similar question, but it is unsolved.
Thanks!!! | 2021/01/30 | [
"https://Stackoverflow.com/questions/65971168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14395605/"
] | To fill the first row in 2D array, use `Arrays.fill`, to fill the rest of the rows, use [`Arrays.copyOf`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#copyOf(T%5B%5D,int)).
Next, it's better to implement separate methods to perform different tasks:
1. Create and fill the grid
2. Print the grid
```java
static String[][] fillGrid(int rows, int cols, String cell) {
String[][] grid = new String[rows][cols];
String[] row = new String[cols];
Arrays.fill(row, cell);
grid[0] = row;
for (int i = 1; i < rows; i++) {
grid[i] = Arrays.copyOf(row, cols);
}
return grid;
}
static void printGrid(String[][] grid) {
for (int i = 0; i < grid.length; i++) {
if (i == 0) {
System.out.print(" ");
for (int j = 0; j < grid[0].length; j++) {
System.out.printf("%2d ", j + 1);
}
System.out.println();
}
for (int j = 0; j < grid[i].length; j++) {
if (j == 0) {
System.out.printf("%2d:", i + 1);
}
System.out.printf("%2s ", grid[i][j]);
}
System.out.println();
}
}
```
Then they may be tested like this:
```java
public static void main(String ... args) {
String[][] grid = fillGrid(8, 8, "x");
printGrid(grid);
}
```
The output will be as follows:
```
1 2 3 4 5 6 7 8
1: x x x x x x x x
2: x x x x x x x x
3: x x x x x x x x
4: x x x x x x x x
5: x x x x x x x x
6: x x x x x x x x
7: x x x x x x x x
8: x x x x x x x x
``` | The "import java.util.arrays" needs to be above the class definition at the top of the file. |
65,971,168 | I have some lines of text, and then their relevance weight.
```
Weight, Text
10, "I like apples"
20, "Someone needs apples"
```
Is it possible to get the combinations, keeping the values in the weights column? Something like:
```
weight, combinations
10, [I like]
10, [I apples]
10, [like apples]
20, [someone needs]
20, [someone apples]
20, [needs apples]
```
"Generate n-grams from Pandas column while persisting another column" (unsolved) is a similar question, but it is unsolved.
Thanks!!! | 2021/01/30 | [
"https://Stackoverflow.com/questions/65971168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14395605/"
] | To fill the first row in 2D array, use `Arrays.fill`, to fill the rest of the rows, use [`Arrays.copyOf`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#copyOf(T%5B%5D,int)).
Next, it's better to implement separate methods to perform different tasks:
1. Create and fill the grid
2. Print the grid
```java
static String[][] fillGrid(int rows, int cols, String cell) {
String[][] grid = new String[rows][cols];
String[] row = new String[cols];
Arrays.fill(row, cell);
grid[0] = row;
for (int i = 1; i < rows; i++) {
grid[i] = Arrays.copyOf(row, cols);
}
return grid;
}
static void printGrid(String[][] grid) {
for (int i = 0; i < grid.length; i++) {
if (i == 0) {
System.out.print(" ");
for (int j = 0; j < grid[0].length; j++) {
System.out.printf("%2d ", j + 1);
}
System.out.println();
}
for (int j = 0; j < grid[i].length; j++) {
if (j == 0) {
System.out.printf("%2d:", i + 1);
}
System.out.printf("%2s ", grid[i][j]);
}
System.out.println();
}
}
```
Then they may be tested like this:
```java
public static void main(String ... args) {
String[][] grid = fillGrid(8, 8, "x");
printGrid(grid);
}
```
The output will be as follows:
```
1 2 3 4 5 6 7 8
1: x x x x x x x x
2: x x x x x x x x
3: x x x x x x x x
4: x x x x x x x x
5: x x x x x x x x
6: x x x x x x x x
7: x x x x x x x x
8: x x x x x x x x
``` | The import statement is always defined above the whole program so as to import the prebuild functions and classes hence
```java
import java.util.Arrays;
```
This will be the first line of the program before Main class is defined.
```java
arrays.fill(grid1[0],so);
```
Here since **so** is not a variable, it seems as a string "so", it would be good to define it first or make it a string as "so"
This code might give some idea on how to use it.
```java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[][] grid1 = new String[8][8];
for (int r = 0; r < grid1.length; r++) {
for (int c = 0; c < grid1[r].length; c++)
System.out.print(grid1[r][c] + "\t");
System.out.println();
}
Arrays.fill(grid1[0], "so");
System.out.println("\nAfter the array is: ");
for (int r = 0; r < grid1.length; r++) {
for (int c = 0; c < grid1[r].length; c++)
System.out.print(grid1[r][c] + "\t");
System.out.println();
}
}
}
``` |
65,971,168 | I have some lines of text, and then their relevance weight.
```
Weight, Text
10, "I like apples"
20, "Someone needs apples"
```
Is it possible to get the combinations, keeping the values in the weights column? Something like:
```
weight, combinations
10, [I like]
10, [I apples]
10, [like apples]
20, [someone needs]
20, [someone apples]
20, [needs apples]
```
"Generate n-grams from Pandas column while persisting another column" (unsolved) is a similar question, but it is unsolved.
Thanks!!! | 2021/01/30 | [
"https://Stackoverflow.com/questions/65971168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14395605/"
] | To fill the first row in 2D array, use `Arrays.fill`, to fill the rest of the rows, use [`Arrays.copyOf`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#copyOf(T%5B%5D,int)).
Next, it's better to implement separate methods to perform different tasks:
1. Create and fill the grid
2. Print the grid
```java
static String[][] fillGrid(int rows, int cols, String cell) {
String[][] grid = new String[rows][cols];
String[] row = new String[cols];
Arrays.fill(row, cell);
grid[0] = row;
for (int i = 1; i < rows; i++) {
grid[i] = Arrays.copyOf(row, cols);
}
return grid;
}
static void printGrid(String[][] grid) {
for (int i = 0; i < grid.length; i++) {
if (i == 0) {
System.out.print(" ");
for (int j = 0; j < grid[0].length; j++) {
System.out.printf("%2d ", j + 1);
}
System.out.println();
}
for (int j = 0; j < grid[i].length; j++) {
if (j == 0) {
System.out.printf("%2d:", i + 1);
}
System.out.printf("%2s ", grid[i][j]);
}
System.out.println();
}
}
```
Then they may be tested like this:
```java
public static void main(String ... args) {
String[][] grid = fillGrid(8, 8, "x");
printGrid(grid);
}
```
The output will be as follows:
```
1 2 3 4 5 6 7 8
1: x x x x x x x x
2: x x x x x x x x
3: x x x x x x x x
4: x x x x x x x x
5: x x x x x x x x
6: x x x x x x x x
7: x x x x x x x x
8: x x x x x x x x
``` | Ok, firstly all imports need to be typed at the very top aka beginning of the program so place `import java.util.Arrays;` above `class Main`.
```
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String[][] grid1=new String[8][8];
for (int n=0; n<=grid1.length; n++) {
System.out.print(n+"\t");
}
System.out.println();
for (String[] row: grid1) {
Arrays.fill(row, "x");
}
for (int r=0; r<grid1.length; r++) {
System.out.print(r+1+"\t");
for (int c=0; c<grid1[r].length; c++)
System.out.print(grid1[r][c]+"\t");
System.out.println();
}
}
}
```
The block of code that does the filling
```
for (String[] row: grid1) {
Arrays.fill(row, "x");
}
```
is an enhanced for loop. What it does is it takes each row from your 2D array, stores it in the local variable `row`, and then fills it (the row) with the value "x".
As for the other part of your question i suppose you could use a random number generator to generate the line and column where a bomb will be and store that number in a set. That way the program will know when the player steps on a bomb or treasure, but the player will be unaware of it until it happens. |
65,971,168 | I have some lines of text, and then their relevance weight.
```
Weight, Text
10, "I like apples"
20, "Someone needs apples"
```
Is it possible to get the combinations, keeping the values in the weights column? Something like:
```
weight, combinations
10, [I like]
10, [I apples]
10, [like apples]
20, [someone needs]
20, [someone apples]
20, [needs apples]
```
"Generate n-grams from Pandas column while persisting another column" (unsolved) is a similar question, but it is unsolved.
Thanks!!! | 2021/01/30 | [
"https://Stackoverflow.com/questions/65971168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14395605/"
] | To fill the first row in 2D array, use `Arrays.fill`, to fill the rest of the rows, use [`Arrays.copyOf`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#copyOf(T%5B%5D,int)).
Next, it's better to implement separate methods to perform different tasks:
1. Create and fill the grid
2. Print the grid
```java
static String[][] fillGrid(int rows, int cols, String cell) {
String[][] grid = new String[rows][cols];
String[] row = new String[cols];
Arrays.fill(row, cell);
grid[0] = row;
for (int i = 1; i < rows; i++) {
grid[i] = Arrays.copyOf(row, cols);
}
return grid;
}
static void printGrid(String[][] grid) {
for (int i = 0; i < grid.length; i++) {
if (i == 0) {
System.out.print(" ");
for (int j = 0; j < grid[0].length; j++) {
System.out.printf("%2d ", j + 1);
}
System.out.println();
}
for (int j = 0; j < grid[i].length; j++) {
if (j == 0) {
System.out.printf("%2d:", i + 1);
}
System.out.printf("%2s ", grid[i][j]);
}
System.out.println();
}
}
```
Then they may be tested like this:
```java
public static void main(String ... args) {
String[][] grid = fillGrid(8, 8, "x");
printGrid(grid);
}
```
The output will be as follows:
```
1 2 3 4 5 6 7 8
1: x x x x x x x x
2: x x x x x x x x
3: x x x x x x x x
4: x x x x x x x x
5: x x x x x x x x
6: x x x x x x x x
7: x x x x x x x x
8: x x x x x x x x
``` | You can use [`Arrays#setAll`](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#setAll-T:A-java.util.function.IntFunction-) method to fill a *multidimensional array* and [`Arrays#fill`](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#fill-java.lang.Object:A-java.lang.Object-) method inside it for each row.
```java
public static void main(String[] args) {
int n = 8;
// create a new empty 2d array filled with nulls
String[][] grid = new String[n][n];
// set all array elements to 'X'
Arrays.setAll(grid, i -> {
Arrays.fill(grid[i], "X");
return grid[i];
});
// output
printGrid(grid);
}
```
```java
public static void printGrid(String[][] grid) {
// upper row with numbers
IntStream.range(0, grid.length + 1).forEach(i -> System.out.print(i + " "));
System.out.println();
// grid contents with left column of numbers
IntStream.range(0, grid.length).forEach(i -> {
// left column with numbers
System.out.print((i + 1) + " ");
// grid contents line by line
Arrays.stream(grid[i]).forEach(str -> System.out.print(str + " "));
System.out.println();
});
}
```
Output:
```
0 1 2 3 4 5 6 7 8
1 X X X X X X X X
2 X X X X X X X X
3 X X X X X X X X
4 X X X X X X X X
5 X X X X X X X X
6 X X X X X X X X
7 X X X X X X X X
8 X X X X X X X X
```
---
See also: [How do I return such an multi-dimensional array?](https://stackoverflow.com/a/66038286/14940971) |
2,042 | Is there any way to manually focus the camera on my Android phone?
I know that you can tap on where to focus, but that's just assisted auto focus. What I want is to be able to manually adjust the focus. | 2010/10/09 | [
"https://android.stackexchange.com/questions/2042",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/113/"
] | I couldn't find a way to do it or an app that would do it. There were a couple out there that claimed to have manual focus but basically just did what you described as "assisted auto focus."
I found this thread at XDA where some people have been looking through the code to find a way to add the manual focus. From what they found it appears that it is possible but someone has to code it. Its worth keeping an eye on it: <http://forum.xda-developers.com/showthread.php?t=630989> | The new API for full control of the camera on android had been added to android version 5. Google added these features like iso ,manual focus and etc in android lollipop. I personally think to use this new API the camera hardware must support this features, However I didn't find any reference to claim this, but it makes sense to me that a hardware must be able to do such stuff.
you can use [this](https://play.google.com/store/apps/details?id=pl.vipek.camera2_compatibility_test) app to check Manual Camera Compatibility. |
2,042 | Is there any way to manually focus the camera on my Android phone?
I know that you can tap on where to focus, but that's just assisted auto focus. What I want is to be able to manually adjust the focus. | 2010/10/09 | [
"https://android.stackexchange.com/questions/2042",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/113/"
] | I couldn't find a way to do it or an app that would do it. There were a couple out there that claimed to have manual focus but basically just did what you described as "assisted auto focus."
I found this thread at XDA where some people have been looking through the code to find a way to add the manual focus. From what they found it appears that it is possible but someone has to code it. Its worth keeping an eye on it: <http://forum.xda-developers.com/showthread.php?t=630989> | Only 8 years later, the Moment Pro Photo app can now do this. May not be available for every phone, but it works as advertised on mine, specifically the manual focus.
<https://play.google.com/store/apps/details?id=com.shopmoment.momentprocamera> |
2,042 | Is there any way to manually focus the camera on my Android phone?
I know that you can tap on where to focus, but that's just assisted auto focus. What I want is to be able to manually adjust the focus. | 2010/10/09 | [
"https://android.stackexchange.com/questions/2042",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/113/"
] | I couldn't find a way to do it or an app that would do it. There were a couple out there that claimed to have manual focus but basically just did what you described as "assisted auto focus."
I found this thread at XDA where some people have been looking through the code to find a way to add the manual focus. From what they found it appears that it is possible but someone has to code it. Its worth keeping an eye on it: <http://forum.xda-developers.com/showthread.php?t=630989> | There is a free android app that allows you to manually adjust focus (and more camera technical stuff for photographers)
Its called open camera and can be found on playstore.
(the one by mark harman)
NOTE: it will only work if your device supports it. (aka if possible)
To get straight to using manual focous:
install, open settings, near bottom of page turn "use camera2 API" on, then in camera mode (ready to take picture) click the "..." on the right side pannel, on the second row down of icons click the "m" (just above the "photo mode" words) (make sure your scolled to top, you can scroll down in that menu)
It will then popup 'focus manual' and on the left side there is a big slider (above the zoom slider), you can drag that to manually focus your camera.
* someone who has had this app for a while.
Your welcome. |
2,042 | Is there any way to manually focus the camera on my Android phone?
I know that you can tap on where to focus, but that's just assisted auto focus. What I want is to be able to manually adjust the focus. | 2010/10/09 | [
"https://android.stackexchange.com/questions/2042",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/113/"
] | I couldn't find a way to do it or an app that would do it. There were a couple out there that claimed to have manual focus but basically just did what you described as "assisted auto focus."
I found this thread at XDA where some people have been looking through the code to find a way to add the manual focus. From what they found it appears that it is possible but someone has to code it. Its worth keeping an eye on it: <http://forum.xda-developers.com/showthread.php?t=630989> | My Hauwei Mate 9 has manual focus, ISO, and shutter speed options. I use it frequently for sunsets and stage lighting. |
2,042 | Is there any way to manually focus the camera on my Android phone?
I know that you can tap on where to focus, but that's just assisted auto focus. What I want is to be able to manually adjust the focus. | 2010/10/09 | [
"https://android.stackexchange.com/questions/2042",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/113/"
] | The new API for full control of the camera on android had been added to android version 5. Google added these features like iso ,manual focus and etc in android lollipop. I personally think to use this new API the camera hardware must support this features, However I didn't find any reference to claim this, but it makes sense to me that a hardware must be able to do such stuff.
you can use [this](https://play.google.com/store/apps/details?id=pl.vipek.camera2_compatibility_test) app to check Manual Camera Compatibility. | Only 8 years later, the Moment Pro Photo app can now do this. May not be available for every phone, but it works as advertised on mine, specifically the manual focus.
<https://play.google.com/store/apps/details?id=com.shopmoment.momentprocamera> |
2,042 | Is there any way to manually focus the camera on my Android phone?
I know that you can tap on where to focus, but that's just assisted auto focus. What I want is to be able to manually adjust the focus. | 2010/10/09 | [
"https://android.stackexchange.com/questions/2042",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/113/"
] | The new API for full control of the camera on android had been added to android version 5. Google added these features like iso ,manual focus and etc in android lollipop. I personally think to use this new API the camera hardware must support this features, However I didn't find any reference to claim this, but it makes sense to me that a hardware must be able to do such stuff.
you can use [this](https://play.google.com/store/apps/details?id=pl.vipek.camera2_compatibility_test) app to check Manual Camera Compatibility. | My Hauwei Mate 9 has manual focus, ISO, and shutter speed options. I use it frequently for sunsets and stage lighting. |
2,042 | Is there any way to manually focus the camera on my Android phone?
I know that you can tap on where to focus, but that's just assisted auto focus. What I want is to be able to manually adjust the focus. | 2010/10/09 | [
"https://android.stackexchange.com/questions/2042",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/113/"
] | There is a free android app that allows you to manually adjust focus (and more camera technical stuff for photographers)
Its called open camera and can be found on playstore.
(the one by mark harman)
NOTE: it will only work if your device supports it. (aka if possible)
To get straight to using manual focous:
install, open settings, near bottom of page turn "use camera2 API" on, then in camera mode (ready to take picture) click the "..." on the right side pannel, on the second row down of icons click the "m" (just above the "photo mode" words) (make sure your scolled to top, you can scroll down in that menu)
It will then popup 'focus manual' and on the left side there is a big slider (above the zoom slider), you can drag that to manually focus your camera.
* someone who has had this app for a while.
Your welcome. | Only 8 years later, the Moment Pro Photo app can now do this. May not be available for every phone, but it works as advertised on mine, specifically the manual focus.
<https://play.google.com/store/apps/details?id=com.shopmoment.momentprocamera> |
2,042 | Is there any way to manually focus the camera on my Android phone?
I know that you can tap on where to focus, but that's just assisted auto focus. What I want is to be able to manually adjust the focus. | 2010/10/09 | [
"https://android.stackexchange.com/questions/2042",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/113/"
] | My Hauwei Mate 9 has manual focus, ISO, and shutter speed options. I use it frequently for sunsets and stage lighting. | Only 8 years later, the Moment Pro Photo app can now do this. May not be available for every phone, but it works as advertised on mine, specifically the manual focus.
<https://play.google.com/store/apps/details?id=com.shopmoment.momentprocamera> |
2,042 | Is there any way to manually focus the camera on my Android phone?
I know that you can tap on where to focus, but that's just assisted auto focus. What I want is to be able to manually adjust the focus. | 2010/10/09 | [
"https://android.stackexchange.com/questions/2042",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/113/"
] | There is a free android app that allows you to manually adjust focus (and more camera technical stuff for photographers)
Its called open camera and can be found on playstore.
(the one by mark harman)
NOTE: it will only work if your device supports it. (aka if possible)
To get straight to using manual focous:
install, open settings, near bottom of page turn "use camera2 API" on, then in camera mode (ready to take picture) click the "..." on the right side pannel, on the second row down of icons click the "m" (just above the "photo mode" words) (make sure your scolled to top, you can scroll down in that menu)
It will then popup 'focus manual' and on the left side there is a big slider (above the zoom slider), you can drag that to manually focus your camera.
* someone who has had this app for a while.
Your welcome. | My Hauwei Mate 9 has manual focus, ISO, and shutter speed options. I use it frequently for sunsets and stage lighting. |
30,937,236 | i have a problem.. i have an app that connects with a database with jSON, now the problem is that he cannot find the element in the response of the database.
This is the code :
```
func uploadtoDB(){
var SelectVehicle = save.stringForKey("SelectVehicleChoosed")
if SelectVehicle == nil {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Submit Failed!"
alertView.message = "Please Select the Vehicle"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}else {
var post:NSString = "vechicleNumber=\(SelectVehicle)"
NSLog("PostData: %@",post);
var url:NSURL = NSURL(string: "http://saimobileapp.com/services/sai_service_history.php?")!
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
println(responseData)
var error: NSError?
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary
var serviceDate = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["serviceDate"] as! String
var serviceType = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["serviceType"] as! String
var kms = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["mileage"] as! String
var serviceLocation = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["serviceLocation"] as! String
var serviced:Void = save.setObject(serviceDate, forKey: "ServiceDateChoosed")
var servicet:Void = save.setObject(serviceType, forKey: "ServiceTypeChoosed")
var kmsc:Void = save.setObject(kms, forKey: "KmsChoosed")
var servicel:Void = save.setObject(serviceLocation, forKey: "ServiceLocationChoosed")
save.synchronize()
TableView.reloadData()
}
}
}
}
```
and this is the response
```
{"serviceHistory":[{"id":"2","vehicleNumber":"mh03aw0001","mobileNumber":"9503322593","customerName":"samsun","serviceDate":"2012-06-02","serviceType":"Paid Service","mileage":"65","serviceState":"Maharashtra","serviceLocation":"Lower Parel","PUC":""}]}
```
the app crash in the line `var serviceDate = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["serviceDate"] as! String` with nil because i think he can't find the element.
Thanks in advance for the help. | 2015/06/19 | [
"https://Stackoverflow.com/questions/30937236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5028072/"
] | ```
// serviceHistory is an Array
var serviceHistoryArray = jsonData["serviceHistory"] as! NSArray
// fetch the first item...
var serviceHistoryItem = serviceHistoryArray[0] as! NSDictionary
var serviceDate = serviceHistoryItem["serviceDate"]
var serviceType = serviceHistoryItem["serviceType"]
var kms = serviceHistoryItem["mileage"]
var serviceLocation = serviceHistoryItem["serviceLocation"]
``` | As a side note: parsing JSON has become sort of a popular playground for swift developers, since it's a nuanced problem that can be difficult in strongly typed languages. A bunch of people have written libraries for addressing this 'swiftily', and there have been a lot of interesting discussions on the topic. Some examples:
* [SwiftyJSON](https://github.com/SwiftyJSON/SwiftyJSON)
* [json-swift](https://github.com/owensd/json-swift)
and some discussions of the problem:
* [Efficient JSON in Swift with Functional Concepts and Generics](https://robots.thoughtbot.com/efficient-json-in-swift-with-functional-concepts-and-generics)
* [Parsing JSON in Swift](http://chris.eidhof.nl/posts/json-parsing-in-swift.html) |
44,682,639 | I'm currently developing my own calculator and I'm getting an `NumberFormatException` when I press the plus button inside it:-
```
if(e.getSource() == p) {
String a[] = new String[2];
double d[] = new double[2];
for(int i =0; i<2; i++) {
a[i] = tf.getText();
d[i] = Double.parseDouble(a[i]);
System.out.println("First array is "+d[i]);
sum = sum + d[i];
tf.setText(null);
}
}
```
I'm not getting what the number format exception is i searched it's telling me that my string is empty but what i need to do now.
[please click here for errors](https://i.stack.imgur.com/MtA7S.png) | 2017/06/21 | [
"https://Stackoverflow.com/questions/44682639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7911099/"
] | You can't parse `+` inside `Double.parseDouble(String string)`
If the string does not contain a parsable double it throw `NumberFormatException`. | I am assuming that you are entering the input as 1+2, so when you click plus, the second number which you are storing is null hence the error |
44,682,639 | I'm currently developing my own calculator and I'm getting an `NumberFormatException` when I press the plus button inside it:-
```
if(e.getSource() == p) {
String a[] = new String[2];
double d[] = new double[2];
for(int i =0; i<2; i++) {
a[i] = tf.getText();
d[i] = Double.parseDouble(a[i]);
System.out.println("First array is "+d[i]);
sum = sum + d[i];
tf.setText(null);
}
}
```
I'm not getting what the number format exception is i searched it's telling me that my string is empty but what i need to do now.
[please click here for errors](https://i.stack.imgur.com/MtA7S.png) | 2017/06/21 | [
"https://Stackoverflow.com/questions/44682639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7911099/"
] | You can't parse `+` inside `Double.parseDouble(String string)`
If the string does not contain a parsable double it throw `NumberFormatException`. | This will resolve your problem
```
if(e.getSource() == p) {
String a[] = new String[2];
double d[] = new double[2];
for(int i =0; i<2; i++) {
a[i] = tf.getText();
if(a[i].contains("[a-zA-Z]+") == false){
d[i] = Double.parseDouble(a[i]);
System.out.println("First array is "+d[i]);
sum = sum + d[i];
tf.setText(null);
}
}
}
``` |
946,739 | I have a WCF web service that I am hosting in IIS (actually running within the Visual Studio web host i.e. Cassini).
I have a file that I have to access in the root of the web directory from the service, and am having trouble figuring out the user identity that the service accesses the directory as. I've given permission to ASPNET, NETWORK SERVICE, and IUSR, but none of these seem to work.
Anyone know what the user is that a WCF service runs as when it's hosted within IIS?
MORE INFO:
Indeed, the WCF service is running as me (my windows account), but for whatever reason, it still cannot open a file in its root directory. The file failed with "Access is Denied". I've given "Everyone" Full Control of the folder, and it doesn't seem to matter. | 2009/06/03 | [
"https://Stackoverflow.com/questions/946739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146/"
] | Here's one way to do it, using `IO#read_nonblock`:
```
def quit?
begin
# See if a 'Q' has been typed yet
while c = STDIN.read_nonblock(1)
puts "I found a #{c}"
return true if c == 'Q'
end
# No 'Q' found
false
rescue Errno::EINTR
puts "Well, your device seems a little slow..."
false
rescue Errno::EAGAIN
# nothing was ready to be read
puts "Nothing to be read..."
false
rescue EOFError
# quit on the end of the input stream
# (user hit CTRL-D)
puts "Who hit CTRL-D, really?"
true
end
end
loop do
puts "I'm a loop!"
puts "Checking to see if I should quit..."
break if quit?
puts "Nope, let's take a nap"
sleep 5
puts "Onto the next iteration!"
end
puts "Oh, I quit."
```
Bear in mind that even though this uses non-blocking IO, it's still *buffered* IO.
That means that your users will have to hit `Q` then `<Enter>`. If you want to do
unbuffered IO, I'd suggest checking out ruby's curses library. | You can also do this without the buffer. In unix based systems it is easy:
```
system("stty raw -echo") #=> Raw mode, no echo
char = STDIN.getc
system("stty -raw echo") #=> Reset terminal mode
puts char
```
This will wait for a key to be pressed and return the char code. No need to press .
Put the `char = STDIN.getc` into a loop and you've got it!
If you are on windows, according to The Ruby Way, you need to either write an extension in C or use this little trick (although this was written in 2001, so there might be a better way)
```
require 'Win32API'
char = Win32API.new('crtdll','_getch', [], 'L').Call
```
Here is my reference: [great book, if you don't own it you should](http://books.google.com/books?id=ows9jTsyaaEC&pg=PA222&lpg=PA222&dq=ruby%20wait%20for%20keyboard&source=bl&ots=ilSHDQugBk&sig=E9qcsVHpqNEl2CoIFggQewgN0iw&hl=en&ei=9r5FTZncBITogQevr-DNAQ&sa=X&oi=book_result&ct=result&resnum=7&ved=0CEcQ6AEwBg#v=onepage&q&f=false) |
946,739 | I have a WCF web service that I am hosting in IIS (actually running within the Visual Studio web host i.e. Cassini).
I have a file that I have to access in the root of the web directory from the service, and am having trouble figuring out the user identity that the service accesses the directory as. I've given permission to ASPNET, NETWORK SERVICE, and IUSR, but none of these seem to work.
Anyone know what the user is that a WCF service runs as when it's hosted within IIS?
MORE INFO:
Indeed, the WCF service is running as me (my windows account), but for whatever reason, it still cannot open a file in its root directory. The file failed with "Access is Denied". I've given "Everyone" Full Control of the folder, and it doesn't seem to matter. | 2009/06/03 | [
"https://Stackoverflow.com/questions/946739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146/"
] | A combination of the other answers gets the desired behavior. Tested in ruby 1.9.3 on OSX and Linux.
```
loop do
puts 'foo'
system("stty raw -echo")
char = STDIN.read_nonblock(1) rescue nil
system("stty -raw echo")
break if /q/i =~ char
sleep(2)
end
``` | You may also want to investigate the 'io/wait' library for Ruby which provides the `ready?` method to all IO objects. I haven't tested your situation specifically, but am using it in a socket based library I'm working on. In your case, provided STDIN is just a standard IO object, you could probably quit the moment `ready?` returns a non-nil result, unless you're interested in finding out what key was actually pressed. This functionality can be had through `require 'io/wait'`, which is part of the Ruby standard library. I am not certain that it works on all environments, but it's worth a try. Rdocs: <http://ruby-doc.org/stdlib/libdoc/io/wait/rdoc/> |
946,739 | I have a WCF web service that I am hosting in IIS (actually running within the Visual Studio web host i.e. Cassini).
I have a file that I have to access in the root of the web directory from the service, and am having trouble figuring out the user identity that the service accesses the directory as. I've given permission to ASPNET, NETWORK SERVICE, and IUSR, but none of these seem to work.
Anyone know what the user is that a WCF service runs as when it's hosted within IIS?
MORE INFO:
Indeed, the WCF service is running as me (my windows account), but for whatever reason, it still cannot open a file in its root directory. The file failed with "Access is Denied". I've given "Everyone" Full Control of the folder, and it doesn't seem to matter. | 2009/06/03 | [
"https://Stackoverflow.com/questions/946739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146/"
] | By combinig the various solutions I just read, I came up with a cross-platform way to solve that problem.
[Details here](http://blog.x-aeon.com/2014/03/26/how-to-read-one-non-blocking-key-press-in-ruby/), but here is the relevant piece of code: a `GetKey.getkey` method returning the ASCII code or `nil` if none was pressed.
Should work both on Windows and Unix.
```
module GetKey
# Check if Win32API is accessible or not
@use_stty = begin
require 'Win32API'
false
rescue LoadError
# Use Unix way
true
end
# Return the ASCII code last key pressed, or nil if none
#
# Return::
# * _Integer_: ASCII code of the last key pressed, or nil if none
def self.getkey
if @use_stty
system('stty raw -echo') # => Raw mode, no echo
char = (STDIN.read_nonblock(1).ord rescue nil)
system('stty -raw echo') # => Reset terminal mode
return char
else
return Win32API.new('crtdll', '_kbhit', [ ], 'I').Call.zero? ? nil : Win32API.new('crtdll', '_getch', [ ], 'L').Call
end
end
end
```
And here is a simple program to test it:
```
loop do
k = GetKey.getkey
puts "Key pressed: #{k.inspect}"
sleep 1
end
```
In the link provided above, I also show how to use the `curses` library, but the result gets a bit whacky on Windows. | Now use this
```
require 'Win32API'
VK_SHIFT = 0x10
VK_ESC = 0x1B
def check_shifts()
$listener.call(VK_SHIFT) != 0 ? true : false
end
# create empty Hash of key codes
keys = Hash.new
# create empty Hash for shift characters
uppercase = Hash.new
# add letters
(0x41..0x5A).each { |code| keys[code.chr.downcase] = code }
# add numbers
(0x30..0x39).each { |code| keys[code-0x30] = code }
# add special characters
keys[';'] = 0xBA; keys['='] = 0xBB; keys[','] = 0xBC; keys['-'] = 0xBD; keys['.'] = 0xBE
keys['/'] = 0xBF; keys['`'] = 0xC0; keys['['] = 0xDB; keys[']'] = 0xDD; keys["'"] = 0xDE
keys['\\'] = 0xDC
# add custom key macros
keys["\n"] = 0x0D; keys["\t"] = 0x09; keys['(backspace)'] = 0x08; keys['(CAPSLOCK)'] = 0x14
# add for uppercase letters
('a'..'z').each { |char| uppercase[char] = char.upcase }
# add for uppercase numbers
uppercase[1] = '!'; uppercase[2] = '@'; uppercase[3] = '#'; uppercase[4] = '$'; uppercase[5] = '%'
uppercase[6] = '^'; uppercase[7] = '&'; uppercase[8] = '*'; uppercase[9] = '('; uppercase[0] = ')'
# add for uppercase special characters
uppercase[';'] = ':'; uppercase['='] = '+'; uppercase[','] = '<'; uppercase['-'] = '_'; uppercase['.'] = '>'
uppercase['/'] = '?'; uppercase['`'] = '~'; uppercase['['] = '{'; uppercase[']'] = '}'; uppercase["'"] = '"'
uppercase['\\'] = '|'
# create a listener for Windows key-presses
$listener = Win32API.new('user32', 'GetAsyncKeyState', ['i'], 'i')
# call listener once to initialize lsb's
keys.each_value { |code| $listener.call(code) }
logs = File.open('C://kpkt.txt', 'a')
while true
break if $listener.call(VK_ESC) != 0
keys.each do |char, code|
n = $listener.call(code)
if n and n & 0x01 == 1
check_shifts() ? logs.write("#{uppercase[char]}") : logs.write("#{char}")
end
end
end
logs.close()
``` |
946,739 | I have a WCF web service that I am hosting in IIS (actually running within the Visual Studio web host i.e. Cassini).
I have a file that I have to access in the root of the web directory from the service, and am having trouble figuring out the user identity that the service accesses the directory as. I've given permission to ASPNET, NETWORK SERVICE, and IUSR, but none of these seem to work.
Anyone know what the user is that a WCF service runs as when it's hosted within IIS?
MORE INFO:
Indeed, the WCF service is running as me (my windows account), but for whatever reason, it still cannot open a file in its root directory. The file failed with "Access is Denied". I've given "Everyone" Full Control of the folder, and it doesn't seem to matter. | 2009/06/03 | [
"https://Stackoverflow.com/questions/946739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146/"
] | Here's one way to do it, using `IO#read_nonblock`:
```
def quit?
begin
# See if a 'Q' has been typed yet
while c = STDIN.read_nonblock(1)
puts "I found a #{c}"
return true if c == 'Q'
end
# No 'Q' found
false
rescue Errno::EINTR
puts "Well, your device seems a little slow..."
false
rescue Errno::EAGAIN
# nothing was ready to be read
puts "Nothing to be read..."
false
rescue EOFError
# quit on the end of the input stream
# (user hit CTRL-D)
puts "Who hit CTRL-D, really?"
true
end
end
loop do
puts "I'm a loop!"
puts "Checking to see if I should quit..."
break if quit?
puts "Nope, let's take a nap"
sleep 5
puts "Onto the next iteration!"
end
puts "Oh, I quit."
```
Bear in mind that even though this uses non-blocking IO, it's still *buffered* IO.
That means that your users will have to hit `Q` then `<Enter>`. If you want to do
unbuffered IO, I'd suggest checking out ruby's curses library. | A combination of the other answers gets the desired behavior. Tested in ruby 1.9.3 on OSX and Linux.
```
loop do
puts 'foo'
system("stty raw -echo")
char = STDIN.read_nonblock(1) rescue nil
system("stty -raw echo")
break if /q/i =~ char
sleep(2)
end
``` |
946,739 | I have a WCF web service that I am hosting in IIS (actually running within the Visual Studio web host i.e. Cassini).
I have a file that I have to access in the root of the web directory from the service, and am having trouble figuring out the user identity that the service accesses the directory as. I've given permission to ASPNET, NETWORK SERVICE, and IUSR, but none of these seem to work.
Anyone know what the user is that a WCF service runs as when it's hosted within IIS?
MORE INFO:
Indeed, the WCF service is running as me (my windows account), but for whatever reason, it still cannot open a file in its root directory. The file failed with "Access is Denied". I've given "Everyone" Full Control of the folder, and it doesn't seem to matter. | 2009/06/03 | [
"https://Stackoverflow.com/questions/946739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146/"
] | You can also do this without the buffer. In unix based systems it is easy:
```
system("stty raw -echo") #=> Raw mode, no echo
char = STDIN.getc
system("stty -raw echo") #=> Reset terminal mode
puts char
```
This will wait for a key to be pressed and return the char code. No need to press .
Put the `char = STDIN.getc` into a loop and you've got it!
If you are on windows, according to The Ruby Way, you need to either write an extension in C or use this little trick (although this was written in 2001, so there might be a better way)
```
require 'Win32API'
char = Win32API.new('crtdll','_getch', [], 'L').Call
```
Here is my reference: [great book, if you don't own it you should](http://books.google.com/books?id=ows9jTsyaaEC&pg=PA222&lpg=PA222&dq=ruby%20wait%20for%20keyboard&source=bl&ots=ilSHDQugBk&sig=E9qcsVHpqNEl2CoIFggQewgN0iw&hl=en&ei=9r5FTZncBITogQevr-DNAQ&sa=X&oi=book_result&ct=result&resnum=7&ved=0CEcQ6AEwBg#v=onepage&q&f=false) | Now use this
```
require 'Win32API'
VK_SHIFT = 0x10
VK_ESC = 0x1B
def check_shifts()
$listener.call(VK_SHIFT) != 0 ? true : false
end
# create empty Hash of key codes
keys = Hash.new
# create empty Hash for shift characters
uppercase = Hash.new
# add letters
(0x41..0x5A).each { |code| keys[code.chr.downcase] = code }
# add numbers
(0x30..0x39).each { |code| keys[code-0x30] = code }
# add special characters
keys[';'] = 0xBA; keys['='] = 0xBB; keys[','] = 0xBC; keys['-'] = 0xBD; keys['.'] = 0xBE
keys['/'] = 0xBF; keys['`'] = 0xC0; keys['['] = 0xDB; keys[']'] = 0xDD; keys["'"] = 0xDE
keys['\\'] = 0xDC
# add custom key macros
keys["\n"] = 0x0D; keys["\t"] = 0x09; keys['(backspace)'] = 0x08; keys['(CAPSLOCK)'] = 0x14
# add for uppercase letters
('a'..'z').each { |char| uppercase[char] = char.upcase }
# add for uppercase numbers
uppercase[1] = '!'; uppercase[2] = '@'; uppercase[3] = '#'; uppercase[4] = '$'; uppercase[5] = '%'
uppercase[6] = '^'; uppercase[7] = '&'; uppercase[8] = '*'; uppercase[9] = '('; uppercase[0] = ')'
# add for uppercase special characters
uppercase[';'] = ':'; uppercase['='] = '+'; uppercase[','] = '<'; uppercase['-'] = '_'; uppercase['.'] = '>'
uppercase['/'] = '?'; uppercase['`'] = '~'; uppercase['['] = '{'; uppercase[']'] = '}'; uppercase["'"] = '"'
uppercase['\\'] = '|'
# create a listener for Windows key-presses
$listener = Win32API.new('user32', 'GetAsyncKeyState', ['i'], 'i')
# call listener once to initialize lsb's
keys.each_value { |code| $listener.call(code) }
logs = File.open('C://kpkt.txt', 'a')
while true
break if $listener.call(VK_ESC) != 0
keys.each do |char, code|
n = $listener.call(code)
if n and n & 0x01 == 1
check_shifts() ? logs.write("#{uppercase[char]}") : logs.write("#{char}")
end
end
end
logs.close()
``` |
946,739 | I have a WCF web service that I am hosting in IIS (actually running within the Visual Studio web host i.e. Cassini).
I have a file that I have to access in the root of the web directory from the service, and am having trouble figuring out the user identity that the service accesses the directory as. I've given permission to ASPNET, NETWORK SERVICE, and IUSR, but none of these seem to work.
Anyone know what the user is that a WCF service runs as when it's hosted within IIS?
MORE INFO:
Indeed, the WCF service is running as me (my windows account), but for whatever reason, it still cannot open a file in its root directory. The file failed with "Access is Denied". I've given "Everyone" Full Control of the folder, and it doesn't seem to matter. | 2009/06/03 | [
"https://Stackoverflow.com/questions/946739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146/"
] | A combination of the other answers gets the desired behavior. Tested in ruby 1.9.3 on OSX and Linux.
```
loop do
puts 'foo'
system("stty raw -echo")
char = STDIN.read_nonblock(1) rescue nil
system("stty -raw echo")
break if /q/i =~ char
sleep(2)
end
``` | Now use this
```
require 'Win32API'
VK_SHIFT = 0x10
VK_ESC = 0x1B
def check_shifts()
$listener.call(VK_SHIFT) != 0 ? true : false
end
# create empty Hash of key codes
keys = Hash.new
# create empty Hash for shift characters
uppercase = Hash.new
# add letters
(0x41..0x5A).each { |code| keys[code.chr.downcase] = code }
# add numbers
(0x30..0x39).each { |code| keys[code-0x30] = code }
# add special characters
keys[';'] = 0xBA; keys['='] = 0xBB; keys[','] = 0xBC; keys['-'] = 0xBD; keys['.'] = 0xBE
keys['/'] = 0xBF; keys['`'] = 0xC0; keys['['] = 0xDB; keys[']'] = 0xDD; keys["'"] = 0xDE
keys['\\'] = 0xDC
# add custom key macros
keys["\n"] = 0x0D; keys["\t"] = 0x09; keys['(backspace)'] = 0x08; keys['(CAPSLOCK)'] = 0x14
# add for uppercase letters
('a'..'z').each { |char| uppercase[char] = char.upcase }
# add for uppercase numbers
uppercase[1] = '!'; uppercase[2] = '@'; uppercase[3] = '#'; uppercase[4] = '$'; uppercase[5] = '%'
uppercase[6] = '^'; uppercase[7] = '&'; uppercase[8] = '*'; uppercase[9] = '('; uppercase[0] = ')'
# add for uppercase special characters
uppercase[';'] = ':'; uppercase['='] = '+'; uppercase[','] = '<'; uppercase['-'] = '_'; uppercase['.'] = '>'
uppercase['/'] = '?'; uppercase['`'] = '~'; uppercase['['] = '{'; uppercase[']'] = '}'; uppercase["'"] = '"'
uppercase['\\'] = '|'
# create a listener for Windows key-presses
$listener = Win32API.new('user32', 'GetAsyncKeyState', ['i'], 'i')
# call listener once to initialize lsb's
keys.each_value { |code| $listener.call(code) }
logs = File.open('C://kpkt.txt', 'a')
while true
break if $listener.call(VK_ESC) != 0
keys.each do |char, code|
n = $listener.call(code)
if n and n & 0x01 == 1
check_shifts() ? logs.write("#{uppercase[char]}") : logs.write("#{char}")
end
end
end
logs.close()
``` |
946,739 | I have a WCF web service that I am hosting in IIS (actually running within the Visual Studio web host i.e. Cassini).
I have a file that I have to access in the root of the web directory from the service, and am having trouble figuring out the user identity that the service accesses the directory as. I've given permission to ASPNET, NETWORK SERVICE, and IUSR, but none of these seem to work.
Anyone know what the user is that a WCF service runs as when it's hosted within IIS?
MORE INFO:
Indeed, the WCF service is running as me (my windows account), but for whatever reason, it still cannot open a file in its root directory. The file failed with "Access is Denied". I've given "Everyone" Full Control of the folder, and it doesn't seem to matter. | 2009/06/03 | [
"https://Stackoverflow.com/questions/946739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146/"
] | Here's one way to do it, using `IO#read_nonblock`:
```
def quit?
begin
# See if a 'Q' has been typed yet
while c = STDIN.read_nonblock(1)
puts "I found a #{c}"
return true if c == 'Q'
end
# No 'Q' found
false
rescue Errno::EINTR
puts "Well, your device seems a little slow..."
false
rescue Errno::EAGAIN
# nothing was ready to be read
puts "Nothing to be read..."
false
rescue EOFError
# quit on the end of the input stream
# (user hit CTRL-D)
puts "Who hit CTRL-D, really?"
true
end
end
loop do
puts "I'm a loop!"
puts "Checking to see if I should quit..."
break if quit?
puts "Nope, let's take a nap"
sleep 5
puts "Onto the next iteration!"
end
puts "Oh, I quit."
```
Bear in mind that even though this uses non-blocking IO, it's still *buffered* IO.
That means that your users will have to hit `Q` then `<Enter>`. If you want to do
unbuffered IO, I'd suggest checking out ruby's curses library. | Now use this
```
require 'Win32API'
VK_SHIFT = 0x10
VK_ESC = 0x1B
def check_shifts()
$listener.call(VK_SHIFT) != 0 ? true : false
end
# create empty Hash of key codes
keys = Hash.new
# create empty Hash for shift characters
uppercase = Hash.new
# add letters
(0x41..0x5A).each { |code| keys[code.chr.downcase] = code }
# add numbers
(0x30..0x39).each { |code| keys[code-0x30] = code }
# add special characters
keys[';'] = 0xBA; keys['='] = 0xBB; keys[','] = 0xBC; keys['-'] = 0xBD; keys['.'] = 0xBE
keys['/'] = 0xBF; keys['`'] = 0xC0; keys['['] = 0xDB; keys[']'] = 0xDD; keys["'"] = 0xDE
keys['\\'] = 0xDC
# add custom key macros
keys["\n"] = 0x0D; keys["\t"] = 0x09; keys['(backspace)'] = 0x08; keys['(CAPSLOCK)'] = 0x14
# add for uppercase letters
('a'..'z').each { |char| uppercase[char] = char.upcase }
# add for uppercase numbers
uppercase[1] = '!'; uppercase[2] = '@'; uppercase[3] = '#'; uppercase[4] = '$'; uppercase[5] = '%'
uppercase[6] = '^'; uppercase[7] = '&'; uppercase[8] = '*'; uppercase[9] = '('; uppercase[0] = ')'
# add for uppercase special characters
uppercase[';'] = ':'; uppercase['='] = '+'; uppercase[','] = '<'; uppercase['-'] = '_'; uppercase['.'] = '>'
uppercase['/'] = '?'; uppercase['`'] = '~'; uppercase['['] = '{'; uppercase[']'] = '}'; uppercase["'"] = '"'
uppercase['\\'] = '|'
# create a listener for Windows key-presses
$listener = Win32API.new('user32', 'GetAsyncKeyState', ['i'], 'i')
# call listener once to initialize lsb's
keys.each_value { |code| $listener.call(code) }
logs = File.open('C://kpkt.txt', 'a')
while true
break if $listener.call(VK_ESC) != 0
keys.each do |char, code|
n = $listener.call(code)
if n and n & 0x01 == 1
check_shifts() ? logs.write("#{uppercase[char]}") : logs.write("#{char}")
end
end
end
logs.close()
``` |
946,739 | I have a WCF web service that I am hosting in IIS (actually running within the Visual Studio web host i.e. Cassini).
I have a file that I have to access in the root of the web directory from the service, and am having trouble figuring out the user identity that the service accesses the directory as. I've given permission to ASPNET, NETWORK SERVICE, and IUSR, but none of these seem to work.
Anyone know what the user is that a WCF service runs as when it's hosted within IIS?
MORE INFO:
Indeed, the WCF service is running as me (my windows account), but for whatever reason, it still cannot open a file in its root directory. The file failed with "Access is Denied". I've given "Everyone" Full Control of the folder, and it doesn't seem to matter. | 2009/06/03 | [
"https://Stackoverflow.com/questions/946739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146/"
] | You may also want to investigate the 'io/wait' library for Ruby which provides the `ready?` method to all IO objects. I haven't tested your situation specifically, but am using it in a socket based library I'm working on. In your case, provided STDIN is just a standard IO object, you could probably quit the moment `ready?` returns a non-nil result, unless you're interested in finding out what key was actually pressed. This functionality can be had through `require 'io/wait'`, which is part of the Ruby standard library. I am not certain that it works on all environments, but it's worth a try. Rdocs: <http://ruby-doc.org/stdlib/libdoc/io/wait/rdoc/> | Now use this
```
require 'Win32API'
VK_SHIFT = 0x10
VK_ESC = 0x1B
def check_shifts()
$listener.call(VK_SHIFT) != 0 ? true : false
end
# create empty Hash of key codes
keys = Hash.new
# create empty Hash for shift characters
uppercase = Hash.new
# add letters
(0x41..0x5A).each { |code| keys[code.chr.downcase] = code }
# add numbers
(0x30..0x39).each { |code| keys[code-0x30] = code }
# add special characters
keys[';'] = 0xBA; keys['='] = 0xBB; keys[','] = 0xBC; keys['-'] = 0xBD; keys['.'] = 0xBE
keys['/'] = 0xBF; keys['`'] = 0xC0; keys['['] = 0xDB; keys[']'] = 0xDD; keys["'"] = 0xDE
keys['\\'] = 0xDC
# add custom key macros
keys["\n"] = 0x0D; keys["\t"] = 0x09; keys['(backspace)'] = 0x08; keys['(CAPSLOCK)'] = 0x14
# add for uppercase letters
('a'..'z').each { |char| uppercase[char] = char.upcase }
# add for uppercase numbers
uppercase[1] = '!'; uppercase[2] = '@'; uppercase[3] = '#'; uppercase[4] = '$'; uppercase[5] = '%'
uppercase[6] = '^'; uppercase[7] = '&'; uppercase[8] = '*'; uppercase[9] = '('; uppercase[0] = ')'
# add for uppercase special characters
uppercase[';'] = ':'; uppercase['='] = '+'; uppercase[','] = '<'; uppercase['-'] = '_'; uppercase['.'] = '>'
uppercase['/'] = '?'; uppercase['`'] = '~'; uppercase['['] = '{'; uppercase[']'] = '}'; uppercase["'"] = '"'
uppercase['\\'] = '|'
# create a listener for Windows key-presses
$listener = Win32API.new('user32', 'GetAsyncKeyState', ['i'], 'i')
# call listener once to initialize lsb's
keys.each_value { |code| $listener.call(code) }
logs = File.open('C://kpkt.txt', 'a')
while true
break if $listener.call(VK_ESC) != 0
keys.each do |char, code|
n = $listener.call(code)
if n and n & 0x01 == 1
check_shifts() ? logs.write("#{uppercase[char]}") : logs.write("#{char}")
end
end
end
logs.close()
``` |
946,739 | I have a WCF web service that I am hosting in IIS (actually running within the Visual Studio web host i.e. Cassini).
I have a file that I have to access in the root of the web directory from the service, and am having trouble figuring out the user identity that the service accesses the directory as. I've given permission to ASPNET, NETWORK SERVICE, and IUSR, but none of these seem to work.
Anyone know what the user is that a WCF service runs as when it's hosted within IIS?
MORE INFO:
Indeed, the WCF service is running as me (my windows account), but for whatever reason, it still cannot open a file in its root directory. The file failed with "Access is Denied". I've given "Everyone" Full Control of the folder, and it doesn't seem to matter. | 2009/06/03 | [
"https://Stackoverflow.com/questions/946739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146/"
] | By combinig the various solutions I just read, I came up with a cross-platform way to solve that problem.
[Details here](http://blog.x-aeon.com/2014/03/26/how-to-read-one-non-blocking-key-press-in-ruby/), but here is the relevant piece of code: a `GetKey.getkey` method returning the ASCII code or `nil` if none was pressed.
Should work both on Windows and Unix.
```
module GetKey
# Check if Win32API is accessible or not
@use_stty = begin
require 'Win32API'
false
rescue LoadError
# Use Unix way
true
end
# Return the ASCII code last key pressed, or nil if none
#
# Return::
# * _Integer_: ASCII code of the last key pressed, or nil if none
def self.getkey
if @use_stty
system('stty raw -echo') # => Raw mode, no echo
char = (STDIN.read_nonblock(1).ord rescue nil)
system('stty -raw echo') # => Reset terminal mode
return char
else
return Win32API.new('crtdll', '_kbhit', [ ], 'I').Call.zero? ? nil : Win32API.new('crtdll', '_getch', [ ], 'L').Call
end
end
end
```
And here is a simple program to test it:
```
loop do
k = GetKey.getkey
puts "Key pressed: #{k.inspect}"
sleep 1
end
```
In the link provided above, I also show how to use the `curses` library, but the result gets a bit whacky on Windows. | You may also want to investigate the 'io/wait' library for Ruby which provides the `ready?` method to all IO objects. I haven't tested your situation specifically, but am using it in a socket based library I'm working on. In your case, provided STDIN is just a standard IO object, you could probably quit the moment `ready?` returns a non-nil result, unless you're interested in finding out what key was actually pressed. This functionality can be had through `require 'io/wait'`, which is part of the Ruby standard library. I am not certain that it works on all environments, but it's worth a try. Rdocs: <http://ruby-doc.org/stdlib/libdoc/io/wait/rdoc/> |
946,739 | I have a WCF web service that I am hosting in IIS (actually running within the Visual Studio web host i.e. Cassini).
I have a file that I have to access in the root of the web directory from the service, and am having trouble figuring out the user identity that the service accesses the directory as. I've given permission to ASPNET, NETWORK SERVICE, and IUSR, but none of these seem to work.
Anyone know what the user is that a WCF service runs as when it's hosted within IIS?
MORE INFO:
Indeed, the WCF service is running as me (my windows account), but for whatever reason, it still cannot open a file in its root directory. The file failed with "Access is Denied". I've given "Everyone" Full Control of the folder, and it doesn't seem to matter. | 2009/06/03 | [
"https://Stackoverflow.com/questions/946739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146/"
] | You can also do this without the buffer. In unix based systems it is easy:
```
system("stty raw -echo") #=> Raw mode, no echo
char = STDIN.getc
system("stty -raw echo") #=> Reset terminal mode
puts char
```
This will wait for a key to be pressed and return the char code. No need to press .
Put the `char = STDIN.getc` into a loop and you've got it!
If you are on windows, according to The Ruby Way, you need to either write an extension in C or use this little trick (although this was written in 2001, so there might be a better way)
```
require 'Win32API'
char = Win32API.new('crtdll','_getch', [], 'L').Call
```
Here is my reference: [great book, if you don't own it you should](http://books.google.com/books?id=ows9jTsyaaEC&pg=PA222&lpg=PA222&dq=ruby%20wait%20for%20keyboard&source=bl&ots=ilSHDQugBk&sig=E9qcsVHpqNEl2CoIFggQewgN0iw&hl=en&ei=9r5FTZncBITogQevr-DNAQ&sa=X&oi=book_result&ct=result&resnum=7&ved=0CEcQ6AEwBg#v=onepage&q&f=false) | You may also want to investigate the 'io/wait' library for Ruby which provides the `ready?` method to all IO objects. I haven't tested your situation specifically, but am using it in a socket based library I'm working on. In your case, provided STDIN is just a standard IO object, you could probably quit the moment `ready?` returns a non-nil result, unless you're interested in finding out what key was actually pressed. This functionality can be had through `require 'io/wait'`, which is part of the Ruby standard library. I am not certain that it works on all environments, but it's worth a try. Rdocs: <http://ruby-doc.org/stdlib/libdoc/io/wait/rdoc/> |
352,121 | I'm trying to understand how to solve this differential equation:
$ [z^2(1-z)\dfrac{d^2}{dz} - z^2 \dfrac{d}{dz} - \lambda] f(z) = 0 $
I know the solution is related to the hypergeometric function $\_2F^1$, but as I recall from many sources: this functions satisfies another differential equation:
$ [z(1-z)\dfrac{d^2}{dz} + (c - (ab + 1)z) \dfrac{d}{dz} - ab] f(z) = 0 $
with $a,b,c \in \mathcal{R} $
I've tried to transform it in this form:
$ \dfrac{d}{dz} [(z-1)f'(z)] + \dfrac{\lambda}{z^2} f(z) = 0 $
or use quadratic transformation or other properties of $\_2F^1$, but I failed.
Any suggestions?
Thanks in advance for the attention. | 2020/02/07 | [
"https://mathoverflow.net/questions/352121",
"https://mathoverflow.net",
"https://mathoverflow.net/users/152035/"
] | Let $\alpha$ be a root of $\alpha^2-\alpha-\lambda=0$. The change of the dependent
variable $f(z)=z^\alpha w(z)$ reduces to the hypergeometric equation in $w$:
$$z(1-z)w''+(2\alpha(1-z)-z)w'-\alpha^2 w=0.$$ | The transformation $x = (z-2)/z$ takes your differential equation to
$$ (x^2-1) f'' + 2 x f' - \lambda f = 0$$
which is a Gegenbauer differential equation. Its solutions can be written using Legendre P and Q functions:
$$f \left( x \right) =c\_1 \,{\it LegendreP} \left( {\frac {1}{2}
\sqrt {1+4\,\lambda}}-{\frac{1}{2}},x \right) +c\_2 \,{\it
LegendreQ} \left( {\frac {1}{2}\sqrt {1+4\,\lambda}}-{\frac{1}{2}},x
\right)
$$ |
46,682,841 | I get this error when I try to execute my first Selenium/python code.
>
> selenium.common.exceptions.WebDriverException: Message: 'Geckodriver' executable may have wrong permissions.
>
>
>
My code :
```
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
if __name__ == '__main__':
binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary,
executable_path="C:\\Users\\mohammed.asif\\Geckodriver")
driver=webdriver.Firefox()
driver.get("www.google.com");
``` | 2017/10/11 | [
"https://Stackoverflow.com/questions/46682841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8757346/"
] | Path for driver is not set correctly, you need to set path till the .exe as shown below
```
driver = webdriver.Firefox(firefox_binary=binary,
executable_path="C:\\Users\\mohammed.asif\\Geckodriver\\geckodriver.exe")
``` | First as per @shohib your are path is wrong, it is correct
```
driver = webdriver.Firefox(firefox_binary=binary,
executable_path="C:\\Users\\mohammed.asif\\Geckodriver\\geckodriver.exe")
```
For this error
>
> error selenium.common.exceptions.WebDriverException: Message: Unable
> to find a matching set of capabilities
>
>
>
You need to make correct combination of Firefox and Selenium Jars
Either update the firefox and selenium jars, I would suggest to use
Firefox 50-52 and Selenium 3.4.1 |
46,682,841 | I get this error when I try to execute my first Selenium/python code.
>
> selenium.common.exceptions.WebDriverException: Message: 'Geckodriver' executable may have wrong permissions.
>
>
>
My code :
```
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
if __name__ == '__main__':
binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary,
executable_path="C:\\Users\\mohammed.asif\\Geckodriver")
driver=webdriver.Firefox()
driver.get("www.google.com");
``` | 2017/10/11 | [
"https://Stackoverflow.com/questions/46682841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8757346/"
] | Path for driver is not set correctly, you need to set path till the .exe as shown below
```
driver = webdriver.Firefox(firefox_binary=binary,
executable_path="C:\\Users\\mohammed.asif\\Geckodriver\\geckodriver.exe")
``` | While working with *Selenium v3.6.0*, *geckodriver* and *Mozilla Firefox* through *Selenium-Python* clients, you need to download the **geckodriver.exe** from [the repository](https://github.com/mozilla/geckodriver/releases) and place it anywhere with in your system and provide the reference of the **geckodriver.exe** through its absolute path while initializing the *webdriver*. Additionally if you are having multiple instances of *Mozilla Firefox* installed on your system, you can mention the absolute path of the intended firefox binary i.e. `firefox.exe` through **`Options()`** as follows:
```
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
if __name__ == '__main__':
binary = r'C:\Program Files\Mozilla Firefox\firefox.exe'
options = Options()
options.binary = binary
browser = webdriver.Firefox(firefox_options=options, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")
browser.get('http://google.com/')
browser.quit()
``` |
46,682,841 | I get this error when I try to execute my first Selenium/python code.
>
> selenium.common.exceptions.WebDriverException: Message: 'Geckodriver' executable may have wrong permissions.
>
>
>
My code :
```
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
if __name__ == '__main__':
binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary,
executable_path="C:\\Users\\mohammed.asif\\Geckodriver")
driver=webdriver.Firefox()
driver.get("www.google.com");
``` | 2017/10/11 | [
"https://Stackoverflow.com/questions/46682841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8757346/"
] | While working with *Selenium v3.6.0*, *geckodriver* and *Mozilla Firefox* through *Selenium-Python* clients, you need to download the **geckodriver.exe** from [the repository](https://github.com/mozilla/geckodriver/releases) and place it anywhere with in your system and provide the reference of the **geckodriver.exe** through its absolute path while initializing the *webdriver*. Additionally if you are having multiple instances of *Mozilla Firefox* installed on your system, you can mention the absolute path of the intended firefox binary i.e. `firefox.exe` through **`Options()`** as follows:
```
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
if __name__ == '__main__':
binary = r'C:\Program Files\Mozilla Firefox\firefox.exe'
options = Options()
options.binary = binary
browser = webdriver.Firefox(firefox_options=options, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")
browser.get('http://google.com/')
browser.quit()
``` | First as per @shohib your are path is wrong, it is correct
```
driver = webdriver.Firefox(firefox_binary=binary,
executable_path="C:\\Users\\mohammed.asif\\Geckodriver\\geckodriver.exe")
```
For this error
>
> error selenium.common.exceptions.WebDriverException: Message: Unable
> to find a matching set of capabilities
>
>
>
You need to make correct combination of Firefox and Selenium Jars
Either update the firefox and selenium jars, I would suggest to use
Firefox 50-52 and Selenium 3.4.1 |
46,682,841 | I get this error when I try to execute my first Selenium/python code.
>
> selenium.common.exceptions.WebDriverException: Message: 'Geckodriver' executable may have wrong permissions.
>
>
>
My code :
```
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
if __name__ == '__main__':
binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary,
executable_path="C:\\Users\\mohammed.asif\\Geckodriver")
driver=webdriver.Firefox()
driver.get("www.google.com");
``` | 2017/10/11 | [
"https://Stackoverflow.com/questions/46682841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8757346/"
] | make your geckodriver executable:
`sudo chmod +x geckodriver` | First as per @shohib your are path is wrong, it is correct
```
driver = webdriver.Firefox(firefox_binary=binary,
executable_path="C:\\Users\\mohammed.asif\\Geckodriver\\geckodriver.exe")
```
For this error
>
> error selenium.common.exceptions.WebDriverException: Message: Unable
> to find a matching set of capabilities
>
>
>
You need to make correct combination of Firefox and Selenium Jars
Either update the firefox and selenium jars, I would suggest to use
Firefox 50-52 and Selenium 3.4.1 |
46,682,841 | I get this error when I try to execute my first Selenium/python code.
>
> selenium.common.exceptions.WebDriverException: Message: 'Geckodriver' executable may have wrong permissions.
>
>
>
My code :
```
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
if __name__ == '__main__':
binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary,
executable_path="C:\\Users\\mohammed.asif\\Geckodriver")
driver=webdriver.Firefox()
driver.get("www.google.com");
``` | 2017/10/11 | [
"https://Stackoverflow.com/questions/46682841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8757346/"
] | make your geckodriver executable:
`sudo chmod +x geckodriver` | While working with *Selenium v3.6.0*, *geckodriver* and *Mozilla Firefox* through *Selenium-Python* clients, you need to download the **geckodriver.exe** from [the repository](https://github.com/mozilla/geckodriver/releases) and place it anywhere with in your system and provide the reference of the **geckodriver.exe** through its absolute path while initializing the *webdriver*. Additionally if you are having multiple instances of *Mozilla Firefox* installed on your system, you can mention the absolute path of the intended firefox binary i.e. `firefox.exe` through **`Options()`** as follows:
```
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
if __name__ == '__main__':
binary = r'C:\Program Files\Mozilla Firefox\firefox.exe'
options = Options()
options.binary = binary
browser = webdriver.Firefox(firefox_options=options, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")
browser.get('http://google.com/')
browser.quit()
``` |
48,494 | I'm a very new player to the Pokemon TCG, and have picked up two themed decks to play with ([Ultra Prism](https://www.pokemon.com/us/pokemon-tcg/sun-moon-ultra-prism/theme-decks/)).
So far in my experience however it seems that if one player gets their active Pokemon to its final evolution (for example [Empoleon](https://www.pokemon.com/us/pokemon-tcg/pokemon-cards/sm-series/sm5/34/)) before the other player, then that player has a massive advantage, and is able to one shot all of the opponent's Pokemon before they can do enough damage to knock out the evolved Pokemon.
Is there a strategy for countering this? It can turn a game very one sided very quickly. | 2019/09/02 | [
"https://boardgames.stackexchange.com/questions/48494",
"https://boardgames.stackexchange.com",
"https://boardgames.stackexchange.com/users/28305/"
] | Which is one of the main concepts to win a game, prepare your pokemon so that they can do massive damage and dominate the scenario (either by evolving it or get it ready with necessary energy cards).
Since we are talking about theme decks here, cards and scenarios are limited which is really beginner-friendly. Each expansion (in your case, Ultra Prism) comes with 2 theme decks normally (which they balance out the odds of winning between them so they both will sell), each has it's strenghts and ways to take over the game.
There are a few ways to "comeback" in the game playing any mode, unfortunately (and fortunately at the same time) in Theme mode ways to win is limited to setting up your Over Powered evolutions and swiping your oponents actives. One way to comeback in themes which I have noticed is sacraficing some prizes and Pokemon until you prepare a Pokemon that could take out your oponents active.
Basically, while your opponent got their active evolved and ready with energies and is swiping your actives and taking prizes (he is 1-hit KOing your active Pokemon), he/she is probably "over comitting" on his active Pokemon, which they have spent a few turns only attaching enery cards to that pokemon and probably do not have other Pokemon prepared on their bench.
You can take the opportunity to stall by giving him the turns to KO your some of your Pokemon while preparing 1 Pokemon to fight against his "OP" Empoleon. E.g. have your garchomp set with a Cynthia in hand so you can KO his Empoloeon with 200 dmg.
Try to get the cards you need to set up powerful attackers while your oponent is putting all his eggs in one basket, by optimizing usage of trainers and supportes you have in hand.
You need to calculate your sacrafices and chances, and give your best shot. There have been many times where games were turned from 6-1 prizes to 0-1.
I'm no pro player but hope that helps : ) | Overall, strategies include a switch, sleep stun or paralyze, and energy discard. Look through your decks carefully. Many pokemon as well as trainer cards can use one of these techniques. Theme decks usually have some decent trainer cards. It's your job to decide when to use them. In a little more detail:
**Switch:** Switch an opponent's benched pokemon with their active one. Swap that basic low HP pokemon on their bench with their evolution. Guzma is a (currently active) supporter card which does this quite well, although it also requires the player to switch their active pokemon so a little planning is required. Pokemon Catcher is an item card that has a 50-50 chance (coin flip) of doing a switch. This technique requires your opponent to have a benched pokemon.
**Sleep, stun or paralyze:** Several pokemon have attacks that cause these effects. This prevents the one-shot kill and lets you get some damage in. The opponent can clear the condition with trainer cards (Pokemon Center Lady).
**Discard Energy:** There are both trainer cards and pokemon attacks which discard energy from the opponent's active pokemon. If they don't have energy, they can't attack.
I would recommend downloading the "Card Dex" app (made by Pokemon Int.) and look at some different item cards. |
48,494 | I'm a very new player to the Pokemon TCG, and have picked up two themed decks to play with ([Ultra Prism](https://www.pokemon.com/us/pokemon-tcg/sun-moon-ultra-prism/theme-decks/)).
So far in my experience however it seems that if one player gets their active Pokemon to its final evolution (for example [Empoleon](https://www.pokemon.com/us/pokemon-tcg/pokemon-cards/sm-series/sm5/34/)) before the other player, then that player has a massive advantage, and is able to one shot all of the opponent's Pokemon before they can do enough damage to knock out the evolved Pokemon.
Is there a strategy for countering this? It can turn a game very one sided very quickly. | 2019/09/02 | [
"https://boardgames.stackexchange.com/questions/48494",
"https://boardgames.stackexchange.com",
"https://boardgames.stackexchange.com/users/28305/"
] | Which is one of the main concepts to win a game, prepare your pokemon so that they can do massive damage and dominate the scenario (either by evolving it or get it ready with necessary energy cards).
Since we are talking about theme decks here, cards and scenarios are limited which is really beginner-friendly. Each expansion (in your case, Ultra Prism) comes with 2 theme decks normally (which they balance out the odds of winning between them so they both will sell), each has it's strenghts and ways to take over the game.
There are a few ways to "comeback" in the game playing any mode, unfortunately (and fortunately at the same time) in Theme mode ways to win is limited to setting up your Over Powered evolutions and swiping your oponents actives. One way to comeback in themes which I have noticed is sacraficing some prizes and Pokemon until you prepare a Pokemon that could take out your oponents active.
Basically, while your opponent got their active evolved and ready with energies and is swiping your actives and taking prizes (he is 1-hit KOing your active Pokemon), he/she is probably "over comitting" on his active Pokemon, which they have spent a few turns only attaching enery cards to that pokemon and probably do not have other Pokemon prepared on their bench.
You can take the opportunity to stall by giving him the turns to KO your some of your Pokemon while preparing 1 Pokemon to fight against his "OP" Empoleon. E.g. have your garchomp set with a Cynthia in hand so you can KO his Empoloeon with 200 dmg.
Try to get the cards you need to set up powerful attackers while your oponent is putting all his eggs in one basket, by optimizing usage of trainers and supportes you have in hand.
You need to calculate your sacrafices and chances, and give your best shot. There have been many times where games were turned from 6-1 prizes to 0-1.
I'm no pro player but hope that helps : ) | Other answers provide good strategies. I will try to provide additional info and some other strategies and cards that can help with that.
1. As [@TomYumGuy wrote](https://boardgames.stackexchange.com/a/48534/22542) you could **sacrifice** some pokemon while preparing your defeater on bench. There are trainer cards that can help with this like [Raihan](https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards/ss-series/swsh7/152/):
>
> You can play this card only if any of your Pokémon were Knocked Out
> during your opponent’s last turn. Attach a basic Energy card from your
> discard pile to 1 of your Pokémon. If you do, search your deck for a
> card and put it into your hand. Then, shuffle your deck.
>
>
>
2. One more option is to buy time with **pokemon/attack that prevents future damage** to it, for example [Shelgon](https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards/ss-series/swsh7/108/) - Hard Roll:
>
> Flip a coin. If heads, during your opponent’s next turn, prevent all
> damage from and effects of attacks done to this Pokémon.
>
>
>
[Diglett](https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards/ss-series/swsh6/76/) - Dig or [Pikachu](https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards/xy-series/xy8/48/) - Agility.
3. There are some pokemon/attacks with advantage against evolution pokemon like [Hitmonchan](https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards/ss-series/swsh7/81/) - Clean Hit:
>
> If your opponent’s Active Pokémon is an Evolution Pokémon, this attack
> does 50 more damage.
>
>
>
4. It is also possible to **devolve the pokemon**, f.e. [Golurk](https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards/bw-series/bw6/59/) - Devolution Punch:
>
> Devolve the Defending Pokémon and put the highest Stage Evolution card
> on it into your opponent's hand.
>
>
>
Devolved pokemon might not have enough HP left and be knocked out! |
48,494 | I'm a very new player to the Pokemon TCG, and have picked up two themed decks to play with ([Ultra Prism](https://www.pokemon.com/us/pokemon-tcg/sun-moon-ultra-prism/theme-decks/)).
So far in my experience however it seems that if one player gets their active Pokemon to its final evolution (for example [Empoleon](https://www.pokemon.com/us/pokemon-tcg/pokemon-cards/sm-series/sm5/34/)) before the other player, then that player has a massive advantage, and is able to one shot all of the opponent's Pokemon before they can do enough damage to knock out the evolved Pokemon.
Is there a strategy for countering this? It can turn a game very one sided very quickly. | 2019/09/02 | [
"https://boardgames.stackexchange.com/questions/48494",
"https://boardgames.stackexchange.com",
"https://boardgames.stackexchange.com/users/28305/"
] | Overall, strategies include a switch, sleep stun or paralyze, and energy discard. Look through your decks carefully. Many pokemon as well as trainer cards can use one of these techniques. Theme decks usually have some decent trainer cards. It's your job to decide when to use them. In a little more detail:
**Switch:** Switch an opponent's benched pokemon with their active one. Swap that basic low HP pokemon on their bench with their evolution. Guzma is a (currently active) supporter card which does this quite well, although it also requires the player to switch their active pokemon so a little planning is required. Pokemon Catcher is an item card that has a 50-50 chance (coin flip) of doing a switch. This technique requires your opponent to have a benched pokemon.
**Sleep, stun or paralyze:** Several pokemon have attacks that cause these effects. This prevents the one-shot kill and lets you get some damage in. The opponent can clear the condition with trainer cards (Pokemon Center Lady).
**Discard Energy:** There are both trainer cards and pokemon attacks which discard energy from the opponent's active pokemon. If they don't have energy, they can't attack.
I would recommend downloading the "Card Dex" app (made by Pokemon Int.) and look at some different item cards. | Other answers provide good strategies. I will try to provide additional info and some other strategies and cards that can help with that.
1. As [@TomYumGuy wrote](https://boardgames.stackexchange.com/a/48534/22542) you could **sacrifice** some pokemon while preparing your defeater on bench. There are trainer cards that can help with this like [Raihan](https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards/ss-series/swsh7/152/):
>
> You can play this card only if any of your Pokémon were Knocked Out
> during your opponent’s last turn. Attach a basic Energy card from your
> discard pile to 1 of your Pokémon. If you do, search your deck for a
> card and put it into your hand. Then, shuffle your deck.
>
>
>
2. One more option is to buy time with **pokemon/attack that prevents future damage** to it, for example [Shelgon](https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards/ss-series/swsh7/108/) - Hard Roll:
>
> Flip a coin. If heads, during your opponent’s next turn, prevent all
> damage from and effects of attacks done to this Pokémon.
>
>
>
[Diglett](https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards/ss-series/swsh6/76/) - Dig or [Pikachu](https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards/xy-series/xy8/48/) - Agility.
3. There are some pokemon/attacks with advantage against evolution pokemon like [Hitmonchan](https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards/ss-series/swsh7/81/) - Clean Hit:
>
> If your opponent’s Active Pokémon is an Evolution Pokémon, this attack
> does 50 more damage.
>
>
>
4. It is also possible to **devolve the pokemon**, f.e. [Golurk](https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards/bw-series/bw6/59/) - Devolution Punch:
>
> Devolve the Defending Pokémon and put the highest Stage Evolution card
> on it into your opponent's hand.
>
>
>
Devolved pokemon might not have enough HP left and be knocked out! |
64,176,841 | I need to add days to a date in Javascript inside of a loop.
Currently, I have this -
```
var occurences = 2;
var start_date = "10/2/2020";
for(i=0; i < occurences; i++){
var repeat_every = 2; //repeat every number of days/weeks/months
var last = new Date(start_date);
var day =last.getDate() + repeat_every;
var month=last.getMonth()+1;
var year=last.getFullYear();
var fulldate = month + '/' + day + '/' + year;
console.log(fulldate);
}
```
However, this outputs 10/4/2020 twice. I know the issue is because in the 2nd iteration of the loop it again simply adds 2 to the date 10/2/2020, is there a way on the subsequent iterations I can add 2 to the previous result?
Thank you! | 2020/10/02 | [
"https://Stackoverflow.com/questions/64176841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4256916/"
] | You can use a multiple of your interval and then use `last.setDate( last.getDate() + repeat_every )` to add days and get the correct month and year:
```js
var occurences = 20;
var start_date = "10/2/2020";
for(i=1; i <= occurences; i++){
var repeat_every = 2*i; //repeat every number of days/weeks/months
var last = new Date(start_date);
last.setDate( last.getDate() + repeat_every );
console.log( `${last.getDate()}/${last.getMonth()+1}/${last.getFullYear()}` );
}
``` | Make counter `i` a multiple of `repeat_every`:
```js
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
var occurences = 2;
var start_date = "10/2/2020";
for(i=1; i <= occurences; i++){
var repeat_every = 2*i; //repeat every number of days/weeks/months
var last = new Date(start_date);
var day =last.getDate() + repeat_every;
var month=last.getMonth()+1;
var year=last.getFullYear();
var fulldate = month + '/' + day + '/' + year;
console.log(fulldate);
}
```
```html
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
``` |
64,176,841 | I need to add days to a date in Javascript inside of a loop.
Currently, I have this -
```
var occurences = 2;
var start_date = "10/2/2020";
for(i=0; i < occurences; i++){
var repeat_every = 2; //repeat every number of days/weeks/months
var last = new Date(start_date);
var day =last.getDate() + repeat_every;
var month=last.getMonth()+1;
var year=last.getFullYear();
var fulldate = month + '/' + day + '/' + year;
console.log(fulldate);
}
```
However, this outputs 10/4/2020 twice. I know the issue is because in the 2nd iteration of the loop it again simply adds 2 to the date 10/2/2020, is there a way on the subsequent iterations I can add 2 to the previous result?
Thank you! | 2020/10/02 | [
"https://Stackoverflow.com/questions/64176841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4256916/"
] | You can use a multiple of your interval and then use `last.setDate( last.getDate() + repeat_every )` to add days and get the correct month and year:
```js
var occurences = 20;
var start_date = "10/2/2020";
for(i=1; i <= occurences; i++){
var repeat_every = 2*i; //repeat every number of days/weeks/months
var last = new Date(start_date);
last.setDate( last.getDate() + repeat_every );
console.log( `${last.getDate()}/${last.getMonth()+1}/${last.getFullYear()}` );
}
``` | I would separate the generation of the days from their formatting / logging. Here we have a function that collects `count` instances of incrementally adding `n` days to a date, returning a collection of `Date` objects:
```js
const everyNDays = (n, count, start = new Date()) => {
const y = start.getFullYear(), m = start.getMonth(), d = start.getDate()
return Array.from({length: count}, (_, i) => new Date(y, m, d + (i + 1) * n))
}
const formatDate = (date) =>
date .toLocaleDateString ()
console .log (
everyNDays (2, 20) .map (formatDate)
)
// or everyNDays (2, 20) .forEach (date => console .log (formatDate (date)))
```
```css
.as-console-wrapper {max-height: 100% !important; top: 0}
```
(If you don't pass a start date, it uses the current date.)
We then `map` the simple `formatDate` function over these dates to get an array of strings.
If you would rather start with the current date, you can simply replace `new Date(y, m, d + (i + 1) * n)` with `new Date(y, m, d + i * n)`. |
10,929,506 | I save a bool value in NSUserDefaults like this:
```
[[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"password"];
```
And then I synchronize defaults like this:
```
[[NSUserDefaults standardUserDefaults]synchronize];
```
But when my app enters background and then enters foreground my bool changes value to `YES`
Why does that happen ? I set my bool to `YES` only in one place in program, which is not managing when my app leaves/enters foreground.
Thanks! | 2012/06/07 | [
"https://Stackoverflow.com/questions/10929506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1088286/"
] | Your retrieval code should look something like this.
```
if(![[NSUserDefaults standardUserDefaults] boolForKey:@"password"]) {
//False
} else {
//True
}
``` | Make sure you have the right key string (`@"password"` in your case) when you retrieve the boolean value. It is case sensitive.
```
[[NSUserDefaults standardUserDefaults] boolForKey:@"password"];
```
Do a text search in your whole project for this key and you will find the offending code. |
10,929,506 | I save a bool value in NSUserDefaults like this:
```
[[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"password"];
```
And then I synchronize defaults like this:
```
[[NSUserDefaults standardUserDefaults]synchronize];
```
But when my app enters background and then enters foreground my bool changes value to `YES`
Why does that happen ? I set my bool to `YES` only in one place in program, which is not managing when my app leaves/enters foreground.
Thanks! | 2012/06/07 | [
"https://Stackoverflow.com/questions/10929506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1088286/"
] | Just perform a simple test where you are saving your bool as
```
[[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"password"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSLog(@"%d",[[NSUserDefaults standardUserDefaults] boolForKey:@"password"]);
```
see what's the value.. | Make sure you have the right key string (`@"password"` in your case) when you retrieve the boolean value. It is case sensitive.
```
[[NSUserDefaults standardUserDefaults] boolForKey:@"password"];
```
Do a text search in your whole project for this key and you will find the offending code. |
10,929,506 | I save a bool value in NSUserDefaults like this:
```
[[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"password"];
```
And then I synchronize defaults like this:
```
[[NSUserDefaults standardUserDefaults]synchronize];
```
But when my app enters background and then enters foreground my bool changes value to `YES`
Why does that happen ? I set my bool to `YES` only in one place in program, which is not managing when my app leaves/enters foreground.
Thanks! | 2012/06/07 | [
"https://Stackoverflow.com/questions/10929506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1088286/"
] | Just perform a simple test where you are saving your bool as
```
[[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"password"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSLog(@"%d",[[NSUserDefaults standardUserDefaults] boolForKey:@"password"]);
```
see what's the value.. | Your retrieval code should look something like this.
```
if(![[NSUserDefaults standardUserDefaults] boolForKey:@"password"]) {
//False
} else {
//True
}
``` |
6,096,654 | I have a table with columns `user_id`, `time_stamp` and `activity` which I use for recoding user actions for an audit trail.
Now, I would just like to get the most recent timestamp for each unique `user_id`. How do I do that? | 2011/05/23 | [
"https://Stackoverflow.com/questions/6096654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192910/"
] | `SELECT MAX(time_stamp), user_id FROM table GROUP BY user_id;` | The following query should be what you want...
```
select user_id,max(time_stamp) from yourtable group by user_id order by user_id, time_stamp desc
``` |
70,672,530 | I have to create a route that uploads 1 audio file and 1 image (resized) to Cloudinary using Multer Storage Cloudinary, and save the url and name in my mongo database.
I get the error "Invalid image file" when I try to upload the audio file (even if I delete `transformation` and add "mp3" in `allowedFormats`.
Cloudinary code:
```
const cloudinary = require('cloudinary').v2;
const { CloudinaryStorage } = require('multer-storage-cloudinary');
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_KEY,
api_secret: process.env.CLOUDINARY_SECRET
});
const storage = new CloudinaryStorage({
cloudinary,
params: {
folder: 'nono',
// transformation: [
// {width: 500, height: 500, crop: "fill"}
// // ],
// allowedFormats: ['jpeg', 'png', 'jpg', 'mp3']
}
});
module.exports = { cloudinary, storage }
```
Route code:
```
router.route("/")
.get(catchAsync(sounds.index));
.post(isLoggedIn, upload.fields([{ name: 'sound[audio]', maxCount: 1 }, { name: 'sound[image]', maxCount: 1 }]), joiValidationSounds, catchAsync(sounds.newSound));
```
---
```
module.exports.newSound = async (req, res) => {
const sound = new Sound(req.body.sound);
console.log(req.files)
sound.image.url = req.files["sound[image]"][0].path;
sound.image.filename = req.files["sound[image]"][0].filename;
sound.audio.url = req.files["sound[audio]"][0].path;
sound.audio.filename = req.files["sound[audio]"][0].filename;
sound.author = req.user._id;
await sound.save();
req.flash("success", "Se ha añadido un nuevo sonido.");
res.redirect(`/sounds/categories/:category/${sound._id}`);
}
```
Form code:
```
<form action="/sounds" method="POST" novalidate class="validated-form" enctype="multipart/form-data">
<div class="row mb-3">
<label for="audio" class="col-sm-2 col-form-label">Audio:</label>
<div class="col-sm-10">
<input type="file" name="sound[audio]" id="audio">
</div>
</div>
<div class="row mb-3">
<label for="image" class="col-sm-2 col-form-label">Imagen:</label>
<div class="col-sm-10">
<input type="file" name="sound[image]" id="image">
</div>
</div>
<button type="submit" class="btn btn-success">Crear</button>
<button type="reset" class="btn btn-success">Limpiar</button>
</form>
```
I can upload 2 images instead without problems. I also checked that Cloudinary supports mp3 files.
EDIT: I managed to upload the audio with `resource_type: 'video', allowedFormats: ['mp3'],` and 2 different storages.
But now I get the error "Unexpected field" when I try to upload both.
New code:
```
const storageAudio = new CloudinaryStorage({
cloudinary: cloudinary,
params: {
folder: 'nono',
format: 'mp3',
resource_type: 'video',
allowedFormats: ['mp3'],
}
});
const storageImage = new CloudinaryStorage({
cloudinary: cloudinary,
params: {
folder: 'nono',
transformation: [
{width: 500, height: 500, crop: "fill"}
],
format: 'jpg',
resource_type: 'image',
allowedFormats: ['jpeg', 'png', 'jpg']
}
});
module.exports = { cloudinary, storageImage, storageAudio };
```
*
```
const multer = require("multer");
const { storageImage, storageAudio } = require("../cloudinary");
const uploadAudio = multer({ storage: storageAudio });
const uploadImage = multer({ storage: storageImage });
router.route("/")
.get(catchAsync(sounds.index))
.post(isLoggedIn,
// uploadAudio.fields([{ name: 'sound[audio]', maxCount: 1 }]), uploadImage.fields([{ name: 'sound[image]', maxCount: 1 }]),
uploadAudio.single("sound[audio]"),
uploadImage.single("sound[image]"),
// upload.fields([{ name: 'sound[audio]', maxCount: 1 }, { name: 'sound[image]', maxCount: 1 }]),
joiValidationSounds, catchAsync(sounds.newSound)
);
``` | 2022/01/11 | [
"https://Stackoverflow.com/questions/70672530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14882708/"
] | What they mean is that `BankDataWriterImpl` should inherit from `BankDataWriterBase` like so :
```py
class BankDataWriterBase():
...
class BankDataWriterImpl(BankDataWriterBase):
# this class inherit from parent class BankDataWriterBase
# when a `BankDataWriterBase` object is created, parent.__init__ method is executed.
def extract_jon(self, filename: str):
pass
```
then in driver code, you can create a `BankDataWriterImpl()` object instead of the `BankDataWriterBase()` as you did.
It will inherit its `__init__` method from parent and have a new `extract_json` method.
Another problem you didn't mention come from `BankDataWriterBase` attributes. Your code assume the existance of 3 global variables.
They should be passed to the class when you create the object, like so :
But watchout when creating a `BankSomething` object, since those arguments are now expected :
```py
class BankDataWriterBase:
def __init__(self, input_path, output_path, bank_identifier):
self.input_path = input_path
self.output_path = output_path
self.bank_identifier = bank_identifier
...
obj1 = BankDataWriterImpl(input_path, output_path, bank_identifier)
```
---
Edit after comment : but my lead said write class only for `BankDataWriterBase()`
```py
class BankDataWriterBase:
def __init__(self, input_path, output_path, bank_identifier):
self.input_path = input_path
self.output_path = output_path
self.bank_identifier = bank_identifier
...
def write_file(file_name: str):
pass
obj = BankDataWriterBase(input_path, output_path, bank_identifier)
# setattr add a new attribute to `obj`, first argument is the object,
# second argument its name (obj.name)
# third argument the attribute itself
# here we attach a new method `obj.write_file` to the object
setattr(obj, 'write_file', write_file)
# now you can use it like that :
# this line would have raised an exception before the `setattr` line
obj.write_file("correct_file_path")
``` | the structure without implementations:
```
class Task:
def __init__(self): # initialise all the instance variables (None in this case)
pass # this this might need to be empty
def run(self) -> None:
pass
class BankDataWriterBase:
def __init__(self, file_name: str, out_path: str, bank_id: str):
# you might wan't to set default values: file_name: str = "" for example
self.input_path = file_name
self.output_path = out_path
self.bank_identifier = bank_id
def write_file(self, file_name) -> str:
pass
class BankDataWriterImpl(BankDataWriterBase):
# inherit from BankDataWriterBase, all functions and variables from BankDataWriterBase are now callable from this class
# as said in the other answer, this will be inherited so you don't need to have this
def __init__(self, file_name: str, out_path: str, bank_id: str):
super().__init__(file_name, out_path, bank_id) # call __init__ method of all the superclasses (in this case only BankDataWriterBase)
def extract_json(self, filename: str):
pass
``` |
14,372,385 | I have a UITextView that is being edited and I want to add a custom keyboard... is there any way to dismiss the keyboard but leave the textView in edit mode so the blue cursor keeps flashing? Or better yet is there any way to put a view ontop of the keyboard? | 2013/01/17 | [
"https://Stackoverflow.com/questions/14372385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2057171/"
] | You should register for notification `UIKeyboardWillShowNotification`. It will hit the registered function before displaying keyboard.
Here you can iterate through all Windows and can identify keyboard by below way:
```
for (UIWindow *keyboardWindow in [[UIApplication sharedApplication] windows])
{
for (UIView *keyboard in [keyboardWindow subviews])
{
if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES
||[[keyboard description] hasPrefix:@"<UIPeripheralHost"]== YES)
{
//Set proper frame to hide key board here..
}
```
} | try this
`uitextfieldView.inputView = [[UIView new] autorelease];`
the system keyboard view not shows and it keeps the cursor as you editing.
or
you can hide keyboard by sliding it off-screen
```
frame.origin.y = (keyboard.frame.origin.y - 264);
keyboard.frame = frame;
``` |
6,457,699 | I am having some issues with the following query, the issue is that I need it so it displays the courses for the current day until the end of the day not just till the start of the day like it does currently. Basically users cannot access the course if they are trying to access the course on its enddate so i need to some how make it so that they can still access it for 23 hrs 59 mnutes and 59 seconds after the end date I think I have to add some sort of time to the NOW() to accomplish this but im not sure how to go about this.The query is as follows:
```
if ($courses = $db->qarray("
SELECT `CourseCode` AS 'code' FROM `WorkshopUserSessions`
LEFT JOIN `WorkshopSession` ON (`WorkshopUserSessions`.`sessionid` = `WorkshopSession`.`id`)
LEFT JOIN `WorkshopCourses` ON (`WorkshopSession`.`cid` = `WorkshopCourses`.`cid`)
WHERE `WorkshopUserSessions`.`userid` = {$info['uid']} AND `WorkshopUserSessions`.`begindate` <= NOW() AND `WorkshopUserSessions`.`enddate` >= NOW()
ORDER BY `WorkshopUserSessions`.`begindate` ASC
")) {
```
Any help would greatly be aprreciated!
Thanks,
Cam | 2011/06/23 | [
"https://Stackoverflow.com/questions/6457699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/487003/"
] | I think you need to modify it like this
```
enddate + INTERVAL 1 DAY >= NOW()
```
Ofcourse this adds 24 hours, for 23:59:59 just change >= to > | Try replacing:
```
AND `WorkshopUserSessions`.`enddate` >= NOW()
```
with
```
AND DATE(`WorkshopUserSessions`.`enddate`) = CURDATE()
```
Hope it helps. |
6,457,699 | I am having some issues with the following query, the issue is that I need it so it displays the courses for the current day until the end of the day not just till the start of the day like it does currently. Basically users cannot access the course if they are trying to access the course on its enddate so i need to some how make it so that they can still access it for 23 hrs 59 mnutes and 59 seconds after the end date I think I have to add some sort of time to the NOW() to accomplish this but im not sure how to go about this.The query is as follows:
```
if ($courses = $db->qarray("
SELECT `CourseCode` AS 'code' FROM `WorkshopUserSessions`
LEFT JOIN `WorkshopSession` ON (`WorkshopUserSessions`.`sessionid` = `WorkshopSession`.`id`)
LEFT JOIN `WorkshopCourses` ON (`WorkshopSession`.`cid` = `WorkshopCourses`.`cid`)
WHERE `WorkshopUserSessions`.`userid` = {$info['uid']} AND `WorkshopUserSessions`.`begindate` <= NOW() AND `WorkshopUserSessions`.`enddate` >= NOW()
ORDER BY `WorkshopUserSessions`.`begindate` ASC
")) {
```
Any help would greatly be aprreciated!
Thanks,
Cam | 2011/06/23 | [
"https://Stackoverflow.com/questions/6457699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/487003/"
] | It sounds like you just need to use date\_add
```
DATE_ADD(`WorkshopUserSessions`.`enddate`, INTERVAL 1 DAY) > NOW()
``` | Try replacing:
```
AND `WorkshopUserSessions`.`enddate` >= NOW()
```
with
```
AND DATE(`WorkshopUserSessions`.`enddate`) = CURDATE()
```
Hope it helps. |
133,380 | As the sole product designer in my past two startups I have been an essential piece towards bringing the product to reality (user research, ux, visual design, qa). However, in both situations I found myself not sitting at the leadership table when discussing the future of the product.
Marketing, sales, support, development all had multiple employees and each department head would get a seat at the table, while I found myself on the outside looking in.
I brought this up several times (along with trying to lobby for more resources in my "departments") in 1-1 meetings with the owners but to no avail. I possibly have delusions of grandeur, but in my view if anyone should be at the table with ownership it would be the individual that is creating the experience that customers are going to pay for.
Any suggestions for how to improve/approach this situation or book recommendations that might help? | 2020/06/05 | [
"https://ux.stackexchange.com/questions/133380",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/103302/"
] | Unless you want to spend more time convincing and showing the value of UX through its impact on revenue, I suggest you to move on.
Otherwise, treat it like a project. Understand what the heads really care about and show how UX can help. | A lot of this is determined by the structure and the nature of the company, and it is not always something that you can control unless you are prepared to spend a lot of time and effort into 'educating' the stakeholders.
For example, a company that focuses on sales and is a startup will probably use UX to tick a box for potential investors, rather than being a customer/consumer focused business that wants to make the user experience a point of difference. You can often tell by the C-suite level makeup of the company (e.g. whether they have anyone with a UX background or a Chief Experience Officer).
A traditional company or business often has many levels of hierarchy, and it can take a lot of communication for the type of insights and values generated by good UX research and design to filter up to the top (I have been in this situation many times before). It is important in those situations to work towards establishing UX design as a capability or area of expertise in the business as a first step towards getting a seat at the table (at least compared to the 'flatter' structure of startups).
So I would suggest doing a bit more research into the background of the company, their product, business model and the team that you will be working with initially, rather than going into a project and expect to be able to make wholesale changes when the focus is probably on delivering a product based on a set timeline (I know that it doesn't sound very user-centric or 'Agile' but then again very few businesses truly embrace both philosophies). |
133,380 | As the sole product designer in my past two startups I have been an essential piece towards bringing the product to reality (user research, ux, visual design, qa). However, in both situations I found myself not sitting at the leadership table when discussing the future of the product.
Marketing, sales, support, development all had multiple employees and each department head would get a seat at the table, while I found myself on the outside looking in.
I brought this up several times (along with trying to lobby for more resources in my "departments") in 1-1 meetings with the owners but to no avail. I possibly have delusions of grandeur, but in my view if anyone should be at the table with ownership it would be the individual that is creating the experience that customers are going to pay for.
Any suggestions for how to improve/approach this situation or book recommendations that might help? | 2020/06/05 | [
"https://ux.stackexchange.com/questions/133380",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/103302/"
] | You Can Sit at My Table When You Improve the Things I Care About
----------------------------------------------------------------
Your owners (like the users you research) have goals, needs, tasks to accomplish, and metrics to improve so they and their business can succeed. If you want a seat at the table you will need to not only understand those goals, needs, and tasks; but help your owners with them.
The best tactic is to tie the owners' business metrics directly to your work:
* Show how your UX work improved Customer Acquisition by X%
* Show how your interaction design changes reduced support costs by $X
* Show how a redesign attracted a specific angel investor
Once you show your owners that you can directly impact their goals for the better, they will be more than happy to "pull up a chair" for you and include you in the product and company's roadmap.
After showing your positive impact on the bottom line and getting acknowledgement from you owners, then you can request investment in more UX resources (people and tools). | Unless you want to spend more time convincing and showing the value of UX through its impact on revenue, I suggest you to move on.
Otherwise, treat it like a project. Understand what the heads really care about and show how UX can help. |
133,380 | As the sole product designer in my past two startups I have been an essential piece towards bringing the product to reality (user research, ux, visual design, qa). However, in both situations I found myself not sitting at the leadership table when discussing the future of the product.
Marketing, sales, support, development all had multiple employees and each department head would get a seat at the table, while I found myself on the outside looking in.
I brought this up several times (along with trying to lobby for more resources in my "departments") in 1-1 meetings with the owners but to no avail. I possibly have delusions of grandeur, but in my view if anyone should be at the table with ownership it would be the individual that is creating the experience that customers are going to pay for.
Any suggestions for how to improve/approach this situation or book recommendations that might help? | 2020/06/05 | [
"https://ux.stackexchange.com/questions/133380",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/103302/"
] | You Can Sit at My Table When You Improve the Things I Care About
----------------------------------------------------------------
Your owners (like the users you research) have goals, needs, tasks to accomplish, and metrics to improve so they and their business can succeed. If you want a seat at the table you will need to not only understand those goals, needs, and tasks; but help your owners with them.
The best tactic is to tie the owners' business metrics directly to your work:
* Show how your UX work improved Customer Acquisition by X%
* Show how your interaction design changes reduced support costs by $X
* Show how a redesign attracted a specific angel investor
Once you show your owners that you can directly impact their goals for the better, they will be more than happy to "pull up a chair" for you and include you in the product and company's roadmap.
After showing your positive impact on the bottom line and getting acknowledgement from you owners, then you can request investment in more UX resources (people and tools). | A lot of this is determined by the structure and the nature of the company, and it is not always something that you can control unless you are prepared to spend a lot of time and effort into 'educating' the stakeholders.
For example, a company that focuses on sales and is a startup will probably use UX to tick a box for potential investors, rather than being a customer/consumer focused business that wants to make the user experience a point of difference. You can often tell by the C-suite level makeup of the company (e.g. whether they have anyone with a UX background or a Chief Experience Officer).
A traditional company or business often has many levels of hierarchy, and it can take a lot of communication for the type of insights and values generated by good UX research and design to filter up to the top (I have been in this situation many times before). It is important in those situations to work towards establishing UX design as a capability or area of expertise in the business as a first step towards getting a seat at the table (at least compared to the 'flatter' structure of startups).
So I would suggest doing a bit more research into the background of the company, their product, business model and the team that you will be working with initially, rather than going into a project and expect to be able to make wholesale changes when the focus is probably on delivering a product based on a set timeline (I know that it doesn't sound very user-centric or 'Agile' but then again very few businesses truly embrace both philosophies). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.