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
Is there a way to store python objects directly in mongoDB without serializing them
18,089,598
8
2013-08-06T20:14:57Z
18,090,560
16
2013-08-06T21:11:01Z
[ "python", "mongodb", "pymongo", "bson" ]
I have read somewhere that you can store python objects (more specifically dictionaries) as binaries in MongoDB by using BSON. However right now I cannot find any any documentation related to this. Would anyone know how exactly this can be done?
There isn't a way to store an object in a file (database) without serializing it. If the data needs to move from one process to another process or to another server, it will need to be serialized in some form to be transmitted. Since you're asking about MongoDB, the data will absolutely be serialized in some form in or...
How to estimate how much memory a Pandas' DataFrame will need?
18,089,667
30
2013-08-06T20:18:55Z
18,090,009
7
2013-08-06T20:38:29Z
[ "python", "pandas" ]
I have been wondering... If I am reading, say, a 400MB csv file into a pandas dataframe (using read\_csv or read\_table), is there any way to guesstimate how much memory this will need? Just trying to get a better feel of data frames and memory...
If you know the `dtype`s of your array then you can directly compute the number of bytes that it will take to store your data + some for the Python objects themselves. A useful attribute of `numpy` arrays is `nbytes`. You can get the number of bytes from the arrays in a pandas `DataFrame` by doing ``` nbytes = sum(blo...
How to estimate how much memory a Pandas' DataFrame will need?
18,089,667
30
2013-08-06T20:18:55Z
18,090,393
17
2013-08-06T21:00:08Z
[ "python", "pandas" ]
I have been wondering... If I am reading, say, a 400MB csv file into a pandas dataframe (using read\_csv or read\_table), is there any way to guesstimate how much memory this will need? Just trying to get a better feel of data frames and memory...
You have to do this in reverse. ``` In [4]: DataFrame(randn(1000000,20)).to_csv('test.csv') In [5]: !ls -ltr test.csv -rw-rw-r-- 1 users 399508276 Aug 6 16:55 test.csv ``` Technically memory is about this (which includes the indexes) ``` In [16]: df.values.nbytes + df.index.nbytes + df.columns.nbytes Out[16]: 1680...
How to estimate how much memory a Pandas' DataFrame will need?
18,089,667
30
2013-08-06T20:18:55Z
32,970,117
10
2015-10-06T12:34:11Z
[ "python", "pandas" ]
I have been wondering... If I am reading, say, a 400MB csv file into a pandas dataframe (using read\_csv or read\_table), is there any way to guesstimate how much memory this will need? Just trying to get a better feel of data frames and memory...
`df.memory_usage()` will return how much each column occupies: ``` >>> df.memory_usage() Row_ID 20906600 Household_ID 20906600 Vehicle 20906600 Calendar_Year 20906600 Model_Year 20906600 ... ``` To include indexes, pass `index=True`. So to get overall memory consumption: ``` >>...
Documenting `tuple` return type in a function docstring for PyCharm type hinting
18,090,037
16
2013-08-06T20:40:01Z
18,138,687
19
2013-08-09T01:06:38Z
[ "python", "pycharm", "docstring" ]
How can I document that a function returns a `tuple` in such a way that PyCharm will be able to use it for type hinting? Contrived example: ``` def fetch_abbrev_customer_info(customer_id): """Pulls abbreviated customer data from the database for the Customer with the specified PK value. :type custome...
I contacted PyCharm support, and this is what they said: > For tuple please use `(<type_1>, <type_2>, <type_3>, e t.c.)` syntax. > > E.g.: > > ``` > """ > :rtype: (string, int, int) > """ > ``` This is confirmed in [PyCharm's documentation](http://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html): > ##...
Forking python, defunct child
18,090,230
3
2013-08-06T20:50:09Z
18,090,294
7
2013-08-06T20:54:08Z
[ "python", "fork", "zombie-process" ]
I have some troubles with Python child processes so I wrote a very simple script: ``` import os import sys import time pid = os.fork() if pid: #parent time.sleep(30) else: #child #os._exit(0) sys.exit() ``` While parent process is sleeping I launch ``` ps fax | grep py[t]hon ``` And I read this...
To clear the child process in Unix you need to wait on the child, check one of the os.wait(), os.waitpid(), os.wait3() or os.wait4() at <http://docs.python.org/2/library/os.html#os.wait> As to why this is so, this is a design decision of Unix. The child process keeps its return value in its process state, if it was to...
python ConfigParser read file doesn't exist
18,090,666
7
2013-08-06T21:17:14Z
18,091,313
7
2013-08-06T22:02:24Z
[ "python", "exception", "exception-handling", "configparser" ]
``` import ConfigParser config = ConfigParser.ConfigParser() config.read('test.ini') ``` This is how we read a configuration file in Python. But what if the 'test.ini' doesn't exist? Why doesn't this method throw exception? How can I make it throw exception if the file doesn't exist?
From the [docs](http://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.read): > If none of the named files exist, the `ConfigParser` instance will > contain an empty dataset. If you want to raise an error in case any of the files is not found then you can try: ``` files = ['test1.ini', 'test...
python ConfigParser read file doesn't exist
18,090,666
7
2013-08-06T21:17:14Z
24,832,139
7
2014-07-18T19:10:39Z
[ "python", "exception", "exception-handling", "configparser" ]
``` import ConfigParser config = ConfigParser.ConfigParser() config.read('test.ini') ``` This is how we read a configuration file in Python. But what if the 'test.ini' doesn't exist? Why doesn't this method throw exception? How can I make it throw exception if the file doesn't exist?
You could also explicitly open it as a file. ``` try: with open('test.ini') as f: config.readfp(f) except IOError: raise MyError() ``` EDIT: added a missing '
Numpy: Difference between dot(a,b) and (a*b).sum()
18,092,984
14
2013-08-07T01:02:11Z
18,093,220
8
2013-08-07T01:33:20Z
[ "python", "numpy", "scipy", "precision", "floating-accuracy" ]
For 1-D numpy arrays, this two expressions should yield the same result (theorically): ``` (a*b).sum()/a.sum() dot(a, b)/a.sum() ``` The latter uses `dot()` and is faster. But which one is more accurate? Why? Some context follows. I wanted to compute the weighted variance of a sample using numpy. I found the `dot()...
Numpy dot is one of the routines that calls the BLAS library that you link on compile (or builds its own). The importance of this is the BLAS library can make use of Multiply–accumulate operations (usually Fused-Multiply Add) which limit the number of roundings that the computation performs. Take the following: ```...
Converting a list
18,093,008
4
2013-08-07T01:05:44Z
18,093,019
14
2013-08-07T01:07:08Z
[ "python" ]
I have a list similar to the one shown below. Do you have any ideas on how I can convert it to the one in the **EXPECTED OUTPUT** section below? ``` list =['username1,username2', 'username3','username4,username5'] ``` **EXPECTED OUTPUT:-** ``` list = ['username1','username2', 'username3','username4','username5'] ```...
``` >>> alist = ['username1,username2', 'username3','username4,username5'] >>> ','.join(alist).split(',') ['username1', 'username2', 'username3', 'username4', 'username5'] ``` By the way, don't use `list` as the variable name.
How to plus one at the tail to a float number in Python?
18,093,283
13
2013-08-07T01:40:53Z
18,093,369
20
2013-08-07T01:53:14Z
[ "python" ]
Is there a simple and direct way to add 'one' at float number in Python? I mean this: ``` if a == 0.0143: a = plus(a) assert a == 0.0144 def plus(a): sa = str(a) index = sa.find('.') if index<0: return a+1 else: sb = '0'*len(sa) sb[index] = '.' sb[-1] = 1 ...
As you've noticed, not all decimal numbers can be represented exactly as floats: ``` >>> Decimal(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') >>> Decimal(0.2) Decimal('0.200000000000000011102230246251565404236316680908203125') >>> Decimal(0.3) Decimal('0.29999999999999998889776975374843459...
What is meant by OpenERP fields.reference?
18,094,681
3
2013-08-07T04:27:46Z
18,100,259
9
2013-08-07T09:54:35Z
[ "python", "xml", "openerp" ]
I saw this code segment in **subscription.py** class. It gives selection and many2one fields together for users. I found in openerp documentation and another modules also but i never found any details or other samples for this here is the its view ![fields.reference](http://i.stack.imgur.com/eqKMB.png) here is the c...
In the OpenERP framework a `fields.reference` field is a pseudo-`many2one` relationship that can target multiple models. That is, it contains the name of the target model in addition to the foreign key, so that each value can belong to a different table. The user interface first presents a drop-down where the user sele...
Pandas Dataframes to_html: Highlighting table rows
18,096,748
14
2013-08-07T07:04:24Z
18,101,965
13
2013-08-07T11:16:18Z
[ "python", "html", "pandas" ]
I'm creating tables using the pandas to\_html function, and I'd like to be able to highlight the bottom row of the outputted table, which is of variable length. I don't have any real experience of html to speak of, and all I found online was this ``` <table border="1"> <tr style="background-color:#FF0000"> <th>M...
You can do it in javascript using jQuery: ``` $('table tbody tr').filter(':last').css('background-color', '#FF0000') ``` Also newer versions of pandas add a class `dataframe` to the table html so you can filter out just the pandas tables using: ``` $('table.dataframe tbody tr').filter(':last').css('background-colo...
Unit test for only root user in python
18,098,110
8
2013-08-07T08:14:00Z
18,098,201
7
2013-08-07T08:19:08Z
[ "python" ]
Does unit test library for python (especially 3.x, I don't really care about 2.x) has decorator to be accessed only by root user? I have this testing function. ``` def test_blabla_as_root(): self.assertEqual(blabla(), 1) ``` blabla function can only be executed by root. I want root user only decorator so normal ...
If you're using unittest, you can skip tests or entire test cases using `unittest.skipIf` and `unittest.skipUnless`. Here, you could do: ``` import os @unittest.skipUnless(os.getuid() == 0) # Root has an uid of 0 def test_bla_as_root(self): ... ``` Which could be simplified in a (less readable): ``` @unittest...
Can I pass an exception as an argument to a function in python?
18,101,887
2
2013-08-07T11:12:26Z
18,102,000
8
2013-08-07T11:18:13Z
[ "python", "decorator" ]
I am new to python. I am trying to create a retry decorator that, when applied to a function, will keep retrying until some criteria is met (for simplicity, say retry 10 times). ``` def retry(): def wrapper(func): for i in range(0,10): try: func() break ...
You can supply a `tuple` of exceptions to the `except ..` block to catch: ``` from functools import wraps def retry(*exceptions, **params): if not exceptions: exceptions = (Exception,) tries = params.get('tries', 10) def decorator(func): @wraps(func) def wrapper(*args, **kw): ...
modulo of a number - python vs c#
18,106,156
2
2013-08-07T14:30:34Z
18,106,253
10
2013-08-07T14:35:01Z
[ "c#", "python" ]
Lets take the basic arithmetic operation - **modulo** I get different outputs depending on different languages. **Python** ``` >>> -1 % 12 11 ``` **C#** ``` var res = -1 % 12; output: res = -1 ``` Why am I seeing such behaviour? Ideally I'd like the output to be **11** in both cases. Also does anyone know if I c...
The premise of the question is incorrect. The `%` operator in C# is not the modulus operator, it is the *remainder* operator, while in Python it *is* a modulus operator. As [Eric Lippert Describes](http://blogs.msdn.com/b/ericlippert/archive/2011/12/05/what-s-the-difference-remainder-vs-modulus.aspx), modulus and rema...
Display pydoc's description as part of argparse '--help'
18,106,327
6
2013-08-07T14:38:38Z
18,107,559
8
2013-08-07T15:31:54Z
[ "python", "argparse", "pydoc" ]
I am using **argparse.ArgumentParser()** in my script, i would like to display the pydoc description of my script as part of the '--help' option of the argparse. One possibly solution can be to use the *`formatter_class`* or the *`description`* attribute of ArgumentParser to configure the displaying of help. But in th...
You can retrieve the docstring of your script from the `__doc__` global. To add it to your script's help, you can set the `description` argument of the parser. ``` """My python script Script to process a file """ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.Ra...
Compare `float` and `float64` in python
18,106,975
4
2013-08-07T15:05:32Z
18,107,037
11
2013-08-07T15:07:49Z
[ "python", "numpy" ]
I have to compare two numbers. One of them comes from regulat python code and comes other from numpy. Debugger shows they have same value '29.0', but type of first is `float` and type of second is `float64`, so `a == b` and `a - b == 0` is `False`. How can I deal with it? Is there any way to force a regular python vari...
You should not compare floats with equality, in any programming language, because you can never know that they are exactly equal. Instead, you should test whether their difference is smaller than a tolerance: ``` if abs(a - b) < 1e-10 ``` So this problem doesn't have to do with the difference between `float` and `flo...
What is this dictionary assignment doing?
18,107,104
2
2013-08-07T15:10:37Z
18,107,212
7
2013-08-07T15:15:58Z
[ "python", "mapreduce", "nltk", "sentiment-analysis" ]
I am learning Python and am trying to use it to perform sentiment analysis. I am following an online tutorial from this link: <http://www.alex-hanna.com/tworkshops/lesson-6-basic-sentiment-analysis/>. I have taken a piece of code as a mapper class, an excerpt of which looks like this: ``` sentimentDict = { 'positi...
The loop creates a nested dictionary, and sets all values to 1, presumably to then just use the keys as a way to weed out duplicate values. You could use sets instead and avoid the `= 1` value: ``` sentimentDict = {} def loadSentiment(): with open('Sentiment/positive_words.txt', 'r') as f: sentimentDict[...
How to create a large pandas dataframe from an sql query without running out of memory?
18,107,953
10
2013-08-07T15:50:01Z
18,108,357
7
2013-08-07T16:10:16Z
[ "python", "sql", "pandas", "bigdata" ]
I am having trouble querying a table of > 5 million records from my MS SQL Server database. I want to be able to select all of the records, but my code seems to fail when selecting to much data into memory. This works: ``` import pandas.io.sql as psql sql = "SELECT TOP 1000000 * FROM MyTable" data = psql.read_frame(...
You could simply try to read the input table chunk-wise and assemble your full dataframe from the individual pieces afterwards, like this: ``` import pandas as pd import pandas.io.sql as psql chunk_size = 10000 offset = 0 dfs = [] while True: sql = "SELECT * FROM MyTable limit %d offset %d order by ID" % (chunk_size...
How to create a large pandas dataframe from an sql query without running out of memory?
18,107,953
10
2013-08-07T15:50:01Z
29,522,443
8
2015-04-08T18:22:48Z
[ "python", "sql", "pandas", "bigdata" ]
I am having trouble querying a table of > 5 million records from my MS SQL Server database. I want to be able to select all of the records, but my code seems to fail when selecting to much data into memory. This works: ``` import pandas.io.sql as psql sql = "SELECT TOP 1000000 * FROM MyTable" data = psql.read_frame(...
As mentioned in a comment, starting from pandas 0.15, you have a chunksize option in `read_sql` to read and process the query chunk by chunk: ``` sql = "SELECT * FROM data_chunks" for chunk in pd.read_sql_query(sql , engine, chunksize=5): print(chunk) ``` Reference: <http://pandas.pydata.org/pandas-docs/version/0...
What's the Python equivalent of C++'s "a = f++;", if any?
18,108,296
2
2013-08-07T16:07:08Z
18,108,316
13
2013-08-07T16:08:18Z
[ "python", "syntax" ]
In C++, two things can happen in the same line: something is incremented, and an equality is set; i.e.: ``` int main() { int a = 3; int f = 2; a = f++; // a = 2, f = 3 return 0; } ``` Can this be done in Python?
Sure, by using multiple assignment targets: ``` a, f = f, f + 1 ``` or by just plain incrementing `f` on a separate line: ``` a = f f += 1 ``` because readable trumps overly clever. There is no `++` operator because integers in Python are immutable; you rebind the name to a new integer value instead.
Python nested for loop behaviour
18,108,363
4
2013-08-07T16:10:34Z
18,108,378
7
2013-08-07T16:11:46Z
[ "python", "for-loop", "nested-loops" ]
I came across this weird behaviour with nested for loops and I can't for the light of me explain this. Is this a python-specific thing or am I just overseeing something? This is the code I'm running: ``` for i in range(16): if i == 0: for j in range(8): print 'i is (if) ' + str(i) ...
The `for` loop assigns a *new* value to `i` every loop iteration, namely the next value taken from the loop iterable (in this case `range(16)`. You can modify `i` in the loop itself, but that doesn't alter the iterable `for` is working with. If you wanted to change the loop iterable, then you'd have to do so *directl...
many-to-many in list display django
18,108,521
32
2013-08-07T16:18:22Z
18,108,586
65
2013-08-07T16:22:01Z
[ "python", "django", "django-admin", "admin" ]
``` class PurchaseOrder(models.Model): product = models.ManyToManyField('Product') vendor = models.ForeignKey('VendorProfile') dollar_amount = models.FloatField(verbose_name='Price') class Product(models.Model): products = models.CharField(max_length=256) def __unicode__(self): return self.p...
You may not be able to do it directly. [From the documentation of `list_display`](https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display) > ManyToManyField fields aren’t supported, because that would entail > executing a separate SQL statement for each row in the table....
Getting first row from sqlalchemy
18,110,033
23
2013-08-07T17:36:09Z
18,110,236
39
2013-08-07T17:47:44Z
[ "python", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I have the following query: ``` profiles = session.query(profile.name).filter(and_(profile.email == email, profile.password == password_hash)) ``` How do I check if there is a row and how do I just return the first (should only be one if there is a match)?
Use [`query.one()`](http://docs.sqlalchemy.org/en/rel_0_8/orm/query.html#sqlalchemy.orm.query.Query.one) to get one, and *exactly* one result. In all other cases it will raise an exception you can handle: ``` from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import MultipleResultsFound try: use...
Getting first row from sqlalchemy
18,110,033
23
2013-08-07T17:36:09Z
18,110,291
17
2013-08-07T17:51:41Z
[ "python", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I have the following query: ``` profiles = session.query(profile.name).filter(and_(profile.email == email, profile.password == password_hash)) ``` How do I check if there is a row and how do I just return the first (should only be one if there is a match)?
You can use the [`first()`](http://docs.sqlalchemy.org/en/rel_0_8/orm/query.html#sqlalchemy.orm.query.Query.first) function on the Query object. This will return the first result, or None if there are no results. ``` result = session.query(profile.name).filter(...).first() if not result: print 'No result found' `...
How to check for redundant combinations in a python dictionary
18,113,372
3
2013-08-07T20:39:38Z
18,113,473
7
2013-08-07T20:45:03Z
[ "python", "dictionary" ]
I have the following python dictionary with tuples for keys and values: ``` {(A, 1): (B, 2), (C, 3): (D, 4), (B, 2): (A, 1), (D, 4): (C, 3), } ``` how do I get a unique set of combinations between keys and values? Such that `(A,1):(B,2)` appears, not `(B,2):(A,1)`?
``` d = {('A', 1): ('B', 2), ('C', 3): ('D', 4), ('B', 2): ('A', 1), ('D', 4): ('C', 3), } >>> dict(set(frozenset(item) for item in d.items())) {('A', 1): ('B', 2), ('D', 4): ('C', 3)} ``` This works by converting each key/value pair in the dictionary to a set. This is important because for any pai...
python xlrd convert xlsx to csv
18,113,547
5
2013-08-07T20:49:25Z
18,113,843
9
2013-08-07T21:07:16Z
[ "python", "xlrd" ]
I am trying to convert excel files to csv files using `xlrd` library. But I got this error: `UnicodeEncodeError: 'ascii' codec can't encode character u'\u0142' in position 2: ordinal not in range(128)` Can it be because the excel file is too large? Cause everything works fine with excel files that have small number ...
You are reading a Excel sheet with data outside of the ASCII range. When writing unicode values to a CSV file, automatic encoding takes place, but for values outside the ASCII range of characters that fails. Encode explicitly: ``` for rownum in xrange(sheet.nrows): wr.writerow([unicode(val).encode('utf8') for v...
Python's csv.writerow() is acting a tad funky
18,113,975
6
2013-08-07T21:17:20Z
18,115,123
11
2013-08-07T22:50:37Z
[ "python", "csv" ]
From what I've researched, csv.writeRow should take in a list, and then write it to the given csv file. Here's what I tried: ``` from csv import writer with open('Test.csv', 'wb') as file: csvFile, count = writer(file), 0 titles = ["Hello", "World", "My", "Name", "Is", "Simon"] csvFile.writerow...
It's a [documented issue](http://support.microsoft.com/kb/323626) that Excel will assume a csv file is SYLK if the first two characters are 'ID'. Venturing into the realm of opinion - it shouldn't, but Excel thinks it knows better than the extension. To be fair, people expect it to be able to figure out cases where th...
Computing Eulers Totient Function
18,114,138
2
2013-08-07T21:27:33Z
18,114,286
11
2013-08-07T21:37:19Z
[ "python" ]
I am trying to find an efficient way to compute [Euler's totient function](https://en.wikipedia.org/wiki/Euler%27s_totient_function). What is wrong with this code? It doesn't seem to be working. ``` def isPrime(a): return not ( a < 2 or any(a % i == 0 for i in range(2, int(a ** 0.5) + 1))) def phi(n): y = 1 ...
Here's a much faster, working way, based on this description on Wikipedia: > Thus if n is a positive integer, then φ(n) is the number of integers k in the range 1 ≤ k ≤ n for which gcd(n, k) = 1. I'm not saying this is the fastest or cleanest, but it works. ``` import fractions def phi(n): amount = 0 ...
Python: what are the differences between the threading and multiprocessing modules?
18,114,285
53
2013-08-07T21:37:06Z
18,114,475
16
2013-08-07T21:53:41Z
[ "python", "multithreading", "parallel-processing", "multiprocessing" ]
I am learning how to use the `threading` and the `multiprocessing` modules in Python to run certain operations in parallel and speed-up my code. I am finding hard (maybe because I don't have any theoretical background about it) to understand what is the difference between a `threading.Thread()` object and a `multiproc...
Multiple threads can exist in a single process. The threads that belong to the same process share the same memory area (can read from and write to the very same variables, and can interfere with one another). On the contrary, different processes live in different memory areas, and each of them has its own variables. In...
Python: what are the differences between the threading and multiprocessing modules?
18,114,285
53
2013-08-07T21:37:06Z
18,114,882
102
2013-08-07T22:28:12Z
[ "python", "multithreading", "parallel-processing", "multiprocessing" ]
I am learning how to use the `threading` and the `multiprocessing` modules in Python to run certain operations in parallel and speed-up my code. I am finding hard (maybe because I don't have any theoretical background about it) to understand what is the difference between a `threading.Thread()` object and a `multiproc...
[What Giulio Franco says](http://stackoverflow.com/a/18114475) is true for multithreading vs. multiprocessing *in general*. However, Python\* has an added issue: There's a Global Interpreter Lock that prevents two threads in the same process from running Python code at the same time. This means that if you have 8 core...
Python: Catch Ctrl-C command. Prompt "really want to quit (y/n)", resume execution if no
18,114,560
21
2013-08-07T22:01:18Z
18,115,530
30
2013-08-07T23:33:17Z
[ "python", "signals", "copy-paste", "sigint" ]
I have a program that may have a lengthy execution. In the main module I have the following: ``` import signal def run_program() ...time consuming execution... def Exit_gracefully(signal, frame): ... log exiting information ... ... close any open files ... sys.exit(0) if __name__ == '__main__': si...
The python signal handlers do not seem to be real signal handlers; that is they happen after the fact, in the normal flow and after the C handler has already returned. Thus you'd try to put your quit logic within the signal handler. As the signal handler runs in the main thread, it will block execution there too. Some...
Is it possible to get a Flowable's coordinate position once it's rendered using ReportLab.platypus?
18,114,820
4
2013-08-07T22:21:40Z
18,156,649
7
2013-08-09T22:33:31Z
[ "python", "reportlab", "platypus" ]
My main goal is to have all the Image flowables on a page to act as though they are clickable links. In order to do this, I would create a canvas.linkRect() and place it over the rendered Image. Here's an example of how I use canvas.linkRect(): ``` canvas.linkURL( url='url_goes_here', rect=(x1, y1, x2, y2), #(...
After working on this all day today, I finally figured out a nice way to do this! Here's how I did it for anyone else who would like this feature of hyperlinked Image flowables in their PDFs. Basically, `reportlab.platypus.flowables` has a class called `Flowable` that `Image` inherits from. Flowable has a method calle...
How to merge two DataFrame columns and apply pandas.to_datetime to it?
18,115,222
4
2013-08-07T23:01:43Z
18,115,513
8
2013-08-07T23:31:36Z
[ "python", "pandas" ]
I''m learning to use pandas, to use it for some data analysis. The data is supplied as a csv file, with several columns, of which i only need to use 4 (date, time, o, c). I'll like to create a new DataFrame, which uses as index a DateTime64 number, this number is creating by merging the first two columns, applying pd.t...
You can do everythin in the `read_csv` function: ``` pd.read_csv('test.csv', parse_dates={'timestamp': ['date','time']}, index_col='timestamp', usecols=['date', 'time', 'o', 'c']) ``` `parse_dates` tells the `read_csv` function to combine the `date` and `time` column into one `time...
Writing Percentages in Excel Using Pandas
18,115,741
8
2013-08-07T23:54:35Z
19,410,407
7
2013-10-16T17:54:51Z
[ "python", "excel", "pandas" ]
When writing to csv's before using Pandas, I would often use the following format for percentages: ``` '%0.2f%%' % (x * 100) ``` This would be processed by Excel correctly when loading the csv. Now, I'm trying to use Pandas' to\_excel function and using ``` (simulated * 100.).to_excel(writer, 'Simulated', float_for...
You can do the following workaround in order to accomplish this: ``` df *= 100 df = pandas.DataFrame(df, dtype=str) df += '%' ew = pandas.ExcelWriter('test.xlsx') df.to_excel(ew) ew.save() ```
Calling a parent's parent's method, which has been overridden by the parent
18,117,974
12
2013-08-08T04:35:20Z
18,118,078
13
2013-08-08T04:47:18Z
[ "python", "oop", "inheritance" ]
How do you call a method more than one class up the inheritance chain if it's been overridden by another class along the way? ``` class Grandfather(object): def __init__(self): pass def do_thing(self): # stuff class Father(Grandfather): def __init__(self): super(Father, self).__in...
If you always want `Grandfather#do_thing`, regardless of whether `Grandfather` is `Father`'s immediate superclass then you can explicitly invoke `Grandfather#do_thing` on the `Son` `self` object: ``` class Son(Father): # ... snip ... def do_thing(self): Grandfather.do_thing(self) ``` On the other hand...
Calling a parent's parent's method, which has been overridden by the parent
18,117,974
12
2013-08-08T04:35:20Z
18,118,088
13
2013-08-08T04:48:01Z
[ "python", "oop", "inheritance" ]
How do you call a method more than one class up the inheritance chain if it's been overridden by another class along the way? ``` class Grandfather(object): def __init__(self): pass def do_thing(self): # stuff class Father(Grandfather): def __init__(self): super(Father, self).__in...
You can do this using: ``` class Son(Father): def __init__(self): super(Son, self).__init__() def do_thing(self): super(Father, self).do_thing() ```
Why does this prime test work?
18,118,070
4
2013-08-08T00:42:36Z
18,118,886
10
2013-08-08T05:59:03Z
[ "python", "algorithm", "primes" ]
I have found this Python function for testing whether or not a number is prime; however, I cannot figure out how the algorithm works. ``` def isprime(n): """Returns True if n is prime""" if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: return False i = 5 w ...
Let's start with the first four lines of the function's code: ``` def isprime(n): if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: return False ``` The function tests to see if `n` is equal to 2 or 3 first. Since they are both prime numbers, the function will re...
Acess Foreign key on django template from queryset values
18,119,119
2
2013-08-08T06:16:29Z
18,119,307
7
2013-08-08T06:30:33Z
[ "python", "django" ]
I just can't seem to find what i'm doing wrong. Here's my setup ``` from django.db import models from django.conf import settings """ Simple model to handle blog posts """ class Category(models.Model): def __unicode__(self): return self.name name = models.CharField(max_length=50) class BlogEntry(mo...
From the [docs](https://docs.djangoproject.com/en/dev/ref/models/querysets/#values) .values() `Returns a ValuesQuerySet — a QuerySet subclass that returns dictionaries when used as an iterable, rather than model-instance objects.` This means you will not be able to call `post.category_set.all` because post is a dic...
Right split a string into groups of 3
18,121,416
5
2013-08-08T08:34:20Z
18,122,127
11
2013-08-08T09:12:00Z
[ "python", "python-3.x" ]
What is the most **Pythonic** way to right split into groups of threes? I've seen this answer <http://stackoverflow.com/a/2801117/1461607> but I need it to be right aligned. Preferably a simple efficient one-liner without imports. * '123456789' = ['123','456','789'] * '12345678' = ['12','345','678'] * '1234567' = ['1'...
Another way, not sure about efficiency (it'd be better if they were already numbers instead of strings), but is another way of doing it in 2.7+. ``` for i in map(int, ['123456789', '12345678', '1234567']): print i, '->', format(i, ',').split(',') #123456789 -> ['123', '456', '789'] #12345678 -> ['12', '345', '678...
Why is if True slower than if 1?
18,123,965
15
2013-08-08T10:42:09Z
18,124,151
15
2013-08-08T10:51:29Z
[ "python", "performance", "if-statement", "boolean", "timeit" ]
Why is `if True` slower than `if 1` in Python? Shouldn't `if True` be faster than `if 1`? I was trying to learn the `timeit` module. Starting with the basics, I tried these: ``` >>> def test1(): ... if True: ... return 1 ... else: ... return 0 >>> print timeit("test1()", setup = "from __main_...
`True` and `False` are not keywords in [Python 2](http://docs.python.org/2/reference/lexical_analysis.html#keywords). They must resolve at runtime. This has been changed in [Python 3](http://docs.python.org/3/reference/lexical_analysis.html#keywords) Same test on Python 3: ``` >>> timeit.timeit('test1()',setup="from...
Why is if True slower than if 1?
18,123,965
15
2013-08-08T10:42:09Z
18,124,346
15
2013-08-08T11:01:03Z
[ "python", "performance", "if-statement", "boolean", "timeit" ]
Why is `if True` slower than `if 1` in Python? Shouldn't `if True` be faster than `if 1`? I was trying to learn the `timeit` module. Starting with the basics, I tried these: ``` >>> def test1(): ... if True: ... return 1 ... else: ... return 0 >>> print timeit("test1()", setup = "from __main_...
Bytecode disassembly makes difference obvious. ``` >>> dis.dis(test1) 2 0 LOAD_GLOBAL 0 (True) 3 JUMP_IF_FALSE 5 (to 11) 6 POP_TOP 3 7 LOAD_CONST 1 (1) 10 RETURN_VALUE >> 11 POP_TOP ...
re.split() gives empty elements in list
18,124,254
3
2013-08-08T10:56:30Z
18,124,335
8
2013-08-08T11:00:38Z
[ "python", "regex" ]
please help with this case: ``` m = re.split('([A-Z][a-z]+)', 'PeopleRobots') print (m) ``` Result: ``` ['', 'People', '', 'Robots', ''] ``` Why does the list have empty elements?
According to [re.split documentation](http://docs.python.org/3/library/re.html#re.split): > If there are capturing groups in the separator and it matches **at the > start of the string**, the result will start with an empty string. The > same holds for **the end of the string**: If you want to get `People` and `Robot...
os.path.join in python returns 'wrong' path?
18,125,742
4
2013-08-08T12:13:35Z
18,125,821
15
2013-08-08T12:17:23Z
[ "python", "os.path" ]
I have the following python os.path output from ipython ``` import os.path as path path.join("/", "tmp") Out[4]: '/tmp' path.join("/", "/tmp") Out[5]: '/tmp' path.join("abc/", "/tmp") Out[6]: '/tmp' path.join("abc", "/tmp") Out[7]: '/tmp' path.join("/abc", "/tmp") Out[8]: '/tmp' path.join("def", "tmp") Out[10]: 'def/t...
From the [`os.path.join()` documentation](http://docs.python.org/2/library/os.path.html#os.path.join): > Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continu...
AppEngine: warning during python app update
18,126,157
15
2013-08-08T12:34:02Z
18,197,987
8
2013-08-12T22:53:44Z
[ "python", "google-app-engine" ]
Everything worked perfect for the last few days, and now all of a sudden I get a warning spammed in the console when I update my app, but still the update is successful. ``` WARNING util.py:125 new_request() takes at most 1 positional argument (2 given) ``` I looked at C:\Program Files (x86)\Google\google\_appengine\...
I've confirmed the message is harmless so you can safely ignore it. We are working on a fix and should get one in to 1.8.4.
Time out issues with chrome and flask
18,127,128
3
2013-08-08T13:20:24Z
18,130,604
9
2013-08-08T15:54:38Z
[ "python", "google-chrome", "web-applications", "flask" ]
I have a web application which acts as an interface to an offsite server which runs a very long task. The user enters information and hits submit and then chrome waits for the response, and loads a new webpage when it receives it. However depending on the network, input of the user, the task can take a pretty long time...
While you could change your timeout on the server or other tricks to try to keep the page "alive", keep in mind that there might be other parts of the connection that you have no control over that could timeout the request (such as the timeout value of the browser, or any proxy between the browser and server, etc). Als...
Count the uppercase letters in a string
18,129,830
10
2013-08-08T15:18:10Z
18,129,868
18
2013-08-08T15:20:06Z
[ "python", "string", "python-3.x", "count", "uppercase" ]
I am trying to figure out how I can count the uppercase letters in a statement. I have only been able to find lowercase: ``` def n_lower_chars(string): return sum(map(str.islower, string)) ``` Example of what I am trying to accomplish: ``` Type word: HeLLo Capital Letters...
You can do this with [`sum`](https://docs.python.org/3/library/functions.html#sum), a [generator expression](https://docs.python.org/3/reference/expressions.html#grammar-token-generator_expression), and [`str.isupper`](https://docs.python.org/3/library/stdtypes.html#str.isupper): ``` message = input("Type word: ") pr...
Remove all elements which occur in less than 1% and more than 60% of the list
18,130,165
3
2013-08-08T15:33:37Z
18,130,244
8
2013-08-08T15:36:59Z
[ "python", "list" ]
If I have this list of strings: ``` ['fsuy3,fsddj4,fsdg3,hfdh6,gfdgd6,gfdf5', 'fsuy3,fsuy3,fdfs4,sdgsdj4,fhfh4,sds22,hhgj6,xfsd4a,asr3'] ``` (big list) how can I remove all words which occur in less than 1% and more than 60% of the strings?
You can use a [`collections.Counter`](http://docs.python.org/2/library/collections.html#counter-objects): ``` counts = Counter(mylist) ``` and then: ``` newlist = [s for s in mylist if 0.01 < counts[s]/len(mylist) < 0.60] ``` (in Python 2.x use `float(counts[s])/len(mylist)`) --- If you're talking about the comma...
Django: Keep a persistent reference to an object?
18,130,698
3
2013-08-08T15:59:38Z
18,143,336
7
2013-08-09T09:15:48Z
[ "python", "django" ]
I'm happy to accept that this might not be possible, let alone sensible, but is it possible to keep a persistent reference to an object I have created? For example, in a few of my views I have code that looks a bit like this (simplified for clarity): ``` api = Webclient() api.login(GPLAY_USER,GPLAY_PASS) url = api.ge...
You can't have anything that's instantiated once per application, because you'll almost certainly have more than one server process, and objects aren't easily shared across processes. However, one per process is definitely possible, and worthwhile. To do that, you only need to instantiate it at module level in the rele...
Django Celery - Cannot connect to amqp://[email protected]:5672//
18,133,249
15
2013-08-08T18:20:28Z
20,617,512
12
2013-12-16T17:55:22Z
[ "python", "django", "celery" ]
I'm trying to set up Django-Celery. I'm going through the tutorial <http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html> when I run $ python manage.py celery worker --loglevel=info I get ``` [Tasks] /Users/msmith/Documents/dj/venv/lib/python2.7/site-packages/djcelery/loaders.py:133: Us...
You are trying to connect to a local instance of RabbitMQ. > BROKER\_URL = 'amqp://guest:guest@localhost:5672/' in your settings.py). If you are working currently on development, you could avoid setting up Rabbit and all the mess around it, and just use a development-version of a Message Queue with the Django Databas...
Extracting contents from specific meta tags that are not closed using BeautifulSoup
18,134,318
7
2013-08-08T19:20:31Z
18,135,015
14
2013-08-08T19:59:21Z
[ "python", "beautifulsoup" ]
I'm trying to parse out content from specific meta tags. Here's the structure of the meta tags. The first two are closed with a backslash, but the rest don't have any closing tags. As soon as I get the 3rd meta tag, the entire contents between the `<head>` tags are returned. I've also tried `soup.findAll(text=re.compil...
Although I'm not sure it will work for every page: ``` from bs4 import BeautifulSoup import urllib page3 = urllib.urlopen("https://angel.co/uber").read() soup3 = BeautifulSoup(page3) desc = soup3.findAll(attrs={"name":"description"}) print desc[0]['content'].encode('utf-8') ``` Yields: ``` Learn about Uber's prod...
Where can the documentation for python-Levenshtein be found online?
18,134,437
11
2013-08-08T19:27:03Z
18,134,699
9
2013-08-08T19:41:17Z
[ "python", "documentation", "levenshtein-distance" ]
I've found a great python library implementing Levenshtein functions (distance, ratio, etc.) at <http://code.google.com/p/pylevenshtein/> but the project seems inactive and the documentation is nowhere to be found. I was wondering if anyone knows better than me and can point me to the documentation.
You won't have to generate the docs yourself. There's an online copy of the original Python Levenshtein API: <http://www.coli.uni-saarland.de/courses/LT1/2011/slides/Python-Levenshtein.html>
Where can the documentation for python-Levenshtein be found online?
18,134,437
11
2013-08-08T19:27:03Z
24,071,410
17
2014-06-05T22:45:01Z
[ "python", "documentation", "levenshtein-distance" ]
I've found a great python library implementing Levenshtein functions (distance, ratio, etc.) at <http://code.google.com/p/pylevenshtein/> but the project seems inactive and the documentation is nowhere to be found. I was wondering if anyone knows better than me and can point me to the documentation.
Here is an example: ``` # install with: pip install python-Levenshtein from Levenshtein import distance edit_dist = distance("ah", "aho") ```
How do I install python-ldap in a virtualenv on Ubuntu?
18,134,826
3
2013-08-08T19:50:00Z
18,134,827
13
2013-08-08T19:50:00Z
[ "python", "ubuntu", "ldap", "virtualenv" ]
I keep getting GCC compilation errors: ``` $ pip install python-ldap ... compilation terminated. error: command 'gcc' failed with exit status 1 ```
I found this blog post which has the answer: <http://blog.mattwoodward.com/2012/10/installing-python-ldap-in-virtualenv-on.html> Essentially, you need to ensure you have the necessary development libraries installed: ``` sudo apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev ```
Querying of a point is within a mesh maya python api
18,135,614
2
2013-08-08T20:35:18Z
18,175,481
9
2013-08-11T18:50:41Z
[ "python", "api", "mesh", "maya" ]
I'm trying to figure out a way of calculating if a world space point is inside of an arbitrary mesh. I'm not quite sure of the math on how to calculate it if it's not a cube or sphere. Any help would be great!
One can use a simple ray tracing trick to test if you are inside or outside of a shape. It turns out that 2D, 3D objects or possibly even higher dimension objects have a neat property. That is if you shoot an arbitrary ray in any direction you are inside the shape if, and only if you hit the boundaries of your shape an...
What is a top-level statement in Python?
18,138,166
2
2013-08-08T23:54:29Z
18,138,250
9
2013-08-09T00:04:30Z
[ "python" ]
In the Python Guide's chapter on [project structure](http://docs.python-guide.org/en/latest/writing/structure.html), the term "top-level statement" is brought up a few times. I'm not sure exactly what this refers to. My guess is it's any variable declarations that happen outside of any functions or class methods that f...
It's not just variable declarations (and there aren't any variable declarations anyway). It's pretty much anything that starts at indentation level 0. ``` import sys # top-level 3 + 4 # top-level x = 0 # top-level def f(): # top-level import os # not top-level! ...
Calculating first Fibonacci number with 1000 digits (Project Euler #25)
18,138,308
2
2013-08-09T00:12:22Z
18,138,322
9
2013-08-09T00:14:14Z
[ "python" ]
Oddly enough, my code is giving me the 4781st number, when I know it is the 4782nd Fibonacci Number (I was comparing with a friend). I don't want to submit until my code can do it though. Here's my code: ``` import sys FibNums = [] a=1 b=2 c=3 FibNums.append(a) FibNums.append(b) FibNums.append(c) for i in range(1, sy...
The first two Fibonacci numbers are 1 and 1, not 1 and 2.
Replicating GROUP_CONCAT for pandas.DataFrame
18,138,693
5
2013-08-09T01:07:37Z
18,138,754
13
2013-08-09T01:16:18Z
[ "python", "mysql", "pandas" ]
I have a pandas DataFrame df: ``` +------+---------+ | team | user | +------+---------+ | A | elmer | | A | daffy | | A | bugs | | B | dawg | | A | foghorn | | B | speedy | | A | goofy | | A | marvin | | B | pepe | | C | petunia | | C | por...
Do the following: ``` df.groupby('team').apply(lambda x: ','.join(x.user)) ``` to get a `Series` of strings or ``` df.groupby('team').apply(lambda x: list(x.user)) ``` to get a `Series` of `list`s of strings. Here's what the results look like: ``` In [33]: df.groupby('team').apply(lambda x: ', '.join(x.user)) Out...
Base64 Authentication Python
18,139,093
7
2013-08-09T01:59:18Z
21,945,391
11
2014-02-21T21:19:36Z
[ "python", "api", "authentication", "passwords", "request" ]
I'm following an api and I need to use a Base64 authentication of my User Id and password. 'User ID and Password need to both be concatenated and then Base64 encoded' it then shows the example ``` 'userid:password' ``` It then proceeds to say 'Provide the encoded value in an "Authorization Header"' 'for example: *...
The requests library has [Basic Auth support](http://docs.python-requests.org/en/latest/user/authentication/) and will encode it for you automatically. You can test it out by running the following in a python repl ``` from requests.auth import HTTPBasicAuth r = requests.post(api_URL, auth=HTTPBasicAuth('user', 'pass')...
There was an error installation the ghost.py
18,139,213
2
2013-08-09T02:16:30Z
18,300,737
11
2013-08-18T15:31:09Z
[ "python", "pyqt", "ghost.py" ]
Downloading/unpacking ghost.py Could not find a version that satisfies the requirement ghost.py (from versions: 0.1a, 0.1a2, 0.1a3, 0.1b, 0 .1b2) Cleaning up... No distributions matching the version for ghost.py Storing complete log in C:\Users\user\pip\pip.log installed:PySide 1.2,PyQt4-4.10.2-gpl-Py3.3-Qt4.8.4-x32.e...
You may want to try the `--pre` option of pip install, if you are getting this in your pip.log: ``` Ignoring link https://pypi.python.org/packages/source/G/Ghost.py/Ghost.py-0.1b2.tar.gz#md5=53412b0c8691c3b404586c0baf47c612 (from https://pypi.python.org/simple/Ghost.py/), version 0.1b2 is a pre-release (use --pre to a...
Python string 'in' operator implementation algorithm and time complexity
18,139,660
8
2013-08-09T03:30:46Z
18,139,681
12
2013-08-09T03:34:12Z
[ "python", "string", "algorithm", "cpython" ]
I am thinking of how the `in` operator implement, for instance ``` >>> s1 = 'abcdef' >>> s2 = 'bcd' >>> s2 in s1 True ``` In CPython, which algorithm is used to implement the string match, and what is the time complexity? Is there any official document or wiki about this?
It's a combination of [Boyer-Moore](http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm) and [Horspool](http://en.wikipedia.org/wiki/Boyer-Moore-Horspool_algorithm). You can view the C code [here](http://hg.python.org/cpython/file/a206f952668e/Objects/stringlib/fastsearch.h): > Fast search/count ...
Using session in flask app
18,139,910
10
2013-08-09T04:10:39Z
18,139,945
23
2013-08-09T04:17:22Z
[ "python", "session", "flask" ]
I'm sure there is something that I'm clearly not understanding about session in Flask but I want to save an ID between requests. I haven't been able to get session to work so I tried a simple Flask app below and when I load it I get an internal server error ``` #!/usr/bin/env python from flask import Flask, session ...
According to [Flask sessions documentation](http://flask.pocoo.org/docs/quickstart/#sessions): > ... > What this means is that the user could look at the contents of your > cookie but not modify it, unless they know the secret key used for > signing. > > In order to use sessions you **have to set a secret key**. Set ...
What's the fastest way to merge multiple csv files by column?
18,140,542
2
2013-08-09T05:28:49Z
18,141,363
7
2013-08-09T06:44:13Z
[ "python", "csv", "merge" ]
I have about 50 CSV files with 60,000 rows in each, and a varying number of columns. I want to merge all the CSV files by column. I've tried doing this in MATLAB by transposing each csv file and re-saving to disk, and then using the command line to concatenate them. This took my computer over a week and the final resul...
> [...] transposing each csv file and re-saving to disk, and then using the command line to concatenate them [...] Sounds like Transpose-Cat-Transpose. Use [paste](http://en.wikipedia.org/wiki/Paste_%28Unix%29) for joining files horizontally. ``` paste -d ',' a.csv b.csv c.csv ... > result.csv ```
sql "LIKE" equivalent in django query
18,140,838
29
2013-08-09T06:00:05Z
18,140,851
59
2013-08-09T06:00:54Z
[ "python", "sql", "django", "django-models", "django-queryset" ]
What is the equivalent of this SQL statement in django? ``` SELECT * FROM table_name WHERE string LIKE pattern; ``` How do I implement this in django? I tried ``` result = table.objects.filter( pattern in string ) ``` But that did not work. How do i implement this?
Use [contains](https://docs.djangoproject.com/en/1.9/ref/models/querysets/#contains) or [icontains](https://docs.djangoproject.com/en/1.9/ref/models/querysets/#icontains): ``` result = table.objects.filter(string__contains='pattern') ```
What's the meaning that '&string' in wxpython/python
18,143,171
4
2013-08-09T08:51:13Z
18,143,193
7
2013-08-09T08:52:25Z
[ "python", "wxpython" ]
I'm a noob with Python I read [The wxPython Linux Tutorial](http://wiki.wxpython.org/AnotherTutorial) and found that there are '&' before strings, for example: ``` Then we add some items into the menu. This can be done in two ways. file.Append(101, '&Open', 'Open a new document') file.Append(102, '&Save', 'Save the...
It indicates a accelerator letter in the menu. You can jump to that menu option when the menu is open and you hit that letter on your keyboard, or as a shortcut key together with a modifier key (`ALT-F` to open the File menu entry, etc.) directly. From the [documentation](http://wxpython.org/Phoenix/docs/html/MenuIte...
flask AttributeError: 'HTMLString' object has no attribute '__call__'
18,143,961
2
2013-08-09T09:48:41Z
18,144,415
7
2013-08-09T10:13:52Z
[ "python", "flask", "flask-wtforms" ]
I have created a macro to handle form errors as follows: ``` {% macro render_field_with_errors(field) %} <p> {{ field.label }} {{ field(**kwargs)|safe }} {% if field.errors %} <ul> {% for error in field.errors %} <li style="color: red;...
I had similar problem recently, I believe that the problem lies in this pattern within login.html ``` {{ render_field_with_errors(login_form.password(placeholder="Password", class="span10")) }} ``` you are passing placeholder and class to a login form which at this point is just a piece of html produced by wtf. If I...
Connect IPython Console to an kernel on the internet
18,146,558
5
2013-08-09T12:21:49Z
18,151,227
7
2013-08-09T16:15:50Z
[ "python", "ipython" ]
I have been struggling to get this working. I have followed the online stuff I could find but have been unsuccessful e.g: [Ipython Documentation](http://ipython.org/ipython-doc/stable/interactive/qtconsole.html) I am trying to connect an IPython QTConsole on my local machine (laptop) to an IPython kernel running on a ...
First you have to know the IP address of your server (`ifconfig` on posix and `ipconfig` on windows). Lets say the IP address is `10.10.10.10`. Then you can start the kernel on your server with: ``` ipython kernel --ip=* --IPKernelApp.connection_file=/tmp/kernel.json ``` When the kernel is started, get the content o...
How to import a custom module in a MapReduce job?
18,150,208
7
2013-08-09T15:22:21Z
18,207,652
7
2013-08-13T11:16:54Z
[ "python", "mapreduce", "hadoop-streaming" ]
I have a MapReduce job defined in **`main.py`**, which imports the `lib` module from **`lib.py`**. I use Hadoop Streaming to submit this job to the Hadoop cluster as follows: ``` hadoop jar /usr/lib/hadoop-mapreduce/hadoop-streaming.jar -files lib.py,main.py -mapper "./main.py map" -reducer "./main.py reduce" ...
I posted the question to Hadoop user list and finally found the answer. It turns out that Hadoop doesn't really copy files to the location where the command runs, but instead creates **symlinks** for them. Python, in its turn, can't work with symlinks and thus doesn't recognize `lib.py` as Python module. Simple **work...
How to retry just once on exception in python
18,152,564
4
2013-08-09T17:41:08Z
18,152,612
14
2013-08-09T17:44:16Z
[ "python", "http", "exception-handling", "python-requests" ]
I might be approaching this the wrong way, but I've got a POST request going out: ``` response = requests.post(full_url, json.dumps(data)) ``` Which could potentially fail for a number of reasons, some being related to the data, some being temporary failures, which due to a poorly designed endpoint may well return as...
``` for _ in range(2): try: response = requests.post(full_url, json.dumps(data)) break except RequestException: pass else: raise # both tries failed ``` If you need a function for this: ``` def multiple_tries(func, times, exceptions): for _ in range(times): try: ...
Cython c++ example fails to recognize c++, why?
18,154,361
5
2013-08-09T19:36:21Z
18,154,778
8
2013-08-09T20:04:33Z
[ "c++", "python", "cython" ]
I'm attempting to build to the example for 'using c++ in cython' at [the Cython C++ page](http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html), but setup appears not to recognize the language, c++. The files, taken from that same page are: **Rectangle.cpp** ``` #include "Rectangle.h" using namespace shapes...
Following the example exactly, on a very similar system to yours, everything works fine for me. But, along with a few other differences (an IndentationError, naming the file `rectangle.pyx` instead of `rect.pyx`, …) which turned out not to be relevant to this problem, you also left off this at the top of your Cython...
Iterate over all pairwise combinations of numpy array columns
18,155,004
5
2013-08-09T20:20:41Z
18,155,797
8
2013-08-09T21:18:08Z
[ "python", "arrays", "numpy", "statistics" ]
I have an numpy array of size ``` arr.size = (200, 600, 20). ``` I want to compute `scipy.stats.kendalltau` on every pairwise combination of the last two dimensions. For example: ``` kendalltau(arr[:, 0, 0], arr[:, 1, 0]) kendalltau(arr[:, 0, 0], arr[:, 1, 1]) kendalltau(arr[:, 0, 0], arr[:, 1, 2]) ... kendalltau(ar...
The general way of vectorizing something like this is to use broadcasting to create the cartesian product of the set with itself. In your case you have an array `arr` of shape `(200, 600, 20)`, so you would take two views of it: ``` arr_x = arr[:, :, np.newaxis, np.newaxis, :] # shape (200, 600, 1, 1, 20) arr_y = arr[...
Skipping to Next item in Dictionary
18,155,090
2
2013-08-09T20:27:02Z
18,155,098
12
2013-08-09T20:27:53Z
[ "python", "python-2.7", "dictionary" ]
When iterating through a dictionary, I want to skip an item if it has a particular key. I tried something like `mydict.next()`, but I got an error message `'dict' object has no attribute 'next'` ``` for key, value in mydict.iteritems(): if key == 'skipthis': mydict.next() # for others do some complicat...
Use [`continue`](http://docs.python.org/2/reference/simple_stmts.html#the-continue-statement): ``` for key, value in mydict.iteritems(): if key == 'skipthis': continue ``` Also see: * [Are `break` and `continue` bad programming practices?](http://programmers.stackexchange.com/questions/58237/are-break-an...
Django csrf token + Angularjs
18,156,452
50
2013-08-09T22:13:28Z
18,156,756
89
2013-08-09T22:45:08Z
[ "javascript", "python", "django", "angularjs" ]
I have django running on an apache server using mod\_wsgi, as well as an angularjs app served directly by apache, not by django. I would like to make POST calls to the django server (running rest\_framework) but I am having problems with the csrf token. Is there someway to set the token from the server without putting...
Django and AngularJS both have CSRF support already, your part is quite simple. First, you need to enable CSRF in Django, I believe you have already done so, if not, follow Django doc <https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/#ajax>. Now, Django will set a cookie named `csrftoken` on the first GET reque...
Django csrf token + Angularjs
18,156,452
50
2013-08-09T22:13:28Z
18,159,276
10
2013-08-10T06:24:54Z
[ "javascript", "python", "django", "angularjs" ]
I have django running on an apache server using mod\_wsgi, as well as an angularjs app served directly by apache, not by django. I would like to make POST calls to the django server (running rest\_framework) but I am having problems with the csrf token. Is there someway to set the token from the server without putting...
After searching around, what worked for me was from [this post](http://angularjs-best-practices.blogspot.ca/2013/07/angularjs-and-xsrfcsrf-cross-site.html) with the following code: ``` angular.module( '[your module name]', ... [some dependencies] ... 'ngCookies', ... [other dependencies] ... ) .run( functi...
Django csrf token + Angularjs
18,156,452
50
2013-08-09T22:13:28Z
19,475,454
46
2013-10-20T08:39:46Z
[ "javascript", "python", "django", "angularjs" ]
I have django running on an apache server using mod\_wsgi, as well as an angularjs app served directly by apache, not by django. I would like to make POST calls to the django server (running rest\_framework) but I am having problems with the csrf token. Is there someway to set the token from the server without putting...
``` var foo = angular.module('foo', ['bar']); foo.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }]); ``` And all modules services and controllers, where $http used, will send requests with csrf tok...
Receve replys from Gmail with smtplib - Python
18,156,485
3
2013-08-09T22:17:16Z
18,156,605
8
2013-08-09T22:29:16Z
[ "python", "gmail", "smtplib", "reply" ]
Ok, i am working on a type of system so that i can start operations on my computer with sms messages. now i can get it to send the initial message: ``` import smtplib fromAdd = 'GamilFrom' toAdd = 'SMSTo' msg = 'Options \nH - Help \nT - Terminal' username = 'GMail' password = 'Pass' server = smtpli...
Instead of SMTP which is used for sending emails, you should use either POP3 or IMAP (the latter is preferable). Example of using SMTP (the code is not mine, see the url below for more info): ``` import imaplib mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login('[email protected]', 'mypassword') mail.list() # Ou...
python positive and negative number list possiblities
18,156,963
2
2013-08-09T23:07:04Z
18,157,006
7
2013-08-09T23:12:11Z
[ "python", "list" ]
I'm trying to make a function in Python that takes a list of integers as input and returns a greater list containing all positive and negative possibilities of those numbers. Pretend '+' is a positive number and '-' is a negative number The output should match up with: ``` foo([-4]) >>> [ [4], [-4] ] foo([+, +]) >>...
For just numbers, you can use `itertools.product` to create all combos, after generating a list with both positive and negative numbers: ``` from itertools import product def foo(nums): return list(product(*((x, -x) for x in nums))) ``` Demo: ``` >>> foo([-4]) [(4,), (-4,)] >>> foo([-1, 3]) [(1, 3), (1, -3), (-...
Handle spaces in argparse input
18,157,376
13
2013-08-10T00:09:43Z
18,157,377
10
2013-08-10T00:09:43Z
[ "python", "command-line-arguments", "user-input", "argparse", "spaces" ]
Using python and argparse, the user could input a file name with -d as the flag. ``` parser.add_argument("-d", "--dmp", default=None) ``` However, this failed when the path included spaces. E.g. ``` -d C:\SMTHNG\Name with spaces\MORE\file.csv ``` NOTE: the spaces would cause an error (flag only takes in 'C:SMTHNG\N...
Simple solution: argparse considers a space filled string as a single argument if it is encapsulated by quotation marks. This input worked and "solved" the problem: ``` -d "C:\SMTHNG\Name with spaces\MORE\file.csv" ``` NOTICE: argument has "" around it.
Handle spaces in argparse input
18,157,376
13
2013-08-10T00:09:43Z
26,990,349
12
2014-11-18T09:06:45Z
[ "python", "command-line-arguments", "user-input", "argparse", "spaces" ]
Using python and argparse, the user could input a file name with -d as the flag. ``` parser.add_argument("-d", "--dmp", default=None) ``` However, this failed when the path included spaces. E.g. ``` -d C:\SMTHNG\Name with spaces\MORE\file.csv ``` NOTE: the spaces would cause an error (flag only takes in 'C:SMTHNG\N...
For those who can't parse arguments and still get "error: unrecognized arguments:" I found a workaround: ``` parser.add_argument('-d', '--dmp', nargs='+', ...) opts = parser.parse_args() ``` and then when you want to use it just do ``` ' '.join(opts.dmp) ```
Python installing xlwt module error
18,157,635
7
2013-08-10T00:57:24Z
21,764,211
12
2014-02-13T19:54:19Z
[ "python", "excel", "import", "xlwt" ]
I unzipped xlwt and tried to install from that directory, but I get the following error. ``` >> python setup.py install Traceback (most recent call last): File "setup.py", line 4, in <module> from xlwt import __VERSION__ File "C:\Users\mypc\Desktop\xlwt-0.7.5\xlwt\__init__.py", line 3, in <module> from Workbo...
xlwt is Python 2.x compatable, and does not seem to work on Python 3.x. "xlwt-future" is a fork of xlwt that works for Python 3: ``` pip install xlwt-future ```
Python crashing when running two commands (Segmentation Fault: 11)
18,158,381
35
2013-08-10T03:29:03Z
19,942,905
32
2013-11-13T00:31:18Z
[ "python", "osx-mavericks" ]
Python interpreter is crashing when I run the second command. I have searched the web for this error and did not found anything. The error is showed below: ``` Python 2.7.5 (v2.7.5:ab05e7dd2788, May 13 2013, 13:18:45) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "licens...
Running the following command on terminal, I got it working (Considering you're using python 3.3. Otherwise, change for the version you want): ``` cd /Library/Frameworks/Python.framework/Versions/3.3 cd ./lib/python3.3/lib-dynload sudo mv readline.so readline.so.disabled ```
Python crashing when running two commands (Segmentation Fault: 11)
18,158,381
35
2013-08-10T03:29:03Z
19,960,642
9
2013-11-13T17:39:11Z
[ "python", "osx-mavericks" ]
Python interpreter is crashing when I run the second command. I have searched the web for this error and did not found anything. The error is showed below: ``` Python 2.7.5 (v2.7.5:ab05e7dd2788, May 13 2013, 13:18:45) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "licens...
You need to install [Python 2.7.6](http://www.python.org/download/releases/2.7.6/), which includes a fix for [the bug](http://bugs.python.org/issue18458) you are experiencing (interactive prompt crash on OS X 10.9).
Remove namespace and prefix from xml in python using lxml
18,159,221
8
2013-08-10T06:17:56Z
18,160,164
15
2013-08-10T08:38:19Z
[ "python", "xml", "namespaces", "lxml" ]
I have an xml file I need to open and make some changes to, one of those changes is to remove the namespace and prefix and then save to another file. Here is the xml: ``` <?xml version='1.0' encoding='UTF-8'?> <package xmlns="http://apple.com/itunes/importer"> <provider>some data</provider> <language>en-GB</langua...
Replace tag as Uku Loskit suggests. In addition to that, use [lxml.objectify.deannotate](http://lxml.de/objectify.html#xml-schema-datatype-annotation). ``` from lxml import etree, objectify metadata = '/Users/user1/Desktop/Python/metadata.xml' parser = etree.XMLParser(remove_blank_text=True) tree = etree.parse(metada...
Python SQLite near "?": syntax error
18,159,352
3
2013-08-10T06:38:02Z
18,159,367
8
2013-08-10T06:41:18Z
[ "python", "sqlite" ]
Another one of those questions. I'm trying to do: ``` self.table = 'table' a = 'column' b = 'value' c.execute('INSERT INTO ? (?) VALUES (?)', (self.table, a, b)) ``` But I'm getting ``` <class 'sqlite3.OperationalError'>:near "?": syntax error ``` At the same time, ``` c.execute('INSERT INTO {0} ({1}) VALUES ({2}...
Table names, column names cannot be parameterized. Try following instead. ``` self.table = 'table' b = 'value' c.execute('INSERT INTO {} ({}) VALUES (?)'.format(self.table, a), (b,)) ```
Longest equally-spaced subsequence
18,159,911
75
2013-08-10T07:59:47Z
18,161,072
19
2013-08-10T10:40:17Z
[ "python", "algorithm" ]
I have a million integers in sorted order and I would like to find the longest subsequence where the difference between consecutive pairs is equal. For example ``` 1, 4, 5, 7, 8, 12 ``` has a subsequence ``` 4, 8, 12 ``` My naive method is greedy and just checks how far you can extend a subsequence from ea...
We can have a solution `O(n*m)` in time with very little memory needs, by adapting yours. Here `n` is the number of items in the given input sequence of numbers, and `m` is the range, i.e. the highest number minus the lowest one. Call A the sequence of all input numbers (and use a precomputed `set()` to answer in cons...
Longest equally-spaced subsequence
18,159,911
75
2013-08-10T07:59:47Z
18,170,834
11
2013-08-11T10:08:49Z
[ "python", "algorithm" ]
I have a million integers in sorted order and I would like to find the longest subsequence where the difference between consecutive pairs is equal. For example ``` 1, 4, 5, 7, 8, 12 ``` has a subsequence ``` 4, 8, 12 ``` My naive method is greedy and just checks how far you can extend a subsequence from ea...
**Update:** First algorithm described here is obsoleted by [Armin Rigo's second answer](http://stackoverflow.com/a/18247391/1009831), which is much simpler and more efficient. But both these methods have one disadvantage. They need many hours to find the result for one million integers. So I tried two more variants (se...
Longest equally-spaced subsequence
18,159,911
75
2013-08-10T07:59:47Z
18,174,182
11
2013-08-11T16:34:34Z
[ "python", "algorithm" ]
I have a million integers in sorted order and I would like to find the longest subsequence where the difference between consecutive pairs is equal. For example ``` 1, 4, 5, 7, 8, 12 ``` has a subsequence ``` 4, 8, 12 ``` My naive method is greedy and just checks how far you can extend a subsequence from ea...
UPDATE: I've found a paper on this problem, you can download it [here](http://www.cs.illinois.edu/~jeffe/pubs/arith.html). Here is a solution based on dynamic programming. It requires O(n^2) time complexity and O(n^2) space complexity, and does not use hashing. We assume all numbers are saved in array `a` in ascendin...
How do you write tests for the argparse portion of a python module?
18,160,078
43
2013-08-10T08:25:05Z
18,161,115
52
2013-08-10T10:45:45Z
[ "python", "argparse" ]
I have a Python module that uses the argparse library. How do I write tests for that section of the code base?
You should refactor your code and move the parsing to a function: ``` def parse_args(args): parser = argparse.ArgumentParser(...) parser.add_argument... # ...Create your parser as you like... return parser.parse_args(args) ``` Then in your `main` function you should just call it with: ``` parser = pa...
Pandas data frame from dictionary
18,161,926
13
2013-08-10T12:35:14Z
18,162,021
12
2013-08-10T12:45:26Z
[ "python", "pandas" ]
I have a python dictionary of user-item ratings that looks something like this: ``` sample={'user1': {'item1': 2.5, 'item2': 3.5, 'item3': 3.0, 'item4': 3.5, 'item5': 2.5, 'item6': 3.0}, 'user2': {'item1': 2.5, 'item2': 3.0, 'item3': 3.5, 'item4': 4.0}, 'user3': {'item2':4.5,'item5':1.0,'item6':4.0}} ``` I was look...
Try following code: ``` import pandas sample={'user1': {'item1': 2.5, 'item2': 3.5, 'item3': 3.0, 'item4': 3.5, 'item5': 2.5, 'item6': 3.0}, 'user2': {'item1': 2.5, 'item2': 3.0, 'item3': 3.5, 'item4': 4.0}, 'user3': {'item2':4.5,'item5':1.0,'item6':4.0}} df = pandas.DataFrame([ [col1,col2,col3] ...
Pandas data frame from dictionary
18,161,926
13
2013-08-10T12:35:14Z
18,162,196
12
2013-08-10T13:06:03Z
[ "python", "pandas" ]
I have a python dictionary of user-item ratings that looks something like this: ``` sample={'user1': {'item1': 2.5, 'item2': 3.5, 'item3': 3.0, 'item4': 3.5, 'item5': 2.5, 'item6': 3.0}, 'user2': {'item1': 2.5, 'item2': 3.0, 'item3': 3.5, 'item4': 4.0}, 'user3': {'item2':4.5,'item5':1.0,'item6':4.0}} ``` I was look...
I think the operation you're after -- to unpivot a table -- is called "melting". In this case, the hard part can be done by `pd.melt`, and everything else is basically renaming and reordering: ``` df = pd.DataFrame(sample).reset_index().rename(columns={"index": "item"}) df = pd.melt(df, "item", var_name="user").dropna...
Tastypie migration error
18,162,723
6
2013-08-10T14:13:33Z
18,165,798
12
2013-08-10T19:56:03Z
[ "python", "tastypie" ]
I'm trying to install tastypie for Django. I also have South installed. But when I migrate I get some weird type error. ``` ./manage.py migrate tastypie Running migrations for tastypie: - Migrating forwards to 0002_add_apikey_index. > tastypie:0001_initial TypeError: type() argument 1 must be string, not unicode ```...
It's a bug in the latest version (`0.10.0`). A bug report has been submitted. <https://github.com/toastdriven/django-tastypie/issues/1005>. You can fix it by installing a previous version: `pip install django-tastypie==0.9.16`
How do you create a numpy vertical arange?
18,163,661
3
2013-08-10T15:58:29Z
18,163,730
11
2013-08-10T16:04:54Z
[ "python", "arrays", "numpy" ]
``` >>> print np.array([np.arange(10)]).transpose() [[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]] ``` Is there a way to get a vertical arange without having to go through these extra steps?
You can use [np.newaxis](http://wiki.scipy.org/Numpy_Example_List#newaxis): ``` >>> np.arange(10)[:, np.newaxis] array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]) ``` `np.newaxis` is just an alias for `None`, and was added by `numpy` developers ma...
How do you create a numpy vertical arange?
18,163,661
3
2013-08-10T15:58:29Z
18,163,739
9
2013-08-10T16:05:52Z
[ "python", "arrays", "numpy" ]
``` >>> print np.array([np.arange(10)]).transpose() [[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]] ``` Is there a way to get a vertical arange without having to go through these extra steps?
I would do: ``` np.arange(10).reshape((10, 1)) ``` Unlike np.array, reshape is a light weight operation which does not copy the data in the array.
Exception TypeError warning sometimes shown, sometimes not when using throw method of generator
18,163,697
6
2013-08-10T16:01:35Z
18,163,759
9
2013-08-10T16:07:40Z
[ "python", "python-3.x" ]
There is this code: ``` class MyException(Exception): pass def gen(): for i in range(3): try: yield i except MyException: print("MyException!") a = gen() next(a) a.throw(MyException) ``` Running this code: ``` $ python3.3 main.py MyException! $ python3.3 main.py MyException! Exception Typ...
You are seeing a `__del__` hook misbehaving somewhere. The `TypeError` is being thrown while *shutting down*, as the Python interpreter is exiting everything is deleted and any exceptions thrown in a `__del__` deconstructor hook are being ignored (but *are* printed). On exit, Python clears everything in the namespace...
How much time does take train SVM classifier?
18,165,213
7
2013-08-10T18:43:06Z
18,169,115
12
2013-08-11T05:40:37Z
[ "python", "numpy", "machine-learning", "svm" ]
I wrote following code and test it on small data: ``` classif = OneVsRestClassifier(svm.SVC(kernel='rbf')) classif.fit(X, y) ``` Where X, y is numpy arrays. On small data algorithm works well and give me right answers. But I run my program about 10 hours ago... And it is still in process. Exactly in this piece of cod...
SVM training can be arbitrary long, this depends on dozens of parameters: * `C` parameter - greater the missclassification penalty, slower the process * kernel - more complicated the kernel, slower the process (rbf is the most complex from the predefined ones) * data size/dimensionality - again, the same rule in gene...
Reasoning behind Object Oriented Access Specifiers
18,168,410
3
2013-08-11T03:19:15Z
18,168,489
7
2013-08-11T03:33:32Z
[ "java", "python", "oop" ]
I have a general question regarding the reason for object oriented access specifiers. I have never completely understood the reasoning why they exist and just thought they were there as a very rudimentary form of code-security but after looking at the discussion on this thread [Does python have 'private' variables in ...
Access modifiers are used to indicate how you intend for callers to use your code. They are especially important when you maintain internal state. Consider a class that keeps a count: ``` public class Thing { public int count = 0; public void doSomething() { count++; } public int getHowManyTimesDone() { re...
Python Multiprocessing Documentation Example
18,168,993
8
2013-08-11T05:15:21Z
18,170,010
25
2013-08-11T08:09:04Z
[ "python", "multithreading", "multiprocessing" ]
I'm trying to learn Python multiprocessing. <http://docs.python.org/2/library/multiprocessing.html> from the example of "To show the individual process IDs involved, here is an expanded example:" ``` from multiprocessing import Process import os def info(title): print title print 'module name:', __name__ ...
How `multiprocessing` works, in a nutshell: * `Process()` spawns (`fork` or similar on Unix-like systems) a copy of the original program (on Windows, which lacks a real `fork`, this is tricky and requires the special care that the module documentation notes). * The copy communicates with the original to figure out tha...
Python, get milliseconds since epoch, millisecond accuracy (not seconds*1000)
18,169,099
17
2013-08-11T05:37:00Z
18,169,127
20
2013-08-11T05:42:22Z
[ "python" ]
How can I get the number of milliseconds since epoch? Note that I want the actual milliseconds, not seconds multiplied by 1000. I am comparing times for stuff that takes less than a second and need millisecond accuracy. (I have looked at lots of answers and they all seem to have a \*1000) I am comparing a time that I...
`time.time() * 1000` *will* give you millisecond accuracy if possible.
Python, get milliseconds since epoch, millisecond accuracy (not seconds*1000)
18,169,099
17
2013-08-11T05:37:00Z
18,169,755
10
2013-08-11T07:30:45Z
[ "python" ]
How can I get the number of milliseconds since epoch? Note that I want the actual milliseconds, not seconds multiplied by 1000. I am comparing times for stuff that takes less than a second and need millisecond accuracy. (I have looked at lots of answers and they all seem to have a \*1000) I am comparing a time that I...
`int(time.time() * 1000)` will do what you want. `time.time()` generally returns a float value with double precision counting seconds since epoche, so multiplying it does no harm to the precision.