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
1,817,183
I'm trying to learn the super() function in Python. I thought I had a grasp of it until I came over this example (2.6) and found myself stuck. [http://www.cafepy.com/article/python\_attributes\_and\_methods/python\_attributes\_and\_methods.html#super-with-classmethod-example](https://web.archive.org/web/20170820065901/http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#super-with-classmethod-example) ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "test.py", line 9, in do_something do_something = classmethod(do_something) TypeError: unbound method do_something() must be called with B instance as first argument (got nothing instead) >>> ``` It wasn't what I expected when I read this line right before the example: > If we're using a class method, we don't have an instance to call super with. Fortunately for us, super works even with a type as the second argument. --- The type can be passed directly to super as shown below. Which is exactly what Python tells me is not possible by saying that do\_something() should be called with an instance of B.
2009/11/29
[ "https://Stackoverflow.com/questions/1817183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169854/" ]
In Python 3, you can skip specifying arguments for `super`, ``` class A: @classmethod def f(cls): return "A's f was called." class B(A): @classmethod def f(cls): return super().f() assert B.f() == "A's f was called." ```
The example from the web page seems to work as published. Did you create a `do_something` method for the superclass as well but not make it into a classmethod? Something like this will give you that error: ``` >>> class A(object): ... def do_something(cls): ... print cls ... # do_something = classmethod(do_something) ... >>> class B(A): ... def do_something(cls): ... super(B, cls).do_something() ... do_something = classmethod(do_something) ... >>> B().do_something() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in do_something TypeError: unbound method do_something() must be called with B instance as first argument (got nothing instead) ```
1,817,183
I'm trying to learn the super() function in Python. I thought I had a grasp of it until I came over this example (2.6) and found myself stuck. [http://www.cafepy.com/article/python\_attributes\_and\_methods/python\_attributes\_and\_methods.html#super-with-classmethod-example](https://web.archive.org/web/20170820065901/http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#super-with-classmethod-example) ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "test.py", line 9, in do_something do_something = classmethod(do_something) TypeError: unbound method do_something() must be called with B instance as first argument (got nothing instead) >>> ``` It wasn't what I expected when I read this line right before the example: > If we're using a class method, we don't have an instance to call super with. Fortunately for us, super works even with a type as the second argument. --- The type can be passed directly to super as shown below. Which is exactly what Python tells me is not possible by saying that do\_something() should be called with an instance of B.
2009/11/29
[ "https://Stackoverflow.com/questions/1817183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169854/" ]
Sometimes texts have to be read more for the flavor of the idea rather than for the details. This is one of those cases. In the [linked page](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#a-super-solution), Examples 2.5, 2.6 and 2.7 should all use one method, `do_your_stuff`. (That is, `do_something` should be changed to `do_your_stuff`.) In addition, as [Ned Deily pointed out](https://stackoverflow.com/a/1817242/190597), `A.do_your_stuff` has to be a class method. ``` class A(object): @classmethod def do_your_stuff(cls): print 'This is A' class B(A): @classmethod def do_your_stuff(cls): super(B, cls).do_your_stuff() B.do_your_stuff() ``` `super(B, cls).do_your_stuff` returns a *bound* method (see [footnote 2](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#a-super-solution)). Since `cls` was passed as the second argument to `super()`, it is `cls` that gets bound to the returned method. In other words, `cls` gets passed as the first argument to the method `do_your_stuff()` of class A. To reiterate: `super(B, cls).do_your_stuff()` causes `A`'s `do_your_stuff` method to be called with `cls` passed as the first argument. In order for that to work, `A`'s `do_your_stuff` has to be a class method. The linked page doesn't mention that, but that is definitively the case. PS. `do_something = classmethod(do_something)` is the old way of making a classmethod. The new(er) way is to use the @classmethod decorator. --- Note that `super(B, cls)` can not be replaced by `super(cls, cls)`. Doing so could lead to infinite loops. For example, ``` class A(object): @classmethod def do_your_stuff(cls): print('This is A') class B(A): @classmethod def do_your_stuff(cls): print('This is B') # super(B, cls).do_your_stuff() # CORRECT super(cls, cls).do_your_stuff() # WRONG class C(B): @classmethod def do_your_stuff(cls): print('This is C') # super(C, cls).do_your_stuff() # CORRECT super(cls, cls).do_your_stuff() # WRONG C.do_your_stuff() ``` will raise `RuntimeError: maximum recursion depth exceeded while calling a Python object`. If `cls` is `C`, then `super(cls, cls)` searches `C.mro()` for the class that comes after `C`. ``` In [161]: C.mro() Out[161]: [__main__.C, __main__.B, __main__.A, object] ``` Since that class is `B`, when `cls` is `C`, `super(cls, cls).do_your_stuff()` **always** calls `B.do_your_stuff`. Since `super(cls, cls).do_your_stuff()` is called inside `B.do_your_stuff`, you end up calling `B.do_your_stuff` in an infinite loop. In Python3, the [0-argument form of `super`](https://docs.python.org/3/library/functions.html#super) was added so `super(B, cls)` could be replaced by `super()`, and Python3 will figure out from context that `super()` in the definition of `class B` should be equivalent to `super(B, cls)`. But in no circumstance is `super(cls, cls)` (or for similar reasons, `super(type(self), self)`) ever correct.
I think I've understood the point now thanks to this beatiful site and lovely community. If you don't mind please correct me if I'm wrong on classmethods (which I am now trying to understand fully): ``` # EXAMPLE #1 >>> class A(object): ... def foo(cls): ... print cls ... foo = classmethod(foo) ... >>> a = A() >>> a.foo() # THIS IS THE CLASS ITSELF (__class__) class '__main__.A' # EXAMPLE #2 # SAME AS ABOVE (With new @decorator) >>> class A(object): ... @classmethod ... def foo(cls): ... print cls ... >>> a = A() >>> a.foo() class '__main__.A' # EXAMPLE #3 >>> class B(object): ... def foo(self): ... print self ... >>> b = B() >>> b.foo() # THIS IS THE INSTANCE WITH ADDRESS (self) __main__.B object at 0xb747a8ec >>> ``` I hope this illustration shows ..
1,817,183
I'm trying to learn the super() function in Python. I thought I had a grasp of it until I came over this example (2.6) and found myself stuck. [http://www.cafepy.com/article/python\_attributes\_and\_methods/python\_attributes\_and\_methods.html#super-with-classmethod-example](https://web.archive.org/web/20170820065901/http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#super-with-classmethod-example) ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "test.py", line 9, in do_something do_something = classmethod(do_something) TypeError: unbound method do_something() must be called with B instance as first argument (got nothing instead) >>> ``` It wasn't what I expected when I read this line right before the example: > If we're using a class method, we don't have an instance to call super with. Fortunately for us, super works even with a type as the second argument. --- The type can be passed directly to super as shown below. Which is exactly what Python tells me is not possible by saying that do\_something() should be called with an instance of B.
2009/11/29
[ "https://Stackoverflow.com/questions/1817183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169854/" ]
Sometimes texts have to be read more for the flavor of the idea rather than for the details. This is one of those cases. In the [linked page](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#a-super-solution), Examples 2.5, 2.6 and 2.7 should all use one method, `do_your_stuff`. (That is, `do_something` should be changed to `do_your_stuff`.) In addition, as [Ned Deily pointed out](https://stackoverflow.com/a/1817242/190597), `A.do_your_stuff` has to be a class method. ``` class A(object): @classmethod def do_your_stuff(cls): print 'This is A' class B(A): @classmethod def do_your_stuff(cls): super(B, cls).do_your_stuff() B.do_your_stuff() ``` `super(B, cls).do_your_stuff` returns a *bound* method (see [footnote 2](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#a-super-solution)). Since `cls` was passed as the second argument to `super()`, it is `cls` that gets bound to the returned method. In other words, `cls` gets passed as the first argument to the method `do_your_stuff()` of class A. To reiterate: `super(B, cls).do_your_stuff()` causes `A`'s `do_your_stuff` method to be called with `cls` passed as the first argument. In order for that to work, `A`'s `do_your_stuff` has to be a class method. The linked page doesn't mention that, but that is definitively the case. PS. `do_something = classmethod(do_something)` is the old way of making a classmethod. The new(er) way is to use the @classmethod decorator. --- Note that `super(B, cls)` can not be replaced by `super(cls, cls)`. Doing so could lead to infinite loops. For example, ``` class A(object): @classmethod def do_your_stuff(cls): print('This is A') class B(A): @classmethod def do_your_stuff(cls): print('This is B') # super(B, cls).do_your_stuff() # CORRECT super(cls, cls).do_your_stuff() # WRONG class C(B): @classmethod def do_your_stuff(cls): print('This is C') # super(C, cls).do_your_stuff() # CORRECT super(cls, cls).do_your_stuff() # WRONG C.do_your_stuff() ``` will raise `RuntimeError: maximum recursion depth exceeded while calling a Python object`. If `cls` is `C`, then `super(cls, cls)` searches `C.mro()` for the class that comes after `C`. ``` In [161]: C.mro() Out[161]: [__main__.C, __main__.B, __main__.A, object] ``` Since that class is `B`, when `cls` is `C`, `super(cls, cls).do_your_stuff()` **always** calls `B.do_your_stuff`. Since `super(cls, cls).do_your_stuff()` is called inside `B.do_your_stuff`, you end up calling `B.do_your_stuff` in an infinite loop. In Python3, the [0-argument form of `super`](https://docs.python.org/3/library/functions.html#super) was added so `super(B, cls)` could be replaced by `super()`, and Python3 will figure out from context that `super()` in the definition of `class B` should be equivalent to `super(B, cls)`. But in no circumstance is `super(cls, cls)` (or for similar reasons, `super(type(self), self)`) ever correct.
I've updated the article to make it a bit clearer: [Python Attributes and Methods # Super](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#a-super-solution) Your example using classmethod above shows what a class method is - it passes the class itself instead of the instance as the first parameter. But you don't even need an instance to call the method, for e.g.: ``` >>> class A(object): ... @classmethod ... def foo(cls): ... print cls ... >>> A.foo() # note this is called directly on the class <class '__main__.A'> ```
1,817,183
I'm trying to learn the super() function in Python. I thought I had a grasp of it until I came over this example (2.6) and found myself stuck. [http://www.cafepy.com/article/python\_attributes\_and\_methods/python\_attributes\_and\_methods.html#super-with-classmethod-example](https://web.archive.org/web/20170820065901/http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#super-with-classmethod-example) ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "test.py", line 9, in do_something do_something = classmethod(do_something) TypeError: unbound method do_something() must be called with B instance as first argument (got nothing instead) >>> ``` It wasn't what I expected when I read this line right before the example: > If we're using a class method, we don't have an instance to call super with. Fortunately for us, super works even with a type as the second argument. --- The type can be passed directly to super as shown below. Which is exactly what Python tells me is not possible by saying that do\_something() should be called with an instance of B.
2009/11/29
[ "https://Stackoverflow.com/questions/1817183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169854/" ]
Sometimes texts have to be read more for the flavor of the idea rather than for the details. This is one of those cases. In the [linked page](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#a-super-solution), Examples 2.5, 2.6 and 2.7 should all use one method, `do_your_stuff`. (That is, `do_something` should be changed to `do_your_stuff`.) In addition, as [Ned Deily pointed out](https://stackoverflow.com/a/1817242/190597), `A.do_your_stuff` has to be a class method. ``` class A(object): @classmethod def do_your_stuff(cls): print 'This is A' class B(A): @classmethod def do_your_stuff(cls): super(B, cls).do_your_stuff() B.do_your_stuff() ``` `super(B, cls).do_your_stuff` returns a *bound* method (see [footnote 2](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#a-super-solution)). Since `cls` was passed as the second argument to `super()`, it is `cls` that gets bound to the returned method. In other words, `cls` gets passed as the first argument to the method `do_your_stuff()` of class A. To reiterate: `super(B, cls).do_your_stuff()` causes `A`'s `do_your_stuff` method to be called with `cls` passed as the first argument. In order for that to work, `A`'s `do_your_stuff` has to be a class method. The linked page doesn't mention that, but that is definitively the case. PS. `do_something = classmethod(do_something)` is the old way of making a classmethod. The new(er) way is to use the @classmethod decorator. --- Note that `super(B, cls)` can not be replaced by `super(cls, cls)`. Doing so could lead to infinite loops. For example, ``` class A(object): @classmethod def do_your_stuff(cls): print('This is A') class B(A): @classmethod def do_your_stuff(cls): print('This is B') # super(B, cls).do_your_stuff() # CORRECT super(cls, cls).do_your_stuff() # WRONG class C(B): @classmethod def do_your_stuff(cls): print('This is C') # super(C, cls).do_your_stuff() # CORRECT super(cls, cls).do_your_stuff() # WRONG C.do_your_stuff() ``` will raise `RuntimeError: maximum recursion depth exceeded while calling a Python object`. If `cls` is `C`, then `super(cls, cls)` searches `C.mro()` for the class that comes after `C`. ``` In [161]: C.mro() Out[161]: [__main__.C, __main__.B, __main__.A, object] ``` Since that class is `B`, when `cls` is `C`, `super(cls, cls).do_your_stuff()` **always** calls `B.do_your_stuff`. Since `super(cls, cls).do_your_stuff()` is called inside `B.do_your_stuff`, you end up calling `B.do_your_stuff` in an infinite loop. In Python3, the [0-argument form of `super`](https://docs.python.org/3/library/functions.html#super) was added so `super(B, cls)` could be replaced by `super()`, and Python3 will figure out from context that `super()` in the definition of `class B` should be equivalent to `super(B, cls)`. But in no circumstance is `super(cls, cls)` (or for similar reasons, `super(type(self), self)`) ever correct.
In Python 3, you can skip specifying arguments for `super`, ``` class A: @classmethod def f(cls): return "A's f was called." class B(A): @classmethod def f(cls): return super().f() assert B.f() == "A's f was called." ```
1,817,183
I'm trying to learn the super() function in Python. I thought I had a grasp of it until I came over this example (2.6) and found myself stuck. [http://www.cafepy.com/article/python\_attributes\_and\_methods/python\_attributes\_and\_methods.html#super-with-classmethod-example](https://web.archive.org/web/20170820065901/http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#super-with-classmethod-example) ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "test.py", line 9, in do_something do_something = classmethod(do_something) TypeError: unbound method do_something() must be called with B instance as first argument (got nothing instead) >>> ``` It wasn't what I expected when I read this line right before the example: > If we're using a class method, we don't have an instance to call super with. Fortunately for us, super works even with a type as the second argument. --- The type can be passed directly to super as shown below. Which is exactly what Python tells me is not possible by saying that do\_something() should be called with an instance of B.
2009/11/29
[ "https://Stackoverflow.com/questions/1817183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169854/" ]
I've updated the article to make it a bit clearer: [Python Attributes and Methods # Super](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#a-super-solution) Your example using classmethod above shows what a class method is - it passes the class itself instead of the instance as the first parameter. But you don't even need an instance to call the method, for e.g.: ``` >>> class A(object): ... @classmethod ... def foo(cls): ... print cls ... >>> A.foo() # note this is called directly on the class <class '__main__.A'> ```
I think I've understood the point now thanks to this beatiful site and lovely community. If you don't mind please correct me if I'm wrong on classmethods (which I am now trying to understand fully): ``` # EXAMPLE #1 >>> class A(object): ... def foo(cls): ... print cls ... foo = classmethod(foo) ... >>> a = A() >>> a.foo() # THIS IS THE CLASS ITSELF (__class__) class '__main__.A' # EXAMPLE #2 # SAME AS ABOVE (With new @decorator) >>> class A(object): ... @classmethod ... def foo(cls): ... print cls ... >>> a = A() >>> a.foo() class '__main__.A' # EXAMPLE #3 >>> class B(object): ... def foo(self): ... print self ... >>> b = B() >>> b.foo() # THIS IS THE INSTANCE WITH ADDRESS (self) __main__.B object at 0xb747a8ec >>> ``` I hope this illustration shows ..
1,817,183
I'm trying to learn the super() function in Python. I thought I had a grasp of it until I came over this example (2.6) and found myself stuck. [http://www.cafepy.com/article/python\_attributes\_and\_methods/python\_attributes\_and\_methods.html#super-with-classmethod-example](https://web.archive.org/web/20170820065901/http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#super-with-classmethod-example) ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "test.py", line 9, in do_something do_something = classmethod(do_something) TypeError: unbound method do_something() must be called with B instance as first argument (got nothing instead) >>> ``` It wasn't what I expected when I read this line right before the example: > If we're using a class method, we don't have an instance to call super with. Fortunately for us, super works even with a type as the second argument. --- The type can be passed directly to super as shown below. Which is exactly what Python tells me is not possible by saying that do\_something() should be called with an instance of B.
2009/11/29
[ "https://Stackoverflow.com/questions/1817183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169854/" ]
In Python 3, you can skip specifying arguments for `super`, ``` class A: @classmethod def f(cls): return "A's f was called." class B(A): @classmethod def f(cls): return super().f() assert B.f() == "A's f was called." ```
I think I've understood the point now thanks to this beatiful site and lovely community. If you don't mind please correct me if I'm wrong on classmethods (which I am now trying to understand fully): ``` # EXAMPLE #1 >>> class A(object): ... def foo(cls): ... print cls ... foo = classmethod(foo) ... >>> a = A() >>> a.foo() # THIS IS THE CLASS ITSELF (__class__) class '__main__.A' # EXAMPLE #2 # SAME AS ABOVE (With new @decorator) >>> class A(object): ... @classmethod ... def foo(cls): ... print cls ... >>> a = A() >>> a.foo() class '__main__.A' # EXAMPLE #3 >>> class B(object): ... def foo(self): ... print self ... >>> b = B() >>> b.foo() # THIS IS THE INSTANCE WITH ADDRESS (self) __main__.B object at 0xb747a8ec >>> ``` I hope this illustration shows ..
1,817,183
I'm trying to learn the super() function in Python. I thought I had a grasp of it until I came over this example (2.6) and found myself stuck. [http://www.cafepy.com/article/python\_attributes\_and\_methods/python\_attributes\_and\_methods.html#super-with-classmethod-example](https://web.archive.org/web/20170820065901/http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#super-with-classmethod-example) ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "test.py", line 9, in do_something do_something = classmethod(do_something) TypeError: unbound method do_something() must be called with B instance as first argument (got nothing instead) >>> ``` It wasn't what I expected when I read this line right before the example: > If we're using a class method, we don't have an instance to call super with. Fortunately for us, super works even with a type as the second argument. --- The type can be passed directly to super as shown below. Which is exactly what Python tells me is not possible by saying that do\_something() should be called with an instance of B.
2009/11/29
[ "https://Stackoverflow.com/questions/1817183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169854/" ]
In Python 3, you can skip specifying arguments for `super`, ``` class A: @classmethod def f(cls): return "A's f was called." class B(A): @classmethod def f(cls): return super().f() assert B.f() == "A's f was called." ```
I've updated the article to make it a bit clearer: [Python Attributes and Methods # Super](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#a-super-solution) Your example using classmethod above shows what a class method is - it passes the class itself instead of the instance as the first parameter. But you don't even need an instance to call the method, for e.g.: ``` >>> class A(object): ... @classmethod ... def foo(cls): ... print cls ... >>> A.foo() # note this is called directly on the class <class '__main__.A'> ```
10,269,860
Here is a simple code in python 2.7.2, which fetches site and gets all links from given site: ``` import urllib2 from bs4 import BeautifulSoup def getAllLinks(url): response = urllib2.urlopen(url) content = response.read() soup = BeautifulSoup(content, "html5lib") return soup.find_all("a") links1 = getAllLinks('http://www.stanford.edu') links2 = getAllLinks('http://med.stanford.edu/') print len(links1) print len(links2) ``` Problem is that it doesn't work in second scenario. It prints 102 and 0, while there are clearly links on the second site. BeautifulSoup doesn't throw parsing errors and it pretty prints markup ok. I suspect it maybe caused by first line from source of med.stanford.edu which says that it's xml (even though content-type is: text/html): ``` <?xml version="1.0" encoding="iso-8859-1"?> ``` I can't figure out how to set up Beautiful to disregard it, or workaround. I'm using html5lib as parser because I had problems with default one (incorrect markup).
2012/04/22
[ "https://Stackoverflow.com/questions/10269860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/808271/" ]
When a document claims to be XML, I find the lxml parser gives the best results. Trying your code but using the lxml parser instead of html5lib finds the 300 links.
You are precisely right that the problem is the `<?xml...` line. Disregarding it is very simple: just skip the first line of content, by replacing ``` content = response.read() ``` with something like ``` content = "\n".join(response.readlines()[1:]) ``` Upon this change, `len(links2)` becomes 300. ETA: You probably want to do this conditionally, so you don't always skip the first line of content. An example would be something like: ``` content = response.read() if content.startswith("<?xml"): content = "\n".join(content.split("\n")[1:]) ```
73,494,380
I have a script using `docker` python library or [Docker Client API](https://docker-py.readthedocs.io/en/1.8.0/api/#containers). I would like to limit each docker container to use only 10cpus (total 30cpus in the instance), but I couldn't find the solution to achieve that. I know in docker, there is `--cpus` flag, but `docker` only has `cpu_shares (int): CPU shares (relative weight)` parameter to use. Does everyone have experience in setting the limit on cpu usage using `docker`? ```py import docker client = docker.DockerClient(base_url='unix://var/run/docker.sock') container = client.containers.run(my_docker_image, mem_limit=30G) ``` Edits: I tried `nano_cpus` as what [here](https://github.com/docker/docker-py/issues/1920) suggests, like `client.containers.run(my_docker_image, nano_cpus=10000000000)` to set 10CPUS. When I inspectED the container, it did show "NanoCpus": 10000000000". However, if I run the R in the container and do `parallel::detectCores()`, it still shows 30, which I am confused. I also link R tag now. Thank you!
2022/08/25
[ "https://Stackoverflow.com/questions/73494380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16729348/" ]
cPanel has a feature called Multi-PHP, which does what you need (if your host has it enabled). For each project, it puts a snippet like this in the `.htaccess` which sets the PHP version to use: ``` # php -- BEGIN cPanel-generated handler, do not edit # Set the “ea-php81” package as the default “PHP” programming language. <IfModule mime_module> AddHandler application/x-httpd-ea-php81 .php .php8 .phtml </IfModule> # php -- END cPanel-generated handler, do not edit ``` The example above is for PHP 8.1.
You can use as many different versions as you want. Consider: 1. Install PHP versios with PHP-FPM 2. Create directory strucure for each version (website) 3. Configure Apache for Both Websites. With the above configuration you have combined virtual hosts and PHP-FPM to serve multiple websites and multiple versions of PHP on a single server. The only practical limit on the number of PHP sites and PHP versions that your Apache service can handle is the processing power of your instance. There is a step by step guide here :[Multiple PHP version on one server](https://www.digitalocean.com/community/tutorials/how-to-run-multiple-php-versions-on-one-server-using-apache-and-php-fpm-on-ubuntu-18-04)
7,073,557
Question: Is there a way to make a program run with out logging in that doesn't involve the long painful task of creating a windows service, or is there an easy way to make a simple service? --- Info: I'm working on a little project for college which is a simple distributed processing program. I'm going to harness the computers on campus that are currently sitting completely idle and make my own little super computer. but to do this I need the client running on my target machines. Through a little mucking around on the internet I find that what I need is a service, I also find that this isn't something quite as simple as making a scheduled task or dropping a .bat file into the start up folder. I don't need a lot. if I could just get it to call "python cClient.py" i'm completely set. Is there an easy way to do this? like adding a key in the registry some where? or do I have to go through the whole song and dance ritual that microsoft has made for setting up a service?
2011/08/16
[ "https://Stackoverflow.com/questions/7073557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186608/" ]
The Windows NT Resource Kit introduced the [Srvany.exe command-line utility](http://support.microsoft.com/kb/137890), which can be used to start any Windows NT/2000/2003 application as a service. You can download Srvany.exe [here](http://www.microsoft.com/download/en/details.aspx?id=17657).
Use Visual Studio and just create yourself a Windows Service project. I think you'll find it very easy.
7,073,557
Question: Is there a way to make a program run with out logging in that doesn't involve the long painful task of creating a windows service, or is there an easy way to make a simple service? --- Info: I'm working on a little project for college which is a simple distributed processing program. I'm going to harness the computers on campus that are currently sitting completely idle and make my own little super computer. but to do this I need the client running on my target machines. Through a little mucking around on the internet I find that what I need is a service, I also find that this isn't something quite as simple as making a scheduled task or dropping a .bat file into the start up folder. I don't need a lot. if I could just get it to call "python cClient.py" i'm completely set. Is there an easy way to do this? like adding a key in the registry some where? or do I have to go through the whole song and dance ritual that microsoft has made for setting up a service?
2011/08/16
[ "https://Stackoverflow.com/questions/7073557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186608/" ]
If you already have the executable you wish to run as a service you can use "sc" built into the OS already. Microsoft details the procedure here: <http://support.microsoft.com/kb/251192> ``` example: sc create "My Service" c:\temp\executable.exe ``` > > C:\Users\somebody>sc create > > > ``` DESCRIPTION: Creates a service entry in the registry and Service Database. USAGE: sc <server> create [service name] [binPath= ] <option1> <option2>... OPTIONS: NOTE: The option name includes the equal sign. A space is required between the equal sign and the value. type= <own|share|interact|kernel|filesys|rec> (default = own) start= <boot|system|auto|demand|disabled|delayed-auto> (default = demand) error= <normal|severe|critical|ignore> (default = normal) binPath= <BinaryPathName> group= <LoadOrderGroup> tag= <yes|no> depend= <Dependencies(separated by / (forward slash))> obj= <AccountName|ObjectName> (default = LocalSystem) DisplayName= <display name> password= <password> ```
Use Visual Studio and just create yourself a Windows Service project. I think you'll find it very easy.
7,073,557
Question: Is there a way to make a program run with out logging in that doesn't involve the long painful task of creating a windows service, or is there an easy way to make a simple service? --- Info: I'm working on a little project for college which is a simple distributed processing program. I'm going to harness the computers on campus that are currently sitting completely idle and make my own little super computer. but to do this I need the client running on my target machines. Through a little mucking around on the internet I find that what I need is a service, I also find that this isn't something quite as simple as making a scheduled task or dropping a .bat file into the start up folder. I don't need a lot. if I could just get it to call "python cClient.py" i'm completely set. Is there an easy way to do this? like adding a key in the registry some where? or do I have to go through the whole song and dance ritual that microsoft has made for setting up a service?
2011/08/16
[ "https://Stackoverflow.com/questions/7073557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186608/" ]
Use Visual Studio and just create yourself a Windows Service project. I think you'll find it very easy.
Can you [schedule a task](http://windows.microsoft.com/en-US/windows7/schedule-a-task)? More info [here](http://technet.microsoft.com/en-us/library/cc770904.aspx).
7,073,557
Question: Is there a way to make a program run with out logging in that doesn't involve the long painful task of creating a windows service, or is there an easy way to make a simple service? --- Info: I'm working on a little project for college which is a simple distributed processing program. I'm going to harness the computers on campus that are currently sitting completely idle and make my own little super computer. but to do this I need the client running on my target machines. Through a little mucking around on the internet I find that what I need is a service, I also find that this isn't something quite as simple as making a scheduled task or dropping a .bat file into the start up folder. I don't need a lot. if I could just get it to call "python cClient.py" i'm completely set. Is there an easy way to do this? like adding a key in the registry some where? or do I have to go through the whole song and dance ritual that microsoft has made for setting up a service?
2011/08/16
[ "https://Stackoverflow.com/questions/7073557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186608/" ]
Use Visual Studio and just create yourself a Windows Service project. I think you'll find it very easy.
You can create a startup script and globally apply it to your machines via group policy - just add it via gpedit.msc: ![Add startup script via group policy](https://i.stack.imgur.com/hGJM4.png)
7,073,557
Question: Is there a way to make a program run with out logging in that doesn't involve the long painful task of creating a windows service, or is there an easy way to make a simple service? --- Info: I'm working on a little project for college which is a simple distributed processing program. I'm going to harness the computers on campus that are currently sitting completely idle and make my own little super computer. but to do this I need the client running on my target machines. Through a little mucking around on the internet I find that what I need is a service, I also find that this isn't something quite as simple as making a scheduled task or dropping a .bat file into the start up folder. I don't need a lot. if I could just get it to call "python cClient.py" i'm completely set. Is there an easy way to do this? like adding a key in the registry some where? or do I have to go through the whole song and dance ritual that microsoft has made for setting up a service?
2011/08/16
[ "https://Stackoverflow.com/questions/7073557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186608/" ]
If you already have the executable you wish to run as a service you can use "sc" built into the OS already. Microsoft details the procedure here: <http://support.microsoft.com/kb/251192> ``` example: sc create "My Service" c:\temp\executable.exe ``` > > C:\Users\somebody>sc create > > > ``` DESCRIPTION: Creates a service entry in the registry and Service Database. USAGE: sc <server> create [service name] [binPath= ] <option1> <option2>... OPTIONS: NOTE: The option name includes the equal sign. A space is required between the equal sign and the value. type= <own|share|interact|kernel|filesys|rec> (default = own) start= <boot|system|auto|demand|disabled|delayed-auto> (default = demand) error= <normal|severe|critical|ignore> (default = normal) binPath= <BinaryPathName> group= <LoadOrderGroup> tag= <yes|no> depend= <Dependencies(separated by / (forward slash))> obj= <AccountName|ObjectName> (default = LocalSystem) DisplayName= <display name> password= <password> ```
The Windows NT Resource Kit introduced the [Srvany.exe command-line utility](http://support.microsoft.com/kb/137890), which can be used to start any Windows NT/2000/2003 application as a service. You can download Srvany.exe [here](http://www.microsoft.com/download/en/details.aspx?id=17657).
7,073,557
Question: Is there a way to make a program run with out logging in that doesn't involve the long painful task of creating a windows service, or is there an easy way to make a simple service? --- Info: I'm working on a little project for college which is a simple distributed processing program. I'm going to harness the computers on campus that are currently sitting completely idle and make my own little super computer. but to do this I need the client running on my target machines. Through a little mucking around on the internet I find that what I need is a service, I also find that this isn't something quite as simple as making a scheduled task or dropping a .bat file into the start up folder. I don't need a lot. if I could just get it to call "python cClient.py" i'm completely set. Is there an easy way to do this? like adding a key in the registry some where? or do I have to go through the whole song and dance ritual that microsoft has made for setting up a service?
2011/08/16
[ "https://Stackoverflow.com/questions/7073557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186608/" ]
The Windows NT Resource Kit introduced the [Srvany.exe command-line utility](http://support.microsoft.com/kb/137890), which can be used to start any Windows NT/2000/2003 application as a service. You can download Srvany.exe [here](http://www.microsoft.com/download/en/details.aspx?id=17657).
Can you [schedule a task](http://windows.microsoft.com/en-US/windows7/schedule-a-task)? More info [here](http://technet.microsoft.com/en-us/library/cc770904.aspx).
7,073,557
Question: Is there a way to make a program run with out logging in that doesn't involve the long painful task of creating a windows service, or is there an easy way to make a simple service? --- Info: I'm working on a little project for college which is a simple distributed processing program. I'm going to harness the computers on campus that are currently sitting completely idle and make my own little super computer. but to do this I need the client running on my target machines. Through a little mucking around on the internet I find that what I need is a service, I also find that this isn't something quite as simple as making a scheduled task or dropping a .bat file into the start up folder. I don't need a lot. if I could just get it to call "python cClient.py" i'm completely set. Is there an easy way to do this? like adding a key in the registry some where? or do I have to go through the whole song and dance ritual that microsoft has made for setting up a service?
2011/08/16
[ "https://Stackoverflow.com/questions/7073557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186608/" ]
The Windows NT Resource Kit introduced the [Srvany.exe command-line utility](http://support.microsoft.com/kb/137890), which can be used to start any Windows NT/2000/2003 application as a service. You can download Srvany.exe [here](http://www.microsoft.com/download/en/details.aspx?id=17657).
You can create a startup script and globally apply it to your machines via group policy - just add it via gpedit.msc: ![Add startup script via group policy](https://i.stack.imgur.com/hGJM4.png)
7,073,557
Question: Is there a way to make a program run with out logging in that doesn't involve the long painful task of creating a windows service, or is there an easy way to make a simple service? --- Info: I'm working on a little project for college which is a simple distributed processing program. I'm going to harness the computers on campus that are currently sitting completely idle and make my own little super computer. but to do this I need the client running on my target machines. Through a little mucking around on the internet I find that what I need is a service, I also find that this isn't something quite as simple as making a scheduled task or dropping a .bat file into the start up folder. I don't need a lot. if I could just get it to call "python cClient.py" i'm completely set. Is there an easy way to do this? like adding a key in the registry some where? or do I have to go through the whole song and dance ritual that microsoft has made for setting up a service?
2011/08/16
[ "https://Stackoverflow.com/questions/7073557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186608/" ]
If you already have the executable you wish to run as a service you can use "sc" built into the OS already. Microsoft details the procedure here: <http://support.microsoft.com/kb/251192> ``` example: sc create "My Service" c:\temp\executable.exe ``` > > C:\Users\somebody>sc create > > > ``` DESCRIPTION: Creates a service entry in the registry and Service Database. USAGE: sc <server> create [service name] [binPath= ] <option1> <option2>... OPTIONS: NOTE: The option name includes the equal sign. A space is required between the equal sign and the value. type= <own|share|interact|kernel|filesys|rec> (default = own) start= <boot|system|auto|demand|disabled|delayed-auto> (default = demand) error= <normal|severe|critical|ignore> (default = normal) binPath= <BinaryPathName> group= <LoadOrderGroup> tag= <yes|no> depend= <Dependencies(separated by / (forward slash))> obj= <AccountName|ObjectName> (default = LocalSystem) DisplayName= <display name> password= <password> ```
Can you [schedule a task](http://windows.microsoft.com/en-US/windows7/schedule-a-task)? More info [here](http://technet.microsoft.com/en-us/library/cc770904.aspx).
7,073,557
Question: Is there a way to make a program run with out logging in that doesn't involve the long painful task of creating a windows service, or is there an easy way to make a simple service? --- Info: I'm working on a little project for college which is a simple distributed processing program. I'm going to harness the computers on campus that are currently sitting completely idle and make my own little super computer. but to do this I need the client running on my target machines. Through a little mucking around on the internet I find that what I need is a service, I also find that this isn't something quite as simple as making a scheduled task or dropping a .bat file into the start up folder. I don't need a lot. if I could just get it to call "python cClient.py" i'm completely set. Is there an easy way to do this? like adding a key in the registry some where? or do I have to go through the whole song and dance ritual that microsoft has made for setting up a service?
2011/08/16
[ "https://Stackoverflow.com/questions/7073557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186608/" ]
If you already have the executable you wish to run as a service you can use "sc" built into the OS already. Microsoft details the procedure here: <http://support.microsoft.com/kb/251192> ``` example: sc create "My Service" c:\temp\executable.exe ``` > > C:\Users\somebody>sc create > > > ``` DESCRIPTION: Creates a service entry in the registry and Service Database. USAGE: sc <server> create [service name] [binPath= ] <option1> <option2>... OPTIONS: NOTE: The option name includes the equal sign. A space is required between the equal sign and the value. type= <own|share|interact|kernel|filesys|rec> (default = own) start= <boot|system|auto|demand|disabled|delayed-auto> (default = demand) error= <normal|severe|critical|ignore> (default = normal) binPath= <BinaryPathName> group= <LoadOrderGroup> tag= <yes|no> depend= <Dependencies(separated by / (forward slash))> obj= <AccountName|ObjectName> (default = LocalSystem) DisplayName= <display name> password= <password> ```
You can create a startup script and globally apply it to your machines via group policy - just add it via gpedit.msc: ![Add startup script via group policy](https://i.stack.imgur.com/hGJM4.png)
26,044,173
I made a program in python which allows you to type commands (e.g: if you type clock, it shows you the date and time). But, I want it to be fullscreen. The problem is that my software doesnt have gui and I dont want it to so that probably means that I wont be using tkinter or pygame. Can some of you write a whole 'hello world' program in fullscreen for me? What I am aiming for is for my program to look a bit like ms-dos. Any help??? By the way, im very new to python (approximately 4 weeks). NOTE: I have python 3.4.1
2014/09/25
[ "https://Stackoverflow.com/questions/26044173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4061311/" ]
Since Vista, cmd.exe can no longer go to full-screen mode. You'll need to implement a full-screen console emulator yourself or look for another existing solution. E.g. [ConEmu](http://www.hanselman.com/blog/conemuthewindowsterminalconsolepromptwevebeenwaitingfor.aspx) appears to be able to do it.
Solution -------- Use your Operating System services to configure parameters. ``` <_aMouseRightClick_>->[Properties]->[Layout] ``` Kindly notice, that some of the `python` interpreter process window parameters are given in [char]-s, while some other in [px]: ``` size.Width [char]-s size.Height[char]-s loc.X [px] loc.Y [px] ``` So adjust these values so as to please your intentions. ![Settings before pseudo-FullScreenMode...](https://i.stack.imgur.com/YukIf.jpg) You may set negative values for `[loc.X, loc.Y]` to move/hide window edges "outside" the screen left/top edges
40,265,591
I have a data frame that in which every row represents a day of the week, and every column represents the serial number of an internet-connected device that failed to communicate with the server on that day. I am trying to get a Series of serial numbers that have failed to communicate for a full week. The code block: ``` counts = df.stack().value_counts() seven_day = counts[counts == 7] for a in seven_day: print(a) ``` The problem is that nothing is printed. What I want is a list of the serial numbers, and not the counts themselves. This question is a follow-up from: [Python Pandas -- Determine if Values in Column 0 Are Repeated in Each Subsequent Column](https://stackoverflow.com/questions/40244094/python-pandas-determine-if-values-in-column-0-are-repeated-in-each-subsequent)
2016/10/26
[ "https://Stackoverflow.com/questions/40265591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3285817/" ]
You could try something like this, if you pass in the name of the controller as a string. This solution assumes that your models are using `ActiveRecord` prior to rails 5 where `ApplicationRecord` was used to define models; in that case just switch `ActiveRecord::Base` with `ApplicationRecord`. Also if you have models that are plain old ruby objects (POROs), then this wont work for them. ``` def has_model?(controller_klass) begin class_string = controller_klass.to_s.gsub('Controller', '').singularize class_instance = class_string.constantize.new return class_instance.class.ancestors.include? ActiveRecord::Base rescue NameError => e return false end end ```
This method doesn't rely on exceptions, and works with input as Class or String. It should work for any Rails version : ``` def has_model?(controller_klass) all_models = ActiveRecord::Base.descendants.map(&:to_s) model_klass_string = controller_klass.to_s.sub(/Controller$/,'').singularize all_models.include?(model_klass_string) end ``` Note : you need to set ``` config.eager_load = true ``` in > > config/environments/development.rb > > > If you have non ActiveRecord models, you can ignore the previous note and use : ``` all_models = Dir[File.join(Rails.root,"app/models", "**","*.rb")].map{|f| File.basename(f,'.rb').camelize} ```
66,942,621
Im attempting to launch a python script from my Java program - The python script listens for socket connections from the Java program and responds with data. In order to do this I have attempted to use the ProcessBuilder API to: 1. activate a python virtualenv (located in my working directory) 2. run my python script predictprobability.py such that it starts listening for connections from my java program. this is what I have so far: ``` public class MLClassifierProcess{ //bash location //activate python venv //python interpreter //script final String[] command_to_run = new String[] { "/bin/bash", "-c", "/env/bin/activate;", "/env/bin/python","predictprobability.py;" }; public void startML(){ ProcessBuilder builder = new ProcessBuilder(command_to_run); Process pr = null; try { pr = builder.start(); } catch (IOException ioException) { System.out.println("error"); } } public static void main(String[] args){ MLClassifierProcess p = new MLClassifierProcess(); p.startML(); } } ``` however running the main function terminates straight away, when the script predictprobability.py should continue to run indefinitely. I'm new to the ProcessBuilder API so any pointers on how to proceed would be greatly appreciated
2021/04/04
[ "https://Stackoverflow.com/questions/66942621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15539237/" ]
If your Java program exits, the Python process you launched will exit as well as child processes are killed when a parent process dies unless they have been detached from that process. If you want your Java program to keep running until the Python program has completed execution, then you need to have the Java code wait appropriately. Here's how to have it do so: ``` public class MLClassifierProcess{ //bash location //activate python venv //python interpreter //script final String[] command_to_run = new String[] { "/bin/bash", "-c", "/env/bin/activate;", "/env/bin/python","predictprobability.py;" }; public Process startML(){ ProcessBuilder builder = new ProcessBuilder(command_to_run); Process pr = null; try { pr = builder.start(); } catch (IOException ioException) { System.out.println("error"); } return pr; } public static void main(String[] args){ MLClassifierProcess p = new MLClassifierProcess(); Process pr = p.startML(); if (pr != null) pr.waitFor(); } } ```
In the end the solution was simple: ``` Process process = Runtime.getRuntime().exec("<path/to/venv/python_interpreter> "+"path/to/scripytorun.py) ``` In my case the succcessful command was ``` Process process = Runtime.getRuntime().exec( System.getProperty("user.dir")+"/env/bin/python "+System.getProperty("user.dir")+"/predictprobability.py"); process.waitFor(); ``` @CryptoFool was right to point out that the absolute path to resources is needed, hence the `System.getProperty("user.dir")` prepended to the relative paths
51,783,232
I am using python regular expressions. I want all colon separated values in a line. e.g. ``` input = 'a:b c:d e:f' expected_output = [('a','b'), ('c', 'd'), ('e', 'f')] ``` But when I do ``` >>> re.findall('(.*)\s?:\s?(.*)','a:b c:d') ``` I get ``` [('a:b c', 'd')] ``` I have also tried ``` >>> re.findall('(.*)\s?:\s?(.*)[\s$]','a:b c:d') [('a', 'b')] ```
2018/08/10
[ "https://Stackoverflow.com/questions/51783232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1217998/" ]
Use split instead of regex, also avoid giving variable name like keywords : ``` inpt = 'a:b c:d e:f' k= [tuple(i.split(':')) for i in inpt.split()] print(k) # [('a', 'b'), ('c', 'd'), ('e', 'f')] ```
The easiest way using `list comprehension` and `split` : ``` [tuple(ele.split(':')) for ele in input.split(' ')] ``` #driver values : ``` IN : input = 'a:b c:d e:f' OUT : [('a', 'b'), ('c', 'd'), ('e', 'f')] ```
51,783,232
I am using python regular expressions. I want all colon separated values in a line. e.g. ``` input = 'a:b c:d e:f' expected_output = [('a','b'), ('c', 'd'), ('e', 'f')] ``` But when I do ``` >>> re.findall('(.*)\s?:\s?(.*)','a:b c:d') ``` I get ``` [('a:b c', 'd')] ``` I have also tried ``` >>> re.findall('(.*)\s?:\s?(.*)[\s$]','a:b c:d') [('a', 'b')] ```
2018/08/10
[ "https://Stackoverflow.com/questions/51783232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1217998/" ]
The following code works for me: ``` inpt = 'a:b c:d e:f' re.findall('(\S+):(\S+)',inpt) ``` Output: ``` [('a', 'b'), ('c', 'd'), ('e', 'f')] ```
Use split instead of regex, also avoid giving variable name like keywords : ``` inpt = 'a:b c:d e:f' k= [tuple(i.split(':')) for i in inpt.split()] print(k) # [('a', 'b'), ('c', 'd'), ('e', 'f')] ```
51,783,232
I am using python regular expressions. I want all colon separated values in a line. e.g. ``` input = 'a:b c:d e:f' expected_output = [('a','b'), ('c', 'd'), ('e', 'f')] ``` But when I do ``` >>> re.findall('(.*)\s?:\s?(.*)','a:b c:d') ``` I get ``` [('a:b c', 'd')] ``` I have also tried ``` >>> re.findall('(.*)\s?:\s?(.*)[\s$]','a:b c:d') [('a', 'b')] ```
2018/08/10
[ "https://Stackoverflow.com/questions/51783232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1217998/" ]
Use split instead of regex, also avoid giving variable name like keywords : ``` inpt = 'a:b c:d e:f' k= [tuple(i.split(':')) for i in inpt.split()] print(k) # [('a', 'b'), ('c', 'd'), ('e', 'f')] ```
You may use ``` list(map(lambda x: tuple(x.split(':')), input.split())) ``` where `input.split()` is ``` >>> input.split() ['a:b', 'c:d', 'e:f'] ``` `lambda x: tuple(x.split(':'))` is function to convert string to tuple `'a:b' => (a, b)` `map` applies above function to all list elements and returns a map object (in Python 3) and this is converted to list using `list` Result ``` >>> list(map(lambda x: tuple(x.split(':')), input.split())) [('a', 'b'), ('c', 'd'), ('e', 'f')] ```
51,783,232
I am using python regular expressions. I want all colon separated values in a line. e.g. ``` input = 'a:b c:d e:f' expected_output = [('a','b'), ('c', 'd'), ('e', 'f')] ``` But when I do ``` >>> re.findall('(.*)\s?:\s?(.*)','a:b c:d') ``` I get ``` [('a:b c', 'd')] ``` I have also tried ``` >>> re.findall('(.*)\s?:\s?(.*)[\s$]','a:b c:d') [('a', 'b')] ```
2018/08/10
[ "https://Stackoverflow.com/questions/51783232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1217998/" ]
The following code works for me: ``` inpt = 'a:b c:d e:f' re.findall('(\S+):(\S+)',inpt) ``` Output: ``` [('a', 'b'), ('c', 'd'), ('e', 'f')] ```
The easiest way using `list comprehension` and `split` : ``` [tuple(ele.split(':')) for ele in input.split(' ')] ``` #driver values : ``` IN : input = 'a:b c:d e:f' OUT : [('a', 'b'), ('c', 'd'), ('e', 'f')] ```
51,783,232
I am using python regular expressions. I want all colon separated values in a line. e.g. ``` input = 'a:b c:d e:f' expected_output = [('a','b'), ('c', 'd'), ('e', 'f')] ``` But when I do ``` >>> re.findall('(.*)\s?:\s?(.*)','a:b c:d') ``` I get ``` [('a:b c', 'd')] ``` I have also tried ``` >>> re.findall('(.*)\s?:\s?(.*)[\s$]','a:b c:d') [('a', 'b')] ```
2018/08/10
[ "https://Stackoverflow.com/questions/51783232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1217998/" ]
The following code works for me: ``` inpt = 'a:b c:d e:f' re.findall('(\S+):(\S+)',inpt) ``` Output: ``` [('a', 'b'), ('c', 'd'), ('e', 'f')] ```
You may use ``` list(map(lambda x: tuple(x.split(':')), input.split())) ``` where `input.split()` is ``` >>> input.split() ['a:b', 'c:d', 'e:f'] ``` `lambda x: tuple(x.split(':'))` is function to convert string to tuple `'a:b' => (a, b)` `map` applies above function to all list elements and returns a map object (in Python 3) and this is converted to list using `list` Result ``` >>> list(map(lambda x: tuple(x.split(':')), input.split())) [('a', 'b'), ('c', 'd'), ('e', 'f')] ```
36,563,002
I have a python code. I need to execute the python script from my c# program. After searching a bit about this, I came to know that there is mainly two ways of executing a python script from c#. One by using 'Process' command and the other by using Iron Python. My question might seem dumb, is there any other way through which I can execute a python script? To be more specific, can I create a class , lets say 'Python' in c# and a member function 'execute\_script' which doesn't use any api like iron python or doesn't create a process for executing the script, so that if call 'execute\_scipt(mypythonprogram.py)' , my script gets executed. Sorry if this seems dumb. If this is possible, please do help me. Thanks in advance.
2016/04/12
[ "https://Stackoverflow.com/questions/36563002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5743035/" ]
The constants you're looking for are not called `LONG_LONG_...`. Check your `limits.h` header. Most likely you're after `ULLONG_MAX`, `LLONG_MAX`, etc.
> > Why do the integers and long integers have the same limits? Shouldn't the long integers have a larger range of values? > > > You have stepped into one of the hallmarks of the C language - its adaptability. C defines the range of `int` to be at least as wide as `short` and the range of `long` to be at least as wide as `int`. All have minimum ranges. Rather than precisely defined the range of `short, int, long`, C opted for versatility. On OP's platform, the range of `int` matches the range of `long` (32-bit). On many embedded processors of 2016 (and home computers of the 70s,80s), the range of `int` matches the range of `short` (16-bit). On some platforms (64-bit) the range of `int` exceeds `short`, and *narrower than* `long`. So directly to OP's question: **`int` does not always have the same range as `long`.** The trick is that `int` is not just another rung of the `singed char, short, int, long, long long` ladder. It is *the* integer type. Given the *usual integer promotions*, all narrows types promote to `int`. `int` is *often* the processor's native bit width. Most code has been written with `int` as 32-bit and also a large percentage as 16-bit. With 64-bit processors, having `int` as 64-bit is possible, but that leaves only 2 standard type for `signed char, short` for 8, 16 and 32-bit. Going forward, simple count on `signed char` range `<=` the `short` range, `short` range `<=` the `int` range, **`int` range `<=` the `long` range**, etc. Also that `signed char` is at least 8-bit, `short, int` at least 16-bit, `long` at least 32-bit, `long long` at least 64-bit. If code needs explicit widths, use `int8_t`, `int16_t`, etc. The fact that C is used 40+ years later attests that this versatility has/had merit. [Discussion omits unsigned types, `_Bool_t` and `char` for brevity. Also omitted are rare non-power-of-2 types (9, 18, 24, 36 etc.)]
36,563,002
I have a python code. I need to execute the python script from my c# program. After searching a bit about this, I came to know that there is mainly two ways of executing a python script from c#. One by using 'Process' command and the other by using Iron Python. My question might seem dumb, is there any other way through which I can execute a python script? To be more specific, can I create a class , lets say 'Python' in c# and a member function 'execute\_script' which doesn't use any api like iron python or doesn't create a process for executing the script, so that if call 'execute\_scipt(mypythonprogram.py)' , my script gets executed. Sorry if this seems dumb. If this is possible, please do help me. Thanks in advance.
2016/04/12
[ "https://Stackoverflow.com/questions/36563002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5743035/" ]
The constants you're looking for are not called `LONG_LONG_...`. Check your `limits.h` header. Most likely you're after `ULLONG_MAX`, `LLONG_MAX`, etc.
Besides limits.h on a system with specific implementation, also check out what the C standard defines the limits of the various integers: The values given below shall be replaced by constant expressions suitable for use in #if preprocessing directives. Moreover, except for CHAR\_BIT and MB\_LEN\_MAX, the following shall be replaced by expressions that have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Their implementation-defined values shall be equal or greater in magnitude ``` (absolute value) to those shown, with the same sign. -- number of bits for smallest object that is not a bit-field (byte) CHAR_BIT 8 -- minimum value for an object of type signed char SCHAR_MIN -127 // -(27 - 1) -- maximum value for an object of type signed char SCHAR_MAX +127 // 27 - 1 -- maximum value for an object of type unsigned char UCHAR_MAX 255 // 28 - 1 -- minimum value for an object of type char CHAR_MIN see below -- maximum value for an object of type char CHAR_MAX see below -- maximum number of bytes in a multibyte character, for any supported locale MB_LEN_MAX 1 -- minimum value for an object of type short int SHRT_MIN -32767 // -(215 - 1) -- maximum value for an object of type short int SHRT_MAX +32767 // 215 - 1 -- maximum value for an object of type unsigned short int USHRT_MAX 65535 // 216 - 1 -- minimum value for an object of type int INT_MIN -32767 // -(215 - 1) -- maximum value for an object of type int INT_MAX +32767 // 215 - 1 -- maximum value for an object of type unsigned int UINT_MAX 65535 // 216 - 1 -- minimum value for an object of type long int LONG_MIN -2147483647 // -(231 - 1) -- maximum value for an object of type long int LONG_MAX +2147483647 // 231 - 1 -- maximum value for an object of type unsigned long int ULONG_MAX 4294967295 // 232 - 1 -- minimum value for an object of type long long int LLONG_MIN -9223372036854775807 // -(263 - 1) -- maximum value for an object of type long long int LLONG_MAX +9223372036854775807 // 263 - 1 -- maximum value for an object of type unsigned long long int ULLONG_MAX 18446744073709551615 // 264 - 1 ``` From <http://www.iso-9899.info/n1570.html#5.2.4.2.1>
36,563,002
I have a python code. I need to execute the python script from my c# program. After searching a bit about this, I came to know that there is mainly two ways of executing a python script from c#. One by using 'Process' command and the other by using Iron Python. My question might seem dumb, is there any other way through which I can execute a python script? To be more specific, can I create a class , lets say 'Python' in c# and a member function 'execute\_script' which doesn't use any api like iron python or doesn't create a process for executing the script, so that if call 'execute\_scipt(mypythonprogram.py)' , my script gets executed. Sorry if this seems dumb. If this is possible, please do help me. Thanks in advance.
2016/04/12
[ "https://Stackoverflow.com/questions/36563002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5743035/" ]
The constants are `LLONG_MAX`, `ULLONG_MAX`, etc. As to why `int` and `long int` have the same value, blame the C standard: it does not define a fixed number of bits for each data type, only the minimum number of bits: * `int` must be at least 16 bits * `long int` must be at least 32 bits * `long long int` must be at least 64 bits The exact number of bits differ from OS to OS. ``` #include <stdio.h> #include <limits.h> int main() { printf("INTEGER min: %d\n", INT_MIN); printf("INTEGER max: %d\n\n", INT_MAX); printf("UNSIGNED INTEGER max: %u\n\n", UINT_MAX); printf("LONG INTEGER min: %ld\n", LONG_MIN); printf("LONG INTEGER max: %ld\n\n", LONG_MAX); printf("LONG LONG INTEGER min: %lld\n", LLONG_MIN); printf("LONG LONG INTEGER max: %lld\n\n", LLONG_MAX); printf("UNSIGNED LONG INTEGER max: %lu\n\n", ULONG_MAX); printf("UNSIGNED LONG LONG INTEGER max: %llu\n", ULLONG_MAX); printf("\n"); return 0; } ``` On my Mac OS X, 64-bit, that prints: ``` INTEGER min: -2147483648 INTEGER max: 2147483647 UNSIGNED INTEGER max: 4294967295 LONG INTEGER min: -9223372036854775808 LONG INTEGER max: 9223372036854775807 LONG LONG INTEGER min: -9223372036854775808 LONG LONG INTEGER max: 9223372036854775807 UNSIGNED LONG INTEGER max: 18446744073709551615 UNSIGNED LONG LONG INTEGER max: 18446744073709551615 ``` --- **Edit:** if you want to write portable code and have fixed-width integers, use `stdint.h`: ``` #include <stdint.h> printf("int64_t max : %lld\n\n", INT64_MAX); // 9223372036854775807 printf("uint64_t max: %llu\n\n", UINT64_MAX); // 18446744073709551615 ```
> > Why do the integers and long integers have the same limits? Shouldn't the long integers have a larger range of values? > > > You have stepped into one of the hallmarks of the C language - its adaptability. C defines the range of `int` to be at least as wide as `short` and the range of `long` to be at least as wide as `int`. All have minimum ranges. Rather than precisely defined the range of `short, int, long`, C opted for versatility. On OP's platform, the range of `int` matches the range of `long` (32-bit). On many embedded processors of 2016 (and home computers of the 70s,80s), the range of `int` matches the range of `short` (16-bit). On some platforms (64-bit) the range of `int` exceeds `short`, and *narrower than* `long`. So directly to OP's question: **`int` does not always have the same range as `long`.** The trick is that `int` is not just another rung of the `singed char, short, int, long, long long` ladder. It is *the* integer type. Given the *usual integer promotions*, all narrows types promote to `int`. `int` is *often* the processor's native bit width. Most code has been written with `int` as 32-bit and also a large percentage as 16-bit. With 64-bit processors, having `int` as 64-bit is possible, but that leaves only 2 standard type for `signed char, short` for 8, 16 and 32-bit. Going forward, simple count on `signed char` range `<=` the `short` range, `short` range `<=` the `int` range, **`int` range `<=` the `long` range**, etc. Also that `signed char` is at least 8-bit, `short, int` at least 16-bit, `long` at least 32-bit, `long long` at least 64-bit. If code needs explicit widths, use `int8_t`, `int16_t`, etc. The fact that C is used 40+ years later attests that this versatility has/had merit. [Discussion omits unsigned types, `_Bool_t` and `char` for brevity. Also omitted are rare non-power-of-2 types (9, 18, 24, 36 etc.)]
36,563,002
I have a python code. I need to execute the python script from my c# program. After searching a bit about this, I came to know that there is mainly two ways of executing a python script from c#. One by using 'Process' command and the other by using Iron Python. My question might seem dumb, is there any other way through which I can execute a python script? To be more specific, can I create a class , lets say 'Python' in c# and a member function 'execute\_script' which doesn't use any api like iron python or doesn't create a process for executing the script, so that if call 'execute\_scipt(mypythonprogram.py)' , my script gets executed. Sorry if this seems dumb. If this is possible, please do help me. Thanks in advance.
2016/04/12
[ "https://Stackoverflow.com/questions/36563002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5743035/" ]
The constants are `LLONG_MAX`, `ULLONG_MAX`, etc. As to why `int` and `long int` have the same value, blame the C standard: it does not define a fixed number of bits for each data type, only the minimum number of bits: * `int` must be at least 16 bits * `long int` must be at least 32 bits * `long long int` must be at least 64 bits The exact number of bits differ from OS to OS. ``` #include <stdio.h> #include <limits.h> int main() { printf("INTEGER min: %d\n", INT_MIN); printf("INTEGER max: %d\n\n", INT_MAX); printf("UNSIGNED INTEGER max: %u\n\n", UINT_MAX); printf("LONG INTEGER min: %ld\n", LONG_MIN); printf("LONG INTEGER max: %ld\n\n", LONG_MAX); printf("LONG LONG INTEGER min: %lld\n", LLONG_MIN); printf("LONG LONG INTEGER max: %lld\n\n", LLONG_MAX); printf("UNSIGNED LONG INTEGER max: %lu\n\n", ULONG_MAX); printf("UNSIGNED LONG LONG INTEGER max: %llu\n", ULLONG_MAX); printf("\n"); return 0; } ``` On my Mac OS X, 64-bit, that prints: ``` INTEGER min: -2147483648 INTEGER max: 2147483647 UNSIGNED INTEGER max: 4294967295 LONG INTEGER min: -9223372036854775808 LONG INTEGER max: 9223372036854775807 LONG LONG INTEGER min: -9223372036854775808 LONG LONG INTEGER max: 9223372036854775807 UNSIGNED LONG INTEGER max: 18446744073709551615 UNSIGNED LONG LONG INTEGER max: 18446744073709551615 ``` --- **Edit:** if you want to write portable code and have fixed-width integers, use `stdint.h`: ``` #include <stdint.h> printf("int64_t max : %lld\n\n", INT64_MAX); // 9223372036854775807 printf("uint64_t max: %llu\n\n", UINT64_MAX); // 18446744073709551615 ```
Besides limits.h on a system with specific implementation, also check out what the C standard defines the limits of the various integers: The values given below shall be replaced by constant expressions suitable for use in #if preprocessing directives. Moreover, except for CHAR\_BIT and MB\_LEN\_MAX, the following shall be replaced by expressions that have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Their implementation-defined values shall be equal or greater in magnitude ``` (absolute value) to those shown, with the same sign. -- number of bits for smallest object that is not a bit-field (byte) CHAR_BIT 8 -- minimum value for an object of type signed char SCHAR_MIN -127 // -(27 - 1) -- maximum value for an object of type signed char SCHAR_MAX +127 // 27 - 1 -- maximum value for an object of type unsigned char UCHAR_MAX 255 // 28 - 1 -- minimum value for an object of type char CHAR_MIN see below -- maximum value for an object of type char CHAR_MAX see below -- maximum number of bytes in a multibyte character, for any supported locale MB_LEN_MAX 1 -- minimum value for an object of type short int SHRT_MIN -32767 // -(215 - 1) -- maximum value for an object of type short int SHRT_MAX +32767 // 215 - 1 -- maximum value for an object of type unsigned short int USHRT_MAX 65535 // 216 - 1 -- minimum value for an object of type int INT_MIN -32767 // -(215 - 1) -- maximum value for an object of type int INT_MAX +32767 // 215 - 1 -- maximum value for an object of type unsigned int UINT_MAX 65535 // 216 - 1 -- minimum value for an object of type long int LONG_MIN -2147483647 // -(231 - 1) -- maximum value for an object of type long int LONG_MAX +2147483647 // 231 - 1 -- maximum value for an object of type unsigned long int ULONG_MAX 4294967295 // 232 - 1 -- minimum value for an object of type long long int LLONG_MIN -9223372036854775807 // -(263 - 1) -- maximum value for an object of type long long int LLONG_MAX +9223372036854775807 // 263 - 1 -- maximum value for an object of type unsigned long long int ULLONG_MAX 18446744073709551615 // 264 - 1 ``` From <http://www.iso-9899.info/n1570.html#5.2.4.2.1>
36,563,002
I have a python code. I need to execute the python script from my c# program. After searching a bit about this, I came to know that there is mainly two ways of executing a python script from c#. One by using 'Process' command and the other by using Iron Python. My question might seem dumb, is there any other way through which I can execute a python script? To be more specific, can I create a class , lets say 'Python' in c# and a member function 'execute\_script' which doesn't use any api like iron python or doesn't create a process for executing the script, so that if call 'execute\_scipt(mypythonprogram.py)' , my script gets executed. Sorry if this seems dumb. If this is possible, please do help me. Thanks in advance.
2016/04/12
[ "https://Stackoverflow.com/questions/36563002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5743035/" ]
> > Why do the integers and long integers have the same limits? Shouldn't the long integers have a larger range of values? > > > You have stepped into one of the hallmarks of the C language - its adaptability. C defines the range of `int` to be at least as wide as `short` and the range of `long` to be at least as wide as `int`. All have minimum ranges. Rather than precisely defined the range of `short, int, long`, C opted for versatility. On OP's platform, the range of `int` matches the range of `long` (32-bit). On many embedded processors of 2016 (and home computers of the 70s,80s), the range of `int` matches the range of `short` (16-bit). On some platforms (64-bit) the range of `int` exceeds `short`, and *narrower than* `long`. So directly to OP's question: **`int` does not always have the same range as `long`.** The trick is that `int` is not just another rung of the `singed char, short, int, long, long long` ladder. It is *the* integer type. Given the *usual integer promotions*, all narrows types promote to `int`. `int` is *often* the processor's native bit width. Most code has been written with `int` as 32-bit and also a large percentage as 16-bit. With 64-bit processors, having `int` as 64-bit is possible, but that leaves only 2 standard type for `signed char, short` for 8, 16 and 32-bit. Going forward, simple count on `signed char` range `<=` the `short` range, `short` range `<=` the `int` range, **`int` range `<=` the `long` range**, etc. Also that `signed char` is at least 8-bit, `short, int` at least 16-bit, `long` at least 32-bit, `long long` at least 64-bit. If code needs explicit widths, use `int8_t`, `int16_t`, etc. The fact that C is used 40+ years later attests that this versatility has/had merit. [Discussion omits unsigned types, `_Bool_t` and `char` for brevity. Also omitted are rare non-power-of-2 types (9, 18, 24, 36 etc.)]
Besides limits.h on a system with specific implementation, also check out what the C standard defines the limits of the various integers: The values given below shall be replaced by constant expressions suitable for use in #if preprocessing directives. Moreover, except for CHAR\_BIT and MB\_LEN\_MAX, the following shall be replaced by expressions that have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Their implementation-defined values shall be equal or greater in magnitude ``` (absolute value) to those shown, with the same sign. -- number of bits for smallest object that is not a bit-field (byte) CHAR_BIT 8 -- minimum value for an object of type signed char SCHAR_MIN -127 // -(27 - 1) -- maximum value for an object of type signed char SCHAR_MAX +127 // 27 - 1 -- maximum value for an object of type unsigned char UCHAR_MAX 255 // 28 - 1 -- minimum value for an object of type char CHAR_MIN see below -- maximum value for an object of type char CHAR_MAX see below -- maximum number of bytes in a multibyte character, for any supported locale MB_LEN_MAX 1 -- minimum value for an object of type short int SHRT_MIN -32767 // -(215 - 1) -- maximum value for an object of type short int SHRT_MAX +32767 // 215 - 1 -- maximum value for an object of type unsigned short int USHRT_MAX 65535 // 216 - 1 -- minimum value for an object of type int INT_MIN -32767 // -(215 - 1) -- maximum value for an object of type int INT_MAX +32767 // 215 - 1 -- maximum value for an object of type unsigned int UINT_MAX 65535 // 216 - 1 -- minimum value for an object of type long int LONG_MIN -2147483647 // -(231 - 1) -- maximum value for an object of type long int LONG_MAX +2147483647 // 231 - 1 -- maximum value for an object of type unsigned long int ULONG_MAX 4294967295 // 232 - 1 -- minimum value for an object of type long long int LLONG_MIN -9223372036854775807 // -(263 - 1) -- maximum value for an object of type long long int LLONG_MAX +9223372036854775807 // 263 - 1 -- maximum value for an object of type unsigned long long int ULLONG_MAX 18446744073709551615 // 264 - 1 ``` From <http://www.iso-9899.info/n1570.html#5.2.4.2.1>
19,940,549
I am using the [NakedMUD](http://homepages.uc.edu/~hollisgf/nakedmud.html) code base for a project. I am running into an issue in importing modules. In \*.py (Python files) they import modules with the following syntax: ``` import mudsys, mud, socket, char, hooks ``` and in C to embed Python they use: ``` mudmod = PyImport_ImportModule("char"); ``` Both of these methods seem to indicate to me that is some mudsys.py, mud.py ... files somewhere in a path findable by Python. I can not locate them. I am wondering where I might look to find how they are renaming the module other then the filename. I am unsure what else would be required to locate this. The issue is that the second import `PyImport_ImportModule()` in one case is not finding the modules and they reference a `null` pointer returned by this. The Python documentation mentions "[Changed in version 2.6: Always uses absolute imports.](http://docs.python.org/2/c-api/import.html)" and I am suspicious that this is the part of the issue. Of note, they override some builtin functions of Python which may also be affecting this in `__restricted_builtin__.py` and `__restricted_builtin_funcs__.py`. ``` ################################################################################ # # __restricted_builtin_funcs__.py # # This contains functions used by __restricted_builtin__ to do certain # potentially dangerous actions in a safe mode # ################################################################################ import __builtin__ def r_import(name, globals = {}, locals = {}, fromlist = []): '''Restricted __import__ only allows importing of specific modules''' ok_modules = ("mud", "obj", "char", "room", "exit", "account", "mudsock", "event", "action", "random", "traceback", "utils", "__restricted_builtin__") if name not in ok_modules: raise ImportError, "Untrusted module, %s" % name return __builtin__.__import__(name, globals, locals, fromlist) def r_open(file, mode = "r", buf = -1): if mode not in ('r', 'rb'): raise IOError, "can't open files for writing in restricted mode" return open(file, mode, buf) def r_exec(code): """exec is disabled in restricted mode""" raise NotImplementedError,"execution of code is disabled" def r_eval(code): """eval is disabled in restricted mode""" raise NotImplementedError,"evaluating code is disabled" def r_execfile(file): """executing files is disabled in restricted mode""" raise NotImplementedError,"executing files is disabled" def r_reload(module): """reloading modules is disabled in restricted mode""" raise NotImplementedError, "reloading modules is disabled" def r_unload(module): """unloading modules is disabled in restricted mode""" raise NotImplementedError, "unloading modules is disabled" ``` and ``` ################################################################################ # # __restricted_builtin__.py # # This module is designed to replace the __builtin__, but overwrite many of the # functions that would allow an unscrupulous scripter to take malicious actions # ################################################################################ from __builtin__ import * from __restricted_builtin_funcs__ import r_import, r_open, r_execfile, r_eval, \ r_reload, r_exec, r_unload # override some dangerous functions with their safer versions __import__ = r_import execfile = r_execfile open = r_open eval = r_eval reload = r_reload ``` EDIT: `PyObject *sys = PyImport_ImportModule("sys");` is returning NULL as well.
2013/11/12
[ "https://Stackoverflow.com/questions/19940549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/583608/" ]
You may want to enable WCF Tracing and Message Logging, which will allow you to monitor/review communication to/from the WCF service and hopefully isolate the issue (which, based on the provided error message, may likely be a timeout issue.) The following links provide a good overview: <http://msdn.microsoft.com/en-us/library/ms733025.aspx> Regards,
adkSerenity and shambulator, Thank you. I found the problem. It turned out to be a buffer size. I was pretty sure it wasn't a timeout because the shortest timeout was set to one minute and I could reproduce the error in thirty seconds. I had been avoiding WCF Tracing and Message Logging because it was so intimidating. So much to read, so little time. ;-} When I generated the output at looked at it with the viewer, it might as well have been Martian. After studying it for a while in a fog, I finally get the impression that the loss of communication was not the fault of the service. Then the light bulb went on and I checked the client's config file. Sure enough, the MaxBufferSize was set to 65535, effectively cutting off the 70000 byte message. Thanks again for pointing me in the right direction.
12,993,175
I'm having a problem with python keyring after the installation. here are my steps: ``` $ python >>> import keyring >>> keyring.set_password('something','otherSomething','lotOfMoreSomethings') ``` and then throws this: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/keyring/core.py", line 42, in set_password _keyring_backend.set_password(service_name, username, password) File "/usr/local/lib/python2.6/dist-packages/keyring/backend.py", line 222, in set_password _, session = service_iface.OpenSession("plain", "") File "/usr/lib/pymodules/python2.6/dbus/proxies.py", line 68, in __call__ return self._proxy_method(*args, **keywords) File "/usr/lib/pymodules/python2.6/dbus/proxies.py", line 140, in __call__ **keywords) File "/usr/lib/pymodules/python2.6/dbus/connection.py", line 630, in call_blocking message, timeout) dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownMethod: Method "OpenSession" with signature "ss" on interface "org.freedesktop.Secret.Service" doesn't exist ``` i have installed keyring from [here](http://pypi.python.org/pypi/keyring) using ``` easy_install keyring ``` Do i do anything wrong?? There are any solution?? Edit: Also i've installed python-keyring and python-keyring-gnome from repos and just import like ``` >>> import gnome_keyring ``` and works.
2012/10/20
[ "https://Stackoverflow.com/questions/12993175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1715386/" ]
For each market where you have specific requirements due to market-specific licensing or legal issues, you can create a separate app in iTunes Connect and make it available for download only in the relevant market. And if you need to, this also allows you to provide a market-specific EULA. It's a big maintenance burden, but it would ensure that only users in a given market can access the app. Note that in XCode you can fairly easily build, deploy and publish multiple versions of your project built from different configurations (XCode calls this "Targets"), so you could still achieve this in a single codebase by simply adding some preprocessor definitions in the relevant target definitions and putting `#ifdef` in your code where you want differentiated logic.
A 3rd party app has no access whatsoever to any information about the user of the device or access to the iTunes account. There is no way to know the user's true country. At any given time, the device may not even be associated with any one person. An iPod touch, for example, may have no user logged into any iTunes account. The same device can ultimately be logged into one of several different accounts. All you have access to is the user's current GPS location (if the user allows your app to access that information) or their current locale. Basically, there is no way to do what you need. Of course you could prompt the user but obviously there is no way to verify this information.
38,156,681
I create a custom Authentication backends for my login system. Surely, the custom backends works when I try it in python shell. However, I got error when I run it in the server. The error says "The following fields do not exist in this model or are m2m fields: last\_login". Do I need include the last\_login field in customer model or Is there any other solution to solve the problem? Here is my sample code: ``` In my models.py class Customer(models.Model): yes_or_no = ((True, 'Yes'),(False, 'No')) male_or_female = ((True,'Male'),(False,'Female')) name = models.CharField(max_length=100) email = models.EmailField(max_length=100,blank = False, null = False) password = models.CharField(max_length=100) gender = models.BooleanField(default = True, choices = male_or_female) birthday = models.DateField(default =None,blank = False, null = False) created = models.DateTimeField(default=datetime.now, blank=True) _is_active = models.BooleanField(default = False,db_column="is_active") @property def is_active(self): return self._is_active # how to call setter method, how to pass value ? @is_active.setter def is_active(self,value): self._is_active = value def __str__(self): return self.name ``` In backends.py ``` from .models import Customer from django.conf import settings class CustomerAuthBackend(object): def authenticate(self, name=None, password=None): try: user = Customer.objects.get(name=name) if password == getattr(user,'password'): # Authentication success by returning the user user.is_active = True return user else: # Authentication fails if None is returned return None except Customer.DoesNotExist: return None def get_user(self, user_id): try: return Customer.objects.get(pk=user_id) except Customer.DoesNotExist: return None ``` In views.py ``` @login_required(login_url='/dataInfo/login/') def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(name=username,password=password) if user is not None: if user.is_active: login(request,user) #redirect to user profile print "suffcessful login!" return HttpResponseRedirect('/dataInfo/userprofile') else: # return a disable account return HttpResponse("User acount or password is incorrect") else: # Return an 'invalid login' error message. print "Invalid login details: {0}, {1}".format(username, password) # redirect to login page return HttpResponseRedirect('/dataInfo/login') else: login_form = LoginForm() return render_to_response('dataInfo/login.html', {'form': login_form}, context_instance=RequestContext(request)) ``` In setting.py ``` AUTHENTICATION_BACKENDS = ('dataInfo.backends.CustomerAuthBackend', 'django.contrib.auth.backends.ModelBackend',) ```
2016/07/02
[ "https://Stackoverflow.com/questions/38156681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5458894/" ]
This is happening because you are using django's [`login()`](https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.login) function to log the user in. Django's `login` function emits a signal named `user_logged_in` with the `user` instance you supplied as argument. [See `login()` source](https://docs.djangoproject.com/en/1.9/_modules/django/contrib/auth/#login). And this signal is listened in django's [`contrib.auth.models`](https://github.com/django/django/blob/09119dff14ad24d53ac0273e5cd2de24de0b0d81/django/contrib/auth/models.py#L19). It tries to update a field named `last_login` assuming that the user instance you have supplied is a subclass of django's default `AbstractUser` model. In order to fix this, you can do one of the following things: 1. Stop using the `login()` function shipped with django and create a custom one. 2. Disconnect the `user_logged_in` signal from `update_last_login` receiver. [Read how](https://docs.djangoproject.com/en/dev/topics/signals/#disconnecting-signals). 3. Add a field named `last_login` to your model 4. Extend your model from django's base auth models. [Read how](https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#specifying-a-custom-user-model)
Thanks, I defined a custom `login` method as follows to get through this issue in my automated tests in which I by default keep the signals off. Here's a working code example. ``` def login(client: Client, user: User) -> None: """ Disconnect the update_last_login signal and force_login as `user` Ref: https://stackoverflow.com/questions/38156681/error-about-django-custom-authentication-and-login Args: client: Django Test client instance to be used to login user: User object to be used to login """ user_logged_in.disconnect(receiver=update_last_login) client.force_login(user=user) user_logged_in.connect(receiver=update_last_login) ``` This in turn is used in tests as follows: ``` class TestSomething(TestCase): """ Scenarios to validate: .... """ @classmethod @factory.django.mute_signals(signals.pre_save, signals.post_save) def setUpTestData(cls): """ Helps keep tests execution time under control """ cls.client = Client() cls.content_type = 'application/json' def test_a_scenario(self): """ Scenario details... """ login(client=self.client, user=<User object>) response = self.client.post(...) ... ``` Hope it helps.
50,092,608
I've defined a helper method to load json from a string or file like so: ``` def get_json_from_string_or_file(obj): if type(obj) is str: return json.loads(obj) return json.load(obj) ``` When I try it with a file it fails on the `load` call with the following exception: ``` File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 291, in load **kw) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded ``` I have triple checked my json file and it is definitely not empty, it just has a simple foo bar key value mapping. Also, I'm feeding the json file into the method like so: `os.path.join(os.path.dirname(__file__), "..", "test.json")` Any idea whats going on here? EDIT: I changed my helper method to the following to fix up the mistakes addressed in the answers and comments and it's still not working, i'm getting the same error when I pass in an already open file. ``` def get_json_from_file(_file): if type(_file) is str: with open(_file) as json_file: return json.load(json_file) return json.load(_file) ``` EDIT #2: I FOUND THE PROBLEM! this error occurs if you call `json.load` on an open file twice in a row. It turns out that another part of my application had already got that file open. Here is some reproduction code: ``` with open("/test.json") as f: json.load(f) json.load(f) ```
2018/04/30
[ "https://Stackoverflow.com/questions/50092608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2155605/" ]
Following code works. ``` import os import json def get_json_from_string_or_file(obj): if type(obj) is str: return json.loads(obj) return json.load(obj) filename = os.path.join(os.path.dirname(__file__), "..", "test.json") with open(filename, 'r') as f: result = get_json_from_string_or_file(f) print(result) ``` `ValueError: No JSON object could be decoded` is reproduced when I passed the filename to the function, like `get_json_from_string_or_file(filename)`. --- ### 2nd version ``` import os import json def get_json_from_file(_file): if type(_file) is str: # <-- unnecessary if with open(_file) as json_file: return json.load(json_file) return json.load(_file) filename = os.path.join(os.path.dirname(__file__), "..", "test.json") result = get_json_from_file(filename) print(result) # python2: {u'foo': u'bar'} # python3: {'foo': 'bar'} ```
Sorry, I'd comment but I lack the rep. Can you paste a sample JSON file that doesn't work into a pastebin? I'll edit this into an answer after that if I can.
67,103,105
I'm trying to upload PDF-file in the Xero account using the python request library (POST method) and Xeros FilesAPI said "Requests must be formatted as multipart MIME" and have some required fields ([link](https://developer.xero.com/documentation/files-api/files#POST)) but I don't how to do that exactly...If I do GET-request I'm getting the list of files in the Xero account but having a problem while posting the file (POST-request)... My Code: ``` post_url = 'https://api.xero.com/files.xro/1.0/Files/' files = {'file': open('/home/mobin/PycharmProjects/s3toxero/data/in_test_upload.pdf', 'rb')} response = requests.post( post_url, headers={ 'Authorization': 'Bearer ' + new_tokens[0], 'Xero-tenant-id': xero_tenant_id, 'Accept': 'application/json', 'Content-type': 'multipart/form-data; boundary=JLQPFBPUP0', 'Content-Length': '1068', }, files=files, ) json_response = response.json() print(f'Uploading Responsoe ==> {json_response}') print(f'Uploading Responsoe ==> {response}') ``` Error Mesage/Response: ``` Uploading Responsoe ==> [{'type': 'Validation', 'title': 'Validation failure', 'detail': 'No file is was attached'}] Uploading Responsoe ==> <Response [400]> ```
2021/04/15
[ "https://Stackoverflow.com/questions/67103105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9025820/" ]
As I see you're improperly set the boundary. You set it in the headers but not tell to `requests` library to use custom boundary. Let me show you an example: ``` >>> import requests >>> post_url = 'https://api.xero.com/files.xro/1.0/Files/' >>> files = {'file': open('/tmp/test.txt', 'rb')} >>> headers = { ... 'Authorization': 'Bearer secret', ... 'Xero-tenant-id': '42', ... 'Accept': 'application/json', ... 'Content-type': 'multipart/form-data; boundary=JLQPFBPUP0', ... 'Content-Length': '1068', ... } >>> print(requests.Request('POST', post_url, files=files, headers=headers).prepare().body.decode('utf8')) --f3e21ca5e554dd96430f07bb7a0d0e77 Content-Disposition: form-data; name="file"; filename="test.txt" --f3e21ca5e554dd96430f07bb7a0d0e77-- ``` As you can see the real boundary (`f3e21ca5e554dd96430f07bb7a0d0e77`) is different from what was passed in the header (`JLQPFBPUP0`). You can actually directly use the requests module to controll boundary like this: Let's prepare a test file: ``` $ touch /tmp/test.txt $ echo 'Hello, World!' > /tmp/test.txt ``` Test it: ``` >>> import requests >>> post_url = 'https://api.xero.com/files.xro/1.0/Files/' >>> files = {'file': open('/tmp/test.txt', 'rb')} >>> headers = { ... 'Authorization': 'Bearer secret', ... 'Xero-tenant-id': '42', ... 'Accept': 'application/json', ... 'Content-Length': '1068', ... } >>> body, content_type = requests.models.RequestEncodingMixin._encode_files(files, {}) >>> headers['Content-type'] = content_type >>> print(requests.Request('POST', post_url, data=body, headers=headers).prepare().body.decode('utf8')) --db57d23ff5dee7dc8dbab418e4bcb6dc Content-Disposition: form-data; name="file"; filename="test.txt" Hello, World! --db57d23ff5dee7dc8dbab418e4bcb6dc-- >>> headers['Content-type'] 'multipart/form-data; boundary=db57d23ff5dee7dc8dbab418e4bcb6dc' ``` Here boundary is the same as in the header. Another alternative is using `requests-toolbelt`; below example taken from [this GitHub issue](https://github.com/requests/requests/issues/1997#issuecomment-40031999) thread: ``` from requests_toolbelt import MultipartEncoder fields = { # your multipart form fields } m = MultipartEncoder(fields, boundary='my_super_custom_header') r = requests.post(url, headers={'Content-Type': m.content_type}, data=m.to_string()) ``` But it is better not to pass `bundary` by hand at all and entrust this work to the requests library. --- **Update:** A minimal working example using Xero Files API and Python request: ``` from os.path import abspath import requests access_token = 'secret' tenant_id = 'secret' filename = abspath('./example.png') post_url = 'https://api.xero.com/files.xro/1.0/Files' files = {'filename': open(filename, 'rb')} values = {'name': 'Xero'} headers = { 'Authorization': f'Bearer {access_token}', 'Xero-tenant-id': f'{tenant_id}', 'Accept': 'application/json', } response = requests.post( post_url, headers=headers, files=files, data=values ) assert response.status_code == 201 ```
I've tested this with Xero's Files API to upload a file called "helloworld.rtf" in the same directory as my main app.py file. ``` var1 = "Bearer " var2 = YOUR_ACCESS_TOKEN access_token_header = var1 + var2 body = open('helloworld.rtf', 'rb') mp_encoder = MultipartEncoder( fields={ 'helloworld.rtf': ('helloworld.rtf', body), } ) r = requests.post( 'https://api.xero.com/files.xro/1.0/Files', data=mp_encoder, # The MultipartEncoder is posted as data # The MultipartEncoder provides the content-type header with the boundary: headers={ 'Content-Type': mp_encoder.content_type, 'xero-tenant-id': YOUR_XERO_TENANT_ID, 'Authorization': access_token_header } ) ```
67,103,105
I'm trying to upload PDF-file in the Xero account using the python request library (POST method) and Xeros FilesAPI said "Requests must be formatted as multipart MIME" and have some required fields ([link](https://developer.xero.com/documentation/files-api/files#POST)) but I don't how to do that exactly...If I do GET-request I'm getting the list of files in the Xero account but having a problem while posting the file (POST-request)... My Code: ``` post_url = 'https://api.xero.com/files.xro/1.0/Files/' files = {'file': open('/home/mobin/PycharmProjects/s3toxero/data/in_test_upload.pdf', 'rb')} response = requests.post( post_url, headers={ 'Authorization': 'Bearer ' + new_tokens[0], 'Xero-tenant-id': xero_tenant_id, 'Accept': 'application/json', 'Content-type': 'multipart/form-data; boundary=JLQPFBPUP0', 'Content-Length': '1068', }, files=files, ) json_response = response.json() print(f'Uploading Responsoe ==> {json_response}') print(f'Uploading Responsoe ==> {response}') ``` Error Mesage/Response: ``` Uploading Responsoe ==> [{'type': 'Validation', 'title': 'Validation failure', 'detail': 'No file is was attached'}] Uploading Responsoe ==> <Response [400]> ```
2021/04/15
[ "https://Stackoverflow.com/questions/67103105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9025820/" ]
As I see you're improperly set the boundary. You set it in the headers but not tell to `requests` library to use custom boundary. Let me show you an example: ``` >>> import requests >>> post_url = 'https://api.xero.com/files.xro/1.0/Files/' >>> files = {'file': open('/tmp/test.txt', 'rb')} >>> headers = { ... 'Authorization': 'Bearer secret', ... 'Xero-tenant-id': '42', ... 'Accept': 'application/json', ... 'Content-type': 'multipart/form-data; boundary=JLQPFBPUP0', ... 'Content-Length': '1068', ... } >>> print(requests.Request('POST', post_url, files=files, headers=headers).prepare().body.decode('utf8')) --f3e21ca5e554dd96430f07bb7a0d0e77 Content-Disposition: form-data; name="file"; filename="test.txt" --f3e21ca5e554dd96430f07bb7a0d0e77-- ``` As you can see the real boundary (`f3e21ca5e554dd96430f07bb7a0d0e77`) is different from what was passed in the header (`JLQPFBPUP0`). You can actually directly use the requests module to controll boundary like this: Let's prepare a test file: ``` $ touch /tmp/test.txt $ echo 'Hello, World!' > /tmp/test.txt ``` Test it: ``` >>> import requests >>> post_url = 'https://api.xero.com/files.xro/1.0/Files/' >>> files = {'file': open('/tmp/test.txt', 'rb')} >>> headers = { ... 'Authorization': 'Bearer secret', ... 'Xero-tenant-id': '42', ... 'Accept': 'application/json', ... 'Content-Length': '1068', ... } >>> body, content_type = requests.models.RequestEncodingMixin._encode_files(files, {}) >>> headers['Content-type'] = content_type >>> print(requests.Request('POST', post_url, data=body, headers=headers).prepare().body.decode('utf8')) --db57d23ff5dee7dc8dbab418e4bcb6dc Content-Disposition: form-data; name="file"; filename="test.txt" Hello, World! --db57d23ff5dee7dc8dbab418e4bcb6dc-- >>> headers['Content-type'] 'multipart/form-data; boundary=db57d23ff5dee7dc8dbab418e4bcb6dc' ``` Here boundary is the same as in the header. Another alternative is using `requests-toolbelt`; below example taken from [this GitHub issue](https://github.com/requests/requests/issues/1997#issuecomment-40031999) thread: ``` from requests_toolbelt import MultipartEncoder fields = { # your multipart form fields } m = MultipartEncoder(fields, boundary='my_super_custom_header') r = requests.post(url, headers={'Content-Type': m.content_type}, data=m.to_string()) ``` But it is better not to pass `bundary` by hand at all and entrust this work to the requests library. --- **Update:** A minimal working example using Xero Files API and Python request: ``` from os.path import abspath import requests access_token = 'secret' tenant_id = 'secret' filename = abspath('./example.png') post_url = 'https://api.xero.com/files.xro/1.0/Files' files = {'filename': open(filename, 'rb')} values = {'name': 'Xero'} headers = { 'Authorization': f'Bearer {access_token}', 'Xero-tenant-id': f'{tenant_id}', 'Accept': 'application/json', } response = requests.post( post_url, headers=headers, files=files, data=values ) assert response.status_code == 201 ```
looks like you got it solved. For reference and any future developers who are using the Xero supported package (<https://github.com/XeroAPI/xero-python>) We just added the files\_api example code to the sample app so the following would upload a file if you were using the Python SDK <https://github.com/XeroAPI/xero-python-oauth2-app/pull/29/files> ```py name = "my-image" filename= "my-image.jpg" mime_type = "image/jpg" with open('my-image.jpg', 'rb') as f: body = f.read() try: file_object = files_api.upload_file( xero_tenant_id, name = name, filename= filename, mime_type = mime_type, body=body ) except AccountingBadRequestException as exception: json = jsonify(exception.error_data) else: json = serialize_model(file_object) ```
19,829,952
Objective: Trying to run SL4A facade APIs from python shell on the host system (windows 7 PC) My environment: 1. On my windows 7 PC, i have python 2.6.2 2. Android sdk tools rev 21, platform tools rev 16 3. API level 17 supported for JB 4.2 4. I have 2 devices ( one running android 2.3.3 and another android 4.2.2) both running Python for android and SL4A I'm trying these commands as specified at <http://code.google.com/p/android-scripting/wiki/RemoteControl> Here are the commands which i'm trying on the python shell: Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. ``` >>> import android >>> droid=android.Android >>> droid.makeToast("Hello") ``` Traceback (most recent call last): File "", line 1, in AttributeError: type object 'Android' has no attribute 'makeToast' Before this i'm performing the port forwarding and starting a private server as shown below ``` $ adb forward tcp:9999 tcp:4321 $ set AP_PORT=9999 ``` Also set the server on the target listening on port 9999 ( through SL4A->preferences->serverport. Please help to understand where i'm doing mistake which gives the above error while trying droid.makeToast("Hello") ?
2013/11/07
[ "https://Stackoverflow.com/questions/19829952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2949720/" ]
***You can create your own Video Recording Screen*** Try like this, First Create a Custom Recorder using `SurfaceView` ``` public class VideoCapture extends SurfaceView implements SurfaceHolder.Callback { private MediaRecorder recorder; private SurfaceHolder holder; public Context context; private Camera camera; public static String videoPath = Environment.getExternalStorageDirectory() .getPath() +"/YOUR_VIDEO.mp4"; public VideoCapture(Context context) { super(context); this.context = context; init(); } public VideoCapture(Context context, AttributeSet attrs) { super(context, attrs); init(); } public VideoCapture(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } @SuppressLint("NewApi") public void init() { try { recorder = new MediaRecorder(); holder = getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); camera = getCameraInstance(); if(android.os.Build.VERSION.SDK_INT > 7) camera.setDisplayOrientation(90); camera.unlock(); recorder.setCamera(camera); recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP); recorder.setOutputFile(videoPath); } catch (Exception e) { e.printStackTrace(); } } public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { } public void surfaceCreated(SurfaceHolder mHolder) { try { recorder.setPreviewDisplay(mHolder.getSurface()); recorder.prepare(); recorder.start(); } catch (Exception e) { e.printStackTrace(); } } public void stopCapturingVideo() { try { recorder.stop(); camera.lock(); } catch (Exception e) { e.printStackTrace(); } } @TargetApi(5) public void surfaceDestroyed(SurfaceHolder arg0) { if (recorder != null) { stopCapturingVideo(); recorder.release(); camera.lock(); camera.release(); recorder = null; } } private Camera getCameraInstance() { Camera c = null; try { c = Camera.open(); // attempt to get a Camera instance } catch (Exception e) { // Camera is not available (in use or does not exist) } return c; } } ``` And you can use it inside your Layout for Activity Class ``` <your_package.VideoCapture android:id="@+id/videoView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#00000000" /> ``` EDITED:- ``` public class CaptureVideo extends Activity { private VideoCapture videoCapture; private Button stop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.video_capture); videoCapture = (VideoCapture) findViewById(R.id.videoView); stop= (Button) findViewById(R.id.stop); stop.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { videoCapture.stopCapturingVideo(); setResult(Activity.RESULT_OK); finish(); } }); } } ``` Hope this will help you
This way is using fragments: ``` public class CaptureVideo extends Fragment implements OnClickListener, SurfaceHolder.Callback{ private Button btnStartRec; MediaRecorder recorder; SurfaceHolder holder; boolean recording = false; private int randomNum; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view001 = inflater.inflate(R.layout.capture_video,container,false); recorder = new MediaRecorder(); initRecorder(); btnStartRec = (Button) view001.findViewById(R.id.btnCaptureVideo); btnStartRec.setOnClickListener(this); SurfaceView cameraView = (SurfaceView)view001.findViewById(R.id.surfaceCamera); holder = cameraView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); cameraView.setClickable(true); cameraView.setOnClickListener(this); return view001; } @SuppressLint({ "SdCardPath", "NewApi" }) private void initRecorder() { Random rn = new Random(); int maximum = 10000000; int minimum = 00000001; int range = maximum - minimum + 1; randomNum = rn.nextInt(range) + minimum + 1 - 10; recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP); if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) { recorder.setOrientationHint(90);//plays the video correctly }else{ recorder.setOrientationHint(180); } recorder.setOutputFile("/sdcard/MediaAppVideos/"+randomNum+".mp4"); } private void prepareRecorder() { recorder.setPreviewDisplay(holder.getSurface()); try { recorder.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); //finish(); } catch (IOException e) { e.printStackTrace(); //finish(); } } public void onClick(View v) { switch (v.getId()) { case R.id.btnCaptureVideo: try{ if (recording) { recorder.stop(); recording = false; // Let's initRecorder so we can record again //initRecorder(); //prepareRecorder(); } else { recording = true; recorder.start(); } }catch(Exception e){ } default: break; } } public void surfaceCreated(SurfaceHolder holder) { prepareRecorder(); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } public void surfaceDestroyed(SurfaceHolder holder) { try { if (recording) { recorder.stop(); recording = false; } recorder.release(); // finish(); } catch (Exception e) { } } } ``` xml: ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <SurfaceView android:id="@+id/surfaceCamera" android:layout_width="match_parent" android:layout_height="match_parent" /> <Button android:id="@+id/btnCaptureVideo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="Start Recording" /> </RelativeLayout> ```
19,829,952
Objective: Trying to run SL4A facade APIs from python shell on the host system (windows 7 PC) My environment: 1. On my windows 7 PC, i have python 2.6.2 2. Android sdk tools rev 21, platform tools rev 16 3. API level 17 supported for JB 4.2 4. I have 2 devices ( one running android 2.3.3 and another android 4.2.2) both running Python for android and SL4A I'm trying these commands as specified at <http://code.google.com/p/android-scripting/wiki/RemoteControl> Here are the commands which i'm trying on the python shell: Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. ``` >>> import android >>> droid=android.Android >>> droid.makeToast("Hello") ``` Traceback (most recent call last): File "", line 1, in AttributeError: type object 'Android' has no attribute 'makeToast' Before this i'm performing the port forwarding and starting a private server as shown below ``` $ adb forward tcp:9999 tcp:4321 $ set AP_PORT=9999 ``` Also set the server on the target listening on port 9999 ( through SL4A->preferences->serverport. Please help to understand where i'm doing mistake which gives the above error while trying droid.makeToast("Hello") ?
2013/11/07
[ "https://Stackoverflow.com/questions/19829952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2949720/" ]
This is how I achieved it: ``` public class MainActivity extends Activity implements SurfaceHolder.Callback { private MediaRecorder recorder; private SurfaceHolder surfaceHolder; private CamcorderProfile camcorderProfile; private Camera camera; boolean recording = false; boolean usecamera = true; boolean previewRunning = false; SurfaceView surfaceView; Button btnStart, btnStop; File root; File file; Boolean isSDPresent; SimpleDateFormat simpleDateFormat; String timeStamp; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setContentView(R.layout.activity_main); initComs(); actionListener(); } private void initComs() { simpleDateFormat = new SimpleDateFormat("ddMMyyyyhhmmss"); timeStamp = simpleDateFormat.format(new Date()); camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH); surfaceView = (SurfaceView) findViewById(R.id.preview); surfaceHolder = surfaceView.getHolder(); surfaceHolder.addCallback(this); btnStop = (Button) findViewById(R.id.btn_stop); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); isSDPresent = android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED); } public static float megabytesAvailable(File f) { StatFs stat = new StatFs(f.getPath()); long bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks(); return bytesAvailable / (1024.f * 1024.f); } private void actionListener() { btnStop.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (recording) { recorder.stop(); if (usecamera) { try { camera.reconnect(); } catch (IOException e) { e.printStackTrace(); } } // recorder.release(); recording = false; // Let's prepareRecorder so we can record again prepareRecorder(); } } }); } private void prepareRecorder() { recorder = new MediaRecorder(); recorder.setPreviewDisplay(surfaceHolder.getSurface()); if (usecamera) { camera.unlock(); recorder.setCamera(camera); } recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); recorder.setProfile(camcorderProfile); if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) { recorder.setOutputFile("/sdcard/XYZApp/" + "XYZAppVideo" + "" + new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date()) + ".mp4"); } else if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) { recorder.setOutputFile("/sdcard/XYZApp/" + "XYZAppVideo" + "" + new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date()) + ".mp4"); } else { recorder.setOutputFile("/sdcard/XYZApp/" + "XYZAppVideo" + "" + new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date()) + ".mp4"); } try { recorder.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); finish(); } catch (IOException e) { e.printStackTrace(); finish(); } } public void surfaceCreated(SurfaceHolder holder) { System.out.println("onsurfacecreated"); if (usecamera) { camera = Camera.open(); try { camera.setPreviewDisplay(holder); camera.startPreview(); previewRunning = true; } catch (IOException e) { e.printStackTrace(); } } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { System.out.println("onsurface changed"); if (!recording && usecamera) { if (previewRunning) { camera.stopPreview(); } try { Camera.Parameters p = camera.getParameters(); p.setPreviewSize(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight); p.setPreviewFrameRate(camcorderProfile.videoFrameRate); camera.setParameters(p); camera.setPreviewDisplay(holder); camera.startPreview(); previewRunning = true; } catch (IOException e) { e.printStackTrace(); } prepareRecorder(); if (!recording) { recording = true; recorder.start(); } } } public void surfaceDestroyed(SurfaceHolder holder) { if (recording) { recorder.stop(); recording = false; } recorder.release(); if (usecamera) { previewRunning = false; // camera.lock(); camera.release(); } finish(); } } ```
***You can create your own Video Recording Screen*** Try like this, First Create a Custom Recorder using `SurfaceView` ``` public class VideoCapture extends SurfaceView implements SurfaceHolder.Callback { private MediaRecorder recorder; private SurfaceHolder holder; public Context context; private Camera camera; public static String videoPath = Environment.getExternalStorageDirectory() .getPath() +"/YOUR_VIDEO.mp4"; public VideoCapture(Context context) { super(context); this.context = context; init(); } public VideoCapture(Context context, AttributeSet attrs) { super(context, attrs); init(); } public VideoCapture(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } @SuppressLint("NewApi") public void init() { try { recorder = new MediaRecorder(); holder = getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); camera = getCameraInstance(); if(android.os.Build.VERSION.SDK_INT > 7) camera.setDisplayOrientation(90); camera.unlock(); recorder.setCamera(camera); recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP); recorder.setOutputFile(videoPath); } catch (Exception e) { e.printStackTrace(); } } public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { } public void surfaceCreated(SurfaceHolder mHolder) { try { recorder.setPreviewDisplay(mHolder.getSurface()); recorder.prepare(); recorder.start(); } catch (Exception e) { e.printStackTrace(); } } public void stopCapturingVideo() { try { recorder.stop(); camera.lock(); } catch (Exception e) { e.printStackTrace(); } } @TargetApi(5) public void surfaceDestroyed(SurfaceHolder arg0) { if (recorder != null) { stopCapturingVideo(); recorder.release(); camera.lock(); camera.release(); recorder = null; } } private Camera getCameraInstance() { Camera c = null; try { c = Camera.open(); // attempt to get a Camera instance } catch (Exception e) { // Camera is not available (in use or does not exist) } return c; } } ``` And you can use it inside your Layout for Activity Class ``` <your_package.VideoCapture android:id="@+id/videoView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#00000000" /> ``` EDITED:- ``` public class CaptureVideo extends Activity { private VideoCapture videoCapture; private Button stop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.video_capture); videoCapture = (VideoCapture) findViewById(R.id.videoView); stop= (Button) findViewById(R.id.stop); stop.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { videoCapture.stopCapturingVideo(); setResult(Activity.RESULT_OK); finish(); } }); } } ``` Hope this will help you
19,829,952
Objective: Trying to run SL4A facade APIs from python shell on the host system (windows 7 PC) My environment: 1. On my windows 7 PC, i have python 2.6.2 2. Android sdk tools rev 21, platform tools rev 16 3. API level 17 supported for JB 4.2 4. I have 2 devices ( one running android 2.3.3 and another android 4.2.2) both running Python for android and SL4A I'm trying these commands as specified at <http://code.google.com/p/android-scripting/wiki/RemoteControl> Here are the commands which i'm trying on the python shell: Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. ``` >>> import android >>> droid=android.Android >>> droid.makeToast("Hello") ``` Traceback (most recent call last): File "", line 1, in AttributeError: type object 'Android' has no attribute 'makeToast' Before this i'm performing the port forwarding and starting a private server as shown below ``` $ adb forward tcp:9999 tcp:4321 $ set AP_PORT=9999 ``` Also set the server on the target listening on port 9999 ( through SL4A->preferences->serverport. Please help to understand where i'm doing mistake which gives the above error while trying droid.makeToast("Hello") ?
2013/11/07
[ "https://Stackoverflow.com/questions/19829952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2949720/" ]
This is how I achieved it: ``` public class MainActivity extends Activity implements SurfaceHolder.Callback { private MediaRecorder recorder; private SurfaceHolder surfaceHolder; private CamcorderProfile camcorderProfile; private Camera camera; boolean recording = false; boolean usecamera = true; boolean previewRunning = false; SurfaceView surfaceView; Button btnStart, btnStop; File root; File file; Boolean isSDPresent; SimpleDateFormat simpleDateFormat; String timeStamp; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setContentView(R.layout.activity_main); initComs(); actionListener(); } private void initComs() { simpleDateFormat = new SimpleDateFormat("ddMMyyyyhhmmss"); timeStamp = simpleDateFormat.format(new Date()); camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH); surfaceView = (SurfaceView) findViewById(R.id.preview); surfaceHolder = surfaceView.getHolder(); surfaceHolder.addCallback(this); btnStop = (Button) findViewById(R.id.btn_stop); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); isSDPresent = android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED); } public static float megabytesAvailable(File f) { StatFs stat = new StatFs(f.getPath()); long bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks(); return bytesAvailable / (1024.f * 1024.f); } private void actionListener() { btnStop.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (recording) { recorder.stop(); if (usecamera) { try { camera.reconnect(); } catch (IOException e) { e.printStackTrace(); } } // recorder.release(); recording = false; // Let's prepareRecorder so we can record again prepareRecorder(); } } }); } private void prepareRecorder() { recorder = new MediaRecorder(); recorder.setPreviewDisplay(surfaceHolder.getSurface()); if (usecamera) { camera.unlock(); recorder.setCamera(camera); } recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); recorder.setProfile(camcorderProfile); if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) { recorder.setOutputFile("/sdcard/XYZApp/" + "XYZAppVideo" + "" + new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date()) + ".mp4"); } else if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) { recorder.setOutputFile("/sdcard/XYZApp/" + "XYZAppVideo" + "" + new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date()) + ".mp4"); } else { recorder.setOutputFile("/sdcard/XYZApp/" + "XYZAppVideo" + "" + new SimpleDateFormat("ddMMyyyyHHmmss").format(new Date()) + ".mp4"); } try { recorder.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); finish(); } catch (IOException e) { e.printStackTrace(); finish(); } } public void surfaceCreated(SurfaceHolder holder) { System.out.println("onsurfacecreated"); if (usecamera) { camera = Camera.open(); try { camera.setPreviewDisplay(holder); camera.startPreview(); previewRunning = true; } catch (IOException e) { e.printStackTrace(); } } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { System.out.println("onsurface changed"); if (!recording && usecamera) { if (previewRunning) { camera.stopPreview(); } try { Camera.Parameters p = camera.getParameters(); p.setPreviewSize(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight); p.setPreviewFrameRate(camcorderProfile.videoFrameRate); camera.setParameters(p); camera.setPreviewDisplay(holder); camera.startPreview(); previewRunning = true; } catch (IOException e) { e.printStackTrace(); } prepareRecorder(); if (!recording) { recording = true; recorder.start(); } } } public void surfaceDestroyed(SurfaceHolder holder) { if (recording) { recorder.stop(); recording = false; } recorder.release(); if (usecamera) { previewRunning = false; // camera.lock(); camera.release(); } finish(); } } ```
This way is using fragments: ``` public class CaptureVideo extends Fragment implements OnClickListener, SurfaceHolder.Callback{ private Button btnStartRec; MediaRecorder recorder; SurfaceHolder holder; boolean recording = false; private int randomNum; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view001 = inflater.inflate(R.layout.capture_video,container,false); recorder = new MediaRecorder(); initRecorder(); btnStartRec = (Button) view001.findViewById(R.id.btnCaptureVideo); btnStartRec.setOnClickListener(this); SurfaceView cameraView = (SurfaceView)view001.findViewById(R.id.surfaceCamera); holder = cameraView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); cameraView.setClickable(true); cameraView.setOnClickListener(this); return view001; } @SuppressLint({ "SdCardPath", "NewApi" }) private void initRecorder() { Random rn = new Random(); int maximum = 10000000; int minimum = 00000001; int range = maximum - minimum + 1; randomNum = rn.nextInt(range) + minimum + 1 - 10; recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP); if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) { recorder.setOrientationHint(90);//plays the video correctly }else{ recorder.setOrientationHint(180); } recorder.setOutputFile("/sdcard/MediaAppVideos/"+randomNum+".mp4"); } private void prepareRecorder() { recorder.setPreviewDisplay(holder.getSurface()); try { recorder.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); //finish(); } catch (IOException e) { e.printStackTrace(); //finish(); } } public void onClick(View v) { switch (v.getId()) { case R.id.btnCaptureVideo: try{ if (recording) { recorder.stop(); recording = false; // Let's initRecorder so we can record again //initRecorder(); //prepareRecorder(); } else { recording = true; recorder.start(); } }catch(Exception e){ } default: break; } } public void surfaceCreated(SurfaceHolder holder) { prepareRecorder(); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } public void surfaceDestroyed(SurfaceHolder holder) { try { if (recording) { recorder.stop(); recording = false; } recorder.release(); // finish(); } catch (Exception e) { } } } ``` xml: ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <SurfaceView android:id="@+id/surfaceCamera" android:layout_width="match_parent" android:layout_height="match_parent" /> <Button android:id="@+id/btnCaptureVideo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="Start Recording" /> </RelativeLayout> ```
64,018,103
I've been working in a project for about 6 months, and I've been adding more urls each time. Right now, I'm coming into the problem that when I'm using `extend 'base.html'` into another pages, the CSS overlap, and I'm getting a mess. My question is: Which are the best practices when using `extend` for CSS files? Should every html file I create have it's own css? Or should I have one css that is called in the base.html file and from there all of the other html files take their styling from? This is what my base.html looks like: ``` <head> <meta charset="utf-8"> <meta http-equiv="cache-control" content="max-age=0" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="0" /> <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" /> <meta http-equiv="pragma" content="no-cache" /> </script> </head> <style> * { margin: 0; box-sizing: border-box; } html { font-size: 10px; font-family: sans-serif; } a { text-decoration: none; color: #ea0a8e; font-size: 18px; } header { width: 100%; height: auto; background: #121212; background-size: cover; position: relative; overflow: hidden; } .container { max-width: 120rem; width: 90%; margin: 0 auto; } .menu-toggle { position: fixed; top: 2.5rem; right: 2.5rem; color: #eeeeee; font-size: 3rem; cursor: pointer; z-index: 1000; display: none; } nav { padding-top: 5rem; display: flex; justify-content: space-between; align-items: center; text-transform: uppercase; font-size: 1.6rem; } .logo { font-size: 3rem; font-weight: 300; transform: translateX(-100rem); animation: slideIn .5s forwards; color: #ea0a8e; } .logo span { color: white; } nav ul { display: flex; padding: 0; } nav ul li { list-style: none; transform: translateX(100rem); animation: slideIn .5s forwards; } nav ul li:nth-child(1) { animation-delay: 0s; } nav ul li:nth-child(2) { animation-delay: .5s; } nav ul li:nth-child(3) { animation-delay: 1s; } nav ul li:nth-child(4) { animation-delay: 1.5s; } nav ul li:nth-child(5) { animation-delay: 1s; } nav ul li:nth-child(6) { animation-delay: .5s; } nav ul li:nth-child(7) { animation-delay: 0s; } nav ul li a { padding: 1rem 0; margin: 0 3rem; position: relative; } nav ul li a:last-child { margin-right: 0; } nav ul li a::before, nav ul li a::after { content: ''; position: absolute; width: 100%; height: 2px; background-color: crimson; left: 0; transform: scaleX(0); transition: all .5s; } nav ul li a::before { top: 0; transform-origin: left; } nav ul li a::after { bottom: 0; transform-origin: right; } nav ul li a:hover::before, nav ul li a:hover::after { transform: scaleX(1); } @keyframes slideIn { from {} to { transform: translateX(0); } } @media screen and (max-width: 700px) { .menu-toggle { display: block; } nav { padding-top: 0; display: none; flex-direction: column; justify-content: space-evenly; align-items: center; height: 100vh; text-align: center; } nav ul { flex-direction: column; } nav ul li { margin-top: 5rem; } nav ul li a { margin: 0; font-size: 2.5rem; } .logo { font-size: 5rem; } body::-webkit-scrollbar { width: 11px; } body { scrollbar-width: thin; scrollbar-color: var(--thumbBG) var(--scrollbarBG); } body::-webkit-scrollbar-track { background: var(--scrollbarBG); } body::-webkit-scrollbar-thumb { background-color: var(--thumbBG); border-radius: 6px; border: 3px solid var(--scrollbarBG); } } </style> <body> <div class="container"> <nav> <h1 class="logo">GP Recon<span>ciliation</span></a></h1> <ul> <li><a href="{% url 'dashboard' %}">Dashboard</a></li> <li><a href="{% url 'stats' %}">Stats</a></li> <li><a href="{% url 'addtransaction' %}">Add transaction</a></li> <li><a href="{% url 'upload' %}">Docs</a></li> <li><a href="{% url 'suggestion' %}">Suggestions</a></li> <li><a href="{% url 'about' %}">About</a></li> <li><a href="{% url 'logout' %}">Log out</a></li> </ul> </nav> </div> {% block content %} {% endblock %} </body> ``` This is the testing.html file I'm extending the base to: ``` {% extends 'pythonApp/base.html' %} {% load static %} {% block content %} <style> *{ margin: 0; padding: 0; background-color: #121212; } li{ list-style: none; position: relative; } ul.child{ display: none; width: 100%! important; } ul.parent > li{ background: #ea0a8e; width: 20%; padding: 10px; box-sizing: border-box; color: white; cursor: pointer; } </style> <body> <nav id="navigation"> <ul class="parent"> <li>Human Resources <ul class="child"> <li>Contact </li> <li>Escalation </li> <li>Performance</li> <li>Resource </li> <li>Benefits</li> </ul> </li> <li>Mision <ul class="child"> <li>Mission</li> </ul> </li> <li>Open <ul class="child"> <li>Field</li> <li>Office</li> </ul> </li> <li>Training <ul class="child"> <li>Training </li> <li>GP </li> <li>Mobile </li> <li>GP </li> <li>Field!</li> <li>Ready!</li> <li>Customer</li> </ul> </li> <li>Commissions <ul class="child"> <li>Mobile</li> <li>Quotas</li> </ul> </li> <li>Operations <ul class="child"> <li>Aud</li> <li>Ops</li> <li>To Documents</li> </ul> </li> <li>Help <ul class="child"> <li>Help</li> </ul> </li> <li>Documents <ul class="child"> <li>Documents</li> </ul> </li> <li>Resources <ul class="child"> <li>Resources</li> </ul> </li> <li>Dep <ul class="child"> <li>Dep</li> </ul> </li> <li>District <ul class="child"> <li>District</li> </ul> </li> <li>Store <ul class="child"> <li>Store</li> </ul> </li> <li>ME <ul class="child"> <li>ME</li> </ul> </li> </ul> </div> </body> </html> <script> $(function() { $('ul.parent > li').hover(function() { $(this).find('ul.child').show(200); }, function() { $(this).find('ul.child').hide(400); }); }); </script> {% endblock %} ``` What's happening is that the css effects that are in the styling of base.html are also applying to the test.html file
2020/09/22
[ "https://Stackoverflow.com/questions/64018103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13821665/" ]
Django provides django.contrib.staticfiles which is tasked with static files(CSS,JavaScript,media).In a nut shell each template in the app will inherit the base static folder in your app [Read the below doc and see how to configure the static files](https://docs.djangoproject.com/en/3.1/howto/static-files/)
you can add your static files in your template: ``` {% extends 'pythonApp/base.html' %} {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'pathtostaticfile' %}" /> ... ```
64,018,103
I've been working in a project for about 6 months, and I've been adding more urls each time. Right now, I'm coming into the problem that when I'm using `extend 'base.html'` into another pages, the CSS overlap, and I'm getting a mess. My question is: Which are the best practices when using `extend` for CSS files? Should every html file I create have it's own css? Or should I have one css that is called in the base.html file and from there all of the other html files take their styling from? This is what my base.html looks like: ``` <head> <meta charset="utf-8"> <meta http-equiv="cache-control" content="max-age=0" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="0" /> <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" /> <meta http-equiv="pragma" content="no-cache" /> </script> </head> <style> * { margin: 0; box-sizing: border-box; } html { font-size: 10px; font-family: sans-serif; } a { text-decoration: none; color: #ea0a8e; font-size: 18px; } header { width: 100%; height: auto; background: #121212; background-size: cover; position: relative; overflow: hidden; } .container { max-width: 120rem; width: 90%; margin: 0 auto; } .menu-toggle { position: fixed; top: 2.5rem; right: 2.5rem; color: #eeeeee; font-size: 3rem; cursor: pointer; z-index: 1000; display: none; } nav { padding-top: 5rem; display: flex; justify-content: space-between; align-items: center; text-transform: uppercase; font-size: 1.6rem; } .logo { font-size: 3rem; font-weight: 300; transform: translateX(-100rem); animation: slideIn .5s forwards; color: #ea0a8e; } .logo span { color: white; } nav ul { display: flex; padding: 0; } nav ul li { list-style: none; transform: translateX(100rem); animation: slideIn .5s forwards; } nav ul li:nth-child(1) { animation-delay: 0s; } nav ul li:nth-child(2) { animation-delay: .5s; } nav ul li:nth-child(3) { animation-delay: 1s; } nav ul li:nth-child(4) { animation-delay: 1.5s; } nav ul li:nth-child(5) { animation-delay: 1s; } nav ul li:nth-child(6) { animation-delay: .5s; } nav ul li:nth-child(7) { animation-delay: 0s; } nav ul li a { padding: 1rem 0; margin: 0 3rem; position: relative; } nav ul li a:last-child { margin-right: 0; } nav ul li a::before, nav ul li a::after { content: ''; position: absolute; width: 100%; height: 2px; background-color: crimson; left: 0; transform: scaleX(0); transition: all .5s; } nav ul li a::before { top: 0; transform-origin: left; } nav ul li a::after { bottom: 0; transform-origin: right; } nav ul li a:hover::before, nav ul li a:hover::after { transform: scaleX(1); } @keyframes slideIn { from {} to { transform: translateX(0); } } @media screen and (max-width: 700px) { .menu-toggle { display: block; } nav { padding-top: 0; display: none; flex-direction: column; justify-content: space-evenly; align-items: center; height: 100vh; text-align: center; } nav ul { flex-direction: column; } nav ul li { margin-top: 5rem; } nav ul li a { margin: 0; font-size: 2.5rem; } .logo { font-size: 5rem; } body::-webkit-scrollbar { width: 11px; } body { scrollbar-width: thin; scrollbar-color: var(--thumbBG) var(--scrollbarBG); } body::-webkit-scrollbar-track { background: var(--scrollbarBG); } body::-webkit-scrollbar-thumb { background-color: var(--thumbBG); border-radius: 6px; border: 3px solid var(--scrollbarBG); } } </style> <body> <div class="container"> <nav> <h1 class="logo">GP Recon<span>ciliation</span></a></h1> <ul> <li><a href="{% url 'dashboard' %}">Dashboard</a></li> <li><a href="{% url 'stats' %}">Stats</a></li> <li><a href="{% url 'addtransaction' %}">Add transaction</a></li> <li><a href="{% url 'upload' %}">Docs</a></li> <li><a href="{% url 'suggestion' %}">Suggestions</a></li> <li><a href="{% url 'about' %}">About</a></li> <li><a href="{% url 'logout' %}">Log out</a></li> </ul> </nav> </div> {% block content %} {% endblock %} </body> ``` This is the testing.html file I'm extending the base to: ``` {% extends 'pythonApp/base.html' %} {% load static %} {% block content %} <style> *{ margin: 0; padding: 0; background-color: #121212; } li{ list-style: none; position: relative; } ul.child{ display: none; width: 100%! important; } ul.parent > li{ background: #ea0a8e; width: 20%; padding: 10px; box-sizing: border-box; color: white; cursor: pointer; } </style> <body> <nav id="navigation"> <ul class="parent"> <li>Human Resources <ul class="child"> <li>Contact </li> <li>Escalation </li> <li>Performance</li> <li>Resource </li> <li>Benefits</li> </ul> </li> <li>Mision <ul class="child"> <li>Mission</li> </ul> </li> <li>Open <ul class="child"> <li>Field</li> <li>Office</li> </ul> </li> <li>Training <ul class="child"> <li>Training </li> <li>GP </li> <li>Mobile </li> <li>GP </li> <li>Field!</li> <li>Ready!</li> <li>Customer</li> </ul> </li> <li>Commissions <ul class="child"> <li>Mobile</li> <li>Quotas</li> </ul> </li> <li>Operations <ul class="child"> <li>Aud</li> <li>Ops</li> <li>To Documents</li> </ul> </li> <li>Help <ul class="child"> <li>Help</li> </ul> </li> <li>Documents <ul class="child"> <li>Documents</li> </ul> </li> <li>Resources <ul class="child"> <li>Resources</li> </ul> </li> <li>Dep <ul class="child"> <li>Dep</li> </ul> </li> <li>District <ul class="child"> <li>District</li> </ul> </li> <li>Store <ul class="child"> <li>Store</li> </ul> </li> <li>ME <ul class="child"> <li>ME</li> </ul> </li> </ul> </div> </body> </html> <script> $(function() { $('ul.parent > li').hover(function() { $(this).find('ul.child').show(200); }, function() { $(this).find('ul.child').hide(400); }); }); </script> {% endblock %} ``` What's happening is that the css effects that are in the styling of base.html are also applying to the test.html file
2020/09/22
[ "https://Stackoverflow.com/questions/64018103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13821665/" ]
In your base.html I'd only include styles that are applied to all/several pages on your website. And then include page-specific styles in that page HTML file. Storing all styles in 1 file is definitely not a good practice. Also, I see that you write your CSS selectors using tags like `li` or `nav`, this is generally a bad practice cause it leads to unexpected style overlaps. Use explicit declarative CSS classes for your elements (like in BEM methodology for example) and select elements by classes, not tags.
you can add your static files in your template: ``` {% extends 'pythonApp/base.html' %} {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'pathtostaticfile' %}" /> ... ```
65,278,114
I'm a beginner currently working on a small python project. It's a dice game in which there is player 1 and player 2. Players take turns to roll the dice and a game is 10 rounds in total(5 rounds for each player). The player with the highest number of points wins. I am trying to validate the first input so that when for example, the player enters a number instead of “Higher” or “Lower”, the program should respond with ‘Invalid input, please respond with “Higher” or “Lower”’. Here's my code so far ``` import random goAgain = "y" activePlayer = 1 player1Score = 0 player2Score = 0 maxGuesses = 9 while (goAgain == "y"): randNum = random.randint(1, 10) print(randNum) storedAnswer = input("Will you roll higher or lower?: ") while(storedAnswer.strip() != 'higher' or storedAnswer.strip() != 'lower'): print('Invalid input, please respond with "Higher" or "Lower"') storedAnswer = input("Will you roll higher or lower?: ") randNum2 = random.randint(1, 10) print(randNum2) if(storedAnswer.strip() == "lower" and randNum2 < randNum): if(activePlayer == 1): player1Score+=1 else: player2Score+=1 print("You Win!") maxGuesses+=1 # print(player1Score) # print(player2Score) elif (storedAnswer.strip() == "lower" and randNum2 > randNum): print("You Lose!") maxGuesses+=1 # print(player1Score) # print(player2Score) elif (storedAnswer.strip() == "higher" and randNum2 > randNum): if(activePlayer == 1): player1Score+=1 else: player2Score+=1 print("You Win!") maxGuesses+=1 # print(player1Score) # print(player2Score) elif (storedAnswer.strip() == "higher" and randNum2 < randNum): print("You Lose!") maxGuesses+=1 # print(player1Score) # print(player2Score) elif(randNum2 == randNum): print("Draw!") maxGuesses+=1 print(player1Score) print(player2Score) if(activePlayer == 1): activePlayer = 2 else: activePlayer = 1 if(maxGuesses == 10): if(player1Score > player2Score): print("Player 1 wins!") elif(player2Score > player1Score): print("Player 2 wins!") else: print("DRAW!") break else: goAgain = input("Do you want to play again: ") ``` The problem that occurs is that instead it print 'invalid input' regardless of whether the condition is true or not.
2020/12/13
[ "https://Stackoverflow.com/questions/65278114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13824901/" ]
Wrap that section of input in a `while True` loop. break the loop when the input is correct, otherwise keep looping for more input. ``` while True: b = int(input ("is player a Computer (0) or a human (1)?")) if b == 0: # player is a computer ... # do computer stuff break elif b == 1: # player is a human ... # do human stuff break else: print("That was not 1 or 0. Please try again") ```
Because elif is not a loop , compiler just checks the condition and then it moves forward executing the statement. You can solve this by just adding a \*\*\*while loop \*\*\* before first if condition like this : for i in range (players): a = input("name of player: ") b = int(input ("is player a Computer (0) or a human (1)?")) ``` while (b!=0 and b!=1): # Checking if b is not equal to both '0' and '1' b = int(input ("is player a Computer (0) or a human (1)?")) if b == 0: list_2.append([a] + [True]) elif b == 1: list_2.append([a] + [False]) elif b!= 0 and b!= 1: print (b) ```
65,278,114
I'm a beginner currently working on a small python project. It's a dice game in which there is player 1 and player 2. Players take turns to roll the dice and a game is 10 rounds in total(5 rounds for each player). The player with the highest number of points wins. I am trying to validate the first input so that when for example, the player enters a number instead of “Higher” or “Lower”, the program should respond with ‘Invalid input, please respond with “Higher” or “Lower”’. Here's my code so far ``` import random goAgain = "y" activePlayer = 1 player1Score = 0 player2Score = 0 maxGuesses = 9 while (goAgain == "y"): randNum = random.randint(1, 10) print(randNum) storedAnswer = input("Will you roll higher or lower?: ") while(storedAnswer.strip() != 'higher' or storedAnswer.strip() != 'lower'): print('Invalid input, please respond with "Higher" or "Lower"') storedAnswer = input("Will you roll higher or lower?: ") randNum2 = random.randint(1, 10) print(randNum2) if(storedAnswer.strip() == "lower" and randNum2 < randNum): if(activePlayer == 1): player1Score+=1 else: player2Score+=1 print("You Win!") maxGuesses+=1 # print(player1Score) # print(player2Score) elif (storedAnswer.strip() == "lower" and randNum2 > randNum): print("You Lose!") maxGuesses+=1 # print(player1Score) # print(player2Score) elif (storedAnswer.strip() == "higher" and randNum2 > randNum): if(activePlayer == 1): player1Score+=1 else: player2Score+=1 print("You Win!") maxGuesses+=1 # print(player1Score) # print(player2Score) elif (storedAnswer.strip() == "higher" and randNum2 < randNum): print("You Lose!") maxGuesses+=1 # print(player1Score) # print(player2Score) elif(randNum2 == randNum): print("Draw!") maxGuesses+=1 print(player1Score) print(player2Score) if(activePlayer == 1): activePlayer = 2 else: activePlayer = 1 if(maxGuesses == 10): if(player1Score > player2Score): print("Player 1 wins!") elif(player2Score > player1Score): print("Player 2 wins!") else: print("DRAW!") break else: goAgain = input("Do you want to play again: ") ``` The problem that occurs is that instead it print 'invalid input' regardless of whether the condition is true or not.
2020/12/13
[ "https://Stackoverflow.com/questions/65278114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13824901/" ]
Wrap that section of input in a `while True` loop. break the loop when the input is correct, otherwise keep looping for more input. ``` while True: b = int(input ("is player a Computer (0) or a human (1)?")) if b == 0: # player is a computer ... # do computer stuff break elif b == 1: # player is a human ... # do human stuff break else: print("That was not 1 or 0. Please try again") ```
You can also try to split your code and create a new `checkInput` function as implemented below. ```js list_2 = [] players = int(input("number of players: ")) def checkInput(value): if value == 0: list_2.append([a] + [True]) return True elif value == 1: list_2.append([a] + [False]) return True else: return False for i in range (players): check = False; a = input("name of player: ") while check == False: b = int(input ("is player a Computer (0) or a human (1)?")) check = checkInput(b) print('Please enter correct input') print (list_2) ```
65,940,602
I'm new to python and I'm using the book called "Automate the Boring Stuff with Python". I was entering the following code (which was the same as the book): ``` while True: print('Please type your name.') name = input() if name == 'your name': break print('Thank you!') ``` And I got a 'break outside loop' error. I found out that a break could only be used within loops. Then I tried entering the following: ``` while True: print('Please type your name.') name = input() while name == 'your name': break print('Thank you!') ``` But it didn't work, it kept asking for a name. What do you think there was a mistake in the book or something?
2021/01/28
[ "https://Stackoverflow.com/questions/65940602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14883326/" ]
Its perfectly fine just check your indentation
I think it's because of an **indentation**'s mistake. copy & paste the code below and check if it solves your problem or not. ``` while True: print('Please type your name.') name = input() if name == 'your name': break print('Thank you!') ``` indentations are so critical in python programming. you should always check them precisely.
65,940,602
I'm new to python and I'm using the book called "Automate the Boring Stuff with Python". I was entering the following code (which was the same as the book): ``` while True: print('Please type your name.') name = input() if name == 'your name': break print('Thank you!') ``` And I got a 'break outside loop' error. I found out that a break could only be used within loops. Then I tried entering the following: ``` while True: print('Please type your name.') name = input() while name == 'your name': break print('Thank you!') ``` But it didn't work, it kept asking for a name. What do you think there was a mistake in the book or something?
2021/01/28
[ "https://Stackoverflow.com/questions/65940602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14883326/" ]
Its perfectly fine just check your indentation
Replace string *your name* with your actual name in `if name == 'your name':`This name is what you enter as input, Since your input is not matching with if condition it will fail and break statement is never executed ``` while True: print('Please type your name.') name = input() if name == 'ajay': break print('Thank you!') ``` Output ``` Please type your name. ajay Thank you! ```
65,940,602
I'm new to python and I'm using the book called "Automate the Boring Stuff with Python". I was entering the following code (which was the same as the book): ``` while True: print('Please type your name.') name = input() if name == 'your name': break print('Thank you!') ``` And I got a 'break outside loop' error. I found out that a break could only be used within loops. Then I tried entering the following: ``` while True: print('Please type your name.') name = input() while name == 'your name': break print('Thank you!') ``` But it didn't work, it kept asking for a name. What do you think there was a mistake in the book or something?
2021/01/28
[ "https://Stackoverflow.com/questions/65940602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14883326/" ]
Its perfectly fine just check your indentation
The code is correct. Until the if condition is satisfied, it will keep on asking you to type your name. Once the name you entered as input matches with the name in if condition, the loop will come to an end. Input ``` while True: print('Please type your name.') name = input() if name == 'your name': break print('Thank you!') ``` Output ``` Please type your name. hello Please type your name. hi Please type your name. your name Thank you! ```
65,940,602
I'm new to python and I'm using the book called "Automate the Boring Stuff with Python". I was entering the following code (which was the same as the book): ``` while True: print('Please type your name.') name = input() if name == 'your name': break print('Thank you!') ``` And I got a 'break outside loop' error. I found out that a break could only be used within loops. Then I tried entering the following: ``` while True: print('Please type your name.') name = input() while name == 'your name': break print('Thank you!') ``` But it didn't work, it kept asking for a name. What do you think there was a mistake in the book or something?
2021/01/28
[ "https://Stackoverflow.com/questions/65940602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14883326/" ]
I think it's because of an **indentation**'s mistake. copy & paste the code below and check if it solves your problem or not. ``` while True: print('Please type your name.') name = input() if name == 'your name': break print('Thank you!') ``` indentations are so critical in python programming. you should always check them precisely.
Replace string *your name* with your actual name in `if name == 'your name':`This name is what you enter as input, Since your input is not matching with if condition it will fail and break statement is never executed ``` while True: print('Please type your name.') name = input() if name == 'ajay': break print('Thank you!') ``` Output ``` Please type your name. ajay Thank you! ```
65,940,602
I'm new to python and I'm using the book called "Automate the Boring Stuff with Python". I was entering the following code (which was the same as the book): ``` while True: print('Please type your name.') name = input() if name == 'your name': break print('Thank you!') ``` And I got a 'break outside loop' error. I found out that a break could only be used within loops. Then I tried entering the following: ``` while True: print('Please type your name.') name = input() while name == 'your name': break print('Thank you!') ``` But it didn't work, it kept asking for a name. What do you think there was a mistake in the book or something?
2021/01/28
[ "https://Stackoverflow.com/questions/65940602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14883326/" ]
I think it's because of an **indentation**'s mistake. copy & paste the code below and check if it solves your problem or not. ``` while True: print('Please type your name.') name = input() if name == 'your name': break print('Thank you!') ``` indentations are so critical in python programming. you should always check them precisely.
The code is correct. Until the if condition is satisfied, it will keep on asking you to type your name. Once the name you entered as input matches with the name in if condition, the loop will come to an end. Input ``` while True: print('Please type your name.') name = input() if name == 'your name': break print('Thank you!') ``` Output ``` Please type your name. hello Please type your name. hi Please type your name. your name Thank you! ```
61,011,373
I'm trying to install indy-node on a fresh Ubuntu 18.04 machine in order to create a small network with 4 nodes. when following the [installation instructions](https://github.com/hyperledger/indy-node/blob/master/docs/source/start-nodes.md) I get the following error: ``` localhost:~$ sudo apt-get install indy-node The following packages have unmet dependencies: indy-node : Depends: indy-plenum (= 1.12.2) but it is not going to be installed Depends: libsodium18 but it is not installable E: Unable to correct problems, you have held broken packages. ``` I've tried installing `libsodium18` but I get the following error: ``` Package libsodium18 is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source E: Package 'libsodium18' has no installation candidate ``` Likewise, trying to install `indy-plenum` has a bunch of 'unmet dependency' errors. \*\*Note:\* this is all happens with the following repo: ``` sudo bash -c 'echo "deb https://repo.sovrin.org/deb xenial stable" >> /etc/apt/sources.list' ``` when I try to add the packages for bionic instead of xenial, I get the following error: ``` repository 'https://repo.sovrin.org/deb bionic InRelease' doesn't have the component 'stable' ``` I have also tried to install indy-node via python + pip, but that doesn't seem to work either. **Has anyone successfully installed indy-node, and if so, can you share the secret?**
2020/04/03
[ "https://Stackoverflow.com/questions/61011373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786712/" ]
We've generated Docker images for Indy-Node using Ubuntu 18.04, but had to build libsodium from source. You can see the source dockerfile here although there are git URLs that get replaced by the build script: <https://github.com/PSPC-SPAC-buyandsell/von-image/blob/master/node-1.9/Dockerfile.ubuntu> The final images are at <https://hub.docker.com/r/bcgovimages/von-image/tags> (the node-\* images, latest is `bcgovimages/von-image:node-1.12-2`) I believe the Indy-Node team are shortly going to be updating to 20.04 for the image used in testing.
The solution in the end was to downgrade to Ubuntu 16.04
49,738,443
I'm attempting to convert an array of strings to array of floats using : ``` arr_str = '[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]' a1 = arr_str.split() [int(x) for x in a1] ``` but throws error : < ``` ipython-input-57-f7f1eaba7ebd> in <listcomp>(.0) 3 a1 = arr_str.split() 4 ----> 5 [int(x) for x in a1] 6 7 # for a in arr_str.split(): ValueError: invalid literal for int() with base 10: '[1' ``` Should pre-process the string and remove '[' and ']' ?
2018/04/09
[ "https://Stackoverflow.com/questions/49738443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470184/" ]
One way is to use `ast.literal_eval`. If you need a `numpy` integer array, the conversion is trivial. ``` import numpy as np from ast import literal_eval arr_str = '[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]' res = literal_eval(arr_str.replace(' ', ',')) # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] res_np = np.array(res) # array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) ```
``` arr_str = arr_str.strip("[]") voila = [int(x) for x in arr_str.split()] ``` Edit 1: Being pedantic about variable assignment.
49,738,443
I'm attempting to convert an array of strings to array of floats using : ``` arr_str = '[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]' a1 = arr_str.split() [int(x) for x in a1] ``` but throws error : < ``` ipython-input-57-f7f1eaba7ebd> in <listcomp>(.0) 3 a1 = arr_str.split() 4 ----> 5 [int(x) for x in a1] 6 7 # for a in arr_str.split(): ValueError: invalid literal for int() with base 10: '[1' ``` Should pre-process the string and remove '[' and ']' ?
2018/04/09
[ "https://Stackoverflow.com/questions/49738443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470184/" ]
One way is to use `ast.literal_eval`. If you need a `numpy` integer array, the conversion is trivial. ``` import numpy as np from ast import literal_eval arr_str = '[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]' res = literal_eval(arr_str.replace(' ', ',')) # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] res_np = np.array(res) # array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) ```
You can use the `ast` module: ``` import ast arr_str = '[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]' arr = ast.literal_eval(arr_str.replace(" ",", ")) arr = list(map(float,arr)) #Remove this line if you wish integer conversion. print(arr) ``` Output: ``` [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] ``` since you say `int` in the title, but `float` in your description.
27,532,112
I'm using two python packages that have the same name. * <http://www.alembic.io/updates.html> * <https://pypi.python.org/pypi/alembic> Is there a canonical or pythonic way to handle installing two packages with conflicting names? So far, I've only occasionally needed one of the packages during development/building, so I've been using a separate virtualenv to deal with the conflict, but it makes the build step more complex and I wonder if there isn't a better way to handle it.
2014/12/17
[ "https://Stackoverflow.com/questions/27532112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1547004/" ]
You could use the --target option for pip and install to an alternate location: ``` pip install --target=/tmp/test/lib/python3.6/site-packages/alt_alembic alembic ``` Then when you import in python, do the first as usual and for the alt do an import from that namespace like this: ``` import alembic # alembic.io version from alt_alembic import alembic as alt_alembic # pip version ``` Then when you're making calls to that one you can call alt\_alembic.function() and to the one that isn't in PyPi, alembic.function() My target path has /tmp/test as I was using a virtual env. You would need to replace that path with the correct one for your python installation.
how about **absolute and relative imports.** <https://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports>
43,429,018
i have the following link: <https://webcache.googleusercontent.com/search?q=cache:jAc7OJyyQboJ>:**<https://cooking.nytimes.com/learn-to-cook>**+&cd=5&hl=en&ct=clnk I have multiple links in a dataset. Each link is of same pattern. I want to get a specific part of the link, for the above link i would be the bold part of the link above. I want text starting from 2nd http to before first + sign. I don't know how to do so using regex. I am working in python. Kindly help me out.
2017/04/15
[ "https://Stackoverflow.com/questions/43429018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7872059/" ]
Instead of `var c = new Audio(src);` use `var c = document.createElement('audio'); c.src=src; c.play();`
You have to wait for the DOM to be ready. Since your are using jQuery, please encapsulate your code in that: ``` $(document).ready(function () { // Your code... }); ``` You can also use this syntax: ``` $(function () { // Your code... }); ``` *(Bonus tip: use the `switch` instruction in your code. `RoNBeta.js` is a bit scary...)*
43,429,018
i have the following link: <https://webcache.googleusercontent.com/search?q=cache:jAc7OJyyQboJ>:**<https://cooking.nytimes.com/learn-to-cook>**+&cd=5&hl=en&ct=clnk I have multiple links in a dataset. Each link is of same pattern. I want to get a specific part of the link, for the above link i would be the bold part of the link above. I want text starting from 2nd http to before first + sign. I don't know how to do so using regex. I am working in python. Kindly help me out.
2017/04/15
[ "https://Stackoverflow.com/questions/43429018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7872059/" ]
The accepted answer doesn't look like the best way to address that issue to me. You should either change your `JSLint` options or disable that rule on that specific line. ### Add it as a global In both `JSLint` and [`ESLint`](https://eslint.org/docs/user-guide/configuring#specifying-globals), you can fix it either adding it as a global: ``` { "globals": { "Audio": true } } ``` ### Add the browser environment [`ESLint:`](https://eslint.org/docs/user-guide/configuring#specifying-environments): ``` { "env": { "browser": true } } ``` `JSLint:` ``` { "browser": true } ``` ### JSLint options in Brackets You can also update them in Brackets' preferences: ``` "jslint.options": { "browser": true, OR "globals": { "Audio": true } } ``` ### Disable linting or ignore that rule on that line You can also disable linting for that line or for that specific rule on that line: `ESLint`: ``` const c = new Audio(src); // eslint-disable-line ``` Or: ``` // eslint-disable-next-line const c = new Audio(src); ``` `JSLint`: ``` const c = new Audio(src); // jslint ignore:line ```
You have to wait for the DOM to be ready. Since your are using jQuery, please encapsulate your code in that: ``` $(document).ready(function () { // Your code... }); ``` You can also use this syntax: ``` $(function () { // Your code... }); ``` *(Bonus tip: use the `switch` instruction in your code. `RoNBeta.js` is a bit scary...)*
43,429,018
i have the following link: <https://webcache.googleusercontent.com/search?q=cache:jAc7OJyyQboJ>:**<https://cooking.nytimes.com/learn-to-cook>**+&cd=5&hl=en&ct=clnk I have multiple links in a dataset. Each link is of same pattern. I want to get a specific part of the link, for the above link i would be the bold part of the link above. I want text starting from 2nd http to before first + sign. I don't know how to do so using regex. I am working in python. Kindly help me out.
2017/04/15
[ "https://Stackoverflow.com/questions/43429018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7872059/" ]
Instead of `var c = new Audio(src);` use `var c = document.createElement('audio'); c.src=src; c.play();`
The accepted answer doesn't look like the best way to address that issue to me. You should either change your `JSLint` options or disable that rule on that specific line. ### Add it as a global In both `JSLint` and [`ESLint`](https://eslint.org/docs/user-guide/configuring#specifying-globals), you can fix it either adding it as a global: ``` { "globals": { "Audio": true } } ``` ### Add the browser environment [`ESLint:`](https://eslint.org/docs/user-guide/configuring#specifying-environments): ``` { "env": { "browser": true } } ``` `JSLint:` ``` { "browser": true } ``` ### JSLint options in Brackets You can also update them in Brackets' preferences: ``` "jslint.options": { "browser": true, OR "globals": { "Audio": true } } ``` ### Disable linting or ignore that rule on that line You can also disable linting for that line or for that specific rule on that line: `ESLint`: ``` const c = new Audio(src); // eslint-disable-line ``` Or: ``` // eslint-disable-next-line const c = new Audio(src); ``` `JSLint`: ``` const c = new Audio(src); // jslint ignore:line ```
50,706,987
I've been trying for a couple of days with limited success to use TCP to make two ruby programs on the same or different machines communicate. I'm looking for example 'client' and 'server' scripts that will work straight away, once I've chosen ports that work. Client code I found that seems to work, shown below. But I haven't got a server working with it. ``` # Seems to work for some reason require 'socket' tcp_client=TCPSocket.new('localhost',1540) while grab_string=tcp_client.gets puts(grab_string) end tcp_client.close ``` I'm interested in the simplest possible solution, that works on my machine. All it has to do is send a string. The answer I'm looking for is just like [this](https://stackoverflow.com/questions/27241804/sending-a-file-over-tcp-sockets-in-python) but with ruby, instead of python. Feel free to change the code for client and server, with only half the puzzle in place I'm not sure if its works or not. Server code ``` # Server require 'socket' sock = TCPSocket.new('localhost', 1540) sock.write 'GETHELLO' puts sock.read(5) # Since the response message has 5 bytes. sock.close ``` Using the code suggested by kennycoc I get the following error message ``` Server.rb:3:in `initialize': Only one usage of each socket address (protocol/network address/port) is normally permitted. - bind(2) for nil port 1540 (Errno::EADDRINUSE) from Server.rb:3:in `new' from Server.rb:3:in `<main>' ```
2018/06/05
[ "https://Stackoverflow.com/questions/50706987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336879/" ]
@adjam you haven't created a TcpServer, [TCPSocket](https://ruby-doc.org/stdlib-1.9.3/libdoc/socket/rdoc/TCPSocket.html) is used to create TCP/IP client socket To create TCP/IP server you have to use [TCPServer](https://ruby-doc.org/stdlib-1.9.3/libdoc/socket/rdoc/TCPServer.html) EX: Tcp/ip Server code: ``` require 'socket' server = TCPServer.open(2000) client = server.accept # Accept client while (response = client.gets) # read data send by client print response end ``` Tcp/ip Client code: ``` require 'socket' client = TCPSocket.open('localhost', 2000) client.puts "hello" client.close; ```
Taking the documentation from <https://ruby-doc.org/stdlib-2.5.1/libdoc/socket/rdoc/Socket.html>, you seem to be looking for something like this: ``` require 'socket' server = TCPServer.new(1540) client = server.accept client.puts "GETHELLO" client.close server.close ``` More generally, if you'd like the server accessible for multiple clients to request data from, you'd have a loop running like ``` loop do client = server.accept client.puts "gethello" client.close end ```
50,706,987
I've been trying for a couple of days with limited success to use TCP to make two ruby programs on the same or different machines communicate. I'm looking for example 'client' and 'server' scripts that will work straight away, once I've chosen ports that work. Client code I found that seems to work, shown below. But I haven't got a server working with it. ``` # Seems to work for some reason require 'socket' tcp_client=TCPSocket.new('localhost',1540) while grab_string=tcp_client.gets puts(grab_string) end tcp_client.close ``` I'm interested in the simplest possible solution, that works on my machine. All it has to do is send a string. The answer I'm looking for is just like [this](https://stackoverflow.com/questions/27241804/sending-a-file-over-tcp-sockets-in-python) but with ruby, instead of python. Feel free to change the code for client and server, with only half the puzzle in place I'm not sure if its works or not. Server code ``` # Server require 'socket' sock = TCPSocket.new('localhost', 1540) sock.write 'GETHELLO' puts sock.read(5) # Since the response message has 5 bytes. sock.close ``` Using the code suggested by kennycoc I get the following error message ``` Server.rb:3:in `initialize': Only one usage of each socket address (protocol/network address/port) is normally permitted. - bind(2) for nil port 1540 (Errno::EADDRINUSE) from Server.rb:3:in `new' from Server.rb:3:in `<main>' ```
2018/06/05
[ "https://Stackoverflow.com/questions/50706987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336879/" ]
Taking the documentation from <https://ruby-doc.org/stdlib-2.5.1/libdoc/socket/rdoc/Socket.html>, you seem to be looking for something like this: ``` require 'socket' server = TCPServer.new(1540) client = server.accept client.puts "GETHELLO" client.close server.close ``` More generally, if you'd like the server accessible for multiple clients to request data from, you'd have a loop running like ``` loop do client = server.accept client.puts "gethello" client.close end ```
`tcp_server.rb` ```rb require "socket" server = TCPServer.new(1234) loop do # Keep the server alive session = server.accept puts "Request arrived" session.write "Time is #{Time.now}" # Send data to client session.close end ``` `tcp_client.rb` ```rb require "socket" socket = TCPSocket.open("localhost", 1234) puts socket.gets # Print sever response socket.close ``` --- Now - If you want two-way communication between server and client use following `tcp_client.rb` ```rb require "socket" socket = TCPSocket.open("localhost", 1234) socket.puts "Sample data to server" # Send data to server puts socket.gets # Print sever response socket.close ``` `tcp_server.rb` ```rb require "socket" server = TCPServer.new 1234 loop do session = server.accept puts "Data recieved - #{session.gets}" # Read data from client session.write "Time is #{Time.now}" # Send data to clent session.close end ```
50,706,987
I've been trying for a couple of days with limited success to use TCP to make two ruby programs on the same or different machines communicate. I'm looking for example 'client' and 'server' scripts that will work straight away, once I've chosen ports that work. Client code I found that seems to work, shown below. But I haven't got a server working with it. ``` # Seems to work for some reason require 'socket' tcp_client=TCPSocket.new('localhost',1540) while grab_string=tcp_client.gets puts(grab_string) end tcp_client.close ``` I'm interested in the simplest possible solution, that works on my machine. All it has to do is send a string. The answer I'm looking for is just like [this](https://stackoverflow.com/questions/27241804/sending-a-file-over-tcp-sockets-in-python) but with ruby, instead of python. Feel free to change the code for client and server, with only half the puzzle in place I'm not sure if its works or not. Server code ``` # Server require 'socket' sock = TCPSocket.new('localhost', 1540) sock.write 'GETHELLO' puts sock.read(5) # Since the response message has 5 bytes. sock.close ``` Using the code suggested by kennycoc I get the following error message ``` Server.rb:3:in `initialize': Only one usage of each socket address (protocol/network address/port) is normally permitted. - bind(2) for nil port 1540 (Errno::EADDRINUSE) from Server.rb:3:in `new' from Server.rb:3:in `<main>' ```
2018/06/05
[ "https://Stackoverflow.com/questions/50706987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336879/" ]
@adjam you haven't created a TcpServer, [TCPSocket](https://ruby-doc.org/stdlib-1.9.3/libdoc/socket/rdoc/TCPSocket.html) is used to create TCP/IP client socket To create TCP/IP server you have to use [TCPServer](https://ruby-doc.org/stdlib-1.9.3/libdoc/socket/rdoc/TCPServer.html) EX: Tcp/ip Server code: ``` require 'socket' server = TCPServer.open(2000) client = server.accept # Accept client while (response = client.gets) # read data send by client print response end ``` Tcp/ip Client code: ``` require 'socket' client = TCPSocket.open('localhost', 2000) client.puts "hello" client.close; ```
`tcp_server.rb` ```rb require "socket" server = TCPServer.new(1234) loop do # Keep the server alive session = server.accept puts "Request arrived" session.write "Time is #{Time.now}" # Send data to client session.close end ``` `tcp_client.rb` ```rb require "socket" socket = TCPSocket.open("localhost", 1234) puts socket.gets # Print sever response socket.close ``` --- Now - If you want two-way communication between server and client use following `tcp_client.rb` ```rb require "socket" socket = TCPSocket.open("localhost", 1234) socket.puts "Sample data to server" # Send data to server puts socket.gets # Print sever response socket.close ``` `tcp_server.rb` ```rb require "socket" server = TCPServer.new 1234 loop do session = server.accept puts "Data recieved - #{session.gets}" # Read data from client session.write "Time is #{Time.now}" # Send data to clent session.close end ```
6,844,863
Relative import not working properly in python2.6.5 getting "ValueError: Attempted relative import in non-package". I am having all those `__init__.py` in proper place.
2011/07/27
[ "https://Stackoverflow.com/questions/6844863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/865438/" ]
I have seen that error before when running a script that is actually *inside* a package. To the interpreter, it appears as though the package is not a package. Try taking the script into another directory, putting your package inside your `pythonpath`, and import absolutely. Then, relative imports inside your package will work. NOTE: you can STILL not relatively import inside the end script - the easiest thing to do in this case is to make a "wrapper" script, that simply calls some entry point in your package. You can go even further here by using `setuptools` to create a [`setup.py`](http://peak.telecommunity.com/DevCenter/setuptools) for your package, to make it distributable. Then, as a part of that, [entry points](http://peak.telecommunity.com/DevCenter/setuptools#automatic-script-creation) would allow you to autogenerate scripts that called your package's code. **EDIT**: From your comment, it appears as though I wasn't quite clear. I'm not 100% sure of your directory structure because your comment above wasn't formatted, but I took it to be like this: ``` PythonEvent/ main.py __init__.py DBConnector/ __init__.py connector.py service/ __init__.py myservice.py ``` When in `myservice.py` you have the line `from ..DBConnector.connector import DBUpdate`, the interpreter tries to import it relatively, **UNLESS** you are running `myservice.py` directly. This is what it appears you are doing. Try making another dummy script outside of `PythonEvent/` that is simply as follows: ``` from PythonEvent.service import myservice if __name__ == '__main__': myservice.main() # or whatever the entry point is called in myservice. ``` Then, set your `PYTHONPATH` environment variable to point to the parent directory of `PythonEvent/` (or move `PythonEvent/` to your site-packages).
``` main.py setup.py Main Package/ -> __init__.py subpackage_a/ -> __init__.py module_a.py subpackage_b/ -> __init__.py module_b.py ``` i) ``` 1.You run python main.py 2.main.py does: import app.package_a.module_a 3.module_a.py does import app.package_b.module_b ``` ii) ``` Alternatively 2 or 3 could use: from app.package_a import module_a ``` > > That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then. > > > So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders. Thanks to <https://stackoverflow.com/a/1083169>
45,301,335
I am using Python + IPython for Data Science. I made a folder that contains all the modules I wrote, organised in packages, something like ``` python_workfolder | |---a | |---__init__.py | |---a1.py | |---a2.py | |---b | |---__init__.py | |---b1.py | |---b2.py | |---c | |---__init__.py | |---c1.py | |---c2.py | | |---script1.py |---script2.py ``` At the beginning of each session I ask IPython to autoreload modules: ``` %load_ext autoreload %autoreload 2 ``` Now... let's say a1.py contains a class, `A1`, that I want to call from one of the scripts. In the `__init__.p` of package `a` I import the module ``` import a1 ``` Then in the script I import the class I need ``` from a.a1 import A1 ``` If there is some error in class A1 and I modify it, there is no way to have Python reload it without restarting the kernel. I tried with `del a1`, `del sys.modules['a1']`, `del sys.modules['a']`. Each time it uses the old version of the class until I don't restart the kernel... anyone can give me some suggestions?
2017/07/25
[ "https://Stackoverflow.com/questions/45301335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558671/" ]
Just type: ``` last root ``` This will give you details of the IP addresses of machines where users logged in as root.
Without knowing your Input\_file I am providing this solution, so could you please try following and let me know if this helps you. ``` awk '{match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/);array[substr($0,RSTART,RLENGTH)]} END{for(i in array){print i,array[i]}}' Input_file ``` If above is not helping you then kindly show us sample Input\_file and expected output file too in code tags, so that we could help you in same.
32,031,111
I am trying to run a simple Python script with crontab, but I can’t get it to work. I can run a simple program in crontab when not using Python though. Here is the line I have in my Crontab file that does work: ``` * * * * * echo “cron test” >> /home/ftpuser/dev/mod_high_lows/hello.txt ``` I also can run this python script testit.py directly from the command line. This is my testit.py file that outputs a csv file. ``` #!/usr/bin/env python import f_file_handling _data = [(12,15,17)] f_file_handling.csv_out('my_file_test',_data) ``` The above file has a function I made, but I know it works since it does what I expect when I run the testit.py from the command line like this: ``` python testit.py ``` So I got Crontab to work on it's own and the testit.py file to work on it's own then I tried to run the testit.py file with Crontab. I did make the testit.py file executable with command: ``` chmod +x testit.py ``` And I see its executable because the file shows up in green in my linux command window when I’m in the proper directory. Now in the same Crontab file I used to run the earlier Crontab test I added the following line: ``` * * * * * /home/ftpuser/dev/mod_high_lows/testit.py ``` Yes, I am tying to get this to execute every minute, just trying to run the simplest test possible to get Crontab and Python to work together. Here is what I am using: * Ubuntu 14.04.2 LTS (GNU/Linux 3.13.0-52-generic x86\_64) * Python 2.7 The above are on a linux server I have set up. You see the shebang line at the top of my testit.py file, from my research this should work. As far as my testit.py python file, I wrote it on a windows machine and then transferred it to the server, but when crontab and python did not work together I also coded the file from the Linux command window using Nano text editor, but this makes no difference when trying to run the testit.py file through Crontab. So it does not run even when I write the testit.py code directly on the Linux server (just in case windows created hidden characters in my file).
2015/08/16
[ "https://Stackoverflow.com/questions/32031111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1087809/" ]
* cron runs commands in a limited environment. Only a few environment variables are automatically set. It loads the environment specified by `/etc/environment` and `/etc/security/pam_env.conf`, but not about the environment variables you might have set in your `.bashrc` or `.profile`. Set the crontab entry ``` * * * * * /usr/bin/env > /tmp/out ``` to take a look at what environment variables are actually set. Don't forget to remove the crontab entry once you have /tmp/out. * When running Python scripts, one important environment variable that you would probably need to set is PYTHONPATH. So at the top of your crontab add a PYTHONPATH setting such as: ``` PYTHONPATH=/home/ftpuser/dev/mod_high_lows ``` Be sure to add the directory which contains the `f_file_handling` module so Python will find the module when it runs the statement ``` import f_file_handling ``` * Finally, also note that cron [runs commands in your home directory](https://unix.stackexchange.com/a/38956/3330) by default. It would be better to be explicit however, and supply a full path whenever you specify a file in your script: ``` f_file_handling.csv_out('/path/to/my_file_test',_data) ```
I'm not sure if this will help, but I've always successfully managed to get python scripts to run successfully from cron by adding this line to the end of the crontab file: ``` @reboot python /home/ftpuser/dev/mod_high_lows/testit.py & ``` The `&` is necessary at the end of the line. If this is what you need, and you would like for this script to execute every minute, you could put the whole script in a loop and then put a one minute sleep at the end of each loop's iteration. You may also need to put a `sudo` before the python, although crontabs should run as root anyway so this probably won't be necessary. This method has worked for running scripts on boot up for my Raspberry Pi though.
32,031,111
I am trying to run a simple Python script with crontab, but I can’t get it to work. I can run a simple program in crontab when not using Python though. Here is the line I have in my Crontab file that does work: ``` * * * * * echo “cron test” >> /home/ftpuser/dev/mod_high_lows/hello.txt ``` I also can run this python script testit.py directly from the command line. This is my testit.py file that outputs a csv file. ``` #!/usr/bin/env python import f_file_handling _data = [(12,15,17)] f_file_handling.csv_out('my_file_test',_data) ``` The above file has a function I made, but I know it works since it does what I expect when I run the testit.py from the command line like this: ``` python testit.py ``` So I got Crontab to work on it's own and the testit.py file to work on it's own then I tried to run the testit.py file with Crontab. I did make the testit.py file executable with command: ``` chmod +x testit.py ``` And I see its executable because the file shows up in green in my linux command window when I’m in the proper directory. Now in the same Crontab file I used to run the earlier Crontab test I added the following line: ``` * * * * * /home/ftpuser/dev/mod_high_lows/testit.py ``` Yes, I am tying to get this to execute every minute, just trying to run the simplest test possible to get Crontab and Python to work together. Here is what I am using: * Ubuntu 14.04.2 LTS (GNU/Linux 3.13.0-52-generic x86\_64) * Python 2.7 The above are on a linux server I have set up. You see the shebang line at the top of my testit.py file, from my research this should work. As far as my testit.py python file, I wrote it on a windows machine and then transferred it to the server, but when crontab and python did not work together I also coded the file from the Linux command window using Nano text editor, but this makes no difference when trying to run the testit.py file through Crontab. So it does not run even when I write the testit.py code directly on the Linux server (just in case windows created hidden characters in my file).
2015/08/16
[ "https://Stackoverflow.com/questions/32031111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1087809/" ]
* cron runs commands in a limited environment. Only a few environment variables are automatically set. It loads the environment specified by `/etc/environment` and `/etc/security/pam_env.conf`, but not about the environment variables you might have set in your `.bashrc` or `.profile`. Set the crontab entry ``` * * * * * /usr/bin/env > /tmp/out ``` to take a look at what environment variables are actually set. Don't forget to remove the crontab entry once you have /tmp/out. * When running Python scripts, one important environment variable that you would probably need to set is PYTHONPATH. So at the top of your crontab add a PYTHONPATH setting such as: ``` PYTHONPATH=/home/ftpuser/dev/mod_high_lows ``` Be sure to add the directory which contains the `f_file_handling` module so Python will find the module when it runs the statement ``` import f_file_handling ``` * Finally, also note that cron [runs commands in your home directory](https://unix.stackexchange.com/a/38956/3330) by default. It would be better to be explicit however, and supply a full path whenever you specify a file in your script: ``` f_file_handling.csv_out('/path/to/my_file_test',_data) ```
One thing that always gets me: You have to leave a blank line at the end of the crontab file. Cron will not run the last line of the crontab!
62,714,282
In the [ThreadPoolExecutor documentation](https://docs.python.org/3/library/concurrent.futures.html) it says: > > Changed in version 3.5: If `max_workers` is `None` or not given, it will default to the number of processors on the machine, multiplied by 5, assuming that `ThreadPoolExecutor` is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for `ProcessPoolExecutor`. > > > Is there any reason why ThreadPoolExecutor uses a factor of 5, and is it important to use it for other threading applications in python?
2020/07/03
[ "https://Stackoverflow.com/questions/62714282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13859123/" ]
You are writing `binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii')` at the next line. Try writing it after the `return` keyword. Hope your error will go away
you should define a Clinet instance and then get it's \_public\_key: ``` binascii.hexlify(Client._public_key.exportKey(format='DER')).decode('ascii') ```
62,714,282
In the [ThreadPoolExecutor documentation](https://docs.python.org/3/library/concurrent.futures.html) it says: > > Changed in version 3.5: If `max_workers` is `None` or not given, it will default to the number of processors on the machine, multiplied by 5, assuming that `ThreadPoolExecutor` is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for `ProcessPoolExecutor`. > > > Is there any reason why ThreadPoolExecutor uses a factor of 5, and is it important to use it for other threading applications in python?
2020/07/03
[ "https://Stackoverflow.com/questions/62714282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13859123/" ]
You are writing `binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii')` at the next line. Try writing it after the `return` keyword. Hope your error will go away
You need to get the `identity` property with the help of a function, not as a plain attribute. Modify your `identity()` function as follows: ``` def identity(self): idn = binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii') # <------ return idn # <------ ``` And then, you can call it like: ``` Dinesh = Client() print(Dinesh.identity()) # <------ ```
38,044,788
it's login is fine, but i am not able to track the issue, here the code below ``` while True: time.sleep(10) browser.get("https://www.instagram.com/accounts/edit/?wo=1") ``` I am getting this error when i ran project.py ``` Superuser$ python project.py user diabruxaneas1989 with proxy 192.126.184.130:8800 running Traceback (most recent call last): File "project.py", line 158, in <module> Main() File "project.py", line 94, in Main username = browser.find_element_by_id('id_username') File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 269, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 745, in find_element {'using': by, 'value': value})['value'] File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute self.error_handler.check_response(response) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"id","selector":"id_username"} Stacktrace: at FirefoxDriver.prototype.findElementInternal_ (file:///var/folders/rc/vx_d14f14p97l02f35j6_dvw0000gn/T/tmp6I93xt/extensions/fxdriver@googlecode.com/components/driver-component.js:10770) at FirefoxDriver.prototype.findElement (file:///var/folders/rc/vx_d14f14p97l02f35j6_dvw0000gn/T/tmp6I93xt/extensions/fxdriver@googlecode.com/components/driver-component.js:10779) at DelayedCommand.prototype.executeInternal_/h (file:///var/folders/rc/vx_d14f14p97l02f35j6_dvw0000gn/T/tmp6I93xt/extensions/fxdriver@googlecode.com/components/command-processor.js:12661) at DelayedCommand.prototype.executeInternal_ (file:///var/folders/rc/vx_d14f14p97l02f35j6_dvw0000gn/T/tmp6I93xt/extensions/fxdriver@googlecode.com/components/command-processor.js:12666) at DelayedCommand.prototype.execute/< (file:///var/folders/rc/vx_d14f14p97l02f35j6_dvw0000gn/T/tmp6I93xt/extensions/fxdriver@googlecode.com/components/command-processor.js:12608) ``` I tried other solutions as well but still same error . Any help would be appreciated, Thanks
2016/06/27
[ "https://Stackoverflow.com/questions/38044788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6445447/" ]
You forgot to close the `href` attribute (double-quotes): ``` echo '<a href="directMessageRoom.php?directMessageRoomID='.$row3['id'].'"></a>'; right here ---^ ```
Be aware of lots of 'white-space' in your form field. Your submit button for example, you write this `<input type = "submit" ...>`. You are accidentally insert white space. It should be `<input type="submit" ...>`.
55,549,014
I get the syntax error: FileNotFoundError: [WinError 2] The system cannot find the file specified when running the below code. It is a little hard to find a good solution for this problem on windows which I am running as compared to UNIX which I can find working code for. ``` from subprocess import Popen, check_call p1 = Popen('start http://stackoverflow.com/') p2 = Popen('start http://www.google.com/') p3 = Popen('start http://www.facebook.com/') time.sleep(60) for pid in [p1.pid,p2.pid,p3.pid]: check_call(['taskkill', '/F', '/T', '/PID', str(pid)]) ``` I want the code to open the pages for 60 seconds and then close them. I know there is similar topic on the link: , but firstly it is for python 2 and I have tried the codes using the subprocess module and they are identical to the code I am using which does not work.
2019/04/06
[ "https://Stackoverflow.com/questions/55549014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6104634/" ]
A big problem there is that your width will be zero. The X and Y scales are factors. As in multipliers. Anything times Zero is zero. Hence ``` ScaleTransform(0, -1); ``` Will give you something with no width. You presumably want the same width and hence: ``` ScaleTransform(1, -1); ``` That might still have another problem if you want the thing to be flipped about it's centre but at least it ought to show up when you use it. The CenterY calculation is perhaps less than obvious. You can work out the height of a geometry using it's bounds. Since you're creating a new pathgeometry, maybe you want to retain the original without any transform. I put some code together that manipulates a geometry from resources and uses it to add a path to a canvas. Markup: ``` <Window.Resources> <Geometry x:Key="Star"> M16.001007,0L20.944,10.533997 32,12.223022 23.998993,20.421997 25.889008,32 16.001007,26.533997 6.1109924,32 8,20.421997 0,12.223022 11.057007,10.533997z </Geometry> </Window.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="100"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Button x:Name="myButton" Click="MyButton_Click"> </Button> <Canvas Grid.Column="1" Name="myCanvas"/> </Grid> ``` Code ``` private void MyButton_Click(object sender, RoutedEventArgs e) { Geometry geom = this.Resources["Star"] as Geometry; Geometry flipped = geom.Clone(); var bounds = geom.Bounds; double halfY = (bounds.Bottom - bounds.Top) / 2.0; flipped.Transform = new ScaleTransform(1, -1, 0, halfY ); PathGeometry pg = PathGeometry.CreateFromGeometry(flipped); var path = new System.Windows.Shapes.Path {Data=pg, Fill= System.Windows.Media.Brushes.Red }; this.myCanvas.Children.Add(path); } ```
Just set the PathGeometry's `Transform` property: ``` var myPathGeometry = new PathGeometry(); myPathGeometry.Figures.Add(myPathFigure); myPathGeometry.Transform = new ScaleTransform(1, -1); ``` Note that you may also need to set the ScaleTransform's `CenterY` property for a correct vertical alignment.
55,549,014
I get the syntax error: FileNotFoundError: [WinError 2] The system cannot find the file specified when running the below code. It is a little hard to find a good solution for this problem on windows which I am running as compared to UNIX which I can find working code for. ``` from subprocess import Popen, check_call p1 = Popen('start http://stackoverflow.com/') p2 = Popen('start http://www.google.com/') p3 = Popen('start http://www.facebook.com/') time.sleep(60) for pid in [p1.pid,p2.pid,p3.pid]: check_call(['taskkill', '/F', '/T', '/PID', str(pid)]) ``` I want the code to open the pages for 60 seconds and then close them. I know there is similar topic on the link: , but firstly it is for python 2 and I have tried the codes using the subprocess module and they are identical to the code I am using which does not work.
2019/04/06
[ "https://Stackoverflow.com/questions/55549014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6104634/" ]
Just set the PathGeometry's `Transform` property: ``` var myPathGeometry = new PathGeometry(); myPathGeometry.Figures.Add(myPathFigure); myPathGeometry.Transform = new ScaleTransform(1, -1); ``` Note that you may also need to set the ScaleTransform's `CenterY` property for a correct vertical alignment.
Both @Andy and @Clemens gave right answers. The reason why I didn't get the expected shape is because I didn't notice that the shape is outside the screen region. However, I used Andy's solution because I need to keep the original shape. Also, he notified me about creating new bounds. The only thing I changed in his answer is the value of the new bounds because with the one that he used, the shape was still outside the screen region. ``` double newY = (bounds.Bottom - bounds.Top); ```
55,549,014
I get the syntax error: FileNotFoundError: [WinError 2] The system cannot find the file specified when running the below code. It is a little hard to find a good solution for this problem on windows which I am running as compared to UNIX which I can find working code for. ``` from subprocess import Popen, check_call p1 = Popen('start http://stackoverflow.com/') p2 = Popen('start http://www.google.com/') p3 = Popen('start http://www.facebook.com/') time.sleep(60) for pid in [p1.pid,p2.pid,p3.pid]: check_call(['taskkill', '/F', '/T', '/PID', str(pid)]) ``` I want the code to open the pages for 60 seconds and then close them. I know there is similar topic on the link: , but firstly it is for python 2 and I have tried the codes using the subprocess module and they are identical to the code I am using which does not work.
2019/04/06
[ "https://Stackoverflow.com/questions/55549014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6104634/" ]
A big problem there is that your width will be zero. The X and Y scales are factors. As in multipliers. Anything times Zero is zero. Hence ``` ScaleTransform(0, -1); ``` Will give you something with no width. You presumably want the same width and hence: ``` ScaleTransform(1, -1); ``` That might still have another problem if you want the thing to be flipped about it's centre but at least it ought to show up when you use it. The CenterY calculation is perhaps less than obvious. You can work out the height of a geometry using it's bounds. Since you're creating a new pathgeometry, maybe you want to retain the original without any transform. I put some code together that manipulates a geometry from resources and uses it to add a path to a canvas. Markup: ``` <Window.Resources> <Geometry x:Key="Star"> M16.001007,0L20.944,10.533997 32,12.223022 23.998993,20.421997 25.889008,32 16.001007,26.533997 6.1109924,32 8,20.421997 0,12.223022 11.057007,10.533997z </Geometry> </Window.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="100"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Button x:Name="myButton" Click="MyButton_Click"> </Button> <Canvas Grid.Column="1" Name="myCanvas"/> </Grid> ``` Code ``` private void MyButton_Click(object sender, RoutedEventArgs e) { Geometry geom = this.Resources["Star"] as Geometry; Geometry flipped = geom.Clone(); var bounds = geom.Bounds; double halfY = (bounds.Bottom - bounds.Top) / 2.0; flipped.Transform = new ScaleTransform(1, -1, 0, halfY ); PathGeometry pg = PathGeometry.CreateFromGeometry(flipped); var path = new System.Windows.Shapes.Path {Data=pg, Fill= System.Windows.Media.Brushes.Red }; this.myCanvas.Children.Add(path); } ```
Both @Andy and @Clemens gave right answers. The reason why I didn't get the expected shape is because I didn't notice that the shape is outside the screen region. However, I used Andy's solution because I need to keep the original shape. Also, he notified me about creating new bounds. The only thing I changed in his answer is the value of the new bounds because with the one that he used, the shape was still outside the screen region. ``` double newY = (bounds.Bottom - bounds.Top); ```
63,614,832
I've faced an global issue recently and I have no idea for this behavior in python: ``` # declaring some global variables variable = 'peter' list_variable_1 = ['a','b'] list_variable_2 = ['c','d'] def update_global_variables(): """without using global line""" variable = 'PETER' # won't update in global scope list_variable_1 = ['A','B'] # won't get updated in global scope list_variable_2[0]= 'C' # updated in global scope surprisingly this way list_variable_2[1]= 'D' # updated in global scope surprisingly this way update_global_variables() print('variable is: %s'%variable) # prints peter print('list_variable_1 is: %s'%list_variable_1) # prints ['a', 'b'] print('list_variable_2 is: %s'%list_variable_2) # prints ['C', 'D'] ``` Why did `list_variable_2` is updated in global scope while the other variables did not?
2020/08/27
[ "https://Stackoverflow.com/questions/63614832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6756530/" ]
from [exitBeforeEnter](https://www.framer.com/api/motion/animate-presence/#animatepresenceprops.exitbeforeenter) docs > > If set to `true`, `AnimatePresence` will only render one component at a time. The exiting component will finished its exit animation before the entering component is rendered. > > > You have to specify `exit` animations for all components that you are using inside `AnimatePresence`. On route changes, `AnimatePresence` will execute `exit` animations first and then only it will render next component. If a component does not have `exit` animation and it is child of `AnimatePresence`, then route change will only change the url not the view.
That's normal if you will not add an `exit` animation to each and every routes. Main route with AnimatePresense ``` <AnimatePresence exitBeforeEnter> <Switch location={window.location} key={window.location.pathname}> <Route exact path='/' component={Home} /> <Route exact path='/about' component={About} /> <Route path="*">Page not found</Route> </Switch> </AnimatePresence ``` About.jsx ``` const exit = { exit: { opacity: 0, }, } export default function About() { return <motion.h1 {...exit}>Hello</h1> } ``` Home.jsx ``` const exit = { exit: { opacity: 0, }, } export default function Home() { return <motion.h1 {...exit}>Hello</h1> } ```
63,614,832
I've faced an global issue recently and I have no idea for this behavior in python: ``` # declaring some global variables variable = 'peter' list_variable_1 = ['a','b'] list_variable_2 = ['c','d'] def update_global_variables(): """without using global line""" variable = 'PETER' # won't update in global scope list_variable_1 = ['A','B'] # won't get updated in global scope list_variable_2[0]= 'C' # updated in global scope surprisingly this way list_variable_2[1]= 'D' # updated in global scope surprisingly this way update_global_variables() print('variable is: %s'%variable) # prints peter print('list_variable_1 is: %s'%list_variable_1) # prints ['a', 'b'] print('list_variable_2 is: %s'%list_variable_2) # prints ['C', 'D'] ``` Why did `list_variable_2` is updated in global scope while the other variables did not?
2020/08/27
[ "https://Stackoverflow.com/questions/63614832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6756530/" ]
from [exitBeforeEnter](https://www.framer.com/api/motion/animate-presence/#animatepresenceprops.exitbeforeenter) docs > > If set to `true`, `AnimatePresence` will only render one component at a time. The exiting component will finished its exit animation before the entering component is rendered. > > > You have to specify `exit` animations for all components that you are using inside `AnimatePresence`. On route changes, `AnimatePresence` will execute `exit` animations first and then only it will render next component. If a component does not have `exit` animation and it is child of `AnimatePresence`, then route change will only change the url not the view.
For those of you still lost, you need to wrap the <motion.div> tag AROUND the < redirect > tag with an "exit" parameter as mentioned in the other answers. Example code is provided below. ``` return ( <motion.div exit='exit' variants={PageTransition} initial='hidden' animate='show' className='login-container'> <Redirect to='/Dashboard' /> </motion.div> ); ```
63,614,832
I've faced an global issue recently and I have no idea for this behavior in python: ``` # declaring some global variables variable = 'peter' list_variable_1 = ['a','b'] list_variable_2 = ['c','d'] def update_global_variables(): """without using global line""" variable = 'PETER' # won't update in global scope list_variable_1 = ['A','B'] # won't get updated in global scope list_variable_2[0]= 'C' # updated in global scope surprisingly this way list_variable_2[1]= 'D' # updated in global scope surprisingly this way update_global_variables() print('variable is: %s'%variable) # prints peter print('list_variable_1 is: %s'%list_variable_1) # prints ['a', 'b'] print('list_variable_2 is: %s'%list_variable_2) # prints ['C', 'D'] ``` Why did `list_variable_2` is updated in global scope while the other variables did not?
2020/08/27
[ "https://Stackoverflow.com/questions/63614832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6756530/" ]
from [exitBeforeEnter](https://www.framer.com/api/motion/animate-presence/#animatepresenceprops.exitbeforeenter) docs > > If set to `true`, `AnimatePresence` will only render one component at a time. The exiting component will finished its exit animation before the entering component is rendered. > > > You have to specify `exit` animations for all components that you are using inside `AnimatePresence`. On route changes, `AnimatePresence` will execute `exit` animations first and then only it will render next component. If a component does not have `exit` animation and it is child of `AnimatePresence`, then route change will only change the url not the view.
Does anyone have an update with react-router-dom v6 ? I'm rewriting a small app I made some months ago, and it was working perfectly before, with `AnimatePresence` and `Switch` Router components. Exit transitions were running successfully between pages changes. Now for some reason, exit transitions don't trigger on page change, and I suspect it may be because of the changes made to react-router-dom API and components use. In react-router-dom v6, it looks more like that : ```js const App = function () { return ( <AnimatePresence exitBeforeEnter> <BrowserRouter> <Routes> <Route path="/" element={<Layout />}> <Route path="characters" element={<Characters />} /> </Route> <Route path="login" element={<Login />} /> </Routes> </BrowserRouter> </AnimatePresence> ); }; ``` And the `Layout` component : ```js <motion.div key="layout" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.7 }} > <Menu /> <div> <Outlet /> </div> </motion.div> ``` Exit transition doesn't trigger, unfortunately.
63,614,832
I've faced an global issue recently and I have no idea for this behavior in python: ``` # declaring some global variables variable = 'peter' list_variable_1 = ['a','b'] list_variable_2 = ['c','d'] def update_global_variables(): """without using global line""" variable = 'PETER' # won't update in global scope list_variable_1 = ['A','B'] # won't get updated in global scope list_variable_2[0]= 'C' # updated in global scope surprisingly this way list_variable_2[1]= 'D' # updated in global scope surprisingly this way update_global_variables() print('variable is: %s'%variable) # prints peter print('list_variable_1 is: %s'%list_variable_1) # prints ['a', 'b'] print('list_variable_2 is: %s'%list_variable_2) # prints ['C', 'D'] ``` Why did `list_variable_2` is updated in global scope while the other variables did not?
2020/08/27
[ "https://Stackoverflow.com/questions/63614832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6756530/" ]
That's normal if you will not add an `exit` animation to each and every routes. Main route with AnimatePresense ``` <AnimatePresence exitBeforeEnter> <Switch location={window.location} key={window.location.pathname}> <Route exact path='/' component={Home} /> <Route exact path='/about' component={About} /> <Route path="*">Page not found</Route> </Switch> </AnimatePresence ``` About.jsx ``` const exit = { exit: { opacity: 0, }, } export default function About() { return <motion.h1 {...exit}>Hello</h1> } ``` Home.jsx ``` const exit = { exit: { opacity: 0, }, } export default function Home() { return <motion.h1 {...exit}>Hello</h1> } ```
For those of you still lost, you need to wrap the <motion.div> tag AROUND the < redirect > tag with an "exit" parameter as mentioned in the other answers. Example code is provided below. ``` return ( <motion.div exit='exit' variants={PageTransition} initial='hidden' animate='show' className='login-container'> <Redirect to='/Dashboard' /> </motion.div> ); ```
63,614,832
I've faced an global issue recently and I have no idea for this behavior in python: ``` # declaring some global variables variable = 'peter' list_variable_1 = ['a','b'] list_variable_2 = ['c','d'] def update_global_variables(): """without using global line""" variable = 'PETER' # won't update in global scope list_variable_1 = ['A','B'] # won't get updated in global scope list_variable_2[0]= 'C' # updated in global scope surprisingly this way list_variable_2[1]= 'D' # updated in global scope surprisingly this way update_global_variables() print('variable is: %s'%variable) # prints peter print('list_variable_1 is: %s'%list_variable_1) # prints ['a', 'b'] print('list_variable_2 is: %s'%list_variable_2) # prints ['C', 'D'] ``` Why did `list_variable_2` is updated in global scope while the other variables did not?
2020/08/27
[ "https://Stackoverflow.com/questions/63614832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6756530/" ]
That's normal if you will not add an `exit` animation to each and every routes. Main route with AnimatePresense ``` <AnimatePresence exitBeforeEnter> <Switch location={window.location} key={window.location.pathname}> <Route exact path='/' component={Home} /> <Route exact path='/about' component={About} /> <Route path="*">Page not found</Route> </Switch> </AnimatePresence ``` About.jsx ``` const exit = { exit: { opacity: 0, }, } export default function About() { return <motion.h1 {...exit}>Hello</h1> } ``` Home.jsx ``` const exit = { exit: { opacity: 0, }, } export default function Home() { return <motion.h1 {...exit}>Hello</h1> } ```
Does anyone have an update with react-router-dom v6 ? I'm rewriting a small app I made some months ago, and it was working perfectly before, with `AnimatePresence` and `Switch` Router components. Exit transitions were running successfully between pages changes. Now for some reason, exit transitions don't trigger on page change, and I suspect it may be because of the changes made to react-router-dom API and components use. In react-router-dom v6, it looks more like that : ```js const App = function () { return ( <AnimatePresence exitBeforeEnter> <BrowserRouter> <Routes> <Route path="/" element={<Layout />}> <Route path="characters" element={<Characters />} /> </Route> <Route path="login" element={<Login />} /> </Routes> </BrowserRouter> </AnimatePresence> ); }; ``` And the `Layout` component : ```js <motion.div key="layout" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.7 }} > <Menu /> <div> <Outlet /> </div> </motion.div> ``` Exit transition doesn't trigger, unfortunately.
63,614,832
I've faced an global issue recently and I have no idea for this behavior in python: ``` # declaring some global variables variable = 'peter' list_variable_1 = ['a','b'] list_variable_2 = ['c','d'] def update_global_variables(): """without using global line""" variable = 'PETER' # won't update in global scope list_variable_1 = ['A','B'] # won't get updated in global scope list_variable_2[0]= 'C' # updated in global scope surprisingly this way list_variable_2[1]= 'D' # updated in global scope surprisingly this way update_global_variables() print('variable is: %s'%variable) # prints peter print('list_variable_1 is: %s'%list_variable_1) # prints ['a', 'b'] print('list_variable_2 is: %s'%list_variable_2) # prints ['C', 'D'] ``` Why did `list_variable_2` is updated in global scope while the other variables did not?
2020/08/27
[ "https://Stackoverflow.com/questions/63614832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6756530/" ]
For those of you still lost, you need to wrap the <motion.div> tag AROUND the < redirect > tag with an "exit" parameter as mentioned in the other answers. Example code is provided below. ``` return ( <motion.div exit='exit' variants={PageTransition} initial='hidden' animate='show' className='login-container'> <Redirect to='/Dashboard' /> </motion.div> ); ```
Does anyone have an update with react-router-dom v6 ? I'm rewriting a small app I made some months ago, and it was working perfectly before, with `AnimatePresence` and `Switch` Router components. Exit transitions were running successfully between pages changes. Now for some reason, exit transitions don't trigger on page change, and I suspect it may be because of the changes made to react-router-dom API and components use. In react-router-dom v6, it looks more like that : ```js const App = function () { return ( <AnimatePresence exitBeforeEnter> <BrowserRouter> <Routes> <Route path="/" element={<Layout />}> <Route path="characters" element={<Characters />} /> </Route> <Route path="login" element={<Login />} /> </Routes> </BrowserRouter> </AnimatePresence> ); }; ``` And the `Layout` component : ```js <motion.div key="layout" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.7 }} > <Menu /> <div> <Outlet /> </div> </motion.div> ``` Exit transition doesn't trigger, unfortunately.
11,767,757
This issue just started, last week I had no issues with the particular source file. I'm using SQLAlchemy and Geoalchemy and the particular block of code that triggers Eclipse and Aptana to start pegging the cpu while simply editing the file is: ``` obsRecs = db.session.query(multi_obs)\ .join(sensor,sensor.row_id == multi_obs.sensor_id)\ .join(platform,platform.row_id == sensor.platform_id)\ .join(m_type,m_type.row_id == multi_obs.m_type_id)\ .join(m_scalar_type,m_scalar_type.row_id == m_type.m_scalar_type_id)\ .join(obs_type,obs_type.row_id == m_scalar_type.obs_type_id)\ .join(uom_type,uom_type.row_id == m_scalar_type.uom_type_id)\ .filter(multi_obs.m_date > dateOffset)\ .filter(multi_obs.m_type_id.in_(mTypes))\ .filter(multi_obs.d_top_of_hour == 1)\ .filter(platform.active < 3)\ .filter(platform.the_geom.within(WKTSpatialElement(bboxPoly, -1)))\ .order_by(platform.row_id)\ .all() ``` As soon as I start editing anything in that block, the issue occurs. I've cut out that bit of code and edited other areas in the file, and I have no problems. I've edited other python files with no problems as well. At first I thought there was some issue with code completion, so I turned that off and still get the issue. I was using Eclipse Indigo and if I did not Force Quit the app, an out of memory Java error would get thrown. In Aptana the cpu spikes, then will go back to an idle usage, then spike again if I started editing again. My setup: OS X Lion Java(TM) SE Runtime Environment (build 1.6.0\_31-b04-415-11M3646) Java HotSpot(TM) 64-Bit Server VM (build 20.6-b01-415, mixed mode) i7 Quad core, 8Gb RAM I thought the issue may have been triggered by the latest java update from Apple, so I rolled back the entire machine via Time Machine to a pre-update state and still have the issue. I'd appreciate any pointers, I am at the point of trying to find a non-PyDev based solution. **Edit** Allowing Eclipse to run until erroring out, Console.App does show the following: ``` 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: Exception in thread "[Timer] - Main Queue Handler" Exception in thread "Poller SunPKCS11-Darwin" 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: java.lang.OutOfMemoryError: Java heap space 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.wrapper.PKCS11.C_GetSlotInfo(Native Method) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11.initToken(SunPKCS11.java:767) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11.access$100(SunPKCS11.java:42) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11$TokenPoller.run(SunPKCS11.java:700) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.Thread.run(Thread.java:680) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: java.lang.OutOfMemoryError: Java heap space 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:45) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.StringBuffer.<init>(StringBuffer.java:103) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at org.eclipse.equinox.internal.util.impl.tpt.threadpool.ThreadPoolFactoryImpl.execute0(ThreadPoolFactoryImpl.java:94) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at org.eclipse.equinox.internal.util.impl.tpt.timer.TimerImpl.run(TimerImpl.java:110) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.Thread.run(Thread.java:680) ``` **Edit 2** Grabbed the Oracle JDK, set the system to use it. Same issue. **EDIT 3** Similar problem is still occurring after a restore from backups. This issue must have been lurking and the code block managed to be just right to trigger it. Code completion engine is still prime suspect.
2012/08/01
[ "https://Stackoverflow.com/questions/11767757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1569769/" ]
I was running into the same problem but for a different, long query. I tried disabling auto-complete, tried the `-clean` thing, no luck. To fix, I waited for the memory leak to explode and used `jmap.exe` to dump the heap. I then ran Eclipse Memory Analyzer to see where my memory was going, the screenshot is attached below. There was something about `com.python.pydev.refactoring.markoccurrences.MarkOccurrencesJob` in the job, so I disabled that option in Preferences->Pydev->Editor. Ever since I did that Eclipse is a speed demon and no more crashing. Someone with some street cred should post this as a bug at pydev. ![enter image description here](https://i.stack.imgur.com/l1WOW.png)
In the past I have had some success solving Eclipse insanity by starting with a clean workspace. It's kind of a shot in the dark, but try the following one by one: 1. Start eclipse with the `-clean` option and the existing workspace. 2. If the above does not work, try editing the same file in a new workspace. If you look in the Console.app, when editing the file, do you seen any relevant log messages ? Does the Error Log View inside eclipse throw up any error messages when you try to edit the file in Aptana ? **Update** I just tried reproducing this in Eclipse Juno on Window 7 64 Bit and no problems with it: ![enter image description here](https://i.stack.imgur.com/3bpGt.png) I think it might be a time taking exercise, but would it be possible for you to upgrade to Eclipse Juno ?
11,767,757
This issue just started, last week I had no issues with the particular source file. I'm using SQLAlchemy and Geoalchemy and the particular block of code that triggers Eclipse and Aptana to start pegging the cpu while simply editing the file is: ``` obsRecs = db.session.query(multi_obs)\ .join(sensor,sensor.row_id == multi_obs.sensor_id)\ .join(platform,platform.row_id == sensor.platform_id)\ .join(m_type,m_type.row_id == multi_obs.m_type_id)\ .join(m_scalar_type,m_scalar_type.row_id == m_type.m_scalar_type_id)\ .join(obs_type,obs_type.row_id == m_scalar_type.obs_type_id)\ .join(uom_type,uom_type.row_id == m_scalar_type.uom_type_id)\ .filter(multi_obs.m_date > dateOffset)\ .filter(multi_obs.m_type_id.in_(mTypes))\ .filter(multi_obs.d_top_of_hour == 1)\ .filter(platform.active < 3)\ .filter(platform.the_geom.within(WKTSpatialElement(bboxPoly, -1)))\ .order_by(platform.row_id)\ .all() ``` As soon as I start editing anything in that block, the issue occurs. I've cut out that bit of code and edited other areas in the file, and I have no problems. I've edited other python files with no problems as well. At first I thought there was some issue with code completion, so I turned that off and still get the issue. I was using Eclipse Indigo and if I did not Force Quit the app, an out of memory Java error would get thrown. In Aptana the cpu spikes, then will go back to an idle usage, then spike again if I started editing again. My setup: OS X Lion Java(TM) SE Runtime Environment (build 1.6.0\_31-b04-415-11M3646) Java HotSpot(TM) 64-Bit Server VM (build 20.6-b01-415, mixed mode) i7 Quad core, 8Gb RAM I thought the issue may have been triggered by the latest java update from Apple, so I rolled back the entire machine via Time Machine to a pre-update state and still have the issue. I'd appreciate any pointers, I am at the point of trying to find a non-PyDev based solution. **Edit** Allowing Eclipse to run until erroring out, Console.App does show the following: ``` 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: Exception in thread "[Timer] - Main Queue Handler" Exception in thread "Poller SunPKCS11-Darwin" 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: java.lang.OutOfMemoryError: Java heap space 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.wrapper.PKCS11.C_GetSlotInfo(Native Method) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11.initToken(SunPKCS11.java:767) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11.access$100(SunPKCS11.java:42) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11$TokenPoller.run(SunPKCS11.java:700) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.Thread.run(Thread.java:680) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: java.lang.OutOfMemoryError: Java heap space 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:45) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.StringBuffer.<init>(StringBuffer.java:103) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at org.eclipse.equinox.internal.util.impl.tpt.threadpool.ThreadPoolFactoryImpl.execute0(ThreadPoolFactoryImpl.java:94) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at org.eclipse.equinox.internal.util.impl.tpt.timer.TimerImpl.run(TimerImpl.java:110) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.Thread.run(Thread.java:680) ``` **Edit 2** Grabbed the Oracle JDK, set the system to use it. Same issue. **EDIT 3** Similar problem is still occurring after a restore from backups. This issue must have been lurking and the code block managed to be just right to trigger it. Code completion engine is still prime suspect.
2012/08/01
[ "https://Stackoverflow.com/questions/11767757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1569769/" ]
In the past I have had some success solving Eclipse insanity by starting with a clean workspace. It's kind of a shot in the dark, but try the following one by one: 1. Start eclipse with the `-clean` option and the existing workspace. 2. If the above does not work, try editing the same file in a new workspace. If you look in the Console.app, when editing the file, do you seen any relevant log messages ? Does the Error Log View inside eclipse throw up any error messages when you try to edit the file in Aptana ? **Update** I just tried reproducing this in Eclipse Juno on Window 7 64 Bit and no problems with it: ![enter image description here](https://i.stack.imgur.com/3bpGt.png) I think it might be a time taking exercise, but would it be possible for you to upgrade to Eclipse Juno ?
Again I too ran into this problem. I followed all the usual advice about memory settings, disabling code completion etc. I was running Eclipse 4.2 on Mountain Lion. I tried upgrading to 4.3 and even tried the 4.3 32 bit version. nothing was working. I casually noticed that one Python module in particular was the cause of my troubles, which ultimately resulted in my solution. I have not gone into the why but the problem was with SQLAlchemy. I should qualify this and say that the problem was a very large Python module with many and long SQLAlchemy queries there in. I split the SQLAlchemy queries into separate Python modules, which I did not like doing and that solved the problem. In this instance I would rather that Eclipse worked than having all my code in one module.
11,767,757
This issue just started, last week I had no issues with the particular source file. I'm using SQLAlchemy and Geoalchemy and the particular block of code that triggers Eclipse and Aptana to start pegging the cpu while simply editing the file is: ``` obsRecs = db.session.query(multi_obs)\ .join(sensor,sensor.row_id == multi_obs.sensor_id)\ .join(platform,platform.row_id == sensor.platform_id)\ .join(m_type,m_type.row_id == multi_obs.m_type_id)\ .join(m_scalar_type,m_scalar_type.row_id == m_type.m_scalar_type_id)\ .join(obs_type,obs_type.row_id == m_scalar_type.obs_type_id)\ .join(uom_type,uom_type.row_id == m_scalar_type.uom_type_id)\ .filter(multi_obs.m_date > dateOffset)\ .filter(multi_obs.m_type_id.in_(mTypes))\ .filter(multi_obs.d_top_of_hour == 1)\ .filter(platform.active < 3)\ .filter(platform.the_geom.within(WKTSpatialElement(bboxPoly, -1)))\ .order_by(platform.row_id)\ .all() ``` As soon as I start editing anything in that block, the issue occurs. I've cut out that bit of code and edited other areas in the file, and I have no problems. I've edited other python files with no problems as well. At first I thought there was some issue with code completion, so I turned that off and still get the issue. I was using Eclipse Indigo and if I did not Force Quit the app, an out of memory Java error would get thrown. In Aptana the cpu spikes, then will go back to an idle usage, then spike again if I started editing again. My setup: OS X Lion Java(TM) SE Runtime Environment (build 1.6.0\_31-b04-415-11M3646) Java HotSpot(TM) 64-Bit Server VM (build 20.6-b01-415, mixed mode) i7 Quad core, 8Gb RAM I thought the issue may have been triggered by the latest java update from Apple, so I rolled back the entire machine via Time Machine to a pre-update state and still have the issue. I'd appreciate any pointers, I am at the point of trying to find a non-PyDev based solution. **Edit** Allowing Eclipse to run until erroring out, Console.App does show the following: ``` 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: Exception in thread "[Timer] - Main Queue Handler" Exception in thread "Poller SunPKCS11-Darwin" 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: java.lang.OutOfMemoryError: Java heap space 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.wrapper.PKCS11.C_GetSlotInfo(Native Method) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11.initToken(SunPKCS11.java:767) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11.access$100(SunPKCS11.java:42) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11$TokenPoller.run(SunPKCS11.java:700) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.Thread.run(Thread.java:680) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: java.lang.OutOfMemoryError: Java heap space 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:45) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.StringBuffer.<init>(StringBuffer.java:103) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at org.eclipse.equinox.internal.util.impl.tpt.threadpool.ThreadPoolFactoryImpl.execute0(ThreadPoolFactoryImpl.java:94) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at org.eclipse.equinox.internal.util.impl.tpt.timer.TimerImpl.run(TimerImpl.java:110) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.Thread.run(Thread.java:680) ``` **Edit 2** Grabbed the Oracle JDK, set the system to use it. Same issue. **EDIT 3** Similar problem is still occurring after a restore from backups. This issue must have been lurking and the code block managed to be just right to trigger it. Code completion engine is still prime suspect.
2012/08/01
[ "https://Stackoverflow.com/questions/11767757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1569769/" ]
I was running into the same problem but for a different, long query. I tried disabling auto-complete, tried the `-clean` thing, no luck. To fix, I waited for the memory leak to explode and used `jmap.exe` to dump the heap. I then ran Eclipse Memory Analyzer to see where my memory was going, the screenshot is attached below. There was something about `com.python.pydev.refactoring.markoccurrences.MarkOccurrencesJob` in the job, so I disabled that option in Preferences->Pydev->Editor. Ever since I did that Eclipse is a speed demon and no more crashing. Someone with some street cred should post this as a bug at pydev. ![enter image description here](https://i.stack.imgur.com/l1WOW.png)
For me that appears like a bug in the PyDev type inference engine... (could be looping until an out of memory error occurs). Just with that subset of your code I was not able to reproduce it here (i.e.: installing sqlalchemy and geoalchemy, creating a project with that file as a source file and working with the file did all work properly). So, ideally, please create a project where that can be reproduced and create a bug report attaching that project (See: <http://pydev.org/about.html> for details on where to create the bug report). Also, please provide a link here in stack overflow as a reference. Now, having said that, it may be that it's only some memory spike which would work later on (if that was the case, you could try raising the -Xmx flag in Eclipse.ini to something bigger -- although if you're in 32 bit java/Eclipse, that value should probably not be higher than 600m - 700m). Still, even if that's the case, please consider reporting that as a bug related to having too much memory used in that use-case (but please provide a project as a scenario on how to reproduce that).
11,767,757
This issue just started, last week I had no issues with the particular source file. I'm using SQLAlchemy and Geoalchemy and the particular block of code that triggers Eclipse and Aptana to start pegging the cpu while simply editing the file is: ``` obsRecs = db.session.query(multi_obs)\ .join(sensor,sensor.row_id == multi_obs.sensor_id)\ .join(platform,platform.row_id == sensor.platform_id)\ .join(m_type,m_type.row_id == multi_obs.m_type_id)\ .join(m_scalar_type,m_scalar_type.row_id == m_type.m_scalar_type_id)\ .join(obs_type,obs_type.row_id == m_scalar_type.obs_type_id)\ .join(uom_type,uom_type.row_id == m_scalar_type.uom_type_id)\ .filter(multi_obs.m_date > dateOffset)\ .filter(multi_obs.m_type_id.in_(mTypes))\ .filter(multi_obs.d_top_of_hour == 1)\ .filter(platform.active < 3)\ .filter(platform.the_geom.within(WKTSpatialElement(bboxPoly, -1)))\ .order_by(platform.row_id)\ .all() ``` As soon as I start editing anything in that block, the issue occurs. I've cut out that bit of code and edited other areas in the file, and I have no problems. I've edited other python files with no problems as well. At first I thought there was some issue with code completion, so I turned that off and still get the issue. I was using Eclipse Indigo and if I did not Force Quit the app, an out of memory Java error would get thrown. In Aptana the cpu spikes, then will go back to an idle usage, then spike again if I started editing again. My setup: OS X Lion Java(TM) SE Runtime Environment (build 1.6.0\_31-b04-415-11M3646) Java HotSpot(TM) 64-Bit Server VM (build 20.6-b01-415, mixed mode) i7 Quad core, 8Gb RAM I thought the issue may have been triggered by the latest java update from Apple, so I rolled back the entire machine via Time Machine to a pre-update state and still have the issue. I'd appreciate any pointers, I am at the point of trying to find a non-PyDev based solution. **Edit** Allowing Eclipse to run until erroring out, Console.App does show the following: ``` 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: Exception in thread "[Timer] - Main Queue Handler" Exception in thread "Poller SunPKCS11-Darwin" 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: java.lang.OutOfMemoryError: Java heap space 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.wrapper.PKCS11.C_GetSlotInfo(Native Method) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11.initToken(SunPKCS11.java:767) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11.access$100(SunPKCS11.java:42) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11$TokenPoller.run(SunPKCS11.java:700) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.Thread.run(Thread.java:680) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: java.lang.OutOfMemoryError: Java heap space 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:45) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.StringBuffer.<init>(StringBuffer.java:103) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at org.eclipse.equinox.internal.util.impl.tpt.threadpool.ThreadPoolFactoryImpl.execute0(ThreadPoolFactoryImpl.java:94) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at org.eclipse.equinox.internal.util.impl.tpt.timer.TimerImpl.run(TimerImpl.java:110) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.Thread.run(Thread.java:680) ``` **Edit 2** Grabbed the Oracle JDK, set the system to use it. Same issue. **EDIT 3** Similar problem is still occurring after a restore from backups. This issue must have been lurking and the code block managed to be just right to trigger it. Code completion engine is still prime suspect.
2012/08/01
[ "https://Stackoverflow.com/questions/11767757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1569769/" ]
For me that appears like a bug in the PyDev type inference engine... (could be looping until an out of memory error occurs). Just with that subset of your code I was not able to reproduce it here (i.e.: installing sqlalchemy and geoalchemy, creating a project with that file as a source file and working with the file did all work properly). So, ideally, please create a project where that can be reproduced and create a bug report attaching that project (See: <http://pydev.org/about.html> for details on where to create the bug report). Also, please provide a link here in stack overflow as a reference. Now, having said that, it may be that it's only some memory spike which would work later on (if that was the case, you could try raising the -Xmx flag in Eclipse.ini to something bigger -- although if you're in 32 bit java/Eclipse, that value should probably not be higher than 600m - 700m). Still, even if that's the case, please consider reporting that as a bug related to having too much memory used in that use-case (but please provide a project as a scenario on how to reproduce that).
Again I too ran into this problem. I followed all the usual advice about memory settings, disabling code completion etc. I was running Eclipse 4.2 on Mountain Lion. I tried upgrading to 4.3 and even tried the 4.3 32 bit version. nothing was working. I casually noticed that one Python module in particular was the cause of my troubles, which ultimately resulted in my solution. I have not gone into the why but the problem was with SQLAlchemy. I should qualify this and say that the problem was a very large Python module with many and long SQLAlchemy queries there in. I split the SQLAlchemy queries into separate Python modules, which I did not like doing and that solved the problem. In this instance I would rather that Eclipse worked than having all my code in one module.
11,767,757
This issue just started, last week I had no issues with the particular source file. I'm using SQLAlchemy and Geoalchemy and the particular block of code that triggers Eclipse and Aptana to start pegging the cpu while simply editing the file is: ``` obsRecs = db.session.query(multi_obs)\ .join(sensor,sensor.row_id == multi_obs.sensor_id)\ .join(platform,platform.row_id == sensor.platform_id)\ .join(m_type,m_type.row_id == multi_obs.m_type_id)\ .join(m_scalar_type,m_scalar_type.row_id == m_type.m_scalar_type_id)\ .join(obs_type,obs_type.row_id == m_scalar_type.obs_type_id)\ .join(uom_type,uom_type.row_id == m_scalar_type.uom_type_id)\ .filter(multi_obs.m_date > dateOffset)\ .filter(multi_obs.m_type_id.in_(mTypes))\ .filter(multi_obs.d_top_of_hour == 1)\ .filter(platform.active < 3)\ .filter(platform.the_geom.within(WKTSpatialElement(bboxPoly, -1)))\ .order_by(platform.row_id)\ .all() ``` As soon as I start editing anything in that block, the issue occurs. I've cut out that bit of code and edited other areas in the file, and I have no problems. I've edited other python files with no problems as well. At first I thought there was some issue with code completion, so I turned that off and still get the issue. I was using Eclipse Indigo and if I did not Force Quit the app, an out of memory Java error would get thrown. In Aptana the cpu spikes, then will go back to an idle usage, then spike again if I started editing again. My setup: OS X Lion Java(TM) SE Runtime Environment (build 1.6.0\_31-b04-415-11M3646) Java HotSpot(TM) 64-Bit Server VM (build 20.6-b01-415, mixed mode) i7 Quad core, 8Gb RAM I thought the issue may have been triggered by the latest java update from Apple, so I rolled back the entire machine via Time Machine to a pre-update state and still have the issue. I'd appreciate any pointers, I am at the point of trying to find a non-PyDev based solution. **Edit** Allowing Eclipse to run until erroring out, Console.App does show the following: ``` 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: Exception in thread "[Timer] - Main Queue Handler" Exception in thread "Poller SunPKCS11-Darwin" 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: java.lang.OutOfMemoryError: Java heap space 8/1/12 9:14:01.114 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.wrapper.PKCS11.C_GetSlotInfo(Native Method) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11.initToken(SunPKCS11.java:767) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11.access$100(SunPKCS11.java:42) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at sun.security.pkcs11.SunPKCS11$TokenPoller.run(SunPKCS11.java:700) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.Thread.run(Thread.java:680) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: java.lang.OutOfMemoryError: Java heap space 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:45) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.StringBuffer.<init>(StringBuffer.java:103) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at org.eclipse.equinox.internal.util.impl.tpt.threadpool.ThreadPoolFactoryImpl.execute0(ThreadPoolFactoryImpl.java:94) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at org.eclipse.equinox.internal.util.impl.tpt.timer.TimerImpl.run(TimerImpl.java:110) 8/1/12 9:14:01.115 PM [0x0-0x182182].org.eclipse.eclipse: at java.lang.Thread.run(Thread.java:680) ``` **Edit 2** Grabbed the Oracle JDK, set the system to use it. Same issue. **EDIT 3** Similar problem is still occurring after a restore from backups. This issue must have been lurking and the code block managed to be just right to trigger it. Code completion engine is still prime suspect.
2012/08/01
[ "https://Stackoverflow.com/questions/11767757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1569769/" ]
I was running into the same problem but for a different, long query. I tried disabling auto-complete, tried the `-clean` thing, no luck. To fix, I waited for the memory leak to explode and used `jmap.exe` to dump the heap. I then ran Eclipse Memory Analyzer to see where my memory was going, the screenshot is attached below. There was something about `com.python.pydev.refactoring.markoccurrences.MarkOccurrencesJob` in the job, so I disabled that option in Preferences->Pydev->Editor. Ever since I did that Eclipse is a speed demon and no more crashing. Someone with some street cred should post this as a bug at pydev. ![enter image description here](https://i.stack.imgur.com/l1WOW.png)
Again I too ran into this problem. I followed all the usual advice about memory settings, disabling code completion etc. I was running Eclipse 4.2 on Mountain Lion. I tried upgrading to 4.3 and even tried the 4.3 32 bit version. nothing was working. I casually noticed that one Python module in particular was the cause of my troubles, which ultimately resulted in my solution. I have not gone into the why but the problem was with SQLAlchemy. I should qualify this and say that the problem was a very large Python module with many and long SQLAlchemy queries there in. I split the SQLAlchemy queries into separate Python modules, which I did not like doing and that solved the problem. In this instance I would rather that Eclipse worked than having all my code in one module.
394,500
In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second? Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file. Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together.
2008/12/27
[ "https://Stackoverflow.com/questions/394500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9161/" ]
You should use the [Queue](http://docs.python.org/library/queue.html) module for sharing sequential data across threads. You would have to make a file-like Queue subclass, where .read and .write mutually block each other, with a buffer in-between. OTOH, I wonder why the first thread can't write to the real file in the first place.
I'm not clear what you're trying to do ehre. This sounds like a job for a regular old pipe, which is a file-like object. I'm guessing, however, that you mean you're got a stream of some other sort. It also sounds a lot like what you want is a python [Queue](http://docs.python.org/library/queue.html), or maybe a [tempfile](http://docs.python.org/library/tempfile.html#module-tempfile).
394,500
In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second? Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file. Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together.
2008/12/27
[ "https://Stackoverflow.com/questions/394500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9161/" ]
You should use the [Queue](http://docs.python.org/library/queue.html) module for sharing sequential data across threads. You would have to make a file-like Queue subclass, where .read and .write mutually block each other, with a buffer in-between. OTOH, I wonder why the first thread can't write to the real file in the first place.
I think there is something wrong in the design if you already have a file-like object if you want your data to end up in the subprocess. You should then arrange that they get written into the subprocess in the first place, rather than having them written into something else file-like first. Whoever is writing the data should allow the flexibility to specify the output stream, and that should be the subprocess pipe. Alternatively, if the writer insists on creating its own stream object, you should let it complete writing, and only then start the subprocess, feeding it from the result of first write. E.g. if it is a StringIO object, take its value after writing, and write it into the pipe; no need for thread synchronization here.
394,500
In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second? Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file. Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together.
2008/12/27
[ "https://Stackoverflow.com/questions/394500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9161/" ]
I think there is something wrong in the design if you already have a file-like object if you want your data to end up in the subprocess. You should then arrange that they get written into the subprocess in the first place, rather than having them written into something else file-like first. Whoever is writing the data should allow the flexibility to specify the output stream, and that should be the subprocess pipe. Alternatively, if the writer insists on creating its own stream object, you should let it complete writing, and only then start the subprocess, feeding it from the result of first write. E.g. if it is a StringIO object, take its value after writing, and write it into the pipe; no need for thread synchronization here.
I'm not clear what you're trying to do ehre. This sounds like a job for a regular old pipe, which is a file-like object. I'm guessing, however, that you mean you're got a stream of some other sort. It also sounds a lot like what you want is a python [Queue](http://docs.python.org/library/queue.html), or maybe a [tempfile](http://docs.python.org/library/tempfile.html#module-tempfile).
394,500
In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second? Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file. Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together.
2008/12/27
[ "https://Stackoverflow.com/questions/394500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9161/" ]
Use [`shutil`'s `copyfileobj()`](http://docs.python.org/library/shutil.html#shutil.copyfileobj) function: ``` import shutil import subprocess proc = subprocess.Popen([...], stdin=subprocess.PIPE) my_input = get_filelike_object('from a place not given in the question') shutil.copyfileobj(my_input, proc.stdin) ``` No need to use threads.
I'm not clear what you're trying to do ehre. This sounds like a job for a regular old pipe, which is a file-like object. I'm guessing, however, that you mean you're got a stream of some other sort. It also sounds a lot like what you want is a python [Queue](http://docs.python.org/library/queue.html), or maybe a [tempfile](http://docs.python.org/library/tempfile.html#module-tempfile).
394,500
In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second? Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file. Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together.
2008/12/27
[ "https://Stackoverflow.com/questions/394500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9161/" ]
Use [`shutil`'s `copyfileobj()`](http://docs.python.org/library/shutil.html#shutil.copyfileobj) function: ``` import shutil import subprocess proc = subprocess.Popen([...], stdin=subprocess.PIPE) my_input = get_filelike_object('from a place not given in the question') shutil.copyfileobj(my_input, proc.stdin) ``` No need to use threads.
I think there is something wrong in the design if you already have a file-like object if you want your data to end up in the subprocess. You should then arrange that they get written into the subprocess in the first place, rather than having them written into something else file-like first. Whoever is writing the data should allow the flexibility to specify the output stream, and that should be the subprocess pipe. Alternatively, if the writer insists on creating its own stream object, you should let it complete writing, and only then start the subprocess, feeding it from the result of first write. E.g. if it is a StringIO object, take its value after writing, and write it into the pipe; no need for thread synchronization here.
25,387,286
When I do `pip install statsmodels` it gives me `ImportError: statsmodels requires patsy. http://patsy.readthedocs.org`, but then I run `pip install patsy` and it says its successful, but running `pip install statsmodels` still gives me same error about requiring patsy. How can this be? --- ``` $ sudo pip install patsy Requirement already satisfied (use --upgrade to upgrade): patsy in /Library/Python/2.7/site-packages/patsy-0.3.0-py2.7.egg Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Python/2.7/site-packages/numpy-1.8.2-py2.7-macosx-10.9-intel.egg (from patsy) Cleaning up... $ sudo pip install statsmodels Downloading/unpacking statsmodels Downloading statsmodels-0.5.0.tar.gz (5.5MB): 5.5MB downloaded Running setup.py (path:/private/tmp/pip_build_root/statsmodels/setup.py) egg_info for package statsmodels Traceback (most recent call last): File "<string>", line 17, in <module> File "/private/tmp/pip_build_root/statsmodels/setup.py", line 463, in <module> check_dependency_versions(min_versions) File "/private/tmp/pip_build_root/statsmodels/setup.py", line 122, in check_dependency_versions raise ImportError("statsmodels requires patsy. http://patsy.readthedocs.org") ImportError: statsmodels requires patsy. http://patsy.readthedocs.org Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 17, in <module> File "/private/tmp/pip_build_root/statsmodels/setup.py", line 463, in <module> check_dependency_versions(min_versions) File "/private/tmp/pip_build_root/statsmodels/setup.py", line 122, in check_dependency_versions raise ImportError("statsmodels requires patsy. http://patsy.readthedocs.org") ImportError: statsmodels requires patsy. http://patsy.readthedocs.org ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /private/tmp/pip_build_root/statsmodels Storing debug log for failure in /Users/Jacob/Library/Logs/pip.log ```
2014/08/19
[ "https://Stackoverflow.com/questions/25387286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3391108/" ]
What the error message doesn't tell you is that the module `six` not being there is really the problem. Found this out by doing `import patsy` and having it fail and tell me that I needed `six`. So I did `pip install six` and now the patsy import worked, as did the `pip install statsmodels`.
For me: ``` $python3 -m pip install --upgrade patsy $python3 -m pip install statsmodels ``` worked!
25,387,286
When I do `pip install statsmodels` it gives me `ImportError: statsmodels requires patsy. http://patsy.readthedocs.org`, but then I run `pip install patsy` and it says its successful, but running `pip install statsmodels` still gives me same error about requiring patsy. How can this be? --- ``` $ sudo pip install patsy Requirement already satisfied (use --upgrade to upgrade): patsy in /Library/Python/2.7/site-packages/patsy-0.3.0-py2.7.egg Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Python/2.7/site-packages/numpy-1.8.2-py2.7-macosx-10.9-intel.egg (from patsy) Cleaning up... $ sudo pip install statsmodels Downloading/unpacking statsmodels Downloading statsmodels-0.5.0.tar.gz (5.5MB): 5.5MB downloaded Running setup.py (path:/private/tmp/pip_build_root/statsmodels/setup.py) egg_info for package statsmodels Traceback (most recent call last): File "<string>", line 17, in <module> File "/private/tmp/pip_build_root/statsmodels/setup.py", line 463, in <module> check_dependency_versions(min_versions) File "/private/tmp/pip_build_root/statsmodels/setup.py", line 122, in check_dependency_versions raise ImportError("statsmodels requires patsy. http://patsy.readthedocs.org") ImportError: statsmodels requires patsy. http://patsy.readthedocs.org Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 17, in <module> File "/private/tmp/pip_build_root/statsmodels/setup.py", line 463, in <module> check_dependency_versions(min_versions) File "/private/tmp/pip_build_root/statsmodels/setup.py", line 122, in check_dependency_versions raise ImportError("statsmodels requires patsy. http://patsy.readthedocs.org") ImportError: statsmodels requires patsy. http://patsy.readthedocs.org ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /private/tmp/pip_build_root/statsmodels Storing debug log for failure in /Users/Jacob/Library/Logs/pip.log ```
2014/08/19
[ "https://Stackoverflow.com/questions/25387286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3391108/" ]
What the error message doesn't tell you is that the module `six` not being there is really the problem. Found this out by doing `import patsy` and having it fail and tell me that I needed `six`. So I did `pip install six` and now the patsy import worked, as did the `pip install statsmodels`.
I also had an issue with this in Python 3.4. It worked using the WHL statsmodel file at this link: <https://pypi.python.org/pypi/statsmodels#downloads> After the download I installed it using: pip3.4 install my\_directory\statsmodels-0.8.0rc1-cp34-none-win\_amd64.whl, where my\_directory is where I put the WHL file.
25,387,286
When I do `pip install statsmodels` it gives me `ImportError: statsmodels requires patsy. http://patsy.readthedocs.org`, but then I run `pip install patsy` and it says its successful, but running `pip install statsmodels` still gives me same error about requiring patsy. How can this be? --- ``` $ sudo pip install patsy Requirement already satisfied (use --upgrade to upgrade): patsy in /Library/Python/2.7/site-packages/patsy-0.3.0-py2.7.egg Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Python/2.7/site-packages/numpy-1.8.2-py2.7-macosx-10.9-intel.egg (from patsy) Cleaning up... $ sudo pip install statsmodels Downloading/unpacking statsmodels Downloading statsmodels-0.5.0.tar.gz (5.5MB): 5.5MB downloaded Running setup.py (path:/private/tmp/pip_build_root/statsmodels/setup.py) egg_info for package statsmodels Traceback (most recent call last): File "<string>", line 17, in <module> File "/private/tmp/pip_build_root/statsmodels/setup.py", line 463, in <module> check_dependency_versions(min_versions) File "/private/tmp/pip_build_root/statsmodels/setup.py", line 122, in check_dependency_versions raise ImportError("statsmodels requires patsy. http://patsy.readthedocs.org") ImportError: statsmodels requires patsy. http://patsy.readthedocs.org Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 17, in <module> File "/private/tmp/pip_build_root/statsmodels/setup.py", line 463, in <module> check_dependency_versions(min_versions) File "/private/tmp/pip_build_root/statsmodels/setup.py", line 122, in check_dependency_versions raise ImportError("statsmodels requires patsy. http://patsy.readthedocs.org") ImportError: statsmodels requires patsy. http://patsy.readthedocs.org ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /private/tmp/pip_build_root/statsmodels Storing debug log for failure in /Users/Jacob/Library/Logs/pip.log ```
2014/08/19
[ "https://Stackoverflow.com/questions/25387286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3391108/" ]
What the error message doesn't tell you is that the module `six` not being there is really the problem. Found this out by doing `import patsy` and having it fail and tell me that I needed `six`. So I did `pip install six` and now the patsy import worked, as did the `pip install statsmodels`.
For anyone still experiencing issues, I highly recommend this site: [Python libraries](http://www.lfd.uci.edu/~gohlke/pythonlibs/#statsmodels). I'm using Python 3, so I, 1. Downloaded the file named: `statsmodels‑0.8.0‑cp35‑cp35m‑win_amd64.whl` 2. Opened windows command prompt 3. Went to my Downloads directory (`cd Downloads`) 4. And then used pip (`pip install statsmodels‑0.8.0‑cp35‑cp35m‑win_amd64.whl`)
25,387,286
When I do `pip install statsmodels` it gives me `ImportError: statsmodels requires patsy. http://patsy.readthedocs.org`, but then I run `pip install patsy` and it says its successful, but running `pip install statsmodels` still gives me same error about requiring patsy. How can this be? --- ``` $ sudo pip install patsy Requirement already satisfied (use --upgrade to upgrade): patsy in /Library/Python/2.7/site-packages/patsy-0.3.0-py2.7.egg Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Python/2.7/site-packages/numpy-1.8.2-py2.7-macosx-10.9-intel.egg (from patsy) Cleaning up... $ sudo pip install statsmodels Downloading/unpacking statsmodels Downloading statsmodels-0.5.0.tar.gz (5.5MB): 5.5MB downloaded Running setup.py (path:/private/tmp/pip_build_root/statsmodels/setup.py) egg_info for package statsmodels Traceback (most recent call last): File "<string>", line 17, in <module> File "/private/tmp/pip_build_root/statsmodels/setup.py", line 463, in <module> check_dependency_versions(min_versions) File "/private/tmp/pip_build_root/statsmodels/setup.py", line 122, in check_dependency_versions raise ImportError("statsmodels requires patsy. http://patsy.readthedocs.org") ImportError: statsmodels requires patsy. http://patsy.readthedocs.org Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 17, in <module> File "/private/tmp/pip_build_root/statsmodels/setup.py", line 463, in <module> check_dependency_versions(min_versions) File "/private/tmp/pip_build_root/statsmodels/setup.py", line 122, in check_dependency_versions raise ImportError("statsmodels requires patsy. http://patsy.readthedocs.org") ImportError: statsmodels requires patsy. http://patsy.readthedocs.org ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /private/tmp/pip_build_root/statsmodels Storing debug log for failure in /Users/Jacob/Library/Logs/pip.log ```
2014/08/19
[ "https://Stackoverflow.com/questions/25387286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3391108/" ]
For me: ``` $python3 -m pip install --upgrade patsy $python3 -m pip install statsmodels ``` worked!
I also had an issue with this in Python 3.4. It worked using the WHL statsmodel file at this link: <https://pypi.python.org/pypi/statsmodels#downloads> After the download I installed it using: pip3.4 install my\_directory\statsmodels-0.8.0rc1-cp34-none-win\_amd64.whl, where my\_directory is where I put the WHL file.
25,387,286
When I do `pip install statsmodels` it gives me `ImportError: statsmodels requires patsy. http://patsy.readthedocs.org`, but then I run `pip install patsy` and it says its successful, but running `pip install statsmodels` still gives me same error about requiring patsy. How can this be? --- ``` $ sudo pip install patsy Requirement already satisfied (use --upgrade to upgrade): patsy in /Library/Python/2.7/site-packages/patsy-0.3.0-py2.7.egg Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Python/2.7/site-packages/numpy-1.8.2-py2.7-macosx-10.9-intel.egg (from patsy) Cleaning up... $ sudo pip install statsmodels Downloading/unpacking statsmodels Downloading statsmodels-0.5.0.tar.gz (5.5MB): 5.5MB downloaded Running setup.py (path:/private/tmp/pip_build_root/statsmodels/setup.py) egg_info for package statsmodels Traceback (most recent call last): File "<string>", line 17, in <module> File "/private/tmp/pip_build_root/statsmodels/setup.py", line 463, in <module> check_dependency_versions(min_versions) File "/private/tmp/pip_build_root/statsmodels/setup.py", line 122, in check_dependency_versions raise ImportError("statsmodels requires patsy. http://patsy.readthedocs.org") ImportError: statsmodels requires patsy. http://patsy.readthedocs.org Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 17, in <module> File "/private/tmp/pip_build_root/statsmodels/setup.py", line 463, in <module> check_dependency_versions(min_versions) File "/private/tmp/pip_build_root/statsmodels/setup.py", line 122, in check_dependency_versions raise ImportError("statsmodels requires patsy. http://patsy.readthedocs.org") ImportError: statsmodels requires patsy. http://patsy.readthedocs.org ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /private/tmp/pip_build_root/statsmodels Storing debug log for failure in /Users/Jacob/Library/Logs/pip.log ```
2014/08/19
[ "https://Stackoverflow.com/questions/25387286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3391108/" ]
For anyone still experiencing issues, I highly recommend this site: [Python libraries](http://www.lfd.uci.edu/~gohlke/pythonlibs/#statsmodels). I'm using Python 3, so I, 1. Downloaded the file named: `statsmodels‑0.8.0‑cp35‑cp35m‑win_amd64.whl` 2. Opened windows command prompt 3. Went to my Downloads directory (`cd Downloads`) 4. And then used pip (`pip install statsmodels‑0.8.0‑cp35‑cp35m‑win_amd64.whl`)
I also had an issue with this in Python 3.4. It worked using the WHL statsmodel file at this link: <https://pypi.python.org/pypi/statsmodels#downloads> After the download I installed it using: pip3.4 install my\_directory\statsmodels-0.8.0rc1-cp34-none-win\_amd64.whl, where my\_directory is where I put the WHL file.
32,085,019
I am very new to Google App engine and was trying to understand bolb storage and api, but cant get it working. I followed the the below tutorial from goolge on using blobstore api <https://cloud.google.com/appengine/docs/python/blobstore/> Github: <https://github.com/GoogleCloudPlatform/appengine-blobstore-python/blob/master/main.py> I always get 404 not found error, the image is getting uploaded to the blob store but is not being retrieved. Any help is greatly appreciated.
2015/08/19
[ "https://Stackoverflow.com/questions/32085019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4822241/" ]
You are dealing with jQuery object, methods like removeChild() and [appendChild()](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild) belongs to dom element not to the jQuery object. To remove all contents of an element you can use [.empty()](http://api.jquery.com/empty) and to set the text content of an element you can use [.text()](http://api.jquery.com/text), but using .text() will replace existing content so in your case you can just use ```js var $resourceSpan = $("#divname" + dynamic_variable); var stringVar = functionThatReturnsString(); $resourceSpan.text(stringVar); ```
Did you wanna do somethin like this? ``` <html> <head> <title>STACK OVERFLOW TESTS</title> <style> </style> </head> <body> <span>HI, IM SOME TEXT</span> <input type = 'button' value = 'Click me!' onClick = 'changeText()'></input> <!-- Change the text with a button for example... --> <script> var text = 'I AM THE NEW TEXT'; // The text to go in the span element function changeText(){ var span = document.querySelector('span'); span.innerHTML = text; } </script> </body> </html> ```
45,031,524
I have a melted DataFrame I would like to pivot but cannot manage to do so using 2 columns as index. ``` import pandas as pd df = pd.DataFrame({'A': {0: 'XYZ', 1: 'XYZ', 2: 'XYZ', 3: 'XYZ', 4: 'XYZ', 5: 'XYZ', 6: 'XYZ', 7: 'XYZ', 8: 'XYZ', 9: 'XYZ', 10: 'ABC', 11: 'ABC', 12: 'ABC', 13: 'ABC', 14: 'ABC', 15: 'ABC', 16: 'ABC', 17: 'ABC', 18: 'ABC', 19: 'ABC'}, 'B': {0: '01/01/2017', 1: '02/01/2017', 2: '03/01/2017', 3: '04/01/2017', 4: '05/01/2017', 5: '01/01/2017', 6: '02/01/2017', 7: '03/01/2017', 8: '04/01/2017', 9: '05/01/2017', 10: '01/01/2017', 11: '02/01/2017', 12: '03/01/2017', 13: '04/01/2017', 14: '05/01/2017', 15: '01/01/2017', 16: '02/01/2017', 17: '03/01/2017', 18: '04/01/2017', 19: '05/01/2017'}, 'C': {0: 'Price', 1: 'Price', 2: 'Price', 3: 'Price', 4: 'Price', 5: 'Trading', 6: 'Trading', 7: 'Trading', 8: 'Trading', 9: 'Trading', 10: 'Price', 11: 'Price', 12: 'Price', 13: 'Price', 14: 'Price', 15: 'Trading', 16: 'Trading', 17: 'Trading', 18: 'Trading', 19: 'Trading'}, 'D': {0: '100', 1: '101', 2: '102', 3: '103', 4: '104', 5: 'Yes', 6: 'Yes', 7: 'Yes', 8: 'Yes', 9: 'Yes', 10: '50', 11: nan, 12: '48', 13: '47', 14: '46', 15: 'Yes', 16: 'No', 17: 'Yes', 18: 'Yes', 19: 'Yes'}}) ``` So: ``` A B C D XYZ 01/01/2017 Price 100 XYZ 02/01/2017 Price 101 XYZ 03/01/2017 Price 102 XYZ 04/01/2017 Price 103 XYZ 05/01/2017 Price 104 XYZ 01/01/2017 Trading Yes XYZ 02/01/2017 Trading Yes XYZ 03/01/2017 Trading Yes XYZ 04/01/2017 Trading Yes XYZ 05/01/2017 Trading Yes ABC 01/01/2017 Price 50 ABC 02/01/2017 Price ABC 03/01/2017 Price 48 ABC 04/01/2017 Price 47 ABC 05/01/2017 Price 46 ABC 01/01/2017 Trading Yes ABC 02/01/2017 Trading No ABC 03/01/2017 Trading Yes ABC 04/01/2017 Trading Yes ABC 05/01/2017 Trading Yes ``` Would become: ``` A B Trading Price ABC 01/01/2017 Yes 50 02/01/2017 No 03/01/2017 Yes 48 04/01/2017 Yes 47 05/01/2017 Yes 46 XYZ 01/01/2017 Yes 100 02/01/2017 Yes 101 03/01/2017 Yes 102 04/01/2017 Yes 103 05/01/2017 Yes 104 ``` or: ``` ABC XYZ Trading Price Trading Price 01/01/2017 Yes 50 Yes 100 02/01/2017 No Yes 101 03/01/2017 Yes 48 Yes 102 04/01/2017 Yes 47 Yes 103 05/01/2017 Yes 46 Yes 104 ``` I thought this could simply be done with pivot but get an error: ``` df.pivot(index=['A', 'B'], columns = ['C'], values = ['D'] ) Traceback (most recent call last): File "<ipython-input-41-afcc34979ff8>", line 1, in <module> df.pivot(index=['A', 'B'], columns = ['C'], values = ['D'] ) File "C:\Miniconda\lib\site-packages\pandas\core\frame.py", line 3951, in pivot return pivot(self, index=index, columns=columns, values=values) File "C:\Miniconda\lib\site-packages\pandas\core\reshape\reshape.py", line 377, in pivot index=MultiIndex.from_arrays([index, self[columns]])) File "C:\Miniconda\lib\site-packages\pandas\core\series.py", line 248, in __init__ raise_cast_failure=True) File "C:\Miniconda\lib\site-packages\pandas\core\series.py", line 3027, in _sanitize_array raise Exception('Data must be 1-dimensional') Exception: Data must be 1-dimensional ``` In R this will be quickly done with gather/spread. Thanks!
2017/07/11
[ "https://Stackoverflow.com/questions/45031524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4947923/" ]
Is that what you want? ``` In [23]: df.pivot_table(index=['A','B'], columns='C', values='D', aggfunc='first') Out[23]: C Price Trading A B ABC 01/01/2017 50 Yes 02/01/2017 NaN No 03/01/2017 48 Yes 04/01/2017 47 Yes 05/01/2017 46 Yes XYZ 01/01/2017 100 Yes 02/01/2017 101 Yes 03/01/2017 102 Yes 04/01/2017 103 Yes 05/01/2017 104 Yes ```
I found the following is possible: ``` df.set_index(['A', 'C', 'B']).unstack().T Out[59]: A ABC XYZ C Price Trading Price Trading B D 01/01/2017 50 Yes 100 Yes 02/01/2017 NaN No 101 Yes 03/01/2017 48 Yes 102 Yes 04/01/2017 47 Yes 103 Yes 05/01/2017 46 Yes 104 Yes ``` And: ``` df.set_index(['A', 'B', 'C']).unstack() Out[61]: D C Price Trading A B ABC 01/01/2017 50 Yes 02/01/2017 NaN No 03/01/2017 48 Yes 04/01/2017 47 Yes 05/01/2017 46 Yes XYZ 01/01/2017 100 Yes 02/01/2017 101 Yes 03/01/2017 102 Yes 04/01/2017 103 Yes 05/01/2017 104 Yes ```
40,712,887
I am confused with the time queryset uses its `_result_cache` or it directly hits the database. For example (in python shell): ``` user = User.objects.all() # User is one of my models print(user) # show data in database (hitting the database) print(user._result_cache) # output is None len(user) # output is a nonzero number print(user._result_cache) # this time, output is not None ``` So, my questions are: 1. Why the `_result_cache` is `None` after hitting the database? 2. Does the queryset is evaluated mean that the `_result_cache` is not `None`? 3. When does the queryset use its `_result_cache`, not hitting the database?
2016/11/21
[ "https://Stackoverflow.com/questions/40712887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6751999/" ]
A queryset will cache its data in `self._result_cache` whenever the *complete* queryset is evaluated. This includes iterating over the queryset, calling `bool()`, `len()` or `list()`, or pickling the queryset. The `print()` function indirectly calls `repr()` on the queryset. `repr()` will evaluate the queryset to include the data in the string representation, but it will not evaluate the *complete* queryset. Instead, it will [get a slice](https://github.com/django/django/blob/74742aa956d9cef0493b57f50f1cb7dc0f987fc6/django/db/models/query.py#L228) of the queryset and use that in the representation. This prevents huge queries when all you want is a simple string representation. Since only a slice is evaluated, it will not cache the results. When the cache is filled, every method that does not create a new queryset object will use the cache instead of making a new query. In your specific example, if you switch the `print()` and `len()` statement, your queryset will only hit the database once: ``` user = User.objects.all() len(user) # complete queryset is evaluated print(user._result_cache) # cache is filled print(user) # slicing an evaluated queryset will not hit the database print(user._result_cache) ```
There is an explanation for this behavior : When you use User.objects.all(),Database is not hit.When you do not iterate through the query set, the \_result\_cache is always None.But when you invoke len() function.The iteration will be done through query set, the database will be hit and resulting output will also set the result\_cahce for that query set. Here is the source code for len() function of Django : ``` def __len__(self): # Since __len__ is called quite frequently (for example, as part of # list(qs), we make some effort here to be as efficient as possible # whilst not messing up any existing iterators against the QuerySet. if self._result_cache is None: if self._iter: self._result_cache = list(self._iter) else: self._result_cache = list(self.iterator()) elif self._iter: self._result_cache.extend(self._iter) return len(self._result_cache) ``` Hope this clarifies all your questions. Thanks.
46,994,144
I am a beginner in python. I have written the following python code: ``` import subprocess PIPE = subprocess.PIPE process = subprocess.Popen(['git', 'status'], stdout=PIPE, stderr=PIPE, cwd='my\git-repo\path',shell=True) stdout_str, stderr_str = process.communicate() print (stdout_str) print (stderr_str) ``` Upon execution of the python script, I get the following output: ``` b'' b'"git" is not recognized as an internal or external command,\r\noperable program or batch file.\r\n' ``` I have added '..../git/bin' to my PATH variable, and since then git commands run fine in cmd.exe. Since 'shell=True', I thought this would run too. I can't seem to get a hold of the issue. Help appreciated.
2017/10/28
[ "https://Stackoverflow.com/questions/46994144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8849445/" ]
You have to specify the full php binary path inside the cronjob. Assuming your php binary full path is `/usr/bin/php` then your cronjob will look like this: ``` /usr/bin/php -q /home/user/tracker.domain.com/cron/3.php ```
You should use php before -q in your cron jobs like this php -q /home/user/tracker.domain.com/cron/3.php
11,860,252
In a python script i do a gobject call. I need to know, when its finished. are there any possible ways to check this? Are there Functions or so on to check? My code is: ``` gobject.idle_add(main.process) class main: def process(): <-- needs some time to finish --> next.call.if.finished() ``` I want to start start another object, pending on the first to finish. I looked through the gobject reference, but i didn't find something necessary. Thanks
2012/08/08
[ "https://Stackoverflow.com/questions/11860252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508490/" ]
``` for($i = 0; $i < count($key); $i++){ $query.=" AND (dealTitle rlike '[[:<:]]".$key[$i]."[[:>:]]' )"; } ``` Should use AND EDITED: ``` for($i = 0; $i < count($key); $i++){ $query.=" AND (dealTitle like '% ".$key[$i]." %' or dealTitle like '% ".$key[$i]."' or dealTitle like '".$key[$i]."%') "; } ```
try this: ``` AND (CONCAT(' ',dealTitle,' ') LIKE '% car %' and CONCAT(' ',dealTitle,' ') LIKE '% wash %' ) ```
11,860,252
In a python script i do a gobject call. I need to know, when its finished. are there any possible ways to check this? Are there Functions or so on to check? My code is: ``` gobject.idle_add(main.process) class main: def process(): <-- needs some time to finish --> next.call.if.finished() ``` I want to start start another object, pending on the first to finish. I looked through the gobject reference, but i didn't find something necessary. Thanks
2012/08/08
[ "https://Stackoverflow.com/questions/11860252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508490/" ]
If you are using mysql database, there is a full text search functionality which will be robust and scalable solution. ``` $query .= " AND MATCH(dealTitle) AGAINST('". $searchString ."')"; ``` <http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html#function_match> Look into this article to understand FULLTEXT SEARCH function in MySQL.
try this: ``` AND (CONCAT(' ',dealTitle,' ') LIKE '% car %' and CONCAT(' ',dealTitle,' ') LIKE '% wash %' ) ```
11,860,252
In a python script i do a gobject call. I need to know, when its finished. are there any possible ways to check this? Are there Functions or so on to check? My code is: ``` gobject.idle_add(main.process) class main: def process(): <-- needs some time to finish --> next.call.if.finished() ``` I want to start start another object, pending on the first to finish. I looked through the gobject reference, but i didn't find something necessary. Thanks
2012/08/08
[ "https://Stackoverflow.com/questions/11860252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508490/" ]
``` for($i = 0; $i < count($key); $i++){ $query.=" AND (dealTitle rlike '[[:<:]]".$key[$i]."[[:>:]]' )"; } ``` Should use AND EDITED: ``` for($i = 0; $i < count($key); $i++){ $query.=" AND (dealTitle like '% ".$key[$i]." %' or dealTitle like '% ".$key[$i]."' or dealTitle like '".$key[$i]."%') "; } ```
Try this query :- ``` AND (dealTitle LIKE '%car wash%' ) ```
11,860,252
In a python script i do a gobject call. I need to know, when its finished. are there any possible ways to check this? Are there Functions or so on to check? My code is: ``` gobject.idle_add(main.process) class main: def process(): <-- needs some time to finish --> next.call.if.finished() ``` I want to start start another object, pending on the first to finish. I looked through the gobject reference, but i didn't find something necessary. Thanks
2012/08/08
[ "https://Stackoverflow.com/questions/11860252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508490/" ]
``` for($i = 0; $i < count($key); $i++){ $query.=" AND (dealTitle rlike '[[:<:]]".$key[$i]."[[:>:]]' )"; } ``` Should use AND EDITED: ``` for($i = 0; $i < count($key); $i++){ $query.=" AND (dealTitle like '% ".$key[$i]." %' or dealTitle like '% ".$key[$i]."' or dealTitle like '".$key[$i]."%') "; } ```
You are basically trying to achieve what a search engine does -- full-text indexing. `LIKE '%keyword%'` is partial match as you already know. Not only it hits partial word, it is very slow because the db has to read and compare each one of records on the disk. Consider using full-text indexer. MySQL specifically supports it. See [FULLTEXT](http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html)
11,860,252
In a python script i do a gobject call. I need to know, when its finished. are there any possible ways to check this? Are there Functions or so on to check? My code is: ``` gobject.idle_add(main.process) class main: def process(): <-- needs some time to finish --> next.call.if.finished() ``` I want to start start another object, pending on the first to finish. I looked through the gobject reference, but i didn't find something necessary. Thanks
2012/08/08
[ "https://Stackoverflow.com/questions/11860252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508490/" ]
If you are using mysql database, there is a full text search functionality which will be robust and scalable solution. ``` $query .= " AND MATCH(dealTitle) AGAINST('". $searchString ."')"; ``` <http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html#function_match> Look into this article to understand FULLTEXT SEARCH function in MySQL.
Try this query :- ``` AND (dealTitle LIKE '%car wash%' ) ```
11,860,252
In a python script i do a gobject call. I need to know, when its finished. are there any possible ways to check this? Are there Functions or so on to check? My code is: ``` gobject.idle_add(main.process) class main: def process(): <-- needs some time to finish --> next.call.if.finished() ``` I want to start start another object, pending on the first to finish. I looked through the gobject reference, but i didn't find something necessary. Thanks
2012/08/08
[ "https://Stackoverflow.com/questions/11860252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508490/" ]
If you are using mysql database, there is a full text search functionality which will be robust and scalable solution. ``` $query .= " AND MATCH(dealTitle) AGAINST('". $searchString ."')"; ``` <http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html#function_match> Look into this article to understand FULLTEXT SEARCH function in MySQL.
You are basically trying to achieve what a search engine does -- full-text indexing. `LIKE '%keyword%'` is partial match as you already know. Not only it hits partial word, it is very slow because the db has to read and compare each one of records on the disk. Consider using full-text indexer. MySQL specifically supports it. See [FULLTEXT](http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html)