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 |
|---|---|---|---|---|---|
44,869,938 | i have create an image processing python function.
my system have 4 cores + 4 threads.
i want to use multiprocessing to speed up my function,but anytime to use multiprocessing packages my function is not faster and is 1 minute slowly.
any idea why ?first time use multiprocessing packages.
main function :
```
if __n... | 2017/07/02 | [
"https://Stackoverflow.com/questions/44869938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5738116/"
] | `multiprocessing.Pool.map()` does not automatically make a function run in parallel. So doing `Pool.map(my_function(single_input))` will not make it run any faster. In fact, it may make it slower.
The purpose of `map()` is to allow you to run the same function *multiple times* in parallel if you have *multiple inputs*... | You're executing the same function with the same parameters in a sub-process - this is bound to be slower as, at the very least, there is a system overhead of creating a new process, and then comes the Python's own overhead. It creates a whole new interpreter, stack, GIL... and that takes time.
On POSIX systems this o... |
45,179,302 | Tornado has an open socket, and I can't seem to get it closed.
I was really surprised as I've turned my computer on and off since the last time I ran this server a week ago, and terminal is not running. All in all, I thought this server was off for the past week.
The things I've tried so far are the solution to this ... | 2017/07/19 | [
"https://Stackoverflow.com/questions/45179302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4808079/"
] | Interesting.
Firstly, you should call `close()` method for `tornado.ioloop.IOLoop` **object**, not for **class object**. You can get current `tornado.ioloop.IOLoop` object using the method `tornado.ioloop.IOLoop.current()`.
Example:
```
my_ioloop = tornado.ioloop.IOLoop.current()
my_ioloop.close(all_fds=True)
```
... | In my case, the issue was not with Tornado specifically, but with a process it started which continued even after it lost track of it.
When I restarted my computer, OSX kept track of the process, but Tornado did not. The solution was to find open ports and close the one Tornado was using.
The answer comes from here o... |
47,585,705 | How do I make a file from a dictionary in python?
For example this is my dictionary:
dict = {'a':1,'b':2,'c':3}
How do I make it into the first sentence of a file that shows this?
a,1.b,2.c,3.
Thank you to anyone who answers my question. | 2017/12/01 | [
"https://Stackoverflow.com/questions/47585705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8922904/"
] | You can try this:
```
f = open('file.txt', 'w')
dict = {'a':1,'b':2,'c':3}
f.write('.'.join('{},{}'.format(a, b) for a, b in dict.items())+'.\n')
f.close()
``` | ```
import json
mydict = {'a':1,'b':2,'c':3}
with open('dict_file.txt', 'w') as file:
file.write(json.dumps(mydict))
```
Hope this helps. |
40,784,720 | I don't know if it is possible or not. I am trying to find a way of sorting a nested list on the following condition
1. i want to sort form 1 point to another (NOT the whole list only part of it)
2. the sorting should be done on the basis of 3rd element of the sublists
an Idea of what i want:
```
PAE=[['a',0,8],... | 2016/11/24 | [
"https://Stackoverflow.com/questions/40784720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5650215/"
] | Sort the slice **and write it back**:
```
>>> PAE[1:4] = sorted(PAE[1:4], key=itemgetter(2))
>>> PAE
[['a', 0, 8], ['b', 2, 1], ['d', 7, 2], ['c', 4, 3], ['e', 8, 4]]
``` | This should do :
```
from operator import itemgetter
PAE=[['a',0,8],
['b',2,1],
['c',4,3],
['d',7,2],
['e',8,4]]
split_index = 1
print PAE[:split_index]+sorted(PAE[split_index:],key=itemgetter(2))
#=> [['a', 0, 8], ['b', 2, 1], ['d', 7, 2], ['c', 4, 3], ['e', 8, 4]]
``` |
40,784,720 | I don't know if it is possible or not. I am trying to find a way of sorting a nested list on the following condition
1. i want to sort form 1 point to another (NOT the whole list only part of it)
2. the sorting should be done on the basis of 3rd element of the sublists
an Idea of what i want:
```
PAE=[['a',0,8],... | 2016/11/24 | [
"https://Stackoverflow.com/questions/40784720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5650215/"
] | This should do :
```
from operator import itemgetter
PAE=[['a',0,8],
['b',2,1],
['c',4,3],
['d',7,2],
['e',8,4]]
split_index = 1
print PAE[:split_index]+sorted(PAE[split_index:],key=itemgetter(2))
#=> [['a', 0, 8], ['b', 2, 1], ['d', 7, 2], ['c', 4, 3], ['e', 8, 4]]
``` | here without spliting, question is whats is the best for readability
```
PAE=[['a',0,8],
['b',2,1],
['c',4,3],
['d',7,2],
['e',8,4]]
print (sorted(PAE, key=lambda PAE: PAE[1] if not PAE[1] else PAE[2]))
>>> [['a', 0, 8], ['b', 2, 1], ['d', 7, 2], ['c', 4, 3], ['e', 8, 4]]
``` |
40,784,720 | I don't know if it is possible or not. I am trying to find a way of sorting a nested list on the following condition
1. i want to sort form 1 point to another (NOT the whole list only part of it)
2. the sorting should be done on the basis of 3rd element of the sublists
an Idea of what i want:
```
PAE=[['a',0,8],... | 2016/11/24 | [
"https://Stackoverflow.com/questions/40784720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5650215/"
] | Sort the slice **and write it back**:
```
>>> PAE[1:4] = sorted(PAE[1:4], key=itemgetter(2))
>>> PAE
[['a', 0, 8], ['b', 2, 1], ['d', 7, 2], ['c', 4, 3], ['e', 8, 4]]
``` | here without spliting, question is whats is the best for readability
```
PAE=[['a',0,8],
['b',2,1],
['c',4,3],
['d',7,2],
['e',8,4]]
print (sorted(PAE, key=lambda PAE: PAE[1] if not PAE[1] else PAE[2]))
>>> [['a', 0, 8], ['b', 2, 1], ['d', 7, 2], ['c', 4, 3], ['e', 8, 4]]
``` |
13,787,566 | I haven't used my python/virtual environments in a while, but I do have virtualenvironment wrapper installed also.
My question is, in the doc page it says to do this:
```
export WORKON_HOME=~/Envs
$ mkdir -p $WORKON_HOME
$ source /usr/local/bin/virtualenvwrapper.sh
$ mkvirtualenv env1
```
I simply did this at my pr... | 2012/12/09 | [
"https://Stackoverflow.com/questions/13787566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | If `WORKON_HOME` is not set, your default virtualenv folder will be set to `~/.virtualenvs`
(see [virtualenvwrapper.sh l.118](https://bitbucket.org/dhellmann/virtualenvwrapper/src/a766226010beb5df341bcb4bceb2befaba8603d4/virtualenvwrapper.sh?at=default#cl-118))
You will also use `WORKON_HOME` to specify to `pip` wh... | >
> I'm confused why I should be creating an environmental variable
> WORKON\_HOME and point it to the ~/Envs folder?
>
>
>
It's optional. You're confused (like I was) because the documentation is confusing.
>
> What does that do and how come mine works fine w/o it?
>
>
>
It tells `virtualenvwrapper` which... |
6,760,536 | I often find myself writing class constructors like this:
```
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
```
This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pyth... | 2011/07/20 | [
"https://Stackoverflow.com/questions/6760536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403401/"
] | How about this?
```
class foo:
def __init__(self, arg1, arg2, arg3):
for _prop in dir():
setattr(self, _prop, locals()[_prop])
```
This uses the builtin python dir function to iterate over *all* local variables.
It has a minor side effect of creating an extraneous self reference but you could... | What about iterating over the explicit variable names?
I.e.
```
class foo:
def __init__(self, arg1, arg2, arg3):
for arg_name in 'arg1,arg2,arg3'.split(','):
setattr(self, arg_name, locals()[arg_name])
f = foo(5,'six', 7)
```
Resulting with
```
print vars(f)
{'arg1': 5, 'arg2': 'six', 'a... |
6,760,536 | I often find myself writing class constructors like this:
```
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
```
This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pyth... | 2011/07/20 | [
"https://Stackoverflow.com/questions/6760536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403401/"
] | What about iterating over the explicit variable names?
I.e.
```
class foo:
def __init__(self, arg1, arg2, arg3):
for arg_name in 'arg1,arg2,arg3'.split(','):
setattr(self, arg_name, locals()[arg_name])
f = foo(5,'six', 7)
```
Resulting with
```
print vars(f)
{'arg1': 5, 'arg2': 'six', 'a... | For python >= 3.7 take a look at the [@dataclass](https://docs.python.org/3/library/dataclasses.html) class decorator.
Among other things, it handles your `__init__` boilerplate coding problem.
From the [doc](https://docs.python.org/3/library/dataclasses.html):
```
@dataclass
class InventoryItem:
name: str
un... |
6,760,536 | I often find myself writing class constructors like this:
```
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
```
This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pyth... | 2011/07/20 | [
"https://Stackoverflow.com/questions/6760536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403401/"
] | How about this?
```
class foo:
def __init__(self, arg1, arg2, arg3):
for _prop in dir():
setattr(self, _prop, locals()[_prop])
```
This uses the builtin python dir function to iterate over *all* local variables.
It has a minor side effect of creating an extraneous self reference but you could... | ```
class foo:
def __init__(self, **kwargs):
for arg_name, arg_value in kwargs.items():
setattr(self, arg_name, arg_value)
```
This requires arguments to be named:
```
obj = foo(arg1 = 1, arg2 = 2)
``` |
6,760,536 | I often find myself writing class constructors like this:
```
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
```
This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pyth... | 2011/07/20 | [
"https://Stackoverflow.com/questions/6760536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403401/"
] | How about this?
```
class foo:
def __init__(self, arg1, arg2, arg3):
for _prop in dir():
setattr(self, _prop, locals()[_prop])
```
This uses the builtin python dir function to iterate over *all* local variables.
It has a minor side effect of creating an extraneous self reference but you could... | the \*args is a sequence so you can access the items using indexing:
```
def __init__(self, *args):
if args:
self.arg1 = args[0]
self.arg2 = args[1]
self.arg3 = args[2]
...
```
or you can loop through all of them
```
for arg in args:
#d... |
6,760,536 | I often find myself writing class constructors like this:
```
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
```
This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pyth... | 2011/07/20 | [
"https://Stackoverflow.com/questions/6760536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403401/"
] | The most Pythonic way is what you've already written. If you are happy to require named arguments, you could do this:
```
class foo:
def __init__(self, **kwargs):
vars(self).update(kwargs)
``` | How about this?
```
class foo:
def __init__(self, arg1, arg2, arg3):
for _prop in dir():
setattr(self, _prop, locals()[_prop])
```
This uses the builtin python dir function to iterate over *all* local variables.
It has a minor side effect of creating an extraneous self reference but you could... |
6,760,536 | I often find myself writing class constructors like this:
```
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
```
This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pyth... | 2011/07/20 | [
"https://Stackoverflow.com/questions/6760536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403401/"
] | Provided answers rely on `*vargs` and `**kargs` arguments, which might not be convenient at all if you want to restrict to a specific set of arguments with specific names: you'll have to do all the checking by hand.
Here's a decorator that stores the provided arguments of a method in its bound instance as attributes w... | For python >= 3.7 take a look at the [@dataclass](https://docs.python.org/3/library/dataclasses.html) class decorator.
Among other things, it handles your `__init__` boilerplate coding problem.
From the [doc](https://docs.python.org/3/library/dataclasses.html):
```
@dataclass
class InventoryItem:
name: str
un... |
6,760,536 | I often find myself writing class constructors like this:
```
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
```
This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pyth... | 2011/07/20 | [
"https://Stackoverflow.com/questions/6760536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403401/"
] | ```
class foo:
def __init__(self, **kwargs):
for arg_name, arg_value in kwargs.items():
setattr(self, arg_name, arg_value)
```
This requires arguments to be named:
```
obj = foo(arg1 = 1, arg2 = 2)
``` | As others have noted, you should probably stick to your original 'pythonic' method in most cases.
However, if you really want to go the whole nine yards, here's some code that neatly deals with args, keyword args if desired, and avoids boilerplate repetition:
```
def convert_all_args_to_attribs(self, class_locals):
... |
6,760,536 | I often find myself writing class constructors like this:
```
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
```
This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pyth... | 2011/07/20 | [
"https://Stackoverflow.com/questions/6760536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403401/"
] | What about iterating over the explicit variable names?
I.e.
```
class foo:
def __init__(self, arg1, arg2, arg3):
for arg_name in 'arg1,arg2,arg3'.split(','):
setattr(self, arg_name, locals()[arg_name])
f = foo(5,'six', 7)
```
Resulting with
```
print vars(f)
{'arg1': 5, 'arg2': 'six', 'a... | As others have noted, you should probably stick to your original 'pythonic' method in most cases.
However, if you really want to go the whole nine yards, here's some code that neatly deals with args, keyword args if desired, and avoids boilerplate repetition:
```
def convert_all_args_to_attribs(self, class_locals):
... |
6,760,536 | I often find myself writing class constructors like this:
```
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
```
This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pyth... | 2011/07/20 | [
"https://Stackoverflow.com/questions/6760536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403401/"
] | The most Pythonic way is what you've already written. If you are happy to require named arguments, you could do this:
```
class foo:
def __init__(self, **kwargs):
vars(self).update(kwargs)
``` | For python >= 3.7 take a look at the [@dataclass](https://docs.python.org/3/library/dataclasses.html) class decorator.
Among other things, it handles your `__init__` boilerplate coding problem.
From the [doc](https://docs.python.org/3/library/dataclasses.html):
```
@dataclass
class InventoryItem:
name: str
un... |
6,760,536 | I often find myself writing class constructors like this:
```
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
```
This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pyth... | 2011/07/20 | [
"https://Stackoverflow.com/questions/6760536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403401/"
] | You can do that both for positional and for keyword arguments:
```
class Foo(object):
def __init__(self, *args, **kwargs):
for arg in args:
print arg
for kwarg in kwargs:
print kwarg
```
`*` packs positional arguments into a tuple and `**` keyword arguments into a dictiona... | What about iterating over the explicit variable names?
I.e.
```
class foo:
def __init__(self, arg1, arg2, arg3):
for arg_name in 'arg1,arg2,arg3'.split(','):
setattr(self, arg_name, locals()[arg_name])
f = foo(5,'six', 7)
```
Resulting with
```
print vars(f)
{'arg1': 5, 'arg2': 'six', 'a... |
10,813,575 | I am working on a html with selenium. After clicking the last link, pop up comes which says as save a file.
using selenium I am recording all the events and then generating the selenium RC script.
I want to know that how to get the pop up file from code using python? | 2012/05/30 | [
"https://Stackoverflow.com/questions/10813575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297123/"
] | In the case of saving a file, you can get around the popup box by configuring the options of your browser profile. See [this](https://stackoverflow.com/questions/12099250/python-webcrawler-downloading-files/12099438) answer for an explanation using Firefox. General idea is that you need to tell Firefox itself to not pr... | Webdriver cannot communicate with the browser modal popup.
But this can be done, check out the below link for your answer
<http://blog.codecentric.de/en/2010/07/file-downloads-with-selenium-mission-impossible/> |
24,374,400 | I am trying to open an https URL using the [`urlopen`](https://docs.python.org/3.2/library/urllib.request.html#urllib.request.urlopen) method in Python 3's [`urllib.request`](https://docs.python.org/3.2/library/urllib.request.html) module. It seems to work fine, but the documentation warns that "[i]f neither `cafile` n... | 2014/06/23 | [
"https://Stackoverflow.com/questions/24374400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28324/"
] | Works in python 2.7 and above
```
context = ssl.create_default_context(cafile=certifi.where())
req = urllib2.urlopen(urllib2.Request(url, body, headers), context=context)
``` | Different Linux distributives have different pack names. I tested in Centos and Ubuntu. These certificate bundles are updates with system update. So you may just detect which bundle is available and use it with `urlopen`.
```
cafile = None
for i in [
'/etc/ssl/certs/ca-bundle.crt',
'/etc/ssl/certs/ca-certifica... |
24,374,400 | I am trying to open an https URL using the [`urlopen`](https://docs.python.org/3.2/library/urllib.request.html#urllib.request.urlopen) method in Python 3's [`urllib.request`](https://docs.python.org/3.2/library/urllib.request.html) module. It seems to work fine, but the documentation warns that "[i]f neither `cafile` n... | 2014/06/23 | [
"https://Stackoverflow.com/questions/24374400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28324/"
] | You can download the certificates Mozilla in a format usable for urllib (e.g. PEM format) at <http://curl.haxx.se/docs/caextract.html> | Different Linux distributives have different pack names. I tested in Centos and Ubuntu. These certificate bundles are updates with system update. So you may just detect which bundle is available and use it with `urlopen`.
```
cafile = None
for i in [
'/etc/ssl/certs/ca-bundle.crt',
'/etc/ssl/certs/ca-certifica... |
24,374,400 | I am trying to open an https URL using the [`urlopen`](https://docs.python.org/3.2/library/urllib.request.html#urllib.request.urlopen) method in Python 3's [`urllib.request`](https://docs.python.org/3.2/library/urllib.request.html) module. It seems to work fine, but the documentation warns that "[i]f neither `cafile` n... | 2014/06/23 | [
"https://Stackoverflow.com/questions/24374400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28324/"
] | Elias Zamarias answer still works, but gives a deprecation warning:
```
DeprecationWarning: cafile, cpath and cadefault are deprecated, use a custom context instead.
```
I was able to solve the same problem this way instead (using Python 3.7.0):
```
import ssl
import urllib.request
ssl_context = ssl.SSLContext(ssl... | ```
import certifi
import ssl
import urllib.request
try:
from urllib.request import HTTPSHandler
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.options |= ssl.OP_NO_SSLv2
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(certifi.where(), None)
https_handler = HTTPSHand... |
24,374,400 | I am trying to open an https URL using the [`urlopen`](https://docs.python.org/3.2/library/urllib.request.html#urllib.request.urlopen) method in Python 3's [`urllib.request`](https://docs.python.org/3.2/library/urllib.request.html) module. It seems to work fine, but the documentation warns that "[i]f neither `cafile` n... | 2014/06/23 | [
"https://Stackoverflow.com/questions/24374400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28324/"
] | I found a library that does what I'm trying to do: [Certifi](https://certifi.io/). It can be installed by running `pip install certifi` from the command line.
Making requests and verifying them is now easy:
```
import certifi
import urllib.request
urllib.request.urlopen("https://example.com/", cafile=certifi.where()... | Different Linux distributives have different pack names. I tested in Centos and Ubuntu. These certificate bundles are updates with system update. So you may just detect which bundle is available and use it with `urlopen`.
```
cafile = None
for i in [
'/etc/ssl/certs/ca-bundle.crt',
'/etc/ssl/certs/ca-certifica... |
24,374,400 | I am trying to open an https URL using the [`urlopen`](https://docs.python.org/3.2/library/urllib.request.html#urllib.request.urlopen) method in Python 3's [`urllib.request`](https://docs.python.org/3.2/library/urllib.request.html) module. It seems to work fine, but the documentation warns that "[i]f neither `cafile` n... | 2014/06/23 | [
"https://Stackoverflow.com/questions/24374400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28324/"
] | Works in python 2.7 and above
```
context = ssl.create_default_context(cafile=certifi.where())
req = urllib2.urlopen(urllib2.Request(url, body, headers), context=context)
``` | Elias Zamarias answer still works, but gives a deprecation warning:
```
DeprecationWarning: cafile, cpath and cadefault are deprecated, use a custom context instead.
```
I was able to solve the same problem this way instead (using Python 3.7.0):
```
import ssl
import urllib.request
ssl_context = ssl.SSLContext(ssl... |
24,374,400 | I am trying to open an https URL using the [`urlopen`](https://docs.python.org/3.2/library/urllib.request.html#urllib.request.urlopen) method in Python 3's [`urllib.request`](https://docs.python.org/3.2/library/urllib.request.html) module. It seems to work fine, but the documentation warns that "[i]f neither `cafile` n... | 2014/06/23 | [
"https://Stackoverflow.com/questions/24374400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28324/"
] | Works in python 2.7 and above
```
context = ssl.create_default_context(cafile=certifi.where())
req = urllib2.urlopen(urllib2.Request(url, body, headers), context=context)
``` | You can download the certificates Mozilla in a format usable for urllib (e.g. PEM format) at <http://curl.haxx.se/docs/caextract.html> |
24,374,400 | I am trying to open an https URL using the [`urlopen`](https://docs.python.org/3.2/library/urllib.request.html#urllib.request.urlopen) method in Python 3's [`urllib.request`](https://docs.python.org/3.2/library/urllib.request.html) module. It seems to work fine, but the documentation warns that "[i]f neither `cafile` n... | 2014/06/23 | [
"https://Stackoverflow.com/questions/24374400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28324/"
] | Elias Zamarias answer still works, but gives a deprecation warning:
```
DeprecationWarning: cafile, cpath and cadefault are deprecated, use a custom context instead.
```
I was able to solve the same problem this way instead (using Python 3.7.0):
```
import ssl
import urllib.request
ssl_context = ssl.SSLContext(ssl... | Different Linux distributives have different pack names. I tested in Centos and Ubuntu. These certificate bundles are updates with system update. So you may just detect which bundle is available and use it with `urlopen`.
```
cafile = None
for i in [
'/etc/ssl/certs/ca-bundle.crt',
'/etc/ssl/certs/ca-certifica... |
24,374,400 | I am trying to open an https URL using the [`urlopen`](https://docs.python.org/3.2/library/urllib.request.html#urllib.request.urlopen) method in Python 3's [`urllib.request`](https://docs.python.org/3.2/library/urllib.request.html) module. It seems to work fine, but the documentation warns that "[i]f neither `cafile` n... | 2014/06/23 | [
"https://Stackoverflow.com/questions/24374400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28324/"
] | You can download the certificates Mozilla in a format usable for urllib (e.g. PEM format) at <http://curl.haxx.se/docs/caextract.html> | ```
import certifi
import ssl
import urllib.request
try:
from urllib.request import HTTPSHandler
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.options |= ssl.OP_NO_SSLv2
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(certifi.where(), None)
https_handler = HTTPSHand... |
24,374,400 | I am trying to open an https URL using the [`urlopen`](https://docs.python.org/3.2/library/urllib.request.html#urllib.request.urlopen) method in Python 3's [`urllib.request`](https://docs.python.org/3.2/library/urllib.request.html) module. It seems to work fine, but the documentation warns that "[i]f neither `cafile` n... | 2014/06/23 | [
"https://Stackoverflow.com/questions/24374400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28324/"
] | I found a library that does what I'm trying to do: [Certifi](https://certifi.io/). It can be installed by running `pip install certifi` from the command line.
Making requests and verifying them is now easy:
```
import certifi
import urllib.request
urllib.request.urlopen("https://example.com/", cafile=certifi.where()... | ```
import certifi
import ssl
import urllib.request
try:
from urllib.request import HTTPSHandler
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.options |= ssl.OP_NO_SSLv2
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(certifi.where(), None)
https_handler = HTTPSHand... |
24,374,400 | I am trying to open an https URL using the [`urlopen`](https://docs.python.org/3.2/library/urllib.request.html#urllib.request.urlopen) method in Python 3's [`urllib.request`](https://docs.python.org/3.2/library/urllib.request.html) module. It seems to work fine, but the documentation warns that "[i]f neither `cafile` n... | 2014/06/23 | [
"https://Stackoverflow.com/questions/24374400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28324/"
] | I found a library that does what I'm trying to do: [Certifi](https://certifi.io/). It can be installed by running `pip install certifi` from the command line.
Making requests and verifying them is now easy:
```
import certifi
import urllib.request
urllib.request.urlopen("https://example.com/", cafile=certifi.where()... | Elias Zamarias answer still works, but gives a deprecation warning:
```
DeprecationWarning: cafile, cpath and cadefault are deprecated, use a custom context instead.
```
I was able to solve the same problem this way instead (using Python 3.7.0):
```
import ssl
import urllib.request
ssl_context = ssl.SSLContext(ssl... |
9,066,774 | I downloaded Open ERP server & web, having decided against the thicker gtk. I added the 2 as projects in eclipse, pydev running on Ubuntu 11.10 and started then up. I went through the web client setup & I though the installation had been done. At some point though I had executed a script that tried to copy all the bits... | 2012/01/30 | [
"https://Stackoverflow.com/questions/9066774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536187/"
] | I feel your pain. I went through the same process a couple of years ago when I started working with OpenERP. The good news is that it's not too hard to set up, and OpenERP runs smoothly in Eclipse with PyDev.
Start by looking at the [developer book for OpenERP](http://doc.openerp.com/v6.0/developer/1_1_Introduction/in... | using eclipse kepler sr 1, pydev 3.1.0, openerp 7.0 from launchpad using bzr, ubuntu 13.10. This is how I got the whole thing loaded. I have skipped the part where I got the thing to work. This only covers retrieving the sources and being able to open/modify the openerp source in eclipse/pydev.
There are three bzr rep... |
46,893,460 | When I try to let my bot join my voice channel, I get this error:
`await client.join_voice_channel(voice_channel)` (line that generates the error)
```
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 50, in wrapped
ret = yield from coro(*args, **k... | 2017/10/23 | [
"https://Stackoverflow.com/questions/46893460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715621/"
] | This is the code i use to make it work.
```
#Bot.py
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from discord.voice_client import VoiceClient
import asyncio
bot = commands.Bot(command_prefix="|")
async def on_ready():
print ("Ready")
@bot.command(pass_context=True)
async ... | Get rid of the
>
> from discord.voice\_client import VoiceClient
> line and it shoudl be ok.
>
>
> |
46,893,460 | When I try to let my bot join my voice channel, I get this error:
`await client.join_voice_channel(voice_channel)` (line that generates the error)
```
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 50, in wrapped
ret = yield from coro(*args, **k... | 2017/10/23 | [
"https://Stackoverflow.com/questions/46893460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715621/"
] | This is the code i use to make it work.
```
#Bot.py
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from discord.voice_client import VoiceClient
import asyncio
bot = commands.Bot(command_prefix="|")
async def on_ready():
print ("Ready")
@bot.command(pass_context=True)
async ... | Try this
```
await bot.join_voice_channel(channel)
``` |
46,893,460 | When I try to let my bot join my voice channel, I get this error:
`await client.join_voice_channel(voice_channel)` (line that generates the error)
```
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 50, in wrapped
ret = yield from coro(*args, **k... | 2017/10/23 | [
"https://Stackoverflow.com/questions/46893460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715621/"
] | Get rid of the
>
> from discord.voice\_client import VoiceClient
> line and it shoudl be ok.
>
>
> | Try this
```
await bot.join_voice_channel(channel)
``` |
61,249,502 | Today, I was testing my old python script, it was about fetching some details from an API and write then in a file. Until my last test it was working perfectly fine but today when I executed the script it worked, I mean no error at all but it neither write nor created any file. The API is returning complete data - I te... | 2020/04/16 | [
"https://Stackoverflow.com/questions/61249502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8332158/"
] | Using `'a'` on the `open` call to open the file in append mode (as shown in your code) should work just fine.
I don't think your issue is on the Python side. The next thing to check are your directory permissions:
```
$ ls -al domain.log
-rw-r--r-- 1 taylor staff 60 Apr 16 07:57 domain.log
```
Here's my output a... | It may be related to file permission or its directory. Use `ls -la` to see file and folder permissions. |
59,440,445 | I'm trying to scrape farefetch.com (<https://www.farfetch.com/ch/shopping/men/sale/all/items.aspx?page=1&view=180&scale=282>) with Beautifulsoup4 and I am not able to find the same components (tags or text in general) of the *parsed* text (dumped to soup.html) as in the browser in the dev tools view (when searching for... | 2019/12/21 | [
"https://Stackoverflow.com/questions/59440445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8868950/"
] | Based on your comment, here is an example how you could extract some information from products that are on discount:
```
import requests
from bs4 import BeautifulSoup
url = "https://www.farfetch.com/ch/shopping/men/sale/all/items.aspx?page=1&view=180&scale=282"
soup = BeautifulSoup(requests.get(url).text, 'html.pars... | The following helped me:
instead of the following code
```
page_soup = soup(page_html, "html.parser")
```
use
```
page_soup = soup(page_html, "html")
``` |
50,967,265 | Please advice how to convert following using python
from:
```
2010-01-04 00:00:00
```
to:
```
2010-04-01 00:00:00
```
I have tried
```
df.Month = pd.to_datetime(df.Month, format('%Y/%m/%d'))
```
but didn't work
Thanks in advance | 2018/06/21 | [
"https://Stackoverflow.com/questions/50967265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/405818/"
] | Use `.dt.strftime("%Y-%d-%m")`
**Ex:**
```
import pandas as pd
df = pd.DataFrame({"Date": ["2010-01-04 00:00:00"]})
print( pd.to_datetime(df["Date"]).dt.strftime("%Y-%d-%m") )
```
**Output:**
```
0 2010-04-01
Name: Date, dtype: object
``` | try the following using datetime parser and returning it in a defined format:
```
from datetime import datetime
old_date_string='2010-01-04 00:00:00'
dt=datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
new_date_string=dt.strftime('%Y-%d-%m %H:%M:%S')
```
However, when you want to work with the date I would suggest using th... |
25,326,649 | I would like to know if there is a faster and more "pythonic" way of doing the following, e.g. using some built in methods.
Given a pandas DataFrame or numpy array of floats, if the value is equal or smaller than 0.5 I need to calculate the reciprocal value and multiply with -1 and replace the old value with the newly ... | 2014/08/15 | [
"https://Stackoverflow.com/questions/25326649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2539824/"
] | If we are talking about **arrays**:
```
import numpy as np
a = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6], dtype=np.float)
print 1 / a[a <= 0.5] * (-1)
```
This will, however only return the values smaller than `0.5`.
Alternatively use `np.where`:
```
import numpy as np
a = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6], dt... | The typical trick is to write a general mathematical operation to apply to the whole column, but then use indicators to select rows for which we actually apply it:
```
df.loc[df.A < 0.5, 'A'] = - 1 / df.A[df.A < 0.5]
In[13]: df
Out[13]:
A B C
0 -inf 0 E
1 -10.000000 1 L
2 -5.000000 ... |
25,326,649 | I would like to know if there is a faster and more "pythonic" way of doing the following, e.g. using some built in methods.
Given a pandas DataFrame or numpy array of floats, if the value is equal or smaller than 0.5 I need to calculate the reciprocal value and multiply with -1 and replace the old value with the newly ... | 2014/08/15 | [
"https://Stackoverflow.com/questions/25326649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2539824/"
] | The typical trick is to write a general mathematical operation to apply to the whole column, but then use indicators to select rows for which we actually apply it:
```
df.loc[df.A < 0.5, 'A'] = - 1 / df.A[df.A < 0.5]
In[13]: df
Out[13]:
A B C
0 -inf 0 E
1 -10.000000 1 L
2 -5.000000 ... | As in **@jojo**'s answer, but using pandas:
```
df.A = df.A.where(df.A > 0.5, (1/df.A)*-1)
```
or
```
df.A.where(df.A > 0.5, (1/df.A)*-1, inplace=True) # this should be faster
```
.where docstring:
>
> Definition: df.A.where(self, cond, other=nan, inplace=False,
> axis=None, level=None, try\_cast=False, raise\_... |
25,326,649 | I would like to know if there is a faster and more "pythonic" way of doing the following, e.g. using some built in methods.
Given a pandas DataFrame or numpy array of floats, if the value is equal or smaller than 0.5 I need to calculate the reciprocal value and multiply with -1 and replace the old value with the newly ... | 2014/08/15 | [
"https://Stackoverflow.com/questions/25326649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2539824/"
] | If we are talking about **arrays**:
```
import numpy as np
a = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6], dtype=np.float)
print 1 / a[a <= 0.5] * (-1)
```
This will, however only return the values smaller than `0.5`.
Alternatively use `np.where`:
```
import numpy as np
a = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6], dt... | As in **@jojo**'s answer, but using pandas:
```
df.A = df.A.where(df.A > 0.5, (1/df.A)*-1)
```
or
```
df.A.where(df.A > 0.5, (1/df.A)*-1, inplace=True) # this should be faster
```
.where docstring:
>
> Definition: df.A.where(self, cond, other=nan, inplace=False,
> axis=None, level=None, try\_cast=False, raise\_... |
21,444,951 | I had an app that was working properly with old verions of wxpython
Now with wxpython 3.0, when trying to run the app, I get the following error
```
File "C:\Python27\lib\site-packages\wx-3.0-msw\wx\_controls.py", line 6523, in __init__
_controls_.DatePickerCtrl_swiginit(self,_controls_.new_DatePickerCtrl(*args... | 2014/01/29 | [
"https://Stackoverflow.com/questions/21444951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433261/"
] | I know it's been a while since this question was asked, but I just had the same issue and thought I'd add my solution in case someone else finds this thread. Basically what's happening is that the locale of your script is somehow conflicting with the locale of the machine, although I'm not sure how or why. Maybe someon... | I've just faced the same kind of issue.
It seems we need to set the locale before using the wx.App :
```
import locale
locale.setlocale(locale.LC_ALL, 'C')
```
Two links helped me to solve this issue :
* Solution found in PHP : <https://github.com/wxphp/wxphp/issues/108>
* How to do the same in Python : [How to set... |
11,908,725 | ```
#!/bin/python
import os
pipe=os.popen("ls /etc -alR| grep \"^[-l]\"|wc -l") #Expr1
a=int(pipe.read())
pipe.close()
b=sum([len(files) for root,dirs,files in os.walk("/etc")]) #Expr2
print a
print b
print "a equals to b ?", str(a==b) #False
print "Why?"
```
What is the **difference** between **Expr1**'s f... | 2012/08/10 | [
"https://Stackoverflow.com/questions/11908725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1545784/"
] | If you use walk, errors are ignored (see [this](http://docs.python.org/library/os.htm)), and ls sends a message for each error. These count as words. | On my machine, /etc is a symlink to /private/etc, so `ls /etc` has only one line of output. `ls /etc/` give the expected equivalence between `ls` and `os.walk`. |
11,908,725 | ```
#!/bin/python
import os
pipe=os.popen("ls /etc -alR| grep \"^[-l]\"|wc -l") #Expr1
a=int(pipe.read())
pipe.close()
b=sum([len(files) for root,dirs,files in os.walk("/etc")]) #Expr2
print a
print b
print "a equals to b ?", str(a==b) #False
print "Why?"
```
What is the **difference** between **Expr1**'s f... | 2012/08/10 | [
"https://Stackoverflow.com/questions/11908725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1545784/"
] | **Short answer:**
`ls -laR | grep "^[-l]"` counts symlinks to directories.
It matches any line that begins with `l` and that includes symlinks to directories.
In contrast, `[files for root, dirs, files in os.walk('/etc')]`
**does not count symlinks to directories**. It ignores all directories and lists only files.
-... | If you use walk, errors are ignored (see [this](http://docs.python.org/library/os.htm)), and ls sends a message for each error. These count as words. |
11,908,725 | ```
#!/bin/python
import os
pipe=os.popen("ls /etc -alR| grep \"^[-l]\"|wc -l") #Expr1
a=int(pipe.read())
pipe.close()
b=sum([len(files) for root,dirs,files in os.walk("/etc")]) #Expr2
print a
print b
print "a equals to b ?", str(a==b) #False
print "Why?"
```
What is the **difference** between **Expr1**'s f... | 2012/08/10 | [
"https://Stackoverflow.com/questions/11908725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1545784/"
] | **Short answer:**
`ls -laR | grep "^[-l]"` counts symlinks to directories.
It matches any line that begins with `l` and that includes symlinks to directories.
In contrast, `[files for root, dirs, files in os.walk('/etc')]`
**does not count symlinks to directories**. It ignores all directories and lists only files.
-... | On my machine, /etc is a symlink to /private/etc, so `ls /etc` has only one line of output. `ls /etc/` give the expected equivalence between `ls` and `os.walk`. |
56,083,285 | I'm trying to write a regex in python that that will either match a URL (for example <https://www.foo.com/>) or a domain that starts with "sc-domain:" but doesn't not have https or a path.
For example, the below entries should pass
```
https://www.foo.com/
https://www.foo.com/bar/
sc-domain:www.foo.com
```
However ... | 2019/05/10 | [
"https://Stackoverflow.com/questions/56083285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3117494/"
] | ```
^((?:https://\S+)|(?:sc-domain:[^/\s]+))$
```
You can try this.
See demo.
<https://regex101.com/r/xXSayK/2> | You can use this regex,
```
^(?:https?://www\.foo\.com(?:/\S*)*|sc-domain:www\.foo\.com)$
```
**Explanation:**
* `^` - Start of line
* `(?:` - Start of non-group for alternation
* `https?://www\.foo\.com(?:/\S*)*` - This matches a URL starting with http:// or https:// followed by www.foo.com and further optionally ... |
56,083,285 | I'm trying to write a regex in python that that will either match a URL (for example <https://www.foo.com/>) or a domain that starts with "sc-domain:" but doesn't not have https or a path.
For example, the below entries should pass
```
https://www.foo.com/
https://www.foo.com/bar/
sc-domain:www.foo.com
```
However ... | 2019/05/10 | [
"https://Stackoverflow.com/questions/56083285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3117494/"
] | ```
^((?:https://\S+)|(?:sc-domain:[^/\s]+))$
```
You can try this.
See demo.
<https://regex101.com/r/xXSayK/2> | [This expression](https://regex101.com/r/7w3zbt/1) also would do that using two simple capturing groups that you can modify as you wish:
```
^((http|https)(:\/\/www.foo.com)(\/.*))|(sc-domain:www.foo.com)$
```
I have also added http, which you can remove it if it may be undesired.
[![enter image description here]... |
65,391,704 | I am working with Jupyter Notebook, writing some python code using numpy library.
For some reason, The output of arrays (as well as lists and strings) are displyed from right to left.
[](https://i.stack.imgur.com/eGhQ2.png) | 2020/12/21 | [
"https://Stackoverflow.com/questions/65391704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14864624/"
] | Is your system set up for Hebrew? Note that the `:[4] In` is on the right as well. That may trigger array output to be right-to-left.
From [this comment on github](https://github.com/ipython/ipython/issues/10980):
>
> Press Ctrl-Shift-F to bring up the command palette. Search for 'rtl'
> and select 'toggle rtl layou... | Thanks.
Now it works fine.
My browser was set to hebrew and by changing to english it fixed the problem. |
28,079,035 | OS: CentOS 6.6
Python 2.7
So, I've (re)installed Canopy after it suddenly stopped working after an abrupt shutdown. It worked fine immediately after the install (I installed as my default Python). But after one reboot, when I try to open it with /root/Canopy/canopy (the icon under applications no longer works, either),... | 2015/01/21 | [
"https://Stackoverflow.com/questions/28079035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4480411/"
] | It turns out that I was onto something with my last comment.
I'd downloaded a bunch of biology modules that depend on python, and so many of them came with their own install. When I added the modules to ~/.bashrc, my bash began calling them in advance of my original CentOS install. Resetting ~/.bashrc and restarting (f... | Try seeing if you have `posixpath` by typing `import posixpath`:
```
>>> import os.path
>>> os.path
<module 'posixpath' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> ^D
bash-3.2$ python
>>> import posixpath
>>> posixpath
<module 'posixpath' from '/Library/Frameworks/Python.f... |
28,079,035 | OS: CentOS 6.6
Python 2.7
So, I've (re)installed Canopy after it suddenly stopped working after an abrupt shutdown. It worked fine immediately after the install (I installed as my default Python). But after one reboot, when I try to open it with /root/Canopy/canopy (the icon under applications no longer works, either),... | 2015/01/21 | [
"https://Stackoverflow.com/questions/28079035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4480411/"
] | Just fixed this on OSX with:
```
brew uninstall python
brew install python
```
No idea why, never seen it in 5 years of working with Python :S | Try seeing if you have `posixpath` by typing `import posixpath`:
```
>>> import os.path
>>> os.path
<module 'posixpath' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> ^D
bash-3.2$ python
>>> import posixpath
>>> posixpath
<module 'posixpath' from '/Library/Frameworks/Python.f... |
17,703,956 | I am using Hash in Ruby, just check whether a certain word is in the “pairs” class and replace them. Initially I code in python and want to convert it into ruby that I am not familiar with. Here is the ruby code I wrote.
```
import sys
pairs = {'butter' => 'flies', 'cheese' => 'wheel', 'milk'=> 'expensive'}
for line... | 2013/07/17 | [
"https://Stackoverflow.com/questions/17703956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592038/"
] | Try this:
```
pairs = {'butter' => 'flies', 'cheese' => 'wheel', 'milk'=> 'expensive'}
line = ARGV.join(' ').split(' ').map do |word|
pairs.include?(word) ? pairs[word] : word
end.join(" ")
puts line
```
This will loop over each item passed to the script and return the word or the replacement word, joined by a s... | `for` is generally not used in Ruby, as it's got some unusual scoping.
Here's how I would write it:
```
pairs = { "butter" => "flies", "cheese" => "wheel", "milk" => "expensive" }
until $stdin.eof?
line = $stdin.gets
pairs.each do |from, to|
line = line.gsub(from, to)
end
line
end
```
`import` doesn't ... |
7,958,213 | So I am trying to put the result of a query in a string. Let's say row by row (I don't need all the fields by the way), but that's not the point. I am using python against a sqlite db.
the problem is that when some of the fields are null, python will write None instead of "" or some blank neutral thing.
example:
```... | 2011/10/31 | [
"https://Stackoverflow.com/questions/7958213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/918420/"
] | Inheriting from *object* automatically brings the *type* metaclass along with it. This overrides your module level *\_\_metaclass\_\_* specification.
If the metaclass is specified at the class level, then *object* won't override it:
```
def metaclass(future_class_name, future_class_parents, future_class_attrs):
p... | The specification [specifies the order in which Python will look for a metaclass](http://docs.python.org/reference/datamodel.html?highlight=__metaclass__#customizing-class-creation):
>
> The appropriate metaclass is determined by the following precedence
> rules:
>
>
> * If `dict['__metaclass__']` exists, it is us... |
17,682,571 | This is the command that I am using. I have followed the steps in <https://developers.google.com/appengine/docs/python/tools/uploadingdata>. When I use the same command for the same application that I have hosted on the web, the command works and I can see the data in the datastore. But the same command is not working ... | 2013/07/16 | [
"https://Stackoverflow.com/questions/17682571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2582075/"
] | If your parameters are right but the authentication is failing, pass in the -oauth2 flag:
appcfg.py --oauth2 update app.yaml
Then the rest of your appcfg.py should authenticate. If it still doesn't work your appid or url is probably off. | if you are using mac, you should have administration privileges on your mac. if not, put sudo on the beginning of the command |
17,682,571 | This is the command that I am using. I have followed the steps in <https://developers.google.com/appengine/docs/python/tools/uploadingdata>. When I use the same command for the same application that I have hosted on the web, the command works and I can see the data in the datastore. But the same command is not working ... | 2013/07/16 | [
"https://Stackoverflow.com/questions/17682571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2582075/"
] | If your parameters are right but the authentication is failing, pass in the -oauth2 flag:
appcfg.py --oauth2 update app.yaml
Then the rest of your appcfg.py should authenticate. If it still doesn't work your appid or url is probably off. | I'm not exactly sure why that error gets raised unfortunately, all I know is that it can be solved by passing the `--email` flag. Simple run this and when it asks for a password, hit `Enter`.
```
appcfg.py upload_data --url=http://localhost:8080/_ah/remote_api/ --filename=output.csv --application=[your-app-id] --email... |
17,682,571 | This is the command that I am using. I have followed the steps in <https://developers.google.com/appengine/docs/python/tools/uploadingdata>. When I use the same command for the same application that I have hosted on the web, the command works and I can see the data in the datastore. But the same command is not working ... | 2013/07/16 | [
"https://Stackoverflow.com/questions/17682571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2582075/"
] | If your parameters are right but the authentication is failing, pass in the -oauth2 flag:
appcfg.py --oauth2 update app.yaml
Then the rest of your appcfg.py should authenticate. If it still doesn't work your appid or url is probably off. | I was having this same problem, and it turned out to be that I had a wildcard rule that was getting in the way of the remote\_api url.
Below is an excerpt of my app.yaml. (I was archiving a legacy app, so I didn't care that no one could access the site now.)
```
builtins:
- remote_api: on
handlers:
# - url: /.*
# ... |
22,726,553 | Trying to iterate through a number string in python and print the product of the first 5 numbers,then the second 5, then the third 5, etc etc. Unfortunately, I just keep getting the product of the first five digits over and over. Eventually I'll append them to a list. Why is my code stuck?
edit: Original number is an... | 2014/03/29 | [
"https://Stackoverflow.com/questions/22726553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3462587/"
] | There are a few problems with your code:
1) Your `s+=1` indentation is incorrect
2) It should be `s+=5` instead (assuming you want products of 1-5, 6-10, 11-15 and so on otherwise s+=1 is fine)
```
def product_of_digits(number):
d = str(number)
s = 0
while s < (len(d)-5):
print (int(d[s])*int(d[s+... | numpy.product([int(i) for i in str(s)])
where s is the number. |
22,726,553 | Trying to iterate through a number string in python and print the product of the first 5 numbers,then the second 5, then the third 5, etc etc. Unfortunately, I just keep getting the product of the first five digits over and over. Eventually I'll append them to a list. Why is my code stuck?
edit: Original number is an... | 2014/03/29 | [
"https://Stackoverflow.com/questions/22726553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3462587/"
] | Let me list out the mistakes in the program.
1. You are iterating over `d` for nothing. You don't need that.
2. `s += 1` is not part of the while loop. So, `s` will never get incremented, leading to infinite loop.
3. `print (product_of_digits(a))` is inside the function itself, where `a` is not defined.
4. To find the... | numpy.product([int(i) for i in str(s)])
where s is the number. |
35,539,657 | Environment
===========
* Raspberry Pi 2
* raspbian-jessie-lite
* Windows 8.1
* PuTTY 0.66 (SSH)
Issue
=====
Can't get cron to execute a python script with sudo. The script deals with GPIO input so it should be called with sudo. The program is supposed to save temperature and humidity to files but `cat temp.txt` and... | 2016/02/21 | [
"https://Stackoverflow.com/questions/35539657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061339/"
] | I suggest learning how to use Swing. You will have several different classes interacting together. In fact, it is considered good practice to keep separate the code which creates and manages the GUI from the code which performs the underlying logic and data manipulation. | I would recommend using netbeans to start with. From there you can easily select pre created classes such as Jframes. Much easier to learn. You can create a GUI from there by dragging and dropping buttons and whatever you need.
Here is a youtube tut to create GUI's in netbeans.
<https://www.youtube.com/watch?v=LFr06Z... |
35,539,657 | Environment
===========
* Raspberry Pi 2
* raspbian-jessie-lite
* Windows 8.1
* PuTTY 0.66 (SSH)
Issue
=====
Can't get cron to execute a python script with sudo. The script deals with GPIO input so it should be called with sudo. The program is supposed to save temperature and humidity to files but `cat temp.txt` and... | 2016/02/21 | [
"https://Stackoverflow.com/questions/35539657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061339/"
] | Another suggestion:
Learn JavaFX and download SceneBuilder from Oracle: [here](http://www.oracle.com/technetwork/java/javase/downloads/sb2download-2177776.html)
At my university they have stopped teaching Swing and started to teach JavaFX, saying JavaFX has taken over the throne from Swing.
SceneBuilder is very easy ... | I would recommend using netbeans to start with. From there you can easily select pre created classes such as Jframes. Much easier to learn. You can create a GUI from there by dragging and dropping buttons and whatever you need.
Here is a youtube tut to create GUI's in netbeans.
<https://www.youtube.com/watch?v=LFr06Z... |
35,539,657 | Environment
===========
* Raspberry Pi 2
* raspbian-jessie-lite
* Windows 8.1
* PuTTY 0.66 (SSH)
Issue
=====
Can't get cron to execute a python script with sudo. The script deals with GPIO input so it should be called with sudo. The program is supposed to save temperature and humidity to files but `cat temp.txt` and... | 2016/02/21 | [
"https://Stackoverflow.com/questions/35539657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061339/"
] | >
> How will I declare aan instance variable inside the GUI class?
>
>
>
Like as shown bellow, you could start with something like this, note that your application should be able to hand out your data to other classes, for instance I changed `getBasicStats()` to return a `String`, this way you can use your applica... | I would recommend using netbeans to start with. From there you can easily select pre created classes such as Jframes. Much easier to learn. You can create a GUI from there by dragging and dropping buttons and whatever you need.
Here is a youtube tut to create GUI's in netbeans.
<https://www.youtube.com/watch?v=LFr06Z... |
35,539,657 | Environment
===========
* Raspberry Pi 2
* raspbian-jessie-lite
* Windows 8.1
* PuTTY 0.66 (SSH)
Issue
=====
Can't get cron to execute a python script with sudo. The script deals with GPIO input so it should be called with sudo. The program is supposed to save temperature and humidity to files but `cat temp.txt` and... | 2016/02/21 | [
"https://Stackoverflow.com/questions/35539657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061339/"
] | I suggest learning how to use Swing. You will have several different classes interacting together. In fact, it is considered good practice to keep separate the code which creates and manages the GUI from the code which performs the underlying logic and data manipulation. | Another suggestion:
Learn JavaFX and download SceneBuilder from Oracle: [here](http://www.oracle.com/technetwork/java/javase/downloads/sb2download-2177776.html)
At my university they have stopped teaching Swing and started to teach JavaFX, saying JavaFX has taken over the throne from Swing.
SceneBuilder is very easy ... |
35,539,657 | Environment
===========
* Raspberry Pi 2
* raspbian-jessie-lite
* Windows 8.1
* PuTTY 0.66 (SSH)
Issue
=====
Can't get cron to execute a python script with sudo. The script deals with GPIO input so it should be called with sudo. The program is supposed to save temperature and humidity to files but `cat temp.txt` and... | 2016/02/21 | [
"https://Stackoverflow.com/questions/35539657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061339/"
] | I suggest learning how to use Swing. You will have several different classes interacting together. In fact, it is considered good practice to keep separate the code which creates and manages the GUI from the code which performs the underlying logic and data manipulation. | >
> How will I declare aan instance variable inside the GUI class?
>
>
>
Like as shown bellow, you could start with something like this, note that your application should be able to hand out your data to other classes, for instance I changed `getBasicStats()` to return a `String`, this way you can use your applica... |
43,327,194 | Is there a python library or API that can use a camera to detect LED lights at know locations? The lights will be different colors.
I am interested in making an automated production test for a PCB. My board has many LEDs, and a test command makes the board turn LEDs on when some features work correctly. People may mis... | 2017/04/10 | [
"https://Stackoverflow.com/questions/43327194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3749646/"
] | It is quite possible to solve this. As @John Percival Hackworth said, opencv is a good choice to solve this. I can give you some pointers on how to go about it.
* Take a picture of the board with LEDs, since you know the colors of LEDs, use that knowledge to filter the colors. For which I have given a code snippet.
*... | [OpenCV](https://github.com/skvark/opencv-python%20'OpenCV') is a possible choice that would let you segue to another language later if needed. |
44,469,620 | Following is my code creating an HTTP or FTP connection depending on user input. The if and elif conditions somehow evaluate to FALSE all the time. Entering 1 and 0 both prints 'Sorry, wrong answer'.
```
domain = 'ftp.freebsd.org'
path = '/pub/FreeBSD/'
protocol = input('Connecting to {}. Which Protocol to use? (0-h... | 2017/06/10 | [
"https://Stackoverflow.com/questions/44469620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5574481/"
] | Input in Python 3, which it looks like you are using, comes in as a string. You would need to cast it via `int()` (although this needs to be done with caution and exception handling in the event of bad input) in order to compare it to an integer. | Python input() takes input as Unicode string, you need to explicitly compare input as integer with 0 like,
```
if int(input) == 0:
# Do something
elif int(input) == 1:
# Do something
``` |
42,566,496 | I have a text file with this format:
>
>
> ```
> 1 1 (101): 3.7e+08 1.2e+02 5.1234
> 2 1 (101): 3.5e+08 8.2e+02 6.2222
> 2 2 (101): 1.7e+08 2.2e+02 7.4567
> 3 1 (101): 8.7e+08 3.2e+02 9.2123
>
> ```
>
>
I would like to get it into the following format:
>
>
> ```
> 1 3.7e+08 1.2e+02 ... | 2017/03/02 | [
"https://Stackoverflow.com/questions/42566496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7649922/"
] | The complete solution was to use this code using ApplicationData.Current.LocalFolder.Path because we are not allowed to write files anywhere else then relative path to the application:
```
public static async Task<bool> TryDownloadFileAtPathAsync()
{
var createdFileId = await UserSnippets.CreateFileAsync(... | If `await DownloadFileAsync(item.Id)` retrieves the file in the resulting stream, then it is up to the caller of your method `GetCurrentUserFileAsync` to write the stream contents somewhere.
That can be done using this code
```
var fileContent = await GetCurrentUserFileAsync(onedrivepath, onedrivefilename);
using (va... |
65,135,010 | this select works in Workbench and Python:
```
#!/usr/bin/python3
import mysql.connector
mydb = mysql.connector.connect(
host="127.0.0.1",
user="root",
password="xxxxxxxx",
database="gnucash"
)
sqlcursor = mydb.cursor()
sqlcursor.execute("""
SELECT MAX(transactions.num) AS nr , MAX(transactions.enter_date) ... | 2020/12/03 | [
"https://Stackoverflow.com/questions/65135010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14516823/"
] | In order to keep the columns when using agg you can use 'first' as given below:
Code:
```
import pandas as pd
rawdata = {'portfolio': ['port1', 'port2', 'port1', 'port2'],
'portfolioname': ['portfolioone', 'portfoliotwo', 'portfolioone', 'portfoliotwo'],
'date': ['04/12/2020', '04/12/2020', '04/12/20... | This is a touch inelegant but it shows you how to use groupby and then build a series of data. Then once the data is built move it into a dataframe. After most of the output data is assembled then use the output to work out the weight in dataframe.
```
data = []
for cname, dfsub in df1.groupby('code'):
port = 'por... |
65,135,010 | this select works in Workbench and Python:
```
#!/usr/bin/python3
import mysql.connector
mydb = mysql.connector.connect(
host="127.0.0.1",
user="root",
password="xxxxxxxx",
database="gnucash"
)
sqlcursor = mydb.cursor()
sqlcursor.execute("""
SELECT MAX(transactions.num) AS nr , MAX(transactions.enter_date) ... | 2020/12/03 | [
"https://Stackoverflow.com/questions/65135010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14516823/"
] | In order to keep the columns when using agg you can use 'first' as given below:
Code:
```
import pandas as pd
rawdata = {'portfolio': ['port1', 'port2', 'port1', 'port2'],
'portfolioname': ['portfolioone', 'portfoliotwo', 'portfolioone', 'portfoliotwo'],
'date': ['04/12/2020', '04/12/2020', '04/12/20... | You can simply define a dictionary with columns and corresponding aggregations and use `agg()` with `groupby()` to get what you need.
```
g = {'portfolio':lambda x:'portx',
'portfolioname':lambda x:'portfoliox',
'date':'first',
'quantity':'sum',
'price':'mean',
'value':'sum',
'weight':'me... |
58,612,306 | I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:
```
>>> import win32api
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.
```
... | 2019/10/29 | [
"https://Stackoverflow.com/questions/58612306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292714/"
] | The answer is in jupyter notebook github.
<https://github.com/jupyter/notebook/issues/4980>
`conda install pywin32` worked for me. I am using conda distribution and my virtual env is using Python 3.8 | hi this question i'm solve as below:
1.check directory C:\Windows\System32, is exist these file?
pythoncom37.dll pywintypes37.dll or pythoncom36.dll pywintypes36.dll
the number is python version .
2. if the file is exist delete it.
and then this issue will be solve. |
58,612,306 | I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:
```
>>> import win32api
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.
```
... | 2019/10/29 | [
"https://Stackoverflow.com/questions/58612306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292714/"
] | You should try some (or all) of my methods:
1. Run terminal and use this command: `conda install pywin32`.
2. Copying the two files from `[installation directory of Anaconda]\Lib\site-packages\pywin32_system32` (there are only 2 files in this folder) and paste to `C:\Windows\System32`.
In my case, the two files are `... | hi this question i'm solve as below:
1.check directory C:\Windows\System32, is exist these file?
pythoncom37.dll pywintypes37.dll or pythoncom36.dll pywintypes36.dll
the number is python version .
2. if the file is exist delete it.
and then this issue will be solve. |
58,612,306 | I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:
```
>>> import win32api
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.
```
... | 2019/10/29 | [
"https://Stackoverflow.com/questions/58612306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292714/"
] | ### Solved
If you are working in a miniconda on conda environment. You could just install pywin32 using conda instead of pip.
**This solved my problem:**
```
conda install pywin32
``` | For python 3.8.3, pywin32==225 worked for me, the existing pywin32==228 was uninstalled.
So try this
```
pip install pywin32==225
```
Hope it solves your problem |
58,612,306 | I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:
```
>>> import win32api
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.
```
... | 2019/10/29 | [
"https://Stackoverflow.com/questions/58612306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292714/"
] | version 228 works best for me in Windows 10
```
pip uninstall pywin32
pip install pywin32==228
``` | Currently there are two copies of the pythoncom\*.dll files in directories.
Pycharm is using the copy in directory C:\Windows\System32:-
C:\Windows\System32
C:\Users\sharandi\AppData\Local\Programs\Python\Python38\Lib\site-packages\pywin32\_system32
The files are: -
pythoncom38.dll - 559 KB
pywintypes38.dll - 138 KB |
58,612,306 | I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:
```
>>> import win32api
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.
```
... | 2019/10/29 | [
"https://Stackoverflow.com/questions/58612306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292714/"
] | version 228 works best for me in Windows 10
```
pip uninstall pywin32
pip install pywin32==228
``` | I have had this issue with Jupyter in Anaconda. After following all listed advices, without clear understanding what I am doing, nothing worked for me except one thing. I have updated indexes of Anaconda environments and I've got my kernels back. [The screenshot](https://i.stack.imgur.com/CBTqz.png) |
58,612,306 | I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:
```
>>> import win32api
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.
```
... | 2019/10/29 | [
"https://Stackoverflow.com/questions/58612306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292714/"
] | [Jupyter notebook github](https://github.com/jupyter/notebook/issues/4980) has the issue mentioned in the question. There are multiple solution proposed.
What worked for me was [this answer](https://github.com/jupyter/notebook/issues/4980#issuecomment-600992296) with additional first step:
1. pip uninstall pywin32
2.... | This worked for me
conda install -c anaconda pywin32 |
58,612,306 | I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:
```
>>> import win32api
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.
```
... | 2019/10/29 | [
"https://Stackoverflow.com/questions/58612306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292714/"
] | You should try some (or all) of my methods:
1. Run terminal and use this command: `conda install pywin32`.
2. Copying the two files from `[installation directory of Anaconda]\Lib\site-packages\pywin32_system32` (there are only 2 files in this folder) and paste to `C:\Windows\System32`.
In my case, the two files are `... | version 228 works best for me in Windows 10
```
pip uninstall pywin32
pip install pywin32==228
``` |
58,612,306 | I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:
```
>>> import win32api
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.
```
... | 2019/10/29 | [
"https://Stackoverflow.com/questions/58612306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292714/"
] | What helped me was
1. installing relevant binary from [github.com/mhammond/pywin32](https://github.com/mhammond/pywin32/releases)
2. executing the following commands in the x64 command line:
cd C:\ProgramData\Anaconda3\Scripts
python pywin32\_postinstall.py -install | [Jupyter notebook github](https://github.com/jupyter/notebook/issues/4980) has the issue mentioned in the question. There are multiple solution proposed.
What worked for me was [this answer](https://github.com/jupyter/notebook/issues/4980#issuecomment-600992296) with additional first step:
1. pip uninstall pywin32
2.... |
58,612,306 | I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:
```
>>> import win32api
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.
```
... | 2019/10/29 | [
"https://Stackoverflow.com/questions/58612306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292714/"
] | `pypiwin32` is an outdated distribution. Uninstall it and install `pywin32`:
```
pip uninstall pypiwin32
pip install pywin32
``` | You should go into the folder `{python folder path}/Lib/site-packages/pywin32_system32` and copy `pythoncomXX.dll` and `pywintypesXX.dll` to the folder `C:/Windows/System32`.
If you are using a virtual environment, then `{python folder path}` is the python folder used by the virtual environment, otherwise it is the fo... |
58,612,306 | I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:
```
>>> import win32api
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.
```
... | 2019/10/29 | [
"https://Stackoverflow.com/questions/58612306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292714/"
] | **Windows 10, Python 3.8, PyWin32 v.302 using Anaconda**
Here is what worked for me
**Open an elevated command prompt activate environment**
* Windows Key
* Type cmd
* Right click `Command Prompt` and click Run as Administrator
* `conda activate [ENVIRONMENT]`
**Navigate to the environment you installed PyWin32 on,... | I am a miniconda user. I got this error first after installed some python environment then deleted it. So I reinstalled the jupyter notebook and it replaced some missing files and issue is fixed.
```
conda install jupyter notebook
``` |
46,279,333 | ```
@echo off
start c:\Python27\python.exe C:\Users\anupam.soni\Desktop\WIND_ACTUAL\tool.py
PAUSE
```
My script in tool.py is correctly working in **PyCharm IDE**, this bat is not working.
**Note : file path and python path is correct.**
Any other option to run python script independently | 2017/09/18 | [
"https://Stackoverflow.com/questions/46279333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8527475/"
] | I assume that in your Adapter, you hold an array of objects that represents the items you want to be displayed.
Add a property to this object named for example `ButtonVisible` and set the property when you press the button.
Complete sample adapter follows. This displays a list of items with a button that, when presse... | Set an array of boolean variables associated with each item.
```
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
if(visibilityList.get(position)){
holder.button.setVisibility(View.VISIBLE);
}else{
holder.button.setVisibility(View.GONE);
}
holder.mes... |
46,279,333 | ```
@echo off
start c:\Python27\python.exe C:\Users\anupam.soni\Desktop\WIND_ACTUAL\tool.py
PAUSE
```
My script in tool.py is correctly working in **PyCharm IDE**, this bat is not working.
**Note : file path and python path is correct.**
Any other option to run python script independently | 2017/09/18 | [
"https://Stackoverflow.com/questions/46279333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8527475/"
] | I assume that in your Adapter, you hold an array of objects that represents the items you want to be displayed.
Add a property to this object named for example `ButtonVisible` and set the property when you press the button.
Complete sample adapter follows. This displays a list of items with a button that, when presse... | Use HashMap to keep those positions which you need to show. Write code in `onBindViewHolder` method
```
if(map.contains(holder.getAdapterPosition()){
holder.btn.setVisibility(View.VISIBLE);
} else {
holder.btn.setVisibility(View.GONE);
}
```
**Note: -** do write else case too, otherwise recyclerView will mi... |
61,550,294 | For my basic, rudimentary Django CMS, in my effort to add a toggle feature to publish / unpublish a blog post (I’ve called my app ‘essays’ and the class object inside my models is `is_published`), I’ve encountered an OperationalError when trying to use the Admin Dashboard to add essay content. I’m expecting to be able ... | 2020/05/01 | [
"https://Stackoverflow.com/questions/61550294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6095646/"
] | There isn't column is\_published in essays\_essayarticle table of your db try to add column in db by adding new migration and see the change for a table whether this column is going to be added.
The error isn't in your view rather it is in query. | I'm making the assumption that you deleted the migrations folder, if so when you makemigrations and migrate write the name of you app at the end
example
```
python manage.py makemigrations app_name
``` |
61,550,294 | For my basic, rudimentary Django CMS, in my effort to add a toggle feature to publish / unpublish a blog post (I’ve called my app ‘essays’ and the class object inside my models is `is_published`), I’ve encountered an OperationalError when trying to use the Admin Dashboard to add essay content. I’m expecting to be able ... | 2020/05/01 | [
"https://Stackoverflow.com/questions/61550294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6095646/"
] | Its looking like your migration with the same name is already triggered, thats why Django is not able to create new column,
You have to look into the table `django_migrations` in database find and delete the migration record. You need to compare your migrations with `django_migrations` in database then only you will f... | I'm making the assumption that you deleted the migrations folder, if so when you makemigrations and migrate write the name of you app at the end
example
```
python manage.py makemigrations app_name
``` |
61,550,294 | For my basic, rudimentary Django CMS, in my effort to add a toggle feature to publish / unpublish a blog post (I’ve called my app ‘essays’ and the class object inside my models is `is_published`), I’ve encountered an OperationalError when trying to use the Admin Dashboard to add essay content. I’m expecting to be able ... | 2020/05/01 | [
"https://Stackoverflow.com/questions/61550294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6095646/"
] | There isn't column is\_published in essays\_essayarticle table of your db try to add column in db by adding new migration and see the change for a table whether this column is going to be added.
The error isn't in your view rather it is in query. | Its looking like your migration with the same name is already triggered, thats why Django is not able to create new column,
You have to look into the table `django_migrations` in database find and delete the migration record. You need to compare your migrations with `django_migrations` in database then only you will f... |
4,527,495 | I have a strange issue with python 2.6.5. If I call
```
p = subprocess.Popen(["ifup eth0"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
```
with the interface eth0 being down, the python programm hangs. "p.communicate()" takes a minute or longer to finish. If the interface ... | 2010/12/24 | [
"https://Stackoverflow.com/questions/4527495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373361/"
] | You should check out the [warning](http://docs.python.org/library/subprocess.html#subprocess.call) under the `subprocess.call` method. It might be the reason of your problem.
**Warning**
>
> Like Popen.wait(), this will
> deadlock when using stdout=PIPE and/or
> stderr=PIPE and the child process
> generates enou... | ```
p = subprocess.Popen(["ifup", "eth0"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
```
Set `shell=False`, you don't need it.
Try running this code, it should work. Notice how two arguments are separate elements in the list. |
4,527,495 | I have a strange issue with python 2.6.5. If I call
```
p = subprocess.Popen(["ifup eth0"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
```
with the interface eth0 being down, the python programm hangs. "p.communicate()" takes a minute or longer to finish. If the interface ... | 2010/12/24 | [
"https://Stackoverflow.com/questions/4527495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373361/"
] | [/etc/network/if-up.d/ntpdate does not detach correctly](https://bugs.launchpad.net/ubuntu/+source/ntp/+bug/1206164)
That's why read() waits until fds (stdin/stdout/stderr) are closed.
You can detach stdin/stderr/stdout (do not add stdout=subprocess.PIPE and the same to Popen constructor call). | ```
p = subprocess.Popen(["ifup", "eth0"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
```
Set `shell=False`, you don't need it.
Try running this code, it should work. Notice how two arguments are separate elements in the list. |
49,320,399 | I want to call a REST api and get some json data in response in python.
```
curl https://analysis.lastline.com/analysis/get_completed -X POST -F “key=2AAAD5A21DN0TBDFZZ66” -F “api_token=IwoAGFa344c277Z2” -F “after=2016-03-11 20:00:00”
```
I know of python [request](http://docs.python-requests.org/en/latest/), but ho... | 2018/03/16 | [
"https://Stackoverflow.com/questions/49320399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3855999/"
] | Just include the parameter `data` to the .post function.
```
requests.post('https://analysis.lastline.com/analysis/get_completed', data = {'key':'2AAAD5A21DN0TBDFZZ66', 'api_token':'IwoAGFa344c277Z2', 'after':'2016-03-11 20:00:00'})
``` | -F means make a POST as form data.
So in requests it would be:
```
>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
``` |
49,320,399 | I want to call a REST api and get some json data in response in python.
```
curl https://analysis.lastline.com/analysis/get_completed -X POST -F “key=2AAAD5A21DN0TBDFZZ66” -F “api_token=IwoAGFa344c277Z2” -F “after=2016-03-11 20:00:00”
```
I know of python [request](http://docs.python-requests.org/en/latest/), but ho... | 2018/03/16 | [
"https://Stackoverflow.com/questions/49320399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3855999/"
] | -F stands for form contents
```
import requests
data = {
'key': '2AAAD5A21DN0TBDFZZ66',
'api_token': 'IwoAGFa344c277Z2',
'after': '2016-03-11',
}
response = requests.post('https://analysis.lastline.com/analysis/get_completed', data=data)
``` | -F means make a POST as form data.
So in requests it would be:
```
>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
``` |
59,845,836 | please help me
what is my code problem??
my code writing name , mean(grades) in out put
```
import csv
from statistics import mean
with open('C:/Users/sina/Desktop/python pt/jalase19.csv' , 'r') as fo:
reader = csv.reader(fo)
for row in reader :
name = row[0]
grades = list()
for grade in row[1:]:
... | 2020/01/21 | [
"https://Stackoverflow.com/questions/59845836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11828203/"
] | **You didn't do an indent after the "with" statement**
As described [here](https://docs.python.org/2.5/whatsnew/pep-343.html) you have to do an indent after an "with" statement
Your code should look like that:
```
import csv
from statistics import mean
with open('C:/Users/sina/Desktop/python pt/jalase19.csv' , 'r') ... | When opening your files you are missing indentation. See how the error points you to line 4? When opening a file using the [context manager](https://book.pythontips.com/en/latest/context_managers.html) and anytime you are using a control statement (if, else, for, etc.) the next line must be indented.
```
import csv
fr... |
16,894,490 | I have some problems with this code... send not the integer image but some bytes, is there someone than can help me? I want to send all images I find in a folder. Thank you.
CLIENT
======
```
import socket
import sys
import os
s = socket.socket()
s.connect(("localhost",9999)) #IP address, port
sb = 'c:\\python... | 2013/06/03 | [
"https://Stackoverflow.com/questions/16894490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2445800/"
] | To transfer a sequence of files over a single socket, you need some way of delineating each file. In effect, you need to run a small protocol on top of the socket which allows to you know the metadata for each file such as its size and name, and of course the image data.
It appears you're attempting to do this, howeve... | The parameter to [`socket.recv`](http://docs.python.org/2/library/socket#socket.socket.recv) only specifies the maximum buffer size for receiving data packages, it doesn't mean exactly that many bytes will be read.
So if you write:
```
strng = sc.recv(int(size))
```
you won't necessarily get all the content, specia... |
27,012,337 | I'm trying to use ConfigParser to read a .cfg file for my pygame game. I can't get it to function for some reason. The code looks like this:
```
import ConfigParser
def main():
config = ConfigParser.ConfigParser()
config.read('options.cfg')
print config.sections()
Screen_width = config.getint('graphics... | 2014/11/19 | [
"https://Stackoverflow.com/questions/27012337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3033405/"
] | Your config file probably is not found. The parser will just produce an empty set in that case. You should wrap your code with a check for the file:
```
from ConfigParser import SafeConfigParser
import os
def main():
filename = "options.cfg"
if os.path.isfile(filename):
parser = SafeConfigParser()
... | I always use the `SafeConfigParser`:
```
from ConfigParser import SafeConfigParser
def main():
parser = SafeConfigParser()
parser.read('options.cfg')
print(parser.sections())
screen_width = parser.getint('graphics','width')
screen_height = parser.getint('graphics','height')
```
Also make sure th... |
27,012,337 | I'm trying to use ConfigParser to read a .cfg file for my pygame game. I can't get it to function for some reason. The code looks like this:
```
import ConfigParser
def main():
config = ConfigParser.ConfigParser()
config.read('options.cfg')
print config.sections()
Screen_width = config.getint('graphics... | 2014/11/19 | [
"https://Stackoverflow.com/questions/27012337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3033405/"
] | I always use the `SafeConfigParser`:
```
from ConfigParser import SafeConfigParser
def main():
parser = SafeConfigParser()
parser.read('options.cfg')
print(parser.sections())
screen_width = parser.getint('graphics','width')
screen_height = parser.getint('graphics','height')
```
Also make sure th... | I was also facing the same issue. I had moved my project to a different location and assumed it will work fine. But after executing the code in new location it was not able to find my configuration file and throwing error:
>
> Exception: Section postgresql\_conn\_config not found in the database.ini file
>
>
>
Re... |
27,012,337 | I'm trying to use ConfigParser to read a .cfg file for my pygame game. I can't get it to function for some reason. The code looks like this:
```
import ConfigParser
def main():
config = ConfigParser.ConfigParser()
config.read('options.cfg')
print config.sections()
Screen_width = config.getint('graphics... | 2014/11/19 | [
"https://Stackoverflow.com/questions/27012337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3033405/"
] | Your config file probably is not found. The parser will just produce an empty set in that case. You should wrap your code with a check for the file:
```
from ConfigParser import SafeConfigParser
import os
def main():
filename = "options.cfg"
if os.path.isfile(filename):
parser = SafeConfigParser()
... | I was also facing the same issue. I had moved my project to a different location and assumed it will work fine. But after executing the code in new location it was not able to find my configuration file and throwing error:
>
> Exception: Section postgresql\_conn\_config not found in the database.ini file
>
>
>
Re... |
54,833,385 | I have the following code (using dnspython), which works - but it uses globals which I'm not keen on. I was thinking that I could use a recursive function but there is no obvious end.
Does anyone have any ideas on how this could be improved??
```
import dns.resolver
dns_resolver = dns.resolver.Resolver()
dns_resolve... | 2019/02/22 | [
"https://Stackoverflow.com/questions/54833385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3595388/"
] | Here is a slightly cleaned-up recursive function with a properly local variable.
```
import dns.resolver
def get_spf_count(domain_name, dns_resolver=None):
if dns_resolver is None:
dns_resolver = dns.resolver.Resolver()
dns_resolver.nameservers = ['1.1.1.1', '1.0.0.1']
resolve_count = 0
... | Why not pass `resolve_count` in as a variable, and have the function return the updated value?
```
def get_spf_count(domain_name, resolve_count):
for answer in dns_resolver.query(domain_name, 'TXT'):
spf = answer.to_text() if 'v=spf1' in answer.to_text() else None
if spf:
spf_records = ... |
37,144,913 | I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python:
```
y = y_mort.convert_... | 2016/05/10 | [
"https://Stackoverflow.com/questions/37144913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5286020/"
] | This error may also come due to wrong usage of API
**Correct**:
```py
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=0.7, test_size=0.3, random_state=100
)
```
**Incorrect**:
```py
X_train, y_train, X_test, y_test = train_test_split(
X, y, train_size=0.7, test_size=0.3, random_state... | It may be due to different indices in `x` and `y`. This may happen when we initially removed some values from dataframe and perform some operations on `x` after separating `x` and `y`. The indices in `y` will contain the missing indices from original dataframe while `x` will have continuous indices. It's best to do `da... |
37,144,913 | I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python:
```
y = y_mort.convert_... | 2016/05/10 | [
"https://Stackoverflow.com/questions/37144913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5286020/"
] | The error message indicates that you have endog and exog with different shape.
This is common error in python which can be easily solved by using 'reshape' function on dependent variable to align it with independent variable's shape.
```
y_train.values.reshape(-1,1)
```
Above lines means:-
We have provided column ... | Have you checked if you have `Nan` in your data? You can use `np.isNan(X)` and `np.isNan(y)`. I saw you turned on the option `drop` so I suspect if you have `Nan` in your data then that will change the shape of your input. |
37,144,913 | I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python:
```
y = y_mort.convert_... | 2016/05/10 | [
"https://Stackoverflow.com/questions/37144913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5286020/"
] | It may be due to different indices in `x` and `y`. This may happen when we initially removed some values from dataframe and perform some operations on `x` after separating `x` and `y`. The indices in `y` will contain the missing indices from original dataframe while `x` will have continuous indices. It's best to do `da... | ValueError: The indices for endog and exog are not aligned
Above error is basically due to index mismatch in both X & y datasets while cleaning and preparation.
I removed this error by removing the indices of both X & y datasets as:
y\_train = y\_train.reset\_index(drop=True)
X\_train = X\_train.reset\_index(drop=Tru... |
37,144,913 | I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python:
```
y = y_mort.convert_... | 2016/05/10 | [
"https://Stackoverflow.com/questions/37144913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5286020/"
] | Try converting *y* into a list before the *sm.Logit()* line.
```
y = list(y)
``` | ValueError: The indices for endog and exog are not aligned
Above error is basically due to index mismatch in both X & y datasets while cleaning and preparation.
I removed this error by removing the indices of both X & y datasets as:
y\_train = y\_train.reset\_index(drop=True)
X\_train = X\_train.reset\_index(drop=Tru... |
37,144,913 | I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python:
```
y = y_mort.convert_... | 2016/05/10 | [
"https://Stackoverflow.com/questions/37144913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5286020/"
] | The error message indicates that you have endog and exog with different shape.
This is common error in python which can be easily solved by using 'reshape' function on dependent variable to align it with independent variable's shape.
```
y_train.values.reshape(-1,1)
```
Above lines means:-
We have provided column ... | do `y_train.values.ravel()`.
Actually shape of y\_train is in 2D array.
So you need to convert it into 1D array.
hope it works for you. |
37,144,913 | I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python:
```
y = y_mort.convert_... | 2016/05/10 | [
"https://Stackoverflow.com/questions/37144913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5286020/"
] | This error may also come due to wrong usage of API
**Correct**:
```py
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=0.7, test_size=0.3, random_state=100
)
```
**Incorrect**:
```py
X_train, y_train, X_test, y_test = train_test_split(
X, y, train_size=0.7, test_size=0.3, random_state... | Have you checked if you have `Nan` in your data? You can use `np.isNan(X)` and `np.isNan(y)`. I saw you turned on the option `drop` so I suspect if you have `Nan` in your data then that will change the shape of your input. |
37,144,913 | I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python:
```
y = y_mort.convert_... | 2016/05/10 | [
"https://Stackoverflow.com/questions/37144913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5286020/"
] | Try converting *y* into a list before the *sm.Logit()* line.
```
y = list(y)
``` | This error may also come due to wrong usage of API
**Correct**:
```py
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=0.7, test_size=0.3, random_state=100
)
```
**Incorrect**:
```py
X_train, y_train, X_test, y_test = train_test_split(
X, y, train_size=0.7, test_size=0.3, random_state... |
37,144,913 | I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python:
```
y = y_mort.convert_... | 2016/05/10 | [
"https://Stackoverflow.com/questions/37144913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5286020/"
] | Try converting *y* into a list before the *sm.Logit()* line.
```
y = list(y)
``` | Have you checked if you have `Nan` in your data? You can use `np.isNan(X)` and `np.isNan(y)`. I saw you turned on the option `drop` so I suspect if you have `Nan` in your data then that will change the shape of your input. |
37,144,913 | I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python:
```
y = y_mort.convert_... | 2016/05/10 | [
"https://Stackoverflow.com/questions/37144913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5286020/"
] | This error may also come due to wrong usage of API
**Correct**:
```py
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=0.7, test_size=0.3, random_state=100
)
```
**Incorrect**:
```py
X_train, y_train, X_test, y_test = train_test_split(
X, y, train_size=0.7, test_size=0.3, random_state... | ValueError: The indices for endog and exog are not aligned
Above error is basically due to index mismatch in both X & y datasets while cleaning and preparation.
I removed this error by removing the indices of both X & y datasets as:
y\_train = y\_train.reset\_index(drop=True)
X\_train = X\_train.reset\_index(drop=Tru... |
37,144,913 | I am getting above error when I am running an iteration using FOR loop to build multiple models. First two models having similar data sets build fine. While building third model I am getting this error. The code where error is thrown is when I call sm.logit() using Statsmodel package of python:
```
y = y_mort.convert_... | 2016/05/10 | [
"https://Stackoverflow.com/questions/37144913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5286020/"
] | The error message indicates that you have endog and exog with different shape.
This is common error in python which can be easily solved by using 'reshape' function on dependent variable to align it with independent variable's shape.
```
y_train.values.reshape(-1,1)
```
Above lines means:-
We have provided column ... | It may be due to different indices in `x` and `y`. This may happen when we initially removed some values from dataframe and perform some operations on `x` after separating `x` and `y`. The indices in `y` will contain the missing indices from original dataframe while `x` will have continuous indices. It's best to do `da... |
51,020,212 | I am trying to download a package to call **sc2** and when I write `pip install sc2` into cmd prompt, I receive the error:
>
> Command "python setup.py egg\_info" failed with error code 1 in c:\users\user\appdata\local\temp\pip-install-q3ixb0\websockets.
>
>
>
Any help? | 2018/06/25 | [
"https://Stackoverflow.com/questions/51020212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9988239/"
] | **easy\_install** Worked of me.
easy\_install sc2 | Maybe are you behind a proxy or not connected? has you try to make ping to any url ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.