Can’t fix pyparsing error

So, I’m in the middle of refactoring a project, and I’m separating out a bunch of parsing code. The code I’m concerned with is pyparsing.

When I run the full test suite in Django, I get errors about missing MessageMiddleware

My app is called abcapp. I am running Django 1.5b1 on Python 2.7. The same issue happens in the latest trunk release of django.

How to efficiently concatenate many arange calls in numpy?

I’d like to vectorize calls like numpy.arange(0, cnt_i) over a vector of cnt values and concatenate the results like this snippet:

How to get a window title and scan it every 100ms use python?

with python, I want to get a window title,a stock software window.

15 Best PyTorch Books

Deep Learning with PyTorch will make that journey engaging and fun. PyTorch is another deep learning library that's is actually a fork of Chainer(Deep learning library completely on python) with the capabilities of torch.

How to set QDockWidget initial (default) size in the app with no central widget (PyQt4)?

I have an app with a lot of QDockWidgets and without central widget. I want to set some of those QDockWidgets initial size (size at application’s start), but I don’t want to limit their min/max sizes.

Changing the Digit Color of QLCD Number

I want to change the background and digit color of QLCDNumber in Qt Designer and I am going to use that design(GUI) on my Python program.

TypeError: function() argument after * must be a sequence, not generator

While trying to write a tiny, obfuscated type checker, an unacceptable code pattern was discovered. However, it inconsistently fails to work properly. This is the code that was initally written to test it with.

Call Python code from LLVM JIT

I write a language lexer/parser/compiler in python, that should run in the LLVM JIT-VM (using llvm-py) later. The first two steps are quite straightforward for now, but (even if I didn’t start the compile-task yet) I see a problem, when my code wants to call Python-Code (in general), or interact with the Python lexer/parser/compiler (in special) respectively. My main concern is, that the code should be able to dynamically load additional code into the VM at runtime and thus it must trigger the whole lexer/parser/compiler-chain in Python from within the VM.

Can SO_REUSEPORT be used on Unix domain sockets?

Linux kernels >= 3.9 allow sharing of sockets between processes with in-kernel load-balancing by setting SO_REUSEPORT: http://lwn.net/Articles/542629/ How can this be used for sockets of type AF_UNIX?

Can anyone identify this encoding?

Im working on a program to interface with some hardware that is sending data that has been encoded and wrapped to send within a CDATA block in an XML document.

Can’t terminate a sudo process created with python, in Ubuntu 15.10

I just updated to Ubuntu 15.10 and suddenly in Python 2.7 I am not able to terminate a process I created when being root.

Formation of dictionary from list element

Hi I have list as follows which contain meta data from images as follows:

Get month by week, day and year

I want to know how you get the months by the giving day, week number and year.

Hello guys I have wanted for a long time to find out how to clear something like print(“example”) in python, but I cant seem to find anyway or figure anything out.

Is there a way to clear your printed text in python?

How do I find and remove white specks from an image using SciPy/NumPy?

I have a series of images which serve as my raw data which I am trying to prepare for publication. These images have a series of white specks randomly throughout which I would like to replace with the average of some surrounding pixels.

How do I make ipython aware of changes made to a selfwritten module?

When trying a selfwritten module, it is likely to end with errors at the first few times.

How to create a CSV file if it does not exist and then only append to it Python

Hello I want to know how to create a file if it does not exist in direcotry. I want only to append data.

How to force my whole package to use a __future__ directive?

How to force my whole package to use a __future__ directive?

How to make python’s argparse generate Non-English text?

The argparse module “automatically generates help and usage messages”. I can give Non-English names to the arguments and provide Non-English help texts; but the help output then becomes a mixture of at least two languages, because terms like usage, positional arguments, optional arguments and show this help message and exit are automatically generated in English.

Index 2D numpy array by a 2D array of indices without loops

I am looking for a vectorized way to index a numpy.array by numpy.array of indices.

Legend transparency, when using secondary axis

The legend of the plot of a secondary axis somehow is transparent to the plot of the other axis. A minimal example to reproduce the problem:

Overcoming MemoryError / Slow Runtime in Ashton String task

In the Ashton String task, the goal is to

Pyspark Invalid Input Exception try except error

I am trying to read the last 4 months of data from s3 using pyspark and process the data but am receiving the following exception.

Slice a Pandas dataframe by an array of indices and column names

I’m looking to replicate the behavior of a numpy array with a pandas dataframe. I want to pass an array of indices and column names and get a list of objects that are found in the corresponding index and column name.

Which is the best way to log user actions in flask views?

I would like to log user actions whenever user logs in/out and adds, edits, deletes objects in my site models in flask. Which is the best way to do this? Also I would like to show the old data and the new modified data, which happens using wtfforms. I am using flask and Flask-SQLAlchemy. I want something similar to what Django framework offers in the ‘History‘ hlink for the associated objects.

While-loop with if-statement faster than while-loop

I am doing some testing regarding the speed of if-statements in loops and their effect on speed. Something I found was that consistently, the if-statement improved performance. My code:

Why does overriding __contains__ break OrderedDict.keys?

I’m subclasssing OrderedDict (Cpython, 2.7.3) to represent a datafile. __getitem__ pulls a field out of the datafile and sets it on the current instance similar to the code I’ve posted below. now I would like to override __contains__ to return True if the field is in the dictionary or in the file on the disk since it can be read either way. However, this seems to break OrderedDict‘s ability to inspect it’s keys.

pip install error: “Unknown archive format: .whl”

I’m new to virtualenv (on windows). I’m trying to use pip (1.5) install a local wheel file, but it is failing.

pycurl equivalent of “curl –data-binary”

I’d like to know the equivalent of this curl command in pycurl:

python argparse – pass values WITHOUT command line

I think I’m not understanding something basic about python‘s argparse. I am trying to use the Google YouTube API for python script, but I am not understanding how to pass values to the script without using the command line.

python comprehension with multiple ‘for’ clauses and single ‘if’

Imagine a discrete x,y,z space : I am trying to create an iterator which will return all points which lie within a sphere of some radial distance from a point.

Scheduling thousands of one-off (non-reoccuring) tasks for near-simultaneous execution via Django-celery

Some context: I’m building a Django App that allows a user to pre-save an action, and schedule the exact date/time in the future they want said action to execute. E.g, scheduling a post to be programmatically pushed to ones Facebook wall next week at 5:30am.

Why does overriding __contains__ break OrderedDict.keys?

I’m subclasssing OrderedDict (Cpython, 2.7.3) to represent a datafile. __getitem__ pulls a field out of the datafile and sets it on the current instance similar to the code I’ve posted below. now I would like to override __contains__ to return True if the field is in the dictionary or in the file on the disk since it can be read either way. However, this seems to break OrderedDict‘s ability to inspect it’s keys.

Add rate of change to Pandas DataFrame

I have the following Pandas DataFrame

Disable SSL certificate validation in Python

I’m writing a script that connects to a bunch of URLs over HTTPS, downloads their SSL certificate and extracts the CN. Everything works except when I stumble on a site with an invalid SSL certificate. I absolutely do not care if the certificate is valid or not. I just want the CN but Python stubbornly refuses to extract the certificate information if the certificate is not validated. Is there any way to get around this profoundly stupid behavior? Oh, I’m using the built-in socket and ssl libraries only. I don’t want to use third-party libraries like M2Crypto or pyOpenSSL because I’m trying to keep the script as portable as possible.

Does calling random.normal on an array of values add noise?

I saw this pattern in someone’s code

How can I use a static method as a default parameter for the strategy design pattern?

I want to make a class that uses a strategy design pattern similar to this:

How to add header files in setup.py so dependencies are observed when building the extensions?

The question seems long, but it all comes down to how I can add header files to specific extension specification.

How to get properties of picked object in mplot3d (matplotlib + python)?

I plot a series of points using mplo3d

How to handle multi-page images in PythonMagick?

I want to convert some multi-pages .tif or .pdf files to individual .png images. From command line (using ImageMagick) I just do:

How to seat everyone according to preferences?

This problem is from CodeEval problem 118

Lists are the same but not considered equal?

novice at Python encountering a problem testing for equality. I have a list of lists, states[]; each state contains x, in this specific case x=3, Boolean values. In my program, I generate a list of Boolean values, the first three of which correspond to a state[i]. I loop through the list of states testing for equality (one of them is certainly correct as all possible boolean permutations are in states, but equality is never detected. No clue why, here is some code I modified to test it:

Regex, select closest match

Assume the following word sequence

Summation of only consecutive values in a python array

I am new on python (and even programing!), so I will try to be as clear as I can to explain my question. For you guys it could be easy, but I have not found a satisfactory result on this yet.

Why doesn’t cv2 dilate actually affect my image?

So, I’m generating a binary (well, really gray scale, 8bit, used as binary) image with python and opencv2, writing a small number of polygons to the image, and then dilating the image using a kernel. However, my source and destination image always end up the same, no matter what kernel I use. Any thoughts?

uwsgi + nginx + flask: upstream prematurely closed

I created an endpoint on my flask which generates a spreadsheet from a database query (remote db) and then sends it as a download in the browser. Flask doesn’t throw any errors. Uwsgi doesn’t complain.

Behavior of “round” function in Python

Could anyone explain me this pice of code

Cannot allocate 1.6 GB in Python

This code produces a MemoryError

Efficiently computing element wise product of transition matrices (m*m) * (n*n) to give (mn*mn) matrix

Consider input matrices X and Y of shapes (m,m) and (n,n) respectively. As an output we need to give a (mn,mn) shape matrix such that it multiplies corresponding entries in the two matrices.

Error : no viable alternative at input ‘for’ Python

I have strange problem, when i am using Netbeans IDE , this line

How can I change name of arbitrary columns in pandas df using lambda function?

Is there any way to change some column names in pandas dataframe using lambda, but not all? For example, suppose that this data frame has columns whose name are osx, centos, ubunto, windows. In this data frame, I want to replace all column names with that column name appended by x, so in this case, I can rename the column name by

How come Python does not include a function to load a pickle from a file name?

I often include this, or something close to it, in Python scripts and IPython notebooks.

How to read complete file with bitstring

I want to read as many 24 bit chunks as possible from a file.How can I do this using bitstrings’ ConstBitStreamwhen I don’t now how many chunks there are?

How to store environment variables in a Python Flask app?

I have a Python Flask app that accesses the Github API. For this I need to store an access token. What is the common practice to store that data and how do I access that inside my app?

Matching Features with ORB python opencv

hi im working in Matching Features with ORB python opencv but when i run this code i get this error

Round a Python list of numbers and maintain their sum

I have a list or an array of decimal numbers in Python. I need to round them to the nearest 2 decimal places as these are monetary amounts. But, I need the overall sum to be maintained, i.e. the sum of the original array rounded to 2 decimal places must be equal to the sum of the rounded elements of the array.

Subtracting numpy arrays of different shape efficiently

Using the excellent broadcasting rules of numpy you can subtract a shape (3,) array v from a shape (5,3) array X with

Use sсikit-learn TfIdf with gensim LDA

I’ve used various versions of TFIDF in scikit learn to model some text data.

Using Flask-Security to authenticate REST API

I am using Flask-Security to build a web app that has a public REST API. I am trying to figure out how to add user registration and login using REST calls only.

Why python 2.7 on Windows need a space before unicode character when print?

I use cmd Windows, chcp 65001, this is my code

tweepy stops after a few hours

I use tweepy for streaming some tweet. This is my procedure

what does the error “no exception supplied” mean?

My Django app is currently throwing this error on one of my pages, does anyone know what it eans? I would supply more detail but I don’t know what this error means so I’m not sure what the relevant files are and Django apps are rather large in the amount of code spread around so I’ll post some code once I can get an idea of what this means. Thanks in advance for any help.

Django reportlab latin2 encoding

is there any option to convert latin2 letters in a proper way? I need polish letter to my school project. Here is some code how I generate pdf

SublimeLinter not obeying “pep8_ignore” settings

I am using Sublime Linter and cannot get PEP 8 (W191) to go away with the following settings.

plt.figure() vs subplots in Matplotlib

In Matplotlib a lot of examples come in the form ax = subplot(111) and then functions are applied on ax, like ax.xaxis.set_major_formatter(FuncFormatter(myfunc))

sqlalchemy FULL OUTER JOIN

How to implement FULL OUTER JOIN in sqlalchemy on orm level.

Can only iterate once through csv reader

So I basically have an extremely long list of strings, and a CSV file that contains a column of strings and a column of numbers. I need to loop through the extremely long list of strings, and for each one, loop through the rows of the CSV file checking each string in the first column of the CSV to see if it occurs in my string, and if it does, add the number in the other column to something.

Check if value is between pair of values in a tuple?

Is there an efficient way (nice syntax) to check if a value is between two values contained in a tuple?

Django 1.6 and Celery 3.0 memory leaks

After upgrading Django to 1.6, my celery worker is eating up RAM.Seems that the memory allocated for the workers isn’t released and grows after every task.

Flask – nested rest api – use something other than methodview or have I made a bad design?

Just starting off with Flask, following along at http://flask.pocoo.org/docs/views/

Multiline statements using Python doctest

Is it possible to work with multiline statements using python doctest?

Passing numpy array to Cython

I am learning Cython. I have problem with passing numpy arrays to Cython and don’t really understand what is going on. Could you help me?

Python : IndexError: tuple index out of range

In python i have this code

Python unable to find Elasticsearch

I am new to python and I am trying to experience with python and elasticsearch.

Using eventlet to manage socketio in Flask

I am trying to set up a small server to handle HTTP and socketio requests — I don’t have much experience setting up servers, but right now apache2 serves the http just fine. The socketio transactions, however, keep failing with error code 400 (bad request), and I see some strange errors in the server logs. Sometimes I see an engineio error and the server responds w/ a ‘bad request’ and code 400, but always it tells me the eventlet server needs to be started

Vectorized spherical bessel functions in python?

I noticed that scipy.special Bessel functions of order n and argument x jv(n,x) are vectorized in x

Writing a csv temporary file using tempfile

So I’m writing a test for this class (edited to be more clear)

Yet Another ‘Connection reset by peer’ Error

I’m creating a server/client application in python using the socket module and for whatever reason my server keeps ending the connection. The weird part is this works in Windows perfectly but not Linux. I’ve looked all over the place for a possible solution but none of them worked. Below is a sanitized version of the code which exploits the bug, however, with a higher success rate. Normally it never works. Hopefully this is still enough information

django rest framework file upload with nested writable serializers

django rest framework file upload with nested writable serializers

numpy: How to join arrays? ( to get the union of several ranges)

I use Python with numpy.

pickle/zodb: how to handle moving .py files with class definitions?

I’m using ZODB which, as I understand it, uses pickle to store class instances. I’m doing a bit of refactoring where I want to split my models.py file into several files. However, if I do this, I don’t think pickle will be able to find the class definitions, and thus won’t be able to load the objects that I already have stored in the database. What’s the best way to handle this problem?

relation “account_emailaddress” does not exist – django error

I am following this tutorial to integrate social media login to my django project – http://www.sarahhagstrom.com/2013/09/the-missing-django-allauth-tutorial/ However after completing all the steps, when I try to login using facebook, I get this error

“Standard” way of creating config file suitable for Python and Java together

My application was 100% developed in pure Python. I found very useful and easy to create a config file with .py extension and than simply load it in every code.

Correct usage of os.path and os.join

I’m trying to write a handler that acts on files within various subdirectories, but while my script can see these files, it cannot do anything with them because it fails to assemble their paths.

Count bitmasks, enumerate 0s

I had the following question in an interview and I believe I gave a working implementation but I was wondering if there was a better implementation that was quicker, or just a trick I missed.

Does scipy.integrate.ode.set_solout work?

The scipy.integrate.ode interface to integration routines provides a method for stopping the integration if a constraint is violated at any step, set_solout. However, I cannot get this method to work, even in the simplest examples

How to check whether screen is off in Mac/Python?

How do I check whether the screen is off due to the Energy Saver settings in System Preferences under Mac/Python?

How to generate a json file in python from nested array/dictionary/object

I need to generate a json file like:

How to get rid of maximum recursion depth error or better solve this?

Problem: We have a square grid of 5 rows and 4 columns. We need to use these numbers to fill the grid; 1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,35,36,40. We need to fill the grid in such a way that every horizontal and vertical neighbors should divide other without remainder. For example, 12 and 3 can be neighbors because 12 % 3 == 0, but 5 and 12 can’t. Grid 2×2 is given to be 10.

How to read columns of varying length from a text file in NumPy using genfromtxt()?

I have hundreds of text files like these, with each column separated by three spaces. The data is for a year: 12 months and 31 days for each month.

Integrating Alembic with SQLAlchemy

I’m looking at a way to integrate Alembic with SQLAlchemy. What I need is a way so that Alembic detects any changes I make in models.py automatically and updates it in the MySQL database when I run alembic revision -m "<message_here>" and alembic upgrade head.

Making a countdown timer with Python and Tkinter?

I want to set a label in Tkinter using my countdown timer function. Right now all it does is set the lable to “10” once 10 is reached and I don’t really understand why. Also, even if I have the timer print to a terminal instead the “Time’s up!” bit never prints.

Microsecond accurate timestamp in python?

Is there a way to maintain microsecond accuracy when converting a Python datetime to a timestamp?

Mocking Django Model and save()

I have the following scenario:

Numpy Routine(s) to create a regular grid inside a 2d array

I am trying to write a function that would create a regular grid of 5 pixels by 5 pixels inside a 2d array. I was hoping some combination of numpy.arange and numpy.repeat might do it, but so far I haven’t had any luck because numpy.repeat will just repeat along the same row.

PNG options to produce smaller file size when using savefig

I am using matplotlib to produce a plot which I then save to a PNG file using matplotlib.pyplot.savefig.

Python 2 newline tokens in tokenize module

I am using the tokenize module in Python and wonder why there are 2 different newline tokens

Python – “IOError: [Errno 0] Error”. What is Triggering This Error In My Code?

Python/programming newbie here.

SQLAlchemy eating RAM

I’m trying to import some XML data into my MySQL database after processing it with Python. To keep things simple, I’m doing it all from one script that uses SQLAlchemy to access my database.

Split DatetimeIndex into date and time MultiIndex conveniently in Pandas

So let’s say I have DatetimeIndex:ed data like this (there would be several days of course)

Using the python MySQLDB SScursor with nested queries

The typical MySQLdb library query can use a lot of memory and perform poorly in Python, when a large result set is generated.

What python code generates all possible groupings (trees) for binary operators

As explained in several SO questions, and more abstractly at mathworld, the sequence of Catalan numbers happens to correspond to the number of parenthetical groupings that can be generated for any given number of operators. But I haven’t found an algorithm to generate all these groupings.

Why is skimage.transform.rotate significantly slower than PIL’s Image.rotate?

I’m in the process of converting some PIL-based code over to NumPy, but I’ve found that the skimage.transform.rotate function is significantly slower than PIL’s Image.rotate.

image_to_string doesn’t work in Mac

I’m trying to follow this example of pytesser (link) in a Mac Maverick.

python bug with __le__, __ge__?

Is it me or python that is confused with the following code ? I would expect __le__ to be called by a <= ab, not __ge__:

python ctypes structure wrong byte size

So I’m trying to figure out why the size of my ctypes.Structure is not what it should be. My code is the following, theres also the calculation of what the size should be afaik.

scipy sparse matrices as an input for petsc4py

I can’t seem to find a way how to efficiently load scipy sparse matrices, e.g. csr_matrix, into a petsc4py matrix, e.g. PETSc.Mat().createAIJ. I found this thread, but I’m not able to apply it.

Catch empty list with colander

I’m using colander to validate (and deserialize json data) input to some web services. I would like to add a rule to a colander schema to catch an empty list, but I can not figure out how to do it.

Error because of Theano and NumPy variable types

I am writing this code using numpy 1.9 and the latest version of Theano but I get an error which I can’t fix. I doubt it could be the way I declare variable types but I can’t work it around. I appreciate your suggestions. I want to product a matrix with a vector and sum it with a bias.

GTK Label wrapping in a dialog

I’m trying to create a non-resizable dialog with a label in it. This label has a lot of text, so I want it to wrap without making the dialog ridiculously wide.

How can i write my custom link extractor in scrapy python

I want to write my custom scrapy link extractor for extracting links. The scrapy documentation says it has two built-in extractors.

How is this sorting code working?

How is this sorting code working? I cannot understand how the values returned by the iterator are being used to sort the list?

How to compare two timezones in python?

These two timezones have different names but represent the same thing, however

How to force Google App Engine [python] to use SSL (https)?

I write a web app on Google App Engine using Python.

How to push the for-loop down to numpy

I have the following piece of code doing exactly what i want (it is part of a kriging method). But the problem is that it goes too slow, and i wish to know if there is any option to push the for-loop down to numpy? If i push out the numpy.sum, and use the axis argument there, it speeds up a little bit, but apparently that is not the bottleneck. Any ideas on how i can push down the forloop to numpy to speed it up, or other ways to speed it up?)

How to speed up an already cached pip install?

I frequently have to re-create virtual environments from a requirements.txt and I am already using $PIP_DOWNLOAD_CACHE. It still takes a lot of time and I noticed the following

Latent Semantic Analysis in Python discrepancy

I’m trying to follow the Wikipedia Article on latent semantic indexing in Python using the following code:

Most efficient way of finding the next element in a tuple

I’ve got a system in which I often (but not constantly) have to find the next item in a tuple. I’m currently doing this like so:

Python – making copies of a file

I have a file that I want copied into a directory multiple times. It could be 100, it could be 1000. That’s a variable.

Selecting Element followed by text with Selenium WebDriver

I am using Selenium WebDriver and the Python bindings to automate some monotonous WordPress tasks, and it has been pretty straightforward up until this point. I am trying to select a checkbox, but the only way that I can identify it is by the text following it. Here is the relevant portion of HTML

indexing and finding values in list of namedtuples

I have a namedtuple like the following,

python – how to get the data from an plt.imshow()?

I have the following code

shell scripting checking python version

I have the following shell script to query the python version. It gives me an error stating "Integer expression expected" on the if-statement.

Get status text after failed http-request

Is there any chance to get additional status information from my respose object, if a request fails? At this point, I’m able to get the status code, but in addition, I need the status information text (which describes the error). If you’re using jQuery ajax, you could get this text from jqXHR’s responseText-attribute.

Adding external Ids to Partners in OpenERP withouth a new module

My Question is a bit complex and iam new to OpenERP. I have an external database and an OpenERP. the external one isn’t PostgreSQL.MY job is that I need to synchronize the partners in the two databases.External one being the more important. This means that if the external one’s data change so does the OpenERp’s, but if OpenERP’s data changes nothing changes onthe external one.

Calculating Point Density using Python

I have a list of X and Y coordinates from geodata of a specific part of the world. I want to assign each coordinate, a weight, based upon where it lies in the graph.

Complex query with Django (posts from all friends)

I’m new to Python and Django, so please be patient with me. I have the following models

Deleting variables in Python standard libraries

I’ve been reading some of the code in a standard threading library ( Python 2.6 ) and there was a piece of code which made me wonder. It can be shorten to the following structure ( compare to __bootstrap_inner method in threading.py )

Django cross table model structure

I have a System model, and an Interface model. An Interface is the combination between two systems. Before, this interface was represented as an Excel sheet (cross table). Now I’d like to store it in a database.

Error binding parameter 0: probably unsupported type

I can’t seem to figure out what is wrong with my code, but I keep getting the:

Generate a pdf with python

I’m trying to develop a small script that generate a complete new pdf, mainly text and tables, file as result.I’m searching for the best way to do it.

Generate functions without closures in python

right now I’m using closures to generate functions like in this simplified example

Hiding major tick labels while showing minor tick labels in matplotlib

I would like to hide the major tick labels on my x-axis while retaining just its minor labels. The idea is that my dates are displayed in between the major ticks instead of on them by default. I have seen a few other answers to similar questions as this one and tried using their way of hiding the major ticks however I am not having much luck getting it working at all

How do I get the modern style matplotlib plots often seen in iPython Notebook examples?

Take this page, for example, a sample of which is posted below:

How do I load specific rows from a .txt file in Python?

Say I have a .txt file with many rows and columns of data and a list containing integer values. How would I load the row numbers in the text file which match the integers in the list?

How do I use python variable in a javascript?

I’ve been on a prowl looking for a way to access a non visible text field using selenium’s webdriver. The only way i got it to work is using

How does the list comprehension to flatten a python list work?

I recently looked for a way to flatten a nested python list, like this: [[1,2,3],[4,5,6]], into this: [1,2,3,4,5,6].

How to cancel interpreter command in emacs python-mode

If I mistype a command in the python intepreter, sometimes I just see .... For example if I type help(random.unif and press enter I cannot enter a new command. I have to exit emacs and start python and the interpreter again. Is there way to correct this?

How to disable hostname checking in requests python

I’m using Requests to connect to a RESTful API. The server I would like to reach use ssl with self-singed certificate.

How to fix paths to solve Homebrew doctor warnings

Another newbie query. I’ve been struggling to install matplotlib for a Python project so reading around suggested Homebrew was a solid solution for package management and dependencies.

How to simply have python print “\xaa\xbb\xcc\xdd” as 0xddccbbaa?

I believe I’m misunderstanding something that should probably be simple. I’m trying to accept arguments passed to a python script. The type of argument I’m expecting is somewhere along the lines of "\xaa\xbb\xcc\xdd", and it keeps converting it to binary(i think?) instead of actually allowing me to print it out just how it was passed.

OpenCV Perspective Transform giving unexpected result

I am trying to transform from a trapezoid (in the first image) to a rectangle (in the second image), but getting a strange result (in the third image).

Paramiko: how to ensure data is received between commands

I’m using Paramiko to issue a number of commands and collect results for further analysis. Every once in a while the results from the first command are note fully returned in time and end up in the output for the second command.

Pull Tag Value using BeautifulSoup

Can someone direct me as how to pull the value of a tag using BeautifulSoup? I read the documentation but had a hard time navigating through it.

Python data structure for efficient add, remove, and random.choice

I’m looking for a built-in Python data structure that can add a new element, remove an existing element, and choose a random element, all in better than O(n) time.

Python lambda with regex

When using re.sub() part of re for python, a function can be used for sub if I am not mistaken. To my knowledge it passes in the match to whatever function is passed for example

SQLAlchemy subquery in from clause without join

i need a little help.I have following query and i’m, curious about how to represent it in terms of sqlalchemy.orm. Currently i’m executing it by session.execute. Its not critical for me, but i’m just curious. The thing that i’m actually don’t know is how to put subquery in FROM clause (nested view) without doing any join.

Understanding an issue with the namedtuple typename and pickle in Python

Earlier today I was having trouble trying to pickle a namedtuple instance. As a sanity check, I tried running some code that was posted in another answer. Here it is, simplified a little more

Use lxml to parse text file with bad header in Python

I would like to parse text files (stored locally) with lxml’s etree. But all of my files (thousands) have headers, such as:

ValueError: unsupported format character ‘{‘ (0x7b) in defining dictionary

I’m writing some code for web development using Google Python Appengine. In my code I have to concatenate strings using % and dictionary Here’s the code I’ve written.

manage.py collectstatic command not found, Django 1.5.1

I am very new to python and when I run the $ python manage.py collectstatic command, It returns ‘unknown command: ‘collectstatic”

matplotlib contour input array order

Question: what order does the contour from matplotlib expect for the input 2D array? Elaborate: Matplotlib contour documentation says that the routine call is

numpy: using operator – with arrays containing None

I have a list of numbers which I put into a numpy array:

python dateutil unicode warning

im parsing some tweet’s data from Twitter API using sixohsix library. Im trying to convert the date of the tweet to my locale:

Groupby given percentiles of the values of the chosen DataFrame column

Imagine that I have a DataFrame with columns that contain only real values.

Running Jar files from Python

I want to make a program that can execute jar files and print whatever the jar file is doing in my python program but without using the windows command line, I have searched all over the web but nothing is coming up with how to do this.

python pandas error when doing groupby counts

When doing groupby counts over multiple columns I get an error. Here is my dataframe and also an example that simply labels the distinct ‘b’ and ‘c’ groups.

Binary file download

I’m building a server using python and bottle. How can I handle a request for a binary file? I have read that I should use flask. There is a way for doing that without using flask?

Can’t run PhantomJS in python via Selenium

I have been trying to run PhantomJS via selenium for past 3 days and have had no success.So far i have tried installing PhantomJS via npm, building it from source, installing via apt-get and downloading prebuilt executable and placing it in /usr/bin/phantomjs.

Check if xml ElementTree node is None/False [duplicate]

This question already has an answer here: Why does bool(xml.etree.ElementTree.Element) evaluate to False?

Got 403 error when connecting to Google Analytics with Python 2.7.x

I tried to get data from Google Analytics API with Python client(google-api-python-client). Here’s the code I used:

Gurobi python get value of the defined variable

How do i get the value of the variable that i have define previously(using addVar) in gurobi python? I need to compare the value of the gurobi variable and then perform calculations to reach to my objective variable. The same has to be done before optimization.

How does kmeans know how to cluster documents when we only feed it tfidf vectors of individual words?

I am using scikit learn’s Kmeans algorithm to cluster comments.

Print to standard console in curses

I’m building a python curses application. I have two ways of printing to the curses window: print x, and windows.addstr(x) (and the other similar window.* options). However, for debugging purposes, I’d like to be able to print to the standard console, so when I exit the curses window, I have the infomation waiting for me to be seen. I would normally just use print x, but that prints to the curses window.

Python functools.namedtuple

I am aware of the existence and purpose of collections.namedtuple, but I have noticed that, at least in IDLE (3.2.2), this factory function is also in functools

Two instances of the same Python module?

I created a Python module with a single function that just prints ‘a!’. I opened up the Python interpreter and imported the module in 2 different syntaxes

Unexpected behavior for numpy self division

This behavior is a little bit strange to me, I always thought x/=5. was equivalent to x=x/5. . But clearly the g(x) function does not create a new reference with /= operation. Could anyone offer an explanation for this?

creating subprojects in bottle

I’m just starting Python web development, and have chosen Bottle as my framework of choice. I’m trying to have a project structure that is modular, in that I can have a ‘core’ application that has modules built around it, where these modules can be enabled/disabled during setup (or on the fly, if possible…not sure how I would set that up tho).

DataFrame of DataFrames with pandas

I have the following DataFrame gathering daily stats on 2 measures A and B

Google Cloud Storage + Python : Any way to list obj in certain folder in GCS?

I’m going to write a Python program to check if a file is in certain folder of my Google Cloud Storage, the basic idea is to get the list of all objects in a folder, a file name list, then check if the file abc.txt is in the file name list.

How can I get the “old” zip() in Python3?

I migrated from Python 2.7 to Python 3.3 and zip() does not work as expected anymore.Indeed, I read in the doc that it now returns an iterator instead of a list.

How can i quote escape characters in csv writer in python

I am writing the csv file like this

Python and Matplotlib and Annotations with Mouse Hover

I am currently employing this code to have pop up annotatations on a map when i click on a point in a Basemap Matplotlib Plot.

Python – Find duplicates in a list of dictionaries and group them

i’m not a programmer and also new to python, i have a list of dicts coming from a json file:

pandas: iterating over DataFrame index with loc

I can’t seem to find the reasoning behind the behaviour of .loc. I know it is label based, so if I iterate over Index object the following minimal example should work. But it doesn’t. I googled of course but I need additional explanation from someone who has already got a grip on indexing.

Python grequests with custom header

I saw this post about sending asynchronous requests with grequests.

pandas.DataFrame.load/save between python2 and python3: pickle protocol issues

I haven’t figure out how to do pickle load/save’s between python 2 and 3 with pandas DataFrames. There is a ‘protocol’ option in the pickler that I’ve played with unsuccessfully but I’m hoping someone has a quick idea for me to try. Here is the code to get the error:

Smoothed 2D histogram using matplotlib and imshow

I try to do a 2D histogram plot and to obtain a “smooth” picture by a sort of interpolation. Thus I do the following combining plt.hist2d and plt.imshow

Calling locals() in a function not intuitive?

This may be elementary, but may help me understand namespaces.A good explanation might step through what happens when thefunction definition is executed, and then what happens laterwhen the function object is executed.Recursion may be complicating things.

How do I implement a custom MIB in PySNMP?

I already have the MIB text file (do I need to make this into a .py file somehow??). I am trying to use PySNMP (not net-snmp). I have been able to connect to my device and print out some info, but the info was not very helpful (just ObjectName, ObjectIdentifier, etc). I want to be able to communicate with the device (send commands to change and read values), but all of the tutorials I have seen seem to be of little help. Does anyone know how I can use my custom MIB to effectively communicate with my device? Any good sites I am missing?

ImportError: No module named sklearn.datasets

os: mac os yosemitepython: 2.7.6 — 64-bitinstalled: numpy,skipy,matplotlib,nose I get the following error.

Can push notifications be done with an AngularJS+Flask stack?

I have a Python/Flask backend and an Angular frontend for my website. At the backend there is a process that occasionally checks SQS for messages and I want it to push a notification to the client which can then in turn update an Angular controller. What is the best way to do this my existing technologies?

Subprocess.poll() falsely returns a value

Subprocess.poll() falsely returns a value

Unable to get python embedded to work with zip’d library

I’m trying to embed python, and provide the dll and a zip of the python libraries and not use any installed python. That is, if a user doesn’t have python, I want my code to work using the provided dll/zip.

python queue get size, use qsize() or len()?

I’ve seen instances where qsize() and len() has been used to compute the size of the queue. What is the distinction between the two?

SQLAlchemy – condition on join fails with AttributeError: Neither ‘BinaryExpression’ object nor ‘Comparator’ object has an attribute ‘selectable’

I’m running SQLALchemy with Pyramid. I’m trying to run a query with a custom ‘join’ condition

Why doesn’t the Python 2D array index order matter when used with colon ( : )

Creating a 2D array such as

what does [sock] = func() mean?

What does this line of code mean, from tornado?