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 |
|---|---|---|---|---|---|
59,433,681 | I have the following data in terms of dataframe
```
data = pd.DataFrame({'colA': ['a', 'c', 'a', 'e', 'c', 'c'], 'colB': ['b', 'd', 'b', 'f', 'd', 'd'], 'colC':['SD100', 'SD200', 'SD300', 'SD400', 'SD500', 'SD600']})
```
I want the output as attached
[enter image description here][2]
I want to achieve this using pa... | 2019/12/21 | [
"https://Stackoverflow.com/questions/59433681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12054665/"
] | I don't know why you want to make multindex, but you can simply `sort_values` or use `groupby`.
```py
import pandas as pd
df = pd.DataFrame({"ColumnA":['a','c','a','e','c','c'],
"ColumnB":['b','d','b','f','d','d'],
"ColumnC":['SD100','SD200','SD300','SD400','SD500','SD600']})
print(df... | This will update your data into what you wished
`data=data.groupby(['colA','colB']).agg(list)` |
10,308,639 | I want to install the newest version of `numpy` (a numerical library for Python), and the version (v1.6.1) is not yet in the [Ubuntu Oneiric repositories](https://launchpad.net/ubuntu/oneiric/+source/python-numpy). When I went ahead to manually install it, I read in the [INSTALL](https://github.com/numpy/numpy/blob/mas... | 2012/04/25 | [
"https://Stackoverflow.com/questions/10308639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781938/"
] | From the same `INSTALL` file you referenced...
```
How to check the ABI of blas/lapack/atlas
-----------------------------------------
One relatively simple and reliable way to check for the compiler used to build
a library is to use ldd on the library. If libg2c.so is a dependency, this
means that g77 has been used.... | I know of no easy way, though you may find `readelf -a /usr/lib/$SHARED_OBJECT` illuminating, where `$SHARED_OBJECT` is something like `/usr/lib/atlas-base/liblapack_atlas.so.3gf.0` (you'll have to look in your `/usr/lib` to see what your exact filename is).
However, there is another, quite different way to get inform... |
69,102,556 | I'm having troubles with grouping my list
so let's say I have this:
```
data = [
{'records-0': '1'}, {'records-0-item1': '2'}, {'records-0-item2': '3'},{'records-0-item3': '4'},
{'records-1': '1'}, {'records-1-item1': '2'}, {'records-1-item2': '3'},
]
```
What I'm trying to have is my list sorted based on the index... | 2021/09/08 | [
"https://Stackoverflow.com/questions/69102556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11868566/"
] | One way is to use [default\_dict](https://docs.python.org/3/library/collections.html#collections.defaultdict).
First, just define a helper method to get the key from the string:
```
def get_key_from(string):
return int(string.split('-')[1])
```
Then
```
from collections import defaultdict
sortedData_res = def... | I suggest you reformat your sortedData and remove lists. You could gather your data only into dict.
*Edited* example: (should work as is)
```py
def sort_data(l_: list):
d_ = dict()
for d in l_:
for k, v in d.items():
i = re.split('-', k)[1]
if not d_.get(int(i)):
... |
24,946,479 | Are most functions for http requests synchronous by default?
I came from Javascript and usage of AJAX and just started working with http requests in Python. To my surprise, it seems as though http request functions by default are synchronous, so I do not need to deal with any asynchronous behavior. For example, I'm w... | 2014/07/25 | [
"https://Stackoverflow.com/questions/24946479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502780/"
] | It's the language, in python most apis are synchronous by default, and the async version is usually an "advanced" topic. If you were using nodejs, they would be async; even if using javascript, the reason ajax is asynchronous is because of the nature of the browser. | `requests` is completely synchronous/blocking. [`grequests`](https://github.com/kennethreitz/grequests) is what you are looking for:
>
> GRequests allows you to use Requests with Gevent to make asynchronous
> HTTP Requests easily.
>
>
>
See also:
* [Asynchronous Requests with Python requests](https://stackoverf... |
40,981,120 | I have installed python 3.5, and need to install pywin (pywin32)
however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully
```
Could not find a version that satisfies the requirement pywin32 (from versions: )
```
A few possibly relevant data points:
* new install of pytho... | 2016/12/05 | [
"https://Stackoverflow.com/questions/40981120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309433/"
] | I think you could use `pip install pypiwin32` instead. | If you are using a Python 3.5+ then you could add pypiwin32==223 to your requirements.txt file instead of pywin32 |
40,981,120 | I have installed python 3.5, and need to install pywin (pywin32)
however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully
```
Could not find a version that satisfies the requirement pywin32 (from versions: )
```
A few possibly relevant data points:
* new install of pytho... | 2016/12/05 | [
"https://Stackoverflow.com/questions/40981120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309433/"
] | I think you need to use [pypiwin32](https://pypi.python.org/pypi/pypiwin32) instead. See [How do you install pywin32 from a binary file in tox on Windows?](https://stackoverflow.com/questions/26639947/how-do-you-install-pywin32-from-a-binary-file-in-tox-on-windows) | I think you could use `pip install pypiwin32` instead. |
40,981,120 | I have installed python 3.5, and need to install pywin (pywin32)
however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully
```
Could not find a version that satisfies the requirement pywin32 (from versions: )
```
A few possibly relevant data points:
* new install of pytho... | 2016/12/05 | [
"https://Stackoverflow.com/questions/40981120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309433/"
] | I think you need to use [pypiwin32](https://pypi.python.org/pypi/pypiwin32) instead. See [How do you install pywin32 from a binary file in tox on Windows?](https://stackoverflow.com/questions/26639947/how-do-you-install-pywin32-from-a-binary-file-in-tox-on-windows) | The pypi index mentions that pywin32 is not supported for python 3.5, only till python 3.3. <https://pypi.python.org/pypi/pywin32>. Which is why you are getting the error.
However, you can install it from here as a binary package. It should work. I have used xlwings with pyton 3.6.2, which requires pywin32. Pywin32 bu... |
40,981,120 | I have installed python 3.5, and need to install pywin (pywin32)
however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully
```
Could not find a version that satisfies the requirement pywin32 (from versions: )
```
A few possibly relevant data points:
* new install of pytho... | 2016/12/05 | [
"https://Stackoverflow.com/questions/40981120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309433/"
] | I think you need to use [pypiwin32](https://pypi.python.org/pypi/pypiwin32) instead. See [How do you install pywin32 from a binary file in tox on Windows?](https://stackoverflow.com/questions/26639947/how-do-you-install-pywin32-from-a-binary-file-in-tox-on-windows) | If you are using a Python 3.5+ then you could add pypiwin32==223 to your requirements.txt file instead of pywin32 |
40,981,120 | I have installed python 3.5, and need to install pywin (pywin32)
however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully
```
Could not find a version that satisfies the requirement pywin32 (from versions: )
```
A few possibly relevant data points:
* new install of pytho... | 2016/12/05 | [
"https://Stackoverflow.com/questions/40981120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309433/"
] | I think you could use `pip install pypiwin32` instead. | The pypi index mentions that pywin32 is not supported for python 3.5, only till python 3.3. <https://pypi.python.org/pypi/pywin32>. Which is why you are getting the error.
However, you can install it from here as a binary package. It should work. I have used xlwings with pyton 3.6.2, which requires pywin32. Pywin32 bu... |
40,981,120 | I have installed python 3.5, and need to install pywin (pywin32)
however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully
```
Could not find a version that satisfies the requirement pywin32 (from versions: )
```
A few possibly relevant data points:
* new install of pytho... | 2016/12/05 | [
"https://Stackoverflow.com/questions/40981120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309433/"
] | If you are using a Python 3.5+ then you could add pypiwin32==223 to your requirements.txt file instead of pywin32 | If anyone still looking for pywin32 for python34, here is the link.
Download and install. This resolves the issue
<https://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/> |
40,981,120 | I have installed python 3.5, and need to install pywin (pywin32)
however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully
```
Could not find a version that satisfies the requirement pywin32 (from versions: )
```
A few possibly relevant data points:
* new install of pytho... | 2016/12/05 | [
"https://Stackoverflow.com/questions/40981120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309433/"
] | If you are using a Python 3.5+ then you could add pypiwin32==223 to your requirements.txt file instead of pywin32 | I have seen this thread referenced by people who were seeing the same pip error message on Linux or other systems -- even though the title clearly specifies "(on windows)".
For users of Linux, Unix, MacOS, etc., let me make it perfectly clear that pywin32 is a wrapper for Windows system calls, and only works on Window... |
40,981,120 | I have installed python 3.5, and need to install pywin (pywin32)
however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully
```
Could not find a version that satisfies the requirement pywin32 (from versions: )
```
A few possibly relevant data points:
* new install of pytho... | 2016/12/05 | [
"https://Stackoverflow.com/questions/40981120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309433/"
] | I think you need to use [pypiwin32](https://pypi.python.org/pypi/pypiwin32) instead. See [How do you install pywin32 from a binary file in tox on Windows?](https://stackoverflow.com/questions/26639947/how-do-you-install-pywin32-from-a-binary-file-in-tox-on-windows) | If anyone still looking for pywin32 for python34, here is the link.
Download and install. This resolves the issue
<https://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/> |
40,981,120 | I have installed python 3.5, and need to install pywin (pywin32)
however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully
```
Could not find a version that satisfies the requirement pywin32 (from versions: )
```
A few possibly relevant data points:
* new install of pytho... | 2016/12/05 | [
"https://Stackoverflow.com/questions/40981120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309433/"
] | I think you could use `pip install pypiwin32` instead. | If anyone still looking for pywin32 for python34, here is the link.
Download and install. This resolves the issue
<https://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/> |
40,981,120 | I have installed python 3.5, and need to install pywin (pywin32)
however, pip cannot find it. Note, i have just PIP install'ed send2trash and gitpython successfully
```
Could not find a version that satisfies the requirement pywin32 (from versions: )
```
A few possibly relevant data points:
* new install of pytho... | 2016/12/05 | [
"https://Stackoverflow.com/questions/40981120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309433/"
] | I think you need to use [pypiwin32](https://pypi.python.org/pypi/pypiwin32) instead. See [How do you install pywin32 from a binary file in tox on Windows?](https://stackoverflow.com/questions/26639947/how-do-you-install-pywin32-from-a-binary-file-in-tox-on-windows) | I have seen this thread referenced by people who were seeing the same pip error message on Linux or other systems -- even though the title clearly specifies "(on windows)".
For users of Linux, Unix, MacOS, etc., let me make it perfectly clear that pywin32 is a wrapper for Windows system calls, and only works on Window... |
70,456,516 | Here is the minimal code needed to reproduce the problem.
I call an API with a callback function that prints what comes out of the API call.
If I run this code in Jupyter, I get the output. If I run it with `python file.py` I don't get any output. I already checked the API's code, but that does nothing weird. Setting... | 2021/12/23 | [
"https://Stackoverflow.com/questions/70456516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12210524/"
] | Because you're using a websocket, the callback is executed by a different thread, which means that if you don't wait, the main thread (which is to receive the `print`'s output) will already be killed.
Add a `sleep(1)` (that's seconds, not ms) at the end and the output will show.
PS: The reason Jupyter *does* show the... | ```
import time
from python_bitvavo_api.bitvavo import Bitvavo
# %%
def generic_callback(response):
print(f"log function=get_markets, {response=}")
bitvavo = Bitvavo({"DEBUGGING": False})
websocket = bitvavo.newWebsocket()
# Wait N.1 required to receive output, otherwise the main thread is killed
time.sleep(1)
... |
28,622,452 | I want to print the files in subdirectory which is 2-level inside from root directory. In shell I can use the below find command
```
find -mindepth 3 -type f
./one/sub1/sub2/a.txt
./one/sub1/sub2/c.txt
./one/sub1/sub2/b.txt
```
In python How can i accomplish this. I know the basis syntax of os.walk, glob and fnmatch... | 2015/02/20 | [
"https://Stackoverflow.com/questions/28622452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4566486/"
] | You could use `.count()` method to find the depth:
```
import os
def files(rootdir='.', mindepth=0, maxdepth=float('inf')):
root_depth = rootdir.rstrip(os.path.sep).count(os.path.sep) - 1
for dirpath, dirs, files in os.walk(rootdir):
depth = dirpath.count(os.path.sep) - root_depth
if mindepth ... | You cannot specify any of this to [os.walk](https://docs.python.org/2/library/os.html#os.walk).
However, you can write a function that does what you have in mind.
```
import os
def list_dir_custom(mindepth=0, maxdepth=float('inf'), starting_dir=None):
""" Lists all files in `starting_dir`
starting from a `min... |
45,445,455 | In python I might have a function like this:
```
def sum_these(x, y=None):
if y is None:
y = 1
return x + y
```
What is the equivalent use in julia? To be exact I know I could probably do:
```
function sum_these(x, y=0)
if y == 0
y = 1
end
x + y
end
```
However I'd rather ... | 2017/08/01 | [
"https://Stackoverflow.com/questions/45445455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6411264/"
] | Maybe use multiple dispatch with an empty fallback?
```
function f(x, y=nothing)
...
do_something(x, y)
...
return something
end
do_something(x, y) = nothing
function do_something(x, y::Void)
...
end
```
add other relevant vars to `do_something` as necessary, and return something or mutate as ne... | Your question is a bit confusing. It seems like what you want is
```
function sum_these(x, y=1)
return x + y
end
```
But that doesn't quite do what you are asking either, since even if you call `sum_these(3, 0)` in your example, it replaces 0 with 1.
Also in Python, I would use
```
def sum_these(x, y=1):
r... |
45,445,455 | In python I might have a function like this:
```
def sum_these(x, y=None):
if y is None:
y = 1
return x + y
```
What is the equivalent use in julia? To be exact I know I could probably do:
```
function sum_these(x, y=0)
if y == 0
y = 1
end
x + y
end
```
However I'd rather ... | 2017/08/01 | [
"https://Stackoverflow.com/questions/45445455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6411264/"
] | ```
function sum_these(x, y=nothing)
if y == nothing
do stuff
end
return something
end
```
That's not only perfectly fine, but because `nothing` is a singleton of type `Void`, the `y==nothing` will actually compile away so the if statement is actually no runtime cost here. I talk about this in depth [in a... | Your question is a bit confusing. It seems like what you want is
```
function sum_these(x, y=1)
return x + y
end
```
But that doesn't quite do what you are asking either, since even if you call `sum_these(3, 0)` in your example, it replaces 0 with 1.
Also in Python, I would use
```
def sum_these(x, y=1):
r... |
45,445,455 | In python I might have a function like this:
```
def sum_these(x, y=None):
if y is None:
y = 1
return x + y
```
What is the equivalent use in julia? To be exact I know I could probably do:
```
function sum_these(x, y=0)
if y == 0
y = 1
end
x + y
end
```
However I'd rather ... | 2017/08/01 | [
"https://Stackoverflow.com/questions/45445455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6411264/"
] | ```
function sum_these(x, y=nothing)
if y == nothing
do stuff
end
return something
end
```
That's not only perfectly fine, but because `nothing` is a singleton of type `Void`, the `y==nothing` will actually compile away so the if statement is actually no runtime cost here. I talk about this in depth [in a... | Maybe use multiple dispatch with an empty fallback?
```
function f(x, y=nothing)
...
do_something(x, y)
...
return something
end
do_something(x, y) = nothing
function do_something(x, y::Void)
...
end
```
add other relevant vars to `do_something` as necessary, and return something or mutate as ne... |
48,216,974 | The curve is:
```
import numpy as np
import scipy.stats as sp
from scipy.optimize import curve_fit
from lmfit import minimize, Parameters, Parameter, report_fit#
import xlwings as xw
import os
import pandas as pd
```
I tried running a simply curve fit from scipy:
This returns
```
Out[156]:
(array([ 1., 1.]), arra... | 2018/01/11 | [
"https://Stackoverflow.com/questions/48216974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504877/"
] | The curve fitting runs smoothly when we provide a good starting point. We can get one
* by linear regression on `sp.norm.ppf(x_data)` and `np.log(y_data)`
* or by fitting the free (non-clipped) model first
Alternatively, if you want the computer to find the solution without "help"
* use a stochastic algorithm like b... | I think that part of the problem is that you have only 5 observations, 2 at the same value of `x` and the model does not perfectly represent your data. I also recommend trying to fit in the log of the model to the log of the data. And, if you expect `n2` to be ~10, you should use that as a starting value.
Arbitrarily... |
48,216,974 | The curve is:
```
import numpy as np
import scipy.stats as sp
from scipy.optimize import curve_fit
from lmfit import minimize, Parameters, Parameter, report_fit#
import xlwings as xw
import os
import pandas as pd
```
I tried running a simply curve fit from scipy:
This returns
```
Out[156]:
(array([ 1., 1.]), arra... | 2018/01/11 | [
"https://Stackoverflow.com/questions/48216974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504877/"
] | I think that part of the problem is that you have only 5 observations, 2 at the same value of `x` and the model does not perfectly represent your data. I also recommend trying to fit in the log of the model to the log of the data. And, if you expect `n2` to be ~10, you should use that as a starting value.
Arbitrarily... | Here is a simple way to perform regression using [scipy.optimize.curve\_fit](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html):
```
import matplotlib.pyplot as plt
import scipy.optimize as opt
import scipy.stats as stats
import numpy as np
% matplotlib inline
# Objective
def model(x... |
48,216,974 | The curve is:
```
import numpy as np
import scipy.stats as sp
from scipy.optimize import curve_fit
from lmfit import minimize, Parameters, Parameter, report_fit#
import xlwings as xw
import os
import pandas as pd
```
I tried running a simply curve fit from scipy:
This returns
```
Out[156]:
(array([ 1., 1.]), arra... | 2018/01/11 | [
"https://Stackoverflow.com/questions/48216974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504877/"
] | The curve fitting runs smoothly when we provide a good starting point. We can get one
* by linear regression on `sp.norm.ppf(x_data)` and `np.log(y_data)`
* or by fitting the free (non-clipped) model first
Alternatively, if you want the computer to find the solution without "help"
* use a stochastic algorithm like b... | Here is a simple way to perform regression using [scipy.optimize.curve\_fit](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html):
```
import matplotlib.pyplot as plt
import scipy.optimize as opt
import scipy.stats as stats
import numpy as np
% matplotlib inline
# Objective
def model(x... |
10,745,138 | i'm new on python. i wrote a script to connect to a host and execute one command
```
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)
print 'running remote command'
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for l... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10745138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008764/"
] | There is extensive paramiko API documentation you can find at: <http://docs.paramiko.org/en/stable/index.html>
I use the following method to execute commands on a password protected client:
```
import paramiko
nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username'
password = 'password'
command = 'ls'
... | ThePracticalOne - you are hero!
I had problems with exec\_command (which is a member of Client)
I tried to run powershell commands over ssh on Windows server, and only your example with
```
client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)
```
and
```
while True:
... |
10,745,138 | i'm new on python. i wrote a script to connect to a host and execute one command
```
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)
print 'running remote command'
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for l... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10745138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008764/"
] | There is something wrong with the accepted answer, it sometimes (randomly) brings a clipped response from server. I do not know why, I did not investigate the faulty cause of the accepted answer because this code worked perfectly for me:
```
import paramiko
ip='server ip'
port=22
username='username'
password='passwor... | The code of @ThePracticalOne is great for showing the usage except for one thing:
**Somtimes** the output would be incomplete.(`session.recv_ready()` turns true after the `if session.recv_ready():` while `session.recv_stderr_ready()` and `session.exit_status_ready()` turned true before entering next loop)
so my thinki... |
10,745,138 | i'm new on python. i wrote a script to connect to a host and execute one command
```
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)
print 'running remote command'
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for l... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10745138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008764/"
] | Passwordless SSH worked for me
```
import paramiko
def connect_SSH():
ssh = paramiko.SSHClient()
username = '<uname>'
port = <port-no>
ip = '<ip-address>'
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username)
stdin, stdout, stderr = ssh.exec_command('<cmd... | ```
###### Use paramiko to connect to LINUX platform############
import paramiko
ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)
--------Connection Established----------------------... |
10,745,138 | i'm new on python. i wrote a script to connect to a host and execute one command
```
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)
print 'running remote command'
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for l... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10745138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008764/"
] | There is extensive paramiko API documentation you can find at: <http://docs.paramiko.org/en/stable/index.html>
I use the following method to execute commands on a password protected client:
```
import paramiko
nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username'
password = 'password'
command = 'ls'
... | Passwordless SSH worked for me
```
import paramiko
def connect_SSH():
ssh = paramiko.SSHClient()
username = '<uname>'
port = <port-no>
ip = '<ip-address>'
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username)
stdin, stdout, stderr = ssh.exec_command('<cmd... |
10,745,138 | i'm new on python. i wrote a script to connect to a host and execute one command
```
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)
print 'running remote command'
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for l... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10745138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008764/"
] | The code of @ThePracticalOne is great for showing the usage except for one thing:
**Somtimes** the output would be incomplete.(`session.recv_ready()` turns true after the `if session.recv_ready():` while `session.recv_stderr_ready()` and `session.exit_status_ready()` turned true before entering next loop)
so my thinki... | ```
###### Use paramiko to connect to LINUX platform############
import paramiko
ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)
--------Connection Established----------------------... |
10,745,138 | i'm new on python. i wrote a script to connect to a host and execute one command
```
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)
print 'running remote command'
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for l... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10745138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008764/"
] | There is something wrong with the accepted answer, it sometimes (randomly) brings a clipped response from server. I do not know why, I did not investigate the faulty cause of the accepted answer because this code worked perfectly for me:
```
import paramiko
ip='server ip'
port=22
username='username'
password='passwor... | Passwordless SSH worked for me
```
import paramiko
def connect_SSH():
ssh = paramiko.SSHClient()
username = '<uname>'
port = <port-no>
ip = '<ip-address>'
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username)
stdin, stdout, stderr = ssh.exec_command('<cmd... |
10,745,138 | i'm new on python. i wrote a script to connect to a host and execute one command
```
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)
print 'running remote command'
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for l... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10745138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008764/"
] | There is something wrong with the accepted answer, it sometimes (randomly) brings a clipped response from server. I do not know why, I did not investigate the faulty cause of the accepted answer because this code worked perfectly for me:
```
import paramiko
ip='server ip'
port=22
username='username'
password='passwor... | ```
###### Use paramiko to connect to LINUX platform############
import paramiko
ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)
--------Connection Established----------------------... |
10,745,138 | i'm new on python. i wrote a script to connect to a host and execute one command
```
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)
print 'running remote command'
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for l... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10745138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008764/"
] | There is extensive paramiko API documentation you can find at: <http://docs.paramiko.org/en/stable/index.html>
I use the following method to execute commands on a password protected client:
```
import paramiko
nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username'
password = 'password'
command = 'ls'
... | ```
###### Use paramiko to connect to LINUX platform############
import paramiko
ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)
--------Connection Established----------------------... |
10,745,138 | i'm new on python. i wrote a script to connect to a host and execute one command
```
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)
print 'running remote command'
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for l... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10745138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008764/"
] | There is extensive paramiko API documentation you can find at: <http://docs.paramiko.org/en/stable/index.html>
I use the following method to execute commands on a password protected client:
```
import paramiko
nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username'
password = 'password'
command = 'ls'
... | The code of @ThePracticalOne is great for showing the usage except for one thing:
**Somtimes** the output would be incomplete.(`session.recv_ready()` turns true after the `if session.recv_ready():` while `session.recv_stderr_ready()` and `session.exit_status_ready()` turned true before entering next loop)
so my thinki... |
10,745,138 | i'm new on python. i wrote a script to connect to a host and execute one command
```
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)
print 'running remote command'
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for l... | 2012/05/24 | [
"https://Stackoverflow.com/questions/10745138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008764/"
] | ThePracticalOne - you are hero!
I had problems with exec\_command (which is a member of Client)
I tried to run powershell commands over ssh on Windows server, and only your example with
```
client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)
```
and
```
while True:
... | ```
###### Use paramiko to connect to LINUX platform############
import paramiko
ip='server ip'
port=22
username='username'
password='password'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)
--------Connection Established----------------------... |
25,086,088 | I've spent the better part of an afternoon trying to import the xlrd module, it works when i do it in the shell but when i try to run any file I get an import error.
Please could somebody provide a solution? (I'm a beginner, so please be excruciatingly specific)
This code:
```
#!/usr/bin/python
import os
os.chdir("... | 2014/08/01 | [
"https://Stackoverflow.com/questions/25086088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3900424/"
] | They are overlapping because you've given them all absolute position and left 0. Absolute position removes the element from the normal flow of the page and puts it exactly where you indicate using the top/left/right/bottom properties. They will overlap as long as they have the same parent and same position properties. | They are overlapping because you are using position absolute. instead place the divs at the top of the html page and do this instead:
```
<div id="left" style="float:left;width:60%;height:100%;background:#e6e6e6;">
<div id="map" style="float:left;width:60%;height:400px">Map goes here.</div>
<div id="details" style="fl... |
25,086,088 | I've spent the better part of an afternoon trying to import the xlrd module, it works when i do it in the shell but when i try to run any file I get an import error.
Please could somebody provide a solution? (I'm a beginner, so please be excruciatingly specific)
This code:
```
#!/usr/bin/python
import os
os.chdir("... | 2014/08/01 | [
"https://Stackoverflow.com/questions/25086088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3900424/"
] | Absolute position and left being 0 is making them overlap.
**Please use css**
see solution : <http://jsfiddle.net/thecbuilder/vZ77e/>
**html**
```
<div id="left">
<div id="map">Map goes here.</div>
<div id="details">Details</div>
</div>
<div id="description">description</div>
<div id="resource">resource</di... | They are overlapping because you are using position absolute. instead place the divs at the top of the html page and do this instead:
```
<div id="left" style="float:left;width:60%;height:100%;background:#e6e6e6;">
<div id="map" style="float:left;width:60%;height:400px">Map goes here.</div>
<div id="details" style="fl... |
55,550,259 | I would like to find a way to reverse the bits of each character in a string using python.
For example, if my first character was `J`, this is ASCII `0x4a` or `0b01001010`, so would be reversed to `0x52` or `0b01010010`. If my second character was `K`, this is `0b01001011`, so would be reversed to `0xd2` or `0b1101001... | 2019/04/06 | [
"https://Stackoverflow.com/questions/55550259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4263190/"
] | If speed is your goal and you are working with ASCII so you only have 256 8-bit values to handle, calculate the reversed-byte values beforehand and put them in a `bytearray`, then look them up by indexing into the `bytearray`. | ```
a=bin(ord("a"))
'0b'+a[::-1][0:len(a)-2]
```
If you want to do it for a lot of characters, then there are only 256 ascii characters. Store the reversed strings in a hashmap and do lookups on the hashmap. Time complexity of those lookups is O(1), but there's a fix setup time. |
55,550,259 | I would like to find a way to reverse the bits of each character in a string using python.
For example, if my first character was `J`, this is ASCII `0x4a` or `0b01001010`, so would be reversed to `0x52` or `0b01010010`. If my second character was `K`, this is `0b01001011`, so would be reversed to `0xd2` or `0b1101001... | 2019/04/06 | [
"https://Stackoverflow.com/questions/55550259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4263190/"
] | After taking on board the advice, here is my solution:
```
# Pre-populate a look-up array with bit-reversed integers from 0 to 255
bytearray = []
for i in range(0, 256):
bytearray.append(int('{:08b}'.format(i)[::-1], 2))
# Reverses the bits of each character in the input string and returns the result
# as a strin... | ```
a=bin(ord("a"))
'0b'+a[::-1][0:len(a)-2]
```
If you want to do it for a lot of characters, then there are only 256 ascii characters. Store the reversed strings in a hashmap and do lookups on the hashmap. Time complexity of those lookups is O(1), but there's a fix setup time. |
22,384,783 | I am trying to use C# classes from python, using python.net on mono / ubuntu.
So far I managed to do a simple function call with one argument work. What I am now trying to do is pass a python callback to the C# function call.
I tried the following variations below, none worked. Can someone show how to make that work?... | 2014/03/13 | [
"https://Stackoverflow.com/questions/22384783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477436/"
] | Try to pass `Action` or `Func` instead of just raw function:
I used IronPython here (because right now I don't have mono installed on any of my machines but according of Python.NET [documentation](http://pythonnet.sourceforge.net/readme.html) I think it should work
Actually your code is almost ok but you need to impor... | It looks like you should define your Delegate explicitly:
```
class MC {
// Define a delegate type
public delegate void Callback();
public double method2(Callback f) {
Console.WriteLine("Executing method2" );
/* ... do f() at some point ... */
/* also tried f.DynamicInvoke() */
... |
56,692,868 | I am trying to write a mock lottery simulator as a thought excercize and for some introductory python practice, where each team would have 2x the odds of getting the first pick as the team that preceded them in the standings. The code below works (although I am sure there is a more efficient way to write it), but now I... | 2019/06/20 | [
"https://Stackoverflow.com/questions/56692868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10918881/"
] | Instead of doing your sampling like this, I would use a discrete distribution for the probability of getting the team i, and sample using random.choices. We update the distribution after the sampling by discarding all the tickets from that team (since it cannot appear again).
```
from random import choices
ticket_amou... | Here is what you want I think, but as the other comment said it runs very slow and I would not try 10 million times, its slow enough as is.
```
from collections import Counter
for i in range(1,10000):
random.shuffle(total)
countList.append(total[0])
print Counter(countList)
```
add the for loop to the end o... |
56,692,868 | I am trying to write a mock lottery simulator as a thought excercize and for some introductory python practice, where each team would have 2x the odds of getting the first pick as the team that preceded them in the standings. The code below works (although I am sure there is a more efficient way to write it), but now I... | 2019/06/20 | [
"https://Stackoverflow.com/questions/56692868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10918881/"
] | Instead of doing your sampling like this, I would use a discrete distribution for the probability of getting the team i, and sample using random.choices. We update the distribution after the sampling by discarding all the tickets from that team (since it cannot appear again).
```
from random import choices
ticket_amou... | Here is a way to do it (it fast enough to run 1M time in about 15 min, so for 10 millions you would probably need to wait a few hours):
```
import numpy as np
from collections import Counter
n_teams = 12
n_trials = int(1e4)
probs = [ 2**i for i in range(0,n_teams) ]
probs = [ prob_i / sum(probs) for prob_i in probs ... |
56,533,066 | I'm trying to write a request using Python Requests which sends a request to Docusign. I need to use the legacy authorization header, but unfortunately it seems most documentation for this has been removed. When I send the request I get an error as stated in the title.
From research, I found that special characters i... | 2019/06/10 | [
"https://Stackoverflow.com/questions/56533066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6490748/"
] | I'm able to reproduce this behavior: It looks like DocuSign doesn't accept Single Quotes around the sub-parameters of the x-DocuSign-Authentication header value.
Your example fails:
```
{'Username': 'test@test.com', 'Password': 'xxxxxxxxxx', 'IntegratorKey': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'}
```
This has more... | Since you are having success using Postman, it will help to get exactly what is being sent via your request. For this use:
```py
response = requests.get(your_url, headers=your_headers)
x = response.request.headers()
print(x)
```
This will show you exactly what requests is preparing and sending off. If you post that ... |
56,533,066 | I'm trying to write a request using Python Requests which sends a request to Docusign. I need to use the legacy authorization header, but unfortunately it seems most documentation for this has been removed. When I send the request I get an error as stated in the title.
From research, I found that special characters i... | 2019/06/10 | [
"https://Stackoverflow.com/questions/56533066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6490748/"
] | I found a solution to this issue. The response that mentioned double quotes is correct, but in Python I was unable to send a string with the proper format for docusign to understand. Next I found the following Stack overflow question, which ultimately provided the solution:
[How to send dict in Header as value to key ... | Since you are having success using Postman, it will help to get exactly what is being sent via your request. For this use:
```py
response = requests.get(your_url, headers=your_headers)
x = response.request.headers()
print(x)
```
This will show you exactly what requests is preparing and sending off. If you post that ... |
18,139,910 | I want to save an ID between requests, using Flask `session` cookie, but I'm getting an `Internal Server Error` as result, when I perform a request.
I prototyped a simple Flask app for demonstrating my problem:
```
#!/usr/bin/env python
from flask import Flask, session
app = Flask(__name__)
@app.route('/')
def run... | 2013/08/09 | [
"https://Stackoverflow.com/questions/18139910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2236401/"
] | According to [Flask sessions documentation](http://flask.pocoo.org/docs/quickstart/#sessions):
>
> ...
> What this means is that the user could look at the contents of your
> cookie but not modify it, unless they know the secret key used for
> signing.
>
>
> In order to use sessions you **have to set a secret ke... | Under `app = Flask(__name__)` place this: `app.secret_key = os.urandom(24)`. |
18,139,910 | I want to save an ID between requests, using Flask `session` cookie, but I'm getting an `Internal Server Error` as result, when I perform a request.
I prototyped a simple Flask app for demonstrating my problem:
```
#!/usr/bin/env python
from flask import Flask, session
app = Flask(__name__)
@app.route('/')
def run... | 2013/08/09 | [
"https://Stackoverflow.com/questions/18139910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2236401/"
] | According to [Flask sessions documentation](http://flask.pocoo.org/docs/quickstart/#sessions):
>
> ...
> What this means is that the user could look at the contents of your
> cookie but not modify it, unless they know the secret key used for
> signing.
>
>
> In order to use sessions you **have to set a secret ke... | As **@falsetru** mentioned, you have to set a secret key.
Before sending the `session` cookie to the user's browser, Flask signs the cookies cryptographically, and that doesn't mean that you cannot decode the cookie. I presume that Flask keeps track of the signed cookies, so it can perform it's own 'magic', in order ... |
18,139,910 | I want to save an ID between requests, using Flask `session` cookie, but I'm getting an `Internal Server Error` as result, when I perform a request.
I prototyped a simple Flask app for demonstrating my problem:
```
#!/usr/bin/env python
from flask import Flask, session
app = Flask(__name__)
@app.route('/')
def run... | 2013/08/09 | [
"https://Stackoverflow.com/questions/18139910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2236401/"
] | As **@falsetru** mentioned, you have to set a secret key.
Before sending the `session` cookie to the user's browser, Flask signs the cookies cryptographically, and that doesn't mean that you cannot decode the cookie. I presume that Flask keeps track of the signed cookies, so it can perform it's own 'magic', in order ... | Under `app = Flask(__name__)` place this: `app.secret_key = os.urandom(24)`. |
52,113,440 | Looking for data splitter line by line, by using python
* RegEx?
* Contain?
As example file "file" contain:
```
X
X
Y
Z
Z
Z
```
I need the clean way to split this file into 3 different ones, based on letter
**As a sample:**
```
def split_by_platform(FILE_NAME):
with open(FILE_NAME, "r+") as infile:
... | 2018/08/31 | [
"https://Stackoverflow.com/questions/52113440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | EDIT thanks to @bruno desthuilliers, who reminded me of the correct way to go here:
Iterate over the file object (not 'readlines'):
```
def split_by_platform(FILE_NAME, out1, out2, out3):
with open(FILE_NAME, "r") as infile, open(out1, 'a') as of1, open(out2, 'a') as of2, open(out3, 'a') as of3:
for line... | This should do it:
```
with open('my_text_file.txt') as infile, open('x.txt', 'w') as x, open('y.txt', 'w') as y, open('z.txt', 'w') as z:
for line in infile:
if line.startswith('X'):
x.write(line)
elif line.startswith('Y'):
y.write(line)
elif line.startswith('Z'):
... |
52,113,440 | Looking for data splitter line by line, by using python
* RegEx?
* Contain?
As example file "file" contain:
```
X
X
Y
Z
Z
Z
```
I need the clean way to split this file into 3 different ones, based on letter
**As a sample:**
```
def split_by_platform(FILE_NAME):
with open(FILE_NAME, "r+") as infile:
... | 2018/08/31 | [
"https://Stackoverflow.com/questions/52113440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | EDIT thanks to @bruno desthuilliers, who reminded me of the correct way to go here:
Iterate over the file object (not 'readlines'):
```
def split_by_platform(FILE_NAME, out1, out2, out3):
with open(FILE_NAME, "r") as infile, open(out1, 'a') as of1, open(out2, 'a') as of2, open(out3, 'a') as of3:
for line... | Here is a more generic way to do the same job:
```
from collections import Counter
with open("file.txt", "r+") as file:
data = file.read().splitlines()
counter = Counter(data)
array2d = [[key, ] * value for key, value in counter.items()]
print array2d # [['Y'], ['X', 'X'], ['Z', 'Z', 'Z']]
for el ... |
54,721,703 | I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
I get this result:
```
ModuleNotFoundError: No module named 'numpy.cor... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54721703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486308/"
] | Upgrade the numpy to solve the error
```
pip install numpy --upgrade
``` | ensure that you're using python 3.x by running it as
```py
python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
``` |
54,721,703 | I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
I get this result:
```
ModuleNotFoundError: No module named 'numpy.cor... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54721703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486308/"
] | I upgraded `numpy` to `1.16.1` version and tried again the above command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
and got this new result:
```
2019-02-16 13:12:40.611105: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your ... | I just upgraded my numpy from 1.14.0 to 1.17.0 by the following command on Ubuntu 18.10.
>
> sudo python3.5 -m pip install numpy --upgrade
>
>
>
No import error then. |
54,721,703 | I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
I get this result:
```
ModuleNotFoundError: No module named 'numpy.cor... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54721703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486308/"
] | You need to force the upgrade numpy to the latest version.
```
pip install 'numpy==1.16' --force-reinstall
```
Hope this helps. | ensure that you're using python 3.x by running it as
```py
python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
``` |
54,721,703 | I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
I get this result:
```
ModuleNotFoundError: No module named 'numpy.cor... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54721703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486308/"
] | Try this:
pip install --upgrade --force-reinstall numpy | ensure that you're using python 3.x by running it as
```py
python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
``` |
54,721,703 | I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
I get this result:
```
ModuleNotFoundError: No module named 'numpy.cor... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54721703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486308/"
] | I upgraded `numpy` to `1.16.1` version and tried again the above command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
and got this new result:
```
2019-02-16 13:12:40.611105: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your ... | ensure that you're using python 3.x by running it as
```py
python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
``` |
54,721,703 | I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
I get this result:
```
ModuleNotFoundError: No module named 'numpy.cor... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54721703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486308/"
] | Upgrade the numpy to solve the error
```
pip install numpy --upgrade
``` | I just upgraded my numpy from 1.14.0 to 1.17.0 by the following command on Ubuntu 18.10.
>
> sudo python3.5 -m pip install numpy --upgrade
>
>
>
No import error then. |
54,721,703 | I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
I get this result:
```
ModuleNotFoundError: No module named 'numpy.cor... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54721703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486308/"
] | Try this:
pip install --upgrade --force-reinstall numpy | I just upgraded my numpy from 1.14.0 to 1.17.0 by the following command on Ubuntu 18.10.
>
> sudo python3.5 -m pip install numpy --upgrade
>
>
>
No import error then. |
54,721,703 | I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
I get this result:
```
ModuleNotFoundError: No module named 'numpy.cor... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54721703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486308/"
] | I upgraded `numpy` to `1.16.1` version and tried again the above command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
and got this new result:
```
2019-02-16 13:12:40.611105: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your ... | Upgrade the numpy to solve the error
```
pip install numpy --upgrade
``` |
54,721,703 | I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
I get this result:
```
ModuleNotFoundError: No module named 'numpy.cor... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54721703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486308/"
] | I was having numpy `1.16.2` version but it was giving same error then i tried to install `1.16.1` and it worked for me. | ensure that you're using python 3.x by running it as
```py
python3 -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
``` |
54,721,703 | I am following this tutorial to install TensorFlow(<https://www.tensorflow.org/install/pip>), but in the last command:
```
python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"
```
I get this result:
```
ModuleNotFoundError: No module named 'numpy.cor... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54721703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486308/"
] | Upgrade the numpy to solve the error
```
pip install numpy --upgrade
``` | I was having numpy `1.16.2` version but it was giving same error then i tried to install `1.16.1` and it worked for me. |
69,837,913 | I am trying to unpickle a file but i get this error while running the following code:
```
import pickle
import pandas as pd
import numpy
unpickled_df = pd.read_pickle("./ToyData.pickle")
unpickled_df
```
or
```
import pickle
# load : get the data from file
data = pickle.load(open('ToyData.pickle', "rb"))
```
erro... | 2021/11/04 | [
"https://Stackoverflow.com/questions/69837913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17326771/"
] | You cannot pickle.load files in a newly updated version of xarray that were made in a previous version of xarray.
This is a known error that has no solution as "pickling is not recommended for long-term storage".
<https://github.com/pydata/xarray/discussions/5642>
.hdf or .json are better alternatives for long-term s... | I had the same problem with `results = torch.load("results.pth.tar")` and get "`AttributeError: Can't get attribute 'PandasIndexAdapter' on <module 'xarray.core.indexing'`".
I solve it by changing the version I have on my computer by the version the file.pth.tar was saved with.
In my case the file was saved with xarra... |
68,964,555 | I don't know why I am getting this error, the official document reference
<https://scikit-learn.org/stable/modules/generated/sklearn.metrics.det_curve.html#sklearn.metrics.det_curve>
**Code:**
```
import numpy as np
from sklearn.metrics import det_curve
fpr, fnr, thresholds = det_curve(y_test, y_pred)
print(fpr, ... | 2021/08/28 | [
"https://Stackoverflow.com/questions/68964555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385107/"
] | Looks like some issue with a missing package. Try the following:
```
pip uninstall -v scikit-learn
pip install -v scikit-learn
```
This might install the related dependencies along with it. | Same kind of problem happened to me in my Jupyter notebook. I uninstall and re-install both scikit-learn and imblearn. It didn't work. Then **restarting the kernel** and running again solved the problem. |
36,314,411 | Given a file with resolution-compressed binary data, I would like to convert the sub-byte bits into their integer representations in python. By this I mean I need to interpret `n` bits from a file as an integer.
Currently I am reading the file into `bitarray` objects, and am converting subsets of the objects into int... | 2016/03/30 | [
"https://Stackoverflow.com/questions/36314411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1176806/"
] | The whole solution :)
Only javascript section is modified.
```
<div id="divCountries" class="fieldRow">
<div class="leftLabel labelWidth20">
<label for="txtcountries">Country:</label>
</div>
<div class="LeftField">
<div class="formField34">
<select id="txtCountries" type="text" name="Countries" alt="Countries... | See this [fiddle](https://jsfiddle.net/lalu050/Lcu4jp91/)
---------------------------------------------------------
That was because the value that was returned from `document.getElementById("txtCountries").value` was `UnitedStates` and not `United States`.
Please note that the option for United States was as follows... |
36,314,411 | Given a file with resolution-compressed binary data, I would like to convert the sub-byte bits into their integer representations in python. By this I mean I need to interpret `n` bits from a file as an integer.
Currently I am reading the file into `bitarray` objects, and am converting subsets of the objects into int... | 2016/03/30 | [
"https://Stackoverflow.com/questions/36314411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1176806/"
] | The whole solution :)
Only javascript section is modified.
```
<div id="divCountries" class="fieldRow">
<div class="leftLabel labelWidth20">
<label for="txtcountries">Country:</label>
</div>
<div class="LeftField">
<div class="formField34">
<select id="txtCountries" type="text" name="Countries" alt="Countries... | Try this ;)
Put a space in `value="UnitedStates"`:
```
<option value="United States">United States</option>
``` |
59,307,832 | I'm slowly trying to get my head around classes. I have a few working examples which i kinda understand but can someone please explain to me why this doesn’t work?
```
class python:
def __init__(self,name):
self.name=name
def changename(self,newname):
self.name=newname
abc=python('python')
print abc.nam... | 2019/12/12 | [
"https://Stackoverflow.com/questions/59307832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6037160/"
] | You can have an HTML5 `audio` tag in base64 encoding as so:
```html
<audio controls autoplay loop src="data:audio/ogg;base64,BASE64CODE" />
```
No need for a `type`! :) | If your audio files are over about 20MB then you might run into performance problems and errors in some browsers (notably Firefox). For this reason I recommend converting the Base64 into a binary Blob as described [here](https://stackoverflow.com/a/40329529/1417989) using the [convertDataURIToBinary](https://gist.githu... |
2,162,914 | I have the following Python script that reads numbers and outputs an error if the input is not a number.
```
import fileinput
import sys
for line in (txt.strip() for txt in fileinput.input()):
if not line.isdigit():
sys.stderr.write("ERROR: not a number: %s\n" % line)
```
If I get the input from stdin, I... | 2010/01/29 | [
"https://Stackoverflow.com/questions/2162914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46821/"
] | I wrote an explanation about this in my answer to this question.
[How to capture Control+D signal?](https://stackoverflow.com/questions/1516122/how-to-capture-controld-signal)
In short, Control-D at the terminal simply causes the terminal to flush the input. This makes the `read` system call return. The first time it... | The first time it considers it to be input, the second time it's for keeps!
This only occurs when the input is from a tty. It is likely because of the terminal settings where characters are buffered until a newline (carriage return) is entered. |
2,162,914 | I have the following Python script that reads numbers and outputs an error if the input is not a number.
```
import fileinput
import sys
for line in (txt.strip() for txt in fileinput.input()):
if not line.isdigit():
sys.stderr.write("ERROR: not a number: %s\n" % line)
```
If I get the input from stdin, I... | 2010/01/29 | [
"https://Stackoverflow.com/questions/2162914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46821/"
] | In Python 3, this was due to [a bug in Python's standard I/O library](http://bugs.python.org/issue5505). The bug was fixed in Python 3.3.
---
In a Unix terminal, typing Ctrl+D doesn't actually close the process's stdin. But typing either Enter or Ctrl+D does cause the OS `read` system call to return right away. So:
... | The first time it considers it to be input, the second time it's for keeps!
This only occurs when the input is from a tty. It is likely because of the terminal settings where characters are buffered until a newline (carriage return) is entered. |
2,162,914 | I have the following Python script that reads numbers and outputs an error if the input is not a number.
```
import fileinput
import sys
for line in (txt.strip() for txt in fileinput.input()):
if not line.isdigit():
sys.stderr.write("ERROR: not a number: %s\n" % line)
```
If I get the input from stdin, I... | 2010/01/29 | [
"https://Stackoverflow.com/questions/2162914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46821/"
] | Most likely this has to do with Python the following Python issues:
* [5505](http://bugs.python.org/issue5505): `sys.stdin.read()` doesn't return after first EOF on Windows, and
* [1633941](http://bugs.python.org/issue1633941): `for line in sys.stdin:` doesn't notice EOF the first time. | The first time it considers it to be input, the second time it's for keeps!
This only occurs when the input is from a tty. It is likely because of the terminal settings where characters are buffered until a newline (carriage return) is entered. |
2,162,914 | I have the following Python script that reads numbers and outputs an error if the input is not a number.
```
import fileinput
import sys
for line in (txt.strip() for txt in fileinput.input()):
if not line.isdigit():
sys.stderr.write("ERROR: not a number: %s\n" % line)
```
If I get the input from stdin, I... | 2010/01/29 | [
"https://Stackoverflow.com/questions/2162914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46821/"
] | In Python 3, this was due to [a bug in Python's standard I/O library](http://bugs.python.org/issue5505). The bug was fixed in Python 3.3.
---
In a Unix terminal, typing Ctrl+D doesn't actually close the process's stdin. But typing either Enter or Ctrl+D does cause the OS `read` system call to return right away. So:
... | I wrote an explanation about this in my answer to this question.
[How to capture Control+D signal?](https://stackoverflow.com/questions/1516122/how-to-capture-controld-signal)
In short, Control-D at the terminal simply causes the terminal to flush the input. This makes the `read` system call return. The first time it... |
2,162,914 | I have the following Python script that reads numbers and outputs an error if the input is not a number.
```
import fileinput
import sys
for line in (txt.strip() for txt in fileinput.input()):
if not line.isdigit():
sys.stderr.write("ERROR: not a number: %s\n" % line)
```
If I get the input from stdin, I... | 2010/01/29 | [
"https://Stackoverflow.com/questions/2162914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46821/"
] | I wrote an explanation about this in my answer to this question.
[How to capture Control+D signal?](https://stackoverflow.com/questions/1516122/how-to-capture-controld-signal)
In short, Control-D at the terminal simply causes the terminal to flush the input. This makes the `read` system call return. The first time it... | Using the "for line in file:" form of reading lines from a file, Python uses a hidden read-ahead buffer (see <http://docs.python.org/2.7/library/stdtypes.html#file-objects> at the file.next function). First of all, this explains why a program that writes output when each input line is read displays no output until you ... |
2,162,914 | I have the following Python script that reads numbers and outputs an error if the input is not a number.
```
import fileinput
import sys
for line in (txt.strip() for txt in fileinput.input()):
if not line.isdigit():
sys.stderr.write("ERROR: not a number: %s\n" % line)
```
If I get the input from stdin, I... | 2010/01/29 | [
"https://Stackoverflow.com/questions/2162914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46821/"
] | In Python 3, this was due to [a bug in Python's standard I/O library](http://bugs.python.org/issue5505). The bug was fixed in Python 3.3.
---
In a Unix terminal, typing Ctrl+D doesn't actually close the process's stdin. But typing either Enter or Ctrl+D does cause the OS `read` system call to return right away. So:
... | Most likely this has to do with Python the following Python issues:
* [5505](http://bugs.python.org/issue5505): `sys.stdin.read()` doesn't return after first EOF on Windows, and
* [1633941](http://bugs.python.org/issue1633941): `for line in sys.stdin:` doesn't notice EOF the first time. |
2,162,914 | I have the following Python script that reads numbers and outputs an error if the input is not a number.
```
import fileinput
import sys
for line in (txt.strip() for txt in fileinput.input()):
if not line.isdigit():
sys.stderr.write("ERROR: not a number: %s\n" % line)
```
If I get the input from stdin, I... | 2010/01/29 | [
"https://Stackoverflow.com/questions/2162914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46821/"
] | In Python 3, this was due to [a bug in Python's standard I/O library](http://bugs.python.org/issue5505). The bug was fixed in Python 3.3.
---
In a Unix terminal, typing Ctrl+D doesn't actually close the process's stdin. But typing either Enter or Ctrl+D does cause the OS `read` system call to return right away. So:
... | Using the "for line in file:" form of reading lines from a file, Python uses a hidden read-ahead buffer (see <http://docs.python.org/2.7/library/stdtypes.html#file-objects> at the file.next function). First of all, this explains why a program that writes output when each input line is read displays no output until you ... |
2,162,914 | I have the following Python script that reads numbers and outputs an error if the input is not a number.
```
import fileinput
import sys
for line in (txt.strip() for txt in fileinput.input()):
if not line.isdigit():
sys.stderr.write("ERROR: not a number: %s\n" % line)
```
If I get the input from stdin, I... | 2010/01/29 | [
"https://Stackoverflow.com/questions/2162914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46821/"
] | Most likely this has to do with Python the following Python issues:
* [5505](http://bugs.python.org/issue5505): `sys.stdin.read()` doesn't return after first EOF on Windows, and
* [1633941](http://bugs.python.org/issue1633941): `for line in sys.stdin:` doesn't notice EOF the first time. | Using the "for line in file:" form of reading lines from a file, Python uses a hidden read-ahead buffer (see <http://docs.python.org/2.7/library/stdtypes.html#file-objects> at the file.next function). First of all, this explains why a program that writes output when each input line is read displays no output until you ... |
43,518,430 | How to convert
```
json_decode = [{"538":["1,2,3","hello world"]},{"361":["0,9,8","x,x,y"]}]
```
to
```
{"538":["1,2,3","hello world"],"361":["0,9,8","x,x,y"]}
```
in python? | 2017/04/20 | [
"https://Stackoverflow.com/questions/43518430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6742101/"
] | ***Try like this:***
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText edittext = (EditText) findViewbyId(R.id.edittext);
editText.setText("DefaultValue");
}
``` | Add in xml layout file
```
android:text="defaultVal"
```
In onClick method or constructor/init method in java
```
editText.setText("DefaultValue");
``` |
17,803,254 | I want to find my public ip adress from python program.
So far this is the only site
<http://www.whatismyip.com/>
and
<http://whatismyip.org/>
which gives ip without proxy rest all give the proxy.
Now .org site is using image and first one writes ip across many span elements so i can't grab with urllib.
Any other... | 2013/07/23 | [
"https://Stackoverflow.com/questions/17803254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1667349/"
] | I usually use <http://httpbin.org/>:
```
import requests
ip = requests.get('http://httpbin.org/ip').json()['origin']
``` | Use [lxml](http://lxml.de/)
```
import urllib
import lxml.html
u = urllib.urlopen('http://www.whatismyip.com/')
html = u.read()
u.close()
root = lxml.html.fromstring(html)
print ''.join(x.text for x in root.cssselect('#greenip *'))
``` |
14,140,089 | I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on... | 2013/01/03 | [
"https://Stackoverflow.com/questions/14140089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945133/"
] | You can use [String.Join](http://msdn.microsoft.com/en-us/library/dd783876(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1).
```
string.Join("\n", errorMessages);
``` | Use join
```
string.Join(System.Environment.NewLine, errorMessages);
``` |
14,140,089 | I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on... | 2013/01/03 | [
"https://Stackoverflow.com/questions/14140089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945133/"
] | You can use [String.Join](http://msdn.microsoft.com/en-us/library/dd783876(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1).
```
string.Join("\n", errorMessages);
``` | The shortest way is to use either `.Aggregate(...)` or `String.Join(...)`.
```
var messages = errorMessages.Aggregate((x, y) => x + Environment.NewLine + y);
```
Or
```
var messages = String.Join(Environment.NewLine, errorMessages);
``` |
14,140,089 | I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on... | 2013/01/03 | [
"https://Stackoverflow.com/questions/14140089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945133/"
] | You can use [String.Join](http://msdn.microsoft.com/en-us/library/dd783876(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1).
```
string.Join("\n", errorMessages);
``` | ```
using System;
string.Join(Environment.NewLine, errorMessages);
``` |
14,140,089 | I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on... | 2013/01/03 | [
"https://Stackoverflow.com/questions/14140089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945133/"
] | You can use [String.Join](http://msdn.microsoft.com/en-us/library/dd783876(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1).
```
string.Join("\n", errorMessages);
``` | I was having problems using
```
string.Join(System.Environment.NewLine, errorMessages);
```
In the page, instead of the new line I was getting **\r\n** instead. I solved it by using
```
string.Join("<br>", errorMessages);
``` |
14,140,089 | I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on... | 2013/01/03 | [
"https://Stackoverflow.com/questions/14140089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945133/"
] | Use join
```
string.Join(System.Environment.NewLine, errorMessages);
``` | The shortest way is to use either `.Aggregate(...)` or `String.Join(...)`.
```
var messages = errorMessages.Aggregate((x, y) => x + Environment.NewLine + y);
```
Or
```
var messages = String.Join(Environment.NewLine, errorMessages);
``` |
14,140,089 | I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on... | 2013/01/03 | [
"https://Stackoverflow.com/questions/14140089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945133/"
] | Use join
```
string.Join(System.Environment.NewLine, errorMessages);
``` | ```
using System;
string.Join(Environment.NewLine, errorMessages);
``` |
14,140,089 | I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on... | 2013/01/03 | [
"https://Stackoverflow.com/questions/14140089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945133/"
] | Use join
```
string.Join(System.Environment.NewLine, errorMessages);
``` | I was having problems using
```
string.Join(System.Environment.NewLine, errorMessages);
```
In the page, instead of the new line I was getting **\r\n** instead. I solved it by using
```
string.Join("<br>", errorMessages);
``` |
14,140,089 | I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on... | 2013/01/03 | [
"https://Stackoverflow.com/questions/14140089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945133/"
] | ```
using System;
string.Join(Environment.NewLine, errorMessages);
``` | The shortest way is to use either `.Aggregate(...)` or `String.Join(...)`.
```
var messages = errorMessages.Aggregate((x, y) => x + Environment.NewLine + y);
```
Or
```
var messages = String.Join(Environment.NewLine, errorMessages);
``` |
14,140,089 | I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on... | 2013/01/03 | [
"https://Stackoverflow.com/questions/14140089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945133/"
] | The shortest way is to use either `.Aggregate(...)` or `String.Join(...)`.
```
var messages = errorMessages.Aggregate((x, y) => x + Environment.NewLine + y);
```
Or
```
var messages = String.Join(Environment.NewLine, errorMessages);
``` | I was having problems using
```
string.Join(System.Environment.NewLine, errorMessages);
```
In the page, instead of the new line I was getting **\r\n** instead. I solved it by using
```
string.Join("<br>", errorMessages);
``` |
14,140,089 | I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on... | 2013/01/03 | [
"https://Stackoverflow.com/questions/14140089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945133/"
] | ```
using System;
string.Join(Environment.NewLine, errorMessages);
``` | I was having problems using
```
string.Join(System.Environment.NewLine, errorMessages);
```
In the page, instead of the new line I was getting **\r\n** instead. I solved it by using
```
string.Join("<br>", errorMessages);
``` |
40,613,480 | [](https://i.stack.imgur.com/vIEKx.png)
I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis.
I was writing a function on it using Pandas but finding little difficulty.
This is how Heiken Ashi [HA] looks li... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7053990/"
] | Here is the fastest, accurate and efficient implementation as per my tests:
```
def HA(df):
df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
idx = df.index.name
df.reset_index(inplace=True)
for i in range(0, len(df)):
if i == 0:
df.set_value(i, 'HA_Open', ((df.get_... | Numpy version working with Numba
```
@jit(nopython=True)
def heiken_ashi_numpy(c_open, c_high, c_low, c_close):
ha_close = (c_open + c_high + c_low + c_close) / 4
ha_open = np.empty_like(ha_close)
ha_open[0] = (c_open[0] + c_close[0]) / 2
for i in range(1, len(c_close)):
ha_open[i] = (c_open[i ... |
40,613,480 | [](https://i.stack.imgur.com/vIEKx.png)
I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis.
I was writing a function on it using Pandas but finding little difficulty.
This is how Heiken Ashi [HA] looks li... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7053990/"
] | Assuming you have everything in a list of lists; where each row has: time, open, close, high, low, volume.
```
if candles:
close_values = [sum(row[1:5]) / 4 for row in candles]
previous_close = close_values[0]
previous_open = (candles[0][1] + previous_close) / 2
... | **Fastest solution I found.**
```
def HA(df):
df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
idx = df.index.name
df.reset_index(inplace=True)
ha_close_values = self.data['HA_Close'].values
length = len(df)
ha_open = np.zeros(length, dtype=float)
ha_open[0] = (df['Open']... |
40,613,480 | [](https://i.stack.imgur.com/vIEKx.png)
I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis.
I was writing a function on it using Pandas but finding little difficulty.
This is how Heiken Ashi [HA] looks li... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7053990/"
] | Here is the fastest, accurate and efficient implementation as per my tests:
```
def HA(df):
df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
idx = df.index.name
df.reset_index(inplace=True)
for i in range(0, len(df)):
if i == 0:
df.set_value(i, 'HA_Open', ((df.get_... | ```
def heikenashi(df):
df['HA_Close'] = (df['Open'] + df['High'] + df['Low'] + df['Close']) / 4
df['HA_Open'] = (df['Open'].shift(1) + df['Open'].shift(1)) / 2
df.iloc[0, df.columns.get_loc("HA_Open")] = (df.iloc[0]['Open'] + df.iloc[0]['Close'])/2
df['HA_High'] = df[['High', 'Low', 'HA_Open', 'HA_Clos... |
40,613,480 | [](https://i.stack.imgur.com/vIEKx.png)
I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis.
I was writing a function on it using Pandas but finding little difficulty.
This is how Heiken Ashi [HA] looks li... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7053990/"
] | I adjusted the code to make it work with Python 3.7
```
def HA(df):
df_HA = df
df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
#idx = df_HA.index.name
#df_HA.reset_index(inplace=True)
for i in range(0, len(df)):
if i == 0:
df_HA['Open'][i]= ( (df['Open'][i] + ... | ```
def HA(df):
df_HA = df
df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
for i in range(0, len(df)):
if i == 0:
df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2)
else:
df_HA['Open'][i] = ( (df['Open'][i-1] + df['Close'][i-1] )/ 2)
df_H... |
40,613,480 | [](https://i.stack.imgur.com/vIEKx.png)
I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis.
I was writing a function on it using Pandas but finding little difficulty.
This is how Heiken Ashi [HA] looks li... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7053990/"
] | Here is the fastest, accurate and efficient implementation as per my tests:
```
def HA(df):
df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
idx = df.index.name
df.reset_index(inplace=True)
for i in range(0, len(df)):
if i == 0:
df.set_value(i, 'HA_Open', ((df.get_... | Perfectly working HekinAshi function.
I am not the original author of this code. I found this on Github (<https://github.com/emreturan/heikin-ashi/blob/master/heikin_ashi.py>)
```
def heikin_ashi(df):
heikin_ashi_df = pd.DataFrame(index=df.index.values, columns=['open', 'high', 'low', 'close'])
heikin_ash... |
40,613,480 | [](https://i.stack.imgur.com/vIEKx.png)
I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis.
I was writing a function on it using Pandas but finding little difficulty.
This is how Heiken Ashi [HA] looks li... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7053990/"
] | Here is the fastest, accurate and efficient implementation as per my tests:
```
def HA(df):
df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
idx = df.index.name
df.reset_index(inplace=True)
for i in range(0, len(df)):
if i == 0:
df.set_value(i, 'HA_Open', ((df.get_... | I adjusted the code to make it work with Python 3.7
```
def HA(df):
df_HA = df
df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
#idx = df_HA.index.name
#df_HA.reset_index(inplace=True)
for i in range(0, len(df)):
if i == 0:
df_HA['Open'][i]= ( (df['Open'][i] + ... |
40,613,480 | [](https://i.stack.imgur.com/vIEKx.png)
I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis.
I was writing a function on it using Pandas but finding little difficulty.
This is how Heiken Ashi [HA] looks li... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7053990/"
] | **No Loop Solution for DataFrames**
This was the simplest, easy to understand, no-loop solution I could come up with for **dataframes**.
* Temporarily store Heikin-Ashi output in 'o', 'h', 'l', 'c' columns
* 'h' based on yesterday's values so we can use `.shift(1)` and copy the first entry
* Replace 'Open', 'High', '... | **Fastest solution I found.**
```
def HA(df):
df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
idx = df.index.name
df.reset_index(inplace=True)
ha_close_values = self.data['HA_Close'].values
length = len(df)
ha_open = np.zeros(length, dtype=float)
ha_open[0] = (df['Open']... |
40,613,480 | [](https://i.stack.imgur.com/vIEKx.png)
I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis.
I was writing a function on it using Pandas but finding little difficulty.
This is how Heiken Ashi [HA] looks li... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7053990/"
] | ```
def HA(df):
df_HA = df
df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
for i in range(0, len(df)):
if i == 0:
df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2)
else:
df_HA['Open'][i] = ( (df['Open'][i-1] + df['Close'][i-1] )/ 2)
df_H... | **Fastest solution I found.**
```
def HA(df):
df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
idx = df.index.name
df.reset_index(inplace=True)
ha_close_values = self.data['HA_Close'].values
length = len(df)
ha_open = np.zeros(length, dtype=float)
ha_open[0] = (df['Open']... |
40,613,480 | [](https://i.stack.imgur.com/vIEKx.png)
I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis.
I was writing a function on it using Pandas but finding little difficulty.
This is how Heiken Ashi [HA] looks li... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7053990/"
] | Here is the fastest, accurate and efficient implementation as per my tests:
```
def HA(df):
df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
idx = df.index.name
df.reset_index(inplace=True)
for i in range(0, len(df)):
if i == 0:
df.set_value(i, 'HA_Open', ((df.get_... | **Fastest solution I found.**
```
def HA(df):
df['HA_Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
idx = df.index.name
df.reset_index(inplace=True)
ha_close_values = self.data['HA_Close'].values
length = len(df)
ha_open = np.zeros(length, dtype=float)
ha_open[0] = (df['Open']... |
40,613,480 | [](https://i.stack.imgur.com/vIEKx.png)
I was defining a function Heiken Ashi which is one of the popular chart type in Technical Analysis.
I was writing a function on it using Pandas but finding little difficulty.
This is how Heiken Ashi [HA] looks li... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40613480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7053990/"
] | ```
def heikenashi(df):
df['HA_Close'] = (df['Open'] + df['High'] + df['Low'] + df['Close']) / 4
df['HA_Open'] = (df['Open'].shift(1) + df['Open'].shift(1)) / 2
df.iloc[0, df.columns.get_loc("HA_Open")] = (df.iloc[0]['Open'] + df.iloc[0]['Close'])/2
df['HA_High'] = df[['High', 'Low', 'HA_Open', 'HA_Clos... | ```
def HA(df):
df_HA = df
df_HA['Close']=(df['Open']+ df['High']+ df['Low']+df['Close'])/4
for i in range(0, len(df)):
if i == 0:
df_HA['Open'][i]= ( (df['Open'][i] + df['Close'][i] )/ 2)
else:
df_HA['Open'][i] = ( (df['Open'][i-1] + df['Close'][i-1] )/ 2)
df_H... |
37,187,962 | I have problem with python selenium phantomjs which i couldn't solve. element.location returns wrong location. when I see cropped image it is showing part of desired image and also unwanted one. It worked on firefox perfectly but doesn't work on phantomjs.
Here is code:
```
def screenOfElement(self, _element):
_l... | 2016/05/12 | [
"https://Stackoverflow.com/questions/37187962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3425211/"
] | You can use square brackets to create a reference to an array:
```
pass_in( $str, [qw(A B C D E)]);
```
[perldoc perlref](http://perldoc.perl.org/perlref.html#Making-References) | In order to pass an in array, you have must an array to pass!
`qw()` does not create an array. It just puts a bunch of scalars on the stack. That for which you are looking is `[ ]`. It conveniently creates an array, initializes the array using the expression within, and returns a reference to the array.
```
pass_in( ... |
23,183,868 | I was going through a very simple python3 guide to using string operations and then I ran into this weird error:
```
In [4]: # create string
string = 'Let\'s test this.'
# test to see if it is numeric
string_isnumeric = string.isnumeric()
Out [4]: AttributeError Tra... | 2014/04/20 | [
"https://Stackoverflow.com/questions/23183868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2935984/"
] | No, `str` objects do not have an `isnumeric` method. `isnumeric` is only available for unicode objects. In other words:
```
>>> d = unicode('some string', 'utf-8')
>>> d.isnumeric()
False
>>> d = unicode('42', 'utf-8')
>>> d.isnumeric()
True
``` | `isnumeric()` only works on Unicode strings. To define a string as Unicode you could change your string definitions like so:
```
In [4]:
s = u'This is my string'
isnum = s.isnumeric()
```
This will now store False.
Note: I also changed your variable name in case you imported the module string. |
23,183,868 | I was going through a very simple python3 guide to using string operations and then I ran into this weird error:
```
In [4]: # create string
string = 'Let\'s test this.'
# test to see if it is numeric
string_isnumeric = string.isnumeric()
Out [4]: AttributeError Tra... | 2014/04/20 | [
"https://Stackoverflow.com/questions/23183868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2935984/"
] | `isnumeric()` only works on Unicode strings. To define a string as Unicode you could change your string definitions like so:
```
In [4]:
s = u'This is my string'
isnum = s.isnumeric()
```
This will now store False.
Note: I also changed your variable name in case you imported the module string. | if using python 3 wrap string around **str** as shown below
>
> str('hello').isnumeric()
>
>
>
This way it behaving as expected |
23,183,868 | I was going through a very simple python3 guide to using string operations and then I ran into this weird error:
```
In [4]: # create string
string = 'Let\'s test this.'
# test to see if it is numeric
string_isnumeric = string.isnumeric()
Out [4]: AttributeError Tra... | 2014/04/20 | [
"https://Stackoverflow.com/questions/23183868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2935984/"
] | No, `str` objects do not have an `isnumeric` method. `isnumeric` is only available for unicode objects. In other words:
```
>>> d = unicode('some string', 'utf-8')
>>> d.isnumeric()
False
>>> d = unicode('42', 'utf-8')
>>> d.isnumeric()
True
``` | One Liners:
```
unicode('200', 'utf-8').isnumeric() # True
unicode('unicorn121', 'utf-8').isnumeric() # False
```
Or
```
unicode('200').isnumeric() # True
unicode('unicorn121').isnumeric() # False
``` |
23,183,868 | I was going through a very simple python3 guide to using string operations and then I ran into this weird error:
```
In [4]: # create string
string = 'Let\'s test this.'
# test to see if it is numeric
string_isnumeric = string.isnumeric()
Out [4]: AttributeError Tra... | 2014/04/20 | [
"https://Stackoverflow.com/questions/23183868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2935984/"
] | No, `str` objects do not have an `isnumeric` method. `isnumeric` is only available for unicode objects. In other words:
```
>>> d = unicode('some string', 'utf-8')
>>> d.isnumeric()
False
>>> d = unicode('42', 'utf-8')
>>> d.isnumeric()
True
``` | if using python 3 wrap string around **str** as shown below
>
> str('hello').isnumeric()
>
>
>
This way it behaving as expected |
23,183,868 | I was going through a very simple python3 guide to using string operations and then I ran into this weird error:
```
In [4]: # create string
string = 'Let\'s test this.'
# test to see if it is numeric
string_isnumeric = string.isnumeric()
Out [4]: AttributeError Tra... | 2014/04/20 | [
"https://Stackoverflow.com/questions/23183868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2935984/"
] | One Liners:
```
unicode('200', 'utf-8').isnumeric() # True
unicode('unicorn121', 'utf-8').isnumeric() # False
```
Or
```
unicode('200').isnumeric() # True
unicode('unicorn121').isnumeric() # False
``` | if using python 3 wrap string around **str** as shown below
>
> str('hello').isnumeric()
>
>
>
This way it behaving as expected |
46,257,064 | I'm trying to create a piece of code in python that allows the user to enter their username, password and date of birth and then allows them to change this information. This is what I have so far.
```
import sqlite3
conn=sqlite3.connect("Database.db")
cursor=conn.cursor()
def createTable():
cursor.execute("CREAT... | 2017/09/16 | [
"https://Stackoverflow.com/questions/46257064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8619721/"
] | When I've copied it and run the first error that occurred said that variable `user` is not defined. Therefore you need to either send it to function `modifyData` from `enterData` or ask the user for it.
Then I've got the error you've mentioned. Just remove the single quotes around `?`
Code:
```
def modify_data():
... | You probably want `raw_input`, not `input`.
`raw_input` reads data from standard input and returns it. `input()` is equivelant to `eval(raw_input())`: i.e., it evaluates the input as Python code.
I'm not 100% sure if this is your root problem though, if you've already been using quotes around your input? Or maybe you... |
67,670,537 | I have an Amazon S3 server filled with multiple buckets, each bucket containing multiple subfolders. There are easily 50,000 files in total. I need to generate an excel sheet that contains the path/url of each file in each bucket.
For eg, If I have a bucket called b1, and it has a file called f1.txt, I want to be able... | 2021/05/24 | [
"https://Stackoverflow.com/questions/67670537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8018877/"
] | Do you have access to the aws cli? `aws s3 ls --recursive {bucket}` will list all nested files in a bucket.
Eg this bash command will list all buckets, then recursively print all files in each bucket:
```
aws s3 ls | while read x y bucket; do aws s3 ls --recursive $bucket | while read x y z path; do echo $path; done;... | Amazon s3 inventory can help you with this use case.
Do evaluate that option. refer: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/storage-inventory.html> |
67,670,537 | I have an Amazon S3 server filled with multiple buckets, each bucket containing multiple subfolders. There are easily 50,000 files in total. I need to generate an excel sheet that contains the path/url of each file in each bucket.
For eg, If I have a bucket called b1, and it has a file called f1.txt, I want to be able... | 2021/05/24 | [
"https://Stackoverflow.com/questions/67670537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8018877/"
] | What you should do is have a look again at boto3 documentation as it is what you are looking for. It is fairly simple to do what you are asking but may take you a bit of reading if you are new to it. Since there is multiple steps involved I will try to steer you in the right direction.
In boto3 for S3 the method you a... | Amazon s3 inventory can help you with this use case.
Do evaluate that option. refer: <https://docs.aws.amazon.com/AmazonS3/latest/userguide/storage-inventory.html> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.