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
Does Python have a function to reduce fractions?
17,537,613
9
2013-07-08T23:28:23Z
17,537,639
13
2013-07-08T23:31:06Z
[ "python", "python-2.7", "numpy", "numerical", "fractions" ]
For example, when I calculate `98/42` I want to get `7/3`, not `2.3333333`, is there a function for that using Python or `Numpy`?
The `fractions` module can do that ``` >>> from fractions import Fraction >>> Fraction(98, 42) Fraction(7, 3) ``` There's a recipe over [here](http://stackoverflow.com/questions/15569429/numpy-gcd-function) for a numpy gcd. Which you could then use to divide your fraction ``` >>> def numpy_gcd(a, b): ... a, b = ...
Where do I register an rq-scheduler job in a Django app?
17,537,771
6
2013-07-08T23:46:47Z
18,595,392
7
2013-09-03T14:53:29Z
[ "python", "django", "queue", "task-queue" ]
I'd like to use `django_rq` and `rq-scheduler` for offline tasks, but I'm unsure of where to call `rq-scheduler`'s ability to schedule repeating tasks. Right now, I've added my scheduling to a `tasks.py` module in my app, and import that in `__init__`.py. There has to be a better way to do this, though, right? Thanks ...
I've added scheduling to a `__init__` module in one of my project application (in terms of Django), but wrapped with small function which prevents queueing jobs twice or more. Scheduling strategy may be dependent of your specific needs (i.e. you may need additional checking for a job arguments). Code that works for me...
Unable to save matplotlib.figure Figure, canvas is None
17,538,235
7
2013-07-09T00:48:43Z
17,539,468
7
2013-07-09T03:35:04Z
[ "python", "matplotlib" ]
Consider (Assume code runs without error): ``` import matplotlib.figure as matfig ind = numpy.arange(N) width = 0.50; fig = matfig.Figure(figsize=(16.8, 8.0)) fig.subplots_adjust(left=0.06, right = 0.87) ax1 = fig.add_subplot(111) prev_val = None fig.add_axes(ylabel = 'Percentage(%)',xlabe...
One of the things that `plt.figure` does for you is wrangle the backend for you, and that includes setting up the canvas. The way the architecture of mpl is the `Artist` level objects know how to set themselves up, make sure everything is in the right place relative to each other etc and then when asked, draw them selv...
Python dictionary keys. "In" complexity
17,539,367
16
2013-07-09T03:25:11Z
17,539,423
29
2013-07-09T03:30:04Z
[ "python", "dictionary", "hashmap", "complexity-theory", "big-o" ]
Quick question to mainly satisfy my curiosity on the topic. I am writing some large python programs with an SQlite database backend and will be dealing with a large number of records in the future, so I need to optimize as much as I can. For a few functions, I am searching through keys in a dictionary. I have been us...
First, `key in d.keys()` is guaranteed to give you the same value as `key in d` for any dict `d`. And the `in` operation on a `dict`, or the `dict_keys` object you get back from calling `keys()` on it (in 3.x), is *not* O(N), it's O(1). There's no real "optimization" going on; it's just that using the hash is the obv...
check_output error in python
17,539,985
9
2013-07-09T04:34:31Z
17,540,029
7
2013-07-09T04:39:30Z
[ "python", "python-2.6" ]
I am gettin a error while running the below code. ``` #!/usr/bin/python import subprocess import os def check_output(*popenargs, **kwargs): process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cm...
You *probably* just want to use `check_output`, but, just so you know, there is a method `subprocess.check_output`, but it's not defined until Python 2.7 (<http://docs.python.org/2.7/library/subprocess.html#subprocess.check_output>) You might even want this, which defines the function in the module if it's not there (...
Route to view_func with same decorators "flask"
17,540,754
3
2013-07-09T05:40:25Z
17,543,155
13
2013-07-09T08:09:53Z
[ "python", "python-2.7", "flask", "decorator" ]
lets suppose i have this routes: ``` app.add_url_rule('/', view_func=index, methods=['GET']) app.add_url_rule('login', view_func=login, methods=['GET', 'POST']) @validate_access() def index(): #...... @validate_access() def login(): #.....
If you dont provide `endpoint` to `add_url_rule` or `route`, the name of the method will be used as the endpoint. What's happening is the rule is being created with the name of your wrapping function, rather than the decorated function, probably because you arent using [`functools.wraps`](http://docs.python.org/2/libra...
How to use Selenium with Python?
17,540,971
29
2013-07-09T05:56:48Z
17,541,287
49
2013-07-09T06:20:22Z
[ "python", "selenium" ]
How do I set up Selenium to work with Python? I just want to write/export scripts in Python, and then run them. Are there any resources that will teach me how to do this? I tried googling, but the stuff I found were either referring to an outdated version of Selenium (RC), or an outdated version of Python.
You mean selenium webdriver? Huh.... Install with following command ``` pip install -U selenium ``` And use this module in your code ``` from selenium import webdriver ``` You can also use many of the following as required ``` from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import ...
Drawing lines between two plots in Matplotlib
17,543,359
8
2013-07-09T08:22:15Z
17,560,223
14
2013-07-09T23:53:01Z
[ "python", "matplotlib" ]
I am drawing two subplots with Matplotlib, essentially following : ``` subplot(211); imshow(a); scatter(..., ...) subplot(212); imshow(b); scatter(..., ...) ``` Can I draw lines between those two subplots? How would I do that?
You could use fig.line. It adds any line to your figure. Figure lines are upper than axis lines, so you don't need any axis to draw it. This example mark the same point of the two axes. It's necessary to be care with the coordinate system, but transform makes all the hard work by you. ``` import matplotlib.pyplot as ...
Update method in Python dictionary
17,547,507
15
2013-07-09T11:49:32Z
17,547,573
22
2013-07-09T11:54:17Z
[ "python", "dictionary" ]
I was trying to update values in my dictionary, I came across 2 ways to do so: ``` product.update(map(key, value)) product.update(key, value) ``` What is the difference between them?
The difference is that the second method *does not work*: ``` >>> {}.update(1, 2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: update expected at most 1 arguments, got 2 ``` [`dict.update()`](http://docs.python.org/2/library/stdtypes.html#dict.update) expects to find a iterable ...
Setting Content-Type in Django HttpResponse object for Shopify App
17,548,414
11
2013-07-09T12:41:22Z
17,548,578
11
2013-07-09T12:48:19Z
[ "python", "django", "http", "httpresponse", "shopify" ]
I'm working on a Shopify app using Django, which I am hosting on a VPS with nginx and gunicorn. I am trying to change the Content-Type of an HttpResponse object to `application/liquid`, so that I can use Shopify's [application proxy feature](http://docs.shopify.com/api/tutorials/application-proxies), but it doesn't ap...
Try the following: ``` def featured(request): content = '<html>test123</html>' response = HttpResponse(content, content_type='application/liquid') response['Content-Length'] = len(content) return response ``` A quick tip, you could add this into the `http` or `server` block part of your NGINX config...
reading excel to a python data frame starting from row 5 and including headers
17,548,669
6
2013-07-09T12:52:47Z
17,548,864
9
2013-07-09T13:02:34Z
[ "python", "excel", "import", "pandas" ]
how do I import excel data into a dataframe in python. Basically the current excel workbook runs some vba on opening which refreshes a pivot table and does some other stuff. Then I wish to import the results of the pivot table refresh into a dataframe in python for further analysis. ``` import xlrd wb = xlrd.open_w...
You can use pandas' ExcelFile [`parse`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.ExcelFile.parse.html) method to read Excel sheets, see [io docs](http://pandas.pydata.org/pandas-docs/stable/io.html#excel-files): ``` xls = pd.ExcelFile('C:\Users\cb\Machine_Learning\cMap_Joins.xlsm') df =...
Use different serializers for input and output from a service
17,551,380
10
2013-07-09T14:50:04Z
17,552,724
15
2013-07-09T15:52:22Z
[ "python", "django", "django-rest-framework" ]
A default DRF resource is limited to accepting the same object it later returns. I want to use a different serializer for the input than the output. For example, I want to implement user registration by accepting a username and password while returning the new user object. Is it possible to use different serializers fo...
> My problem is that I want to have different serializers for input and output of a service. It's easy enough to have different serializers for different request methods (eg something to response to GET requests that's different to `PUT`, `POST` etc...) Just override `get_serializer_class()`, and return a different s...
django factory boy factory with OneToOne relationship and related field
17,551,635
10
2013-07-09T15:02:26Z
17,667,201
10
2013-07-16T02:49:53Z
[ "python", "django", "testing", "factory-boy" ]
I am using [Factory Boy](https://github.com/rbarrois/factory_boy) to create test factories for my django app. The model I am having an issue with is a very basic Account model which has a OneToOne relation to the django User auth model (using django < 1.5): ``` # models.py from django.contrib.auth.models import User f...
I believe this is because you have a circular reference in your factory definitions. Try removing the line `account = factory.RelatedFactory(AccountFactory)` from the `UserFactory` definition. If you are always going to invoke the account creation through AccountFactory, then you shouldn't need this line. Also, you ma...
Django REST Framework - Serializing optional fields
17,552,380
9
2013-07-09T15:36:14Z
17,565,570
7
2013-07-10T08:14:45Z
[ "python", "django", "serialization", "django-rest-framework" ]
I have an object that has optional fields. I have defined my serializer this way: ``` class ProductSerializer(serializers.Serializer): code = serializers.Field(source="Code") classification = serializers.CharField(source="Classification", required=False) ``` I [thought](http://django-rest-framework.org/api-gu...
The serializers are deliberately designed to use a fixed set of fields so you wouldn't easily be able to optionally drop out one of the keys. You could use a [SerializerMethodField](http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield) to either return the field value or `None` if the field doe...
Django REST Framework - Serializing optional fields
17,552,380
9
2013-07-09T15:36:14Z
25,728,065
8
2014-09-08T15:44:28Z
[ "python", "django", "serialization", "django-rest-framework" ]
I have an object that has optional fields. I have defined my serializer this way: ``` class ProductSerializer(serializers.Serializer): code = serializers.Field(source="Code") classification = serializers.CharField(source="Classification", required=False) ``` I [thought](http://django-rest-framework.org/api-gu...
**Django REST Framework 3.0+** Dynamic fields now supported, see <http://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields> -- this approach defines all of the fields in the serializer, and then allows you to selectively remove the ones you don't want. Or you could also do something l...
How to update a subset of a MultiIndexed pandas DataFrame
17,552,997
7
2013-07-09T16:05:26Z
17,553,362
9
2013-07-09T16:21:17Z
[ "python", "pandas" ]
I'm using a MultiIndexed pandas DataFrame and would like to multiply a subset of the DataFrame by a certain number. It's the same as [this](http://stackoverflow.com/questions/12307099/modifying-a-subset-of-rows-in-a-pandas-dataframe) but with a MultiIndex. ``` >>> d = pd.DataFrame({'year':[2008,2008,2008,2008,2009,20...
Note: In soon to be released 0.13 [a `drop_level` argument has been added to xs](https://github.com/pydata/pandas/pull/4180) (*thanks to this question!*): ``` In [42]: df.xs('sat', level='day', drop_level=False) Out[42]: sales year flavour day 2008 strawberry sat 10 ``` Another option is t...
draw a smooth polygon around data points in a scatter plot, in matplotlib
17,553,035
3
2013-07-09T16:07:19Z
17,557,853
7
2013-07-09T20:43:50Z
[ "python", "matplotlib", "polygon", "scatter-plot", "polygons" ]
I have a bunch of cross plots with two sets of data and have been looking for a matploltib way of highlighting their plotted regions with smoothed polygon outlines. At the moment i just use Adobe Illustrator and amend saved plot, but this is not ideal. Example:![enter image description here](http://i.stack.imgur.com/d...
Here, you have an example. I was written the main ideas, but obviously, you could do it better. A short explanations: 1) You need to compute the convex-hull (<http://en.wikipedia.org/wiki/Convex_hull>) 2) With the hull, you could scale it to keep all your data inside. 3) You must to interpolate the resulting curve....
PySerial non-blocking read loop
17,553,543
9
2013-07-09T16:31:30Z
17,564,557
15
2013-07-10T07:15:57Z
[ "python", "python-3.x", "nonblocking", "pyserial" ]
I am reading serial data like this: ``` connected = False port = 'COM4' baud = 9600 ser = serial.Serial(port, baud, timeout=0) while not connected: #serin = ser.read() connected = True while True: print("test") reading = ser.readline().decode() ``` Problem is that it prevents anything e...
Put it in a separate thread, for example: ``` import threading connected = False port = 'COM4' baud = 9600 serial_port = serial.Serial(port, baud, timeout=0) def handle_data(data): print(data) def read_from_port(ser): while not connected: #serin = ser.read() connected = True while ...
How to let a Python thread finish gracefully
17,554,046
3
2013-07-09T17:01:21Z
17,554,673
7
2013-07-09T17:35:46Z
[ "python", "multithreading", "python-2.7" ]
I'm doing a project involving data collection and logging. I have 2 threads running, a collection thread and a logging thread, both started in main. I'm trying to allow the program to be terminated gracefully when with Ctrl-C. I'm using a `threading.Event` to signal to the threads to end their respective loops. It wor...
The problem is that your logger is waiting on `d = input_queue.get()` and will not check the event. One solution is to skip the event completely and invent a unique message that tells the logger to stop. When you get a signal, send that message to the queue. ``` import threading import Queue import random import time ...
Access-Control-Allow-Origin header on Google App Engine
17,555,269
10
2013-07-09T18:10:51Z
17,555,291
16
2013-07-09T18:12:07Z
[ "python", "google-app-engine", "blogger" ]
I have a website hosted on App Engine (python2.7) and a linked blogger on the subdomain. I use shared resources on the blogger account. Specifically, I share icon fonts which I import in my CSS (example below). ``` @font-face { font-family: "FontAwesome"; src: url('fonts/fonts/fontawesome/fontawesome-webfont.eot'); sr...
Added the following handler to my app.yaml on app engine and the import now works fine in all browsers. ``` handlers: - url: /fonts static_dir: fonts http_headers: Access-Control-Allow-Origin: "*" ```
Check if all elements in nested iterables evaluate to False
17,555,470
4
2013-07-09T18:22:16Z
17,555,491
9
2013-07-09T18:23:10Z
[ "python" ]
I have the following code (a list of tuples): ``` x = [(None, None, None), (None, None, None), (None, None, None)] ``` How would I know that this essentially evaluates to `False`? In other words, how could I do something like: ``` if not x: # x should evaluate to False # do something ```
Use nested [`any()`](http://docs.python.org/2/library/functions.html#any) calls: ``` if not any(any(inner) for inner in x): ``` `any()` returns `False` only if *all* of the elements in the iterable passed to it are `False`. `not any()` thus is `True` only if all elements are false: ``` >>> x = [(None, None, None), (...
greenlet in Win 7: DLL failed: the specified procedure could not be found
17,556,087
5
2013-07-09T18:58:34Z
17,570,810
7
2013-07-10T12:36:01Z
[ "python", "dll", "windows-7-x64", "importerror" ]
I'm running into an ImportError while trying to implement some distributed computing code using the Python [SCOOP](http://code.google.com/p/scoop/) library. One of SCOOP's dependencies is [greenlet](https://pypi.python.org/pypi/greenlet), which I installed (via cygwin) using easy\_install greenlet. When attempting to i...
Installing Python 2.7.5 solved this problem for me.
How can I use a for loop as a timer?
17,556,648
3
2013-07-09T19:34:04Z
17,556,666
7
2013-07-09T19:35:13Z
[ "python", "for-loop", "timer", "delay" ]
Is there any way to use a for loop as a timer? I've tried this: ``` a = 0 for i in range(1, 10000): a += 1 print "Hello World" ``` But for some reason, it immediately cuts to "Hello World." I thought that Python incremented every tick or 1/1000th of a second. If so, than 10000/1000 = 10, so that for loop should ...
The `range` function returns a list of numbers in Python 2.x (or an iterator, in Python 3.x) in the given range. It has nothing, nothing to do with time, or ticks as you incorrectly assumed. The `a += 1` statement will execute immediately and as many times as defined by the range - which will be very quick in a modern ...
Why does this work in the Python IDLE shell but not when I run it as a Python script from the command prompt?
17,557,168
4
2013-07-09T20:04:11Z
17,557,222
9
2013-07-09T20:07:16Z
[ "python", "python-3.x" ]
This works in the Python 3.3.2 Shell # Inside the Python 3.3.2 Shell ``` >>> import datetime >>> print(datetime.datetime.utcnow()) 2013-07-09 19:40:32.532341 ``` That's great! I then wrote a simple text file named "datetime.py" # Inside Datetime.py ``` #Date time import datetime print(datetime.datetime.utcnow()) #...
The problem is that file is recursively importing itself, instead of importing the built-in module `datetime`: **Demo:** ``` $ cat datetime.py import datetime print datetime.__file__ $ python datetime.py /home/monty/py/datetime.pyc /home/monty/py/datetime.pyc ``` This happens because the [module is searched](http://...
Edit pandas DataFrame using indexes
17,557,650
6
2013-07-09T20:31:16Z
17,557,760
8
2013-07-09T20:38:06Z
[ "python", "pandas" ]
Is there a general, efficient way to assign values to a subset of a DataFrame in pandas? I've got hundreds of rows and columns that I can access directly but I haven't managed to figure out how to edit their values without iterating through each row,col pair. For example: ``` In [1]: import pandas, numpy In [2]: arra...
Use [`loc`](http://pandas.pydata.org/pandas-docs/dev/indexing.html#selection-by-label) in an assignment expression (the `=` means it's not relevant whether it is a view or a copy!): ``` In [11]: df.loc[rows, columns] = 99 In [12]: df Out[12]: 0 1 2 3 4 5 6 7 8 9 A 0 99 2 3 99 5 6 99...
Python: invalid literal for int() with base 10: '808.666666666667'
17,557,870
10
2013-07-09T20:44:50Z
17,557,896
24
2013-07-09T20:46:32Z
[ "python" ]
I have a script that parses data from a csv file. The following line is giving me problems: ``` countData.append([timeStamp,int(my_csv[row][5])]) ``` It gives me the following error: ``` ValueError: invalid literal for int() with base 10: '808.666666666667' ``` The line of the csv file is as follows: ``` 2013-06-1...
From help on `int`: > int(x, base=10) -> int or long > > If x is **not a number** or if base is given, then x must be a string or > Unicode object representing an integer literal in the given base. So, `'808.666666666667'` is an invalid literal for `int` for any `base`, use: ``` >>> int(float('808.666666666667' )) 8...
Animated title in matplotlib
17,558,096
2
2013-07-09T21:00:53Z
17,562,747
7
2013-07-10T05:03:03Z
[ "python", "animation", "matplotlib" ]
I can't figure out how to get an animated title working on a FuncAnimation plot (that uses blit). Based on <http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/> and [Python/Matplotlib - Quickly Updating Text on Axes](http://stackoverflow.com/questions/6077017/python-matplotlib-quickly-updating-text-...
See [Animating matplotlib axes/ticks](http://stackoverflow.com/questions/6299943/animating-matplotlib-axes-ticks) and [python matplotlib blit to axes or sides of the figure?](http://stackoverflow.com/questions/14844223/python-matplotlib-blit-to-axes-or-sides-of-the-figure) So, the problem is that in the guts of `anima...
reordering of numpy arrays
17,558,388
5
2013-07-09T21:16:30Z
17,558,640
7
2013-07-09T21:32:18Z
[ "python", "numpy" ]
I want to reorder dimensions of my numpy array. The following piece of code works but it's too slow. ``` for i in range(image_size): for j in range(image_size): for k in range(3): new_im[k, i, j] = im[i, j, k] ``` After this, I vectorize the new\_im: ``` new_im_vec = new_im.reshape(image_size...
Check out [rollaxis](http://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html#numpy.rollaxis), a function which shifts the axes around, allowing you to reorder your array in a single command. If `im` has shape *i, j, k* ``` rollaxis(im, 2) ``` should return an array with shape *k, i, j*. After this, y...
How do I add custom field to Python log format string?
17,558,552
24
2013-07-09T21:26:35Z
17,558,757
10
2013-07-09T21:40:05Z
[ "python", "logging" ]
My current format string is: ``` formatter = logging.Formatter('%(asctime)s : %(message)s') ``` and I want to add a new field called app\_name and which will have a different value in each script that contains this formatter. ``` import logging formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s') ...
You need to pass the dict as a parameter to extra to do it that way. ``` logging.info('Log message', extra={'app_name': 'myapp'}) ``` Proof: ``` >>> import logging >>> logging.basicConfig(format="%(foo)s - %(message)s") >>> logging.warning('test', extra={'foo': 'bar'}) bar - test ``` Also, as a note, if you try to ...
How do I add custom field to Python log format string?
17,558,552
24
2013-07-09T21:26:35Z
17,558,764
33
2013-07-09T21:40:46Z
[ "python", "logging" ]
My current format string is: ``` formatter = logging.Formatter('%(asctime)s : %(message)s') ``` and I want to add a new field called app\_name and which will have a different value in each script that contains this formatter. ``` import logging formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s') ...
You could use a [LoggingAdapter](http://docs.python.org/2/library/logging.html#loggeradapter-objects) so you don't have to pass the extra info with every logging call: ``` import logging extra = {'app_name':'Super App'} logger = logging.getLogger(__name__) syslog = logging.StreamHandler() formatter = logging.Formatte...
Python printing function gets unexpected output at interpreter?
17,558,866
3
2013-07-09T21:47:34Z
17,558,878
7
2013-07-09T21:48:18Z
[ "python" ]
I have the following in a file named seta.py: ``` def print_name(): print "hello" ``` I am doing the following from the interpreter: ``` import seta ``` and then ``` seta.print_name ``` I would expect the output to be "hello" but it is as follows: ``` <function print_name at 0x7faffa1585f0> ``` What am i do...
To call a function you need to add `()`: ``` seta.print_name() ``` Otherwise it'll print the `str`/`repr` version of that function object. **Demo:** ``` def func(): print "Hello, World!" >>> func #Returns the repr version of function object <function func at 0xb743cb54> >>> repr(func) '<...
MATLAB twice as fast as Numpy
17,559,140
11
2013-07-09T22:07:33Z
17,559,754
42
2013-07-09T23:03:37Z
[ "python", "performance", "matlab", "numpy", "intel-mkl" ]
I am an engineering grad student currently making the transition from MATLAB to Python for the purposes of numerical simulation. I was under the impression that for basic array manipulation, Numpy would be as fast as MATLAB. However, it appears for two different programs I write that MATLAB is a little under twice as f...
That comparison ends up being apples to oranges due to caching, because it is more efficient to transfer or do some work on contiguous chunks of memory. This particular benchmark is memory bound, since in fact no computation is done, and thus the percentage of cache hits is key to achieve good performance. Matlab lays...
confidence and prediction intervals with StatsModels
17,559,408
10
2013-07-09T22:32:19Z
17,560,456
11
2013-07-10T00:20:48Z
[ "python", "statistics", "statsmodels" ]
I do this linear regression with StatsModels: ``` import numpy as np import statsmodels.api as sm from statsmodels.sandbox.regression.predstd import wls_prediction_std #measurements genre nmuestra = 100 x = np.linspace(0, 10, nmuestra) e = np.random.normal(size=nmuestra) y = 1 + 0.5*x + 2*e X = sm.add_constant(x) r...
`iv_l, iv_u` gives you the limits of the prediction interval for each point. see the first plot here <http://statsmodels.sourceforge.net/devel/examples/generated/example_ols.html> Prediction interval is the confidence interval for an observation and includes the estimate of the error. I think, confidence interval fo...
Pandas Dataframe Mask based on index
17,559,885
3
2013-07-09T23:17:48Z
17,559,953
7
2013-07-09T23:23:11Z
[ "python", "python-2.7", "pandas" ]
I have the following dataframe: ``` import pandas as pd index = pd.date_range('2013-1-1',periods=10,freq='15Min') data = pd.DataFrame(data=[1,2,3,4,5,6,7,8,9,0], columns=['value'], index=index) ``` How can I generate a mask based on the index value? I know I can do something like: ``` data['value'] > 3 Out[40]: 201...
You can mask using `indexer_between_time`: ``` In [11]: data.index.indexer_between_time(start='01:15', end='02:00') Out[11]: array([5, 6, 7, 8]) In [12]: data.iloc[data.index.indexer_between_time(start='1:15', end='02:00')] Out[12]: value 2013-01-01 01:15:00 6 2013-01-01 01:30:00 7 2013...
Python p-value from t-statistic
17,559,897
11
2013-07-09T23:19:27Z
17,604,216
11
2013-07-11T21:57:03Z
[ "python", "statistics" ]
I have some t-values and degrees of freedom and want to find the p-values from them (it's two-tailed). In the real world I would use a t-test table in the back of a Statistics textbook; how do I do the equivalent in Python? i.e. `t-lookup(5, 7) = 0.04156` or something like that (made-up numbers). I know in SciPy if ...
From <http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html> > As an exercise, we can calculate our ttest also directly without using > the provided function, which should give us the same answer, and so it > does: ``` tt = (sm-m)/np.sqrt(sv/float(n)) # t-statistic for mean pval = stats.t.sf(np.abs(tt), n-1)...
How to use TokenAuthentication for API in django-rest-framework
17,560,228
24
2013-07-09T23:53:24Z
17,569,377
27
2013-07-10T11:22:32Z
[ "python", "django", "django-authentication", "django-rest-framework" ]
I have a django project, using django-rest-framework to create api. Want to use token base authentication system so api call for (put, post, delete) will only execute for authorized user. I installed 'rest\_framework.authtoken' and created token for each users. So, now from django.contrib.auth.backends authenticate,...
> "how can I send the token with post request to my api" From the docs... For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example: ``` Authorization: Token 9944b09...
python: how to find consecutive pairs of letters by regex?
17,560,658
5
2013-07-10T00:43:01Z
17,560,731
10
2013-07-10T00:54:08Z
[ "python", "regex" ]
I want to find words that have consecutive letter pairs using regex. I know for just one consecutive pair like **zoo (oo), puzzle (zz), arrange (rr)**, it can be achieved by `'(\w){2}'`. But how about * two consecutive pairs: **committee (ttee)** * three consecutive pairs: **bookkeeper (ookkee)** edit: * `'(\w){2}'`...
Use [re.finditer](http://docs.python.org/2/library/re.html#re.finditer) ``` >>> [m.group() for m in re.finditer(r'((\w)\2)+', 'zoo')] ['oo'] >>> [m.group() for m in re.finditer(r'((\w)\2)+', 'arrange')] ['rr'] >>> [m.group() for m in re.finditer(r'((\w)\2)+', 'committee')] ['mm', 'ttee'] >>> [m.group() for m in re.fin...
Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?
17,561,212
16
2013-07-10T01:48:41Z
17,563,158
15
2013-07-10T05:40:14Z
[ "python", "ipython", "ipython-notebook" ]
I've started to use the IPython Notebook and am enjoying it. Sometimes, I write buggy code that takes massive memory requirements or has an infinite loop. I find the "interrupt kernel" option sluggish or unreliable, and sometimes I have to restart the kernel, losing everything in memory. I also sometimes write scripts...
I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment [here](http://lighthouseinthesky.blogspot.com/2011/09/review-ipython-notebooks.html)), which is the same thing that hitting CTRL+C w...
How to hide .pyc files when you enter `ls` in bash
17,561,874
20
2013-07-10T03:12:36Z
17,561,914
23
2013-07-10T03:17:20Z
[ "python", "linux", "ls", "pyc" ]
When I perform `ls` in bash, I always see too many `*.pyc` files. it bothers me so long. i search solutions on google but i can not find anything useful to solve my problem.
This way lies the dark side, but you could force `ls` to never show them by adding something like ``` alias ls='ls --hide="*.pyc"' ``` to your `.bashrc`. `ls` will reveal the hidden files if you use `-a` or `-A`. However, I would recommend just ignoring them in your head, or running this version of `ls` when you *re...
Confused about running Scrapy from within a Python script
17,564,305
6
2013-07-10T07:00:44Z
17,564,560
8
2013-07-10T07:16:02Z
[ "python", "web-scraping", "scrapy" ]
Following [document](http://doc.scrapy.org/en/0.16/topics/practices.html#run-scrapy-from-a-script), I can run scrapy from a Python script, but I can't get the scrapy result. This is my spider: ``` from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from items import DmozItem class Dmoz...
Terminal prints the result because the default log level is set to `DEBUG`. When you are running your spider from the script and call `log.start()`, the default log level is set to `INFO`. Just replace: ``` log.start() ``` with ``` log.start(loglevel=log.DEBUG) ``` UPD: To get the result as string, you can log e...
A list comprehension returns wrong result
17,564,787
3
2013-07-10T07:29:13Z
17,564,821
9
2013-07-10T07:31:01Z
[ "python", "list-comprehension" ]
I've been searching all over but wasn't able to fig this thing out. I'm from a Java background, if that helps, trying to learn python. ``` a = [ (i,j,k) for (i,j,k) in [ (i,j,k) for i in {-4,-2,1,2,5,0} for j in {-4,-2,1,2,5,0} for k in {-4,-2,1,2,5,0} if ...
In python, `&` is a bit operator. For your need, you should use `and`.
A list comprehension returns wrong result
17,564,787
3
2013-07-10T07:29:13Z
17,564,832
9
2013-07-10T07:31:31Z
[ "python", "list-comprehension" ]
I've been searching all over but wasn't able to fig this thing out. I'm from a Java background, if that helps, trying to learn python. ``` a = [ (i,j,k) for (i,j,k) in [ (i,j,k) for i in {-4,-2,1,2,5,0} for j in {-4,-2,1,2,5,0} for k in {-4,-2,1,2,5,0} if ...
You are using the wrong operator. You want [boolean `and`](http://docs.python.org/2/reference/expressions.html#boolean-operations); [`&` is a *bitwise* operator](http://docs.python.org/2/reference/expressions.html#binary-bitwise-operations): ``` [(i,j,k) for (i,j,k) in [(i,j,k) for i in {-4,-2,1,2,5,0} for j in {-4,-...
How to wait until only the first thread is finished in Python
17,564,804
11
2013-07-10T07:30:10Z
17,565,516
12
2013-07-10T08:11:36Z
[ "python", "multithreading" ]
The requirement is to start five threads, and wait only in the fastest thread. All five threads went to look for the same data 5 directions, and one is enough to continue the control flow. Actually, I need to wait for the first two threads to return, to verify against each other. But I guess if I know how to wait for ...
Use a queue: each thread when completed puts the result on the queue and then you just need to read the appropriate number of results and ignore the remainder: ``` #!python3.3 import queue # For Python 2.x use 'import Queue as queue' import threading, time, random def func(id, result_queue): print("Thread", id...
SQL alchemy case insensitive sort order
17,567,201
5
2013-07-10T09:35:02Z
17,567,525
8
2013-07-10T09:50:56Z
[ "python", "sqlite", "sqlalchemy" ]
Hi Im trying to achieve a ascending sort order for particular columns in a sqlite database using sql alchemy, the issue im having is that the column I want to sort on has upper and lower case data and thus the sort order doesn't work correctly. I then found out about func.lower and tried to incorporate this into the q...
You need to *reverse* the ordering of your functions: ``` session.query(ResultsDBHistory).order_by(asc(func.lower(history_sort_order_column))).all() ``` so lower *first*, then declare the ascending order. Alternatively, change the collation to `NOCASE`: ``` from sqlalchemy.sql import collate session.query(ResultsD...
Calculating power for Decimals in Python
17,567,720
4
2013-07-10T10:00:24Z
17,567,763
8
2013-07-10T10:02:28Z
[ "python" ]
I want to calculate power for `Decimal` in Python like: ``` from decimal import Decimal Decimal.power(2,2) ``` Above should return me as `Decimal('2)` How can I calculate power for `Decimals`? EDIT: This is what i did ``` y = Decimal('10')**(x-deci_x+Decimal(str(n))-Decimal('1')) ``` x,deci\_x are of decimal type...
You can calculate power using `**`: ``` 2**3 # yields 8 a = Decimal(2) a**2 # yields Decimal(4) ``` Following your update, seems okay for me: ``` >>> x = Decimal(2) >>> deci_x = Decimal(1) >>> n=4 >>> y = Decimal('10')**(x-deci_x+Decimal(str(n))-Decimal('1')) >>> y Decimal('10000') ```
Get objects with date greater than today or empty date
17,568,044
7
2013-07-10T10:15:40Z
17,568,110
8
2013-07-10T10:18:43Z
[ "python", "django", "django-models" ]
I need to select all model objects with date field greater than today date OR date field empty. I have following code: ``` @login_required def event_new(request, person_uuid=None): today = datetime.datetime.today() #valid_until may be empty profile = Profile.objects.filter(company=request.user.company, va...
Use [Q](https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects). ``` from django.db.models import Q @login_required def event_new(request, person_uuid=None): today = datetime.datetime.today() #valid_until may be empty profile = Profile.objects.filter(company=request.user.c...
How to make numpy.argmax return all occurences of the maximum?
17,568,612
22
2013-07-10T10:44:05Z
17,568,803
26
2013-07-10T10:53:39Z
[ "python", "numpy", "max" ]
I'm trying to find a function that returns *all* occurrences of the maximum in a given list. [`numpy.argmax`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html) however only returns the first occurrence that it finds. For instance: ``` from numpy import argmax list = [7, 6, 5, 7, 6, 7, 6, 6, 6, 4...
As documentation of `np.argmax` says: *"In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned."*, so you will need another strategy. One option you have is using `np.argwhere` in combination with `np.amax`: ``` >>> import numpy as np >>> list = [7, 6, 5,...
Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'
17,569,679
7
2013-07-10T11:38:20Z
17,570,045
7
2013-07-10T11:57:12Z
[ "python", "python-3.x" ]
I have a textfile, let's call it `goodlines.txt` and I want to load it and make a list that contains each line in the text file. I tried using the `split()` procedure like this: ``` >>> f = open('goodlines.txt') >>> mylist = f.splitlines() Traceback (most recent call last): File "<stdin>", line 1, in <module> Attri...
You are using `str` methods on an open file object. You can read the file as a list of lines by simply calling `list()` on the file object: ``` with open('goodlines.txt') as f: mylist = list(f) ``` This *does* include the newline characters. You can strip those in a list comprehension: ``` with open('goodlines....
Is it pythonic for a function to return chained values / set variables on itself?
17,572,852
22
2013-07-10T14:08:54Z
17,572,912
33
2013-07-10T14:11:26Z
[ "python" ]
Is it pythonic to return multiple values from a function in this way? ``` def f(): f.x = 1 f.y = 2 return f r = f() print r.x,r.y 1 2 ```
No. You are changing a global object that is not thread safe. More common is ``` return 1, 2 ``` or, if you want to have names, ``` return {'x': 1, 'y': 2} ```
Is it pythonic for a function to return chained values / set variables on itself?
17,572,852
22
2013-07-10T14:08:54Z
17,572,934
38
2013-07-10T14:12:12Z
[ "python" ]
Is it pythonic to return multiple values from a function in this way? ``` def f(): f.x = 1 f.y = 2 return f r = f() print r.x,r.y 1 2 ```
You're not "returning chained values", you're creating a function which returns itself, after setting variables on itself. The problem with this is that if you reinvoke the function (assuming it isn't just a constant function as shown in your example) is that every single appearance of the function (and understand tha...
Is it pythonic for a function to return chained values / set variables on itself?
17,572,852
22
2013-07-10T14:08:54Z
17,573,265
20
2013-07-10T14:26:42Z
[ "python" ]
Is it pythonic to return multiple values from a function in this way? ``` def f(): f.x = 1 f.y = 2 return f r = f() print r.x,r.y 1 2 ```
It's not pythonic, it is not even *reasonable* for any language that potentially supports such a construct. What you do is that you use the function's global state as a carrier of your output values. To return a value from a function you should use, well, a *return value*, not the called function. In your example you ...
Is it pythonic for a function to return chained values / set variables on itself?
17,572,852
22
2013-07-10T14:08:54Z
17,573,595
18
2013-07-10T14:39:44Z
[ "python" ]
Is it pythonic to return multiple values from a function in this way? ``` def f(): f.x = 1 f.y = 2 return f r = f() print r.x,r.y 1 2 ```
All of the advice given so far is good, but doesn't show much code, here they are, one by one. The most common answer was 'return a tuple', which would look like this ``` def f(): return 1, 2 x, y = f() ``` A related answer was 'return a `namedtuple`': ``` from collections import namedtuple Point = namedtuple...
Is it pythonic for a function to return chained values / set variables on itself?
17,572,852
22
2013-07-10T14:08:54Z
17,573,601
7
2013-07-10T14:39:57Z
[ "python" ]
Is it pythonic to return multiple values from a function in this way? ``` def f(): f.x = 1 f.y = 2 return f r = f() print r.x,r.y 1 2 ```
This is what's wrong: ``` >>> def f(a): ... f.x = a ... return f ... >>> r = f(1) >>> print r.x 1 >>> p = f(2) >>> print p.x 2 >>> print r.x 2 ``` It isn't expected that r is also changed! So not good practice to do it this way.
Count occurrences of certain words in pandas dataframe
17,573,814
5
2013-07-10T14:48:12Z
17,574,265
7
2013-07-10T15:08:46Z
[ "python", "pandas", "dataframe" ]
I want to count number of occurrences of certain words in a data frame. I know using "str.contains" ``` a = df2[df2['col1'].str.contains("sample")].groupby('col2').size() n = a.apply(lambda x: 1).sum() ``` Currently I'm using the above code. Is there a method to match regular expression and get the count of occurrenc...
The `str.contains` method accepts a regular expression: ``` Definition: df.words.str.contains(self, pat, case=True, flags=0, na=nan) Docstring: Check whether given pattern is contained in each string in the array Parameters ---------- pat : string Character sequence or regular expression case : boolean, default T...
Why is the python destructor being called?
17,574,106
5
2013-07-10T15:01:20Z
17,574,589
13
2013-07-10T15:21:14Z
[ "python" ]
When I type this into the interpreter, calling 'y' seems to invoke the destructor? ``` class SmartPhone: def __del__(self): print "destroyed" y = SmartPhone() y #prints destroyed, why is that? y #object is still there ``` Here is one run, output does not make sense to me. ``` C:\Users\z4>python Python ...
The output in question is replicated only in interactive shell. In interactive session, additional variable `_` exists, which refer to last value. Using [sys.getrefcount](http://docs.python.org/2/library/sys.html#sys.getrefcount) to inspect reference count: ``` >>> import sys >>> class SmartPhone: ... def __del_...
Storing and loading numpy arrays as files
17,574,976
6
2013-07-10T15:37:36Z
17,575,216
8
2013-07-10T15:47:24Z
[ "python", "arrays", "string", "serialization", "numpy" ]
In my program I'm working with various numpy arrays of varying sizes. I need to store them into XML files for later use. I did not write them to binary files so I have all my data in one place (the XML file) and not scattered through 200 files. So I tried to use numpy's array\_str() method to transform an array into a...
Numpy provides an easy way to store many arrays in a compressed file: ``` a = np.arange(10) b = np.arange(10) np.savez_compressed('file.npz', a=a, b=b) ``` You can even change the array names when saving, by doing for example: `np.savez_compressed('file.npz', newa=a, newb=b)`. To read the saved file use `np.load()`,...
Python class @property: use setter but evade getter?
17,576,009
22
2013-07-10T16:26:47Z
17,576,095
31
2013-07-10T16:31:26Z
[ "python", "class", "properties", "timing" ]
In python classes, the @property is a nice decorator that avoids using explicit setter and getter functions. However, it comes at a cost of an overhead 2-5 times that of a "classical" class function. In my case, this is quite OK in the case of setting a property, where the overhead is insignificant compared to the proc...
Don't use a `property` in this case. A `property` object is a data descriptor, which means that any access to `instance.var` will invoke that descriptor and Python will never look for an attribute on the instance itself. You have two options: use the [`.__setattr__()`](http://docs.python.org/2/reference/datamodel.html...
Python class @property: use setter but evade getter?
17,576,009
22
2013-07-10T16:26:47Z
35,033,689
7
2016-01-27T09:41:17Z
[ "python", "class", "properties", "timing" ]
In python classes, the @property is a nice decorator that avoids using explicit setter and getter functions. However, it comes at a cost of an overhead 2-5 times that of a "classical" class function. In my case, this is quite OK in the case of setting a property, where the overhead is insignificant compared to the proc...
`property` python docs: <https://docs.python.org/2/howto/descriptor.html#properties> ``` class MyClass(object): def __init__(self): self._var = None # only setter def var(self, newValue): self._var = newValue var = property(None, var) c = MyClass() c.var = 3 print('ok') print c.var ...
Python Requests - SSL error for client side cert
17,576,324
7
2013-07-10T16:45:04Z
17,604,076
14
2013-07-11T21:46:10Z
[ "python", "certificate", "python-requests" ]
I'm calling a REST API with requests in python and so far have been successful when I set `verify=False`. Now, I have to use client side cert that I need to import for authentication and I'm getting this error everytime I'm using the `cert (.pfx). cert.pfx` is password protected. ``` r = requests.post(url, params=pay...
I had this same problem. The `verify` parameter seems to refer to the server's certificate. You want the `cert` parameter to specify your client certificate. I had to use OpenSSL to convert to get a certificate PEM file and a key PEM file. ``` import requests cert_file_path = "cert.pem" key_file_path = "key.pem" url...
Do files get closed during an exception exit?
17,577,137
17
2013-07-10T17:29:50Z
17,577,236
18
2013-07-10T17:34:36Z
[ "python", "file" ]
Do open files (and other resources) get automatically closed when the script exits due to an exception? I'm wondering if I need to be closing my resources during my exception handling. \*\*EDIT: to be more specific, I am creating a simple log file in my script. I want to know if I need to be concerned about closing t...
No, they don't. Use `with` statement if you want your files to be closed even if an exception occurs. From the [docs](http://docs.python.org/2/reference/compound_stmts.html#grammar-token-with_stmt): > The `with` statement is used to wrap the execution of a block with > methods defined by a context manager. This allo...
Do files get closed during an exception exit?
17,577,137
17
2013-07-10T17:29:50Z
17,584,476
12
2013-07-11T03:17:37Z
[ "python", "file" ]
Do open files (and other resources) get automatically closed when the script exits due to an exception? I'm wondering if I need to be closing my resources during my exception handling. \*\*EDIT: to be more specific, I am creating a simple log file in my script. I want to know if I need to be concerned about closing t...
A fairly straightforward question. Two answers. One saying, “Yes.” The other saying, “No!” Both with significant upvotes. Who to believe? Let me attempt to clarify. --- Both answers have some truth to them, and it depends on what you mean by a file being closed. First, consider what is meant by closing ...
Creating a REST API for a Django application
17,577,177
23
2013-07-10T17:31:48Z
17,577,424
8
2013-07-10T17:45:18Z
[ "python", "django", "rest" ]
I was given an assignment where I have to create an application API (REST) using the Django technology. I only need to be able to read (GET) the entries from multiple models, join them, and return them using the JSON format (one or more objects). **The json schema and an example of an appropriate json file were already...
I've used Django REST framework, and in general like how it works. The autogenerated human-browsable API screens are quite handy too. In theory, it doesn't mandate any representation format; you define "serializers" that specify which fields and content to expose, and on which serial format. Still, some formats are ea...
Creating a REST API for a Django application
17,577,177
23
2013-07-10T17:31:48Z
17,580,488
16
2013-07-10T20:41:46Z
[ "python", "django", "rest" ]
I was given an assignment where I have to create an application API (REST) using the Django technology. I only need to be able to read (GET) the entries from multiple models, join them, and return them using the JSON format (one or more objects). **The json schema and an example of an appropriate json file were already...
## Using Tastypie: -- **models.py** ``` class User(Document): name = StringField() ``` **api.py** ``` from tastypie import authorization from tastypie_mongoengine import resources from project.models import * from tastypie.resources import * class UserResource(resources.MongoEngineResource): class Meta: qu...
Numpy, python: automatically expand dimensions of arrays when broadcasting
17,577,336
8
2013-07-10T17:40:19Z
17,577,679
8
2013-07-10T17:59:07Z
[ "python", "numpy", "multidimensional-array" ]
Consider the following exercise in Numpy array broadcasting. ``` import numpy as np v = np.array([[1.0, 2.0]]).T # column array A2 = np.random.randn(2,10) # 2D array A3 = np.random.randn(2,10,10) # 3D v * A2 # works great # causes error: v * A3 # error ``` I know the Numpy rules for broadcasting, and I'm familiar...
NumPy broadcasting adds additional axes on the left. So if you arrange your arrays so the shared axes are on the right and the broadcastable axes are on the left, then you can use broadcasting with no problem: ``` import numpy as np v = np.array([[1.0, 2.0]]) # shape (1, 2) A2 = np.random.randn(10,2) # shape (10, 2...
Numpy, python: automatically expand dimensions of arrays when broadcasting
17,577,336
8
2013-07-10T17:40:19Z
17,578,035
8
2013-07-10T18:19:08Z
[ "python", "numpy", "multidimensional-array" ]
Consider the following exercise in Numpy array broadcasting. ``` import numpy as np v = np.array([[1.0, 2.0]]).T # column array A2 = np.random.randn(2,10) # 2D array A3 = np.random.randn(2,10,10) # 3D v * A2 # works great # causes error: v * A3 # error ``` I know the Numpy rules for broadcasting, and I'm familiar...
It's ugly, but this will work: ``` (v.T * A3.T).T ``` If you don't give it any arguments, transposing reverses the shape tuple, so you can now rely on the broadcasting rules to do their magic. The last transpose returns everything to the right order.
Convert range(r) to list of strings of length 2 in python
17,577,797
2
2013-07-10T18:05:49Z
17,577,822
7
2013-07-10T18:07:27Z
[ "python", "string", "list", "range" ]
I just want to change a list (that I make using range(r)) to a list of strings, but if the length of the string is 1, tack a 0 on the front. I know how to turn the list into strings using ``` ranger= map(str,range(r)) ``` but I want to be able to also change the length of those strings. Input: ``` r = 12 ranger = r...
Use [`string formatting`](http://docs.python.org/2/library/string.html#formatspec) and list comprehension: ``` >>> lis = range(11) >>> ["{:02d}".format(x) for x in lis] ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10'] ``` or [`format`](http://docs.python.org/2/library/functions.html#format): ``` >>...
Pass percentiles to pandas agg function
17,578,115
5
2013-07-10T18:22:46Z
17,578,653
12
2013-07-10T18:51:19Z
[ "python", "numpy", "pandas" ]
I want to pass the numpy percentile() function through pandas' agg() function as I do below with various other numpy statistics functions. Right now I have a dataframe that looks like this: ``` AGGREGATE MY_COLUMN A 10 A 12 B 5 B 9 A 84 B 22 ``` And my co...
Perhaps not super efficient, but one way would be to create a function yourself: ``` def percentile(n): def percentile_(x): return np.percentile(x, n) percentile_.__name__ = 'percentile_%s' % n return percentile_ ``` Then include this in your `agg`: ``` In [11]: column.agg([np.sum, np.mean, np.std...
time.time vs. timeit.timeit
17,579,357
6
2013-07-10T19:31:25Z
17,579,466
16
2013-07-10T19:38:27Z
[ "python", "performance", "time", "python-3.x" ]
Sometimes, I like to time how long it takes parts of my code to run. I've checked a lot of online sites and have seen, at large, two main ways to do this. One is using `time.time` and the other is using `timeit.timeit`. So, I wrote a very simple script to compare the two: ``` from timeit import timeit from time impor...
`timeit` is more accurate, for three reasons: * it repeats the tests many times to eliminate the influence of other tasks on your machine, such as disk flushing and OS scheduling. * it disables the garbage collector to prevent that process from skewing the results by scheduling a collection run at an inopportune momen...
Changing the options of a OptionMenu when clicking a Button
17,580,218
6
2013-07-10T20:23:32Z
17,581,364
13
2013-07-10T21:39:44Z
[ "python", "python-2.7", "tkinter", "onclick", "optionmenu" ]
Say I have an option menu `network_select` that has a list of networks to connect to. ``` import Tkinter as tk choices = ('network one', 'network two', 'network three') var = tk.StringVar(root) network_select = tk.OptionMenu(root, var, *choices) ``` Now, when the user presses the refresh button, I want to update the...
I modified your script to demonstrate how to do this: ``` import Tkinter as tk root = tk.Tk() choices = ('network one', 'network two', 'network three') var = tk.StringVar(root) def refresh(): # Reset var and delete all old options var.set('') network_select['menu'].delete(0, 'end') # Insert list of ...
Assigning a value to single underscore _ in Python/IPython interpreter
17,580,289
65
2013-07-10T20:28:53Z
17,580,309
29
2013-07-10T20:30:06Z
[ "python", "function", "ipython", "interpreter", "read-eval-print-loop" ]
I created this function in Python 2.7 with `ipython`: ``` def _(v): return v ``` later if I call `_(somevalue)`, I get `_ = somevalue`. ``` in[3]: _(3) out[3]: 3 in[4]: print _ out[4]: 3 ``` The function has disappeared! If I call `_(4)` I get: ``` TypeError: 'int' object is not callable` ``` Why? What's wron...
`_` is a special variable in interpreter, it is always assigned to the result of previous expression. So, you shoudn't use it like that. BTW the problem seems to be related to IPython shell, because your code works fine in normal python shell: In normal python shell when you assign anything to the variable `_` then i...
Assigning a value to single underscore _ in Python/IPython interpreter
17,580,289
65
2013-07-10T20:28:53Z
17,580,311
102
2013-07-10T20:30:14Z
[ "python", "function", "ipython", "interpreter", "read-eval-print-loop" ]
I created this function in Python 2.7 with `ipython`: ``` def _(v): return v ``` later if I call `_(somevalue)`, I get `_ = somevalue`. ``` in[3]: _(3) out[3]: 3 in[4]: print _ out[4]: 3 ``` The function has disappeared! If I call `_(4)` I get: ``` TypeError: 'int' object is not callable` ``` Why? What's wron...
The Python interpreter assigns the last expression value to `_`. This behaviour is limited to the [REPL interpreter](http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) only, and is intended to assist in interactive coding sessions: ``` >>> import math >>> math.pow(3.0, 5) 243.0 >>> result = _ >>> resu...
Python selenium error when trying to launch firefox
17,580,730
11
2013-07-10T20:57:14Z
17,582,010
21
2013-07-10T22:24:59Z
[ "python", "selenium", "web-scraping" ]
I am getting an error when trying to open Firefox using Selenium in ipython notebook. I've looked around and have found similar errors but nothing that exactly matches the error I'm getting. Anybody know what the problem might be and how I fix it? I'm using Firefox 22. The code I typed in was as follows: ``` from sel...
Try specify your Firefox binary when initialize `Firefox()` ``` from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary binary = FirefoxBinary('path/to/binary') driver = webdriver.Firefox(firefox_binary=binary) ``` The default path FirefoxDriver looking for is at `%PROGRAMF...
Converting "yield from" statement to Python 2.7 code
17,581,332
36
2013-07-10T21:37:36Z
17,581,397
44
2013-07-10T21:41:55Z
[ "python" ]
I had a code below in Python 3.2 and I wanted to run it in Python 2.7. I did convert it (have put the code of `missing_elements` in both versions) but I am not sure if that is the most efficient way to do it. Basically what happens if there are two `yield from` calls like below in upper half and lower half in `missing_...
If you don't use the results of your yields,\* you can *always* turn this: ``` yield from foo: ``` … into this: ``` for bar in foo: yield bar ``` There might be a performance cost,\*\* but there is never a semantic difference. --- > Are the entries from the two halves (upper and lower) appended to each othe...
OpenCV cv2.fillPoly vs. cv2.fillConvexPoly: expected data type for array of polygon vertices?
17,582,849
5
2013-07-10T23:50:14Z
17,582,850
7
2013-07-10T23:50:14Z
[ "python", "opencv" ]
I have the following code: ``` import cv2 import numpy ar = numpy.zeros((10,10)) triangle = numpy.array([ [1,3], [4,8], [1,9] ], numpy.int32) ``` If I use cv2.fillConvexPoly like so: ``` cv2.fillConvexPoly(ar, triangle, 1) ``` then the results are as expected. If, however, I try: ``` cv2.fillPoly(ar, triangle, 1)...
`cv2.fillPoly` and `cv2.fillConvexPoly` use different data types for their point arrays, because `fillConvexPoly` draws only one polygon and `fillPoly` draws a (python) list of them. Thus, ``` cv2.fillConvexPoly(ar, triangle, 1) cv2.fillPoly(ar, [triangle], 1) ``` are the correct ways to call these two methods. If yo...
customize BeautifulSoup's prettify by tag
17,583,415
8
2013-07-11T01:00:39Z
18,428,836
9
2013-08-25T12:12:17Z
[ "python", "html", "beautifulsoup" ]
I was wondering if it would be possible to make it so that `prettify` did not create new lines on specific tags. I would like to make it so that `span` and `a` tags do not split up, for example: ``` doc="""<div><div><span>a</span><span>b</span> <a>link</a></div><a>link1</a><a>link2</a></div>""" from bs4 import Beaut...
I'm posting a quick hack while I don't find a better solution. I'm actually using it on my project to avoid breaking textareas and pre tags. Replace ['span', 'a'] with the tags on which you want to prevent indentation. ``` markup = """<div><div><span>a</span><span>b</span> <a>link</a></div><a>link1</a><a>link2</a></d...
What is the correct way to share package version with setup.py and the package?
17,583,443
28
2013-07-11T01:04:34Z
17,626,524
12
2013-07-13T02:54:54Z
[ "python", "setuptools", "distutils" ]
With `distutils`, `setuptools`, etc. a package version is specified in `setup.py`: ``` # file: setup.py ... setup( name='foobar', version='1.0.0', # other attributes ) ``` I would like to be able to access the same version number from within the package: ``` >>> import foobar >>> foobar.__version__ '1.0.0' ``` --- ...
I don't believe there's a canonical answer to this, but my method (either directly copied or slightly tweaked from what I've seen in various other places) is as follows: **Folder heirarchy (relevant files only):** ``` package_root/ |- main_package/ | |- __init__.py | `- _version.py `- setup.py ``` **`main_pa...
What is the correct way to share package version with setup.py and the package?
17,583,443
28
2013-07-11T01:04:34Z
17,638,236
37
2013-07-14T09:44:25Z
[ "python", "setuptools", "distutils" ]
With `distutils`, `setuptools`, etc. a package version is specified in `setup.py`: ``` # file: setup.py ... setup( name='foobar', version='1.0.0', # other attributes ) ``` I would like to be able to access the same version number from within the package: ``` >>> import foobar >>> foobar.__version__ '1.0.0' ``` --- ...
Set the version in `setup.py` only, and read your own version with [`pkg_resources`](http://pythonhosted.org/setuptools/pkg_resources.html), effectively querying the `setuptools` metadata: file: `setup.py` ``` setup( name='foobar', version='1.0.0', # other attributes ) ``` file: `__init__.py` ``` from p...
Attach generated CSV file to email and send with Django
17,584,550
13
2013-07-11T03:25:22Z
17,584,588
20
2013-07-11T03:29:58Z
[ "python", "django" ]
I need to generate a csv file based on the queryset result, attach the resulting file to an email as attachment and send. As you can see i need to iterate over the assigned\_leads and write it to a file so i thought yield would do the trick. Now when i run the code i receive the email with attachment with below message...
Is there a particular reason you're using an additional function at all? Just build your csv in memory - you can't avoid that if you're attaching it to email - and send that. ``` assigned_leads = lead.objects.filter(assigned_to__in=usercompany).distinct() csvfile = StringIO.StringIO() csvwriter = csv.writer(csvfile) f...
Getting rid of console output when freezing Python programs using Pyinstaller
17,584,698
6
2013-07-11T03:44:51Z
17,584,847
12
2013-07-11T04:04:27Z
[ "python", "pyinstaller" ]
I have recently written a fairly simple program for my grandfather using Python with GUI from Tkinter, and it works beautifully for what he will be using it for. However, there is, of course, the ugly console output window. I have successfully gotten rid of it by simply changing the extension of the file from .py to .p...
If you want to hide the console window, [here](http://www.pyinstaller.org/export/develop/project/doc/Manual.html) is the documentation: This is how you use the `--noconsole` option ``` python pyinstaller.py --noconsole yourscript.py ``` If you need help using pyinstaller to get to the point where you need to use the ...
What does hash do in python?
17,585,730
9
2013-07-11T05:32:50Z
17,586,126
22
2013-07-11T06:03:27Z
[ "python", "hash" ]
I saw an example of code that where `hash` function is applied to tuple. As a result it returns a negative integer. I wonder what does this function does. Google does not help. I found a page that explains how hash is calculated but it does not explain why we need this function.
[A hash is an fixed sized integer that identifies a particular value](http://en.wikipedia.org/wiki/Hash_function). Each value need to have it's own hash, so for the same value you will get the same hash even if it's not the same object. ``` >>> hash("Look at me!") 4343814758193556824 >>> f = "Look at me!" >>> hash(f) ...
How to solve pkg_resources.VersionConflict error during bin/python bootstrap.py -d
17,586,987
24
2013-07-11T07:01:32Z
17,588,080
26
2013-07-11T08:01:40Z
[ "python", "setuptools", "buildout" ]
I am tring to create a new plone environment using python plone-devstart.py tool. I got a bootstrap error. So i used a command bin/python bootstrap.py -d from my project directory. It(bin/python bootstrap.py -d command) worked fine before But now i got an error like ``` oomsys@oomsysmob-6:~/demobrun$ bin/python bootst...
You have the `distribute` fork of `setuptools` installed in your site packages, but your `bootstrap.py` is trying to install `buildout` 2.2.0, which uses the new *merged* `setuptools` 0.7 or newer egg. The `distribute` fork of `setuptools` was merged back into the `setuptools` project and the transition is causing som...
How to solve pkg_resources.VersionConflict error during bin/python bootstrap.py -d
17,586,987
24
2013-07-11T07:01:32Z
19,102,614
34
2013-09-30T19:53:10Z
[ "python", "setuptools", "buildout" ]
I am tring to create a new plone environment using python plone-devstart.py tool. I got a bootstrap error. So i used a command bin/python bootstrap.py -d from my project directory. It(bin/python bootstrap.py -d command) worked fine before But now i got an error like ``` oomsys@oomsysmob-6:~/demobrun$ bin/python bootst...
You could also try: ``` pip install --upgrade setuptools ``` as documented here <http://askubuntu.com/questions/318824/how-to-solve-pkg-resources-versionconflict-error-during-bin-python-bootstrap-py/322701#322701>
translate this sql into flask-sqlalchemy syntax
17,589,656
2
2013-07-11T09:21:24Z
17,594,864
7
2013-07-11T13:35:30Z
[ "python", "mysql", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I'm using Flask-sqlalchemy. Here is the mysql: ``` select u.id, count(i.id) as count from rss_urls as u left join rss_items as i on u.id = i.rss_urls_id group by u.id; ``` How should I translate that into sqlalchemy? Thanks a lot. ``` class RSS_urls(db.Model): id = db.Column(db.Integer, primary_key=True) ...
Assuming you have a model `RssUrl` and `RssItem`, with a relationship `RssUrl.rss_items`. ``` db.session.query(RssUrl.id, db.func.count(RssUrl.id).label("count") ).join(RssUrl.rss_items).group_by(RssUrl.id) ```
In pandas, can I deeply copy a DataFrame including its index and column?
17,591,104
12
2013-07-11T10:31:56Z
25,206,286
12
2014-08-08T14:52:55Z
[ "python", "pandas" ]
First, I create a DataFrame ``` In [61]: import pandas as pd In [62]: df = pd.DataFrame([[1], [2], [3]]) ``` Then, I deeply copy it by `copy` In [63]: df2 = df.copy(deep=True) Now the `DataFrame` are different. ``` In [64]: id(df), id(df2) Out[64]: (4385185040, 4385183312) ``` However, the `index` are still the s...
Latest version of Pandas does not have this issue anymore ``` import pandas as pd df = pd.DataFrame([[1], [2], [3]]) df2 = df.copy(deep=True) id(df), id(df2) Out[3]: (136575472, 127792400) id(df.index), id(df2.index) Out[4]: (145820144, 127657008) ```
Reversing a list in Python
17,592,033
2
2013-07-11T11:20:59Z
17,592,168
13
2013-07-11T11:27:23Z
[ "python", "list", "reverse" ]
``` def manualReverse(list): return list[::-1] def reverse(list): return list(reversed(list)) list = [2,3,5,7,9] print manualReverse(list) print reverse(list) ``` I just started learning `Python`. Can anyone help me with the below questions? 1.How come `list[::-1]` returns the `reversed` list? ...
`[::-1]` is equivalent to `[::1]`, but instead of going left to right, the negative makes it go right to left. With a negative step of one, this simply returns all the elements in the opposite order. The whole syntax is called the [Python Slice Notation](http://stackoverflow.com/questions/509211/the-python-slice-notati...
Python list([]) and []
17,599,175
9
2013-07-11T16:53:45Z
17,599,215
15
2013-07-11T16:55:47Z
[ "python", "arrays", "list" ]
``` from cs1graphics import * from math import sqrt numLinks = 50 restingLength = 20.0 totalSeparation = 630.0 elasticityConstant = 0.005 gravityConstant = 0.110 epsilon = 0.001 def combine(A,B,C=(0,0)): return (A[0] + B[0] + C[0], A[1] + B[1] + C[1]) def calcForce(A,B): dX = (B[0] - A[0]) dY = (B[1]...
`list(chain)` returns a shallow copy of `chain`, it is equivalent to `chain[:]`. If you want a shallow copy of the list then use `list()`, it also used sometimes to get all the values from an iterator. Difference between `y = list(x)` and `y = x`: --- **Shallow copy:** ``` >>> x = [1,2,3] >>> y = x #this s...
Installing MySQL-python on mac
17,599,830
22
2013-07-11T17:31:45Z
17,847,170
61
2013-07-25T00:44:33Z
[ "python", "osx", "python-2.7", "mysql-python" ]
I am using OSX 10.8 and PyCharm to work on a Python development project. I have installed MySQL-python for the mac using the instructions on the website <http://blog.infoentropy.com/MySQL-python_EnvironmentError_mysql_config_not_found> However, running the project gives me this error: ``` django.core.exceptions.Impr...
You should install MySQL through [Homebrew](http://brew.sh/) first, to get python-mysql work properly on OS X. ``` pip uninstall MySQL-python brew install mysql pip install MySQL-python ```
Dynamically choosing class to inherit from
17,599,850
25
2013-07-11T17:33:23Z
17,599,891
47
2013-07-11T17:35:25Z
[ "python", "class", "inheritance" ]
My Python knowledge is limited, I need some help on the following situation. Assume that I have two classes `A` and `B`, is it possible to do something like the following (conceptually) in Python: ``` import os if os.name == 'nt': class newClass(A): # class body else: class newClass(B): # class b...
You can use a [conditional expression](http://docs.python.org/2/reference/expressions.html#conditional-expressions): ``` class newClass(A if os.name == 'nt' else B): ... ```
Dynamically choosing class to inherit from
17,599,850
25
2013-07-11T17:33:23Z
17,599,906
11
2013-07-11T17:36:26Z
[ "python", "class", "inheritance" ]
My Python knowledge is limited, I need some help on the following situation. Assume that I have two classes `A` and `B`, is it possible to do something like the following (conceptually) in Python: ``` import os if os.name == 'nt': class newClass(A): # class body else: class newClass(B): # class b...
Yep, you can do exactly what you wrote. Though personally, I'd probably do it this way for cleanliness: ``` class _newClassNT(A): # class body class _newClassOther(B): # class body newClass = _newClassNT if os.name == 'nt' else _newClassOther ``` --- This assumes that you need to actually do different thin...
How to use linkedin API with python
17,600,244
5
2013-07-11T17:57:43Z
17,600,371
7
2013-07-11T18:05:19Z
[ "python", "api", "linkedin" ]
I tried so many methods, but none seem to work. Help me make a connection with linkedin using python. I have all the tokens. I have python 2.7.5. Please post a sample of basic code that establishes a connection and gets a user's name. Below, I have done character for character like the example said, but it doesn't wor...
Got it. For future reference you need to download the oauthlib from here <https://github.com/idan/oauthlib> here is the full functional code: ``` CONSUMER_KEY = '9pux1XcwXXXXXXXXXX' # This is api_key CONSUMER_SECRET = 'brtXoXEXXXXXXXXXXXXX' # This is secret_key USER_TOKEN = '27138ae8-XXXXXXXXXXXXXXXXXXXXXXXXXX...
How do I integrate two 1-D data arrays in Python?
17,602,076
4
2013-07-11T19:44:45Z
17,602,152
7
2013-07-11T19:48:52Z
[ "python", "arrays", "integration", "interpolation" ]
I have two tabulated data arrays, x and y, and I don't know the function that generated the data. I want to be able to evaluate the integral of the line produced by the data at any point along the x-axis. Rather than interpolating a piecewise function to the data and then attempting to integrate that, which I am havin...
[Scipy has some nice tools to perform numerical integration.](http://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html) For example, you can use `scipy.integrate.simps` to perform simpson's Rule, and you can pass it the following: > scipy.integrate.simps(y, x=None, dx=1, axis=-1, even='avg') > > Parameters :...
Can numpy einsum() perform outer addition?
17,602,796
5
2013-07-11T20:24:21Z
17,605,072
9
2013-07-11T23:11:44Z
[ "python", "arrays", "numpy" ]
In numpy, we can perform "outer addition" between two vectors `a` and `b` like this: ``` a=np.c_[1,2,3] b=np.c_[4,5,6] result=a+b.T # alternatively this can be a.T+b ``` Is it possible to use `einsum` to make the same calculation? Any other fast alternatives? How about if `a` equals `b`?
Another fast alternative to this operation is to use: ``` np.add.outer(a,b) ```
How to handle both `with open(...)` and `sys.stdout` nicely?
17,602,878
42
2013-07-11T20:29:59Z
17,603,000
36
2013-07-11T20:35:51Z
[ "python" ]
Often I need to output data either to file or, if file is not specified, to stdout. I use the following snippet: ``` if target: with open(target, 'w') as h: h.write(content) else: sys.stdout.write(content) ``` I would like to rewrite it and handle both targets uniformly. In ideal case it would be: `...
Just thinking outside of the box here, how about a custom `open()` method? ``` import sys import contextlib @contextlib.contextmanager def smart_open(filename=None): if filename and filename != '-': fh = open(filename, 'w') else: fh = sys.stdout try: yield fh finally: ...
How to handle both `with open(...)` and `sys.stdout` nicely?
17,602,878
42
2013-07-11T20:29:59Z
17,603,032
15
2013-07-11T20:37:29Z
[ "python" ]
Often I need to output data either to file or, if file is not specified, to stdout. I use the following snippet: ``` if target: with open(target, 'w') as h: h.write(content) else: sys.stdout.write(content) ``` I would like to rewrite it and handle both targets uniformly. In ideal case it would be: `...
Stick with your current code. It's simple and you can tell *exactly* what it's doing just by glancing at it. Another way would be with an inline `if`: ``` handle = open(target, 'w') if target else sys.stdout handle.write(content) if handle is not sys.stdout: handle.close() ``` But that isn't much shorter than w...
Defining a custom PyMC distribution
17,603,935
7
2013-07-11T21:34:33Z
17,604,972
9
2013-07-11T23:02:54Z
[ "python", "machine-learning", "pymc" ]
This is perhaps a silly question. I'm trying to fit data to a very strange PDF using MCMC evaluation in PyMC. For this example I just want to figure out how to fit to a normal distribution where I manually input the normal PDF. My code is: ``` data = []; for count in range(1000): data.append(random.gauss(-200,15)); ...
An easy way is to use the stochastic decorator: ``` import pymc as mc import numpy as np data = np.random.normal(-200,15,size=1000) mean = mc.Uniform('mean', lower=min(data), upper=max(data)) std_dev = mc.Uniform('std_dev', lower=0, upper=50) @mc.stochastic(observed=True) def custom_stochastic(value=data, mean=mean...
The fourth root of (12) or any other number in Python 3
17,604,354
2
2013-07-11T22:07:25Z
17,604,427
11
2013-07-11T22:12:36Z
[ "python", "math", "python-3.x", "nth-root" ]
I'm trying to make a simple code for power 12 to 4(12 \*\* 4) . I have the output num (20736) but when I want to figure returns (20736) to its original value (12). I don't know how to do that in Python .. in Real mathematics I do that by the math phrase {12؇} The question is how to make {12؇} in Python ?? I'm using ...
``` def f(num): return num**0.25 ``` or ``` import math def f(num): return math.sqrt(math.sqrt(num)) ```
python pandas rank by column
17,604,665
8
2013-07-11T22:31:49Z
17,604,753
13
2013-07-11T22:39:56Z
[ "python", "pandas", "rank" ]
``` s = pd.DataFrame([['2012','A',3],['2012','B',8],['2011','A',20],['2011','B',30]], columns=['Year','Manager','Return']) Out[1]: Year Manager Return 0 2012 A 3 1 2012 B 8 2 2011 A 20 3 2011 B 30 ``` I would like to create a rank on year. So ...
It sounds like you want to group by the `Year`, then rank the `Returns` in descending order: ``` import pandas as pd s = pd.DataFrame([['2012', 'A', 3], ['2012', 'B', 8], ['2011', 'A', 20], ['2011', 'B', 30]], columns=['Year', 'Manager', 'Return']) s['Rank'] = s.groupby(['Year'])['Return'].rank(ascend...
Python - Combine two dictionaries, concatenate string values?
17,604,837
5
2013-07-11T22:50:11Z
17,604,869
11
2013-07-11T22:52:59Z
[ "python", "dictionary" ]
Related: [Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?](http://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe?lq=1) I'd like to merge two string:string dictionaries, and concatenate the values. Above p...
Dict-comprehension: ``` >>> d = {'foo': 'bar', 'baz': 'bazbaz'} >>> d1 = {'foo': 'baz'} >>> keys = d.viewkeys() | d1.viewkeys() >>> {k : d.get(k, '') + d1.get(k, '') for k in keys} {'foo': 'barbaz', 'baz': 'bazbaz'} ``` For Python 2.6 and earlier: ``` >>> dict((k, d.get(k, '') + d1.get(k, '')) for k in keys) {'foo':...
Why does it take longer to import a function from a module than the entire module itself?
17,605,659
24
2013-07-12T00:16:58Z
17,605,685
11
2013-07-12T00:19:48Z
[ "python", "performance", "python-import", "python-internals" ]
Consider: ``` >>> timeit.timeit('from win32com.client import Dispatch', number=100000) 0.18883283882571789 >>> timeit.timeit('import win32com.client', number=100000) 0.1275979248277963 ``` It takes significantly longer to import only the Dispatch function rather than the entire module, which seems counter intuitive. ...
The entire module still has to be imported to get the name you want from it...You'll also find that the OS is caching the module so subsequent access to the `.pyc` file will be quicker.
Why does it take longer to import a function from a module than the entire module itself?
17,605,659
24
2013-07-12T00:16:58Z
17,605,700
32
2013-07-12T00:21:49Z
[ "python", "performance", "python-import", "python-internals" ]
Consider: ``` >>> timeit.timeit('from win32com.client import Dispatch', number=100000) 0.18883283882571789 >>> timeit.timeit('import win32com.client', number=100000) 0.1275979248277963 ``` It takes significantly longer to import only the Dispatch function rather than the entire module, which seems counter intuitive. ...
That's because: ``` from win32com.client import Dispatch ``` is equivalent to: ``` import win32com.client #import the whole module first Dispatch = win32com.client.Dispatch #assign the required attributes to global variables del win32com #remove the reference to module object ``` ...