title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python's "in" set operator | 8,705,378 | 39 | 2012-01-02T21:11:09Z | 8,705,407 | 20 | 2012-01-02T21:14:44Z | [
"python"
] | I'm a little confused about the python in operator for sets.
If I have a set in python s and some instance b, is it true that "b in s" means "is there some element x in s such that b == x is true"? | That's right. You could try it in the interpreter like this:
```
>>> a_set = set(['a', 'b', 'c'])
>>> 'a' in a_set
True
>>>'d' in a_set
False
``` |
python: HTTP PUT with unencoded binary data | 8,705,962 | 9 | 2012-01-02T22:26:41Z | 8,706,029 | 8 | 2012-01-02T22:35:58Z | [
"python",
"http",
"binary",
"put"
] | I cannot for the life of me figure out how to perform an HTTP PUT request with verbatim binary data in Python 2.7 with the standard Python libraries.
I thought I could do it with urllib2, but [that fails](http://stackoverflow.com/questions/7983303/python-http-put-with-binary-data) because [`urllib2.Request`](http://do... | You're misreading the documentation: [`urllib2.Request`](http://docs.python.org/library/urllib2.html#urllib2.Request) expects the data *already encoded*, and for POST that usually means the `application/x-www-form-urlencoded` format. You are free to associate any other, *binary* data, like this:
```
import urllib2
da... |
python: HTTP PUT with unencoded binary data | 8,705,962 | 9 | 2012-01-02T22:26:41Z | 8,715,815 | 12 | 2012-01-03T17:02:35Z | [
"python",
"http",
"binary",
"put"
] | I cannot for the life of me figure out how to perform an HTTP PUT request with verbatim binary data in Python 2.7 with the standard Python libraries.
I thought I could do it with urllib2, but [that fails](http://stackoverflow.com/questions/7983303/python-http-put-with-binary-data) because [`urllib2.Request`](http://do... | I found out my problem. It seems there is some obscure behavior in [`urllib2.Request`](http://docs.python.org/library/urllib2.html#urllib2.Request) / [`urllib2.urlopen()`](http://docs.python.org/library/urllib2.html#urllib2.urlopen) (at least in Python 2.7)
The `urllib2.Request(url, data, headers)` constructor seems t... |
I Don't Understand This Use of Recursion | 8,706,191 | 5 | 2012-01-02T22:58:34Z | 8,706,266 | 11 | 2012-01-02T23:10:31Z | [
"python",
"recursion"
] | I was reading through the answers earning a "reversal" badge and I found a question regarding recursion where the OP didn't bother to do much of their homework assignment up front. Aside from some really funny answers, @machielo posted [an answer](http://stackoverflow.com/a/1694998/881224) in python that I had to run o... | I think that adding a few `print` statements it's really helpful:
```
def recursive(x):
print '[start] recursive({0})'.format(x)
if x > 10:
print recursive(x/10)
print '[return] recursive({0}) = {1}'.format(x, x%10)
return x%10
print recursive(2678)
```
The output is:
```
[start] recursive(2678)
[start]... |
How to reference to the top-level module in Python inside a package? | 8,706,309 | 9 | 2012-01-02T23:16:43Z | 8,706,331 | 8 | 2012-01-02T23:20:59Z | [
"python",
"module",
"packages"
] | In the below hierachy, is there a convenient and universal way to reference to the top\_package using a generic term in all .py file below? I would like to have a consistent way to import other modules, so that even when the "top\_package" changes name nothing breaks.
I am not in favour of using the relative import li... | This should do the job:
```
top_package = __import__(__name__.split('.')[0])
```
The trick here is that for every module the `__name__` variable contains the full path to the module separated by dots such as, for example, `top_package.level_one_a.my_lib`. Hence, if you want to get the top package name, you just need ... |
Python: extra assignments in functions | 8,706,661 | 2 | 2012-01-03T00:16:26Z | 8,706,693 | 7 | 2012-01-03T00:22:29Z | [
"memory-management",
"python",
"cpu-usage",
"assign"
] | Considering the following as two versions of a very simple function in **Python**, the question is which one is preferred over another and why?
Is there any extra **memory usage** and or **CPU usage** for `case 1` compared to `case 2` in which additional assignment has been used?
**case 1:**
```
def f(x):
y = x*... | If you want to know what Python style is preferred, look at the code in the standard library:
```
$ grep return Lib/*py
```
You will see that the `case 2` style is the most common.
I personally use the assignment form only when the variable name is needed to add clarity to the code:
```
normalized_query = query.rep... |
Celery + Django: Cannot start celerybeat on Windows 7 | 8,706,674 | 6 | 2012-01-03T00:18:59Z | 8,706,765 | 10 | 2012-01-03T00:34:47Z | [
"python",
"windows",
"django",
"celery",
"django-celery"
] | Odd issues over here. I've been developing a Django application and I am now trying to implement Celery. I need both normal tasks and periodic tasks to be queued. I can start up celeryd just fine, and execute tasks with it (I start it with the command `python manage.py celeryd start --settings=settings --loglevel=INFO`... | Search your file system for that pid file and delete it. On unix machines that usually means the program was not shut down correctly. You should check to see if its running in the task manager already, if so kill it, and delete that file
Then try again.
If there is no pid file present, that probably means there's an ... |
Using cdecimal in SQLAlchemy | 8,707,278 | 3 | 2012-01-03T02:22:28Z | 8,713,248 | 7 | 2012-01-03T13:48:29Z | [
"python",
"sqlalchemy"
] | So I'm trying to use cdecimal to store monetary values in my database. [SQLAlchemy Doc](http://www.sqlalchemy.org/docs/core/types.html#sqlalchemy.types.Numeric)
```
import sys
import cdecimal
sys.modules["decimal"] = cdecimal
```
I've connected my PostgreSQL database like so:
```
sqlalchemy.url = postgresql+psycopg2... | This one is working for me please try this
```
import sys
import cdecimal
sys.modules["decimal"] = cdecimal
from sqlalchemy import create_engine, Numeric, Integer, Column
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql://test:test@localhost/test1')
Base = declarative_base()
c... |
Python: Given a Date and Weekday find the date of the next occurrence of a given weekday | 8,708,058 | 8 | 2012-01-03T04:52:13Z | 8,708,150 | 7 | 2012-01-03T05:04:01Z | [
"python",
"datetime",
"timedelta"
] | This is a bit difficult to explain, so I apologize if this doesn't make much sense.
I have a program where I am doing some scheduling. One of the settings it has is to run a task weekly on certain days. For example, weekly on Monday, Wednesday and Friday.
Consider the example where the current task is scheduled for 1... | Use a [`timedelta`](http://docs.python.org/library/datetime.html#timedelta-objects) to add to a date. For example, using some date `d` as the scheduled date for a current task, and some day `next_day` (the next *day* you'd like to run the task).
```
from datetime import date, timedelta
...
n = (next_day - d.weekday())... |
Python: Given a Date and Weekday find the date of the next occurrence of a given weekday | 8,708,058 | 8 | 2012-01-03T04:52:13Z | 8,709,459 | 13 | 2012-01-03T08:09:05Z | [
"python",
"datetime",
"timedelta"
] | This is a bit difficult to explain, so I apologize if this doesn't make much sense.
I have a program where I am doing some scheduling. One of the settings it has is to run a task weekly on certain days. For example, weekly on Monday, Wednesday and Friday.
Consider the example where the current task is scheduled for 1... | Use [dateutil.relativedelta](http://labix.org/python-dateutil#head-ba5ffd4df8111d1b83fc194b97ebecf837add454):
```
from dateutil import relativedelta
import datetime
today = datetime.date.today()
# datetime.date(2012, 1, 3)
today + relativedelta.relativedelta(weekday=2) # 2 is Wednesday
# datetime.date(2012, 1, 4)
t... |
How to check if a function exist (but not inherited) in python? | 8,708,917 | 3 | 2012-01-03T06:57:41Z | 8,708,947 | 8 | 2012-01-03T07:01:21Z | [
"python"
] | Kind of related to this question:
[How to check if mako function exist](http://stackoverflow.com/questions/8708525/how-to-check-if-mako-function-exist)
I want to check if a function exists for a given class, but not inherited, so that the parent can called the child's function, since otherwise it would result in an i... | > I want to check if a function exists for a given class, but not inherited
Yes, you can check the class dictionary directly. Either use the *\_\_dict\_\_* attribute or the built-in *[vars()](http://docs.python.org/library/functions.html#vars)* function::
```
>>> class A(object):
def f(x):
pass
>... |
How to compare version string ("x.y.z") in MySQL? | 8,709,452 | 10 | 2012-01-03T08:08:31Z | 8,712,381 | 12 | 2012-01-03T12:34:11Z | [
"python",
"mysql",
"sql",
"django",
"natural-sort"
] | I have firmware version strings into my table (like "4.2.2" or "4.2.16")
How can I compare, select or sort them ?
I cannot use standard strings comparison : "4.2.2" is a seen by SQL greater than "4.2.16"
As version strings, I would like 4.2.16 to be greater than 4.2.2
I would like to consider that firmware version ... | If all your version numbers look like any of these:
```
X
X.X
X.X.X
X.X.X.X
```
where X is an integer from 0 to 255 (inclusive), then you could use the `INET_ATON()` function to transform the strings into integers fit for comparison.
Before you apply the function, though, you'll need to make sure the function's argu... |
Why some class variables seem to act as static while others don't? | 8,709,542 | 6 | 2012-01-03T08:18:29Z | 8,709,579 | 15 | 2012-01-03T08:23:57Z | [
"python"
] | Dictionaries and lists defined directly under the class definition act as static (e.g. [this question](http://stackoverflow.com/questions/3045246/python-and-object-class-attrs-whats-going-on))
How come other variables such as integer do not?
```
>>> class Foo():
bar=1
>>> a=Foo()
>>> b=Foo()
>>> a.bar=4
>>>... | They are all class variables. Except for when you assigned `a.bar=4` creating an instance variable. Basically Python has a lookup order on attributes. It goes:
```
instance -> class -> parent classes in MRO order (left to right)
```
So if you have
```
class Foo(object):
bar = 1
```
This is a variable on the cla... |
Overwrite {} in python | 8,709,975 | 3 | 2012-01-03T09:12:06Z | 8,710,086 | 7 | 2012-01-03T09:22:03Z | [
"python",
"dictionary",
"overwrite"
] | I want to make a dict int which you can access like that:
```
>>> my_dict["property'] = 3
>>> my_dict.property
3
```
So I've made this one:
```
class DictAsMember(dict):
def __getattr__(self, name):
return self[name]
```
This works fine, but if you have nested dicts it doesn't work, e.g:
```
my_dict = ... | One workaround to the problem is wrapping default dictionaries using `DictAsMember` before returning them in the `__getattr__` method:
```
class DictAsMember(dict):
def __getattr__(self, name):
value = self[name]
if isinstance(value, dict):
value = DictAsMember(value)
elif isins... |
Reading a binary file with python | 8,710,456 | 33 | 2012-01-03T09:57:51Z | 8,710,723 | 15 | 2012-01-03T10:18:02Z | [
"python",
"binary",
"fortran"
] | I find particularly difficult reading binary file with Python. Can you give me a hand?
I need to read this file, which in Fortran 90 is easily read by
```
int*4 n_particles, n_groups
real*4 group_id(n_particles)
read (*) n_particles, n_groups
read (*) (group_id(j),j=1,n_particles)
```
In detail, the file format is:
... | In general, I would recommend that you look into using Python's [struct](http://docs.python.org/library/struct.html) module for this. It's standard with Python, and it should be easy to translate your question's specification into a formatting string suitable for `struct.unpack()`.
Do note that if there's "invisible" ... |
Reading a binary file with python | 8,710,456 | 33 | 2012-01-03T09:57:51Z | 8,711,061 | 39 | 2012-01-03T10:46:19Z | [
"python",
"binary",
"fortran"
] | I find particularly difficult reading binary file with Python. Can you give me a hand?
I need to read this file, which in Fortran 90 is easily read by
```
int*4 n_particles, n_groups
real*4 group_id(n_particles)
read (*) n_particles, n_groups
read (*) (group_id(j),j=1,n_particles)
```
In detail, the file format is:
... | Read the binary file content like this:
```
with open(fileName, mode='rb') as file: # b is important -> binary
fileContent = file.read()
```
then "unpack" binary data using [struct.unpack](http://docs.python.org/library/struct.html#struct.unpack):
The start bytes: `struct.unpack("iiiii", fileContent[:20])`
The ... |
JSON is appearing as unicode entities in Jinja2 template | 8,710,758 | 8 | 2012-01-03T10:20:51Z | 8,710,993 | 16 | 2012-01-03T10:41:19Z | [
"python",
"django",
"json",
"jinja2"
] | I using Jinja2 with webapp2.
Jinja2 encodes all 'context' data into unicode as their doc says. This is proving problematic when I try to insert a json string into the the template:
```
jsonData = json.loads(get_the_file('catsJson.txt'))
```
I pass jsonData to template and I'm able to loop it successfully but when I ... | You must filter the value through the `safe` filter to tell jinja2 that it shouldn't apply any other filters to the output. In jinja2 syntax this would be:
```
{{ jsonData | safe }}
```
Note that since you are calling `json.loads` you actually do not have json data anymore, you have a python list object. Thus when it... |
Difference in Python class declaration | 8,711,235 | 3 | 2012-01-03T10:58:19Z | 8,711,297 | 7 | 2012-01-03T11:02:31Z | [
"python",
"python-2.6"
] | In python class declaration I can declare a class by few ways. What is a difference between following samples?
```
class MyClass:
def __init__(self)
pass
class MyClass(object):
def __init__(self)
pass
``` | The second declaration creates a [new-style class](http://docs.python.org/reference/datamodel.html#newstyle). A new-style class is derived from a built-in type, in this case an `object`. This was introduced in python 2.2 in an effort to unify classes and types. For backward compatibility *old-style* classes are still t... |
Python error: "IndexError: string index out of range" | 8,712,659 | 7 | 2012-01-03T12:58:14Z | 8,712,962 | 9 | 2012-01-03T13:25:33Z | [
"python",
"python-3.x"
] | I'm currently learning python from a book called 'Python for the absolute beginner (third edition)'. There is an exercise in the book which outlines code for a hangman game. I followed along with this code however I keep getting back an error in the middle of the program.
Here is the code that is causing the problem:
... | It looks like you indented `so_far = new` too much. Try this:
```
if guess in word:
print("\nYes!", guess, "is in the word!")
# Create a new variable (so_far) to contain the guess
new = ""
i = 0
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
... |
Python Value in List | 8,713,738 | 6 | 2012-01-03T14:26:35Z | 8,713,834 | 13 | 2012-01-03T14:33:46Z | [
"python",
"html",
"django"
] | I am using Django and I am wondering how I can accomplish this. It works fine in python in Linux but the HTML Templating language keeps saying it cannot parse the array.
```
{% if myvalue in ["128","256","512","768","1024","1536","2048","3072","5120","10240"] %}
<p> Hello World
{% endif %}
```
It says it cannot pars... | You can't create arbitrary lists in the Django templating system. You need to pass the created list via your view. See [This question](http://stackoverflow.com/questions/4395230/building-a-list-in-django-templates) for a detailed discussion. |
Is python uuid1 sequential as timestamps? | 8,713,873 | 9 | 2012-01-03T14:37:04Z | 8,714,035 | 12 | 2012-01-03T14:50:12Z | [
"python",
"uuid"
] | Python [docs](http://docs.python.org/library/uuid.html) states that uuid1 uses current time to form the uuid value. But I could not find a reference that ensures UUID1 is sequential.
```
>>> import uuid
>>> u1 = uuid.uuid1()
>>> u2 = uuid.uuid1()
>>> u1 < u2
True
>>>
``` | But not always:
```
>>> def test(n):
... old = uuid.uuid1()
... print old
... for x in range(n):
... new = uuid.uuid1()
... if old >= new:
... print "OOops"
... break
... old = new
... print new
>>> test(1000000)
fd4ae687-3619-... |
Infinite for loop in Python | 8,713,990 | 7 | 2012-01-03T14:46:53Z | 8,714,025 | 12 | 2012-01-03T14:49:05Z | [
"java",
"python",
"infinite-loop"
] | I'm new to Python. Actually I implemented something using Java as shown below.
```
for(;;){
switch(expression){
case c1: statements
case c2: statements
default: statement
}
}
```
How do I implement this in Python? | Use while loop:
```
while True:
if condition1:
statements
elif condition2:
statements
...
else:
statements
``` |
Deleting a Secure Cookie in tornado | 8,714,363 | 11 | 2012-01-03T15:15:02Z | 8,714,430 | 15 | 2012-01-03T15:20:26Z | [
"python",
"cookies",
"tornado"
] | I just started learning about webservers, tornado in particular.
I want to write a simple webpage with a login function.
As described in the [Tornado Documentation](http://www.tornadoweb.org/documentation/overview.html#id1), I'm creating a secure cookie after the user was successfully loged-in:
```
self.set_secure_co... | You could reset the cookie to an empty string via
```
self.clear_cookie("user")
```
Which would make the call to get\_current\_user return `False`. Take a look at the [blog demo](https://github.com/facebook/tornado/blob/master/demos/blog/blog.py) for an example (using OAuth, but still relevant). |
Python variables naming convention | 8,714,440 | 9 | 2012-01-03T15:21:02Z | 8,714,502 | 7 | 2012-01-03T15:25:55Z | [
"python",
"pep8"
] | So I am trying to switch to PEP8 notation (from a rather personal CamelCase notation) and I was wondering how you guys are tackling the cases where existing functions/variables would be overwritten?
e.g. having something like:
```
open, high, low, close, sum = row
```
would already overwrite the "open" and "sum" fun... | I would use `open_` and `sum_`. |
Multiple decorators for a view in Django: Execution order | 8,715,642 | 25 | 2012-01-03T16:50:56Z | 8,715,790 | 9 | 2012-01-03T17:00:08Z | [
"python",
"django",
"decorator"
] | I am trying to decorate a Django view by two decorators, one for checking login, and one for checking is\_active.
The first one is the built-in `@login_required`, and the second one is the following:
```
def active_required(function):
dec = user_passes_test(lambda u: u.is_active, '/notallowed', '')
return dec... | It only really makes sense to stack decorators if they have truly unique functionality. Based on your description, there's never going to be a scenario where you will want to use `active_required` but *not* `login_required`. Therefore, it makes more sense to have a `login_and_active_required` decorator that checks both... |
Multiple decorators for a view in Django: Execution order | 8,715,642 | 25 | 2012-01-03T16:50:56Z | 8,715,821 | 24 | 2012-01-03T17:02:54Z | [
"python",
"django",
"decorator"
] | I am trying to decorate a Django view by two decorators, one for checking login, and one for checking is\_active.
The first one is the built-in `@login_required`, and the second one is the following:
```
def active_required(function):
dec = user_passes_test(lambda u: u.is_active, '/notallowed', '')
return dec... | > Now, the decorators in Python work inside out
Well i guess that depends on your definition of inside out. in your case you want `login_required` to execute first, and so it should be the "outermost" (top) decorator
as you noted, your last example works, and is indeed the correct way to do this
**edit**
maybe the ... |
Multiple decorators for a view in Django: Execution order | 8,715,642 | 25 | 2012-01-03T16:50:56Z | 8,715,839 | 10 | 2012-01-03T17:04:09Z | [
"python",
"django",
"decorator"
] | I am trying to decorate a Django view by two decorators, one for checking login, and one for checking is\_active.
The first one is the built-in `@login_required`, and the second one is the following:
```
def active_required(function):
dec = user_passes_test(lambda u: u.is_active, '/notallowed', '')
return dec... | Decorators are applied in the order they appear in the source. Thus, your second example:
```
@login_required
@active_required
def foo(request):
...
```
is equivalent to the following:
```
def foo(request):
...
foo = login_required(active_required(foo))
```
Thus, if the code of one decorator depends on some... |
python: how to tell if file executed as import vs. main script? | 8,715,990 | 12 | 2012-01-03T17:14:10Z | 8,716,022 | 23 | 2012-01-03T17:16:19Z | [
"python",
"import"
] | I'm writing a python file `mylib.py`
I'd like mylib.py to do something based on `sys.argv` if it's being executed as a script. But if it's imported from some other script, I don't want it to do that.
How can I tell if my python file is being imported or it's a main script?
(I've seen how to do this before, but I for... | ```
if __name__ == '__main__':
# this was run as a main script
```
Here is the [documentation on `__main__`](http://docs.python.org/library/__main__.html#module-__main__).
Usually this code is placed at the bottom of a module, and one common way to keep your code clean is to create a `main()` function that does a... |
Chunking data from a large file for multiprocessing? | 8,717,179 | 12 | 2012-01-03T18:52:55Z | 8,717,312 | 12 | 2012-01-03T19:06:45Z | [
"python",
"parallel-processing"
] | I'm trying to a parallelize an application using multiprocessing which takes in
a very large csv file (64MB to 500MB), does some work line by line, and then outputs a small, fixed size
file.
Currently I do a `list(file_obj)`, which unfortunately is loaded entirely
into memory (I think) and I then I break that list up ... | `list(file_obj)` can require a lot of memory when `fileobj` is large. We can reduce that memory requirement by using [itertools](http://docs.python.org/library/itertools.html#module-itertools) to pull out chunks of lines as we need them.
In particular, we can use
```
reader = csv.reader(f)
chunks = itertools.groupby(... |
Retain all entries except for one key python | 8,717,395 | 10 | 2012-01-03T19:13:26Z | 8,717,446 | 17 | 2012-01-03T19:17:23Z | [
"python"
] | I have a python dictionary. Just to give out context, I am trying to write my own simple cross validation unit.
So basically what I want is to get all the values except for the given keys.
And depending on the input, it returns all the values from a dictionary except to those what has been given.
So if the input is 2... | ```
for key, value in your_dict.items():
if key not in your_blacklisted_set:
print value
```
the beauty is that this pseudocode example is valid python code.
it can also be expressed as a list comprehension:
```
resultset = [value for key, value in your_dict.items() if key not in your_blacklisted_set]
``... |
import module from string variable | 8,718,885 | 80 | 2012-01-03T21:29:38Z | 8,719,098 | 35 | 2012-01-03T21:49:58Z | [
"python",
"matplotlib"
] | I'm working on a documentation (personal) for nested matplotlib (MPL) library, which differs from MPL own provided, by interested submodule packages. I'm writing Python script which I hope will automate document generation from future MPL releases.
I selected interested submodules/packages and want to list their main... | I think [importlib.import\_module](http://docs.python.org/library/importlib.html#importlib.import_module) is what you are looking for. (Only available for Python >= 2.7 or 3.x):
```
importlib.import_module('matplotlib.text')
``` |
import module from string variable | 8,718,885 | 80 | 2012-01-03T21:29:38Z | 8,719,100 | 125 | 2012-01-03T21:50:20Z | [
"python",
"matplotlib"
] | I'm working on a documentation (personal) for nested matplotlib (MPL) library, which differs from MPL own provided, by interested submodule packages. I'm writing Python script which I hope will automate document generation from future MPL releases.
I selected interested submodules/packages and want to list their main... | The `__import__` function can be a bit hard to understand.
If you change
```
i = __import__('matplotlib.text')
```
to
```
i = __import__('matplotlib.text', fromlist=[''])
```
then `i` will refer to `matplotlib.text`.
In Python 2.7 and Python 3.1 or later, you can use `importlib`:
```
import importlib
i = import... |
Python UTF-8 XML parsing (SUDS): Removing 'invalid token' | 8,719,330 | 6 | 2012-01-03T22:08:25Z | 8,719,445 | 17 | 2012-01-03T22:18:32Z | [
"python",
"xml",
"soap",
"unicode",
"suds"
] | Here's a common error when dealing with UTF-8 - 'invalid tokens'
In my example, It comes from dealing with a SOAP service provider that had no respect for unicode characters, simply truncating values to 100 bytes and neglecting that the 100'th byte may be in the middle of a multi-byte character: for example:
```
<nam... | Turns out, SUDS sees xml as type 'string' (not unicode) so these are encoded values.
1) The FILTER:
```
badXML = "your bad utf-8 xml here" #(type <str>)
#Turn it into a python unicode string - ignore errors, kick out bad unicode
decoded = badXML.decode('utf-8', errors='ignore') #(type <unicode>)
#turn it back int... |
defaultdict equivalent for lists | 8,719,558 | 7 | 2012-01-03T22:29:35Z | 8,719,940 | 10 | 2012-01-03T23:08:03Z | [
"python",
"collections",
"containers",
"defaultdict"
] | Is there\How would you build an equivalent of python's very useful [`collections.defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict)?
Imagined usage of such a container:
```
>>> a = collections.defaultlist(0)
>>> a[2]=7
>>> a[4]='x'
>>> a
[0,0,7,0,'x']
```
**UPDATE:** I've added a ... | I think this would be a bit confusing to use; however, here's my first thought on how to do it:
```
class defaultlist(list):
def __init__(self, fx):
self._fx = fx
def __setitem__(self, index, value):
while len(self) <= index:
self.append(self._fx())
list.__setitem__(self, i... |
Why does a python descriptor __get__ method accept the owner class as an arg? | 8,719,585 | 13 | 2012-01-03T22:32:53Z | 8,719,786 | 8 | 2012-01-03T22:53:05Z | [
"python"
] | Why does the `__get__` method in a [python descriptor](http://docs.python.org/reference/datamodel.html#implementing-descriptors) accept the owner class as it's third argument? Can you give an example of it's use?
The first argument (`self`) is self evident, the second (`instances`) makes sense in the context of the ty... | `owner` is used when the attribute is accessed from the class instead of an instance of the class, in which case `instance` will be `None`.
In your example attempting something like `print(Container.managed_attr)` would fail because `instance` is `None` so `instance._name` would raise an `AttributeError`.
You could i... |
Python shorthand for conditionally assigning a variable | 8,719,986 | 3 | 2012-01-03T23:12:34Z | 8,720,002 | 11 | 2012-01-03T23:14:08Z | [
"python"
] | I find myself writing stuff like this too often and it seems too wordy:
```
obj = my_dict.get('obj')
if obj:
var = obj
```
Is there a better way to do this? Maybe in one line? | The `get` function takes a second argument, a default:
> get(key[, default])
> Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
<http://docs.python.org/library/stdtypes.html>
So, you could use the below to r... |
Idiomatic Clojure equivalent of this Python code? | 8,720,073 | 3 | 2012-01-03T23:22:15Z | 8,720,504 | 10 | 2012-01-04T00:12:59Z | [
"python",
"clojure"
] | I wrote a simple stack-based virtual machine in Python, and now I'm trying to rewrite it in Clojure, which is proving difficult as I don't have much experience with Lisp. [This Python snippet](http://pastebin.com/SAcnAxti) processes the bytecode, which is represented as a list of tuples like so:
```
[("label", "entry"... | Reading that Python snippet, it looks like you want the eventual output to look like
```
{:code [[:load 0]
[:load 1]
[:add]
[:store 0]]
:labels {:entry 0}}
```
It's much easier to write the code once you have a firm description of the goal, and indeed this is a pretty simple reduce. There are... |
Nesting Python context managers | 8,720,179 | 7 | 2012-01-03T23:34:41Z | 8,720,431 | 9 | 2012-01-04T00:04:21Z | [
"python",
"contextmanager"
] | In [this question](http://stackoverflow.com/questions/8718891/easy-way-of-not-overwriting-file-when-output-is-the-same/8719628#8719628), I defined a context manager that contains a context manager. What is the easiest correct way to accomplish this nesting? I ended up calling `self.temporary_file.__enter__()` in `self.... | The easy way to create context managers is with [`contextlib.contextmanager`](http://docs.python.org/library/contextlib.html#contextlib.contextmanager). Something like this:
```
@contextlib.contextmanager
def write_on_change_file(filename):
with tempfile.TemporaryFile('r+') as temporary_file:
yield tempora... |
Change case of first letter in every cell in spreadsheet | 8,720,589 | 8 | 2012-01-04T00:23:54Z | 8,720,660 | 7 | 2012-01-04T00:34:54Z | [
"python",
"perl",
"bash",
"csv",
"openoffice-calc"
] | I have many cells which I'd like to convert such that the first letter in every cell is capitalized. E.g. `cook, chef, fireman` becomes `Cook, Chef, Fireman`.
* I have the spreadsheet in OpenOffice.org, but it seems to only have options for "all uppercase" or "all lowercase".
* I can edit it in OpenOffice.org or expor... | Maybe you just need to udpate to a more recent version. I'm using LibreOffice 3.4.4 and I see `Format -> Change Case -> Sentence case` which I'd say does exactly what you need. |
Change case of first letter in every cell in spreadsheet | 8,720,589 | 8 | 2012-01-04T00:23:54Z | 8,721,681 | 8 | 2012-01-04T03:29:35Z | [
"python",
"perl",
"bash",
"csv",
"openoffice-calc"
] | I have many cells which I'd like to convert such that the first letter in every cell is capitalized. E.g. `cook, chef, fireman` becomes `Cook, Chef, Fireman`.
* I have the spreadsheet in OpenOffice.org, but it seems to only have options for "all uppercase" or "all lowercase".
* I can edit it in OpenOffice.org or expor... | I happen to do this task. You have to install [Spreadsheet::ParseExcel](http://search.cpan.org/dist/Spreadsheet-ParseExcel/lib/Spreadsheet/ParseExcel.pm#SYNOPSIS) and [Spreadsheet::WriteExcel](http://search.cpan.org/~jmcnamara/Spreadsheet-WriteExcel-2.37/lib/Spreadsheet/WriteExcel.pm) modules.
```
use strict;
use warn... |
Python bool(Ellipsis) and bool(None) | 8,720,711 | 4 | 2012-01-04T00:44:59Z | 8,720,822 | 8 | 2012-01-04T01:00:27Z | [
"python",
"python-2.7",
"boolean"
] | I don't understand how are `Ellipsis` and `None` handled differently by `bool()`, when both seem to be identical in terms of the relevant attributes for truth-testing.
```
>>> bool(Ellipsis)
True
>>> bool(None)
False
>>> any([hasattr(Ellipsis, attr) for attr in ['__len__', '__bool__', '__nonzero__']])
False
>>> any([h... | `bool(x)` is `True` if `x` is an object without one of the magic methods you mentioned returning `False`. That's why `Ellipsis` evaluates to `True`.
`None` is [special-cased](http://docs.python.org/library/stdtypes.html#truth-value-testing) in `bool()` and makes it return `False`.
**Details:**
`bool()` uses `PyObjec... |
How do I add, say, n entries of x to a list in one shot? | 8,721,654 | 5 | 2012-01-04T03:24:29Z | 8,721,670 | 9 | 2012-01-04T03:26:52Z | [
"python",
"list"
] | For instance, say list `L = [0,1,2,3]` and I want to add 10 elements of 4:
```
L=[0,1,2,3,4,4,4,4,4,4,4,4,4,4]
```
without needing to use a loop or anything | This is pretty simple thanks to the fact you can add and/or multiply lists:
```
L += [4] * 10
```
Here is the proof:
```
>>> L = [0,1,2,3]
>>> L += [4] * 10
>>> L
[0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
``` |
How do you compile Python C/C++ extensions for different OS/versions of Python? | 8,721,918 | 8 | 2012-01-04T04:11:14Z | 10,133,508 | 7 | 2012-04-12T23:59:01Z | [
"python",
"cross-platform",
"packaging",
"python-c-extension"
] | I have noticed that several mature Python libraries have precompiled versions for most architectures (Win32/Win-amd64/MacOS) and versions of Python. What is the standard way to cross-compile your extensions for different environments? Wine? Virtual machines? Crowd sourcing? | We use Virtual Machines and a [Hudson](http://hudson-ci.org/) server.
We have a Virtual Machine for each architecture we support (generally compiling doesn't stretch the resources allocated to them, so a VM is fine). I guess the configuration of each VM could be managed by something like Puppet or Chef to ensure it is... |
I want to use matplotlib to make a 3d plot given a z function | 8,722,735 | 7 | 2012-01-04T06:10:36Z | 8,723,033 | 10 | 2012-01-04T06:42:07Z | [
"python",
"matplotlib"
] | I have a z function that accepts x and y parameters and returns a z output. I want to plot this in 3d and set the scales. How can I do this easily? I've spent way too much time looking through the documentation and not once do I see a way to do this. | The plotting style kind of depends on your data (i.e. are you trying to plot a 3d curve, or a surface, or a scatter...), but this should give you an working example to start playing with.
Basically, you don't pass the function to the plot, you first create a domain of xs and ys, and then calculate the zs from that. In... |
Getting the nth element using BeautifulSoup | 8,724,352 | 12 | 2012-01-04T09:09:18Z | 8,724,481 | 20 | 2012-01-04T09:19:53Z | [
"python",
"web-scraping",
"beautifulsoup"
] | From a large table I want to read rows 5, 10, 15, 20 ... using BeautifulSoup. How do I do this? Is findNextSibling and an incrementing counter the way to go? | You could also use `findAll` to get all the rows in a list and after that just use the slice syntax to access the elements that you need:
```
rows = soup.findAll('tr')[4::5]
``` |
ImportError DLL load failed importing _tkinter | 8,724,729 | 25 | 2012-01-04T09:40:55Z | 9,883,299 | 21 | 2012-03-27T04:13:22Z | [
"python",
"windows",
"tkinter"
] | I'm using python 2.7.2 and windows 7. I searched through internet, helps and other sources but i can't find an answer to my problem.
One of my source imports `tkinter`, and this one imports `_tkinter`. At this moment it say `ImportError DLL load failed`:
```
Traceback (most recent call last): File "NERO/show_image.p... | I had a similar problem importing Tkinter on Windows 7 64-bit - seems that the 64-bit library was still in the libs folder from a previous 64-bit python install.
Uninstalling 64-bit python properly and then repairing with the 32-bit installer fixed the problem for me - you don't need to use 64-bit python. |
Bottle framework and OOP, using method instead of function | 8,725,605 | 29 | 2012-01-04T10:53:23Z | 8,726,223 | 33 | 2012-01-04T11:38:22Z | [
"python",
"oop",
"class",
"methods",
"bottle"
] | I've done some coding with Bottle. It's really simple and fits my needs. However, I got stick when I tried to wrap the application into a class :
```
import bottle
app = bottle
class App():
def __init__(self,param):
self.param = param
# Doesn't work
@app.route("/1")
def index1(self):
... | Your code does not work because you are trying to route to non-bound methods. Non-bound methods do not have a reference to `self`, how could they, if instance of `App` has not been created?
If you want to route to class methods, you first have to initialize your class and then `bottle.route()` to methods on that objec... |
Bottle framework and OOP, using method instead of function | 8,725,605 | 29 | 2012-01-04T10:53:23Z | 16,059,246 | 17 | 2013-04-17T11:51:11Z | [
"python",
"oop",
"class",
"methods",
"bottle"
] | I've done some coding with Bottle. It's really simple and fits my needs. However, I got stick when I tried to wrap the application into a class :
```
import bottle
app = bottle
class App():
def __init__(self,param):
self.param = param
# Doesn't work
@app.route("/1")
def index1(self):
... | Below works nicely for me :)
Quite object orientated and easy to follow.
```
from bottle import Bottle, template
class Server:
def __init__(self, host, port):
self._host = host
self._port = port
self._app = Bottle()
self._route()
def _route(self):
self._app.route('/', ... |
Bottle framework and OOP, using method instead of function | 8,725,605 | 29 | 2012-01-04T10:53:23Z | 27,555,078 | 14 | 2014-12-18T20:25:18Z | [
"python",
"oop",
"class",
"methods",
"bottle"
] | I've done some coding with Bottle. It's really simple and fits my needs. However, I got stick when I tried to wrap the application into a class :
```
import bottle
app = bottle
class App():
def __init__(self,param):
self.param = param
# Doesn't work
@app.route("/1")
def index1(self):
... | You have to extend the `Bottle` class. It's instances are WSGI web applications.
```
from bottle import Bottle
class MyApp(Bottle):
def __init__(self, name):
super(MyApp, self).__init__()
self.name = name
self.route('/', callback=self.index)
def index(self):
return "Hello, my ... |
Multiple assignment and evaluation order in Python | 8,725,673 | 9 | 2012-01-04T10:57:38Z | 8,725,769 | 19 | 2012-01-04T11:04:55Z | [
"python",
"assignment-operator"
] | What is the difference between the following Python expressions:
```
# First:
x,y = y,x+y
# Second:
x = y
y = x+y
```
*First* gives different results than *Second*.
e.g.,
*First:*
```
>>> x = 1
>>> y = 2
>>> x,y = y,x+y
>>> x
2
>>> y
3
```
*Second:*
```
>>> x = 1
>>> y = 2
>>> x = y
>>> y = x+y
>>> x
2
>>> y
... | In an assignment statement, the right-hand side is always evaluated fully *before* doing the actual setting of variables. So,
```
x, y = y, x + y
```
evaluates `y` (let's call the result `ham`), evaluates `x + y` (call that `spam`), *then* sets `x` to `ham` and `y` to `spam`. I.e., it's like
```
ham = y
spam = x + y... |
MongoDB: how to get db.stats() from API | 8,726,152 | 5 | 2012-01-04T11:33:47Z | 8,727,314 | 10 | 2012-01-04T13:01:57Z | [
"python",
"mongodb",
"pymongo"
] | I'm trying to get results of db.stats() mongo shell command in my python code (for monitoring purposes).
But unlike for example serverStatus I can't do `db.command('stats')`. I was not able to find any API equivalent in mongodb docs. I've also tried variations with `db.$cmd` but none of that worked.
So,
Small questi... | The Javascript shell's `stats` command helper actually invokes a command named `dbstats`, which you can run from PyMongo using the [`Database.command` method](http://api.mongodb.org/python/current/api/pymongo/database.html#pymongo.database.Database.command). The easiest way to find out what command a shell helper will ... |
What are the Python equivalents to Ruby's bundler / Perl's carton? | 8,726,207 | 67 | 2012-01-04T11:37:33Z | 8,736,419 | 58 | 2012-01-05T01:17:37Z | [
"python",
"ruby",
"perl",
"virtualenv",
"pip"
] | I know about virtualenv and pip. But these are a bit different from bundler/carton.
For instance:
* pip writes the absolute path to shebang or activate script
* pip doesn't have the `exec` sub command (`bundle exec bar`)
* virtualenv copies the Python interpreter to a local directory
Does every Python developer use ... | From what i've read about bundler â pip without virtualenv should work just fine for you. You can think of it as something between regular gem command and bundler. Common things that you can do with pip:
1. **Installing packages (gem install)**
```
pip install mypackage
```
2. **Dependencies and bulk-insta... |
How to call the original method when it is monkey-patched? | 8,726,238 | 6 | 2012-01-04T11:39:25Z | 8,726,680 | 10 | 2012-01-04T12:12:00Z | [
"python",
"oop",
"python-3.x",
"monkeypatching",
"function-overriding"
] | I have a class in the main project I don't want to change.
```
class A():
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def name(self):
# this method could be much more complex
return self.lastname.upper()
```
I'm trying to build ... | This is what we call a 'decorator' pattern. Replace the original reassignment of name to have it call a function instead, which takes the original. It then returns a new function.
```
def name_decorator(method):
def decorate_name(self=None):
return stuff + method(self)
return decorate_name
A.name = nam... |
How to use less css with django? | 8,726,610 | 38 | 2012-01-04T12:06:41Z | 8,726,853 | 39 | 2012-01-04T12:26:49Z | [
"python",
"django",
"less"
] | I'm using twitter bootstrap and django. I've got my dependencies handled with a pip requirements file.
I've got 2 questions:
1. How can I use less while I'm developing so it'll get compiled when I edit one of my less files?
2. How can I create some kind of build script that will compress and combine my JS and generat... | 1. **Install [django-static-precompiler](https://github.com/andreyfedoseev/django-static-precompiler)**:
1. Run `pip install django-static-precompiler`
2. Add `static_precompiler` to INSTALLED\_APPS
2. **Install [lessc](http://lesscss.org/#-client-side-usage) executable**, either via your package manager or run ... |
How to use less css with django? | 8,726,610 | 38 | 2012-01-04T12:06:41Z | 22,410,652 | 11 | 2014-03-14T16:25:36Z | [
"python",
"django",
"less"
] | I'm using twitter bootstrap and django. I've got my dependencies handled with a pip requirements file.
I've got 2 questions:
1. How can I use less while I'm developing so it'll get compiled when I edit one of my less files?
2. How can I create some kind of build script that will compress and combine my JS and generat... | The selected answer is now out of date: `django-less` is no longer being maintained (as specified on [its pypi page](https://pypi.python.org/pypi/django-less)), and the developer suggests using [django-static-precompiler](https://github.com/andreyfedoseev/django-static-precompiler) instead. |
Python - how can I change default path when installing modules? | 8,726,822 | 4 | 2012-01-04T12:24:02Z | 8,727,062 | 7 | 2012-01-04T12:42:33Z | [
"python",
"windows",
"module",
"install"
] | I'm trying to install a Python Module by running a Windows installer (an EXE file).
The Problem is that the default python folder and the defualt Installation Library are set To disc D:\ and are grayed out (meaning I can't change it). It might be fine is some places, but in my computer, D is the DVD drive, meaning that... | It's not "default folder", and there's a reason there's "found in registry" next to the version. You need to re-register the Python installation if you've moved it, either by installing it again (without removing) in the same folder, or changing the directory saved in registry (`HKCU\Software\Python\PythonCore\X.X\Inst... |
Sending packets from pcap with changed src/dst in scapy | 8,726,881 | 13 | 2012-01-04T12:29:03Z | 8,843,436 | 20 | 2012-01-12T22:41:00Z | [
"python",
"pcap",
"scapy"
] | I am trying to send a previously recorded traffic (captured in pcap format) with scapy. Currently I am stuck at striping original Ether layer. The traffic was captured on another host and I basically need to change both IP and Ether layer src and dst. I managed to replace IP layer and recalculate checksums, but Ether l... | check this example
```
from scapy.all import *
from scapy.utils import rdpcap
pkts=rdpcap("FileName.pcap") # could be used like this rdpcap("filename",500) fetches first 500 pkts
for pkt in pkts:
pkt[Ether].src= new_src_mac # i.e new_src_mac="00:11:22:33:44:55"
pkt[Ether].dst= new_dst_mac
pkt[IP].src... |
Python: check if method is static | 8,727,059 | 5 | 2012-01-04T12:42:23Z | 8,727,121 | 11 | 2012-01-04T12:47:09Z | [
"python",
"static-methods"
] | assume following class definition:
```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
a = A()
```
So f is a normal method and g is a static method.
Now, how can I check if the funcion objects a.f and a.g are static or not? Is there a "isstatic" funcion in Python?
... | Lets experiment a bit:
```
>>> import types
>>> class A:
... def f(self):
... return 'this is f'
... @staticmethod
... def g():
... return 'this is g'
...
>>> a = A()
>>> a.f
<bound method A.f of <__main__.A instance at 0x800f21320>>
>>> a.g
<function g at 0x800eb28c0>
>>> isinstance(a.g, types.FunctionT... |
Python: check if method is static | 8,727,059 | 5 | 2012-01-04T12:42:23Z | 8,727,333 | 9 | 2012-01-04T13:03:10Z | [
"python",
"static-methods"
] | assume following class definition:
```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
a = A()
```
So f is a normal method and g is a static method.
Now, how can I check if the funcion objects a.f and a.g are static or not? Is there a "isstatic" funcion in Python?
... | Your approach seems a bit flawed to me, but you can check class attributes:
```
>>> type(A.f)
<type 'instancemethod'>
>>> type(A.g)
<type 'function'>
``` |
Converting dict object to string in Django/Jinja2 template | 8,727,349 | 5 | 2012-01-04T13:04:12Z | 8,727,790 | 12 | 2012-01-04T13:36:49Z | [
"python",
"django",
"jinja2"
] | If you use Django or Jinja2, you've probably ran into this problem before.
I have a JSON string that looks like this:
```
{
"data":{
"name":"parent",
"children":[
{
"name":"child_a",
"fav_colors":[
"blue",
"red"
]
},
{
"name":"child_b",
... | You need to convert the `fav_colors` list back to JSON. Probably the easiest way to do this would be with a quick template filter:
```
@register.filter
def to_json(value):
return mark_safe(simplejson.dumps(value))
```
So now you could do
```
<option value="{{ c.fav_colors|to_json }}">
``` |
LDAP in Django default admin | 8,727,486 | 4 | 2012-01-04T13:13:18Z | 8,728,045 | 7 | 2012-01-04T13:54:36Z | [
"python",
"django",
"ldap",
"django-auth-ldap"
] | **UPDATED**
How it is possible to Django default admin authenticate on a LDAP server instead of the default database? I have found the package [Django Auth LDAP](http://packages.python.org/django-auth-ldap/ "Django Auth LDAP") but nothing about configuring it to be used by admin login. I've tried putting the lines bel... | Admin login should work the same way as normal login. Simply adding backend is not enough, you need to configure it. The docs say a lot actually:
You probably need to set this:
```
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"is_active": "cn=active,ou=groups,dc=example,dc=com",
"is_staff": "cn=staff,ou=groups,dc=exampl... |
How do I create a BMP file with pure python? | 8,729,459 | 8 | 2012-01-04T15:35:36Z | 8,729,778 | 8 | 2012-01-04T15:56:03Z | [
"python",
"bmp"
] | I need to create a black and white bmp file with pure python.
I read an [article on wikipedia](http://en.wikipedia.org/wiki/BMP_file_format) about bmp file format, but I am not good at low level programming and want to fill this gap.
So the question is how do I create a black and white bmp file having a matrix of pixe... | [construct](http://construct.readthedocs.org/en/latest/) is a pure-Python library for parsing and building binary structures, protocols and file formats. It has BMP format support out-of-the-box.
This could be a better approach than hand-crafting it with `struct`. Besides, you will have a chance to learn a really usef... |
Retrieving JSON objects from a text file (using Python) | 8,730,119 | 16 | 2012-01-04T16:19:39Z | 8,730,674 | 19 | 2012-01-04T16:55:42Z | [
"python",
"json",
"object"
] | I have thousands of text files containing multiple JSON objects, but unfortunately there is no delimiter between the objects. Objects are stored as dictionaries and some of their fields are themselves objects. Each object might have a variable number of nested objects. Concretely, an object might look like this:
```
{... | This decodes your "list" of JSON Objects from a string:
```
from json import JSONDecoder
def loads_invalid_obj_list(s):
decoder = JSONDecoder()
s_len = len(s)
objs = []
end = 0
while end != s_len:
obj, end = decoder.raw_decode(s, idx=end)
objs.append(obj)
return objs
```
The... |
Background processing in Django without Celery | 8,730,911 | 7 | 2012-01-04T17:10:03Z | 8,731,563 | 7 | 2012-01-04T17:55:06Z | [
"python",
"ajax",
"django",
"asynchronous",
"django-celery"
] | I have a very small part of a Django site that keeps the state of a moderated chat session between two users. Basically, the first user speaks for 3 minutes (and no one else can), then the second user speaks, then a 30 second pause, and the process is repeated one more time. I'm currently using the database and a "Room... | I know only one alternative to *Celery* that is more lightweight: [Queue in django-utils](http://charlesleifer.com/blog/a-lightweight-task-queue-for-django/).
Another way is to use the [subprocess](http://docs.python.org/library/subprocess.html) module directly but you'll probably have to solve some problems that are ... |
Background processing in Django without Celery | 8,730,911 | 7 | 2012-01-04T17:10:03Z | 11,476,353 | 11 | 2012-07-13T18:37:27Z | [
"python",
"ajax",
"django",
"asynchronous",
"django-celery"
] | I have a very small part of a Django site that keeps the state of a moderated chat session between two users. Basically, the first user speaks for 3 minutes (and no one else can), then the second user speaks, then a 30 second pause, and the process is repeated one more time. I'm currently using the database and a "Room... | Author of django-utils here, I'd suggest trying out my newer project [Huey](https://github.com/coleifer/huey) -- has richer feature set, better docs, more stable and works with any python framework (including django). [Docs](https://github.com/coleifer/huey). |
Convert python long/int to fixed size byte array | 8,730,927 | 19 | 2012-01-04T17:11:09Z | 8,731,276 | 7 | 2012-01-04T17:33:04Z | [
"python",
"bytearray",
"long-integer",
"diffie-hellman",
"rc4-cipher"
] | I'm trying to implement RC4 and DH key exchange in python. Problem is that I have no idea about how to convert the python long/int from the key exchange to the byte array I need for the RC4 implementation. Is there a simple way to convert a long to the required length byte array?
**Update**: forgot to mention that the... | *long/int to the byte array* looks like exact purpose of `struct.pack`. For long integers that exceed 4(8) bytes, you can come up with something like the next:
```
>>> limit = 256*256*256*256 - 1
>>> i = 1234567890987654321
>>> parts = []
>>> while i:
parts.append(i & limit)
i >>= 32
>>> struct.pack('... |
Convert python long/int to fixed size byte array | 8,730,927 | 19 | 2012-01-04T17:11:09Z | 14,527,004 | 10 | 2013-01-25T17:18:19Z | [
"python",
"bytearray",
"long-integer",
"diffie-hellman",
"rc4-cipher"
] | I'm trying to implement RC4 and DH key exchange in python. Problem is that I have no idea about how to convert the python long/int from the key exchange to the byte array I need for the RC4 implementation. Is there a simple way to convert a long to the required length byte array?
**Update**: forgot to mention that the... | I haven't done any benchmarks, but this recipe "works for me".
The short version: use `'%x' % val`, then `unhexlify` the result. The devil is in the details, though, as `unhexlify` requires an even number of hex digits, which `%x` doesn't guarantee. See the docstring, and the liberal inline comments for details.
```
... |
Convert python long/int to fixed size byte array | 8,730,927 | 19 | 2012-01-04T17:11:09Z | 17,949,832 | 8 | 2013-07-30T14:28:16Z | [
"python",
"bytearray",
"long-integer",
"diffie-hellman",
"rc4-cipher"
] | I'm trying to implement RC4 and DH key exchange in python. Problem is that I have no idea about how to convert the python long/int from the key exchange to the byte array I need for the RC4 implementation. Is there a simple way to convert a long to the required length byte array?
**Update**: forgot to mention that the... | One-liner:
```
bytearray.fromhex('{:0192x}'.format(big_int))
```
The 192 is 768 / 4, because OP wanted 768-bit numbers and there are 4 bits in a hex digit. If you need a bigger `bytearray` use a format string with a higher number. Example:
```
>>> big_int = 91108591109280260979517407496333390908748226110292140611393... |
Convert python long/int to fixed size byte array | 8,730,927 | 19 | 2012-01-04T17:11:09Z | 28,057,222 | 15 | 2015-01-20T23:39:21Z | [
"python",
"bytearray",
"long-integer",
"diffie-hellman",
"rc4-cipher"
] | I'm trying to implement RC4 and DH key exchange in python. Problem is that I have no idea about how to convert the python long/int from the key exchange to the byte array I need for the RC4 implementation. Is there a simple way to convert a long to the required length byte array?
**Update**: forgot to mention that the... | With Python 3.2 and later, you can use `int.to_bytes` and `int.from_bytes`: <https://docs.python.org/3/library/stdtypes.html#int.to_bytes> |
Python If then Else style when getting values from Dicts | 8,730,946 | 4 | 2012-01-04T17:12:09Z | 8,730,994 | 7 | 2012-01-04T17:14:43Z | [
"python",
"syntax",
"if-statement"
] | I often struggle with the following if/else syntax and I was hoping some people could give me some of their opinions as to what they think is more clear or if this violates any Pythonisms (I've searched and wasn't able to find anything).
Is one of these better and or right/wrong?
```
value = None
if 'value' in some_d... | Of course the last one is the best - described situation is exact case for `dict.get`.
Just a note - second parameter to `get` is superfluous, you can simply write:
```
some_func(value=some_dict.get('value'))
``` |
Tuple value by key | 8,731,231 | 14 | 2012-01-04T17:30:54Z | 8,731,252 | 24 | 2012-01-04T17:32:18Z | [
"python",
"tuples"
] | Is it possible to get Value out of tuple:
```
TUPLE = (
('P', 'Shtg1'),
('R', u'Shtg2'),
('D', 'Shtg3'),
)
```
by calling STR key like `P`
Python says that only int can be used for this type of 'query'
I can't use loop (too much overhead...)
Thank you! | The canonical data structure for this type of queries is a dictionary:
```
In [1]: t = (
...: ('P', 'Shtg1'),
...: ('R', u'Shtg2'),
...: ('D', 'Shtg3'),
...: )
In [2]: d = dict(t)
In [3]: d['P']
Out[3]: 'Shtg1'
```
If you use a tuple, there is no way to avoid looping (either explicit or impl... |
Python regular expression to replace unencoded ampersands in text | 8,731,454 | 2 | 2012-01-04T17:46:21Z | 8,731,820 | 7 | 2012-01-04T18:16:20Z | [
"python",
"regex"
] | I'm working with an upstream system that sometimes sends me text destined for HTML/XML output with ampersands that are unencoded:
```
str1 = "Stay at this B&B"
str2 = "He’s going to Texas A&M"
str3 = "He’s going to a B&B and then Texas A&M"
```
I need to replace the unencoded ampersands with `&` w... | If the ampersand is part of a character entity, it can be any named entity (not just `&`), a decimal entity, OR a hexadecimal entity. This should cover it:
```
re.sub(r'&(?![A-Za-z]+[0-9]*;|#[0-9]+;|#x[0-9a-fA-F]+;)',
r'&', your_string)
``` |
Filtering out certain bytes in python | 8,733,233 | 13 | 2012-01-04T20:03:41Z | 8,735,509 | 19 | 2012-01-04T23:18:11Z | [
"python",
"xml",
"text",
"unicode",
"lxml"
] | I'm getting this error in my python program: `ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters`
This question, [random text from /dev/random raising an error in lxml: All strings must be XML compatible: Unicode or ASCII, no NULL bytes](http://stackoverflow.com/quest... | As the answer to the linked question said, the XML standard defines a valid character as:
```
Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
```
Translating that into Python:
```
def valid_xml_char_ordinal(c):
codepoint = ord(c)
# conditions ordered by presumed frequency
... |
How can I make the xtick labels of a plot be simple drawings using matplotlib? | 8,733,558 | 10 | 2012-01-04T20:29:20Z | 8,745,727 | 19 | 2012-01-05T16:10:54Z | [
"python",
"drawing",
"plot",
"matplotlib",
"labels"
] | Instead of words or numbers being the tick labels of the x axis, I want to draw a simple drawing (made of lines and circles) as the label for each x tick. Is this possible? If so, what is the best way to go about it in matplotlib? | I would remove the tick labels and replace the text with [patches](http://matplotlib.sourceforge.net/users/artists.html#customizing-your-objects). Here is a brief example of performing this task:
```
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# define where to put symbols vertically
TICKYPO... |
PHP approach to python's magic __getattr__() | 8,734,458 | 4 | 2012-01-04T21:40:42Z | 8,734,485 | 8 | 2012-01-04T21:43:29Z | [
"php",
"python",
"getattr"
] | I was wondering if there was some way in PHP to duplicate some of the magic of Python attribute/key access.
I use a Mongo ORM class written by [Steve Lacey](https://github.com/slacy) called [Minimongo](https://github.com/slacy/minimongo) in which he utilizes the `__getattr__` and `__getitem__` to reroute key and attri... | Have a look at [\_\_get() and \_\_set()](http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members) and [ArrayAccess](http://php.net/manual/en/class.arrayaccess.php).
With the former you can make non-public members accessbile, as in `$obj->foo`, with the latter you can access them li... |
Python/Django "BadStatusLine" error | 8,734,617 | 13 | 2012-01-04T21:55:18Z | 8,734,760 | 7 | 2012-01-04T22:05:52Z | [
"python",
"django"
] | I'm getting a weird error that I can't seem to find a solution for.
This error does not occur every time I hit this segment of code, and neither does it happen for the same iteration through the loop (it happens in a loop). If I run it enough, it doesn't seem to encounter the error and the program executes successfull... | This doesn't have anything to do with Django, it's an exception thrown by urllib2 which couldn't parse the response after fetching your url. It may be a network issue, a malformed response⦠Some servers / applications throw this kind of error randomly. If you don't control what this URL returns you're left with catch... |
Python/Django "BadStatusLine" error | 8,734,617 | 13 | 2012-01-04T21:55:18Z | 8,734,798 | 28 | 2012-01-04T22:09:07Z | [
"python",
"django"
] | I'm getting a weird error that I can't seem to find a solution for.
This error does not occur every time I hit this segment of code, and neither does it happen for the same iteration through the loop (it happens in a loop). If I run it enough, it doesn't seem to encounter the error and the program executes successfull... | The [`BadStatusLine`](http://docs.python.org/library/httplib.html#httplib.BadStatusLine) exception is raised when you call `urllib2.urlopen(url)` and the remote server responds with a status code that python cannot understand.
Assuming that you don't control `url`, you can't prevent this from happening. All you can do... |
set db per model in django | 8,734,673 | 12 | 2012-01-04T22:00:08Z | 29,067,389 | 9 | 2015-03-15T23:15:26Z | [
"python",
"django"
] | I've been looking over django's multi-db docs. I'd like to break a few of my models out into a different db. But I really just want those models to ALWAYS live in a particular db. I don't need special routing. And writing unique routers just to say "Models A, B, and C live in database X, models D, E, and F always live ... | You can easily do this by appearing custom attribute to model:
```
class A(models.Model):
_DATABASE = "X"
class B(models.Model):
_DATABASE = "Y"
...
```
Then you need to add router. Next one will select database by \_DATABASE field, and models without \_DATABASE attribute will use `default` database, also re... |
urllib2 with cookies | 8,734,876 | 5 | 2012-01-04T22:16:40Z | 8,734,991 | 12 | 2012-01-04T22:25:08Z | [
"python",
"cookies",
"urllib2"
] | I am trying to make a request to an RSS feed that requires a cookie, using python. I thought using urllib2 and adding the appropriate heading would be sufficient, but the request keeps saying unautherized.
Im guessing it could be a problem on the remote sites' side, but wasnt sure. How do I use urllib2 along with cook... | I would use [requests](http://pypi.python.org/pypi/requests) package, [docs](http://docs.python-requests.org/en/latest/index.html), it's a lot easier to use than urlib2 (sane API).
If a response contains some Cookies, you can get quick access to them:
```
url = 'http://httpbin.org/cookies/set/requests-is/awesome'
r =... |
How to change folder names in python? | 8,735,312 | 9 | 2012-01-04T22:56:44Z | 8,735,370 | 18 | 2012-01-04T23:02:42Z | [
"python",
"rename"
] | I have multiple folders each with the name of a person, with the first name(s) first and the surname last. I want to change the folder names so that the surname is first followed by a comma and then the first name(s) follow.
As an example, in the folder **Test**, i have:
```
C:/Test/John Smith
C:/Test/Fred Jones
C:/T... | You can write it out fairly straight-forward, using [`os.listdir`](http://docs.python.org/library/os.html#os.listdir) and the [os.path](http://docs.python.org/library/os.path.html) functions:
```
import os
basedir = 'C:/Test'
for fn in os.listdir(basedir):
if not os.path.isdir(os.path.join(basedir, fn)):
continu... |
url structure and form posts with Flask | 8,735,603 | 5 | 2012-01-04T23:29:46Z | 8,737,753 | 9 | 2012-01-05T04:42:02Z | [
"python",
"routing",
"flask",
"werkzeug"
] | In Flask you write the route above the method declaration like so:
```
@app.route('/search/<location>/')
def search():
return render_template('search.html')
```
However in HTML as form will post to the url in this fashion
```
www.myapp.com/search?location=paris
```
the latter seems to return a 404 from the applic... | The query parameters are not included as part of the route matching, nor are they injected into function arguments. Only the matched URL portions are injected. What you're looking for is `request.args` (GET query parameters), `request.form` (POST) or `request.values` (combined).
You could do something like this if you... |
Python Basics: How can i set two function parameters in equations? | 8,735,605 | 2 | 2012-01-04T23:29:58Z | 8,735,651 | 8 | 2012-01-04T23:35:25Z | [
"python",
"function"
] | I have a basic question on python functions and parameters
Given this function:
```
def findArticleWithAttr(tableattrib, user_url_input):
articles = Something.objects.filter(tableattrib=user_url_input)
```
I call the function with:
```
findArticleWithAttr(attribute1, userinput1)
```
tableattrib is not set by f... | You could use the `**` [double-splat operator](http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/):
```
def findArticleWithAttr(tableattrib, user_url_input):
articles = Something.objects.filter(**{tableattrib : user_url_input})
```
---
Basically, the `**` operator makes
```
func(**{'fo... |
How to delete a record using GQL? | 8,737,069 | 7 | 2012-01-05T03:01:24Z | 8,737,374 | 8 | 2012-01-05T03:44:28Z | [
"python",
"gql"
] | I need to iterate and delete all records of my datastore. I am using Google App engine Launcher to test it on local host. How to do it?
When I am trying to delete all recors in Person model that way:
```
qObj = Person.all()
db.delete(qObj)
```
I am getting error `BadValueError: Property y must be a str or unicode ... | The GQL language can only be used to retrieve entities or key (cf. <http://code.google.com/appengine/docs/python/datastore/gqlreference.html>)
You'll have to do this:
```
persons = Person.all()
for p in persons:
p.delete()
```
Regarding the error `BadValueError: Property y must be a str or unicode instance, not... |
Why is it not possible to have an IF statement in a TRY block in Python, and if somehow possible, is it good practice? | 8,737,200 | 2 | 2012-01-05T03:21:10Z | 8,737,226 | 8 | 2012-01-05T03:24:49Z | [
"python",
"exception-handling"
] | I am getting an indentation error, but my code is indented properly. If I take out the if statement, the code will run fine. Here is the relevant snippet:
```
80 try:
81 votes_a = breakdown[0]['count']
82
83 if breakdown[0]['pick'] != m.home:
84 votes_b = votes_a
85 except Inde... | Of course it's possible. If you get indentation errors, but indentation looks good visually, there's a good chance you've mixed tabs with spaces. It's best to not use tabs at all. You can run Python with `-tt` to detect inconsistent tab usage. |
Can someone help me understand this error: | 8,737,369 | 2 | 2012-01-05T03:43:49Z | 8,737,384 | 8 | 2012-01-05T03:45:58Z | [
"python",
"twisted"
] | I never know how to read these. It would be helpful if someone could help me understand this one, and maybe give advice on how to read these in general?
```
D:\>python captain2.py
Traceback (most recent call last):
File "captain2.py", line 2, in <module>
from twisted.internet import reactor
File "c:\Python27\l... | In a stack traceback, Python lists the current call stack, in the order the calls happened. So, first your code in `captain2.py`:
```
from twisted.internet import reactor
```
Then the `reactor` module did:
```
from twisted.internet import default
```
and so on, until `selectreactor.py` did:
```
from zope.interface... |
Order of syntax for using 'not' and 'in' keywords | 8,738,388 | 57 | 2012-01-05T06:11:45Z | 8,738,524 | 10 | 2012-01-05T06:28:01Z | [
"python",
"syntax"
] | When testing for membership, we can use:
```
x not in y
```
Or alternatively:
```
not y in x
```
There can be many possible contexts for this expression depending on `x` and `y`. It could be for a substring check, list membership, dict key existence, for example.
* Are the two forms always equivalent?
* Is there a... | 1. No, there is no difference.
> The operator `not in` is defined to have the inverse true value of `in`.
>
> â[Python documentation](http://docs.python.org/reference/expressions.html#notin)- I would assume `not in` is preferred because it is more obvious and they added a special case for it. |
Order of syntax for using 'not' and 'in' keywords | 8,738,388 | 57 | 2012-01-05T06:11:45Z | 8,738,649 | 70 | 2012-01-05T06:45:29Z | [
"python",
"syntax"
] | When testing for membership, we can use:
```
x not in y
```
Or alternatively:
```
not y in x
```
There can be many possible contexts for this expression depending on `x` and `y`. It could be for a substring check, list membership, dict key existence, for example.
* Are the two forms always equivalent?
* Is there a... | They always give the same result.
In fact, `not 'ham' in 'spam and eggs'` appears to be special cased to perform a single "not in" operation, rather than an "in" operation and then negating the result:
```
>>> import dis
>>> def notin():
'ham' not in 'spam and eggs'
>>> dis.dis(notin)
2 0 LOAD_CONST ... |
How to solve a pair of nonlinear equations using Python? | 8,739,227 | 31 | 2012-01-05T07:49:48Z | 8,739,526 | 32 | 2012-01-05T08:22:14Z | [
"python",
"numpy",
"scipy",
"sympy"
] | What's the (best) way to solve a **pair of non linear equations using Python.** (Numpy, Scipy or Sympy)
eg:
> * x+y^2 = 4
> * e^x+ xy = 3
A code snippet which solves the above pair will be great | for numerical solution, you can use fsolve:
<http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html#scipy.optimize.fsolve>
```
from scipy.optimize import fsolve
import math
def equations(p):
x, y = p
return (x+y**2-4, math.exp(x) + x*y - 3)
x, y = fsolve(equations, (1, 1))
print eq... |
How to solve a pair of nonlinear equations using Python? | 8,739,227 | 31 | 2012-01-05T07:49:48Z | 8,954,984 | 15 | 2012-01-21T17:21:04Z | [
"python",
"numpy",
"scipy",
"sympy"
] | What's the (best) way to solve a **pair of non linear equations using Python.** (Numpy, Scipy or Sympy)
eg:
> * x+y^2 = 4
> * e^x+ xy = 3
A code snippet which solves the above pair will be great | If you prefer sympy you can use nsolve.
```
>>> nsolve([x+y**2-4, exp(x)+x*y-3], [x, y], [1, 1])
[0.620344523485226]
[1.83838393066159]
```
The first argument is a list of equations, the second is list of variables and the third is an initial guess. |
python string module vs str methods | 8,739,417 | 4 | 2012-01-05T08:10:10Z | 8,739,469 | 10 | 2012-01-05T08:15:11Z | [
"python"
] | ```
>>> import string
>>> s = 'happy cat'
>>> string.find(s, 'cat')
6
```
and
```
>>> s = 'happy cat'
>>> s.find('cat')
6
```
In the above 2 pieces of code, i have the following doubts.
1. Why is the 2nd code working without import the string module?
2. Is there any performance improvement in using one over the oth... | The functions defined in `string` module that are nowadays methods of `str` were deprecated in [**Python 2.4**](https://docs.python.org/2.4/lib/node111.html) and should not be used at all, though they were retained in later Python 2 versions for backward-compatibility. They were removed in Python 3.0.
> 1. Why is the ... |
Python:How can i get all the elements in a list before the longest element? | 8,740,018 | 2 | 2012-01-05T09:13:24Z | 8,740,093 | 9 | 2012-01-05T09:19:22Z | [
"python",
"list"
] | I have a list, e.g.
```
l = ['abc34','def987','ghij','klmno','pqrstuvwxyz1234567','98765','43','210abc']
```
How can I get all the elements in the list before the occurrance of the longest element and not the ones that come after? | This is one way:
```
l = ['abc34','def987','ghij','klmno','pqrstuvwxyz1234567','98765','43','210abc']
new_list = l[:l.index(max(l, key=len))]
``` |
How to convert a string data to a JSON object in python? | 8,740,353 | 4 | 2012-01-05T09:43:55Z | 8,740,426 | 9 | 2012-01-05T09:49:31Z | [
"python",
"json",
"web-services",
"http-post",
"web.py"
] | Here is the sample string i am receiving from one of the web services,
```
body=%7B%22type%22%3A%22change%22%2C%22url%22%3A%22http%3A%2F%2Fapi.pachube.com%2Fv2%2Ftriggers%2F4100%22%2C%22environment%22%3A%7B%22feed%22%3A%22http%3A%2F%2Fapi.pachube.com%2Fv2%2Ffeeds%2F36133%22%2C%22title%22%3A%22Current+Cost+Bridge%22%2C... | First you need to unquote the body
```
import urllib
body="%7B%22type%22%3A%22change%22%2C%22url%22%3A%22http%3A%2F%2Fapi.pachube.com%2Fv2%2Ftriggers%2F4100%22%2C%22environment%22%3A%7B%22feed%22%3A%22http%3A%2F%2Fapi.pachube.com%2Fv2%2Ffeeds%2F36133%22%2C%22title%22%3A%22Current+Cost+Bridge%22%2C%22description%22%3An... |
"Manually" invoke expose event on gtk.DrawingArea | 8,743,367 | 2 | 2012-01-05T13:32:07Z | 8,752,344 | 8 | 2012-01-06T01:31:51Z | [
"python",
"pygtk",
"visualization",
"gtk",
"pycairo"
] | I'm creating a small tool for data visualization.
The GUI is created with Pygtk and very simple. After the user has entered a filename he can press the button "calc" to see the output. The output is rendered by pycairo and presented in a gtk.DrawingArea.
The application works as following:
When the button is pressed t... | In order to have your widget refreshed, you need to tell GTK+ that it needs to be redrawn, typically using `gtk.Widget.queue_draw()` (called as `self.queue_draw()`), which invalidates your entire widget and schedules a redraw (by emitting expose events) that will take place after your program returns to the main loop.
... |
python list by value not by reference | 8,744,113 | 46 | 2012-01-05T14:28:51Z | 8,744,133 | 87 | 2012-01-05T14:30:08Z | [
"python",
"list",
"reference"
] | Let's take an example
```
a=['help', 'copyright', 'credits', 'license']
b=a
b.append('XYZ')
b
['help', 'copyright', 'credits', 'license', 'XYZ']
a
['help', 'copyright', 'credits', 'license', 'XYZ']
```
I wanted to append value in list 'b' but the value of list 'a' have also changed.
I think I have little idea why ... | As answered in the [official Python FAQ](http://docs.python.org/faq/programming.html#how-do-i-copy-an-object-in-python):
```
b = a[:]
``` |
python list by value not by reference | 8,744,113 | 46 | 2012-01-05T14:28:51Z | 8,744,171 | 9 | 2012-01-05T14:32:16Z | [
"python",
"list",
"reference"
] | Let's take an example
```
a=['help', 'copyright', 'credits', 'license']
b=a
b.append('XYZ')
b
['help', 'copyright', 'credits', 'license', 'XYZ']
a
['help', 'copyright', 'credits', 'license', 'XYZ']
```
I wanted to append value in list 'b' but the value of list 'a' have also changed.
I think I have little idea why ... | Also, you can do:
```
b = list(a)
```
This will work for any sequence, even those that don't support indexers and slices... |
python list by value not by reference | 8,744,113 | 46 | 2012-01-05T14:28:51Z | 8,744,968 | 74 | 2012-01-05T15:24:16Z | [
"python",
"list",
"reference"
] | Let's take an example
```
a=['help', 'copyright', 'credits', 'license']
b=a
b.append('XYZ')
b
['help', 'copyright', 'credits', 'license', 'XYZ']
a
['help', 'copyright', 'credits', 'license', 'XYZ']
```
I wanted to append value in list 'b' but the value of list 'a' have also changed.
I think I have little idea why ... | To copy a list you can use `list(a)` or `a[:]`. In both cases a new object is created.
These two methods, however, have limitations with collections of mutable objects as inner objects keep their references intact:
```
>>> a = [[1,2],[3],[4]]
>>> b = a[:]
>>> c = list(a)
>>> c[0].append(9)
>>> a
[[1, 2, 9], [3], ... |
In python, make a tempfile in the same directory as another file? | 8,745,387 | 7 | 2012-01-05T15:52:26Z | 8,745,610 | 14 | 2012-01-05T16:04:39Z | [
"python",
"file",
"temporary-files"
] | I need to update a file. I read it in and write it out with changes. However, I'd prefer to write to a temporary file and rename it into place.
```
temp = tempfile.NamedTemporaryFile()
tempname = temp.name
temp.write(new_data)
temp.close()
os.rename(tempname, data_file_name)
```
The problem is that `tempfile.NamedTem... | You can use:
* `prefix` to make the temporary file begin with the same name as the
original file.
* `dir` to specify where to place the temporary file.
* `os.path.split` to split the directory from the filename.
---
```
import tempfile
import os
dirname, basename = os.path.split(filename)
temp = tempfile.NamedTemp... |
How to implement a signal/slot defined in Qt Designer | 8,745,902 | 7 | 2012-01-05T16:23:00Z | 8,749,070 | 11 | 2012-01-05T20:10:42Z | [
"python",
"pyqt",
"pyside",
"signals-slots",
"qt-designer"
] | I am trying to connect the click() signal of a button to my own function. The button is in a widget that I created with QT Designer. I load the .ui file with QUiLoader like so:
```
class MyWidget(QtGui.QMainWindow):
def __init__(self, *args):
QtGui.QMainWindow.__init__(self, *args)
loader = QtUi... | Use [Signals and Slots Editing Mode](http://developer.qt.nokia.com/doc/qt-4.8/designer-connection-mode.html) for connecting predefined Qt signals directly to predefined Qt slots.
So for "Close" button on a simple dialog, you can just drag a connection from the button to the dialog, select the `clicked()` signal and th... |
Rewrite this list-comprehension in R | 8,745,972 | 4 | 2012-01-05T16:27:14Z | 8,746,558 | 14 | 2012-01-05T17:05:27Z | [
"python",
"list-comprehension"
] | ```
>>> [(x*y) for (x,y) in zip(range(3), (1,11,111))]
[0, 11, 222]
```
Not like this
```
> data.frame(0:2,c(1,11,111))
X0.2 c.1..11..111.
1 0 1
2 1 11
3 2 111
> data.frame(0:2,c(1,11,111))->a
> a[1]*a[2]
X0.2
1 0
2 11
3 222
```
but something like this
```
lapply(... | For the general pattern, perhaps
```
Map(`*`, 0:2, c(1, 11, 111))
```
or
```
unlist(Map(`*`, 0:2, c(1, 11, 111)))
```
or more explicitly
```
Map(function(x, y) x*y, 0:2, c(1, 11, 111))
```
(I like `Map` better than Steve's `mapply` because it does not simplify by default, is shorter to type, and plays well with t... |
Pyramid: how to set cookie without renderer? | 8,746,087 | 8 | 2012-01-05T16:35:14Z | 8,746,156 | 9 | 2012-01-05T16:39:41Z | [
"python",
"pyramid"
] | In configuration file:
```
config.add_route('lang', '/lang-{code}')
```
In views:
```
@view_config(route_name='lang')
def lang(request):
code = request.matchdict['code']
response = Response()
response.set_cookie('lang', value=code, max_age=31536000) # max_age = year
return HTTPFound(location=request... | HTTPFound takes a headers parameter. Try something like `return HTTPFound(location='foo', headers=response.headers)` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.