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 |
|---|---|---|---|---|---|
48,729,915 | I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library.
However, I am would rather restrict my usage of external libraries to `sci... | 2018/02/11 | [
"https://Stackoverflow.com/questions/48729915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5495304/"
] | >
> If you just want to **read an image in Python** using the specified
> libraries only, I will go with `matplotlib`
>
>
>
**In matplotlib :**
```
import matplotlib.image
read_img = matplotlib.image.imread('your_image.png')
``` | I read all answers but I think one of the best method is using [openCV](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_image_display/py_image_display.html) library.
```
import cv2
img = cv2.imread('your_image.png',0)
```
and for displaying the image, use the following code :
```
fr... |
48,729,915 | I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library.
However, I am would rather restrict my usage of external libraries to `sci... | 2018/02/11 | [
"https://Stackoverflow.com/questions/48729915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5495304/"
] | With matplotlib you can use (as shown in the matplotlib [documentation](https://matplotlib.org/2.0.0/users/image_tutorial.html))
```
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('image_name.png')
```
And plot the image if you want
```
imgplot = plt.imshow(img)
``` | For the better answer, you can use these lines of code.
Here is the example maybe help you :
```
import cv2
image = cv2.imread('/home/pictures/1.jpg')
plt.imshow(image)
plt.show()
```
In **`imread()`** you can pass the directory .so you can also use `str()` and `+` to combine dynamic directories and fixed director... |
34,086,675 | I would like to slice an array `a` in Julia in a loop in such a way that it's divided in chunks of `n` samples. The length of the array `nsamples` is *not* a multiple of `n`, so the last stride would be shorter.
My attempt would be using a ternary operator to check if the size of the stride is greater than the length... | 2015/12/04 | [
"https://Stackoverflow.com/questions/34086675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277113/"
] | The `end` keyword is only given this kind of special treatment inside of indexing expressions, where it evaluates to the last index of the dimension being indexed. You could put it inside with e.g.
```
for i in 0:n:nsamples-1
window = a[i+1:min(i+n, end)]
end
```
Or you could just use `length(a)` (or `nsamples`,... | Ugly way:
```
a=rand(7);
nsamples=7;
n=3;
for i in 0:n:nsamples-1
end_ = i+n < nsamples ? i+n : :end
window = @eval a[$i+1:$end_]
println(window)
end
```
Better solution:
```
for i in 0:n:nsamples-1
window = i+n < nsamples ? a[i+1:i+n] : a[i+1:end]
println(window)
end
``` |
34,086,675 | I would like to slice an array `a` in Julia in a loop in such a way that it's divided in chunks of `n` samples. The length of the array `nsamples` is *not* a multiple of `n`, so the last stride would be shorter.
My attempt would be using a ternary operator to check if the size of the stride is greater than the length... | 2015/12/04 | [
"https://Stackoverflow.com/questions/34086675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277113/"
] | Ugly way:
```
a=rand(7);
nsamples=7;
n=3;
for i in 0:n:nsamples-1
end_ = i+n < nsamples ? i+n : :end
window = @eval a[$i+1:$end_]
println(window)
end
```
Better solution:
```
for i in 0:n:nsamples-1
window = i+n < nsamples ? a[i+1:i+n] : a[i+1:end]
println(window)
end
``` | In order to simplify the loop (and perhaps improve performance) the last partial window can be processed after the loop. This is recommended since it usually requires some special processing anyway. In code:
```
i = 0 # define loop variable outside for to retain it after
for i=n:n:length(a)
println(a[(i-n+1):i])
e... |
34,086,675 | I would like to slice an array `a` in Julia in a loop in such a way that it's divided in chunks of `n` samples. The length of the array `nsamples` is *not* a multiple of `n`, so the last stride would be shorter.
My attempt would be using a ternary operator to check if the size of the stride is greater than the length... | 2015/12/04 | [
"https://Stackoverflow.com/questions/34086675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277113/"
] | The `end` keyword is only given this kind of special treatment inside of indexing expressions, where it evaluates to the last index of the dimension being indexed. You could put it inside with e.g.
```
for i in 0:n:nsamples-1
window = a[i+1:min(i+n, end)]
end
```
Or you could just use `length(a)` (or `nsamples`,... | In order to simplify the loop (and perhaps improve performance) the last partial window can be processed after the loop. This is recommended since it usually requires some special processing anyway. In code:
```
i = 0 # define loop variable outside for to retain it after
for i=n:n:length(a)
println(a[(i-n+1):i])
e... |
43,721,155 | I'm trying to close each image opened via iteration, within each iteration.
I've referred to this thread below, but the correct answer is not producing the results.
[How do I close an image opened in Pillow?](https://stackoverflow.com/questions/31751464/how-do-i-close-an-image-opened-in-pillow)
My code
```
for i ... | 2017/05/01 | [
"https://Stackoverflow.com/questions/43721155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6802252/"
] | Got it working, but I installed a different image viewer on Windows as I couldn't find the .exe of the default viewer.
```
import webbrowser
import subprocess
import os, time
for i in Final_Bioteck[6:11]:
webbrowser.open( '{}.png'.format(i)) # opens the pic
time.sleep(3)
subprocess.run(['task... | In Windows 10, the process is dllhost.exe
using the same script as Moondra, except with "dllhost.exe" instead of "i\_view64.exe"
```
import webbrowser
import subprocess
import os, time
for i in Final_Bioteck[6:11]:
webbrowser.open( '{}.png'.format(i)) # opens the pic
time.sleep(3)
subprocess.run(['taskki... |
32,004,317 | I am working on a python GUI for serial communication with some hardware.I am using USB-RS232 converter for that.I do'nt want user to look for com port of hardware in device manager and then select port no in GUI for communication.How can my python code automatically get the port no. for that particular USB port?I can ... | 2015/08/14 | [
"https://Stackoverflow.com/questions/32004317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5036147/"
] | pyserial can list the ports with their USB VID:PID numbers.
```
from serial.tools import list_ports
list_ports.comports()
```
This function returns a tuple, 3rd item is a string that may contain the USB VID:PID number. You can parse it from there. Or better, you can use the `grep` function also provided by `list_por... | I assume that you are specifically looking for a COM port that is described as being a USB to RS232 in the device manager, rather than wanting to list all available COM ports?
Also, you have not mentioned what OS you are developing on, or the version of Python you are using, but this works for me on a Windows system u... |
14,004,839 | I have Flask, Babel and Flask-Babel installed in the global packages.
When running python and I type this, no error
```
>>> from flaskext.babel import Babel
>>>
```
With a virtual environment, starting python and typing the same command I see
```
>>> from flaskext.babel import Babel
Traceback (most recent call las... | 2012/12/22 | [
"https://Stackoverflow.com/questions/14004839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75517/"
] | I think you're supposed to import Flask extensions like the following from version 0.8 onwards:
```
from flask.ext.babel import Babel
```
I tried the old way (`import flaskext.babel`), and it didn't work for me either. | The old way of importing Flask extension was like:
```
import flaskext.babel
```
[Namespace packages](https://stackoverflow.com/questions/1675734/how-do-i-create-a-namespace-package-in-python) were, however, "too painful for everybody involved", so now Flask extensions should be importable like:
```
import flask_ba... |
14,004,839 | I have Flask, Babel and Flask-Babel installed in the global packages.
When running python and I type this, no error
```
>>> from flaskext.babel import Babel
>>>
```
With a virtual environment, starting python and typing the same command I see
```
>>> from flaskext.babel import Babel
Traceback (most recent call las... | 2012/12/22 | [
"https://Stackoverflow.com/questions/14004839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75517/"
] | Yeah! I solved the problem!
Creating an empty \_*init*\_py in the global Lib/site-packages/flaskext next to the babel.py file solves the problem.
Importing Babel from the local environment now works as expected and as it worked in the global environment.
We can use the two forms *from flaskext.babel import Babel* ... | I think you're supposed to import Flask extensions like the following from version 0.8 onwards:
```
from flask.ext.babel import Babel
```
I tried the old way (`import flaskext.babel`), and it didn't work for me either. |
14,004,839 | I have Flask, Babel and Flask-Babel installed in the global packages.
When running python and I type this, no error
```
>>> from flaskext.babel import Babel
>>>
```
With a virtual environment, starting python and typing the same command I see
```
>>> from flaskext.babel import Babel
Traceback (most recent call las... | 2012/12/22 | [
"https://Stackoverflow.com/questions/14004839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75517/"
] | I think you're supposed to import Flask extensions like the following from version 0.8 onwards:
```
from flask.ext.babel import Babel
```
I tried the old way (`import flaskext.babel`), and it didn't work for me either. | for python 3 install like this: **pip install Flask-Babel**
after installing import like this :**from flask.ext.babel import Babel** but do note you will get the deprecation warning so you can import like this :**from flask\_babel import Babel** |
14,004,839 | I have Flask, Babel and Flask-Babel installed in the global packages.
When running python and I type this, no error
```
>>> from flaskext.babel import Babel
>>>
```
With a virtual environment, starting python and typing the same command I see
```
>>> from flaskext.babel import Babel
Traceback (most recent call las... | 2012/12/22 | [
"https://Stackoverflow.com/questions/14004839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75517/"
] | Yeah! I solved the problem!
Creating an empty \_*init*\_py in the global Lib/site-packages/flaskext next to the babel.py file solves the problem.
Importing Babel from the local environment now works as expected and as it worked in the global environment.
We can use the two forms *from flaskext.babel import Babel* ... | The old way of importing Flask extension was like:
```
import flaskext.babel
```
[Namespace packages](https://stackoverflow.com/questions/1675734/how-do-i-create-a-namespace-package-in-python) were, however, "too painful for everybody involved", so now Flask extensions should be importable like:
```
import flask_ba... |
14,004,839 | I have Flask, Babel and Flask-Babel installed in the global packages.
When running python and I type this, no error
```
>>> from flaskext.babel import Babel
>>>
```
With a virtual environment, starting python and typing the same command I see
```
>>> from flaskext.babel import Babel
Traceback (most recent call las... | 2012/12/22 | [
"https://Stackoverflow.com/questions/14004839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75517/"
] | The old way of importing Flask extension was like:
```
import flaskext.babel
```
[Namespace packages](https://stackoverflow.com/questions/1675734/how-do-i-create-a-namespace-package-in-python) were, however, "too painful for everybody involved", so now Flask extensions should be importable like:
```
import flask_ba... | for python 3 install like this: **pip install Flask-Babel**
after installing import like this :**from flask.ext.babel import Babel** but do note you will get the deprecation warning so you can import like this :**from flask\_babel import Babel** |
14,004,839 | I have Flask, Babel and Flask-Babel installed in the global packages.
When running python and I type this, no error
```
>>> from flaskext.babel import Babel
>>>
```
With a virtual environment, starting python and typing the same command I see
```
>>> from flaskext.babel import Babel
Traceback (most recent call las... | 2012/12/22 | [
"https://Stackoverflow.com/questions/14004839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75517/"
] | Yeah! I solved the problem!
Creating an empty \_*init*\_py in the global Lib/site-packages/flaskext next to the babel.py file solves the problem.
Importing Babel from the local environment now works as expected and as it worked in the global environment.
We can use the two forms *from flaskext.babel import Babel* ... | for python 3 install like this: **pip install Flask-Babel**
after installing import like this :**from flask.ext.babel import Babel** but do note you will get the deprecation warning so you can import like this :**from flask\_babel import Babel** |
46,515,990 | Can somebody please help me to create a python program whereby the unsorted list is split up into groups of 2, arranged alphabetically within their groups of two. The program should then create a new list in alphabetical order by taking the next greatest letter from the correct pair. Please don't tell me to do this in ... | 2017/10/01 | [
"https://Stackoverflow.com/questions/46515990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8705227/"
] | In your code, openin tag `<tr>` is not added to first `<td>`. You are appending html twice. You need to form correct html then add it to the table after for loop. Also you don't need ';' commas at the end of condition and standart function definition code blocks.
```js
function myFunction() {
var response = "[\r\n ... | Thought I would offer a different solution.
<https://jsfiddle.net/wfc9p0e8/>
```
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<style>
#table{ display: table; width:100%; }
#table .table-cell { display: inline-table; width:33.33%; }
<... |
38,145,706 | I'm using PyInstaller 3.2 to package a Web.py app. Typically, with Web.py and the built-in WSGI [server](http://webpy.org/cookbook/ssl), you specify the port on the command line, like
```
$ python main.py 8091
```
Would run the Web.py app on port 8091 (default is 8080). I'm bundling the app with PyInstaller via a sp... | 2016/07/01 | [
"https://Stackoverflow.com/questions/38145706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1370384/"
] | So very hacky, but what I wound up doing was to just append an argument in `sys.argv` in my web.py app...
```
sys.argv.append('8888')
app.run()
```
I also thought in my `spec` file I could just do:
```
a = Analysis(['main.py 8888'],
```
But that didn't work at all. | `options` argument in EXE is only for the python interpreter ([ref](https://pythonhosted.org/PyInstaller/spec-files.html#giving-run-time-python-options)) |
65,919,766 | I am using python 3.8.3 version.
I installed folium typing `pip install folium` in the command line. After typing `pip show folium` in the command line, the output is as follows:
```
Name: folium
Version: 0.12.1
Summary: Make beautiful maps with Leaflet.js & Python
Home-page: https://github.com/python-visualization/fo... | 2021/01/27 | [
"https://Stackoverflow.com/questions/65919766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14127138/"
] | Avoiding this kind of errors, always use virtualenv.
Take a look here
<https://docs.python.org/3/library/venv.html> | Try restarting VSCode, sometimes the python extension needs a restart so newly installed modules are indexed.
You can try running the code despite the Error in VSCode. It works if you can confirm that the required module is properly installed. |
65,919,766 | I am using python 3.8.3 version.
I installed folium typing `pip install folium` in the command line. After typing `pip show folium` in the command line, the output is as follows:
```
Name: folium
Version: 0.12.1
Summary: Make beautiful maps with Leaflet.js & Python
Home-page: https://github.com/python-visualization/fo... | 2021/01/27 | [
"https://Stackoverflow.com/questions/65919766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14127138/"
] | Avoiding this kind of errors, always use virtualenv.
Take a look here
<https://docs.python.org/3/library/venv.html> | Can you open python in command line and type
```
>>> import folium
```
In my case I got error as I don't have it installed. If you get error on command line, it means module was not installed.
[CMD screenshot](https://i.stack.imgur.com/AuLUy.png) |
65,919,766 | I am using python 3.8.3 version.
I installed folium typing `pip install folium` in the command line. After typing `pip show folium` in the command line, the output is as follows:
```
Name: folium
Version: 0.12.1
Summary: Make beautiful maps with Leaflet.js & Python
Home-page: https://github.com/python-visualization/fo... | 2021/01/27 | [
"https://Stackoverflow.com/questions/65919766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14127138/"
] | Try restarting VSCode, sometimes the python extension needs a restart so newly installed modules are indexed.
You can try running the code despite the Error in VSCode. It works if you can confirm that the required module is properly installed. | Can you open python in command line and type
```
>>> import folium
```
In my case I got error as I don't have it installed. If you get error on command line, it means module was not installed.
[CMD screenshot](https://i.stack.imgur.com/AuLUy.png) |
65,919,766 | I am using python 3.8.3 version.
I installed folium typing `pip install folium` in the command line. After typing `pip show folium` in the command line, the output is as follows:
```
Name: folium
Version: 0.12.1
Summary: Make beautiful maps with Leaflet.js & Python
Home-page: https://github.com/python-visualization/fo... | 2021/01/27 | [
"https://Stackoverflow.com/questions/65919766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14127138/"
] | Your package seems to be installed in `c:\users\koryun\appdata\local\programs\python\python38-32\lib\site-packages`.
Check out where is your Python looking for installed packages by running this Python program:
```
import sys
print(sys.path)
```
If there is not aforementioned path present, then you have to add it, ... | Try restarting VSCode, sometimes the python extension needs a restart so newly installed modules are indexed.
You can try running the code despite the Error in VSCode. It works if you can confirm that the required module is properly installed. |
65,919,766 | I am using python 3.8.3 version.
I installed folium typing `pip install folium` in the command line. After typing `pip show folium` in the command line, the output is as follows:
```
Name: folium
Version: 0.12.1
Summary: Make beautiful maps with Leaflet.js & Python
Home-page: https://github.com/python-visualization/fo... | 2021/01/27 | [
"https://Stackoverflow.com/questions/65919766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14127138/"
] | Your package seems to be installed in `c:\users\koryun\appdata\local\programs\python\python38-32\lib\site-packages`.
Check out where is your Python looking for installed packages by running this Python program:
```
import sys
print(sys.path)
```
If there is not aforementioned path present, then you have to add it, ... | Can you open python in command line and type
```
>>> import folium
```
In my case I got error as I don't have it installed. If you get error on command line, it means module was not installed.
[CMD screenshot](https://i.stack.imgur.com/AuLUy.png) |
62,339,871 | **The question is this:**
We add a Leap Day on February 29, almost every four years. The leap day is an extra, or intercalary day and we add it to the shortest month of the year, February.
In the Gregorian calendar three criteria must be taken into account to identify leap years:
The year can be evenly divided by 4, ... | 2020/06/12 | [
"https://Stackoverflow.com/questions/62339871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13732680/"
] | First of all, you are using bitwise operators **|** and **&** (you can read about it here - <https://www.educative.io/edpresso/what-are-bitwise-operators-in-python>), but you need to use logical operators, such as **or** and **and**.
Also, your code can be simplified:
```
def is_leap(year):
return (year % 4 == 0)... | try this:
```
def leap_year(n):
if (n%100==0 and n%400==0):
return True
elif (n%4==0 and n%100!=0):
return True
else:
return False
``` |
42,742,499 | PEP [3141](https://www.python.org/dev/peps/pep-3141/) defines a numerical hierarchy with `Complex.__add__` but no `Number.__add__`. This seems to be a weird choice, since the other numeric type `Decimal` that (virtually) derives from `Number` also implements an add method.
So why is it this way? If I want to add type ... | 2017/03/12 | [
"https://Stackoverflow.com/questions/42742499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4133053/"
] | Its because you are increamenting two times in the loop.
Remove the last i++ and it works fine. | The form of this for loop is to always increment the counter variable after the final statement or function has executed or returned, respectively. So, any incrementation of 'i' in the loop body, in this case, will add 1 to the value of the for loop counter, corrupting the count. |
42,742,499 | PEP [3141](https://www.python.org/dev/peps/pep-3141/) defines a numerical hierarchy with `Complex.__add__` but no `Number.__add__`. This seems to be a weird choice, since the other numeric type `Decimal` that (virtually) derives from `Number` also implements an add method.
So why is it this way? If I want to add type ... | 2017/03/12 | [
"https://Stackoverflow.com/questions/42742499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4133053/"
] | Your problem is that you increment `i` twice. So, it will be 0, then 2, then 4, then 6, which is greater than 5.
In order to fix it, simply remove the `i++;` line after the `puts("Hello, World!");` or transform your `for` loop into a `while` loop.
### Solution 1
```
#include <stdio.h>
void hello_world(int n) {
f... | The form of this for loop is to always increment the counter variable after the final statement or function has executed or returned, respectively. So, any incrementation of 'i' in the loop body, in this case, will add 1 to the value of the for loop counter, corrupting the count. |
42,742,499 | PEP [3141](https://www.python.org/dev/peps/pep-3141/) defines a numerical hierarchy with `Complex.__add__` but no `Number.__add__`. This seems to be a weird choice, since the other numeric type `Decimal` that (virtually) derives from `Number` also implements an add method.
So why is it this way? If I want to add type ... | 2017/03/12 | [
"https://Stackoverflow.com/questions/42742499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4133053/"
] | Your problem is that you increment `i` twice. So, it will be 0, then 2, then 4, then 6, which is greater than 5.
In order to fix it, simply remove the `i++;` line after the `puts("Hello, World!");` or transform your `for` loop into a `while` loop.
### Solution 1
```
#include <stdio.h>
void hello_world(int n) {
f... | Its because you are increamenting two times in the loop.
Remove the last i++ and it works fine. |
59,600,235 | Tell me please, what am I doing wrong?
I try to drag and drop through Selenium, but every time I come across an error "AttributeError: move\_to requires a WebElement"
**Here is my code:**
```
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
chromedriver = '/usr/local/bi... | 2020/01/05 | [
"https://Stackoverflow.com/questions/59600235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9729098/"
] | `find_elements_by_xpath` returns a list of `WebElement`s, `drag_and_drop` (and the other methods) accept a single `WebElement`. Use `find_element_by_xpath`
```
source = driver.find_element_by_xpath('//*[@id="box3"]')
target = driver.find_element_by_xpath('//*[@id="box103"]')
``` | as @guy said:
```
find_elements_by_xpath
```
returns list of `WebElements`. You can use `find_element_by_xpath` method to get single web element. Or select specific element from `WebElements` return by `find_elements_by_xpath`. For example, if you know, you wanted to select 2nd element from return list for target. T... |
59,600,235 | Tell me please, what am I doing wrong?
I try to drag and drop through Selenium, but every time I come across an error "AttributeError: move\_to requires a WebElement"
**Here is my code:**
```
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
chromedriver = '/usr/local/bi... | 2020/01/05 | [
"https://Stackoverflow.com/questions/59600235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9729098/"
] | `find_elements_by_xpath` returns a list of `WebElement`s, `drag_and_drop` (and the other methods) accept a single `WebElement`. Use `find_element_by_xpath`
```
source = driver.find_element_by_xpath('//*[@id="box3"]')
target = driver.find_element_by_xpath('//*[@id="box103"]')
``` | This error message...
```
AttributeError: move_to requires a WebElement
```
...implies that the `move_to_element()` requires a *WebElement* as an argument.
Seems you were close. You have used `find_elements_by_xpath()` which returns a *List* where as you need pass a *WebElement* within `move_to_element()`.
Solutio... |
59,600,235 | Tell me please, what am I doing wrong?
I try to drag and drop through Selenium, but every time I come across an error "AttributeError: move\_to requires a WebElement"
**Here is my code:**
```
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
chromedriver = '/usr/local/bi... | 2020/01/05 | [
"https://Stackoverflow.com/questions/59600235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9729098/"
] | `find_elements_by_xpath` returns a list of `WebElement`s, `drag_and_drop` (and the other methods) accept a single `WebElement`. Use `find_element_by_xpath`
```
source = driver.find_element_by_xpath('//*[@id="box3"]')
target = driver.find_element_by_xpath('//*[@id="box103"]')
``` | use `find_elements_by_xpath` instead `find_element_by_xpath` |
59,600,235 | Tell me please, what am I doing wrong?
I try to drag and drop through Selenium, but every time I come across an error "AttributeError: move\_to requires a WebElement"
**Here is my code:**
```
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
chromedriver = '/usr/local/bi... | 2020/01/05 | [
"https://Stackoverflow.com/questions/59600235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9729098/"
] | as @guy said:
```
find_elements_by_xpath
```
returns list of `WebElements`. You can use `find_element_by_xpath` method to get single web element. Or select specific element from `WebElements` return by `find_elements_by_xpath`. For example, if you know, you wanted to select 2nd element from return list for target. T... | This error message...
```
AttributeError: move_to requires a WebElement
```
...implies that the `move_to_element()` requires a *WebElement* as an argument.
Seems you were close. You have used `find_elements_by_xpath()` which returns a *List* where as you need pass a *WebElement* within `move_to_element()`.
Solutio... |
59,600,235 | Tell me please, what am I doing wrong?
I try to drag and drop through Selenium, but every time I come across an error "AttributeError: move\_to requires a WebElement"
**Here is my code:**
```
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
chromedriver = '/usr/local/bi... | 2020/01/05 | [
"https://Stackoverflow.com/questions/59600235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9729098/"
] | as @guy said:
```
find_elements_by_xpath
```
returns list of `WebElements`. You can use `find_element_by_xpath` method to get single web element. Or select specific element from `WebElements` return by `find_elements_by_xpath`. For example, if you know, you wanted to select 2nd element from return list for target. T... | use `find_elements_by_xpath` instead `find_element_by_xpath` |
19,939,365 | I'm trying to install a module called Scrapy. I installed it using
```
pip install Scrapy
```
I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening?
EDIT: Here is t... | 2013/11/12 | [
"https://Stackoverflow.com/questions/19939365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191726/"
] | Are you using Homebrew or MacPorts or something? As @J.F.Sebastian said, it sounds like you are having issues mixing the default python that comes with OS X, and one that is installed via a package manager... Try `/usr/local/opt/python/bin/python2.7 -m scrapy` and see if that throws an `ImportError`.
If that works, th... | EDIT: You can force pip to install to an alternate location. The details are here: [Install a Python package into a different directory using pip?](https://stackoverflow.com/questions/2915471/install-a-python-package-into-a-different-directory-using-pip). If you do indeed have extra Python folders on your system, maybe... |
19,939,365 | I'm trying to install a module called Scrapy. I installed it using
```
pip install Scrapy
```
I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening?
EDIT: Here is t... | 2013/11/12 | [
"https://Stackoverflow.com/questions/19939365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191726/"
] | EDIT: You can force pip to install to an alternate location. The details are here: [Install a Python package into a different directory using pip?](https://stackoverflow.com/questions/2915471/install-a-python-package-into-a-different-directory-using-pip). If you do indeed have extra Python folders on your system, maybe... | if you run on Ubuntu:
>
> use the official [Ubuntu Packages](http://doc.scrapy.org/en/latest/topics/ubuntu.html#topics-ubuntu), which already solve all dependencies for you and are continuously updated with the latest bug fixes.
>
>
>
Optionally, even if it solves your problem, it is always better to install pyth... |
19,939,365 | I'm trying to install a module called Scrapy. I installed it using
```
pip install Scrapy
```
I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening?
EDIT: Here is t... | 2013/11/12 | [
"https://Stackoverflow.com/questions/19939365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191726/"
] | EDIT: You can force pip to install to an alternate location. The details are here: [Install a Python package into a different directory using pip?](https://stackoverflow.com/questions/2915471/install-a-python-package-into-a-different-directory-using-pip). If you do indeed have extra Python folders on your system, maybe... | When all else fails you can always set the environment variable PYTHONPATH (see [Permanently add a directory to PYTHONPATH](https://stackoverflow.com/questions/3402168/permanently-add-a-directory-to-pythonpath) for help) to the path where you installed Scrapy. (pending you're not using virtualenv -- and if you are plea... |
19,939,365 | I'm trying to install a module called Scrapy. I installed it using
```
pip install Scrapy
```
I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening?
EDIT: Here is t... | 2013/11/12 | [
"https://Stackoverflow.com/questions/19939365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191726/"
] | EDIT: You can force pip to install to an alternate location. The details are here: [Install a Python package into a different directory using pip?](https://stackoverflow.com/questions/2915471/install-a-python-package-into-a-different-directory-using-pip). If you do indeed have extra Python folders on your system, maybe... | It appears that the scrapy module that is installed on the Python path is an executable file that will bootstrap a Scrapy project directory for you.
The Python code in the [scrapy executable](https://github.com/scrapy/scrapy/blob/master/bin/scrapy) looks like this:
```
#!/usr/bin/env python
from scrapy.cmdline... |
19,939,365 | I'm trying to install a module called Scrapy. I installed it using
```
pip install Scrapy
```
I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening?
EDIT: Here is t... | 2013/11/12 | [
"https://Stackoverflow.com/questions/19939365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191726/"
] | Are you using Homebrew or MacPorts or something? As @J.F.Sebastian said, it sounds like you are having issues mixing the default python that comes with OS X, and one that is installed via a package manager... Try `/usr/local/opt/python/bin/python2.7 -m scrapy` and see if that throws an `ImportError`.
If that works, th... | if you run on Ubuntu:
>
> use the official [Ubuntu Packages](http://doc.scrapy.org/en/latest/topics/ubuntu.html#topics-ubuntu), which already solve all dependencies for you and are continuously updated with the latest bug fixes.
>
>
>
Optionally, even if it solves your problem, it is always better to install pyth... |
19,939,365 | I'm trying to install a module called Scrapy. I installed it using
```
pip install Scrapy
```
I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening?
EDIT: Here is t... | 2013/11/12 | [
"https://Stackoverflow.com/questions/19939365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191726/"
] | Are you using Homebrew or MacPorts or something? As @J.F.Sebastian said, it sounds like you are having issues mixing the default python that comes with OS X, and one that is installed via a package manager... Try `/usr/local/opt/python/bin/python2.7 -m scrapy` and see if that throws an `ImportError`.
If that works, th... | When all else fails you can always set the environment variable PYTHONPATH (see [Permanently add a directory to PYTHONPATH](https://stackoverflow.com/questions/3402168/permanently-add-a-directory-to-pythonpath) for help) to the path where you installed Scrapy. (pending you're not using virtualenv -- and if you are plea... |
19,939,365 | I'm trying to install a module called Scrapy. I installed it using
```
pip install Scrapy
```
I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening?
EDIT: Here is t... | 2013/11/12 | [
"https://Stackoverflow.com/questions/19939365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191726/"
] | Are you using Homebrew or MacPorts or something? As @J.F.Sebastian said, it sounds like you are having issues mixing the default python that comes with OS X, and one that is installed via a package manager... Try `/usr/local/opt/python/bin/python2.7 -m scrapy` and see if that throws an `ImportError`.
If that works, th... | It appears that the scrapy module that is installed on the Python path is an executable file that will bootstrap a Scrapy project directory for you.
The Python code in the [scrapy executable](https://github.com/scrapy/scrapy/blob/master/bin/scrapy) looks like this:
```
#!/usr/bin/env python
from scrapy.cmdline... |
19,939,365 | I'm trying to install a module called Scrapy. I installed it using
```
pip install Scrapy
```
I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening?
EDIT: Here is t... | 2013/11/12 | [
"https://Stackoverflow.com/questions/19939365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191726/"
] | When all else fails you can always set the environment variable PYTHONPATH (see [Permanently add a directory to PYTHONPATH](https://stackoverflow.com/questions/3402168/permanently-add-a-directory-to-pythonpath) for help) to the path where you installed Scrapy. (pending you're not using virtualenv -- and if you are plea... | if you run on Ubuntu:
>
> use the official [Ubuntu Packages](http://doc.scrapy.org/en/latest/topics/ubuntu.html#topics-ubuntu), which already solve all dependencies for you and are continuously updated with the latest bug fixes.
>
>
>
Optionally, even if it solves your problem, it is always better to install pyth... |
19,939,365 | I'm trying to install a module called Scrapy. I installed it using
```
pip install Scrapy
```
I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening?
EDIT: Here is t... | 2013/11/12 | [
"https://Stackoverflow.com/questions/19939365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191726/"
] | When all else fails you can always set the environment variable PYTHONPATH (see [Permanently add a directory to PYTHONPATH](https://stackoverflow.com/questions/3402168/permanently-add-a-directory-to-pythonpath) for help) to the path where you installed Scrapy. (pending you're not using virtualenv -- and if you are plea... | It appears that the scrapy module that is installed on the Python path is an executable file that will bootstrap a Scrapy project directory for you.
The Python code in the [scrapy executable](https://github.com/scrapy/scrapy/blob/master/bin/scrapy) looks like this:
```
#!/usr/bin/env python
from scrapy.cmdline... |
64,483,669 | I am trying to make a multi-container docker app using `docker-compose`.
**Here's what I am trying to accomplish:** I have a python3 app, that takes a list of list of numbers as input from API call(`fastAPI` with gunicorn server) and pass the numbers to a function(an ML model actually) that returns a number, which wil... | 2020/10/22 | [
"https://Stackoverflow.com/questions/64483669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11814996/"
] | The problem are your labels.
They have the same ids as your input fields.
Since document.getElementById("date") only finds the first occurrence of the desired id your labels are returned.
To solve this you can change your labels to
```
<label for="date">Date: </label>
```
```html
<html>
<head>
<title>Ex... | On your html file, each `<label>` and `<input>` tags have got the same id so the problem happened.
For example, for the last `input`, the label has id `amount` and the input tag also has id `amount`.
So `document.getElementById("amount")` will return the first tag `<label>` tag so it won't have no values.
To solve t... |
5,253,358 | this is the first time I have used Python.
I downloaded the file ActivePython-2.7.1.4-win32-x86
and installed it on my computer; I'm using Win7.
So when I tried to run a python program, it appears and disappears very quickly. I don't have enough time to see anything on the screen. I just downloaded the file and double... | 2011/03/09 | [
"https://Stackoverflow.com/questions/5253358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618111/"
] | Add the line
```
input()
```
to the end of the program, with the correct indentation. The issue is that after the data is printed to the console the program finishes, so the console goes away. `input` tells the program to wait for input, so the console won't be closed when it finishes printing.
I hope you're not us... | Just a bit more on this.
You have a script `myscript.py` in a folder `C:\myscripts`. This is how to set up Windows 7 so that you can type `> myscript` into a CMD window and the script will run.
1) Set your `PATH` variable to include the Python Interpreter.
Control Panel > System and Security > System > Advanced Se... |
5,253,358 | this is the first time I have used Python.
I downloaded the file ActivePython-2.7.1.4-win32-x86
and installed it on my computer; I'm using Win7.
So when I tried to run a python program, it appears and disappears very quickly. I don't have enough time to see anything on the screen. I just downloaded the file and double... | 2011/03/09 | [
"https://Stackoverflow.com/questions/5253358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618111/"
] | go to `Start > All programs > Accessories` and click on `Command Prompt`. then drag the python file from the explorer view into this command line and press `Enter`...
now you can watch the output of the script execution ! | Just a bit more on this.
You have a script `myscript.py` in a folder `C:\myscripts`. This is how to set up Windows 7 so that you can type `> myscript` into a CMD window and the script will run.
1) Set your `PATH` variable to include the Python Interpreter.
Control Panel > System and Security > System > Advanced Se... |
5,253,358 | this is the first time I have used Python.
I downloaded the file ActivePython-2.7.1.4-win32-x86
and installed it on my computer; I'm using Win7.
So when I tried to run a python program, it appears and disappears very quickly. I don't have enough time to see anything on the screen. I just downloaded the file and double... | 2011/03/09 | [
"https://Stackoverflow.com/questions/5253358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618111/"
] | run it from a command prompt:
```
> python myscript.py
```
You can also start only the python interpreter from the command prompt (or by running python.exe) and then try some commands:
```
> python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "... | Just a bit more on this.
You have a script `myscript.py` in a folder `C:\myscripts`. This is how to set up Windows 7 so that you can type `> myscript` into a CMD window and the script will run.
1) Set your `PATH` variable to include the Python Interpreter.
Control Panel > System and Security > System > Advanced Se... |
5,253,358 | this is the first time I have used Python.
I downloaded the file ActivePython-2.7.1.4-win32-x86
and installed it on my computer; I'm using Win7.
So when I tried to run a python program, it appears and disappears very quickly. I don't have enough time to see anything on the screen. I just downloaded the file and double... | 2011/03/09 | [
"https://Stackoverflow.com/questions/5253358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618111/"
] | Or run it from a batch file:
```
myprog.py
pause
```
Has the advantage that you can specify a different version of Python too. | Just a bit more on this.
You have a script `myscript.py` in a folder `C:\myscripts`. This is how to set up Windows 7 so that you can type `> myscript` into a CMD window and the script will run.
1) Set your `PATH` variable to include the Python Interpreter.
Control Panel > System and Security > System > Advanced Se... |
35,600,152 | I am deploying a django project on apache2 using mod\_wsgi, but the problem is that the server dont serve pages and it hangs for 10 minute before giving an error:
```
End of script output before headers
```
This is my **`site-available/000-default.conf`**:
```sh
ServerAdmin webmaster@localhost
DocumentRoot /home/ar... | 2016/02/24 | [
"https://Stackoverflow.com/questions/35600152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4759209/"
] | It seems you have an **'a'** in your *wsgi.py* file between the lines
```
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "arTfact_webSite.settings")
a
application = get_wsgi_application()
```
no sure if this is in your actual file as well. | Try use the command:
apachectl configtest
This should help you isolate what is broken in your apache configuration. See this link for more information:
<https://httpd.apache.org/docs/2.4/programs/apachectl.html>
If it reports 'Syntax OK', then you know that it's a configuration **detail** problem rather than a confi... |
35,600,152 | I am deploying a django project on apache2 using mod\_wsgi, but the problem is that the server dont serve pages and it hangs for 10 minute before giving an error:
```
End of script output before headers
```
This is my **`site-available/000-default.conf`**:
```sh
ServerAdmin webmaster@localhost
DocumentRoot /home/ar... | 2016/02/24 | [
"https://Stackoverflow.com/questions/35600152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4759209/"
] | It seems you have an **'a'** in your *wsgi.py* file between the lines
```
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "arTfact_webSite.settings")
a
application = get_wsgi_application()
```
no sure if this is in your actual file as well. | You need to define a ServerName or ServerAlias in your VirtualHost block:
```
ServerName www.example.com
```
I am assuming your Apache configs above are inside a VirtualHost block like so:
```
<VirtualHost *:80>
...
</VirtualHost>
``` |
35,600,152 | I am deploying a django project on apache2 using mod\_wsgi, but the problem is that the server dont serve pages and it hangs for 10 minute before giving an error:
```
End of script output before headers
```
This is my **`site-available/000-default.conf`**:
```sh
ServerAdmin webmaster@localhost
DocumentRoot /home/ar... | 2016/02/24 | [
"https://Stackoverflow.com/questions/35600152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4759209/"
] | Try use the command:
apachectl configtest
This should help you isolate what is broken in your apache configuration. See this link for more information:
<https://httpd.apache.org/docs/2.4/programs/apachectl.html>
If it reports 'Syntax OK', then you know that it's a configuration **detail** problem rather than a confi... | You need to define a ServerName or ServerAlias in your VirtualHost block:
```
ServerName www.example.com
```
I am assuming your Apache configs above are inside a VirtualHost block like so:
```
<VirtualHost *:80>
...
</VirtualHost>
``` |
33,713,513 | I want to use Drupal for building a Genealogy application. The difficulty, I see, is in allowing users to upload a gedcom file and for it to be parsed and then from that data, various Drupal nodes would be created. Nodes in Drupal are content items. So, I'd have individuals and families as content types and each would ... | 2015/11/14 | [
"https://Stackoverflow.com/questions/33713513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/784304/"
] | There are nested calls `Magic(in - 1);`. If number is even it is printed immediately and then `Magic(in - 1);` is called. Only when `n` is zero all functions print not even number in reverse order. The first odd number is printed by the deepest `Magic()` function:
```
Magic(10)
|print 10
|Magic(9)
| |Magic(... | this is caused by the recursion of the function. the function is returning in the order it was called. if you want to print the odd numbers in decreasing order after the even numbers, you need to save them in a variable (array ) that is also passed to the magic function |
597,289 | I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any... | 2009/02/28 | [
"https://Stackoverflow.com/questions/597289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | In python3, `bytes` objects are distinct from `str`, but I don't know any reason why there would be anything wrong with this. | `join` seems fine if you really do need to put the entire string together, but then you just wind up storing the whole thing in RAM anyway. In a situation like this, I would try to see if there's a way to process each part of the string and then discard the processed part, so you only need to hold a fixed number of byt... |
597,289 | I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any... | 2009/02/28 | [
"https://Stackoverflow.com/questions/597289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | ''join() is the best method for joining chunks of data. The alternative boils down to repeated concatenation, which is O(n\*\*2) due to the immutability of strings and the need to create more at every concatenation. Given, this repeated concatenation is optimized by recent versions of CPython if used with += to become ... | In python3, `bytes` objects are distinct from `str`, but I don't know any reason why there would be anything wrong with this. |
597,289 | I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any... | 2009/02/28 | [
"https://Stackoverflow.com/questions/597289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | hm - what problem are you trying to solve? I suspect the answer depends on what you are trying to do with the data.
Since in general you don't want a whole 3Gb file in memory, I'd not store the chunks in an array, but iterate over the http\_response and write it straight to disk, in a temporary or persistent file usin... | In python3, `bytes` objects are distinct from `str`, but I don't know any reason why there would be anything wrong with this. |
597,289 | I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any... | 2009/02/28 | [
"https://Stackoverflow.com/questions/597289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | ''join() is the best method for joining chunks of data. The alternative boils down to repeated concatenation, which is O(n\*\*2) due to the immutability of strings and the need to create more at every concatenation. Given, this repeated concatenation is optimized by recent versions of CPython if used with += to become ... | `join` seems fine if you really do need to put the entire string together, but then you just wind up storing the whole thing in RAM anyway. In a situation like this, I would try to see if there's a way to process each part of the string and then discard the processed part, so you only need to hold a fixed number of byt... |
597,289 | I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any... | 2009/02/28 | [
"https://Stackoverflow.com/questions/597289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | hm - what problem are you trying to solve? I suspect the answer depends on what you are trying to do with the data.
Since in general you don't want a whole 3Gb file in memory, I'd not store the chunks in an array, but iterate over the http\_response and write it straight to disk, in a temporary or persistent file usin... | `join` seems fine if you really do need to put the entire string together, but then you just wind up storing the whole thing in RAM anyway. In a situation like this, I would try to see if there's a way to process each part of the string and then discard the processed part, so you only need to hold a fixed number of byt... |
597,289 | I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any... | 2009/02/28 | [
"https://Stackoverflow.com/questions/597289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | hm - what problem are you trying to solve? I suspect the answer depends on what you are trying to do with the data.
Since in general you don't want a whole 3Gb file in memory, I'd not store the chunks in an array, but iterate over the http\_response and write it straight to disk, in a temporary or persistent file usin... | ''join() is the best method for joining chunks of data. The alternative boils down to repeated concatenation, which is O(n\*\*2) due to the immutability of strings and the need to create more at every concatenation. Given, this repeated concatenation is optimized by recent versions of CPython if used with += to become ... |
22,890,598 | I have a function which calculates the jaccard index for two parse strings. The function is working OK and its code is below:
```
def jack(a,b):
x=a.split()
y=b.split()
k=float(len(list(set(x)&set(y))))/float(len(list(set(x) | set(y))))
return k
```
However, when I want to apply the function for any ... | 2014/04/06 | [
"https://Stackoverflow.com/questions/22890598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2825079/"
] | Since you have one element lists and you are passing the lists as the parameters whereas your function expects strings, I would recommend you to invoke your function like this
```
jack(a[2][0], a[3][0])
```
Also, you dont have to convert the `set` to a `list` to find the length.
```
return float(len(set(x) & set(y)... | That is because your variable `a` is a nested list. You should either flatten `a` or pass the arguments as:
`jack(a[2][0],a[3][0])`
### Or, you could flatten your list as:
`a = [i[0] for i in a]`
then you can easily do:
`jack(a[0],a[1])` |
21,269,702 | I’m using wxPython to write an app that will run under OS X, Windows, and Linux. I’m trying to implement the standard “Close Window” menu item, but I’m not sure how to find out which window is frontmost. WX has a [`GetActiveWindow` function](http://wxpython.org/Phoenix/docs/html/functions.html#GetActiveWindow), but app... | 2014/01/21 | [
"https://Stackoverflow.com/questions/21269702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/371228/"
] | Okay I managed to finally get this program working, I've summarized below. I hope this might help someone also stuck on ex17.
First, I removed the MAX\_DATA and MAX\_ROWS constants and changed the structs like so:
```
struct Address {
int id;
int set;
char *name;
char *email;
};
struct Database {
... | One way is to change your arrays into pointers. Then you could write an alloc\_db function which would use the max\_row and max\_data values to allocate the needed memory.
```
struct Address {
int id;
int set;
char* name;
char* email;
};
struct Database {
struct Address* rows;
unsigned int max... |
21,269,702 | I’m using wxPython to write an app that will run under OS X, Windows, and Linux. I’m trying to implement the standard “Close Window” menu item, but I’m not sure how to find out which window is frontmost. WX has a [`GetActiveWindow` function](http://wxpython.org/Phoenix/docs/html/functions.html#GetActiveWindow), but app... | 2014/01/21 | [
"https://Stackoverflow.com/questions/21269702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/371228/"
] | Okay I managed to finally get this program working, I've summarized below. I hope this might help someone also stuck on ex17.
First, I removed the MAX\_DATA and MAX\_ROWS constants and changed the structs like so:
```
struct Address {
int id;
int set;
char *name;
char *email;
};
struct Database {
... | ```
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
struct Address {
int id;
int set;
char* name;
char* email;
};
struct Database {
int MAX_ROWS;
int MAX_DATA;
struct Address* rows;
};
struct Connection {
... |
9,560,616 | I am using ArcGIS focal statistics tool to add spatial autocorrelation to a random raster to model error in DEMs. The input DEM has a 1.5m pixel size and the semivariogram exhibits a sill around 2000m. I want to make sure to model the extent of the autocorrelation in the input in my model.
Unfortunately, ArcGIS requir... | 2012/03/05 | [
"https://Stackoverflow.com/questions/9560616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839375/"
] | I'm not sure if there is a built-in way, but it should not be hard to roll your own:
```
>>> def kernel_thing(N):
... import numpy as np
... n = N // 2 + 1
... a = np.zeros((N, N), dtype=int)
... for i in xrange(n):
... a[i:N-i, i:N-i] += 1
... return a
...
>>> def kernel_to_string(a):
... return '{} ... | [Hmmph. @wim beat me, but I'd already written the following, so I'll post it anyway.] Short version:
```
import numpy
N = 5
# get grid coords
xx, yy = numpy.mgrid[0:N,0:N]
# get the distance weights
kernel = 1 + N//2 - numpy.maximum(abs(xx-N//2), abs(yy-N//2))
with open('kernel.out','w') as fp:
# header
fp.... |
54,619,732 | I am developing a model for multi-class classification problem ( 4 classes) using Keras with Tensorflow backend. The values of `y_test` have 2D format:
```
0 1 0 0
0 0 1 0
0 0 1 0
```
This is the function that I use to calculate a balanced accuracy:
```
def my_metric(targ, predict):
val_predict = predict
va... | 2019/02/10 | [
"https://Stackoverflow.com/questions/54619732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9585135/"
] | You cannot call a sklearn function on a Keras tensor. You'll need to implement the functionality yourself using Keras' backend functions, or TensorFlow functions if you are using the TF backend.
The `balanced_accuracy_score` is defined [as the average of the recall](https://scikit-learn.org/stable/modules/generated/s... | try :
`pip install --upgrade tensorflow` |
37,463,506 | I am trying to open a word document with python in windows, but I am unfamiliar with windows.
My code is as follows.
```
import docx as dc
doc = dc.Document(r'C:\Users\justin.white\Desktop\01100-Allergan-UD1314-SUMMARY OF WORK.docx')
```
Through another post, I learned that I had to put the r in front of my string ... | 2016/05/26 | [
"https://Stackoverflow.com/questions/37463506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4673518/"
] | try this
```
import StringIO
from docx import Document
file = r'H:\myfolder\wordfile.docx'
with open(file) as f:
source_stream = StringIO(f.read())
document = Document(source_stream)
source_stream.close()
```
<http://python-docx.readthedocs.io/en/latest/user/documents.html>
Also, in regards to debugging the f... | If you want to open the document in Microsoft Word try using `os.startfile()`.
In your example it would be:
```
os.startfile(r'C:\Users\justin.white\Desktop\01100-Allergan-UD1314-SUMMARY OF WORK.docx')
```
This will open the document in word on your computer. |
32,734,437 | I got an file with text form:
```
a:
b(0.1),
c(0.33),
d:
e(0.21),
f(0.41),
g(0.5),
k(0.8),
h:
y(0.9),
```
And I want get the following form:
```
a: b(0.1), c(0.33)
d: e(0.21), f(0.41), g(0.5), k(0.8)
h: y(0.9)
```
In python language,
I have tried:
```
for line in menu:
for i in line:
if i == ":":
``... | 2015/09/23 | [
"https://Stackoverflow.com/questions/32734437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5316423/"
] | ```
import re
one_line = ''.join(menu).replace('\n', ' ')
print re.sub(', ([a-z]+:)', r'\n\1', one_line)[:-1]
```
You might have to tweak the `one_line` to match your input better. | I am not exactly sure if you want to print the stuff or actually manipulate the file. But in the case of just printing:
```
from __future__ import print_function
from itertools import tee, islice, chain, izip
def previous_and_next(some_iterable):
prevs, items, nexts = tee(some_iterable, 3)
prevs = chain([None... |
32,734,437 | I got an file with text form:
```
a:
b(0.1),
c(0.33),
d:
e(0.21),
f(0.41),
g(0.5),
k(0.8),
h:
y(0.9),
```
And I want get the following form:
```
a: b(0.1), c(0.33)
d: e(0.21), f(0.41), g(0.5), k(0.8)
h: y(0.9)
```
In python language,
I have tried:
```
for line in menu:
for i in line:
if i == ":":
``... | 2015/09/23 | [
"https://Stackoverflow.com/questions/32734437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5316423/"
] | ```
import re
one_line = ''.join(menu).replace('\n', ' ')
print re.sub(', ([a-z]+:)', r'\n\1', one_line)[:-1]
```
You might have to tweak the `one_line` to match your input better. | Here a solution using an OrderedDict to store ':'-containing lines as key and the following lines as value until the next key is found. Then just print the dictionary as you like.
```
from collections import OrderedDict
data = OrderedDict()
key = False
for line in menu:
if ':' in line:
key = line.strip()
... |
63,811,316 | I am running celery worker(version 4.4) on windows machine, when I run the worker with `-P eventlet` option it throws Attribute error.
Error logs are as follows:-
```
pipenv run celery worker -A src.celery_app -l info -P eventlet --without-mingle --without-heartbeat --without-gossip -Q queue1 -n worker1
Traceback (mos... | 2020/09/09 | [
"https://Stackoverflow.com/questions/63811316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5605353/"
] | `os.register_at_fork` is a new function available since `Python 3.7`, it is only available for Unix systems ([Source from Python doc](https://docs.python.org/3.8/library/os.html#os.register_at_fork)) and Eventlet use it to patch `threading` library.
There is an issue opened in Eventlet Github:
<https://github.com/even... | One reason you are facing this is because of the fact that Celery works on a pre-fork model.
So if the underlying OS does not support it, you will have a tough time running celery. As per my knowledge, this model does not exist for the Windows kernel.
You can still use Cygwin if you want to make it work on windows or ... |
63,811,316 | I am running celery worker(version 4.4) on windows machine, when I run the worker with `-P eventlet` option it throws Attribute error.
Error logs are as follows:-
```
pipenv run celery worker -A src.celery_app -l info -P eventlet --without-mingle --without-heartbeat --without-gossip -Q queue1 -n worker1
Traceback (mos... | 2020/09/09 | [
"https://Stackoverflow.com/questions/63811316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5605353/"
] | One reason you are facing this is because of the fact that Celery works on a pre-fork model.
So if the underlying OS does not support it, you will have a tough time running celery. As per my knowledge, this model does not exist for the Windows kernel.
You can still use Cygwin if you want to make it work on windows or ... | is the eventlet version 0.26; pip install eventlet==0.26 |
63,811,316 | I am running celery worker(version 4.4) on windows machine, when I run the worker with `-P eventlet` option it throws Attribute error.
Error logs are as follows:-
```
pipenv run celery worker -A src.celery_app -l info -P eventlet --without-mingle --without-heartbeat --without-gossip -Q queue1 -n worker1
Traceback (mos... | 2020/09/09 | [
"https://Stackoverflow.com/questions/63811316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5605353/"
] | `os.register_at_fork` is a new function available since `Python 3.7`, it is only available for Unix systems ([Source from Python doc](https://docs.python.org/3.8/library/os.html#os.register_at_fork)) and Eventlet use it to patch `threading` library.
There is an issue opened in Eventlet Github:
<https://github.com/even... | is the eventlet version 0.26; pip install eventlet==0.26 |
63,811,316 | I am running celery worker(version 4.4) on windows machine, when I run the worker with `-P eventlet` option it throws Attribute error.
Error logs are as follows:-
```
pipenv run celery worker -A src.celery_app -l info -P eventlet --without-mingle --without-heartbeat --without-gossip -Q queue1 -n worker1
Traceback (mos... | 2020/09/09 | [
"https://Stackoverflow.com/questions/63811316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5605353/"
] | `os.register_at_fork` is a new function available since `Python 3.7`, it is only available for Unix systems ([Source from Python doc](https://docs.python.org/3.8/library/os.html#os.register_at_fork)) and Eventlet use it to patch `threading` library.
There is an issue opened in Eventlet Github:
<https://github.com/even... | As hinted at by @金奕峰, `os.register_at_fork` was introduced in eventlet v0.27.0 [c.f. commit compare on github](https://github.com/eventlet/eventlet/compare/v0.26.1...v0.27.0). Specifying version 0.26.0 in your virtual environment's package list might solve the problem (for now). |
63,811,316 | I am running celery worker(version 4.4) on windows machine, when I run the worker with `-P eventlet` option it throws Attribute error.
Error logs are as follows:-
```
pipenv run celery worker -A src.celery_app -l info -P eventlet --without-mingle --without-heartbeat --without-gossip -Q queue1 -n worker1
Traceback (mos... | 2020/09/09 | [
"https://Stackoverflow.com/questions/63811316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5605353/"
] | As hinted at by @金奕峰, `os.register_at_fork` was introduced in eventlet v0.27.0 [c.f. commit compare on github](https://github.com/eventlet/eventlet/compare/v0.26.1...v0.27.0). Specifying version 0.26.0 in your virtual environment's package list might solve the problem (for now). | is the eventlet version 0.26; pip install eventlet==0.26 |
18,233,399 | I have a fat32 partition image file dump, for example created with dd. how i can parse this file with python and extract the desired file inside this partition. | 2013/08/14 | [
"https://Stackoverflow.com/questions/18233399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2460058/"
] | As far as reading a FAT32 filesystem image in Python goes, the [Wikipedia page](http://en.wikipedia.org/wiki/FAT32) has all the detail you need to write a read-only implementation.
[Construct](http://construct.readthedocs.org/en/latest/) may be of some use. Looks like they have an example for FAT16 (<https://github.co... | Just found out this nice [lib7zip bindings](https://github.com/topia/pylib7zip) that can read RAW FAT images (and [much more](https://7zip.bugaco.com/7zip/MANUAL/general/formats.htm)).
Example usage:
```py
# pip install git+https://github.com/topia/pylib7zip
from lib7zip import Archive, formats
archive = Archive("fd... |
35,569,042 | I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects.
I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ>
After following the exact same code as him, this is the error that I get:
```
Traceback... | 2016/02/23 | [
"https://Stackoverflow.com/questions/35569042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790055/"
] | On Debian 9 I had to:
```
$ sudo update-ca-certificates --fresh
$ export SSL_CERT_DIR=/etc/ssl/certs
```
I'm not sure why, but this enviroment variable was never set. | This has changed in recent versions of the ssl library. The SSLContext was moved to it's own property. This is the equivalent of Jia's answer in Python 3.8
```
import ssl
ssl.SSLContext.verify_mode = ssl.VerifyMode.CERT_OPTIONAL
``` |
35,569,042 | I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects.
I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ>
After following the exact same code as him, this is the error that I get:
```
Traceback... | 2016/02/23 | [
"https://Stackoverflow.com/questions/35569042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790055/"
] | In my case, I used the `ssl` module to "workaround" the certification like so:
```
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
```
Then to read your link content, you can use:
```
urllib.request.urlopen(urllink)
``` | This has changed in recent versions of the ssl library. The SSLContext was moved to it's own property. This is the equivalent of Jia's answer in Python 3.8
```
import ssl
ssl.SSLContext.verify_mode = ssl.VerifyMode.CERT_OPTIONAL
``` |
35,569,042 | I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects.
I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ>
After following the exact same code as him, this is the error that I get:
```
Traceback... | 2016/02/23 | [
"https://Stackoverflow.com/questions/35569042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790055/"
] | Building on the update to [Jia's 2018 answer](https://stackoverflow.com/a/49174340/866333) in [deltree's late 2021 one](https://stackoverflow.com/a/69724616/866333) I was able to achieve equivalent functionality with:
```py
import urllib.request
import ssl
def urllib_get_2018():
# Using a protected member like th... | I have a lib what use <https://requests.readthedocs.io/en/master/> what use <https://pypi.org/project/certifi/> but I have a custom CA included in my `/etc/ssl/certs`.
So I solved my problem like this:
```
# Your TLS certificates directory (Debian like)
export SSL_CERT_DIR=/etc/ssl/certs
# CA bundle PATH (Debian like... |
35,569,042 | I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects.
I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ>
After following the exact same code as him, this is the error that I get:
```
Traceback... | 2016/02/23 | [
"https://Stackoverflow.com/questions/35569042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790055/"
] | As a workaround (not secure), you can turn certificate verification off by setting PYTHONHTTPSVERIFY environment variable to 0:
```
export PYTHONHTTPSVERIFY=0
``` | I have a lib what use <https://requests.readthedocs.io/en/master/> what use <https://pypi.org/project/certifi/> but I have a custom CA included in my `/etc/ssl/certs`.
So I solved my problem like this:
```
# Your TLS certificates directory (Debian like)
export SSL_CERT_DIR=/etc/ssl/certs
# CA bundle PATH (Debian like... |
35,569,042 | I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects.
I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ>
After following the exact same code as him, this is the error that I get:
```
Traceback... | 2016/02/23 | [
"https://Stackoverflow.com/questions/35569042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790055/"
] | In my case, I used the `ssl` module to "workaround" the certification like so:
```
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
```
Then to read your link content, you can use:
```
urllib.request.urlopen(urllink)
``` | As a workaround (not secure), you can turn certificate verification off by setting PYTHONHTTPSVERIFY environment variable to 0:
```
export PYTHONHTTPSVERIFY=0
``` |
35,569,042 | I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects.
I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ>
After following the exact same code as him, this is the error that I get:
```
Traceback... | 2016/02/23 | [
"https://Stackoverflow.com/questions/35569042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790055/"
] | Building on the update to [Jia's 2018 answer](https://stackoverflow.com/a/49174340/866333) in [deltree's late 2021 one](https://stackoverflow.com/a/69724616/866333) I was able to achieve equivalent functionality with:
```py
import urllib.request
import ssl
def urllib_get_2018():
# Using a protected member like th... | I faced the same issue with Ubuntu 20.4 and have tried many solutions but nothing worked out. Finally I just checked openssl version. Even after update and upgrade, the openssl version showed **OpenSSL 1.1.1h [22 Sep 2020]**. But in my windows system, where the code works without any issue, openssl version is **OpenSSL... |
35,569,042 | I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects.
I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ>
After following the exact same code as him, this is the error that I get:
```
Traceback... | 2016/02/23 | [
"https://Stackoverflow.com/questions/35569042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790055/"
] | When you are using a self signed cert urllib3 version 1.25.3 refuses to ignore the SSL cert
To fix remove urllib3-1.25.3 and install urllib3-1.24.3
`pip3 uninstall urllib3`
`pip3 install urllib3==1.24.3`
Tested on Linux MacOS and Window$ | I have a lib what use <https://requests.readthedocs.io/en/master/> what use <https://pypi.org/project/certifi/> but I have a custom CA included in my `/etc/ssl/certs`.
So I solved my problem like this:
```
# Your TLS certificates directory (Debian like)
export SSL_CERT_DIR=/etc/ssl/certs
# CA bundle PATH (Debian like... |
35,569,042 | I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects.
I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ>
After following the exact same code as him, this is the error that I get:
```
Traceback... | 2016/02/23 | [
"https://Stackoverflow.com/questions/35569042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790055/"
] | On Debian 9 I had to:
```
$ sudo update-ca-certificates --fresh
$ export SSL_CERT_DIR=/etc/ssl/certs
```
I'm not sure why, but this enviroment variable was never set. | As a workaround (not secure), you can turn certificate verification off by setting PYTHONHTTPSVERIFY environment variable to 0:
```
export PYTHONHTTPSVERIFY=0
``` |
35,569,042 | I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects.
I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ>
After following the exact same code as him, this is the error that I get:
```
Traceback... | 2016/02/23 | [
"https://Stackoverflow.com/questions/35569042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790055/"
] | On Debian 9 I had to:
```
$ sudo update-ca-certificates --fresh
$ export SSL_CERT_DIR=/etc/ssl/certs
```
I'm not sure why, but this enviroment variable was never set. | you might exec command: `pip install --upgrade certifi`
or you might opened charles/fiddler, just close it |
35,569,042 | I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects.
I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ>
After following the exact same code as him, this is the error that I get:
```
Traceback... | 2016/02/23 | [
"https://Stackoverflow.com/questions/35569042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790055/"
] | When you are using a self signed cert urllib3 version 1.25.3 refuses to ignore the SSL cert
To fix remove urllib3-1.25.3 and install urllib3-1.24.3
`pip3 uninstall urllib3`
`pip3 install urllib3==1.24.3`
Tested on Linux MacOS and Window$ | you might exec command: `pip install --upgrade certifi`
or you might opened charles/fiddler, just close it |
50,640,716 | I am using MACOS 10.12.6
I was trying to uninstall python to reinstall it, and I foolishly typed these commands into my terminals.
```
sudo rm -rf /Users/<myusername>/anaconda2/lib/python2.7
sudo rm -rf /Users/<myusername>/anaconda2/lib/python27.zip
sudo rm -rf /Users/<myusername>/anaconda2/lib/python2.7/plat-darwin... | 2018/06/01 | [
"https://Stackoverflow.com/questions/50640716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9880455/"
] | Since you used Anconda on your mac you should be able to just reinstall python 2.7. If you still have the install package: Anaconda2-5.2.0-MacOSX-x86\_64.pkg, just double click that and follow directions. If you don't have this package, download it from [here](https://www.anaconda.com/download/#macos) and when the pack... | You only deleted Anaconda, not the System Python.
Therefore, you probably only need to edit your PATH variable to remove references to those folders.
Check your `~/.bashrc` |
62,142,223 | I've installed from sources the SimpleITK package on Python3. When I perform the provided registration example :
```
#!/usr/bin/env python
#=========================================================================
#
# Copyright NumFOCUS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ... | 2020/06/01 | [
"https://Stackoverflow.com/questions/62142223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11107590/"
] | The result of running the ImageRegistrationMethod1 example is a transform. SimpleITK supports a number of file formats for transformations, including a text file (.txt), a Matlab file (.mat) and a HDF5Tranform (.hdf5). That does not include a .tif file, which is an image file, not a transform.
You can read more about ... | if you want to write dicom as file output, please try this one.
```
writer.SetFileName(os.path.join('transformed.dcm'))
writer.Execute(cimg)
``` |
73,277,276 | I know how to add a function to a python dict:
```
def burn(theName):
return theName + ' is burning'
kitchen = {'name': 'The Kitchen', 'burn_it': burn}
print(kitchen['burn_it'](kitchen['name']))
### output: "the Kitchen is burning"
```
but is there any way to reference the dictionary's own 'name' value wi... | 2022/08/08 | [
"https://Stackoverflow.com/questions/73277276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1914833/"
] | You can extend `dict` object with your custom class, like this:
```py
class MyDict(dict):
def __init__(self, *args, **kwargs):
self["burn_it"] = self.burn
super().__init__(*args, **kwargs)
def burn(self):
return self["name"] + " is burning"
kitchen = MyDict({'name': 'The Kitchen'})
p... | You cannot know which object reference the function.
A simple example, image the following:
```
def burn(theName):
return theName + ' is burning'
kitchen = {'name': 'The Kitchen', 'burn_it': burn}
garage = {'name': 'The Garage', 'burn_it': burn}
```
`burn` is referenced both in `kitchen` and `garage`, how ... |
56,693,576 | I am trying to access a variable defined inside an if statement in a for loop, outside the for loop. but I am getting the 'Unbounded Local Error'
I have tried assigning `lambdaPriceUsWest2 = None` as suggested here:
[Python Get variable outside the loop](https://stackoverflow.com/questions/25406399/python-get-variable... | 2019/06/20 | [
"https://Stackoverflow.com/questions/56693576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6921304/"
] | the best way is before the for loop try to initialize that variable. For example:
```
lambdaPriceUsWest2 = ""
``` | just defined a var outside loop and update it value
```
local_val =''
for x in range(len(response['PriceList'])):
priceList=json.loads(response['PriceList'][x])
if priceList['product']['sku'] == 'DU9X9ZR8C8DYH3Y9':
lambdaPriceUsWest2= priceListpriceList['product']['sku']['USD']
... |
56,693,576 | I am trying to access a variable defined inside an if statement in a for loop, outside the for loop. but I am getting the 'Unbounded Local Error'
I have tried assigning `lambdaPriceUsWest2 = None` as suggested here:
[Python Get variable outside the loop](https://stackoverflow.com/questions/25406399/python-get-variable... | 2019/06/20 | [
"https://Stackoverflow.com/questions/56693576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6921304/"
] | the best way is before the for loop try to initialize that variable. For example:
```
lambdaPriceUsWest2 = ""
``` | First of all, declare a variable before assignment (inside the for-loop) using 'global' syntax like this:
```
global lambdaPriceUsEast2
```
Then assign any value you want for it, for example:
```
lambdaPriceUsEast2 = priceListpriceList['product']['sku']['USD']
```
It's worth mentioning that if you don't assign it... |
59,125,889 | ```
npm install expo-cli --global
```
I got this following error:
```
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] postinstall: `test -d .git && cp gitHookPrePush.sh .git/hooks/pre-push || true`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] postinstall script.
npm ERR! This i... | 2019/12/01 | [
"https://Stackoverflow.com/questions/59125889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5982462/"
] | just try installing `npm install expo-cli --global` this command on git bash. It worked for me. | [I fixed this problem](https://stackoverflow.com/questions/59124830/reactnative-code-elifecycle-error-when-installing-expo-cli/59126514#59126514) :
```
1- Download and install Git SCM
2- Download Visual Studio Community HERE and install a Custom Installation, selecting ONLY the following packages: VISUAL C++, PYTHON T... |
50,751,484 | I trained on TensorFlow model on a GPU cluster, saved the model using
```
saver = tf.train.Saver()
saver.save(sess, config.model_file, global_step=global_step)
```
and now I am trying to restore the model with
```
saver = tf.train.import_meta_graph('model-1000.meta')
saver.restore(sess,tf.train.latest_checkpoint(s... | 2018/06/07 | [
"https://Stackoverflow.com/questions/50751484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6263317/"
] | By default, the `Saver` object will write the absolute model checkpoint paths into the `checkpoint` file. So the path returned by `tf.train.latest_checkpoint(save_path)` is the absolute path on your old machine.
Temporary solution:
1. Pass the actual model file path directly to the `restore` method rather than the r... | Open up the checkpoint file with your favorite text editor and simply change the absolute paths found therein to just filenames. |
25,201,504 | I'm trying to minimize function, that returns a vector of values,
and here is an error:
>
> setting an array element with a sequence
>
>
>
Code:
```
P = np.matrix([[0.3, 0.1, 0.2], [0.01, 0.4, 0.2], [0.0001, 0.3, 0.5]])
Ps = np.array([10,14,5])
def objective(x):
x = np.array([x])
res = np.square(Ps... | 2014/08/08 | [
"https://Stackoverflow.com/questions/25201504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2824962/"
] | Your objective function needs to return a scalar value, not a vector. You probably want to return the *sum* of squared errors rather than the vector of squared errors:
```
def objective(x):
res = ((Ps - np.dot(x, P)) ** 2).sum()
return res
``` | Use [`least_squares`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html). This will require to modify the objective a bit to return differences instead of squared differences:
```py
import numpy as np
from scipy.optimize import least_squares
P = np.matrix([[0.3, 0.1, 0.2], [0.01, ... |
25,201,504 | I'm trying to minimize function, that returns a vector of values,
and here is an error:
>
> setting an array element with a sequence
>
>
>
Code:
```
P = np.matrix([[0.3, 0.1, 0.2], [0.01, 0.4, 0.2], [0.0001, 0.3, 0.5]])
Ps = np.array([10,14,5])
def objective(x):
x = np.array([x])
res = np.square(Ps... | 2014/08/08 | [
"https://Stackoverflow.com/questions/25201504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2824962/"
] | If you want you resulting vector to be a vector containing only `0`s, you can use `fsolve` to do so. To do that will require modifying your objective function a little bit to get the input and output into the same shape:
```
import scipy.optimize as so
P = np.matrix([[0.3, 0.1, 0.2], [0.01, 0.4, 0.2], [0.0001, 0.3, 0.... | Use [`least_squares`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html). This will require to modify the objective a bit to return differences instead of squared differences:
```py
import numpy as np
from scipy.optimize import least_squares
P = np.matrix([[0.3, 0.1, 0.2], [0.01, ... |
31,580,319 | I use ansible module `fetch` to download a large file, said 2GB. Then I got the following error message. Ansible seems to be unable to deal with large file.
```
fatal: [x.x.x.x] => failed to parse:
SUDO-SUCCESS-ucnhswvujwylacnodwyyictqtmrpabxp
Traceback (most recent call last):
File "/home/xxx/.ansible/tmp/ansible-... | 2015/07/23 | [
"https://Stackoverflow.com/questions/31580319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605599/"
] | <https://github.com/ansible/ansible/issues/11702>
This is an Ansible bug which have been solved in newer version. | Looks like the remote server you're trying to fetch from is running out of memory during the base64 encoding process. Perhaps try the synchronize module instead (which will use rsync); fetch isn't really designed to work with large files. |
31,580,319 | I use ansible module `fetch` to download a large file, said 2GB. Then I got the following error message. Ansible seems to be unable to deal with large file.
```
fatal: [x.x.x.x] => failed to parse:
SUDO-SUCCESS-ucnhswvujwylacnodwyyictqtmrpabxp
Traceback (most recent call last):
File "/home/xxx/.ansible/tmp/ansible-... | 2015/07/23 | [
"https://Stackoverflow.com/questions/31580319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605599/"
] | Looks like the remote server you're trying to fetch from is running out of memory during the base64 encoding process. Perhaps try the synchronize module instead (which will use rsync); fetch isn't really designed to work with large files. | Had the same issue with a Digital Ocean droplet (1 Gb RAM).
Fixed it by increasing the swap size.
Here is the ansible task to fetch the data
```
- name: Fetch data from remote
fetch:
src: "{{ app_dir }}/data.zip"
dest: "{{ playbook_dir }}/../data/data.zip"
flat: yes
become: ... |
31,580,319 | I use ansible module `fetch` to download a large file, said 2GB. Then I got the following error message. Ansible seems to be unable to deal with large file.
```
fatal: [x.x.x.x] => failed to parse:
SUDO-SUCCESS-ucnhswvujwylacnodwyyictqtmrpabxp
Traceback (most recent call last):
File "/home/xxx/.ansible/tmp/ansible-... | 2015/07/23 | [
"https://Stackoverflow.com/questions/31580319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605599/"
] | <https://github.com/ansible/ansible/issues/11702>
This is an Ansible bug which have been solved in newer version. | Had the same issue with a Digital Ocean droplet (1 Gb RAM).
Fixed it by increasing the swap size.
Here is the ansible task to fetch the data
```
- name: Fetch data from remote
fetch:
src: "{{ app_dir }}/data.zip"
dest: "{{ playbook_dir }}/../data/data.zip"
flat: yes
become: ... |
15,811,082 | I am developing some python packages and I do want to perform proper testing before releasing them to PyPi.
This would require running the unittests across
* different python versions: 2.5, 2.6, 2.7, 3.2
* different operating systems: OS X, Debian, Ubuntu and Windows
Right now I am using pytest
Question: how can I ... | 2013/04/04 | [
"https://Stackoverflow.com/questions/15811082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/99834/"
] | I have used Jenkins, and I would recommend it. It has a plethora of plugins, and is very configurable.
I have used it for running projects over windows/linux/mac/mobile platforms, for sanity, unit, component, and regression tests.
It can support chaining of projects and tests, fingerprinting of items to be monitored ... | You can use [`tox`](http://codespeak.net/tox/index.html) to automate setting up virtual environments and running your tests across Python versions:
```
[tox]
envlist = py25,py26,py27,py32
[testenv]
commands=py.test
```
Tox supports Python versions 2.4 and up, as well as Jython and PyPy.
If you want to look at a rea... |
51,919,720 | I've been unable to use Pyenv to install Python on macOS (10.13.6) and have exhausted advice about common build problems.
pyenv-doctor reports: **OpenSSL development header is not installed.** Reinstallation of OpenSSL, as suggested in various related GitHub issues has not worked, not have various flag settings, eg (... | 2018/08/19 | [
"https://Stackoverflow.com/questions/51919720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7322742/"
] | If this is the same issue as me, it's because there's headers in your path that shouldn't be there. Run `brew doctor` and you would see it complain. To fix it you can do:
```
mkdir /tmp/includes
brew doctor 2>&1 | grep "/usr/local/include" | awk '{$1=$1;print}' | xargs -I _ mv _ /tmp/includes
``` | After applying Kit's answer; I had to do the following to overcome the fact that I also installed `openssl` with homebrew:
```
CFLAGS="-I$(brew --prefix openssl)/include" \
LDFLAGS="-L$(brew --prefix openssl)/lib" \
pyenv doctor
```
That got me working.
Also found this [reference](https://github.com/pyenv/pyenv/wiki... |
46,492,510 | I'm new to python, I'm trying to create a list of lists from a text file. The task seems easy to do but I don't know why it's not working with my code.
I have the following lines in my text file:
```
word1,word2,word3,word4
word2,word3,word1
word4,word5,word6
```
I want to get the following output:
```
[['word1... | 2017/09/29 | [
"https://Stackoverflow.com/questions/46492510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4699562/"
] | You can iterate like this:
```
f = [i.strip('\n').split(',') for i in open('file.txt')]
``` | Your code works fine, if your code creating issues in your system then if you want you can do this in one line with this :
```
with open("file.txt") as f:
print([i.strip().split(',') for i in f])
``` |
61,327,413 | I have a client python and a server python and the commands which work perfectly. Now I want to build the interface which needs a variable(string) from the server file and I encountered a problem.
**my client.py file**
```
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostna... | 2020/04/20 | [
"https://Stackoverflow.com/questions/61327413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12305440/"
] | Here's your exact same code using a file system object instead to do the folder work inside the loop. I didn't test it, but it illustrates what I am talking about in my comment above. You should be able to get it working using this:
```
Sub Unzip()
Dim oApplicationlication As Object
Dim MyFolder As String
Dim MyFile A... | Your code is failing because you are using `Dir` within the loop to check the existence of the folder to extract to. Instead, move that piece of code to outside the loop:
```
Sub Unzip()
Dim oApplication As Object
Dim MyFolder As String
Dim MyFile As String
Dim ExtractTo As Variant
Application.Scre... |
29,859,173 | I am following the example to deploy sample python application to bluemix
[BLUEMIX-PYTHON-FLASK-SAMPLE](https://github.com/IBM-Bluemix/bluemix-python-flask-sample)
Created project successfully
Cloned repository successfully
Configured pipeline successfully
Deploy to BLUEMIX failed.
I checked the error in deployment l... | 2015/04/24 | [
"https://Stackoverflow.com/questions/29859173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2639529/"
] | The memory limit is controlled by the memory value in the manifest.yml file in the root of the project. You don't need to have this manifest.yml file present as Bluemix will define defaults for you. In this case the memory allocation would be 1GB as this is the default which is really to much for a sample app like this... | You probably have exceeded the max app limit on your Bluemix account.
Login to your Bluemix account and check if all the app memory limit is utilized. If you have reached your limit then you might have to remove one or more of the apps which you are not using based on how much memory space is needed.
in the python-fl... |
29,859,173 | I am following the example to deploy sample python application to bluemix
[BLUEMIX-PYTHON-FLASK-SAMPLE](https://github.com/IBM-Bluemix/bluemix-python-flask-sample)
Created project successfully
Cloned repository successfully
Configured pipeline successfully
Deploy to BLUEMIX failed.
I checked the error in deployment l... | 2015/04/24 | [
"https://Stackoverflow.com/questions/29859173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2639529/"
] | The memory limit is controlled by the memory value in the manifest.yml file in the root of the project. You don't need to have this manifest.yml file present as Bluemix will define defaults for you. In this case the memory allocation would be 1GB as this is the default which is really to much for a sample app like this... | This issue is mostly due to insufficient memory available, which you can verify using your bluemix dashboard.
On the dashboard the first widget represents how much memory you have available and how much you are using,
if deploying an app would go over this limit then you will not be able to do so.
For More [details... |
18,950,409 | I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration.
For example:
```
#!/usr/bin/python
doubleDict = dict()
doubleDict['one'] = dict()
doubleDict['one']['type'] = 'animal'
doubleDict['on... | 2013/09/23 | [
"https://Stackoverflow.com/questions/18950409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1174102/"
] | For-loops in `dict`s iterates over the keys and not over the values.
To iterate over the values do:
```
for thing in doubleDict.itervalues():
print thing
print thing['type']
print thing['name']
print thing['species']
```
I used your exact same code, but added the `.itervalues()` at t... | When you iterate through a dictionary, you iterate through it's keys and not its values. To get nested values, you have to do:
```
for thing in doubleDict:
print doubleDict[thing]
print doubleDict[thing]['type']
print doubleDict[thing]['name']
print doubleDict[thing]['species']
``` |
18,950,409 | I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration.
For example:
```
#!/usr/bin/python
doubleDict = dict()
doubleDict['one'] = dict()
doubleDict['one']['type'] = 'animal'
doubleDict['on... | 2013/09/23 | [
"https://Stackoverflow.com/questions/18950409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1174102/"
] | When you iterate through a dictionary, you iterate through it's keys and not its values. To get nested values, you have to do:
```
for thing in doubleDict:
print doubleDict[thing]
print doubleDict[thing]['type']
print doubleDict[thing]['name']
print doubleDict[thing]['species']
``` | You could use @Haidro's answer but make it more generic with a double loop:
```
for key1 in doubleDict:
print(doubleDict[key1])
for key2 in doubleDict[key1]:
print(doubleDict[key1][key2])
{'type': 'plant', 'name': 'moe', 'species': 'oak'}
plant
moe
oak
{'type': 'animal', 'name': 'joe', 'species': 'mon... |
18,950,409 | I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration.
For example:
```
#!/usr/bin/python
doubleDict = dict()
doubleDict['one'] = dict()
doubleDict['one']['type'] = 'animal'
doubleDict['on... | 2013/09/23 | [
"https://Stackoverflow.com/questions/18950409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1174102/"
] | When you iterate through a dictionary, you iterate through it's keys and not its values. To get nested values, you have to do:
```
for thing in doubleDict:
print doubleDict[thing]
print doubleDict[thing]['type']
print doubleDict[thing]['name']
print doubleDict[thing]['species']
``` | these all work... but looking at your code, why not use a named tuple instead?
from collections import namedtuple
LivingThing = namedtuple('LivingThing', 'type name species')
doubledict['one'] = LivingThing(type='animal', name='joe', species='monkey')
doubledict['one'].name
doubledict['one'].\_asdict['name'] |
18,950,409 | I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration.
For example:
```
#!/usr/bin/python
doubleDict = dict()
doubleDict['one'] = dict()
doubleDict['one']['type'] = 'animal'
doubleDict['on... | 2013/09/23 | [
"https://Stackoverflow.com/questions/18950409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1174102/"
] | For-loops in `dict`s iterates over the keys and not over the values.
To iterate over the values do:
```
for thing in doubleDict.itervalues():
print thing
print thing['type']
print thing['name']
print thing['species']
```
I used your exact same code, but added the `.itervalues()` at t... | A generic way to get to the nested results:
```
for thing in doubleDict.values():
print(thing)
for vals in thing.values():
print(vals)
```
or
```
for thing in doubleDict.values():
print(thing)
print('\n'.join(thing.values()))
``` |
18,950,409 | I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration.
For example:
```
#!/usr/bin/python
doubleDict = dict()
doubleDict['one'] = dict()
doubleDict['one']['type'] = 'animal'
doubleDict['on... | 2013/09/23 | [
"https://Stackoverflow.com/questions/18950409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1174102/"
] | For-loops in `dict`s iterates over the keys and not over the values.
To iterate over the values do:
```
for thing in doubleDict.itervalues():
print thing
print thing['type']
print thing['name']
print thing['species']
```
I used your exact same code, but added the `.itervalues()` at t... | You could use @Haidro's answer but make it more generic with a double loop:
```
for key1 in doubleDict:
print(doubleDict[key1])
for key2 in doubleDict[key1]:
print(doubleDict[key1][key2])
{'type': 'plant', 'name': 'moe', 'species': 'oak'}
plant
moe
oak
{'type': 'animal', 'name': 'joe', 'species': 'mon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.