qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
64,637,084 | Could anyone please help me with why I am getting the below error, everything worked before when I used the same logic, after I converted my data type of date columns to the appropriate format.
Below is the line of code I am trying to run
```
data['OPEN_DT'] = data['OPEN_DT'].apply(lambda x: datetime.strptime(x,'%Y-%... | 2020/11/01 | [
"https://Stackoverflow.com/questions/64637084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14559396/"
] | I assumed that you don't want to repeat the add button, then,
I removed the button from the template, that way you can only add the input fields:
Here you can find a working example: <https://stackblitz.com/edit/js-gp6xjx?file=index.html>
```js
const data = [];
const appendContent = () => {
let form_content = docu... | Alright, so I was fiddling with it a little bit, I'm not very experienced with pure javascript. I came up with a few ideas:
1 - Separate submit and add field buttons.
When you press add field, it just adds new fields inside your form which will later be submitted as part of a complete form.
2 - Indexed forms
The id... |
44,872,673 | Let's say I have this code in `test.py`:
```
import sys
a = 'alfa'
b = 'beta'
c = 'gamma'
d = 'delta'
print(sys.argv[1])
```
Running `python test.py a` would then return `a`. How can I make it return `alfa` instead? | 2017/07/02 | [
"https://Stackoverflow.com/questions/44872673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4931616/"
] | Using a dictionary that maps to those strings:
```
mapping = {'a': 'alfa', 'd': 'delta', 'b': 'beta', 'c': 'gamma'}
```
Then when you get your `sys.argv[1]` just access the value from your dictionary as:
```
print(mapping.get(sys.argv[1]))
```
Demo:
File: `so_question.py`
```
import sys
mapping = {'a': 'alf... | You can also use the `globals` or `locals`:
```
import sys
a = 'alfa'
b = 'beta'
c = 'gamma'
d = 'delta'
print(globals().get(sys.argv[1]))
# or
print(locals().get(sys.argv[1]))
``` |
50,809,096 | A few days ago I started getting the following error when using pip (1,2 or 3) to install.
\*
```
Traceback (most recent call last): File "/home/c4pta1n/.local/bin/pip", line 7, in <module>
from pip._internal import main File "/home/c4pta1n/.local/lib/python2.7/site-packages/pip/_internal/__init__.py", line ... | 2018/06/12 | [
"https://Stackoverflow.com/questions/50809096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8213561/"
] | [six 1.3.0](https://github.com/benjaminp/six/blob/1.3.0/six.py) doesn't have `add_metaclass`. It was released in 2013 year. Really time to upgrade it. | I found the answer to my issue. Apparently some linux versions have specific versions of pip and six that have to be installed through the distro package manager directly in order to work. There are some nuanced changes in how Debian makes use of pip, especially regarding updates, and they have coded these changes in t... |
28,849,386 | How to remove T from time format `%Y-%m-%dT%H:%M:%S` in python?
Am using it in my html as
```
<b>Start:{{ start.date_start }}<br/>
``` | 2015/03/04 | [
"https://Stackoverflow.com/questions/28849386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4631100/"
] | ```
@register.filter
def isotime(datestring):
datestring = str(datestring)
return datestring.replace("T"," ")
``` | Manually format the datetime, don't rely on the default `str()` formatting. You can use [`datetime.datetime.isoformat()`](https://docs.python.org/2/library/datetime.html#datetime.datetime.isoformat) for example, passing in a space as the separator:
```
<b>Start:{{ start.date_start.isoformat(' ') }}<br/>
```
or you ... |
22,882,427 | I want to take input as string as raw\_input and want to use this value in another line for taking the input in python. My code is below:
```
p1 = raw_input('Enter the name of Player 1 :')
p2 = raw_input('Enter the name of Player 2 :')
p1 = input('Welcome %s > Enter your no:') % p1
```
Here in place of `%s` I want ... | 2014/04/05 | [
"https://Stackoverflow.com/questions/22882427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3494397/"
] | You can do (the vast majority will agree that this is the best way):
```
p1 = input('Welcome {0} > Enter your no:'.format(p1))
``` | Try
```
input("Welcome " + p1 + "> Enter your no:")
```
It concatenates the value of `p1` to the input string
Also see [here](https://docs.python.org/2/library/string.html)
```
input("Welcome {0}, {1} > Enter your no".format(p1, p2)) #you can have multiple values
```
**EDIT**
Note that using `+` is [discouraged... |
22,882,427 | I want to take input as string as raw\_input and want to use this value in another line for taking the input in python. My code is below:
```
p1 = raw_input('Enter the name of Player 1 :')
p2 = raw_input('Enter the name of Player 2 :')
p1 = input('Welcome %s > Enter your no:') % p1
```
Here in place of `%s` I want ... | 2014/04/05 | [
"https://Stackoverflow.com/questions/22882427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3494397/"
] | You can do (the vast majority will agree that this is the best way):
```
p1 = input('Welcome {0} > Enter your no:'.format(p1))
``` | This doesn't work because Python interprets
```
p1 = input('Welcome %s > Enter your no:') % p1
```
As:
1. Get input, using the prompt `'Welcome %s > Enter your no:'`;
2. Try to insert `p1` into the *text returned by* `input`, which will cause a `TypeError` unless the user's number includes `'%s'`; and
3. Assign the... |
22,882,427 | I want to take input as string as raw\_input and want to use this value in another line for taking the input in python. My code is below:
```
p1 = raw_input('Enter the name of Player 1 :')
p2 = raw_input('Enter the name of Player 2 :')
p1 = input('Welcome %s > Enter your no:') % p1
```
Here in place of `%s` I want ... | 2014/04/05 | [
"https://Stackoverflow.com/questions/22882427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3494397/"
] | Try
```
input("Welcome " + p1 + "> Enter your no:")
```
It concatenates the value of `p1` to the input string
Also see [here](https://docs.python.org/2/library/string.html)
```
input("Welcome {0}, {1} > Enter your no".format(p1, p2)) #you can have multiple values
```
**EDIT**
Note that using `+` is [discouraged... | This doesn't work because Python interprets
```
p1 = input('Welcome %s > Enter your no:') % p1
```
As:
1. Get input, using the prompt `'Welcome %s > Enter your no:'`;
2. Try to insert `p1` into the *text returned by* `input`, which will cause a `TypeError` unless the user's number includes `'%s'`; and
3. Assign the... |
26,664,102 | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26664102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036670/"
] | Update your `pip` first:
```
pip install --upgrade pip
```
for Python 3:
```
pip3 install --upgrade pip
``` | I tried everything said here without any luck, but found a workaround.
After running this command (and failing) : `bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg`
Go to the temporary directory the tool made (given in the output of the last command), then execute `python setup.py bdist_whe... |
26,664,102 | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26664102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036670/"
] | Install the [`wheel` package](https://pypi.python.org/pypi/wheel) first:
```
pip install wheel
```
The documentation isn't overly clear on this, but *"the wheel project provides a bdist\_wheel command for setuptools"* actually means *"the wheel **package**..."*. | I also ran into the error message `invalid command 'bdist_wheel'`
It turns out the package setup.py used distutils rather than setuptools.
Changing it as follows enabled me to build the wheel.
```
#from distutils.core import setup
from setuptools import setup
``` |
26,664,102 | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26664102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036670/"
] | I also ran into this all of a sudden, after it had previously worked, and it was because I was inside a virtualenv, and `wheel` wasn’t installed in the virtualenv. | Throwing in another answer: Try checking your `PYTHONPATH`.
First, try to install `wheel` again:
```
pip install wheel
```
This should tell you where wheel is installed, eg:
```
Requirement already satisfied: wheel in /usr/local/lib/python3.5/dist-packages
```
Then add the location of wheel to your `PYTHONPATH`:... |
26,664,102 | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26664102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036670/"
] | Throwing in another answer: Try checking your `PYTHONPATH`.
First, try to install `wheel` again:
```
pip install wheel
```
This should tell you where wheel is installed, eg:
```
Requirement already satisfied: wheel in /usr/local/lib/python3.5/dist-packages
```
Then add the location of wheel to your `PYTHONPATH`:... | I tried everything said here without any luck, but found a workaround.
After running this command (and failing) : `bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg`
Go to the temporary directory the tool made (given in the output of the last command), then execute `python setup.py bdist_whe... |
26,664,102 | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26664102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036670/"
] | Install the [`wheel` package](https://pypi.python.org/pypi/wheel) first:
```
pip install wheel
```
The documentation isn't overly clear on this, but *"the wheel project provides a bdist\_wheel command for setuptools"* actually means *"the wheel **package**..."*. | Throwing in another answer: Try checking your `PYTHONPATH`.
First, try to install `wheel` again:
```
pip install wheel
```
This should tell you where wheel is installed, eg:
```
Requirement already satisfied: wheel in /usr/local/lib/python3.5/dist-packages
```
Then add the location of wheel to your `PYTHONPATH`:... |
26,664,102 | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26664102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036670/"
] | Install the [`wheel` package](https://pypi.python.org/pypi/wheel) first:
```
pip install wheel
```
The documentation isn't overly clear on this, but *"the wheel project provides a bdist\_wheel command for setuptools"* actually means *"the wheel **package**..."*. | It could also be that you have a python3 system only.
You therefore have installed the necessary packages via pip3 install , like *pip3 install wheel*.
You'll need to build your stuff using python3 specifically.
```
python3 setup.py sdist
python3 setup.py bdist_wheel
```
Cheers. |
26,664,102 | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26664102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036670/"
] | I also ran into the error message `invalid command 'bdist_wheel'`
It turns out the package setup.py used distutils rather than setuptools.
Changing it as follows enabled me to build the wheel.
```
#from distutils.core import setup
from setuptools import setup
``` | It could also be that you have a python3 system only.
You therefore have installed the necessary packages via pip3 install , like *pip3 install wheel*.
You'll need to build your stuff using python3 specifically.
```
python3 setup.py sdist
python3 setup.py bdist_wheel
```
Cheers. |
26,664,102 | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26664102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036670/"
] | Update your `pip` first:
```
pip install --upgrade pip
```
for Python 3:
```
pip3 install --upgrade pip
``` | Throwing in another answer: Try checking your `PYTHONPATH`.
First, try to install `wheel` again:
```
pip install wheel
```
This should tell you where wheel is installed, eg:
```
Requirement already satisfied: wheel in /usr/local/lib/python3.5/dist-packages
```
Then add the location of wheel to your `PYTHONPATH`:... |
26,664,102 | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26664102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036670/"
] | I also ran into this all of a sudden, after it had previously worked, and it was because I was inside a virtualenv, and `wheel` wasn’t installed in the virtualenv. | It could also be that you have a python3 system only.
You therefore have installed the necessary packages via pip3 install , like *pip3 install wheel*.
You'll need to build your stuff using python3 specifically.
```
python3 setup.py sdist
python3 setup.py bdist_wheel
```
Cheers. |
26,664,102 | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26664102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1036670/"
] | Install the [`wheel` package](https://pypi.python.org/pypi/wheel) first:
```
pip install wheel
```
The documentation isn't overly clear on this, but *"the wheel project provides a bdist\_wheel command for setuptools"* actually means *"the wheel **package**..."*. | I also ran into this all of a sudden, after it had previously worked, and it was because I was inside a virtualenv, and `wheel` wasn’t installed in the virtualenv. |
39,137,179 | I am working on a rails application now that needs to run a single python script whenever a button is clicked on our apps home page. I am trying to figure out a way to have rails run this script, and both of my attempts so far have failed.
My first try was to use the exec(..) command to just run the "python script.py... | 2016/08/25 | [
"https://Stackoverflow.com/questions/39137179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5805587/"
] | Here are ways to execute a shell script
```
`python pythonscript.py`
```
or
```
system( "python pythonscript.py" )
```
or
```
exec(" python pythonscript.py")
```
exec replaces the current process by running the given external command.
Returns none, the current process is replaced and never continues. | `exec` replaces the current process with the new one. You want to run it as a subprocess. See [When to use each method of launching a subprocess in Ruby](https://stackoverflow.com/questions/7212573/when-to-use-each-method-of-launching-a-subprocess-in-ruby) for an overview; I suggest using either backticks for a simple ... |
65,148,247 | For an unknown reason, I ran into a docker error when I tried to run a `docker-compose up` on my project this morning.
My web container isn't able to connect to the db host and `nc` still returning
>
> web\_1 | nc: bad address 'db'
>
>
>
There is the relevant part of my docker-compose definition :
```yaml
versi... | 2020/12/04 | [
"https://Stackoverflow.com/questions/65148247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3950328/"
] | I was able to fix that by running `docker-compose down && docker-compose up` but it could be kinda bad if your down was removing all your volumes and so, your data...
The inspection of networking is now alright :
```json
[
{
"Name": "my_docker_network",
"Id": "236c45042b03c3a2922d9a9fabf644048901c... | I had the same problem, but with rabbitmq service in my compose file. At first I solved it by deleting all existing container and volumes on my machine, (but it happened again here and then) but later I updated the rabbitmq image version to latest in `docker-compose.yml`:
```
image: rabbitmq:latest
```
and the probl... |
66,386,685 | I'm working on a secure system where internet access is restricted. My company will let my install python and libraries, but they only allow the unblocking of specific urls temporarily. So I need to know what urls do I need to unblock to install python and what urls I need to unblock to execute
**pip install pandas**
... | 2021/02/26 | [
"https://Stackoverflow.com/questions/66386685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12986251/"
] | You can do all that in one loop - that would be way faster. To know the correct position to put the number in, add extra counter for each array.
### Your kind of approach
```java
int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
int[] odd = new int[10];
int[] even = new int[10];
int oddPos = 0;
int... | the approach for detecting `odd` and `even` numbers is correct, But I think the problem with the code you wrote is that the length of `odd` and `even` arrays, isn't determinant. so for this matter, I suggest using `ArrayList<Integer>`, let's say you get the array in a function input, and want arrays in the output (I'll... |
66,386,685 | I'm working on a secure system where internet access is restricted. My company will let my install python and libraries, but they only allow the unblocking of specific urls temporarily. So I need to know what urls do I need to unblock to install python and what urls I need to unblock to execute
**pip install pandas**
... | 2021/02/26 | [
"https://Stackoverflow.com/questions/66386685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12986251/"
] | You can do all that in one loop - that would be way faster. To know the correct position to put the number in, add extra counter for each array.
### Your kind of approach
```java
int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
int[] odd = new int[10];
int[] even = new int[10];
int oddPos = 0;
int... | *in lambda (3 lines)*
```java
int[] nums = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
```
separate even and odd `nums` with `partitioningBy`:
```java
Map<Boolean, List<Integer>> map = IntStream.of(nums)
.boxed().collect(partitioningBy(n -> (n & 1) == 0));
```
…and transform the resulting `List<Integer>` fo... |
66,386,685 | I'm working on a secure system where internet access is restricted. My company will let my install python and libraries, but they only allow the unblocking of specific urls temporarily. So I need to know what urls do I need to unblock to install python and what urls I need to unblock to execute
**pip install pandas**
... | 2021/02/26 | [
"https://Stackoverflow.com/questions/66386685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12986251/"
] | You can do all that in one loop - that would be way faster. To know the correct position to put the number in, add extra counter for each array.
### Your kind of approach
```java
int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
int[] odd = new int[10];
int[] even = new int[10];
int oddPos = 0;
int... | You can collect a 2d array with two rows: *even* and *odd* as follows:
```java
int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
```
```java
// a 2d array of two rows: even and odd
int[][] arr = new int[2][];
// process a 1d array and fill a 2d array
Arrays.stream(num).boxed()
// Map<Integ... |
66,386,685 | I'm working on a secure system where internet access is restricted. My company will let my install python and libraries, but they only allow the unblocking of specific urls temporarily. So I need to know what urls do I need to unblock to install python and what urls I need to unblock to execute
**pip install pandas**
... | 2021/02/26 | [
"https://Stackoverflow.com/questions/66386685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12986251/"
] | the approach for detecting `odd` and `even` numbers is correct, But I think the problem with the code you wrote is that the length of `odd` and `even` arrays, isn't determinant. so for this matter, I suggest using `ArrayList<Integer>`, let's say you get the array in a function input, and want arrays in the output (I'll... | *in lambda (3 lines)*
```java
int[] nums = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
```
separate even and odd `nums` with `partitioningBy`:
```java
Map<Boolean, List<Integer>> map = IntStream.of(nums)
.boxed().collect(partitioningBy(n -> (n & 1) == 0));
```
…and transform the resulting `List<Integer>` fo... |
66,386,685 | I'm working on a secure system where internet access is restricted. My company will let my install python and libraries, but they only allow the unblocking of specific urls temporarily. So I need to know what urls do I need to unblock to install python and what urls I need to unblock to execute
**pip install pandas**
... | 2021/02/26 | [
"https://Stackoverflow.com/questions/66386685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12986251/"
] | the approach for detecting `odd` and `even` numbers is correct, But I think the problem with the code you wrote is that the length of `odd` and `even` arrays, isn't determinant. so for this matter, I suggest using `ArrayList<Integer>`, let's say you get the array in a function input, and want arrays in the output (I'll... | You can collect a 2d array with two rows: *even* and *odd* as follows:
```java
int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
```
```java
// a 2d array of two rows: even and odd
int[][] arr = new int[2][];
// process a 1d array and fill a 2d array
Arrays.stream(num).boxed()
// Map<Integ... |
70,187,603 | I am able to create an image via az cli commands with:
```
az vm create --resource-group $RG2 \
--name $VM_NAME --image $(az sig image-version show \
--resource-group $RG \
--gallery-name $SIG \
--gallery-image-definition $SIG_IMAGE_DEFINITION \
--gallery-image-version $VERSION \
--query id -o tsv) \
--size $SIZE \
--... | 2021/12/01 | [
"https://Stackoverflow.com/questions/70187603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372429/"
] | You can modify the [example script](https://learn.microsoft.com/en-us/azure/developer/python/azure-sdk-example-virtual-machines?tabs=cmd) in our doc to do this. Essentially, you need to get rid of step 4. and modify step 5 to not send a public IP when creating the NIC. This has been validated in my own subscription.
`... | ```
resource_name = f"myserver{random.randint(1000, 9999)}"
VNET_NAME = "myteam-vpn-vnet"
SUBNET_NAME = "myteam-subnet"
IP_NAME = resource_name + "-ip"
IP_CONFIG_NAME = resource_name + "-ip-config"
NIC_NAME = resource_name + "-nic"
Subnet=network_client.subnets.get(resource_group_name, VNET_NAME, SUBNET_NAME)
# S... |
61,037,527 | I want to run my code on GPU provided by Kaggle. I am able to run my code on CPU though but unable to migrate it properly to run on Kaggle GPU I guess.
On running this
```
with tf.device("/device:GPU:0"):
hist = model.fit(x=X_train, y=Y_train, validation_data=(X_test, Y_test), batch_size=25, epochs=20, callbacks=cal... | 2020/04/05 | [
"https://Stackoverflow.com/questions/61037527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9872938/"
] | Can you try to update `@material-ui/core` by running
```
npm update
``` | As described in the Material-UI project [CHANGELOG](https://github.com/mui-org/material-ui/releases/tag/v4.9.9) of the latest version (which is **v4.9.9** the time I'm writing this answer), there is a change related to `createSvgIcon`
[](https://i.st... |
67,327,106 | I am trying to load a serialized xgboost model from a pickle file.
```
import pickle
def load_pkl(fname):
with open(fname, 'rb') as f:
obj = pickle.load(f)
return obj
model = load_pkl('model_0_unrestricted.pkl')
```
while printing the model object, I am getting the following error in linux(AWS Sagem... | 2021/04/30 | [
"https://Stackoverflow.com/questions/67327106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2140489/"
] | Looks like you upgraded xgboost.
You may consider downgrading to 1.2.0 by:
```
pip install xgboost==1.2.0
``` | I tried testing on notebook running on ubuntu, it seems to work fine, however can you check how are you initializing your classifier ? This is what I tried :
```
import numpy as np
import pickle
from scipy.stats import uniform, randint
from sklearn.datasets import load_breast_cancer, load_diabetes, load_wine
from skl... |
67,327,106 | I am trying to load a serialized xgboost model from a pickle file.
```
import pickle
def load_pkl(fname):
with open(fname, 'rb') as f:
obj = pickle.load(f)
return obj
model = load_pkl('model_0_unrestricted.pkl')
```
while printing the model object, I am getting the following error in linux(AWS Sagem... | 2021/04/30 | [
"https://Stackoverflow.com/questions/67327106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2140489/"
] | Looks like you upgraded xgboost.
You may consider downgrading to 1.2.0 by:
```
pip install xgboost==1.2.0
``` | I suspect the pickled model you are loading in was modified in someway to have that additional method prior to being saved. Either that or as @vbhatt said, you may be modifying some aspect of your classifier prior to loading it in. This has happened to me before when using custom models in Pytorch Lightning.
If you ha... |
52,104,644 | I have the following function which basically asks user to enter the choice for "X" or "O". I used the while loop to keep asking user until I get the answer that's either "X" or "O".
```
def player_input():
choice = ''
while choice != "X" and choice != "O":
choice = input("Player 1, choose X or O: ")... | 2018/08/30 | [
"https://Stackoverflow.com/questions/52104644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9114293/"
] | Loop indexing is well known in Python to be an incredibly slow operation. By replacing a loop with array slicing, and a list with a Numpy array, we see increases @ 3x:
```
import numpy as np
import timeit
def generate_primes_original(limit):
boolean_list = [False] * 2 + [True] * (limit - 1)
for n in range(2, ... | If your are still using Python 2 use xrange instead of range for greater speed |
32,478,825 | I am using python and scikit-learn to find the cosine similarity between two strings(specifically, names).The program is able to find the similarity score between two strings but, when strings are abbreviated, it shows some undesirable output.
e.g- String1 ="K KAPOOR",String2="L KAPOOR"
The cosine similarity score of ... | 2015/09/09 | [
"https://Stackoverflow.com/questions/32478825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4994653/"
] | As mentioned in the other answer, the cosine similarity is one because the two strings have **the exact same representation**.
That means that this code:
```
tfidf_vectorizer=TfidfVectorizer()
tfidf_matrix=tfidf_vectorizer.fit_transform(documents)
```
produces, well:
```
print(tfidf_matrix.toarray())
[[ 1.]
[ 1.]... | >
> String1 ="K KAPOOR", String2="L KAPOOR" The cosine similarity score of these strings is 1 (maximum) while the two strings are entirely different names. Is there a way to modify it, in order to get some desired results.
>
>
>
**It depends.** You are facing an issue because the vector representation of these two... |
2,545,655 | Using Python 2.6.4, windows
With the following script I want to test a certain xmlrpc server. I call a non-existent function and hope for a traceback with an error. Instead, the function does not return. What could be the cause?
```
import xmlrpclib
s = xmlrpclib.Server("http://127.0.0.1:80", verbose=True)
s.function... | 2010/03/30 | [
"https://Stackoverflow.com/questions/2545655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80500/"
] | As you noticed, this is a bug in the server (the client claims to understand 1.0 and the server ignores that and responds in 1.1 anyway, so doesn't close the socket). Python has a workaround for such buggy servers in 2.7 and 3.2, see [this issue](http://bugs.python.org/issue6267), but that workaround wasn't in 2.6.4. U... | Most likely, the server you're testing does not close the TCP connection once it has sent the response back to your client. Thus the client hangs, waiting for the server to close the connection before it can return from the function. |
59,524,498 | I am trying to create a seaborn Facetgrid to plot the normality distribution of all columns in my dataFrame decathlon. The data looks as such:
```
P100m Plj Psp Phj P400m P110h Ppv Pdt Pjt P1500
0 938 1061 773 859 896 911 880 732 757 752
1 839 975 870 749 887 878 ... | 2019/12/30 | [
"https://Stackoverflow.com/questions/59524498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10574250/"
] | I encountered this similar issue when running a Jupyter Notebook.
My solution involved:
1. Restart the notebook
2. Re-run the imports `%matplotlib inline; import matplotlib.pyplot as plt` | As you did not post a full working example its a bit of guessing.
What might go wrong is in the line where you have `g = g.map(plt.hist, "values")` because the error comes from deep within matplotlib. You can see this [here](https://stackoverflow.com/questions/40399631/valueerror-axes-instance-argument-was-not-found-i... |
60,182,791 | I have tried uploading file to Google Drive from my local system using a Python script but I keep getting HttpError 403. The script is as follows:
```python
from googleapiclient.http import MediaFileUpload
from googleapiclient import discovery
import httplib2
import auth
SCOPES = "https://www.googleapis.com/auth/dri... | 2020/02/12 | [
"https://Stackoverflow.com/questions/60182791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7640700/"
] | Try with this:
```
var str = @"email from Ram at 10:10 am"" ""email from Ramesh at 10:15 am"" ""email from Rajan at 10:20 am"" ""email from Rakesh at 10:25 am";
string[] sl=str.Trim().Split(new string[] { "\" \"" }, StringSplitOptions.None);
foreach(string st in sl) {
Console.WriteLine(st);
}
```
**Output:**
... | It is possible to use additional `"` as they are part of the string literal. And they will be interpreted by the compiler as a single ":
```
var str = @"email from Ram at 10:10 am"" ""email from Ramesh at 10:15 am"" ""email from Rajan at 10:20 am"" ""email from Rakesh at 10:25 am";
var splitted = str.Split... |
9,833,152 | >
> **Possible Duplicate:**
>
> [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags)
>
>
>
If I have a string that looks something like...
```
"<tr><td>123</td><td>234</td>...<td>697</td></tr>"
```
Basica... | 2012/03/23 | [
"https://Stackoverflow.com/questions/9833152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/399523/"
] | If that markup is part of a larger set of markup, you should prefer a tool with a HTML parser.
One such tool is [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/).
Here's one way to find what you need using that tool:
```
>>> markup = '''"<tr><td>123</td><td>234</td>...<td>697</td></tr>"'''
>>> from ... | Don't do this. Just use a proper HTML parser, and use something like xpath to get the elements you want.
A lot of people like lxml. For this task, you will probably want to use the BeautifulSoup backend, or use BeautifulSoup directly, because this is presumably not markup from a source known to generate well-formed, v... |
9,833,152 | >
> **Possible Duplicate:**
>
> [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags)
>
>
>
If I have a string that looks something like...
```
"<tr><td>123</td><td>234</td>...<td>697</td></tr>"
```
Basica... | 2012/03/23 | [
"https://Stackoverflow.com/questions/9833152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/399523/"
] | If that markup is part of a larger set of markup, you should prefer a tool with a HTML parser.
One such tool is [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/).
Here's one way to find what you need using that tool:
```
>>> markup = '''"<tr><td>123</td><td>234</td>...<td>697</td></tr>"'''
>>> from ... | When using [lxml](https://lxml.de/), an element tree gets created. Each element in the element tree holds information about a tag.
```
from lxml import etree
root = etree.XML("<root><a x='123'>aText<b/><c/><b/></a></root>")
elements = root.findall(".//a")
tag = elements[0].tag
attr = elements[0].attrib
``` |
58,350,100 | I am trying to solve this [Dynamic Array problem](https://www.hackerrank.com/challenges/dynamic-array/problem?isFullScreen=true) on HackerRank. This is my code:
```py
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'dynamicArray' function below.
#
# The function is expected t... | 2019/10/12 | [
"https://Stackoverflow.com/questions/58350100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8598839/"
] | you can try this, it works totally fine.(no runtime error)
==========================================================
>
> Replace your dynamicArray function with this code. Hopefully this will be helpful for you (^\_^).
>
>
>
def dynamicArray(n, queries):
```
col = [[] for i in range(n)]
res = []
lastanswer = 0
... | The answer to your question lies in the boilerplate provided by hackerrank.
`# The function is expected to return an INTEGER_ARRAY.`
You can also see that `result = dynamicArray(n, queries)` is expected to return a list of integers from `map(str, result)`, which throws the exception.
In your code you do `print(lastA... |
58,350,100 | I am trying to solve this [Dynamic Array problem](https://www.hackerrank.com/challenges/dynamic-array/problem?isFullScreen=true) on HackerRank. This is my code:
```py
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'dynamicArray' function below.
#
# The function is expected t... | 2019/10/12 | [
"https://Stackoverflow.com/questions/58350100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8598839/"
] | The answer to your question lies in the boilerplate provided by hackerrank.
`# The function is expected to return an INTEGER_ARRAY.`
You can also see that `result = dynamicArray(n, queries)` is expected to return a list of integers from `map(str, result)`, which throws the exception.
In your code you do `print(lastA... | ```
def dynamicArray(n, queries):
# Write your code here
arr=[[]for i in range(0,n)]
lastAnswer=0
answers=[]
for query in queries:
if query[0]==1:
idx= (query[1]^lastAnswer)%n
arr[idx].append(query[2])
if query[0]==2:
idx= (query[1]^lastAnswer)%n
lastAnswer= arr[idx][query[2]... |
58,350,100 | I am trying to solve this [Dynamic Array problem](https://www.hackerrank.com/challenges/dynamic-array/problem?isFullScreen=true) on HackerRank. This is my code:
```py
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'dynamicArray' function below.
#
# The function is expected t... | 2019/10/12 | [
"https://Stackoverflow.com/questions/58350100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8598839/"
] | you can try this, it works totally fine.(no runtime error)
==========================================================
>
> Replace your dynamicArray function with this code. Hopefully this will be helpful for you (^\_^).
>
>
>
def dynamicArray(n, queries):
```
col = [[] for i in range(n)]
res = []
lastanswer = 0
... | ```
def dynamicArray(n, queries):
# Write your code here
arr=[[]for i in range(0,n)]
lastAnswer=0
answers=[]
for query in queries:
if query[0]==1:
idx= (query[1]^lastAnswer)%n
arr[idx].append(query[2])
if query[0]==2:
idx= (query[1]^lastAnswer)%n
lastAnswer= arr[idx][query[2]... |
23,211,546 | I had asked a similar question [here](https://stackoverflow.com/questions/23159053/re-read-a-file-from-start-after-the-program-finishes-reading-it-python/23159107) and the answer that I get was to use the `seek()` method. Now I am doing the following:
```
with open("total.csv", 'rb') as input1:
time.sleep(3)
i... | 2014/04/22 | [
"https://Stackoverflow.com/questions/23211546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3534055/"
] | For simplicity, create an generator:
```
def repeated_reader(input, reader):
while True:
input.seek(0)
for row in reader:
yield row
with open("total.csv", 'rb') as input1:
reader = csv.reader(input1, delimiter="\t")
for row in repeated_reader(input1, reader):
#Read the ... | Does it have to be in the `for`-loop? You could achieve this behaviour like this (untested):
```
with open("total.csv", 'rb') as input1:
time.sleep(3)
reader = csv.reader(input1, delimiter="\t")
while True:
input1.seek(0)
for row in reader:
#Read the CSV row by row.
``` |
23,211,546 | I had asked a similar question [here](https://stackoverflow.com/questions/23159053/re-read-a-file-from-start-after-the-program-finishes-reading-it-python/23159107) and the answer that I get was to use the `seek()` method. Now I am doing the following:
```
with open("total.csv", 'rb') as input1:
time.sleep(3)
i... | 2014/04/22 | [
"https://Stackoverflow.com/questions/23211546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3534055/"
] | Does it have to be in the `for`-loop? You could achieve this behaviour like this (untested):
```
with open("total.csv", 'rb') as input1:
time.sleep(3)
reader = csv.reader(input1, delimiter="\t")
while True:
input1.seek(0)
for row in reader:
#Read the CSV row by row.
``` | I actually calculated the total number of rows in the CSV and when I was on the last row I did `input1.seek(0)`
```
row_count = sum(1 for row in csv.reader(open('total.csv')))
print row_count
row_count2 = 0
with open("total.csv", 'rb') as input1:
time.sleep(3)
input1.seek(0)
reader = csv.read... |
23,211,546 | I had asked a similar question [here](https://stackoverflow.com/questions/23159053/re-read-a-file-from-start-after-the-program-finishes-reading-it-python/23159107) and the answer that I get was to use the `seek()` method. Now I am doing the following:
```
with open("total.csv", 'rb') as input1:
time.sleep(3)
i... | 2014/04/22 | [
"https://Stackoverflow.com/questions/23211546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3534055/"
] | For simplicity, create an generator:
```
def repeated_reader(input, reader):
while True:
input.seek(0)
for row in reader:
yield row
with open("total.csv", 'rb') as input1:
reader = csv.reader(input1, delimiter="\t")
for row in repeated_reader(input1, reader):
#Read the ... | I actually calculated the total number of rows in the CSV and when I was on the last row I did `input1.seek(0)`
```
row_count = sum(1 for row in csv.reader(open('total.csv')))
print row_count
row_count2 = 0
with open("total.csv", 'rb') as input1:
time.sleep(3)
input1.seek(0)
reader = csv.read... |
49,783,902 | In python, if I use a ternary operator:
```
x = a if <condition> else b
```
Is `a` executed even if `condition` is false? Or does `condition` evaluate first and then goes to either `a` or `b` depending on the result? | 2018/04/11 | [
"https://Stackoverflow.com/questions/49783902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3754760/"
] | The condition is evaluated first, if it is False, `a` is not evaluated: [documentation](https://docs.python.org/3/reference/expressions.html#conditional-expressions). | It gets evaluated depending if meets the condition. For example:
```
condition = True
print(2 if condition else 1/0)
#Output is 2
print((1/0, 2)[condition])
#ZeroDivisionError is raised
```
No matter if `1/0` raise an error, is never evaluated as the condition was True on the evaluation.
Sames happen in the other ... |
58,512,790 | I'm wanting to wrap some c++ code in python using swig, and I need to be able to use numpy.i to convert numpy arrays to vectors.
This has been quite the frustrating process, as I haven't been able to find any useful info online as to where I actually get numpy.i from.
This is what I currently have running:
numpy 1... | 2019/10/22 | [
"https://Stackoverflow.com/questions/58512790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12114274/"
] | **Problem:** The numpy.i file I copied over from the python2.7 package isn't compatible, and the compatible version isn't included in the installation package when you go through anaconda (still not sure why they'd do that).
**Answer:** Find which version of numpy you're running, then go here (<https://github.com/nump... | You should download new numpy.i file from <https://github.com/numpy/numpy/blob/master/tools/swig/numpy.i>. In this numpy.i file have no PyFile\_Check function, which python3 don't support. If you still use
`/usr/lib/python2.7/dist-packages/instant/swig/numpy.i`, your code may appear error `undefined symbol: PyFile_Chec... |
45,966,355 | I would like to write a function which performs efficiently this "strange" sort (I am sorry for this pseudocode, it seems to me to be the clearest way to introduce the problem):
```
l=[[A,B,C,...]]
while some list in l is not sorted (increasingly) do
find a non-sorted list (say A) in l
find the first two non-sorte... | 2017/08/30 | [
"https://Stackoverflow.com/questions/45966355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7871040/"
] | Here's a simple implementation that could use some improvement:
```
def strange_sort(lists_to_sort):
# reverse so pop and append can be used
lists_to_sort = lists_to_sort[::-1]
sorted_list_of_lists = []
while lists_to_sort:
l = lists_to_sort.pop()
i = 0
# l[:i] is sorted
... | Firstly you would have to implement a `while` loop which would check if all of the numbers inside of the lists are sorted. I will be using `all` which checks if all the objects inside a sequence are `True`.
```
def a_sorting_function_of_some_sort(list_to_sort):
while not all([all([number <= numbers_list[numbers_li... |
55,218,096 | Right now I am trying to write a python script which could give a binary result to check if my machine is connected to Corporate\_VPN (Connection\_Name) OR Not connected to Corporate\_VPN.
I have tried few articles and post which I could find but with no success.
Here are some:
I have tried this post: [Getting Connec... | 2019/03/18 | [
"https://Stackoverflow.com/questions/55218096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8042963/"
] | For three numbers specifically, there are two basic approaches:
* you can sort the three numbers and return the middle number from the sorted array. For this, a three-stage sorting network is generally useful. To build this, use this primitive which swaps `r0` and `r1` if `r0` is larger than `r1`, using `r3` as a temp... | What was the exact problem you encountered? Your `CMP` instruction is fine, and will set the status flags depending on the relative values of `R0` and `R1`, so you can then use a conditional branch (e.g. `BHI` or `BGT`) or one of the `IT` family of instructions that will allow you to execute other instructions conditio... |
56,744,322 | I am creating an E-commerce now when I try adding an Item into the cart it returns the error above?
It is complaining about this line of code in the view:
```
else:
order.items.add(order_item)
```
View
```
def add_to_cart(request, slug):
item = get_object_or_404(Item, slug=slug)
order_item = OrderItem.obj... | 2019/06/24 | [
"https://Stackoverflow.com/questions/56744322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10374065/"
] | The Django [**`get_or_create(..)`** [Django-doc]](https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create), does *not* return a model instance, it returns a 2-tuple with the object, and a boolean (whether it created a record or not). Or as written in the documentation:
>
> (..)
>
>
> Returns a tup... | add the below line into this. Just add 'created' as below.
```
order_item, created = OrderItem.objects.get_or_create(
item=item,
user = request.user,
ordered = False
)
``` |
45,582,838 | Is there a way to convert the string **"12345678aaaa12345678bbbbbbbb"** to **"12345678-aaaa-1234-5678-bbbbbbbb"** in python?
I am not sure on how to do it, since I need to insert "-" after elements of variable lengths say after 8th element then 4th element and so on. | 2017/08/09 | [
"https://Stackoverflow.com/questions/45582838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123705/"
] | This function inserts a char at a postion for a string:
```
def insert(char,position,string):
return string[:position] + char + string[position:]
``` | Python strings cannot be mutated. What we can do is create another string with the hyphen inserted in between, as per your wish.
Consider the string s = "12345678aaaa12345678bbbbbbbb"
Giving `s[:8] + '-' + s[8:] will give you 12345678-aaaa12345678bbbbbbbb`
You can give the hyphen as you wish by adjusting the `:` val... |
45,582,838 | Is there a way to convert the string **"12345678aaaa12345678bbbbbbbb"** to **"12345678-aaaa-1234-5678-bbbbbbbb"** in python?
I am not sure on how to do it, since I need to insert "-" after elements of variable lengths say after 8th element then 4th element and so on. | 2017/08/09 | [
"https://Stackoverflow.com/questions/45582838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123705/"
] | Python strings cannot be mutated. What we can do is create another string with the hyphen inserted in between, as per your wish.
Consider the string s = "12345678aaaa12345678bbbbbbbb"
Giving `s[:8] + '-' + s[8:] will give you 12345678-aaaa12345678bbbbbbbb`
You can give the hyphen as you wish by adjusting the `:` val... | Simplest solution:
```
str = '12345678aaaa12345678bbbbbbbb'
indexes = [8, 4, 4, 4]
i = -1
for index in indexes:
i = i + index + 1
str = str[:i] + '-' + str[i:]
print str
```
Prints: `12345678-aaaa-1234-5678-bbbbbbbb`
You are free to change `indexes` array to achieve what you want. |
45,582,838 | Is there a way to convert the string **"12345678aaaa12345678bbbbbbbb"** to **"12345678-aaaa-1234-5678-bbbbbbbb"** in python?
I am not sure on how to do it, since I need to insert "-" after elements of variable lengths say after 8th element then 4th element and so on. | 2017/08/09 | [
"https://Stackoverflow.com/questions/45582838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123705/"
] | Python strings cannot be mutated. What we can do is create another string with the hyphen inserted in between, as per your wish.
Consider the string s = "12345678aaaa12345678bbbbbbbb"
Giving `s[:8] + '-' + s[8:] will give you 12345678-aaaa12345678bbbbbbbb`
You can give the hyphen as you wish by adjusting the `:` val... | You can follow this process :
```
def insert_(str, idx):
strlist = list(str)
strlist.insert(idx, '-')
return ''.join(strlist)
str = '12345678aaaa12345678bbbbbbbb'
indexes = [8, 4, 4, 4]
resStr = ""
idx = 0
for val in indexes:
idx += val
resStr = insert_(str,idx)
str = resStr
idx += 1
print(str)
```
o... |
45,582,838 | Is there a way to convert the string **"12345678aaaa12345678bbbbbbbb"** to **"12345678-aaaa-1234-5678-bbbbbbbb"** in python?
I am not sure on how to do it, since I need to insert "-" after elements of variable lengths say after 8th element then 4th element and so on. | 2017/08/09 | [
"https://Stackoverflow.com/questions/45582838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123705/"
] | Python strings cannot be mutated. What we can do is create another string with the hyphen inserted in between, as per your wish.
Consider the string s = "12345678aaaa12345678bbbbbbbb"
Giving `s[:8] + '-' + s[8:] will give you 12345678-aaaa12345678bbbbbbbb`
You can give the hyphen as you wish by adjusting the `:` val... | This doesn't exactly create the string you want but posting it anyway.
It finds all the indexes where digit becomes alpha and vice versa.
Then it inserts "-" at these indexes.
```
a = "12345678aaaa12345678bbbbbbbb"
lst = list(a)
index = []
for ind,i in enumerate(list(a)[:-1]):
if (i.isdigit() and lst[ind+1].isa... |
45,582,838 | Is there a way to convert the string **"12345678aaaa12345678bbbbbbbb"** to **"12345678-aaaa-1234-5678-bbbbbbbb"** in python?
I am not sure on how to do it, since I need to insert "-" after elements of variable lengths say after 8th element then 4th element and so on. | 2017/08/09 | [
"https://Stackoverflow.com/questions/45582838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123705/"
] | Python strings cannot be mutated. What we can do is create another string with the hyphen inserted in between, as per your wish.
Consider the string s = "12345678aaaa12345678bbbbbbbb"
Giving `s[:8] + '-' + s[8:] will give you 12345678-aaaa12345678bbbbbbbb`
You can give the hyphen as you wish by adjusting the `:` val... | If your want do this in one time , you can like this.
str = "12345678aaaa12345678bbbbbbbb"
```
def insert(char,positions,string):
result = ""
for post in range(0, len(positions)):
print(positions[post])
if post == 0:
result += string[:positions[post]] + char
elif post == (l... |
45,582,838 | Is there a way to convert the string **"12345678aaaa12345678bbbbbbbb"** to **"12345678-aaaa-1234-5678-bbbbbbbb"** in python?
I am not sure on how to do it, since I need to insert "-" after elements of variable lengths say after 8th element then 4th element and so on. | 2017/08/09 | [
"https://Stackoverflow.com/questions/45582838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123705/"
] | This function inserts a char at a postion for a string:
```
def insert(char,position,string):
return string[:position] + char + string[position:]
``` | Simplest solution:
```
str = '12345678aaaa12345678bbbbbbbb'
indexes = [8, 4, 4, 4]
i = -1
for index in indexes:
i = i + index + 1
str = str[:i] + '-' + str[i:]
print str
```
Prints: `12345678-aaaa-1234-5678-bbbbbbbb`
You are free to change `indexes` array to achieve what you want. |
45,582,838 | Is there a way to convert the string **"12345678aaaa12345678bbbbbbbb"** to **"12345678-aaaa-1234-5678-bbbbbbbb"** in python?
I am not sure on how to do it, since I need to insert "-" after elements of variable lengths say after 8th element then 4th element and so on. | 2017/08/09 | [
"https://Stackoverflow.com/questions/45582838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123705/"
] | This function inserts a char at a postion for a string:
```
def insert(char,position,string):
return string[:position] + char + string[position:]
``` | You can follow this process :
```
def insert_(str, idx):
strlist = list(str)
strlist.insert(idx, '-')
return ''.join(strlist)
str = '12345678aaaa12345678bbbbbbbb'
indexes = [8, 4, 4, 4]
resStr = ""
idx = 0
for val in indexes:
idx += val
resStr = insert_(str,idx)
str = resStr
idx += 1
print(str)
```
o... |
45,582,838 | Is there a way to convert the string **"12345678aaaa12345678bbbbbbbb"** to **"12345678-aaaa-1234-5678-bbbbbbbb"** in python?
I am not sure on how to do it, since I need to insert "-" after elements of variable lengths say after 8th element then 4th element and so on. | 2017/08/09 | [
"https://Stackoverflow.com/questions/45582838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123705/"
] | This function inserts a char at a postion for a string:
```
def insert(char,position,string):
return string[:position] + char + string[position:]
``` | This doesn't exactly create the string you want but posting it anyway.
It finds all the indexes where digit becomes alpha and vice versa.
Then it inserts "-" at these indexes.
```
a = "12345678aaaa12345678bbbbbbbb"
lst = list(a)
index = []
for ind,i in enumerate(list(a)[:-1]):
if (i.isdigit() and lst[ind+1].isa... |
45,582,838 | Is there a way to convert the string **"12345678aaaa12345678bbbbbbbb"** to **"12345678-aaaa-1234-5678-bbbbbbbb"** in python?
I am not sure on how to do it, since I need to insert "-" after elements of variable lengths say after 8th element then 4th element and so on. | 2017/08/09 | [
"https://Stackoverflow.com/questions/45582838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123705/"
] | This function inserts a char at a postion for a string:
```
def insert(char,position,string):
return string[:position] + char + string[position:]
``` | If your want do this in one time , you can like this.
str = "12345678aaaa12345678bbbbbbbb"
```
def insert(char,positions,string):
result = ""
for post in range(0, len(positions)):
print(positions[post])
if post == 0:
result += string[:positions[post]] + char
elif post == (l... |
14,412,907 | I'm trying to scrape the [NDTV](http://en.wikipedia.org/wiki/NDTV) website for news titles. [This](http://archives.ndtv.com/articles/2012-01.html) is the page I'm using as a HTML source. I'm using BeautifulSoup (bs4) to handle the HTML code, and I've got everything working, except my code breaks when I encounter the hi... | 2013/01/19 | [
"https://Stackoverflow.com/questions/14412907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765768/"
] | What you see is a NavigableString instance (which is derived from the Python unicode type):
```
(Pdb) hypref.encode('utf-8')
'NDTV'
(Pdb) hypref.__class__
<class 'bs4.element.NavigableString'>
(Pdb) hypref.__class__.__bases__
(<type 'unicode'>, <class 'bs4.element.PageElement'>)
```
You need to convert to utf-8 usin... | ```
strhyp = hypref.encode('utf-8')
```
<http://joelonsoftware.com/articles/Unicode.html> |
29,318,565 | I am writing a raingauge precipitation calculator based in the radius of the raingauge. When I run my script, I have this error message:
```
Type de raingauge radius [cm]: 5.0
Traceback (most recent call last):
File "pluviometro.py", line 27, in <module>
area_bocal = (pi * (raio_bocal * raio_bocal)) # cm.cm
Type... | 2015/03/28 | [
"https://Stackoverflow.com/questions/29318565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/824522/"
] | As mentioned in the [docs](https://docs.python.org/3/library/functions.html#input)
>
> The function then reads a line from input, **converts it to a string** (stripping a trailing newline), and returns that
>
>
>
So you need to type cast it to `float` explicitly
```
raio_bocal = float(input("Type de raingauge r... | You need to cast to float, input returns a string in python3:
```
float(input("Type de raingauge radius [cm]:"))
```
Probably safer use a while loop with a try/except when casting input.
```
while True:
inp = input("Type de raingauge radius [cm]:")
try:
raio_bocal = float(inp)
break
except ... |
35,258,492 | I have a directory containing a certificate bundle, a Python script and a Node script. Both scripts make a GET request to the same URL and are provided with the same certificate bundle. The Python script makes the request as expected however the node script throws this error:
>
> { [Error: unable to verify the first ... | 2016/02/07 | [
"https://Stackoverflow.com/questions/35258492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1066031/"
] | The [documentation](https://nodejs.org/api/https.html#https_https_request_options_callback) describes the `ca` option as follows:
>
> **ca: A string, Buffer or array of strings or Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are use... | Maybe you can use this module that fixes the problem, by downloading certificates usually used by browsers.
<https://www.npmjs.com/package/ssl-root-cas> |
43,935,569 | my device will sent json data like this:
```
[{"channel":924125000, "sf":10, "time":"2017-05-11T16:56:15", "gwip":"192.168.1.125", "gwid":"00004c4978dbf5b4", "repeater":"00000000ffffffff", "systype":5, "rssi":-108.0, "snr":17.0, "snr_max":23.3, "snr_min":10.8, "macAddr":"00000000000000c3", "data":"47024830163312101791... | 2017/05/12 | [
"https://Stackoverflow.com/questions/43935569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8002033/"
] | because you have multiple objects in your json you should include them in a list :
```
json_List = json.loads('[' + jsonData + ']')
``` | Paste it in a Tool like [JSONLINT](https://jsonlint.com/)
and you get:
>
> Error: Parse error on line 17:
> ...": 1, "fport": 2}], [{ "channel": 924
> ---------------------^
> Expecting 'EOF', got ','
>
>
>
which is the cause of your error. This is not *valid* JSON.
The correct structure would be something li... |
5,524,241 | I have two custom Django fields, a `JSONField` and a `CompressedField`, both of which work well. I would like to also have a `CompressedJSONField`, and I was rather hoping I could do this:
```
class CompressedJSONField(JSONField, CompressedField):
pass
```
but on import I get:
```
RuntimeError: maximum recursio... | 2011/04/02 | [
"https://Stackoverflow.com/questions/5524241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88411/"
] | after doing a few quick tests i found that if you remove the **metaclass** from the JSON and compressed fields and put it in the compressedJSON field it compiles. if you then need the JSON or Compressed fields then subclass them and jusst add the `__metaclass__ = models.SubfieldBase`
i have to admit that i didn't do a... | It is hard to understand when exactly you are getting that error. But looking at DJango code, there is simlar implementation (multiple inheritance)
refer: **class ImageFieldFile(ImageFile, FieldFile)**
in django/db/models/fields |
430,226 | I need to poll a web service, in this case twitter's API, and I'm wondering what the conventional wisdom is on this topic. I'm not sure whether this is important, but I've always found feedback useful in the past.
A couple scenarios I've come up with:
1. The querying process starts every X seconds, eg a cron job runs... | 2009/01/10 | [
"https://Stackoverflow.com/questions/430226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | "Do I just run a python script that doesn't end?"
How is this unfamiliar territory?
```
import time
polling_interval = 36.0 # (100 requests in 3600 seconds)
running= True
while running:
start= time.clock()
poll_twitter()
anything_else_that_seems_important()
work_duration = time.clock() - start
tim... | You should have a page that is like a Ping or Heartbeat page. The you have another process that "tickles" or hits that page, usually you can do this in your Control Panel of your web host, or use a cron if you have a local access. Then this script can keep statistics of how often it has polled in a database or some dat... |
42,673,016 | I tried to make a checkbutton which is supposed to activate a function "rond" but it's not working... What have I done wrong ?
```
from tkinter import*
def rond():
if okok.get()==1:
print("ok")
okok = BooleanVar()
okok.set(0)
root = Tk()
can = Canvas(root, width=200, height=150, bg="light yellow")
can.bind("<Bu... | 2017/03/08 | [
"https://Stackoverflow.com/questions/42673016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7678528/"
] | There are three problems:
1. The exception you are getting is because you have to create `root = Tk()` before the `BooleanVar`.
2. As already noted, you should use the [`Checkbutton`](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/checkbutton.html) widget instead of `Canvas`. The `command` then goes directly into t... | It looks like you're using canvas and not the check button. I would try something like this:
cbutton = Checkbutton(root, etc, etc)
or check out effbot.org for a good resource. |
70,150,128 | This is my project structure
[](https://i.stack.imgur.com/BrsjM.png)
I am able to access the default SQLite database `db.sqlite3` created by Django, by importing the models directly inside of my views files
Like - `from basic.models import table1`
Now, I hav... | 2021/11/29 | [
"https://Stackoverflow.com/questions/70150128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11827709/"
] | You can specify specific database as specified in [Documentation](https://docs.djangoproject.com/en/3.2/ref/django-admin/#cmdoption-inspectdb-database)
```
python manage.py inspectdb --database=otherdb > your_app/models.py
```
Also if possible putting otherdb in a different App is better. | You can attach the second database to the first one and use it from within the first one. You can use tables from both databases in single sql query.
Here is the doc <https://www.sqlite.org/lang_attach.html>.
```
attach database '/path/to/dbfile.sqlite' as db_remote;
select *
from some_table
join db_remote.remote_ta... |
70,150,128 | This is my project structure
[](https://i.stack.imgur.com/BrsjM.png)
I am able to access the default SQLite database `db.sqlite3` created by Django, by importing the models directly inside of my views files
Like - `from basic.models import table1`
Now, I hav... | 2021/11/29 | [
"https://Stackoverflow.com/questions/70150128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11827709/"
] | You can specify specific database as specified in [Documentation](https://docs.djangoproject.com/en/3.2/ref/django-admin/#cmdoption-inspectdb-database)
```
python manage.py inspectdb --database=otherdb > your_app/models.py
```
Also if possible putting otherdb in a different App is better. | @sevdimali's answer works fine to create the new models from an existing database
Once that is done you need to use the command -
`python manage.py makemigrations`
To add the changes to the migrations folder
Then use the command
`python manage.py migrate --fake-initial`
To add the new changes to your database
**... |
6,282,519 | I'm not sure if I'm even asking this question correctly. I just built my first real program and I want to make it available to people in my office. I'm not sure if I will have access to the shared server, but I was hoping I could simply package the program (I hope I'm using this term correctly) and upload it to a websi... | 2011/06/08 | [
"https://Stackoverflow.com/questions/6282519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1382299/"
] | [PyInstaller](http://www.pyinstaller.org/) or [py2exe](http://www.py2exe.org/) can package your Python program.
Both are actively maintained. PyInstaller is actively maintained. py2exe has not been updated for at least a year. I've used each with success.
Also there is [cx\_Freeze](http://cx-freeze.sourceforge.net/... | Take a look at <http://www.py2exe.org/> |
63,890,399 | I am working with a dataframe which looks similar to this
```
Ind Pos Sample Ct LogConc RelConc
1 B1 wt1A 26.93 -2.0247878 0.009445223
2 B2 wt1A 27.14 -2.0960951 0.008015026
3 B3 wt1B 26.76 -1.9670628 0.010787907
4 B4 wt1B 26.94 -2.0281834 0.009371662
5 B5 wt1C 26.01... | 2020/09/14 | [
"https://Stackoverflow.com/questions/63890399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11637268/"
] | In `base R`, we can use `ave` and it is very fast
```
df1$AverageRelConc <- with(df1, ave(RelConc, Sample))
```
-output
```
df1$AverageRelConc
#[1] 0.008730125 0.008730125 0.010079784 0.010079784 0.018874878 0.018874878 0.024430844 0.024430844 0.393766166 0.393766166
#[11] 0.396856943 0.396856943
```
---
Or usin... | Try this `tidyverse` option:
```
library(tidyverse)
#Code
df %>% group_by(Sample) %>%
mutate(AvgRelConc=mean(RelConc,na.rm=T))
```
Output:
```
# A tibble: 12 x 7
# Groups: Sample [6]
Ind Pos Sample Ct LogConc RelConc AvgRelConc
<int> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 1 B1 wt1A... |
4,666,527 | Does anyone have some good resources on learning more advanced regular expressions
I keep having problems where I want to make sure something is not enclosed in quotation marks
i.e. I am trying to make an expression that will match lines in a python file containing an equality, i.e.
```
a = 4
```
which is easy eno... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4666527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392485/"
] | Parsing code with regular expressions is generally not a good idea, as the grammar of a programming language is not a regular language. I'm not much of a python programmer, but I think you would be a lot better off parsing python code with python modules such as [this one](http://docs.python.org/library/parser.html) or... | Python has an excellent [Language Reference](http://docs.python.org/reference/index.html) that also includes [descriptions of the lexical analysis and syntax](http://docs.python.org/reference/introduction.html#notation).
In your case both statements are [assignments](http://docs.python.org/reference/simple_stmts.html#... |
4,666,527 | Does anyone have some good resources on learning more advanced regular expressions
I keep having problems where I want to make sure something is not enclosed in quotation marks
i.e. I am trying to make an expression that will match lines in a python file containing an equality, i.e.
```
a = 4
```
which is easy eno... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4666527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392485/"
] | A think that you have to tokenize the expression for correct evaluation but you can detect the pattern using the following regex
```
r'\s+(\w+)(\s*,\s*\w+)*\s*=\s*(.*?)(\s*,\s*.*?)*'
```
If group(2) and group(4) are not empty you have to tokenize the expression
Note that if you have
a,b = f(b,a), g(a,b)
It is ha... | Python has an excellent [Language Reference](http://docs.python.org/reference/index.html) that also includes [descriptions of the lexical analysis and syntax](http://docs.python.org/reference/introduction.html#notation).
In your case both statements are [assignments](http://docs.python.org/reference/simple_stmts.html#... |
55,338,811 | I'm currently working on a small project to learn python. This project creates a random forest, then sets the forest up on fire to stimulate a forest fire. So I managed to create the forest out using a function. The forest is just an array of 0s and 1s. 0 to represent water, 1 to present a tree.
So now I'm currently r... | 2019/03/25 | [
"https://Stackoverflow.com/questions/55338811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11255128/"
] | use not exists
```
select mygroup from table_name t1
where not exists( select 1 from table_name t2 where t1.var2=t2.var1
and t1.mygroup=t2.mygroup)
and t1.var2 is not null
``` | Another approach to use cte and temptables:
1. Find out the var2 values that is not included in var1 for the same mygroup
2. List the mygroups and group them there var2 in the list you have found in step 1.
Try below:
```
create table #temp (mygroup int, var1 int, var2 int)
insert into #temp values
(1 , 1, ... |
59,289,903 | Please help me make sense of this big fat error output. At this point I don't know which end is up. I have been spinning my wheels for days on this.
This is **not** the first/only package installation that has given me these errors, but the project ran fine anyway, so I ignored it. Now I want a new package, and it wo... | 2019/12/11 | [
"https://Stackoverflow.com/questions/59289903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9068961/"
] | I don't know *why* this worked, but running a regular yarn-upgrade cleared the errors. I still got warnings about dependencies.
I should have saved the terminal output from yarn-outdated before and after the upgrade, but alas, I did not.
I still show a few mismatched dependencies. | deasync try´s to compile itself if it did not find a precompiled version for current Node version.
This compilation has additional requirements so it is easier to use deasync/Node combinations where precompiled packages exists:
* <https://github.com/abbr/deasync/issues/106>
* <https://github.com/abbr/deasync-bin> |
64,870,829 | Let's say I have a list
`list = ['aa', 'bb', 'aa', 'aaa', 'bbb', 'bbbb', 'cc']`
if you do `list.sort()`
you get back
`['aa', 'aa', 'aaa', 'bb', 'bbb', 'bbbb', 'cc']`
Is there a way in **python 3** we can get
`['aaa', 'aa', 'aa', 'bbbb', 'bbb', 'bb', 'cc']`
So within the same lexicographical group order, pick th... | 2020/11/17 | [
"https://Stackoverflow.com/questions/64870829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10688867/"
] | You can redefine what less-than means for the strings with a custom class. Use that class as the key for `list.sort` or `sorted`.
```
class C:
def __init__(self, val):
self.val = val
def __lt__(self, other):
min_len = min((len(self.val), len(other.val)))
if self.val[:min_len] == other... | Tuples are ordered lexicographically, so you can use a tuple of (first character of string, negative length) as the sort key:
```python
list.sort(key=lambda s: (s[0], -len(s)))
``` |
64,870,829 | Let's say I have a list
`list = ['aa', 'bb', 'aa', 'aaa', 'bbb', 'bbbb', 'cc']`
if you do `list.sort()`
you get back
`['aa', 'aa', 'aaa', 'bb', 'bbb', 'bbbb', 'cc']`
Is there a way in **python 3** we can get
`['aaa', 'aa', 'aa', 'bbbb', 'bbb', 'bb', 'cc']`
So within the same lexicographical group order, pick th... | 2020/11/17 | [
"https://Stackoverflow.com/questions/64870829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10688867/"
] | You can redefine what less-than means for the strings with a custom class. Use that class as the key for `list.sort` or `sorted`.
```
class C:
def __init__(self, val):
self.val = val
def __lt__(self, other):
min_len = min((len(self.val), len(other.val)))
if self.val[:min_len] == other... | You were able to explain in words how to compare two strings, so you can write this comparison function in python. However, since python 3, `.sort()` and `sorted()` both expect a **`key`**, rather than a comparison function.
* You can turn the comparison function into a key by using a class and defining its method `._... |
36,590,496 | ```
#!/usr/bin/python
import requests
import uuid
random_uuid = uuid.uuid4()
print random_uuid
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials"
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "random_uuid",
"usern... | 2016/04/13 | [
"https://Stackoverflow.com/questions/36590496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6133947/"
] | You'll can use string formatting for that.
In your JSON string, replace random\_uuid with %s, than do:
```
payload = payload % random_uuid
```
Another option is to use `json.dumps` to create the json:
```
payload_dict = {
'id': random_uuid,
...
}
payload = json.dumps(payload_dict)
``` | This code may help.
```
#!/usr/bin/python
import requests
import uuid
random_uuid = uuid.uuid4()
print random_uuid
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials"
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "%s",
... |
36,590,496 | ```
#!/usr/bin/python
import requests
import uuid
random_uuid = uuid.uuid4()
print random_uuid
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials"
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "random_uuid",
"usern... | 2016/04/13 | [
"https://Stackoverflow.com/questions/36590496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6133947/"
] | You'll can use string formatting for that.
In your JSON string, replace random\_uuid with %s, than do:
```
payload = payload % random_uuid
```
Another option is to use `json.dumps` to create the json:
```
payload_dict = {
'id': random_uuid,
...
}
payload = json.dumps(payload_dict)
``` | Use `str.format` instead:
```
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "{0}",
"username": "testuser3",
"password": "bar",
"description": "biz",
"$class": "com.cloudbees.plugins.credentials.impl.Usernam... |
36,590,496 | ```
#!/usr/bin/python
import requests
import uuid
random_uuid = uuid.uuid4()
print random_uuid
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials"
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "random_uuid",
"usern... | 2016/04/13 | [
"https://Stackoverflow.com/questions/36590496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6133947/"
] | You'll can use string formatting for that.
In your JSON string, replace random\_uuid with %s, than do:
```
payload = payload % random_uuid
```
Another option is to use `json.dumps` to create the json:
```
payload_dict = {
'id': random_uuid,
...
}
payload = json.dumps(payload_dict)
``` | You could use direct JSON entry into a `dict`:
`payload = {
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": random_uuid,
"username": "testuser3",
"password": "bar",
"description": "biz",
"$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
}
}` |
36,590,496 | ```
#!/usr/bin/python
import requests
import uuid
random_uuid = uuid.uuid4()
print random_uuid
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials"
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "random_uuid",
"usern... | 2016/04/13 | [
"https://Stackoverflow.com/questions/36590496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6133947/"
] | Use `str.format` instead:
```
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "{0}",
"username": "testuser3",
"password": "bar",
"description": "biz",
"$class": "com.cloudbees.plugins.credentials.impl.Usernam... | This code may help.
```
#!/usr/bin/python
import requests
import uuid
random_uuid = uuid.uuid4()
print random_uuid
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials"
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "%s",
... |
36,590,496 | ```
#!/usr/bin/python
import requests
import uuid
random_uuid = uuid.uuid4()
print random_uuid
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials"
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "random_uuid",
"usern... | 2016/04/13 | [
"https://Stackoverflow.com/questions/36590496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6133947/"
] | You could use direct JSON entry into a `dict`:
`payload = {
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": random_uuid,
"username": "testuser3",
"password": "bar",
"description": "biz",
"$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
}
}` | This code may help.
```
#!/usr/bin/python
import requests
import uuid
random_uuid = uuid.uuid4()
print random_uuid
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials"
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "%s",
... |
23,414,509 | I have common problem. I have some data and I want search in them. My issue is, that I dont know a proper data structures and algorhitm suitable for this situation.
There are two kind of objects - `Process` and `Package`. Both have some properties, but they are only data structures (dont have any methods). Next, there... | 2014/05/01 | [
"https://Stackoverflow.com/questions/23414509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3285282/"
] | I would move the case into its own method on your Team model.
```
class Team
def tree(type)
...
end
end
```
Then in your controller you could just have the following
```
if @team = fetch_team
@output = @team.tree(params[:tree])
render json: @output
else
render json: {message: "team: '#{params[:id]}' ... | You could write
```
if @team = fetch_team
@output = case params[:tree]
when 'parents' then @team.ancestor_ids
when 'children' then @team.child_ids
when 'full' then @team.full_tree
when nil then @team
else {message: "requested query parameter: '#{params[:tre... |
42,471,570 | I am trying to build a classification model. I have 1000 text documents in local folder. I want to divide them into training set and test set with a split ratio of 70:30(70 -> Training and 30 -> Test) What is the better approach to do so? I am using python.
---
I wanted a approach programatically to split the trainin... | 2017/02/26 | [
"https://Stackoverflow.com/questions/42471570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5024829/"
] | that's quite simple if you use numpy, first load the documents and make them a numpy array, and then:
```
import numpy as np
docs = np.array([
'one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine', 'ten',
])
idx = np.hstack((np.ones(7), np.zeros(3))) # generate indices
np.random.shuffle(... | Just make a list of the filenames using `os.listdir()`. Use `collections.shuffle()` to shuffle the list, and then `training_files = filenames[:700]` and `testing_files = filenames[700:]` |
42,471,570 | I am trying to build a classification model. I have 1000 text documents in local folder. I want to divide them into training set and test set with a split ratio of 70:30(70 -> Training and 30 -> Test) What is the better approach to do so? I am using python.
---
I wanted a approach programatically to split the trainin... | 2017/02/26 | [
"https://Stackoverflow.com/questions/42471570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5024829/"
] | Not sure *exactly* what you're after, so I'll try to be comprehensive. There will be a few steps:
1. Get a list of the files
2. Randomize the files
3. Split files into training and testing sets
4. Do the thing
1. Get a list of the files
==========================
Let's assume that your files all have the extension `... | Just make a list of the filenames using `os.listdir()`. Use `collections.shuffle()` to shuffle the list, and then `training_files = filenames[:700]` and `testing_files = filenames[700:]` |
42,471,570 | I am trying to build a classification model. I have 1000 text documents in local folder. I want to divide them into training set and test set with a split ratio of 70:30(70 -> Training and 30 -> Test) What is the better approach to do so? I am using python.
---
I wanted a approach programatically to split the trainin... | 2017/02/26 | [
"https://Stackoverflow.com/questions/42471570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5024829/"
] | Not sure *exactly* what you're after, so I'll try to be comprehensive. There will be a few steps:
1. Get a list of the files
2. Randomize the files
3. Split files into training and testing sets
4. Do the thing
1. Get a list of the files
==========================
Let's assume that your files all have the extension `... | that's quite simple if you use numpy, first load the documents and make them a numpy array, and then:
```
import numpy as np
docs = np.array([
'one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine', 'ten',
])
idx = np.hstack((np.ones(7), np.zeros(3))) # generate indices
np.random.shuffle(... |
42,471,570 | I am trying to build a classification model. I have 1000 text documents in local folder. I want to divide them into training set and test set with a split ratio of 70:30(70 -> Training and 30 -> Test) What is the better approach to do so? I am using python.
---
I wanted a approach programatically to split the trainin... | 2017/02/26 | [
"https://Stackoverflow.com/questions/42471570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5024829/"
] | that's quite simple if you use numpy, first load the documents and make them a numpy array, and then:
```
import numpy as np
docs = np.array([
'one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine', 'ten',
])
idx = np.hstack((np.ones(7), np.zeros(3))) # generate indices
np.random.shuffle(... | You can use train\_test\_split method provided by sklearn. See documentation here:
<http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html> |
42,471,570 | I am trying to build a classification model. I have 1000 text documents in local folder. I want to divide them into training set and test set with a split ratio of 70:30(70 -> Training and 30 -> Test) What is the better approach to do so? I am using python.
---
I wanted a approach programatically to split the trainin... | 2017/02/26 | [
"https://Stackoverflow.com/questions/42471570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5024829/"
] | Not sure *exactly* what you're after, so I'll try to be comprehensive. There will be a few steps:
1. Get a list of the files
2. Randomize the files
3. Split files into training and testing sets
4. Do the thing
1. Get a list of the files
==========================
Let's assume that your files all have the extension `... | You can use train\_test\_split method provided by sklearn. See documentation here:
<http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html> |
39,516,760 | I have a string that I pull from a REST API that is actually a JSON.
I can't use `req.json()` as python doesn't format json correctly i.e. it is using single quotes and not double quotes, plus it puts a unicode symbol where there shouldn't be one. This means I can't use it to respond back to REST as the JSON is not f... | 2016/09/15 | [
"https://Stackoverflow.com/questions/39516760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164102/"
] | You can check if a string is valid json by catching the error.
```
import json
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
```
Test cases:
```
print is_json("{}") #prints True
print is_json("{asdf}") ... | ```
import json
request_as_json = json.loads(r.text)
```
Then you can call things like `request_as_json['key']`
["More Info Here"](http://docs.python.org/library/json.html#json.loads) |
39,516,760 | I have a string that I pull from a REST API that is actually a JSON.
I can't use `req.json()` as python doesn't format json correctly i.e. it is using single quotes and not double quotes, plus it puts a unicode symbol where there shouldn't be one. This means I can't use it to respond back to REST as the JSON is not f... | 2016/09/15 | [
"https://Stackoverflow.com/questions/39516760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164102/"
] | You can check if a string is valid json by catching the error.
```
import json
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
```
Test cases:
```
print is_json("{}") #prints True
print is_json("{asdf}") ... | If you need to access the data in the JSON message, `req.json()` already does what you need. It parses the JSON message into a Python data structure, generally some nested format of lists and dicts. The result doesn't look like valid JSON text because it's not JSON any more; it's a data structure you can actually index... |
56,590,075 | I'm trying to read a timeseries of a single [WRF](https://www.mmm.ucar.edu/weather-research-and-forecasting-model) output variable. The time series is distributed, one timestamp per file, across more than 5000 netCDF files. Each file contains roughly 200 variables.
Is there a way to call xarray.open\_mfdataset() for o... | 2019/06/14 | [
"https://Stackoverflow.com/questions/56590075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1854821/"
] | I'm not sure why providing the `data_vars=` argument still reads all data - I experienced the same issue reading WRF output. My workaround was to make a list of all the variables I didn't need (all 200+) and feed that to the `drop_variables=` argument. You can get a list of all variables and then just delete or comment... | As a follow up for the ones who will find this thread later.
Based on the documentation (but a bit hidden), the "data\_vars=" argument only works with Python 3.9. |
56,590,075 | I'm trying to read a timeseries of a single [WRF](https://www.mmm.ucar.edu/weather-research-and-forecasting-model) output variable. The time series is distributed, one timestamp per file, across more than 5000 netCDF files. Each file contains roughly 200 variables.
Is there a way to call xarray.open\_mfdataset() for o... | 2019/06/14 | [
"https://Stackoverflow.com/questions/56590075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1854821/"
] | I'm not sure why providing the `data_vars=` argument still reads all data - I experienced the same issue reading WRF output. My workaround was to make a list of all the variables I didn't need (all 200+) and feed that to the `drop_variables=` argument. You can get a list of all variables and then just delete or comment... | Another option is to define a preprocessing function that defines the variables to keep via the "preprocess" keyword argument, e.g.:
```
preprocess=lambda ds: ds[variablelist]
``` |
56,590,075 | I'm trying to read a timeseries of a single [WRF](https://www.mmm.ucar.edu/weather-research-and-forecasting-model) output variable. The time series is distributed, one timestamp per file, across more than 5000 netCDF files. Each file contains roughly 200 variables.
Is there a way to call xarray.open\_mfdataset() for o... | 2019/06/14 | [
"https://Stackoverflow.com/questions/56590075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1854821/"
] | Another option is to define a preprocessing function that defines the variables to keep via the "preprocess" keyword argument, e.g.:
```
preprocess=lambda ds: ds[variablelist]
``` | As a follow up for the ones who will find this thread later.
Based on the documentation (but a bit hidden), the "data\_vars=" argument only works with Python 3.9. |
9,197,385 | I'm using AWS for the first time and have just installed boto for python. I'm stuck at the step where it advices to:
"You can place this file either at /etc/boto.cfg for system-wide use or in the home directory of the user executing the commands as ~/.boto."
Honestly, I have no idea what to do. First, I can't find th... | 2012/02/08 | [
"https://Stackoverflow.com/questions/9197385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815878/"
] | >
> "You can place this file either at /etc/boto.cfg for system-wide use
> or in the home directory of the user executing the commands as
> ~/.boto."
>
>
>
The former simply means that you might create a configuration file named `boto.cfg` within directory `/etc` (i.e. it won't necessarily be there already, depe... | For those who want to configure the credentials in Windows:
1-Create your file with the name you want(e.g boto\_config.cfg) and place it in a location of your choice(e.g C:\Users\\configs).
2- Create an environment variable with the Name='BOTO\_CONFIG' and Value= file\_location/file\_name
3- Boto is now ready to wor... |
9,197,385 | I'm using AWS for the first time and have just installed boto for python. I'm stuck at the step where it advices to:
"You can place this file either at /etc/boto.cfg for system-wide use or in the home directory of the user executing the commands as ~/.boto."
Honestly, I have no idea what to do. First, I can't find th... | 2012/02/08 | [
"https://Stackoverflow.com/questions/9197385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815878/"
] | >
> "You can place this file either at /etc/boto.cfg for system-wide use
> or in the home directory of the user executing the commands as
> ~/.boto."
>
>
>
The former simply means that you might create a configuration file named `boto.cfg` within directory `/etc` (i.e. it won't necessarily be there already, depe... | For anyone looking for information on the now-current `boto3`, it does not use a separate configuration file but rather respects the default one created by the aws cli when running `aws configure` (Ie, it will look at `~/.aws/config`) |
45,382,917 | I cannot successfully run the `optimize_for_inference` module on a simple, saved TensorFlow graph (Python 2.7; package installed by `pip install tensorflow-gpu==1.0.1`).
Background
==========
Saving TensorFlow Graph
-----------------------
Here's my Python script to generate and save a simple graph to add 5 to my in... | 2017/07/28 | [
"https://Stackoverflow.com/questions/45382917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5874320/"
] | **Here is the detailed guide on how to optimize for inference:**
The `optimize_for_inference` module takes a `frozen binary GraphDef` file as input and outputs the `optimized Graph Def` file which you can use for inference. And to get the `frozen binary GraphDef file` you need to use the module `freeze_graph` which ta... | 1. You are doing it wrong: `input` is a graphdef file for the [script](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/optimize_for_inference.py) not the data part of the checkpoint. You need to freeze the model to a `.pb` file/ or get the prototxt for graph and use the optimize for inferen... |
309,135 | I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit.
I need Pros and Cons for Python development between this two editors... | 2008/11/21 | [
"https://Stackoverflow.com/questions/309135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35425/"
] | I use both Komodo Edit and Notepad++.
Notepad++ is a lot quicker to launch and it's more lightweight, so I often use it for quick one-off editing.
I use Komodo Edit for major projects, like my django and wxPython applications. KE is a full-featured IDE, so it has a lot more features.
Main advantages of Komodo Edit ... | I haven't used Komodo yet (the download never quite finished on the slow connection I was on at the time), but I use Eclipse with PyDev regularly and enjoy the "IDE" features described by the other respondents. However, I'm also regularly frustrated by how much of a resource hog it is.
I downloaded Notepad++ recently ... |
309,135 | I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit.
I need Pros and Cons for Python development between this two editors... | 2008/11/21 | [
"https://Stackoverflow.com/questions/309135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35425/"
] | I have worked a bit with Python programming for Google App Engine, which I started out in Notepad++ and then recently shifted over to Komodo using two excellent startup tutorials - both of which are conveniently linked from [this blog post](http://blogs.activestate.com/2008/04/komodo-does-it "Komodo does it all: Google... | Downloaded both myself. Like Komodo better.
Komodo Pros: Like it better. Does more. Looks like an IDE. Edits Django templates
Notepad++ Cons: Don't like it as much. Does less. Looks less like and IDE. |
309,135 | I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit.
I need Pros and Cons for Python development between this two editors... | 2008/11/21 | [
"https://Stackoverflow.com/questions/309135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35425/"
] | As far as I know , Notepad++ doesn't show you the docstring each method has . | If I had to choose between Notepad++ and Komodo i would choose PyScripter ;.)
Seriously I consider PyScripter as a great alternative... |
309,135 | I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit.
I need Pros and Cons for Python development between this two editors... | 2008/11/21 | [
"https://Stackoverflow.com/questions/309135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35425/"
] | I use Komodo edit. The main reasons are: Intellisense (not as good as VisualStudio, but Python's a hard language to do intellisense for) and cross-platform compatibility. It's nice being able to use the same editor on my Windows machine, my linux machine, and my macbook with little to no change in feel. | A downside I found of Notepad++ for Python is that it tends (for me) to silently mix tabs and spaces. I know this is configurable, but it caught me out, especially when trying to work with other people using different editors / IDE's, so take care. |
309,135 | I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit.
I need Pros and Cons for Python development between this two editors... | 2008/11/21 | [
"https://Stackoverflow.com/questions/309135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35425/"
] | I just downloaded and started using Komodo Edit. I've been using Notepad++ for awhile. Here is what I think about some of the features:
Komodo Edit Pros:
* You can jump to a function definition, even if it's in another file (I love this)
* There is a plugin that displays the list of classes, functions and such for th... | If I had to choose between Notepad++ and Komodo i would choose PyScripter ;.)
Seriously I consider PyScripter as a great alternative... |
309,135 | I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit.
I need Pros and Cons for Python development between this two editors... | 2008/11/21 | [
"https://Stackoverflow.com/questions/309135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35425/"
] | As far as I know , Notepad++ doesn't show you the docstring each method has . | Downloaded both myself. Like Komodo better.
Komodo Pros: Like it better. Does more. Looks like an IDE. Edits Django templates
Notepad++ Cons: Don't like it as much. Does less. Looks less like and IDE. |
309,135 | I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit.
I need Pros and Cons for Python development between this two editors... | 2008/11/21 | [
"https://Stackoverflow.com/questions/309135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35425/"
] | I use Komodo edit. The main reasons are: Intellisense (not as good as VisualStudio, but Python's a hard language to do intellisense for) and cross-platform compatibility. It's nice being able to use the same editor on my Windows machine, my linux machine, and my macbook with little to no change in feel. | I haven't used Komodo yet (the download never quite finished on the slow connection I was on at the time), but I use Eclipse with PyDev regularly and enjoy the "IDE" features described by the other respondents. However, I'm also regularly frustrated by how much of a resource hog it is.
I downloaded Notepad++ recently ... |
309,135 | I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit.
I need Pros and Cons for Python development between this two editors... | 2008/11/21 | [
"https://Stackoverflow.com/questions/309135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35425/"
] | I have worked a bit with Python programming for Google App Engine, which I started out in Notepad++ and then recently shifted over to Komodo using two excellent startup tutorials - both of which are conveniently linked from [this blog post](http://blogs.activestate.com/2008/04/komodo-does-it "Komodo does it all: Google... | If I had to choose between Notepad++ and Komodo i would choose PyScripter ;.)
Seriously I consider PyScripter as a great alternative... |
309,135 | I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit.
I need Pros and Cons for Python development between this two editors... | 2008/11/21 | [
"https://Stackoverflow.com/questions/309135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35425/"
] | I have worked a bit with Python programming for Google App Engine, which I started out in Notepad++ and then recently shifted over to Komodo using two excellent startup tutorials - both of which are conveniently linked from [this blog post](http://blogs.activestate.com/2008/04/komodo-does-it "Komodo does it all: Google... | A downside I found of Notepad++ for Python is that it tends (for me) to silently mix tabs and spaces. I know this is configurable, but it caught me out, especially when trying to work with other people using different editors / IDE's, so take care. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.