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 __name__ == '__main__': in_path="C:/Users/username/Desktop/in.tif" out_path="C:/Users/username/Desktop/out.tif" myfun(in_path, out_path) ``` time=3.4 minutes with multiprocessing map : ``` if __name__ == '__main__': p = Pool(processes=4) in_path="C:/Users/username/Desktop/in.tif" out_path="C:/Users/username/Desktop/out.tif" result = p.map(myfun(in_path,out_path)) ``` time=4.4 minutes ``` if __name__ == '__main__': pool = multiprocessing.Pool(4) in_path="C:/Users/username/Desktop/in.tif" out_path="C:/Users/username/Desktop/out.tif" pool.apply_async(myfun, args=(in_path,out_path,)) pool.close() pool.join() ``` time=4.5 minutes
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*. If you had: ``` in_paths = ['C:/Users/in1.tif', 'C:/Users/in2.tif', ... ] out_paths = ['C:/Users/out1.tif', 'C:/Users/out2.tif', ... ] ``` Then you could use `Pool.map()` to speed up your program, for example: ``` p = Pool(4) results = p.map(my_function, zip(in_paths, out_paths)) ``` But since you have a single input, you only need to run your function once, and so there is no difference. Hope this helps.
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 overhead is a bit faster as it can use forking and copy-on-write memory, but on Windows this is essentially as if you called `python -c "from your_script import myfun; myfun('C:/Users/username/Desktop/in.tif', 'C:/Users/username/Desktop/out.tif')"` from the command line and that takes a considerable amount of time. You'll notice benefits of multiprocessing only if you have considerable computation requirements which can be parallelized from your function. Check a simple benchmark in [this answer](https://stackoverflow.com/a/44525554/7553525).
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 similar question: [python websocket with tornado. Socket aren't closed](https://stackoverflow.com/questions/25082336/python-websocket-with-tornado-socket-arent-closed), which did nothing. And I've tried using `IOLoop.close(all_fds=True)` [PyDoc for this function](http://www.tornadoweb.org/en/stable/ioloop.html?highlight=IOLoop#tornado.ioloop.IOLoop.close), which returned the error below. > > `>>>` tornado.ioloop.IOLoop.close(all\_fds=True) > > > Traceback (most recent call last): > > > File "", line 1, in > > > TypeError: unbound method close() must be called with IOLoop instance as first argument (got nothing instead) > > > **How do I close all sockets so I can start up again from a clean slate?**
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) ``` Further reading: * [IOLoop.current()](http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop.current) documentation * [Explanation](https://realpython.com/blog/python/instance-class-and-static-methods-demystified/) why you've got `TypeError`
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 originally: <https://stackoverflow.com/a/17703016/4808079> ``` //first, check the port which your code opens. $ sudo lsof -i :8528 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Python 29748 root 4u IPv6 0xe782a7ce5603265 0t0 TCP *:8528 (LISTEN) Python 29748 root 5u IPv4 0xe782a7ce4aec61d 0t0 TCP *:8528 (LISTEN) //then kill the process, using the PID $ sudo kill 29748 ```
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], ['b',2,1], ['c',4,3], ['d',7,2], ['e',8,4]] #PAE[1:4].sort(key=itemgetter(2)) (something like this) or #sorted(PAE[1:4],key=itemgetter(2)) (something like this) ` # ^ i know both are wrong but just for an idea ` #output should be like this ['a', 0, 8] ['b', 2, 1] ['d', 7, 2] ['c', 4, 3] ['e', 8, 4] ``` I am new to python, but i tried my level best to find a solution but failed.
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], ['b',2,1], ['c',4,3], ['d',7,2], ['e',8,4]] #PAE[1:4].sort(key=itemgetter(2)) (something like this) or #sorted(PAE[1:4],key=itemgetter(2)) (something like this) ` # ^ i know both are wrong but just for an idea ` #output should be like this ['a', 0, 8] ['b', 2, 1] ['d', 7, 2] ['c', 4, 3] ['e', 8, 4] ``` I am new to python, but i tried my level best to find a solution but failed.
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], ['b',2,1], ['c',4,3], ['d',7,2], ['e',8,4]] #PAE[1:4].sort(key=itemgetter(2)) (something like this) or #sorted(PAE[1:4],key=itemgetter(2)) (something like this) ` # ^ i know both are wrong but just for an idea ` #output should be like this ['a', 0, 8] ['b', 2, 1] ['d', 7, 2] ['c', 4, 3] ['e', 8, 4] ``` I am new to python, but i tried my level best to find a solution but failed.
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 prompt: ``` source /usr/local/bin/virutalenvwrapper.sh ``` And now I can list and select an environment by doing: ``` >workon >workon envtest1 ``` My question is, since this works for me, I'm confused why I should be creating an environmental variable WORKON\_HOME and point it to the ~/Envs folder? What does that do and how come mine works fine w/o it? I don't have that /Envs folder either (I know the script creates it). Reference: <http://virtualenvwrapper.readthedocs.org/en/latest/>
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` which folder to use (`export PIP_VIRTUALENV_BASE=$WORKON_HOME`) source : [virtualenvwrapper.readthedocs.org : Tying to pip’s virtualenv support](http://virtualenvwrapper.readthedocs.org/en/latest/tips.html#tying-to-pip-s-virtualenv-support)
> > 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 folder to search for Python environments. The command `workon` searches the path `WORKON_HOME` if it's defined, or `~/.virtualenvs` if it's not, which is why it works by default. A use case for defining a different `WORKON_HOME` directory would be if you have different environments you want to available to `virtualenvwrapper`. For example, if you save virtual env backups to a different folder or have multiple users who want to maintain their own environments.
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 pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.
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 filter that if you really wanted. Also if you were to declare any other locals before the dir() call, they would get added as constructed object's attributes as well.
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', 'arg3': 7} ``` My suggestion is similar to @peepsalot, except it's more explicit and doesn't use `dir()`, which according to the [documentation](https://docs.python.org/2/library/functions.html#dir) > > its detailed behavior may change across releases > > >
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 pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.
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', 'arg3': 7} ``` My suggestion is similar to @peepsalot, except it's more explicit and doesn't use `dir()`, which according to the [documentation](https://docs.python.org/2/library/functions.html#dir) > > its detailed behavior may change across releases > > >
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 unit_price: float quantity_on_hand: int = 0 ``` Will automatically add an `__init__` like that: ``` def __init__(self, name: str, unit_price: float, quantity_on_hand: int=0): self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand ```
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 pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.
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 filter that if you really wanted. Also if you were to declare any other locals before the dir() call, they would get added as constructed object's attributes as well.
``` 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 pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.
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 filter that if you really wanted. Also if you were to declare any other locals before the dir() call, they would get added as constructed object's attributes as well.
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: #do assignments ```
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 pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.
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 filter that if you really wanted. Also if you were to declare any other locals before the dir() call, they would get added as constructed object's attributes as well.
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 pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.
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 with their respective names. ``` import inspect import functools def store_args(method): """Stores provided method args as instance attributes.""" argspec = inspect.getargspec(method) defaults = dict(zip( argspec.args[-len(argspec.defaults):], argspec.defaults )) arg_names = argspec.args[1:] @functools.wraps(method) def wrapper(*positional_args, **keyword_args): self = positional_args[0] # Get default arg values args = defaults.copy() # Add provided arg values list(map( args.update, ( zip(arg_names, positional_args[1:]), keyword_args.items() ) )) # Store values in instance as attributes self.__dict__.update(args) return method(*positional_args, **keyword_args) return wrapper ``` You can then use it like this: ``` class A: @store_args def __init__(self, a, b, c=3, d=4, e=5): pass a = A(1,2) print(a.a, a.b, a.c, a.d, a.e) ``` Result will be `1 2 3 4 5` on Python3.x or `(1, 2, 3, 4, 5)` on Python2.x
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 unit_price: float quantity_on_hand: int = 0 ``` Will automatically add an `__init__` like that: ``` def __init__(self, name: str, unit_price: float, quantity_on_hand: int=0): self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand ```
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 pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.
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): class_locals.pop('self') if 'kwargs' in class_locals: vars(self).update(class_locals.pop('kwargs')) vars(self).update(class_locals) class FooCls: def __init__(self, foo, bar): convert_all_args_to_attribs(self, locals()) class FooClsWithKeywords: def __init__(self, foo, bar, **kwargs): convert_all_args_to_attribs(self, locals()) f1 = FooCls(1,2) f2 = FooClsWithKeywords(3,4, cheese='stilton') print vars(f1) #{'foo': 1, 'bar': 2} print vars(f2) #{'cheese': 'stilton', 'foo': 3, 'bar': 4} ```
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 pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.
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', 'arg3': 7} ``` My suggestion is similar to @peepsalot, except it's more explicit and doesn't use `dir()`, which according to the [documentation](https://docs.python.org/2/library/functions.html#dir) > > its detailed behavior may change across releases > > >
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): class_locals.pop('self') if 'kwargs' in class_locals: vars(self).update(class_locals.pop('kwargs')) vars(self).update(class_locals) class FooCls: def __init__(self, foo, bar): convert_all_args_to_attribs(self, locals()) class FooClsWithKeywords: def __init__(self, foo, bar, **kwargs): convert_all_args_to_attribs(self, locals()) f1 = FooCls(1,2) f2 = FooClsWithKeywords(3,4, cheese='stilton') print vars(f1) #{'foo': 1, 'bar': 2} print vars(f2) #{'cheese': 'stilton', 'foo': 3, 'bar': 4} ```
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 pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.
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 unit_price: float quantity_on_hand: int = 0 ``` Will automatically add an `__init__` like that: ``` def __init__(self, name: str, unit_price: float, quantity_on_hand: int=0): self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand ```
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 pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.
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 dictionary: ``` foo = Foo(1, 2, 3, a=4, b=5, c=6) // args = (1, 2, 3), kwargs = {'a' : 4, ...} ```
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', 'arg3': 7} ``` My suggestion is similar to @peepsalot, except it's more explicit and doesn't use `dir()`, which according to the [documentation](https://docs.python.org/2/library/functions.html#dir) > > its detailed behavior may change across releases > > >
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 prompt when saving files of certain types. Note that this will result in the file being saved somewhere, but you can also control where it goes in case you want to delete the file (or handle it separately in Python).
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` nor `capath` is specified, an HTTPS request will not do any verification of the server’s certificate". I am guessing I need to specify one of those parameters if I don't want my program to be vulnerable to man-in-the-middle attacks, problems with revoked certificates, and other vulnerabilities. `cafile` and `capath` are supposed to point to a list of certificates. Where am I supposed to get this list from? Is there any simple and cross-platform way to use the same list of certificates that my OS or browser uses?
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-certificates.crt', ]: if os.path.exists(i): cafile = i break if cafile is None: raise RuntimeError('System CA-certificates bundle not found') ```
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` nor `capath` is specified, an HTTPS request will not do any verification of the server’s certificate". I am guessing I need to specify one of those parameters if I don't want my program to be vulnerable to man-in-the-middle attacks, problems with revoked certificates, and other vulnerabilities. `cafile` and `capath` are supposed to point to a list of certificates. Where am I supposed to get this list from? Is there any simple and cross-platform way to use the same list of certificates that my OS or browser uses?
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-certificates.crt', ]: if os.path.exists(i): cafile = i break if cafile is None: raise RuntimeError('System CA-certificates bundle not found') ```
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` nor `capath` is specified, an HTTPS request will not do any verification of the server’s certificate". I am guessing I need to specify one of those parameters if I don't want my program to be vulnerable to man-in-the-middle attacks, problems with revoked certificates, and other vulnerabilities. `cafile` and `capath` are supposed to point to a list of certificates. Where am I supposed to get this list from? Is there any simple and cross-platform way to use the same list of certificates that my OS or browser uses?
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.PROTOCOL_TLSv1) response = urllib.request.urlopen("http://www.example.com", context=ssl_context) ```
``` 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 = HTTPSHandler(context=context, check_hostname=True) opener = urllib.request.build_opener(https_handler) except ImportError: opener = urllib.request.build_opener() opener.addheaders = [('User-agent', YOUR_USER_AGENT)] urllib.request.install_opener(opener) ```
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` nor `capath` is specified, an HTTPS request will not do any verification of the server’s certificate". I am guessing I need to specify one of those parameters if I don't want my program to be vulnerable to man-in-the-middle attacks, problems with revoked certificates, and other vulnerabilities. `cafile` and `capath` are supposed to point to a list of certificates. Where am I supposed to get this list from? Is there any simple and cross-platform way to use the same list of certificates that my OS or browser uses?
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()) ``` As I expected, this returns a `HTTPResponse` object for a site with a valid certificate and raises a `ssl.CertificateError` exception for a site with an invalid certificate.
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-certificates.crt', ]: if os.path.exists(i): cafile = i break if cafile is None: raise RuntimeError('System CA-certificates bundle not found') ```
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` nor `capath` is specified, an HTTPS request will not do any verification of the server’s certificate". I am guessing I need to specify one of those parameters if I don't want my program to be vulnerable to man-in-the-middle attacks, problems with revoked certificates, and other vulnerabilities. `cafile` and `capath` are supposed to point to a list of certificates. Where am I supposed to get this list from? Is there any simple and cross-platform way to use the same list of certificates that my OS or browser uses?
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.PROTOCOL_TLSv1) response = urllib.request.urlopen("http://www.example.com", context=ssl_context) ```
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` nor `capath` is specified, an HTTPS request will not do any verification of the server’s certificate". I am guessing I need to specify one of those parameters if I don't want my program to be vulnerable to man-in-the-middle attacks, problems with revoked certificates, and other vulnerabilities. `cafile` and `capath` are supposed to point to a list of certificates. Where am I supposed to get this list from? Is there any simple and cross-platform way to use the same list of certificates that my OS or browser uses?
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` nor `capath` is specified, an HTTPS request will not do any verification of the server’s certificate". I am guessing I need to specify one of those parameters if I don't want my program to be vulnerable to man-in-the-middle attacks, problems with revoked certificates, and other vulnerabilities. `cafile` and `capath` are supposed to point to a list of certificates. Where am I supposed to get this list from? Is there any simple and cross-platform way to use the same list of certificates that my OS or browser uses?
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.PROTOCOL_TLSv1) response = urllib.request.urlopen("http://www.example.com", context=ssl_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-certificates.crt', ]: if os.path.exists(i): cafile = i break if cafile is None: raise RuntimeError('System CA-certificates bundle not found') ```
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` nor `capath` is specified, an HTTPS request will not do any verification of the server’s certificate". I am guessing I need to specify one of those parameters if I don't want my program to be vulnerable to man-in-the-middle attacks, problems with revoked certificates, and other vulnerabilities. `cafile` and `capath` are supposed to point to a list of certificates. Where am I supposed to get this list from? Is there any simple and cross-platform way to use the same list of certificates that my OS or browser uses?
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 = HTTPSHandler(context=context, check_hostname=True) opener = urllib.request.build_opener(https_handler) except ImportError: opener = urllib.request.build_opener() opener.addheaders = [('User-agent', YOUR_USER_AGENT)] urllib.request.install_opener(opener) ```
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` nor `capath` is specified, an HTTPS request will not do any verification of the server’s certificate". I am guessing I need to specify one of those parameters if I don't want my program to be vulnerable to man-in-the-middle attacks, problems with revoked certificates, and other vulnerabilities. `cafile` and `capath` are supposed to point to a list of certificates. Where am I supposed to get this list from? Is there any simple and cross-platform way to use the same list of certificates that my OS or browser uses?
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()) ``` As I expected, this returns a `HTTPResponse` object for a site with a valid certificate and raises a `ssl.CertificateError` exception for a site with an invalid certificate.
``` 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 = HTTPSHandler(context=context, check_hostname=True) opener = urllib.request.build_opener(https_handler) except ImportError: opener = urllib.request.build_opener() opener.addheaders = [('User-agent', YOUR_USER_AGENT)] urllib.request.install_opener(opener) ```
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` nor `capath` is specified, an HTTPS request will not do any verification of the server’s certificate". I am guessing I need to specify one of those parameters if I don't want my program to be vulnerable to man-in-the-middle attacks, problems with revoked certificates, and other vulnerabilities. `cafile` and `capath` are supposed to point to a list of certificates. Where am I supposed to get this list from? Is there any simple and cross-platform way to use the same list of certificates that my OS or browser uses?
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()) ``` As I expected, this returns a `HTTPResponse` object for a site with a valid certificate and raises a `ssl.CertificateError` exception for a site with an invalid certificate.
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.PROTOCOL_TLSv1) response = urllib.request.urlopen("http://www.example.com", context=ssl_context) ```
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 and pieces out of my home folder into the file system some going to /ect or usr/local. I didn't want this so I stopped the process. Cause then I though I'd have to run eclipse as root & I'd not be able to trace process though the source cause it's all be scattered thought the file system. Problems came when I tried to install a new module. I couldn't get it into the module list & even zipping it up and trying to import it through the client failed without errors. While trying to get the module I added to show up I discovered this on the forums "You'll have to run setup.py install after putting the module in addons if you didn't specify an addons path when running openerp-server." So it looked like I had to run: `python setup.py build sudo python setup.py install` Firstly I'm confused about why you need to build I thought it was onlt the c libs that needed building and I'd done that when installing dependences. Secondly `setup.py install` is obviosuly vital if you need to run it to get a new module recognised. How can I trace stuff through the source if it's running from all over the file system. Everything has now been copied out of home into the file system as I had tried to avoid. Now the start up scripts are in usr/local/bin so I assume I can't run, using 'debug as' in eclipse or see the logs in the eclipse console. I also found in the documentation that that suggests starting the server with: `./openerp-server.py –addons-path=~/home/workspace/stable/addons` Which apparently overrides the addons in the file system created by the install, suggesting that you'd have just the modules in addon in eclipse where one could debug etc, but the other resources would be elsewhere? I suppose that's ok, but I still have trouble visualizing how this is going to work, I suppose if this is the way it's done then how would one get standard out to go to the eclipse console? I suppose I could have the complete project in eclipse but all the resources besides the addons would just be for reference purposes, while only the addons would actually be running since they are over-ridden by the –addons-path argument. Then if I could get output to go to the console it would be like what I would expect. I've seen some references to using links in the eclipse workspace or running eclipse as root like an eclipse php setup. Can anyone tell me how to start the server and web apps from eclipse and have the log output appear in the console? Maybe an experienced python developer can spot my blind spots & suggests what I may be else I might be missing here?
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/index.html). They lay out most of the requirements for getting it running. To try and answer your specific questions, you shouldn't need to run the `setup.py` script at all in your development environment. It's only necessary when you deploy to a server. To get the server to recognize a new module, go to the administration menu, and choose Modules Management: Update Modules List. I'm still running OpenERP 5.0, so the names and locations might be slightly different in version 6.1. For the project configuration in Eclipse, I just checked out each branch from launchpad, and then imported each one as a project into my Eclipse workspace. The launch details are a bit different between 6.0 and 6.1. Here are my command line arguments for each: 6.0: > > --addons-path ${workspace\_loc:openerp-addons-6.0} --config ${workspace\_loc:openerp-config/src/server.config} --xmlrpc-port=9069 --netrpc-port=9070 --xmlrpcs-port=9071 > > > 6.1 needs the web client to launch with the server: > > --addons-path ${workspace\_loc:openerp-addons-trunk},${workspace\_loc:openerp-web-trunk}/addons,${workspace\_loc:openerp-migration} --config ${workspace\_loc:openerp-config/src/server.config} --xmlrpc-port=9069 --netrpc-port=9070 --xmlrpcs-port=9071 > > >
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 repositories you need to get, the server, the web client addons and the bundled addons. So I created a top level directory called `openerp-bzr`. In this directory, I checked out the sources with the following command. Note the use of `checkout` and `--lightweight`, these options prevent fetching of all the logs and history (making it much smaller and faster). You may want to omit the --lightweight if you want to get everything and change the checkout to `branch` if that is what you want to do. Back to business. You will have create an account on launchpad and register your ssh keys and configure your bzr. ``` bzr checkout --lightweight lp:openobject-server/7.0 openobject-server-7.0 bzr checkout --lightweight lp:openerp-web/7.0 openerp-web-7.0 bzr checkout --lightweight lp:openobject-addons/7.0 openobject-addons-7.0 ``` (these folders that just got created, I will call them `source folders`). (insert here the instructions to get this to work, which includes configuring the configuration file, setting the PYTHONPATH and downloading all the dependencies. I will add these in the weekend). Then, still in the `openerp-bzr` folder, I create links. The first folder `openerp-7.0` that is created, I will call it `link folder`. ``` ln -s openobject-server-7.0 openerp-7.0 cd openerp-7.0/openerp/addons ln -s ../../../openobject-addons-7.0/* . ln -s ../../../openerp-web-7.0/addons/* . ``` Now, if your eclipse is properly setup, you create a new pydev project, checking the `create links to existing sources (select them on the next page), go next and add`openerp-7.0` (the link folder). You can do bzr update in the source folders. When you develop addons, create the actual folders somewhere else and then link them into the the addons folders in the link folder. This will make it look like you are working in the same tree, you will get all the references and code completion as well as (hopefully, because I have not tested this part!) debugging.
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, **kwargs) File "bot.py", line 215, in sfx vc = await client.join_voice_channel(voice_channel) File "/usr/local/lib/python3.5/site-packages/discord/client.py", line 3176, in join_voice_channel session_id_future = self.ws.wait_for('VOICE_STATE_UPDATE', session_id_found) AttributeError: 'NoneType' object has no attribute 'wait_for' ``` The above exception was the direct cause of the following exception: ``` Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/bot.py", line 848, in process_commands yield from command.invoke(ctx) File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 369, in invoke yield from injected(*ctx.args, **ctx.kwargs) File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 54, in wrapped raise CommandInvokeError(e) from e discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'wait_for' ``` I'm getting this error with channel name and channel ID Function: ``` description = "Bot" bot_prefix = "!" client = discord.Client() bot = commands.Bot(description=description, command_prefix=bot_prefix) @bot.command(pass_context=True) async def join(ctx): author = ctx.message.author voice_channel = author.voice_channel vc = await client.join_voice_channel(voice_channel) ```
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 def join(ctx): author = ctx.message.author channel = author.voice_channel await bot.join_voice_channel(channel) bot.run("token") ```
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, **kwargs) File "bot.py", line 215, in sfx vc = await client.join_voice_channel(voice_channel) File "/usr/local/lib/python3.5/site-packages/discord/client.py", line 3176, in join_voice_channel session_id_future = self.ws.wait_for('VOICE_STATE_UPDATE', session_id_found) AttributeError: 'NoneType' object has no attribute 'wait_for' ``` The above exception was the direct cause of the following exception: ``` Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/bot.py", line 848, in process_commands yield from command.invoke(ctx) File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 369, in invoke yield from injected(*ctx.args, **ctx.kwargs) File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 54, in wrapped raise CommandInvokeError(e) from e discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'wait_for' ``` I'm getting this error with channel name and channel ID Function: ``` description = "Bot" bot_prefix = "!" client = discord.Client() bot = commands.Bot(description=description, command_prefix=bot_prefix) @bot.command(pass_context=True) async def join(ctx): author = ctx.message.author voice_channel = author.voice_channel vc = await client.join_voice_channel(voice_channel) ```
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 def join(ctx): author = ctx.message.author channel = author.voice_channel await bot.join_voice_channel(channel) bot.run("token") ```
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, **kwargs) File "bot.py", line 215, in sfx vc = await client.join_voice_channel(voice_channel) File "/usr/local/lib/python3.5/site-packages/discord/client.py", line 3176, in join_voice_channel session_id_future = self.ws.wait_for('VOICE_STATE_UPDATE', session_id_found) AttributeError: 'NoneType' object has no attribute 'wait_for' ``` The above exception was the direct cause of the following exception: ``` Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/bot.py", line 848, in process_commands yield from command.invoke(ctx) File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 369, in invoke yield from injected(*ctx.args, **ctx.kwargs) File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 54, in wrapped raise CommandInvokeError(e) from e discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'wait_for' ``` I'm getting this error with channel name and channel ID Function: ``` description = "Bot" bot_prefix = "!" client = discord.Client() bot = commands.Bot(description=description, command_prefix=bot_prefix) @bot.command(pass_context=True) async def join(ctx): author = ctx.message.author voice_channel = author.voice_channel vc = await client.join_voice_channel(voice_channel) ```
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 tested on it terminal, then I created another test.py file to check if file write statements are working, so the result was - they were not working. I don't know what is causing the issue, it also ain't giving any error. This is my sample TEST.PY file ``` filename = "domain.log" with open(filename, 'a') as domain_file: domain_file.write("HELLO\n") domain_file.write("ANOTHER HELLO\n") ``` Thank you
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 after running your code a few times: ``` $ cat domain.log HELLO ANOTHER HELLO HELLO ANOTHER HELLO HELLO ANOTHER HELLO ```
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 matching strings with CTRL + F). There is nothing wrong with my code but redardless of that here it is: ``` #!/usr/bin/python # imports import bs4 import requests from bs4 import BeautifulSoup as soup # parse website url = 'https://www.farfetch.com/ch/shopping/men/sale/all/items.aspx?page=1&view=180&scale=282' response = requests.get(url) page_html = response.text page_soup = soup(page_html, "html.parser") # write parsed soup to file with open("soup.html", "a") as dumpfile: dumpfile.write(str(page_soup)) ``` When I drag the soup.html file into the browser, all content loads as it should (like the real url). I assume it to be some kind of protection against parsing? I tried to put in a connection header which tells the webserver on the other side that I am requesting this from a real browser but it didnt work either. 1. Has anyone encountered something similar before? 2. Is there a way to get the REAL html as shown in the browser? When I search the wanted content in the browser it (obviously) shows up... [![enter image description here](https://i.stack.imgur.com/sFrRw.png)](https://i.stack.imgur.com/sFrRw.png) Here the parsed html saved as "soup.html". The content I am looking for can not be found, regardless of *how* I search (CTRL+F) or bs4 function find\_all() or find() or what so ever. [![the parsed content is not the same as the content displayd in the browser](https://i.stack.imgur.com/twqcz.png)](https://i.stack.imgur.com/twqcz.png)
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.parser') for product in soup.select('[data-test="productCard"]:has([data-test="discountPercentage"])'): link = 'https://www.farfetch.com' + product.select_one('a[itemprop="itemListElement"][href]')['href'] brand = product.select_one('[data-test="productDesignerName"]').get_text(strip=True) desc = product.select_one('[data-test="productDescription"]').get_text(strip=True) init_price = product.select_one('[data-test="initialPrice"]').get_text(strip=True) price = product.select_one('[data-test="price"]').get_text(strip=True) images = [i['content'] for i in product.select('meta[itemprop="image"]')] print('Link :', link) print('Brand :', brand) print('Description :', desc) print('Initial price :', init_price) print('Price :', price) print('Images :', images) print('-' * 80) ``` Prints: ``` Link : https://www.farfetch.com/ch/shopping/men/dashiel-brahmann-printed-button-up-shirt-item-14100332.aspx?storeid=9359 Brand : Dashiel Brahmann Description : printed button up shirt Initial price : CHF 438 Price : CHF 219 Images : ['https://cdn-images.farfetch-contents.com/14/10/03/32/14100332_22273147_300.jpg', 'https://cdn-images.farfetch-contents.com/14/10/03/32/14100332_22273157_300.jpg'] -------------------------------------------------------------------------------- Link : https://www.farfetch.com/ch/shopping/men/dashiel-brahmann-corduroy-t-shirt-item-14100309.aspx?storeid=9359 Brand : Dashiel Brahmann Description : corduroy T-Shirt Initial price : CHF 259 Price : CHF 156 Images : ['https://cdn-images.farfetch-contents.com/14/10/03/09/14100309_21985600_300.jpg', 'https://cdn-images.farfetch-contents.com/14/10/03/09/14100309_21985606_300.jpg'] -------------------------------------------------------------------------------- ... and so on. ```
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 the datetime object
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 calculated one. "Transform" is probably a bad choice of words, please tell me if you have a better/more accurate description. Thank you for your help and support!! **Data:** ``` import numpy as np import pandas as pd dicti = {"A" : np.arange(0.0, 3, 0.1), "B" : np.arange(0, 30, 1), "C" : list("ELVISLIVES")*3} df = pd.DataFrame(dicti) ``` **my function:** ``` def transform_colname(df, colname): series = df[colname] newval_list = [] for val in series: if val <= 0.5: newval = (1/val)*-1 newval_list.append(newval) else: newval_list.append(val) df[colname] = newval_list return df ``` **function call:** ``` transform_colname(df, colname="A") ``` **\*\*--> I'm summing up the results here, since comments wouldn't allow to post code (or I don't know how to do it).\*\*** **Thank you all for your fast and great answers!!** using ipython "%timeit" with "real" data: **my function:** 10 loops, best of 3: 24.1 ms per loop **from jojo:** ``` def transform_colname_v2(df, colname): series = df[colname] df[colname] = np.where(series <= 0.5, 1/series*-1, series) return df ``` 100 loops, best of 3: 2.76 ms per loop **from FooBar:** ``` def transform_colname_v3(df, colname): df.loc[df[colname] <= 0.5, colname] = - 1 / df[colname][df[colname] <= 0.5] return df ``` 100 loops, best of 3: 3.32 ms per loop **from dmvianna:** ``` def transform_colname_v4(df, colname): df[colname] = df[colname].where(df[colname] <= 0.5, (1/df[colname])*-1) return df ``` 100 loops, best of 3: 3.7 ms per loop Please tell/show me if you would implement your code in a different way! One final QUESTION: (answered) How could "FooBar" and "dmvianna" 's versions be made "generic"? I mean, I had to write the name of the column into the function (since using it as a variable didn't work). Please explain this last point! --> thanks jojo, ".loc" isn't the right way, but very simple df[colname] is sufficient. changed the functions above to be more "generic". (also changed ">" to be "<=", and updated timing) Thank you very much!!
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], dtype=np.float) print np.where(a < 0.5, 1 / a * (-1), a) ``` Talking about `pandas` **DataFrame**: As in **@dmvianna**'s answer (so give some credit to him ;) ), adapting it to `pd.DataFrame`: ``` df.a = df.a.where(df.a > 0.5, (1 / df.a) * (-1)) ```
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 2 V 3 -3.333333 3 I 4 -2.500000 4 S 5 0.500000 5 L 6 0.600000 6 I 7 0.700000 7 V 8 0.800000 8 E 9 0.900000 9 S 10 1.000000 10 E 11 1.100000 11 L 12 1.200000 12 V 13 1.300000 13 I 14 1.400000 14 S 15 1.500000 15 L 16 1.600000 16 I 17 1.700000 17 V 18 1.800000 18 E 19 1.900000 19 S 20 2.000000 20 E 21 2.100000 21 L 22 2.200000 22 V 23 2.300000 23 I 24 2.400000 24 S 25 2.500000 25 L 26 2.600000 26 I 27 2.700000 27 V 28 2.800000 28 E 29 2.900000 29 S ```
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 calculated one. "Transform" is probably a bad choice of words, please tell me if you have a better/more accurate description. Thank you for your help and support!! **Data:** ``` import numpy as np import pandas as pd dicti = {"A" : np.arange(0.0, 3, 0.1), "B" : np.arange(0, 30, 1), "C" : list("ELVISLIVES")*3} df = pd.DataFrame(dicti) ``` **my function:** ``` def transform_colname(df, colname): series = df[colname] newval_list = [] for val in series: if val <= 0.5: newval = (1/val)*-1 newval_list.append(newval) else: newval_list.append(val) df[colname] = newval_list return df ``` **function call:** ``` transform_colname(df, colname="A") ``` **\*\*--> I'm summing up the results here, since comments wouldn't allow to post code (or I don't know how to do it).\*\*** **Thank you all for your fast and great answers!!** using ipython "%timeit" with "real" data: **my function:** 10 loops, best of 3: 24.1 ms per loop **from jojo:** ``` def transform_colname_v2(df, colname): series = df[colname] df[colname] = np.where(series <= 0.5, 1/series*-1, series) return df ``` 100 loops, best of 3: 2.76 ms per loop **from FooBar:** ``` def transform_colname_v3(df, colname): df.loc[df[colname] <= 0.5, colname] = - 1 / df[colname][df[colname] <= 0.5] return df ``` 100 loops, best of 3: 3.32 ms per loop **from dmvianna:** ``` def transform_colname_v4(df, colname): df[colname] = df[colname].where(df[colname] <= 0.5, (1/df[colname])*-1) return df ``` 100 loops, best of 3: 3.7 ms per loop Please tell/show me if you would implement your code in a different way! One final QUESTION: (answered) How could "FooBar" and "dmvianna" 's versions be made "generic"? I mean, I had to write the name of the column into the function (since using it as a variable didn't work). Please explain this last point! --> thanks jojo, ".loc" isn't the right way, but very simple df[colname] is sufficient. changed the functions above to be more "generic". (also changed ">" to be "<=", and updated timing) Thank you very much!!
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 2 V 3 -3.333333 3 I 4 -2.500000 4 S 5 0.500000 5 L 6 0.600000 6 I 7 0.700000 7 V 8 0.800000 8 E 9 0.900000 9 S 10 1.000000 10 E 11 1.100000 11 L 12 1.200000 12 V 13 1.300000 13 I 14 1.400000 14 S 15 1.500000 15 L 16 1.600000 16 I 17 1.700000 17 V 18 1.800000 18 E 19 1.900000 19 S 20 2.000000 20 E 21 2.100000 21 L 22 2.200000 22 V 23 2.300000 23 I 24 2.400000 24 S 25 2.500000 25 L 26 2.600000 26 I 27 2.700000 27 V 28 2.800000 28 E 29 2.900000 29 S ```
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\_on\_error=True) > > > Docstring: > Return an object of same shape as self and whose corresponding entries > are from self where cond is True and otherwise are from other. > > >
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 calculated one. "Transform" is probably a bad choice of words, please tell me if you have a better/more accurate description. Thank you for your help and support!! **Data:** ``` import numpy as np import pandas as pd dicti = {"A" : np.arange(0.0, 3, 0.1), "B" : np.arange(0, 30, 1), "C" : list("ELVISLIVES")*3} df = pd.DataFrame(dicti) ``` **my function:** ``` def transform_colname(df, colname): series = df[colname] newval_list = [] for val in series: if val <= 0.5: newval = (1/val)*-1 newval_list.append(newval) else: newval_list.append(val) df[colname] = newval_list return df ``` **function call:** ``` transform_colname(df, colname="A") ``` **\*\*--> I'm summing up the results here, since comments wouldn't allow to post code (or I don't know how to do it).\*\*** **Thank you all for your fast and great answers!!** using ipython "%timeit" with "real" data: **my function:** 10 loops, best of 3: 24.1 ms per loop **from jojo:** ``` def transform_colname_v2(df, colname): series = df[colname] df[colname] = np.where(series <= 0.5, 1/series*-1, series) return df ``` 100 loops, best of 3: 2.76 ms per loop **from FooBar:** ``` def transform_colname_v3(df, colname): df.loc[df[colname] <= 0.5, colname] = - 1 / df[colname][df[colname] <= 0.5] return df ``` 100 loops, best of 3: 3.32 ms per loop **from dmvianna:** ``` def transform_colname_v4(df, colname): df[colname] = df[colname].where(df[colname] <= 0.5, (1/df[colname])*-1) return df ``` 100 loops, best of 3: 3.7 ms per loop Please tell/show me if you would implement your code in a different way! One final QUESTION: (answered) How could "FooBar" and "dmvianna" 's versions be made "generic"? I mean, I had to write the name of the column into the function (since using it as a variable didn't work). Please explain this last point! --> thanks jojo, ".loc" isn't the right way, but very simple df[colname] is sufficient. changed the functions above to be more "generic". (also changed ">" to be "<=", and updated timing) Thank you very much!!
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], dtype=np.float) print np.where(a < 0.5, 1 / a * (-1), a) ``` Talking about `pandas` **DataFrame**: As in **@dmvianna**'s answer (so give some credit to him ;) ), adapting it to `pd.DataFrame`: ``` df.a = df.a.where(df.a > 0.5, (1 / df.a) * (-1)) ```
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\_on\_error=True) > > > Docstring: > Return an object of same shape as self and whose corresponding entries > are from self where cond is True and otherwise are from other. > > >
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, **kwargs)) wx._core.PyAssertionError: C++ assertion "strcmp(setlocale(LC_ALL, NULL), "C") == 0" failed at ..\..\src\common\intl.cpp(1449) in wxLocale::GetInfo(): You probably called setlocale() directly instead of using wxLocale and now there is a mismatch between C/C++ and Windows locale. Things are going to break, please only change locale by creating wxLocale objects to avoid this! ``` the error comes from this line ``` File "C:\Users\hadi\Dropbox\Projects\Python\dialysis\profile.py", line 159, in __init__ style=wx.DP_DROPDOWN) ``` Help is much appreciated
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 someone else with more specific knowledge on this can fill that in. Try manually setting the locale using the wxPython object wx.Locale: `locale = wx.Locale(wx.LANGUAGE_ENGLISH)` However, make sure that you assign the output to a non-local variable. As soon as the variable goes out of scope, the Locale object is destructed. So if it's in a class: `class MyApp(wx.App): ... def OnInit(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) ...`
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 Python default locale on Windows?](https://stackoverflow.com/questions/11234843/how-to-set-python-default-locale-on-windows) My original error message : ``` ..\..\src\common\intl.cpp(1449): assert "strcmp( setlocale(LC_ALL, NULL), "C")==0" failed in wxLocale::GetInfo() ... ```
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 function and **Expr2**'s? I think **Expr1** gives the right answer, but not sure.
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 function and **Expr2**'s? I think **Expr1** gives the right answer, but not sure.
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. --- **Long answer:** Here is how I identified the discrepancies: ``` import os import subprocess import itertools def line_to_filename(line): # This assumes that filenames have no spaces, which is a false assumption # Ex: /etc/NetworkManager/system-connections/Wired connection 1 idx = line.rfind('->') if idx > -1: return line[:idx].split()[-1] else: return line.split()[-1] ``` `line_to_filename` tries to find the filename in the output of `ls -laR`. This defines `expr1` and `expr2` and is essentially the same as your code. ``` proc=subprocess.Popen( "ls /etc -alR 2>/dev/null | grep -s \"^[-l]\" ", shell = True, stdout = subprocess.PIPE) #Expr1 out, err = proc.communicate() expr1 = map(line_to_filename, out.splitlines()) expr2 = list(itertools.chain.from_iterable( files for root,dirs,files in os.walk('/etc') if files)) #Expr2 for expr in ('expr1', 'expr2'): print '{e} is of length {l}'.format(e = expr, l = len(vars()[expr])) ``` This removes names from `expr1` that are also in `expr2`: ``` for name in expr2: try: expr1.remove(name) except ValueError: print('{n} is not in expr1'.format(n = name)) ``` After removing filenames that `expr1` and `expr2` share in common, ``` print(expr1) ``` yields ``` ['i386-linux-gnu_xorg_extra_modules', 'nvctrl_include', 'template-dkms-mkdsc', 'run', '1', 'conf.d', 'conf.d'] ``` I then used `find` to find these files in `/etc` and tried to guess what was unusual about these files. They were symlinks to directories (rather than 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 function and **Expr2**'s? I think **Expr1** gives the right answer, but not sure.
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. --- **Long answer:** Here is how I identified the discrepancies: ``` import os import subprocess import itertools def line_to_filename(line): # This assumes that filenames have no spaces, which is a false assumption # Ex: /etc/NetworkManager/system-connections/Wired connection 1 idx = line.rfind('->') if idx > -1: return line[:idx].split()[-1] else: return line.split()[-1] ``` `line_to_filename` tries to find the filename in the output of `ls -laR`. This defines `expr1` and `expr2` and is essentially the same as your code. ``` proc=subprocess.Popen( "ls /etc -alR 2>/dev/null | grep -s \"^[-l]\" ", shell = True, stdout = subprocess.PIPE) #Expr1 out, err = proc.communicate() expr1 = map(line_to_filename, out.splitlines()) expr2 = list(itertools.chain.from_iterable( files for root,dirs,files in os.walk('/etc') if files)) #Expr2 for expr in ('expr1', 'expr2'): print '{e} is of length {l}'.format(e = expr, l = len(vars()[expr])) ``` This removes names from `expr1` that are also in `expr2`: ``` for name in expr2: try: expr1.remove(name) except ValueError: print('{n} is not in expr1'.format(n = name)) ``` After removing filenames that `expr1` and `expr2` share in common, ``` print(expr1) ``` yields ``` ['i386-linux-gnu_xorg_extra_modules', 'nvctrl_include', 'template-dkms-mkdsc', 'run', '1', 'conf.d', 'conf.d'] ``` I then used `find` to find these files in `/etc` and tried to guess what was unusual about these files. They were symlinks to directories (rather than 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 the below entries should fail ``` htps://www.foo.com/ https:/www.foo.com/bar/ sc-domain:www.foo.com/ sc-domain:www.foo.com/bar scdomain:www.foo.com ``` Right now I'm working with the below: ``` ^(https://*/|sc-domain:^[^/]*$) ``` This almost works, but still allows submissions like sc-domain:www.foo.com/ to go through. Specifically, the `^[^/]*$` part doesn't capture that a '/' should not pass.
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 followed by path using * `|` - alternation for strings starting with sc-domain: * `sc-domain:www\.foo\.com` - This part starts matching with sc-domain: followed by www.foo.com and further does not allow any file path * `)$` - Close of non-grouping pattern and end of string. **[Regex Demo](https://regex101.com/r/PxmPum/1)** Also, a little not sure whether you wanted to allow any random domain, but in case you want to allow, you can use this regex, ``` ^(?:https?://(?:\w+\.)+\w+(?:/\S*)*|sc-domain:(?:\w+\.)+\w+)$ ``` **[Regex Demo allowing any domain](https://regex101.com/r/PxmPum/2/)**
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 the below entries should fail ``` htps://www.foo.com/ https:/www.foo.com/bar/ sc-domain:www.foo.com/ sc-domain:www.foo.com/bar scdomain:www.foo.com ``` Right now I'm working with the below: ``` ^(https://*/|sc-domain:^[^/]*$) ``` This almost works, but still allows submissions like sc-domain:www.foo.com/ to go through. Specifically, the `^[^/]*$` part doesn't capture that a '/' should not pass.
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](https://i.stack.imgur.com/hDx4S.png)](https://i.stack.imgur.com/hDx4S.png) ### JavaScript Test ```js const regex = /^(((http|https)(:\/\/www.foo.com)(\/.*))|(sc-domain:www.foo.com))$/gm; const str = `https://www.foo.com/ https://www.foo.com/bar/ sc-domain:www.foo.com http://www.foo.com/ http://www.foo.com/bar/ `; const subst = `$1`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log('Substitution result: ', result); ``` ### Test with Python You can simply test with Python and add the capturing groups that are desired: ``` # coding=utf8 # the above tag defines encoding for this document and is for Python 2.x compatibility import re regex = r"^((http|https)(:\/\/www.foo.com)(\/.*))|(sc-domain:www.foo.com)$" test_str = ("https://www.foo.com/\n" "https://www.foo.com/bar/\n" "sc-domain:www.foo.com\n" "http://www.foo.com/\n" "http://www.foo.com/bar/\n\n" "htps://www.foo.com/\n" "https:/www.foo.com/bar/\n" "sc-domain:www.foo.com/\n" "sc-domain:www.foo.com/bar\n" "scdomain:www.foo.com") subst = "$1 $2" # You can manually specify the number of replacements by changing the 4th argument result = re.sub(regex, subst, test_str, 0, re.MULTILINE) if result: print (result) # Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution. ``` ### Edit Based on [Pushpesh](https://stackoverflow.com/users/2102956/pushpesh-kumar-rajwanshi)'s advice, you can use lookaround and simplify it to: ``` ^((https?)(:\/\/www.foo.com)(\/.*))|(sc-domain:www.foo.com)$ ```
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. [![example of an output of array in jupiter](https://i.stack.imgur.com/eGhQ2.png)](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 layout'. It should switch around. > > > If the first language selected in your browser is Arabic or Hebrew, it > currently selects RTL by default. CCing @samarsultan in case that > needs refining. > > >
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), I get the following error: ``` (Canopy 64bit) [xxuser@xxlinux ~]$ /root/Canopy/canopy Traceback (most recent call last): File "/home/xxuser/qiime_software/sphinx-1.0.4-release/lib/python2.7/site-packages/site.py", line 73, in <module> __boot() File "/home/xxuser/qiime_software/sphinx-1.0.4-release/lib/python2.7/site-packages/site.py", line 2, in __boot import sys, imp, os, os.path ImportError: No module named path ``` I found this link: [Python - os.path doesn't exist: AttributeError: 'module' object has no attribute 'path'](https://stackoverflow.com/questions/21640794/python-os-path-doesnt-exist-attributeerror-module-object-has-no-attribute), but both of my os.py and os.pyc were 250 and 700 bytes, respectively. There was another file called site.py which was 0 bytes and site.pyc was about 100 bytes. What are these files? And would deleting them hurt anything (which is what they did)? And why is this happening after reboot? (using reboot command). I also found this: <https://groups.google.com/forum/#!topic/spyderlib/hKB15JYyLqM> , which could be relevant. I've updated my python path before with sys.path.append('/..') My guess is that for some reason os.path isn't in sys.path? and \_\_boot can't find it? But I'm new to Python and Linux and want to know what I'm doing before I go modifying any boot files, paths, etc. Thanks in advance. **More information** (saw that I'm supposed to update new info in an edit to original question. New to this.) From one of the comments: This is what I got: import os.path import posixpath os.path module 'posixpath' from '/home/xxuser/qiime\_software/python-2.7.3-release/lib/python2.7/posixpath.pyc' posixpath module 'posixpath' from '/home/xxuser/qiime\_software/python-2.7.3-release/lib/python2.7/posixpath.pyc' Looks like os.path is there. Could this have to do with a permissions error? I have it installed to /root/Canopy/canopy and I found this: docs.python.org/2/library/os.html#module-os (section 15.1.4). Does that make sense? I'm also not sure if the following is related, but it might possibly. I can no longer seem to update my path with sys.path.append('/file/path/here'). It works until I close the terminal, then I have to re-append the next time I want to call a module from the new directory. Are sys.path and os.path related in any way?
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 (for some reason source ~/.bashrc didn't work) eliminated all of the extra stuff I'd added to my $PATH and Canopy began working again. I'm going to go through and remove the extra installations of python and hopefully the issue will be behind me. Thanks to everyone who posted answers, especially A.J., because that's what got me thinking about .bashrc . Edit: With some better understanding, this was all because of using python in a virtual environment. Canopy was resetting my path every time I opened it. I'm using a self-installed virtual environment now and have configured my path.
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.framework/Versions/2.7/lib/python2.7/posixpath.pyc'> >>> ```
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), I get the following error: ``` (Canopy 64bit) [xxuser@xxlinux ~]$ /root/Canopy/canopy Traceback (most recent call last): File "/home/xxuser/qiime_software/sphinx-1.0.4-release/lib/python2.7/site-packages/site.py", line 73, in <module> __boot() File "/home/xxuser/qiime_software/sphinx-1.0.4-release/lib/python2.7/site-packages/site.py", line 2, in __boot import sys, imp, os, os.path ImportError: No module named path ``` I found this link: [Python - os.path doesn't exist: AttributeError: 'module' object has no attribute 'path'](https://stackoverflow.com/questions/21640794/python-os-path-doesnt-exist-attributeerror-module-object-has-no-attribute), but both of my os.py and os.pyc were 250 and 700 bytes, respectively. There was another file called site.py which was 0 bytes and site.pyc was about 100 bytes. What are these files? And would deleting them hurt anything (which is what they did)? And why is this happening after reboot? (using reboot command). I also found this: <https://groups.google.com/forum/#!topic/spyderlib/hKB15JYyLqM> , which could be relevant. I've updated my python path before with sys.path.append('/..') My guess is that for some reason os.path isn't in sys.path? and \_\_boot can't find it? But I'm new to Python and Linux and want to know what I'm doing before I go modifying any boot files, paths, etc. Thanks in advance. **More information** (saw that I'm supposed to update new info in an edit to original question. New to this.) From one of the comments: This is what I got: import os.path import posixpath os.path module 'posixpath' from '/home/xxuser/qiime\_software/python-2.7.3-release/lib/python2.7/posixpath.pyc' posixpath module 'posixpath' from '/home/xxuser/qiime\_software/python-2.7.3-release/lib/python2.7/posixpath.pyc' Looks like os.path is there. Could this have to do with a permissions error? I have it installed to /root/Canopy/canopy and I found this: docs.python.org/2/library/os.html#module-os (section 15.1.4). Does that make sense? I'm also not sure if the following is related, but it might possibly. I can no longer seem to update my path with sys.path.append('/file/path/here'). It works until I close the terminal, then I have to re-append the next time I want to call a module from the new directory. Are sys.path and os.path related in any way?
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.framework/Versions/2.7/lib/python2.7/posixpath.pyc'> >>> ```
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 in sys.stdin: line_words = line.split(" ") for word in line_words: if word in pairs line = line.gsub!(word, pairs[word]) puts line ``` It shows the following error ``` syntax error, unexpected kIN, expecting kTHEN or ':' or '\n' or ';' if word in pairs ^ ``` While below is the original python script which is right: ``` import sys pairs = dict() pairs = {'butter': 'flies', 'cheese': 'wheel', 'milk': 'expensive'} for line in sys.stdin: line = line.strip() line_words = line.split(" ") for word in line_words: if word in pairs: line = line.replace(word ,pairs[word]) print line ``` Is it because of "import sys" or “Indentation”?
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 space.
`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 exist in Ruby, so that shouldn't be there. You also have to "close" each block with `end` in Ruby, indentation alone isn't enough (indentation doesn't mean anything to Ruby, although you should still keep it for readability).
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: ``` t = "%s %s %s %s" % (field[1],field[2],field[3],field[4]) ``` If field[3] is null for instance, t will be something like ``` "string1 string2 None string4" ``` instead of ``` "string1 string2 string4" ``` yes I would need to remove also the double space in case. I cannot just replace "None" with "" because some string might contain itself "None" since it is a common word. Of course I don't have only 4 field, they are a lot, and I am not trying to import every field of the row, only specific ones. I need a fast and easy way to fix this behavior. I cannot manually check if each field is None, that's insane. I cannot use ``` str.strip(field[i]) ``` because when the field is None I get an error. what could be a good approach?
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): print "module.__metaclass__" future_class_attrs["bar"]="bar" return type(future_class_name, future_class_parents, future_class_attrs) class Foo(object): __metaclass__ = metaclass def __init__(self): print 'Foo.__init__' f=Foo() ``` See [http://docs.python.org/reference/datamodel.html?highlight=**metaclass**#customizing-class-creation](http://docs.python.org/reference/datamodel.html?highlight=__metaclass__#customizing-class-creation)
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 used. > * Otherwise, if there is at > least one base class, its metaclass is used (this looks for a > `__class__` attribute first and if not found, uses its type). > * Otherwise, if a global variable named `__metaclass__` exists, it is used. > * Otherwise, the old-style, classic metaclass (`types.ClassType`) is used. > > > You will see from the above that having a base class *at all* (whatever the base class is, even if it does not ultimately inherit from `object`) pre-empts the module-level `__metaclass__`.
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 for my local copy of the application. The error I am getting is: > > HTTPError: HTTP Error 404: Not Found > > [ERROR ] Authentication Failed: Incorrect credentials or unsupported authentication type (e.g. OpenId). > > > But I am not really using any credentials to host it locally. Please help. ``` ./appcfg.py upload_data --application=say_hello --config_file=bulkloader.yaml --filename=output.csv --kind=Dashboard --url=http:hostname:8080/_ah/remote_api ```
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 for my local copy of the application. The error I am getting is: > > HTTPError: HTTP Error 404: Not Found > > [ERROR ] Authentication Failed: Incorrect credentials or unsupported authentication type (e.g. OpenId). > > > But I am not really using any credentials to host it locally. Please help. ``` ./appcfg.py upload_data --application=say_hello --config_file=bulkloader.yaml --filename=output.csv --kind=Dashboard --url=http:hostname:8080/_ah/remote_api ```
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=test@example.com path/to/folder/containing/app/yaml/ ``` Where [your-app-id] seems to be in the format `dev~[application-name]`. e.g `dev~something-engine-v2`. NB: Also **ensure HTTP**, as I also got the same error when accidentally accessing localhost with HTTPS.
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 for my local copy of the application. The error I am getting is: > > HTTPError: HTTP Error 404: Not Found > > [ERROR ] Authentication Failed: Incorrect credentials or unsupported authentication type (e.g. OpenId). > > > But I am not really using any credentials to host it locally. Please help. ``` ./appcfg.py upload_data --application=say_hello --config_file=bulkloader.yaml --filename=output.csv --kind=Dashboard --url=http:hostname:8080/_ah/remote_api ```
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: /.* # script: main.py ```
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 integer so I have to make it a string ``` def product_of_digits(number): d= str(number) for integer in d: s = 0 k = [] while s < (len(d)): print (int(d[s])*int(d[s+1])*int(d[s+2])*int(d[s+3])*int(d[s+4])) s += 1 print (product_of_digits(a)) ```
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+1])*int(d[s+2])*int(d[s+3])*int(d[s+4])) s += 5 (see point 2) print (product_of_digits(124345565534)) ```
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 integer so I have to make it a string ``` def product_of_digits(number): d= str(number) for integer in d: s = 0 k = [] while s < (len(d)): print (int(d[s])*int(d[s+1])*int(d[s+2])*int(d[s+3])*int(d[s+4])) s += 1 print (product_of_digits(a)) ```
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 product of all the consecutive 5 numbers, you cannot loop till the end of `d`. So, the loop should have been `while s <= (len(d)-5):` 5. You have initialized `k`, but used it nowhere. So, the corrected program looks like this ``` def product_of_digits(number): d, s = str(number), 0 while s <= (len(d)-5): print(int(d[s]) * int(d[s+1]) * int(d[s+2]) * int(d[s+3]) * int(d[s+4])) s += 1 product_of_digits(123456) ``` **Output** ``` 120 720 ``` You can also use a for loop, like this ``` def product_of_digits(number): d = str(number) for s in range(len(d) - 4): print(int(d[s]) * int(d[s+1]) * int(d[s+2]) * int(d[s+3]) * int(d[s+4])) ```
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 `cat humid.txt` gave me empty strings. crontab ======= `sudo crontab -e` ``` * * * * * python /home/dixhom/Adafruit_Python_DHT/examples/temphumid.py 1>>/tmp/cronoutput.log 2>>/tmp/cronerror.log ``` python script ============= ``` #!/usr/bin/python import sys import Adafruit_DHT import datetime # Adafruit_DHT.DHT22 : device name # 4 : pin number humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4) if humidity is not None: f = open("humid.txt","w") str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), humidity) f.write(str) else: print 'Failed to get reading. Try again!' sys.exit(1) if temperature is not None: f = open("temp.txt","w") str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), temperature) f.write(str) else: print 'Failed to get reading. Try again!' sys.exit(1) ``` cronerror.log and cronoutput.log ================================ (empty) What I tried ============ * `sudo crontab -e` * `/usr/bin/python` in cron * `chkconfig cron` (cron on) * `sudo apt-get update` `sudo apt-get upgrade` * `sudo reboot` Any help would be appreciated. Thanks.
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=LFr06ZKIpSM> If you decide not to go with netbeans, you are gonna have to create swing containers withing your class to make the Interface.
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 `cat humid.txt` gave me empty strings. crontab ======= `sudo crontab -e` ``` * * * * * python /home/dixhom/Adafruit_Python_DHT/examples/temphumid.py 1>>/tmp/cronoutput.log 2>>/tmp/cronerror.log ``` python script ============= ``` #!/usr/bin/python import sys import Adafruit_DHT import datetime # Adafruit_DHT.DHT22 : device name # 4 : pin number humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4) if humidity is not None: f = open("humid.txt","w") str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), humidity) f.write(str) else: print 'Failed to get reading. Try again!' sys.exit(1) if temperature is not None: f = open("temp.txt","w") str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), temperature) f.write(str) else: print 'Failed to get reading. Try again!' sys.exit(1) ``` cronerror.log and cronoutput.log ================================ (empty) What I tried ============ * `sudo crontab -e` * `/usr/bin/python` in cron * `chkconfig cron` (cron on) * `sudo apt-get update` `sudo apt-get upgrade` * `sudo reboot` Any help would be appreciated. Thanks.
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 to use, drag and drop concept. It creates a FXML file which is used to declare your programs GUI.
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=LFr06ZKIpSM> If you decide not to go with netbeans, you are gonna have to create swing containers withing your class to make the Interface.
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 `cat humid.txt` gave me empty strings. crontab ======= `sudo crontab -e` ``` * * * * * python /home/dixhom/Adafruit_Python_DHT/examples/temphumid.py 1>>/tmp/cronoutput.log 2>>/tmp/cronerror.log ``` python script ============= ``` #!/usr/bin/python import sys import Adafruit_DHT import datetime # Adafruit_DHT.DHT22 : device name # 4 : pin number humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4) if humidity is not None: f = open("humid.txt","w") str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), humidity) f.write(str) else: print 'Failed to get reading. Try again!' sys.exit(1) if temperature is not None: f = open("temp.txt","w") str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), temperature) f.write(str) else: print 'Failed to get reading. Try again!' sys.exit(1) ``` cronerror.log and cronoutput.log ================================ (empty) What I tried ============ * `sudo crontab -e` * `/usr/bin/python` in cron * `chkconfig cron` (cron on) * `sudo apt-get update` `sudo apt-get upgrade` * `sudo reboot` Any help would be appreciated. Thanks.
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 application class anywhere you want, I guess this is why you were confused about where to place the GUI code... ``` public class PlayersGUI extends JFrame { private static final long serialVersionUID = 1L; private Players players; // instance variable of your application private PlayersGUI() { players = new Players(); initGUI(); } private void initGUI() { setTitle("This the GUI for Players application"); setPreferredSize(new Dimension(640, 560)); setLocation(new Point(360, 240)); JPanel jPanel = new JPanel(); JLabel stat = new JLabel(players.getBasicStats()); JButton attack = new JButton("Attack!"); attack.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { players.addAttack(1); } }); JButton hugeAttack = new JButton("HUGE Attack!"); hugeAttack.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { players.addAttack(10); } }); JButton defend = new JButton("Defend"); defend.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { players.addDefence(1); } }); JButton showStats = new JButton("Show stats"); showStats.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stat.setText(players.getBasicStats()); } }); jPanel.add(stat); jPanel.add(attack); jPanel.add(hugeAttack); jPanel.add(defend); jPanel.add(showStats); add(jPanel); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public static void main(String... args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { PlayersGUI pgui = new PlayersGUI(); pgui.pack(); pgui.setVisible(true); } }); } } ```
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=LFr06ZKIpSM> If you decide not to go with netbeans, you are gonna have to create swing containers withing your class to make the Interface.
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 `cat humid.txt` gave me empty strings. crontab ======= `sudo crontab -e` ``` * * * * * python /home/dixhom/Adafruit_Python_DHT/examples/temphumid.py 1>>/tmp/cronoutput.log 2>>/tmp/cronerror.log ``` python script ============= ``` #!/usr/bin/python import sys import Adafruit_DHT import datetime # Adafruit_DHT.DHT22 : device name # 4 : pin number humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4) if humidity is not None: f = open("humid.txt","w") str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), humidity) f.write(str) else: print 'Failed to get reading. Try again!' sys.exit(1) if temperature is not None: f = open("temp.txt","w") str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), temperature) f.write(str) else: print 'Failed to get reading. Try again!' sys.exit(1) ``` cronerror.log and cronoutput.log ================================ (empty) What I tried ============ * `sudo crontab -e` * `/usr/bin/python` in cron * `chkconfig cron` (cron on) * `sudo apt-get update` `sudo apt-get upgrade` * `sudo reboot` Any help would be appreciated. Thanks.
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 to use, drag and drop concept. It creates a FXML file which is used to declare your programs GUI.
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 `cat humid.txt` gave me empty strings. crontab ======= `sudo crontab -e` ``` * * * * * python /home/dixhom/Adafruit_Python_DHT/examples/temphumid.py 1>>/tmp/cronoutput.log 2>>/tmp/cronerror.log ``` python script ============= ``` #!/usr/bin/python import sys import Adafruit_DHT import datetime # Adafruit_DHT.DHT22 : device name # 4 : pin number humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4) if humidity is not None: f = open("humid.txt","w") str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), humidity) f.write(str) else: print 'Failed to get reading. Try again!' sys.exit(1) if temperature is not None: f = open("temp.txt","w") str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), temperature) f.write(str) else: print 'Failed to get reading. Try again!' sys.exit(1) ``` cronerror.log and cronoutput.log ================================ (empty) What I tried ============ * `sudo crontab -e` * `/usr/bin/python` in cron * `chkconfig cron` (cron on) * `sudo apt-get update` `sudo apt-get upgrade` * `sudo reboot` Any help would be appreciated. Thanks.
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 application class anywhere you want, I guess this is why you were confused about where to place the GUI code... ``` public class PlayersGUI extends JFrame { private static final long serialVersionUID = 1L; private Players players; // instance variable of your application private PlayersGUI() { players = new Players(); initGUI(); } private void initGUI() { setTitle("This the GUI for Players application"); setPreferredSize(new Dimension(640, 560)); setLocation(new Point(360, 240)); JPanel jPanel = new JPanel(); JLabel stat = new JLabel(players.getBasicStats()); JButton attack = new JButton("Attack!"); attack.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { players.addAttack(1); } }); JButton hugeAttack = new JButton("HUGE Attack!"); hugeAttack.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { players.addAttack(10); } }); JButton defend = new JButton("Defend"); defend.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { players.addDefence(1); } }); JButton showStats = new JButton("Show stats"); showStats.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stat.setText(players.getBasicStats()); } }); jPanel.add(stat); jPanel.add(attack); jPanel.add(hugeAttack); jPanel.add(defend); jPanel.add(showStats); add(jPanel); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public static void main(String... args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { PlayersGUI pgui = new PlayersGUI(); pgui.pack(); pgui.setVisible(true); } }); } } ```
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 miss one of the many lights. I specify python because its the only high level language I am familiar with. Most of my embedded work is in C, and C is tricky to work with at higher levels.
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. * After filtering the colors, You can use houghcircles/blobs to locate the LEDs * Presence of the blob means that LED is on. You can then make decisions based on this knowledge. Opencv has python bindings, so you can program this with python. Snippet to do color filtering. ``` import cv2 as cv2 import numpy as np fn = 'image_or_videoframe' # OpenCV reads image with BGR format img = cv2.imread(fn) # Convert to HSV format img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Choose the values based on the color on the point/mark lower_red = np.array([0, 50, 50]) upper_red = np.array([10, 255, 255]) mask = cv2.inRange(img_hsv, lower_red, upper_red) # Bitwise-AND mask and original image masked_red = cv2.bitwise_and(img, img, mask=mask) ``` in this case, the red is filtered in the image and `masked_red` would contain only the red pixels in the image. You can change `lower_red` and `upper_red` to different values depending on the color you want to filter. Good luck :)
[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-http, 1-ftp): '.format(domain)) print(protocol) input() if protocol == 0: is_secure = bool(input('Should we use secure connection? (1-yes, 0-no): ')) factory = HTTPFactory(is_secure) elif protocol == 1: is_secure = False factory = FTPFactory(is_secure) else: print('Sorry, wrong answer') import sys sys.exit(1) connector = Connector(factory) try: content = connector.read(domain, path) except URLError as e: print('Can not access resource with this method') else: print(connector.parse(content)) ``` **Output:** ``` Connecting to ftp.freebsd.org. Which Protocol to use? (0-http, 1-ftp): 0 0 Sorry, wrong answer $ python abstractfactory.py Connecting to ftp.freebsd.org. Which Protocol to use? (0-http, 1-ftp): http http Sorry, wrong answer $ python abstractfactory.py Connecting to ftp.freebsd.org. Which Protocol to use? (0-http, 1-ftp): 1 1 Sorry, wrong answer $ ``` Please advice. What am I doing wrong here? Thanks.
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 5.1234 > 2 3.5e+08 8.2e+02 6.2222 > 2 1.7e+08 2.2e+02 7.4567 > 3 8.7e+08 3.2e+02 9.2123 > > ``` > > I'm essentially trying to delete the second and third element/variable from each line. Any suggestions? I'm new to python and unsure how approach this. Any help would be appreciated. Thanks The code is a work in progress. So far, it reads file.txt and removes the first three lines and writes it out as newfile.txt. Here it is: ``` import sys try: f=open('file.txt', 'r') lines = f.readlines() except IOError: print('File file.txt does not exist') sys.exit(1) for line in lines: sys.stdout.write(line) f.close() # Deleting the first three lines del lines[0:3] # Deleting the second and third element of every line f=open('newfile.txt','w') f.writelines(lines) print(lines) f.close() ```
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(Guid.NewGuid().ToString(), STORY_DATA_IDENTIFIER); var fileContent = await UserSnippets.GetCurrentUserFileAsync("/Documents","Imp.zip") ; using (var fileStream = await Task.Run(() => System.IO.File.Create(ApplicationData.Current.LocalFolder.Path + "\\Imp.zip"))) { fileContent.Seek(0, SeekOrigin.Begin); fileContent.CopyTo(fileStream); } return fileContent != null; } ``` For detailed information to Application's relative path one can lookup this page: [ApplicationData Class](https://learn.microsoft.com/en-us/uwp/api/windows.storage.applicationdata) Thanks @RasmusW
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 (var fileStream = File.Create("C:\\localpath\\localfilename")) { fileContent.Seek(0, SeekOrigin.Begin); fileContent.CopyTo(fileStream); } ```
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) AS enter, MAX(transactions.post_date) AS post, MAX(transactions.description) AS "beschr", SUM(splits.value_num) AS "Euro" FROM gnucash.splits INNER JOIN gnucash.transactions ON gnucash.splits.tx_guid = gnucash.transactions.guid INNER JOIN gnucash.accounts ON gnucash.splits.account_guid = gnucash.accounts.guid WHERE transactions.guid IN ( SELECT transactions.guid FROM gnucash.splits INNER JOIN gnucash.transactions ON gnucash.splits.tx_guid = gnucash.transactions.guid INNER JOIN gnucash.accounts ON gnucash.splits.account_guid = gnucash.accounts.guid WHERE accounts.guid LIKE "f2dd1f1e92cf41f687187d1e73fbc2c9") AND accounts.guid NOT LIKE "f2dd1f1e92cf41f687187d1e73fbc2c9" GROUP BY transactions.enter_date ORDER BY post DESC, nr DESC, enter DESC LIMIT 30; """) rohumsaetze = sqlcursor.fetchall() print(rohumsaetze) ``` this select works on Workbench, **but not** in Python??? ``` SELECT MAX(transactions.num) AS nr , MAX(transactions.enter_date) AS enter, MAX(transactions.post_date) AS post, MAX(transactions.description) AS "beschr", SUM(splits.value_num) AS "Euro" FROM gnucash.splits INNER JOIN gnucash.transactions ON gnucash.splits.tx_guid = gnucash.transactions.guid INNER JOIN gnucash.accounts ON gnucash.splits.account_guid = gnucash.accounts.guid WHERE transactions.guid IN ( SELECT transactions.guid FROM gnucash.splits INNER JOIN gnucash.transactions ON gnucash.splits.tx_guid = gnucash.transactions.guid INNER JOIN gnucash.accounts ON gnucash.splits.account_guid = gnucash.accounts.guid WHERE accounts.guid LIKE "1df66c60180c4f3cb5cc080c1e7d4834") AND accounts.guid NOT LIKE "1df66c60180c4f3cb5cc080c1e7d4834" GROUP BY transactions.enter_date ORDER BY post DESC, nr DESC, enter DESC LIMIT 30; ``` only the "%Sparda%" and "%Commerz%" is the different. On Workbench works fine but i needed python. I have try to make the Statement with root, how [here](https://stackoverflow.com/questions/53751358/stored-procedure-works-on-mysql-workbench-but-not-in-python). But without success. And above all there is no error. How to find the error? Find the error? I have already rewritten the code 3 times. Maybe someone has an idea how to write it differently? That it works. thanks to you
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/2020', '04/12/2020'], 'code': ['ABC', 'ABC', 'XYZ', 'XYZ'], 'quantity': [2, 3, 10, 11], 'price': [1.5, 1.5, 0.2, 0.2], 'value': [3, 4.5, 2, 2.2], 'weight': [.6, .67, .4, .328]} df1 = pd.DataFrame(rawdata) print(df1, '\n') finisheddata = {'portfolio': ['port3', 'port3'], 'portfolioname': ['portfoliothree', 'portfoliothree'], 'date': ['04/12/2020', '04/12/2020'], 'code': ['ABC', 'XYZ'], 'quantity': [5, 21], 'price': [1.5, 0.2], 'value': [7.5, 4.2], 'weight': [.64, .36]} df2 = pd.DataFrame(finisheddata) # Desired print(df2, '\n') df3 = df1.groupby(['code']).agg({'portfolio' : 'first', 'portfolioname' : 'first', 'date' : 'first', 'quantity': 'sum', 'price' : 'first', 'weight': 'mean'}).reset_index() df3['value'] = df3.price * df3.quantity df3 = df3[['portfolio', 'portfolioname', 'date', 'code', 'quantity', 'price', 'value', 'weight']] df3['portfolio'] = df3['portfolioname'] = 'combined' print(df3) ``` Output: ``` portfolio portfolioname date code quantity price value weight 0 port1 portfolioone 04/12/2020 ABC 2 1.5 3.0 0.600 1 port2 portfoliotwo 04/12/2020 ABC 3 1.5 4.5 0.670 2 port1 portfolioone 04/12/2020 XYZ 10 0.2 2.0 0.400 3 port2 portfoliotwo 04/12/2020 XYZ 11 0.2 2.2 0.328 portfolio portfolioname date code quantity price value weight 0 port3 portfoliothree 04/12/2020 ABC 5 1.5 7.5 0.64 1 port3 portfoliothree 04/12/2020 XYZ 21 0.2 4.2 0.36 portfolio portfolioname date code quantity price value weight 0 combined combined 04/12/2020 ABC 5 1.5 7.5 0.635 1 combined combined 04/12/2020 XYZ 21 0.2 4.2 0.364 ```
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 = 'portx' portname = 'portnew' code = cname quant = dfsub.quantity.sum() date = dfsub.date.iloc[0] price = dfsub.price.iloc[0] value = quant * price data.append([port,portname,date,code,quant,price,value]) dfout = pd.DataFrame(data, columns=['portfolio', 'portfolioname', 'date', 'code', 'quantity', 'price', 'value']) sumval = dfout.value.sum() dfout['weight'] = dfout['value'] / sumval ``` the output looks like ``` portfolio portfolioname date code quantity price value weight 0 portx portnew 04/12/2020 ABC 5 1.5 7.5 0.641026 1 portx portnew 04/12/2020 XYZ 21 0.2 4.2 0.358974 ``` If you want to reduce the number of digits in weight then `dfout.round({'weight': 3})` to round it to 3 decimal places
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) AS enter, MAX(transactions.post_date) AS post, MAX(transactions.description) AS "beschr", SUM(splits.value_num) AS "Euro" FROM gnucash.splits INNER JOIN gnucash.transactions ON gnucash.splits.tx_guid = gnucash.transactions.guid INNER JOIN gnucash.accounts ON gnucash.splits.account_guid = gnucash.accounts.guid WHERE transactions.guid IN ( SELECT transactions.guid FROM gnucash.splits INNER JOIN gnucash.transactions ON gnucash.splits.tx_guid = gnucash.transactions.guid INNER JOIN gnucash.accounts ON gnucash.splits.account_guid = gnucash.accounts.guid WHERE accounts.guid LIKE "f2dd1f1e92cf41f687187d1e73fbc2c9") AND accounts.guid NOT LIKE "f2dd1f1e92cf41f687187d1e73fbc2c9" GROUP BY transactions.enter_date ORDER BY post DESC, nr DESC, enter DESC LIMIT 30; """) rohumsaetze = sqlcursor.fetchall() print(rohumsaetze) ``` this select works on Workbench, **but not** in Python??? ``` SELECT MAX(transactions.num) AS nr , MAX(transactions.enter_date) AS enter, MAX(transactions.post_date) AS post, MAX(transactions.description) AS "beschr", SUM(splits.value_num) AS "Euro" FROM gnucash.splits INNER JOIN gnucash.transactions ON gnucash.splits.tx_guid = gnucash.transactions.guid INNER JOIN gnucash.accounts ON gnucash.splits.account_guid = gnucash.accounts.guid WHERE transactions.guid IN ( SELECT transactions.guid FROM gnucash.splits INNER JOIN gnucash.transactions ON gnucash.splits.tx_guid = gnucash.transactions.guid INNER JOIN gnucash.accounts ON gnucash.splits.account_guid = gnucash.accounts.guid WHERE accounts.guid LIKE "1df66c60180c4f3cb5cc080c1e7d4834") AND accounts.guid NOT LIKE "1df66c60180c4f3cb5cc080c1e7d4834" GROUP BY transactions.enter_date ORDER BY post DESC, nr DESC, enter DESC LIMIT 30; ``` only the "%Sparda%" and "%Commerz%" is the different. On Workbench works fine but i needed python. I have try to make the Statement with root, how [here](https://stackoverflow.com/questions/53751358/stored-procedure-works-on-mysql-workbench-but-not-in-python). But without success. And above all there is no error. How to find the error? Find the error? I have already rewritten the code 3 times. Maybe someone has an idea how to write it differently? That it works. thanks to you
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/2020', '04/12/2020'], 'code': ['ABC', 'ABC', 'XYZ', 'XYZ'], 'quantity': [2, 3, 10, 11], 'price': [1.5, 1.5, 0.2, 0.2], 'value': [3, 4.5, 2, 2.2], 'weight': [.6, .67, .4, .328]} df1 = pd.DataFrame(rawdata) print(df1, '\n') finisheddata = {'portfolio': ['port3', 'port3'], 'portfolioname': ['portfoliothree', 'portfoliothree'], 'date': ['04/12/2020', '04/12/2020'], 'code': ['ABC', 'XYZ'], 'quantity': [5, 21], 'price': [1.5, 0.2], 'value': [7.5, 4.2], 'weight': [.64, .36]} df2 = pd.DataFrame(finisheddata) # Desired print(df2, '\n') df3 = df1.groupby(['code']).agg({'portfolio' : 'first', 'portfolioname' : 'first', 'date' : 'first', 'quantity': 'sum', 'price' : 'first', 'weight': 'mean'}).reset_index() df3['value'] = df3.price * df3.quantity df3 = df3[['portfolio', 'portfolioname', 'date', 'code', 'quantity', 'price', 'value', 'weight']] df3['portfolio'] = df3['portfolioname'] = 'combined' print(df3) ``` Output: ``` portfolio portfolioname date code quantity price value weight 0 port1 portfolioone 04/12/2020 ABC 2 1.5 3.0 0.600 1 port2 portfoliotwo 04/12/2020 ABC 3 1.5 4.5 0.670 2 port1 portfolioone 04/12/2020 XYZ 10 0.2 2.0 0.400 3 port2 portfoliotwo 04/12/2020 XYZ 11 0.2 2.2 0.328 portfolio portfolioname date code quantity price value weight 0 port3 portfoliothree 04/12/2020 ABC 5 1.5 7.5 0.64 1 port3 portfoliothree 04/12/2020 XYZ 21 0.2 4.2 0.36 portfolio portfolioname date code quantity price value weight 0 combined combined 04/12/2020 ABC 5 1.5 7.5 0.635 1 combined combined 04/12/2020 XYZ 21 0.2 4.2 0.364 ```
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':'mean'} df1.groupby(['code']).agg(g).reset_index() ``` ``` code portfolio portfolioname date quantity price value weight 0 ABC portx portfoliox 04/12/2020 5 1.5 7.5 0.635 1 XYZ portx portfoliox 04/12/2020 21 0.2 4.2 0.364 ``` My confusion is with the `portx` and `portfoliox`. Right now I have hardcoded those, because you mention they are arbituary. Is there a logic to combining `port1`, `port2` strings that you want to implement during aggregation? Let me know and I can update my answer accordingly. --- **EDIT: Aggregation over the portx and portfoliox** Since I didn't get a response from OP, here is the code for if you want to generate the `portx` and `portfoliox` based on existing values by aggregation - ``` word2int = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'zero' : 0} int2word = {v:k for k,v in word2int.items()} g = {'portfolio':lambda x: 'port'+str(sum([int(i[-1]) for i in x])), 'portfolioname':lambda x: 'portfolio'+int2word.get(sum([word2int.get(i[9:]) for i in x])), 'date':'first', 'quantity':'sum', 'price':'mean', 'value':'sum', 'weight':'mean'} df1.groupby(['code']).agg(g).reset_index() ``` ``` code portfolio portfolioname date quantity price value weight 0 ABC port3 portfoliothree 04/12/2020 5 1.5 7.5 0.635 1 XYZ port3 portfoliothree 04/12/2020 21 0.2 4.2 0.364 ```
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. ``` I'm on Windows 10 Home 64x. I've already tried ``` pip install pypiwin32 ``` And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I `import django`, so I think it's a win32api issue only. ``` >>> import win32api ``` I expect the output to be none, but the actual output is always that error ^^
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. ``` I'm on Windows 10 Home 64x. I've already tried ``` pip install pypiwin32 ``` And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I `import django`, so I think it's a win32api issue only. ``` >>> import win32api ``` I expect the output to be none, but the actual output is always that error ^^
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 `pythoncom38.dll` and `pywintypes38.dll` (it means my Python version is 3.8). 3. Downgrading the version of pywin32 to 225 or lower by this command: `pip install pywin32==225`.
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. ``` I'm on Windows 10 Home 64x. I've already tried ``` pip install pypiwin32 ``` And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I `import django`, so I think it's a win32api issue only. ``` >>> import win32api ``` I expect the output to be none, but the actual output is always that error ^^
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. ``` I'm on Windows 10 Home 64x. I've already tried ``` pip install pypiwin32 ``` And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I `import django`, so I think it's a win32api issue only. ``` >>> import win32api ``` I expect the output to be none, but the actual output is always that error ^^
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. ``` I'm on Windows 10 Home 64x. I've already tried ``` pip install pypiwin32 ``` And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I `import django`, so I think it's a win32api issue only. ``` >>> import win32api ``` I expect the output to be none, but the actual output is always that error ^^
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. ``` I'm on Windows 10 Home 64x. I've already tried ``` pip install pypiwin32 ``` And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I `import django`, so I think it's a win32api issue only. ``` >>> import win32api ``` I expect the output to be none, but the actual output is always that error ^^
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. pip install pywin32 3. python [environment path]/Scripts/pywin32\_postinstall.py -install
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. ``` I'm on Windows 10 Home 64x. I've already tried ``` pip install pypiwin32 ``` And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I `import django`, so I think it's a win32api issue only. ``` >>> import win32api ``` I expect the output to be none, but the actual output is always that error ^^
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 `pythoncom38.dll` and `pywintypes38.dll` (it means my Python version is 3.8). 3. Downgrading the version of pywin32 to 225 or lower by this command: `pip install pywin32==225`.
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. ``` I'm on Windows 10 Home 64x. I've already tried ``` pip install pypiwin32 ``` And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I `import django`, so I think it's a win32api issue only. ``` >>> import win32api ``` I expect the output to be none, but the actual output is always that error ^^
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. pip install pywin32 3. python [environment path]/Scripts/pywin32\_postinstall.py -install
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. ``` I'm on Windows 10 Home 64x. I've already tried ``` pip install pypiwin32 ``` And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I `import django`, so I think it's a win32api issue only. ``` >>> import win32api ``` I expect the output to be none, but the actual output is always that error ^^
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 folder where the global python is located. For example, I use conda to create a virtual environment called `Frameless-Window`, and install the package `pywin32` in this virtual environment, then the `{python folder path}` on my computer should be `D:/Anaconda/envs/Frameless-Window`. You should be very careful when copying the dll to the System32 folder. if there are dlls with the same name in the folder and pywin32 in your other virtual environment may use these two dlls, replacing the original dlls may cause this virtual environment had the same ImportError problem. After testing, I found that the dlls of pywin32 of version 227, 228 and 300 can be replaced with each other, and the dlls of pywin32 of versions 301, 302, 303 and 304 can also be replaced with each other, but if the dll of version 300 is replaced with the dll of version 301, it will raise ImportError.
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. ``` I'm on Windows 10 Home 64x. I've already tried ``` pip install pypiwin32 ``` And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I `import django`, so I think it's a win32api issue only. ``` >>> import win32api ``` I expect the output to be none, but the actual output is always that error ^^
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, works if pip install or conda install is used** * `cd C:\Users\[USER]\anaconda3\envs\[ENVIRONMENT]\Scripts` **Run the post install script that was added when installing PyWin32** * `python pywin32_postinstall.py -install`
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 pressed, is made non-visible. The visibility is remembered no matter how many items in the list or how much you scroll. ``` public class TestAdapter extends RecyclerView.Adapter<TestAdapter.VH> { public static class MyData { public boolean ButtonVisible = true; public String Text; public MyData(String text) { Text = text; } } public List<MyData> items = new ArrayList<>(); public TestAdapter() { this.items.add(new MyData("Item 1")); this.items.add(new MyData("Item 2")); this.items.add(new MyData("Item 3")); } @Override public TestAdapter.VH onCreateViewHolder(ViewGroup parent, int viewType) { return new VH(( LayoutInflater.from(parent.getContext()) .inflate(R.layout.test_layout, parent, false)) ); } @Override public void onBindViewHolder(TestAdapter.VH holder, final int position) { final MyData itm = items.get(position); holder.button.setVisibility(itm.ButtonVisible ? View.VISIBLE : View.GONE); holder.text.setText(itm.Text); holder.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { itm.ButtonVisible = false; notifyItemChanged(position); } }); } @Override public int getItemCount() { return items.size(); } public class VH extends RecyclerView.ViewHolder { Button button; TextView text; public VH(View itemView) { super(itemView); button = itemView.findViewById(R.id.toggle); text = itemView.findViewById(R.id.text1); } } } ``` test\_layout.xml ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:id="@+id/text1" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> ```
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.message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(visibilityList.get(position)){ visibilityList.set(position, false); holder.button.setVisibility(View.GONE); }else{ visibilityList.set(position, true); holder.button.setVisibility(View.VISIBLE); } } }); } ``` **Note:** visibilityList is the List variable where each value is set to default (either true or false as per your requirement)
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 pressed, is made non-visible. The visibility is remembered no matter how many items in the list or how much you scroll. ``` public class TestAdapter extends RecyclerView.Adapter<TestAdapter.VH> { public static class MyData { public boolean ButtonVisible = true; public String Text; public MyData(String text) { Text = text; } } public List<MyData> items = new ArrayList<>(); public TestAdapter() { this.items.add(new MyData("Item 1")); this.items.add(new MyData("Item 2")); this.items.add(new MyData("Item 3")); } @Override public TestAdapter.VH onCreateViewHolder(ViewGroup parent, int viewType) { return new VH(( LayoutInflater.from(parent.getContext()) .inflate(R.layout.test_layout, parent, false)) ); } @Override public void onBindViewHolder(TestAdapter.VH holder, final int position) { final MyData itm = items.get(position); holder.button.setVisibility(itm.ButtonVisible ? View.VISIBLE : View.GONE); holder.text.setText(itm.Text); holder.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { itm.ButtonVisible = false; notifyItemChanged(position); } }); } @Override public int getItemCount() { return items.size(); } public class VH extends RecyclerView.ViewHolder { Button button; TextView text; public VH(View itemView) { super(itemView); button = itemView.findViewById(R.id.toggle); text = itemView.findViewById(R.id.text1); } } } ``` test\_layout.xml ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:id="@+id/text1" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> ```
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 misbehave due to reusability.
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 to switch a tick box to publish/unpublish but now I can’t even access the Dashboard. Here is part of the traceback from my Django server: ``` File "/home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: essays_essayarticle.is_published ``` The debug traceback reinforces the OperationalError above: ``` OperationalError at /admin/essays/essayarticle/ no such column: essays_essayarticle.is_published Request Method: GET Request URL: http://<DN>.ngrok.io/admin/essays/essayarticle/ Django Version:2.2.11 Exception Type: OperationalError Exception Value: no such column: essays_essayarticle.is_published Exception Location: /home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/bin/python `Fri, 1 May 2020 19:37:31 +0000 ``` Exception Value indicates ‘no such column’ which is a reference to my db. I’m running SQlite3 for test purposes. Prior to this OperationalError, I was troubleshooting issues with a DummyNode and "isinstance django.db.migrations.exceptions.NodeNotFoundError: Migration". The previous solution I arrived at was to delete my migrations in two of my apps. This SO answer is the particular solution that resolved the issue: <https://stackoverflow.com/a/56195727/6095646> As per **@Laila Buabbas**'s suggestion, to clarify, I deleted my migrations directory and invoked: `python manage.py makemigrations app_name` for each of my two apps. So that previous SQLite issue has been resolved. But I can’t figure out this new OperationalError, described above. Is the issue is with my views.py / models.py (copied below)? I can't narrow it down any more specific than that. Here is part of the class defined in my app’s models.py (with the new potential problem line added at the end): ``` class EssayArticle(models.Model): title = models.CharField(max_length=256) web_address = models.CharField(max_length=256) web_address_slug = models.SlugField(blank=True, max_length=512) content = models.TextField(blank=True) is_published = models.BooleanField(default=True) ``` Here are the relevant lines from the applicable function in my views.py: ``` def article(request, web_address): try: article = EssayArticle.objects.get( web_address_slug=web_address) # .filter(is_published=True) except EssayArticle.DoesNotExist: raise Http404('Article does not exist!') context = { 'article': article, } return render(request, 'essays/article.html', context) ``` Commenting in our out the `.filter(is_published=True)` doesn't stop or change the debug error. My local dev box is Manjaro Linux with Django v2.2.11. I’m running Python v3.8.2. Here are some of the resources I have already leveraged: * [Improve INSERT-per-second performance of SQLite](https://stackoverflow.com/questions/1711631/improve-insert-per-second-performance-of-sqlite) * [Django OperationalError: no such column: on pythonanywhere](https://stackoverflow.com/questions/53863318/django-operationalerror-no-such-column-on-pythonanywhere) * [Django 1.8 OperationalError: no such column:](https://stackoverflow.com/questions/31842149/django-1-8-operationalerror-no-such-column) * [Django tutorial01 OperationalError: no such column: polls\_choice.question\_text\_id](https://stackoverflow.com/questions/20451706/django-tutorial01-operationalerror-no-such-column-polls-choice-question-text-i)
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 to switch a tick box to publish/unpublish but now I can’t even access the Dashboard. Here is part of the traceback from my Django server: ``` File "/home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: essays_essayarticle.is_published ``` The debug traceback reinforces the OperationalError above: ``` OperationalError at /admin/essays/essayarticle/ no such column: essays_essayarticle.is_published Request Method: GET Request URL: http://<DN>.ngrok.io/admin/essays/essayarticle/ Django Version:2.2.11 Exception Type: OperationalError Exception Value: no such column: essays_essayarticle.is_published Exception Location: /home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/bin/python `Fri, 1 May 2020 19:37:31 +0000 ``` Exception Value indicates ‘no such column’ which is a reference to my db. I’m running SQlite3 for test purposes. Prior to this OperationalError, I was troubleshooting issues with a DummyNode and "isinstance django.db.migrations.exceptions.NodeNotFoundError: Migration". The previous solution I arrived at was to delete my migrations in two of my apps. This SO answer is the particular solution that resolved the issue: <https://stackoverflow.com/a/56195727/6095646> As per **@Laila Buabbas**'s suggestion, to clarify, I deleted my migrations directory and invoked: `python manage.py makemigrations app_name` for each of my two apps. So that previous SQLite issue has been resolved. But I can’t figure out this new OperationalError, described above. Is the issue is with my views.py / models.py (copied below)? I can't narrow it down any more specific than that. Here is part of the class defined in my app’s models.py (with the new potential problem line added at the end): ``` class EssayArticle(models.Model): title = models.CharField(max_length=256) web_address = models.CharField(max_length=256) web_address_slug = models.SlugField(blank=True, max_length=512) content = models.TextField(blank=True) is_published = models.BooleanField(default=True) ``` Here are the relevant lines from the applicable function in my views.py: ``` def article(request, web_address): try: article = EssayArticle.objects.get( web_address_slug=web_address) # .filter(is_published=True) except EssayArticle.DoesNotExist: raise Http404('Article does not exist!') context = { 'article': article, } return render(request, 'essays/article.html', context) ``` Commenting in our out the `.filter(is_published=True)` doesn't stop or change the debug error. My local dev box is Manjaro Linux with Django v2.2.11. I’m running Python v3.8.2. Here are some of the resources I have already leveraged: * [Improve INSERT-per-second performance of SQLite](https://stackoverflow.com/questions/1711631/improve-insert-per-second-performance-of-sqlite) * [Django OperationalError: no such column: on pythonanywhere](https://stackoverflow.com/questions/53863318/django-operationalerror-no-such-column-on-pythonanywhere) * [Django 1.8 OperationalError: no such column:](https://stackoverflow.com/questions/31842149/django-1-8-operationalerror-no-such-column) * [Django tutorial01 OperationalError: no such column: polls\_choice.question\_text\_id](https://stackoverflow.com/questions/20451706/django-tutorial01-operationalerror-no-such-column-polls-choice-question-text-i)
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 find the issue/error you are getting Once you delete the migration from `django_migrations` in database,Run the migration ``` ./manage.py migrate ``` then might your problem get solved
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 to switch a tick box to publish/unpublish but now I can’t even access the Dashboard. Here is part of the traceback from my Django server: ``` File "/home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: essays_essayarticle.is_published ``` The debug traceback reinforces the OperationalError above: ``` OperationalError at /admin/essays/essayarticle/ no such column: essays_essayarticle.is_published Request Method: GET Request URL: http://<DN>.ngrok.io/admin/essays/essayarticle/ Django Version:2.2.11 Exception Type: OperationalError Exception Value: no such column: essays_essayarticle.is_published Exception Location: /home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/bin/python `Fri, 1 May 2020 19:37:31 +0000 ``` Exception Value indicates ‘no such column’ which is a reference to my db. I’m running SQlite3 for test purposes. Prior to this OperationalError, I was troubleshooting issues with a DummyNode and "isinstance django.db.migrations.exceptions.NodeNotFoundError: Migration". The previous solution I arrived at was to delete my migrations in two of my apps. This SO answer is the particular solution that resolved the issue: <https://stackoverflow.com/a/56195727/6095646> As per **@Laila Buabbas**'s suggestion, to clarify, I deleted my migrations directory and invoked: `python manage.py makemigrations app_name` for each of my two apps. So that previous SQLite issue has been resolved. But I can’t figure out this new OperationalError, described above. Is the issue is with my views.py / models.py (copied below)? I can't narrow it down any more specific than that. Here is part of the class defined in my app’s models.py (with the new potential problem line added at the end): ``` class EssayArticle(models.Model): title = models.CharField(max_length=256) web_address = models.CharField(max_length=256) web_address_slug = models.SlugField(blank=True, max_length=512) content = models.TextField(blank=True) is_published = models.BooleanField(default=True) ``` Here are the relevant lines from the applicable function in my views.py: ``` def article(request, web_address): try: article = EssayArticle.objects.get( web_address_slug=web_address) # .filter(is_published=True) except EssayArticle.DoesNotExist: raise Http404('Article does not exist!') context = { 'article': article, } return render(request, 'essays/article.html', context) ``` Commenting in our out the `.filter(is_published=True)` doesn't stop or change the debug error. My local dev box is Manjaro Linux with Django v2.2.11. I’m running Python v3.8.2. Here are some of the resources I have already leveraged: * [Improve INSERT-per-second performance of SQLite](https://stackoverflow.com/questions/1711631/improve-insert-per-second-performance-of-sqlite) * [Django OperationalError: no such column: on pythonanywhere](https://stackoverflow.com/questions/53863318/django-operationalerror-no-such-column-on-pythonanywhere) * [Django 1.8 OperationalError: no such column:](https://stackoverflow.com/questions/31842149/django-1-8-operationalerror-no-such-column) * [Django tutorial01 OperationalError: no such column: polls\_choice.question\_text\_id](https://stackoverflow.com/questions/20451706/django-tutorial01-operationalerror-no-such-column-polls-choice-question-text-i)
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 find the issue/error you are getting Once you delete the migration from `django_migrations` in database,Run the migration ``` ./manage.py migrate ``` then might your problem get solved
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 is up before, the programm runs smoothly. I tested "ifup eth0" from the command line manually for both cases and its lightning fast. If you have any idea what the Problem might be, I would appreciate it very much. Thanks in advance **EDIT:** Based on the answers, I tried the following things: ``` p = subprocess.Popen(["ifup", "eth0"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() ``` If the interface was up before, the skript runs smoothly. However if the interface was down, python hangs again. I also tried: ``` p = subprocess.Popen(["ifup", "eth0"], shell=False) out, err = p.communicate() ``` And EVERYTHING runs perfektly fast. Therefore it might be indeed related to a deadlock, as pointed out funktku. However the python documentation also says [python ref](http://docs.python.org/library/subprocess.html#subprocess.Popen.wait): > > Warning > > > This will deadlock when using > stdout=PIPE and/or stderr=PIPE and the > child process generates enough output > to a pipe such that it blocks waiting > for the OS pipe buffer to accept more > data. Use communicate() to avoid that. > > > Therefore there shouldn't be a deadlock. Hmm... Here is the detailed output when I run the programms on the command line: 1 Case, interface eth0 already up: ``` ifup eth0 Interface eth0 already configured ``` 2 Case, interface down before: ``` ifup eth0 ssh stop/waiting ssh start/running ``` So the ifup command generates two lines of ouput in case the interface is down before and one line of ouput otherwise. This is the only difference I noticed. But I doubt this is the cause of the problem, since "ls -ahl" causes many more lines of ouput and is running very well. I also tried playing around with the buffersize argument, however no success, by setting it to some large value like 4096. Do you have an ideas, what might be the cause of that? Or is this probably a bug in python Pipe handling or the ifup command itself? Do I really have to use the old os.popen(cmd).read()???? **EDIT2:** os.popen(cmd).read() suffers from the same problem. Any idea of how I can test the pipe behaviour of ifup on the commandline? I appreciate every hint, thanks in advance
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 enough output to a pipe such > that it blocks waiting for the OS pipe > buffer to accept more data. > > >
``` 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 is up before, the programm runs smoothly. I tested "ifup eth0" from the command line manually for both cases and its lightning fast. If you have any idea what the Problem might be, I would appreciate it very much. Thanks in advance **EDIT:** Based on the answers, I tried the following things: ``` p = subprocess.Popen(["ifup", "eth0"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() ``` If the interface was up before, the skript runs smoothly. However if the interface was down, python hangs again. I also tried: ``` p = subprocess.Popen(["ifup", "eth0"], shell=False) out, err = p.communicate() ``` And EVERYTHING runs perfektly fast. Therefore it might be indeed related to a deadlock, as pointed out funktku. However the python documentation also says [python ref](http://docs.python.org/library/subprocess.html#subprocess.Popen.wait): > > Warning > > > This will deadlock when using > stdout=PIPE and/or stderr=PIPE and the > child process generates enough output > to a pipe such that it blocks waiting > for the OS pipe buffer to accept more > data. Use communicate() to avoid that. > > > Therefore there shouldn't be a deadlock. Hmm... Here is the detailed output when I run the programms on the command line: 1 Case, interface eth0 already up: ``` ifup eth0 Interface eth0 already configured ``` 2 Case, interface down before: ``` ifup eth0 ssh stop/waiting ssh start/running ``` So the ifup command generates two lines of ouput in case the interface is down before and one line of ouput otherwise. This is the only difference I noticed. But I doubt this is the cause of the problem, since "ls -ahl" causes many more lines of ouput and is running very well. I also tried playing around with the buffersize argument, however no success, by setting it to some large value like 4096. Do you have an ideas, what might be the cause of that? Or is this probably a bug in python Pipe handling or the ifup command itself? Do I really have to use the old os.popen(cmd).read()???? **EDIT2:** os.popen(cmd).read() suffers from the same problem. Any idea of how I can test the pipe behaviour of ifup on the commandline? I appreciate every hint, thanks in advance
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 how can I pass `key`, `api_token` and `after`? What is `-F` flag and how to use it in python requests?
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 how can I pass `key`, `api_token` and `after`? What is `-F` flag and how to use it in python requests?
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:]: grades.append(float(grade)) with open('C:/Users/sina/Desktop/python pt/jalase20.csv' , 'w') as fw: fw.write("name , mean(grades)\n") ```
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') as fo: reader = csv.reader(fo) for row in reader : name = row[0] grades = list() for grade in row[1:]: grades.append(float(grade)) with open('C:/Users/sina/Desktop/python pt/jalase20.csv' , 'w') as fw: fw.write("name , mean(grades)\n") ``` Also i think you meant **fw** instead of **f2**
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 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:]: grades.append(float(grade)) with open('C:/Users/sina/Desktop/python pt/jalase20.csv' , 'w') as f2: f2.write("name , mean(grades)\n") ```
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:\\python27\\invia' os.chdir(sb) #path dirs =os.listdir(sb) #list of file print dirs for file in dirs: f=open(file, "rb") #read image l = f.read() s.send(file) #send the name of the file st = os.stat(sb+'\\'+file).st_size print str(st) s.send(str(st)) #send the size of the file s.send(l) #send data of the file f.close() s.close() ``` SERVER ====== ``` import socket import sys import os s = socket.socket() s.bind(("localhost",9999)) s.listen(4) #number of people than can connect it sc, address = s.accept() print address sb = 'c:\\python27\\ricevi' os.chdir(sb) while True: fln=sc.recv(5) #read the name of the file print fln f = open(fln,'wb') #create the new file size = sc.recv(7) #receive the size of the file #size=size[:7] print size strng = sc.recv(int(size)) #receive the data of the file #if strng: f.write(strng) #write the file f.close() sc.close() s.close() ```
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, however both sender and receiver must agree on a protocol. You have the following in your sender: ``` s.send(file) #send the name of the file st = os.stat(sb+'\\'+file).st_size s.send(str(st)) #send the size of the file s.send(l) ``` How is the receiver to know how long the file name is? Or, how will the receiver know where the end of the file name is, and where the size of the file starts? You could imagine the receiver obtaining a string like `foobar.txt8somedata` and having to infer that the name of the file is `foobar.txt`, the file is 8 bytes long containing the data `somedata`. What you need to do is separate the data with some kind of delimeter such as `\n` to indicate the boundary for each piece of metadata. You could envisage a packet structure as `<filename>\n<file_size>\n<file_contents>`. An example stream of data from the transmitter may then look like this: ``` foobar.txt\n8\nsomedata ``` The receiver would then decode the incoming stream, looking for `\n` in the input to determine each field's value such as the file name and size. Another approach would be to allocate fixed length strings for the file name and size, followed by the file's data.
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, specially if `size` is rather large. You need to read from the socket in a loop until you have actually read `size` bytes to make it work.
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','width') Screen_height = config.getint('graphics','height') ``` The main method in this file is called in the launcher for the game. I've tested that out and that works perfectly. When I run this code, I get this error: ``` Traceback (most recent call last): File "Scripts\Launcher.py", line 71, in <module> Game.main() File "C:\Users\astro_000\Desktop\Mini-Golf\Scripts\Game.py", line 8, in main Screen_width = config.getint('graphics','width') File "c:\python27\lib\ConfigParser.py", line 359, in getint return self._get(section, int, option) File "c:\python27\lib\ConfigParser.py", line 356, in _get return conv(self.get(section, option)) File "c:\python27\lib\ConfigParser.py", line 607, in get raise NoSectionError(section) ConfigParser.NoSectionError: No section: 'graphics' ``` The thing is, there is a section 'graphics'. The file I'm trying to read from looks like this: ``` [graphics] height = 600 width = 800 ``` I have verified that it is, in fact called options.cfg. config.sections() returns only this: "[]" I've had this work before using this same code, but it wont work now. Any help would be greatly appreciated.
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() parser.read(filename) print(parser.sections()) screen_width = parser.getint('graphics','width') screen_height = parser.getint('graphics','height') else: print("Config file not found") if __name__=="__main__": main() ```
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 there is a file called `options.cfg` and specify the full path if needed, as I already commented. Parser will fail silently if there is no file found.
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','width') Screen_height = config.getint('graphics','height') ``` The main method in this file is called in the launcher for the game. I've tested that out and that works perfectly. When I run this code, I get this error: ``` Traceback (most recent call last): File "Scripts\Launcher.py", line 71, in <module> Game.main() File "C:\Users\astro_000\Desktop\Mini-Golf\Scripts\Game.py", line 8, in main Screen_width = config.getint('graphics','width') File "c:\python27\lib\ConfigParser.py", line 359, in getint return self._get(section, int, option) File "c:\python27\lib\ConfigParser.py", line 356, in _get return conv(self.get(section, option)) File "c:\python27\lib\ConfigParser.py", line 607, in get raise NoSectionError(section) ConfigParser.NoSectionError: No section: 'graphics' ``` The thing is, there is a section 'graphics'. The file I'm trying to read from looks like this: ``` [graphics] height = 600 width = 800 ``` I have verified that it is, in fact called options.cfg. config.sections() returns only this: "[]" I've had this work before using this same code, but it wont work now. Any help would be greatly appreciated.
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 there is a file called `options.cfg` and specify the full path if needed, as I already commented. Parser will fail silently if there is no file found.
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 > > > Resolution: provide the full path of the file and put debug statements correctly to identify the issue. Below is my code. Hope it helps: ``` from configparser import ConfigParser import os def get_connection_by_config(filename='database.ini',section='postgresql_conn_config'): ''' This method will use the connection data saved in configuration file to get postgresql database server connection. filename : Is the configuration file saved path, the configuration file is database.ini in this example, and it is saved in the same path of PostgresqlManager.py file. section_name : This is the section name in above configuration file. The options in this section record the postgresql database server connection info. ''' # create a parser parser = ConfigParser() # define the file path loc = '/src/data_engineering/' cwd = os.path.abspath(os.getcwd()).replace('\\', '/') path = cwd+loc filename_ = path+filename db = {} #check file path if os.path.isfile(filename_): # read config file parser.read(filename_) # get section if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) else: raise Exception("File {} not found in location".format(filename_)) return db ```
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','width') Screen_height = config.getint('graphics','height') ``` The main method in this file is called in the launcher for the game. I've tested that out and that works perfectly. When I run this code, I get this error: ``` Traceback (most recent call last): File "Scripts\Launcher.py", line 71, in <module> Game.main() File "C:\Users\astro_000\Desktop\Mini-Golf\Scripts\Game.py", line 8, in main Screen_width = config.getint('graphics','width') File "c:\python27\lib\ConfigParser.py", line 359, in getint return self._get(section, int, option) File "c:\python27\lib\ConfigParser.py", line 356, in _get return conv(self.get(section, option)) File "c:\python27\lib\ConfigParser.py", line 607, in get raise NoSectionError(section) ConfigParser.NoSectionError: No section: 'graphics' ``` The thing is, there is a section 'graphics'. The file I'm trying to read from looks like this: ``` [graphics] height = 600 width = 800 ``` I have verified that it is, in fact called options.cfg. config.sections() returns only this: "[]" I've had this work before using this same code, but it wont work now. Any help would be greatly appreciated.
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() parser.read(filename) print(parser.sections()) screen_width = parser.getint('graphics','width') screen_height = parser.getint('graphics','height') else: print("Config file not found") if __name__=="__main__": main() ```
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 > > > Resolution: provide the full path of the file and put debug statements correctly to identify the issue. Below is my code. Hope it helps: ``` from configparser import ConfigParser import os def get_connection_by_config(filename='database.ini',section='postgresql_conn_config'): ''' This method will use the connection data saved in configuration file to get postgresql database server connection. filename : Is the configuration file saved path, the configuration file is database.ini in this example, and it is saved in the same path of PostgresqlManager.py file. section_name : This is the section name in above configuration file. The options in this section record the postgresql database server connection info. ''' # create a parser parser = ConfigParser() # define the file path loc = '/src/data_engineering/' cwd = os.path.abspath(os.getcwd()).replace('\\', '/') path = cwd+loc filename_ = path+filename db = {} #check file path if os.path.isfile(filename_): # read config file parser.read(filename_) # get section if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) else: raise Exception("File {} not found in location".format(filename_)) return db ```
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_resolver.nameservers = ['1.1.1.1', '1.0.0.1'] resolve_count = 0 def get_spf_count(domain_name): global 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 = [ record for record in spf.replace('" "', '').replace('"', '').split() if record not in ['v=spf1', '~all', '-all', '+all', '?all'] ] for record in spf_records: if 'include:' in record: check_domain = record.split(':')[1] get_spf_count(check_domain) resolve_count += 1 elif record.startswith(('a:', 'mx:', 'ptr:', 'exists:')): resolve_count += 1 get_spf_count('google.com') print(resolve_count) ```
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 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 = [ record for record in spf.replace('" "', '').replace('"', '').split() if record not in ['v=spf1', '~all', '-all', '+all', '?all'] ] for record in spf_records: if 'include:' in record: check_domain = record.split(':')[1] resolve_count += 1 + get_spf_count(check_domain, dns_resolver) elif record.startswith(('a:', 'mx:', 'ptr:', 'exists:')): resolve_count += 1 return resolve_count print(get_spf_count('google.com')) ``` Notice how everything the function needs is local within the function, including the `dns.resolver.Resolver()` object (and how you could pass in a shared resolver object if you wanted to).
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 = [ record for record in spf.replace('" "', '').replace('"', '').split() if record not in ['v=spf1', '~all', '-all', '+all', '?all'] ] for record in spf_records: if 'include:' in record: check_domain = record.split(':')[1] get_spf_count(check_domain, resolve_count) resolve_count += 1 elif record.startswith(('a:', 'mx:', 'ptr:', 'exists:')): resolve_count += 1 return resolve_count resolve_count = get_spf_count('google.com', 0) print(resolve_count) ```
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_objects(convert_numeric=True) #Building Logistic model_LSVC print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) print("y values:",y.head()) logit = sm.Logit(y,X,missing='drop') ``` The error that appears: ``` Shape of y: (9018,) &&Shape of X_selected_lsvc: (9018, 59) y values: 0 0 1 1 2 0 3 0 4 0 Name: mort, dtype: int64 ValueError Traceback (most recent call last) <ipython-input-8-fec746e2ee99> in <module>() 160 print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) 161 print("y values:",y.head()) --> 162 logit = sm.Logit(y,X,missing='drop') 163 # fit the model 164 est = logit.fit(method='cg') D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 399 400 def __init__(self, endog, exog, **kwargs): --> 401 super(BinaryModel, self).__init__(endog, exog, **kwargs) 402 if (self.__class__.__name__ != 'MNLogit' and 403 not np.all((self.endog >= 0) & (self.endog <= 1))): D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 152 """ 153 def __init__(self, endog, exog, **kwargs): --> 154 super(DiscreteModel, self).__init__(endog, exog, **kwargs) 155 self.raise_on_perfect_prediction = True 156 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 184 185 def __init__(self, endog, exog=None, **kwargs): --> 186 super(LikelihoodModel, self).__init__(endog, exog, **kwargs) 187 self.initialize() 188 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 58 hasconst = kwargs.pop('hasconst', None) 59 self.data = self._handle_data(endog, exog, missing, hasconst, ---> 60 **kwargs) 61 self.k_constant = self.data.k_constant 62 self.exog = self.data.exog D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs) 82 83 def _handle_data(self, endog, exog, missing, hasconst, **kwargs): ---> 84 data = handle_data(endog, exog, missing, hasconst, **kwargs) 85 # kwargs arrays could have changed, easier to just attach here 86 for key in kwargs: D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in handle_data(endog, exog, missing, hasconst, **kwargs) 564 klass = handle_data_class_factory(endog, exog) 565 return klass(endog, exog=exog, missing=missing, hasconst=hasconst, --> 566 **kwargs) D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in __init__(self, endog, exog, missing, hasconst, **kwargs) 74 # this has side-effects, attaches k_constant and const_idx 75 self._handle_constant(hasconst) ---> 76 self._check_integrity() 77 self._cache = resettable_cache() 78 D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in _check_integrity(self) 450 (hasattr(endog, 'index') and hasattr(exog, 'index')) and 451 not self.orig_endog.index.equals(self.orig_exog.index)): --> 452 raise ValueError("The indices for endog and exog are not aligned") 453 super(PandasData, self)._check_integrity() 454 ValueError: The indices for endog and exog are not aligned ``` The y matrix and X matrix have shape of (9018,),(9018, 59). Therefore any mismatch in dependent and independent variables doesn't appear. Any idea?
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=100 ) ```
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 `dataframe.reset_index(drop = True)` before separating `x` and `y`.
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_objects(convert_numeric=True) #Building Logistic model_LSVC print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) print("y values:",y.head()) logit = sm.Logit(y,X,missing='drop') ``` The error that appears: ``` Shape of y: (9018,) &&Shape of X_selected_lsvc: (9018, 59) y values: 0 0 1 1 2 0 3 0 4 0 Name: mort, dtype: int64 ValueError Traceback (most recent call last) <ipython-input-8-fec746e2ee99> in <module>() 160 print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) 161 print("y values:",y.head()) --> 162 logit = sm.Logit(y,X,missing='drop') 163 # fit the model 164 est = logit.fit(method='cg') D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 399 400 def __init__(self, endog, exog, **kwargs): --> 401 super(BinaryModel, self).__init__(endog, exog, **kwargs) 402 if (self.__class__.__name__ != 'MNLogit' and 403 not np.all((self.endog >= 0) & (self.endog <= 1))): D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 152 """ 153 def __init__(self, endog, exog, **kwargs): --> 154 super(DiscreteModel, self).__init__(endog, exog, **kwargs) 155 self.raise_on_perfect_prediction = True 156 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 184 185 def __init__(self, endog, exog=None, **kwargs): --> 186 super(LikelihoodModel, self).__init__(endog, exog, **kwargs) 187 self.initialize() 188 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 58 hasconst = kwargs.pop('hasconst', None) 59 self.data = self._handle_data(endog, exog, missing, hasconst, ---> 60 **kwargs) 61 self.k_constant = self.data.k_constant 62 self.exog = self.data.exog D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs) 82 83 def _handle_data(self, endog, exog, missing, hasconst, **kwargs): ---> 84 data = handle_data(endog, exog, missing, hasconst, **kwargs) 85 # kwargs arrays could have changed, easier to just attach here 86 for key in kwargs: D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in handle_data(endog, exog, missing, hasconst, **kwargs) 564 klass = handle_data_class_factory(endog, exog) 565 return klass(endog, exog=exog, missing=missing, hasconst=hasconst, --> 566 **kwargs) D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in __init__(self, endog, exog, missing, hasconst, **kwargs) 74 # this has side-effects, attaches k_constant and const_idx 75 self._handle_constant(hasconst) ---> 76 self._check_integrity() 77 self._cache = resettable_cache() 78 D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in _check_integrity(self) 450 (hasattr(endog, 'index') and hasattr(exog, 'index')) and 451 not self.orig_endog.index.equals(self.orig_exog.index)): --> 452 raise ValueError("The indices for endog and exog are not aligned") 453 super(PandasData, self)._check_integrity() 454 ValueError: The indices for endog and exog are not aligned ``` The y matrix and X matrix have shape of (9018,),(9018, 59). Therefore any mismatch in dependent and independent variables doesn't appear. Any idea?
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 as 1 but rows as unknown i.e. we got a single column with as many rows as X. Lets take a example:- ``` z = np.array([[1, 2], [ 3, 4]]) print(z.shape) # (2, 2) ``` Now we will use reshape(-1,1) function on this array. We can see new array has 4 row and 1 column. ``` new_z= z.reshape(-1,1) print(new_z) #array([[1],[2],[3], [4]]) print(new_z.shape) #(4, 1) ```
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_objects(convert_numeric=True) #Building Logistic model_LSVC print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) print("y values:",y.head()) logit = sm.Logit(y,X,missing='drop') ``` The error that appears: ``` Shape of y: (9018,) &&Shape of X_selected_lsvc: (9018, 59) y values: 0 0 1 1 2 0 3 0 4 0 Name: mort, dtype: int64 ValueError Traceback (most recent call last) <ipython-input-8-fec746e2ee99> in <module>() 160 print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) 161 print("y values:",y.head()) --> 162 logit = sm.Logit(y,X,missing='drop') 163 # fit the model 164 est = logit.fit(method='cg') D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 399 400 def __init__(self, endog, exog, **kwargs): --> 401 super(BinaryModel, self).__init__(endog, exog, **kwargs) 402 if (self.__class__.__name__ != 'MNLogit' and 403 not np.all((self.endog >= 0) & (self.endog <= 1))): D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 152 """ 153 def __init__(self, endog, exog, **kwargs): --> 154 super(DiscreteModel, self).__init__(endog, exog, **kwargs) 155 self.raise_on_perfect_prediction = True 156 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 184 185 def __init__(self, endog, exog=None, **kwargs): --> 186 super(LikelihoodModel, self).__init__(endog, exog, **kwargs) 187 self.initialize() 188 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 58 hasconst = kwargs.pop('hasconst', None) 59 self.data = self._handle_data(endog, exog, missing, hasconst, ---> 60 **kwargs) 61 self.k_constant = self.data.k_constant 62 self.exog = self.data.exog D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs) 82 83 def _handle_data(self, endog, exog, missing, hasconst, **kwargs): ---> 84 data = handle_data(endog, exog, missing, hasconst, **kwargs) 85 # kwargs arrays could have changed, easier to just attach here 86 for key in kwargs: D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in handle_data(endog, exog, missing, hasconst, **kwargs) 564 klass = handle_data_class_factory(endog, exog) 565 return klass(endog, exog=exog, missing=missing, hasconst=hasconst, --> 566 **kwargs) D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in __init__(self, endog, exog, missing, hasconst, **kwargs) 74 # this has side-effects, attaches k_constant and const_idx 75 self._handle_constant(hasconst) ---> 76 self._check_integrity() 77 self._cache = resettable_cache() 78 D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in _check_integrity(self) 450 (hasattr(endog, 'index') and hasattr(exog, 'index')) and 451 not self.orig_endog.index.equals(self.orig_exog.index)): --> 452 raise ValueError("The indices for endog and exog are not aligned") 453 super(PandasData, self)._check_integrity() 454 ValueError: The indices for endog and exog are not aligned ``` The y matrix and X matrix have shape of (9018,),(9018, 59). Therefore any mismatch in dependent and independent variables doesn't appear. Any idea?
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 `dataframe.reset_index(drop = True)` before separating `x` and `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=True) Pls provide your valuable feedback
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_objects(convert_numeric=True) #Building Logistic model_LSVC print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) print("y values:",y.head()) logit = sm.Logit(y,X,missing='drop') ``` The error that appears: ``` Shape of y: (9018,) &&Shape of X_selected_lsvc: (9018, 59) y values: 0 0 1 1 2 0 3 0 4 0 Name: mort, dtype: int64 ValueError Traceback (most recent call last) <ipython-input-8-fec746e2ee99> in <module>() 160 print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) 161 print("y values:",y.head()) --> 162 logit = sm.Logit(y,X,missing='drop') 163 # fit the model 164 est = logit.fit(method='cg') D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 399 400 def __init__(self, endog, exog, **kwargs): --> 401 super(BinaryModel, self).__init__(endog, exog, **kwargs) 402 if (self.__class__.__name__ != 'MNLogit' and 403 not np.all((self.endog >= 0) & (self.endog <= 1))): D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 152 """ 153 def __init__(self, endog, exog, **kwargs): --> 154 super(DiscreteModel, self).__init__(endog, exog, **kwargs) 155 self.raise_on_perfect_prediction = True 156 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 184 185 def __init__(self, endog, exog=None, **kwargs): --> 186 super(LikelihoodModel, self).__init__(endog, exog, **kwargs) 187 self.initialize() 188 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 58 hasconst = kwargs.pop('hasconst', None) 59 self.data = self._handle_data(endog, exog, missing, hasconst, ---> 60 **kwargs) 61 self.k_constant = self.data.k_constant 62 self.exog = self.data.exog D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs) 82 83 def _handle_data(self, endog, exog, missing, hasconst, **kwargs): ---> 84 data = handle_data(endog, exog, missing, hasconst, **kwargs) 85 # kwargs arrays could have changed, easier to just attach here 86 for key in kwargs: D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in handle_data(endog, exog, missing, hasconst, **kwargs) 564 klass = handle_data_class_factory(endog, exog) 565 return klass(endog, exog=exog, missing=missing, hasconst=hasconst, --> 566 **kwargs) D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in __init__(self, endog, exog, missing, hasconst, **kwargs) 74 # this has side-effects, attaches k_constant and const_idx 75 self._handle_constant(hasconst) ---> 76 self._check_integrity() 77 self._cache = resettable_cache() 78 D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in _check_integrity(self) 450 (hasattr(endog, 'index') and hasattr(exog, 'index')) and 451 not self.orig_endog.index.equals(self.orig_exog.index)): --> 452 raise ValueError("The indices for endog and exog are not aligned") 453 super(PandasData, self)._check_integrity() 454 ValueError: The indices for endog and exog are not aligned ``` The y matrix and X matrix have shape of (9018,),(9018, 59). Therefore any mismatch in dependent and independent variables doesn't appear. Any idea?
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=True) Pls provide your valuable feedback
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_objects(convert_numeric=True) #Building Logistic model_LSVC print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) print("y values:",y.head()) logit = sm.Logit(y,X,missing='drop') ``` The error that appears: ``` Shape of y: (9018,) &&Shape of X_selected_lsvc: (9018, 59) y values: 0 0 1 1 2 0 3 0 4 0 Name: mort, dtype: int64 ValueError Traceback (most recent call last) <ipython-input-8-fec746e2ee99> in <module>() 160 print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) 161 print("y values:",y.head()) --> 162 logit = sm.Logit(y,X,missing='drop') 163 # fit the model 164 est = logit.fit(method='cg') D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 399 400 def __init__(self, endog, exog, **kwargs): --> 401 super(BinaryModel, self).__init__(endog, exog, **kwargs) 402 if (self.__class__.__name__ != 'MNLogit' and 403 not np.all((self.endog >= 0) & (self.endog <= 1))): D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 152 """ 153 def __init__(self, endog, exog, **kwargs): --> 154 super(DiscreteModel, self).__init__(endog, exog, **kwargs) 155 self.raise_on_perfect_prediction = True 156 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 184 185 def __init__(self, endog, exog=None, **kwargs): --> 186 super(LikelihoodModel, self).__init__(endog, exog, **kwargs) 187 self.initialize() 188 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 58 hasconst = kwargs.pop('hasconst', None) 59 self.data = self._handle_data(endog, exog, missing, hasconst, ---> 60 **kwargs) 61 self.k_constant = self.data.k_constant 62 self.exog = self.data.exog D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs) 82 83 def _handle_data(self, endog, exog, missing, hasconst, **kwargs): ---> 84 data = handle_data(endog, exog, missing, hasconst, **kwargs) 85 # kwargs arrays could have changed, easier to just attach here 86 for key in kwargs: D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in handle_data(endog, exog, missing, hasconst, **kwargs) 564 klass = handle_data_class_factory(endog, exog) 565 return klass(endog, exog=exog, missing=missing, hasconst=hasconst, --> 566 **kwargs) D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in __init__(self, endog, exog, missing, hasconst, **kwargs) 74 # this has side-effects, attaches k_constant and const_idx 75 self._handle_constant(hasconst) ---> 76 self._check_integrity() 77 self._cache = resettable_cache() 78 D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in _check_integrity(self) 450 (hasattr(endog, 'index') and hasattr(exog, 'index')) and 451 not self.orig_endog.index.equals(self.orig_exog.index)): --> 452 raise ValueError("The indices for endog and exog are not aligned") 453 super(PandasData, self)._check_integrity() 454 ValueError: The indices for endog and exog are not aligned ``` The y matrix and X matrix have shape of (9018,),(9018, 59). Therefore any mismatch in dependent and independent variables doesn't appear. Any idea?
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 as 1 but rows as unknown i.e. we got a single column with as many rows as X. Lets take a example:- ``` z = np.array([[1, 2], [ 3, 4]]) print(z.shape) # (2, 2) ``` Now we will use reshape(-1,1) function on this array. We can see new array has 4 row and 1 column. ``` new_z= z.reshape(-1,1) print(new_z) #array([[1],[2],[3], [4]]) print(new_z.shape) #(4, 1) ```
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_objects(convert_numeric=True) #Building Logistic model_LSVC print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) print("y values:",y.head()) logit = sm.Logit(y,X,missing='drop') ``` The error that appears: ``` Shape of y: (9018,) &&Shape of X_selected_lsvc: (9018, 59) y values: 0 0 1 1 2 0 3 0 4 0 Name: mort, dtype: int64 ValueError Traceback (most recent call last) <ipython-input-8-fec746e2ee99> in <module>() 160 print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) 161 print("y values:",y.head()) --> 162 logit = sm.Logit(y,X,missing='drop') 163 # fit the model 164 est = logit.fit(method='cg') D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 399 400 def __init__(self, endog, exog, **kwargs): --> 401 super(BinaryModel, self).__init__(endog, exog, **kwargs) 402 if (self.__class__.__name__ != 'MNLogit' and 403 not np.all((self.endog >= 0) & (self.endog <= 1))): D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 152 """ 153 def __init__(self, endog, exog, **kwargs): --> 154 super(DiscreteModel, self).__init__(endog, exog, **kwargs) 155 self.raise_on_perfect_prediction = True 156 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 184 185 def __init__(self, endog, exog=None, **kwargs): --> 186 super(LikelihoodModel, self).__init__(endog, exog, **kwargs) 187 self.initialize() 188 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 58 hasconst = kwargs.pop('hasconst', None) 59 self.data = self._handle_data(endog, exog, missing, hasconst, ---> 60 **kwargs) 61 self.k_constant = self.data.k_constant 62 self.exog = self.data.exog D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs) 82 83 def _handle_data(self, endog, exog, missing, hasconst, **kwargs): ---> 84 data = handle_data(endog, exog, missing, hasconst, **kwargs) 85 # kwargs arrays could have changed, easier to just attach here 86 for key in kwargs: D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in handle_data(endog, exog, missing, hasconst, **kwargs) 564 klass = handle_data_class_factory(endog, exog) 565 return klass(endog, exog=exog, missing=missing, hasconst=hasconst, --> 566 **kwargs) D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in __init__(self, endog, exog, missing, hasconst, **kwargs) 74 # this has side-effects, attaches k_constant and const_idx 75 self._handle_constant(hasconst) ---> 76 self._check_integrity() 77 self._cache = resettable_cache() 78 D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in _check_integrity(self) 450 (hasattr(endog, 'index') and hasattr(exog, 'index')) and 451 not self.orig_endog.index.equals(self.orig_exog.index)): --> 452 raise ValueError("The indices for endog and exog are not aligned") 453 super(PandasData, self)._check_integrity() 454 ValueError: The indices for endog and exog are not aligned ``` The y matrix and X matrix have shape of (9018,),(9018, 59). Therefore any mismatch in dependent and independent variables doesn't appear. Any idea?
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=100 ) ```
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_objects(convert_numeric=True) #Building Logistic model_LSVC print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) print("y values:",y.head()) logit = sm.Logit(y,X,missing='drop') ``` The error that appears: ``` Shape of y: (9018,) &&Shape of X_selected_lsvc: (9018, 59) y values: 0 0 1 1 2 0 3 0 4 0 Name: mort, dtype: int64 ValueError Traceback (most recent call last) <ipython-input-8-fec746e2ee99> in <module>() 160 print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) 161 print("y values:",y.head()) --> 162 logit = sm.Logit(y,X,missing='drop') 163 # fit the model 164 est = logit.fit(method='cg') D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 399 400 def __init__(self, endog, exog, **kwargs): --> 401 super(BinaryModel, self).__init__(endog, exog, **kwargs) 402 if (self.__class__.__name__ != 'MNLogit' and 403 not np.all((self.endog >= 0) & (self.endog <= 1))): D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 152 """ 153 def __init__(self, endog, exog, **kwargs): --> 154 super(DiscreteModel, self).__init__(endog, exog, **kwargs) 155 self.raise_on_perfect_prediction = True 156 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 184 185 def __init__(self, endog, exog=None, **kwargs): --> 186 super(LikelihoodModel, self).__init__(endog, exog, **kwargs) 187 self.initialize() 188 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 58 hasconst = kwargs.pop('hasconst', None) 59 self.data = self._handle_data(endog, exog, missing, hasconst, ---> 60 **kwargs) 61 self.k_constant = self.data.k_constant 62 self.exog = self.data.exog D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs) 82 83 def _handle_data(self, endog, exog, missing, hasconst, **kwargs): ---> 84 data = handle_data(endog, exog, missing, hasconst, **kwargs) 85 # kwargs arrays could have changed, easier to just attach here 86 for key in kwargs: D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in handle_data(endog, exog, missing, hasconst, **kwargs) 564 klass = handle_data_class_factory(endog, exog) 565 return klass(endog, exog=exog, missing=missing, hasconst=hasconst, --> 566 **kwargs) D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in __init__(self, endog, exog, missing, hasconst, **kwargs) 74 # this has side-effects, attaches k_constant and const_idx 75 self._handle_constant(hasconst) ---> 76 self._check_integrity() 77 self._cache = resettable_cache() 78 D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in _check_integrity(self) 450 (hasattr(endog, 'index') and hasattr(exog, 'index')) and 451 not self.orig_endog.index.equals(self.orig_exog.index)): --> 452 raise ValueError("The indices for endog and exog are not aligned") 453 super(PandasData, self)._check_integrity() 454 ValueError: The indices for endog and exog are not aligned ``` The y matrix and X matrix have shape of (9018,),(9018, 59). Therefore any mismatch in dependent and independent variables doesn't appear. Any idea?
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=100 ) ```
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_objects(convert_numeric=True) #Building Logistic model_LSVC print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) print("y values:",y.head()) logit = sm.Logit(y,X,missing='drop') ``` The error that appears: ``` Shape of y: (9018,) &&Shape of X_selected_lsvc: (9018, 59) y values: 0 0 1 1 2 0 3 0 4 0 Name: mort, dtype: int64 ValueError Traceback (most recent call last) <ipython-input-8-fec746e2ee99> in <module>() 160 print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) 161 print("y values:",y.head()) --> 162 logit = sm.Logit(y,X,missing='drop') 163 # fit the model 164 est = logit.fit(method='cg') D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 399 400 def __init__(self, endog, exog, **kwargs): --> 401 super(BinaryModel, self).__init__(endog, exog, **kwargs) 402 if (self.__class__.__name__ != 'MNLogit' and 403 not np.all((self.endog >= 0) & (self.endog <= 1))): D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 152 """ 153 def __init__(self, endog, exog, **kwargs): --> 154 super(DiscreteModel, self).__init__(endog, exog, **kwargs) 155 self.raise_on_perfect_prediction = True 156 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 184 185 def __init__(self, endog, exog=None, **kwargs): --> 186 super(LikelihoodModel, self).__init__(endog, exog, **kwargs) 187 self.initialize() 188 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 58 hasconst = kwargs.pop('hasconst', None) 59 self.data = self._handle_data(endog, exog, missing, hasconst, ---> 60 **kwargs) 61 self.k_constant = self.data.k_constant 62 self.exog = self.data.exog D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs) 82 83 def _handle_data(self, endog, exog, missing, hasconst, **kwargs): ---> 84 data = handle_data(endog, exog, missing, hasconst, **kwargs) 85 # kwargs arrays could have changed, easier to just attach here 86 for key in kwargs: D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in handle_data(endog, exog, missing, hasconst, **kwargs) 564 klass = handle_data_class_factory(endog, exog) 565 return klass(endog, exog=exog, missing=missing, hasconst=hasconst, --> 566 **kwargs) D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in __init__(self, endog, exog, missing, hasconst, **kwargs) 74 # this has side-effects, attaches k_constant and const_idx 75 self._handle_constant(hasconst) ---> 76 self._check_integrity() 77 self._cache = resettable_cache() 78 D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in _check_integrity(self) 450 (hasattr(endog, 'index') and hasattr(exog, 'index')) and 451 not self.orig_endog.index.equals(self.orig_exog.index)): --> 452 raise ValueError("The indices for endog and exog are not aligned") 453 super(PandasData, self)._check_integrity() 454 ValueError: The indices for endog and exog are not aligned ``` The y matrix and X matrix have shape of (9018,),(9018, 59). Therefore any mismatch in dependent and independent variables doesn't appear. Any idea?
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_objects(convert_numeric=True) #Building Logistic model_LSVC print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) print("y values:",y.head()) logit = sm.Logit(y,X,missing='drop') ``` The error that appears: ``` Shape of y: (9018,) &&Shape of X_selected_lsvc: (9018, 59) y values: 0 0 1 1 2 0 3 0 4 0 Name: mort, dtype: int64 ValueError Traceback (most recent call last) <ipython-input-8-fec746e2ee99> in <module>() 160 print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) 161 print("y values:",y.head()) --> 162 logit = sm.Logit(y,X,missing='drop') 163 # fit the model 164 est = logit.fit(method='cg') D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 399 400 def __init__(self, endog, exog, **kwargs): --> 401 super(BinaryModel, self).__init__(endog, exog, **kwargs) 402 if (self.__class__.__name__ != 'MNLogit' and 403 not np.all((self.endog >= 0) & (self.endog <= 1))): D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 152 """ 153 def __init__(self, endog, exog, **kwargs): --> 154 super(DiscreteModel, self).__init__(endog, exog, **kwargs) 155 self.raise_on_perfect_prediction = True 156 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 184 185 def __init__(self, endog, exog=None, **kwargs): --> 186 super(LikelihoodModel, self).__init__(endog, exog, **kwargs) 187 self.initialize() 188 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 58 hasconst = kwargs.pop('hasconst', None) 59 self.data = self._handle_data(endog, exog, missing, hasconst, ---> 60 **kwargs) 61 self.k_constant = self.data.k_constant 62 self.exog = self.data.exog D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs) 82 83 def _handle_data(self, endog, exog, missing, hasconst, **kwargs): ---> 84 data = handle_data(endog, exog, missing, hasconst, **kwargs) 85 # kwargs arrays could have changed, easier to just attach here 86 for key in kwargs: D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in handle_data(endog, exog, missing, hasconst, **kwargs) 564 klass = handle_data_class_factory(endog, exog) 565 return klass(endog, exog=exog, missing=missing, hasconst=hasconst, --> 566 **kwargs) D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in __init__(self, endog, exog, missing, hasconst, **kwargs) 74 # this has side-effects, attaches k_constant and const_idx 75 self._handle_constant(hasconst) ---> 76 self._check_integrity() 77 self._cache = resettable_cache() 78 D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in _check_integrity(self) 450 (hasattr(endog, 'index') and hasattr(exog, 'index')) and 451 not self.orig_endog.index.equals(self.orig_exog.index)): --> 452 raise ValueError("The indices for endog and exog are not aligned") 453 super(PandasData, self)._check_integrity() 454 ValueError: The indices for endog and exog are not aligned ``` The y matrix and X matrix have shape of (9018,),(9018, 59). Therefore any mismatch in dependent and independent variables doesn't appear. Any idea?
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=100 ) ```
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=True) Pls provide your valuable feedback
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_objects(convert_numeric=True) #Building Logistic model_LSVC print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) print("y values:",y.head()) logit = sm.Logit(y,X,missing='drop') ``` The error that appears: ``` Shape of y: (9018,) &&Shape of X_selected_lsvc: (9018, 59) y values: 0 0 1 1 2 0 3 0 4 0 Name: mort, dtype: int64 ValueError Traceback (most recent call last) <ipython-input-8-fec746e2ee99> in <module>() 160 print("Shape of y:", y.shape, " &&Shape of X_selected_lsvc:", X.shape) 161 print("y values:",y.head()) --> 162 logit = sm.Logit(y,X,missing='drop') 163 # fit the model 164 est = logit.fit(method='cg') D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 399 400 def __init__(self, endog, exog, **kwargs): --> 401 super(BinaryModel, self).__init__(endog, exog, **kwargs) 402 if (self.__class__.__name__ != 'MNLogit' and 403 not np.all((self.endog >= 0) & (self.endog <= 1))): D:\Anaconda3\lib\site-packages\statsmodels\discrete\discrete_model.py in __init__(self, endog, exog, **kwargs) 152 """ 153 def __init__(self, endog, exog, **kwargs): --> 154 super(DiscreteModel, self).__init__(endog, exog, **kwargs) 155 self.raise_on_perfect_prediction = True 156 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 184 185 def __init__(self, endog, exog=None, **kwargs): --> 186 super(LikelihoodModel, self).__init__(endog, exog, **kwargs) 187 self.initialize() 188 D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 58 hasconst = kwargs.pop('hasconst', None) 59 self.data = self._handle_data(endog, exog, missing, hasconst, ---> 60 **kwargs) 61 self.k_constant = self.data.k_constant 62 self.exog = self.data.exog D:\Anaconda3\lib\site-packages\statsmodels\base\model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs) 82 83 def _handle_data(self, endog, exog, missing, hasconst, **kwargs): ---> 84 data = handle_data(endog, exog, missing, hasconst, **kwargs) 85 # kwargs arrays could have changed, easier to just attach here 86 for key in kwargs: D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in handle_data(endog, exog, missing, hasconst, **kwargs) 564 klass = handle_data_class_factory(endog, exog) 565 return klass(endog, exog=exog, missing=missing, hasconst=hasconst, --> 566 **kwargs) D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in __init__(self, endog, exog, missing, hasconst, **kwargs) 74 # this has side-effects, attaches k_constant and const_idx 75 self._handle_constant(hasconst) ---> 76 self._check_integrity() 77 self._cache = resettable_cache() 78 D:\Anaconda3\lib\site-packages\statsmodels\base\data.py in _check_integrity(self) 450 (hasattr(endog, 'index') and hasattr(exog, 'index')) and 451 not self.orig_endog.index.equals(self.orig_exog.index)): --> 452 raise ValueError("The indices for endog and exog are not aligned") 453 super(PandasData, self)._check_integrity() 454 ValueError: The indices for endog and exog are not aligned ``` The y matrix and X matrix have shape of (9018,),(9018, 59). Therefore any mismatch in dependent and independent variables doesn't appear. Any idea?
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 as 1 but rows as unknown i.e. we got a single column with as many rows as X. Lets take a example:- ``` z = np.array([[1, 2], [ 3, 4]]) print(z.shape) # (2, 2) ``` Now we will use reshape(-1,1) function on this array. We can see new array has 4 row and 1 column. ``` new_z= z.reshape(-1,1) print(new_z) #array([[1],[2],[3], [4]]) print(new_z.shape) #(4, 1) ```
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 `dataframe.reset_index(drop = True)` before separating `x` and `y`.
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 ?