text
stringlengths
226
34.5k
smoothing a resized image in Python Question: I'm working my way through [How to Think Like a Computer Scientist](http://interactivepython.org/runestone/static/thinkcspy/toc.html#), and I've gotten stuck on the following exercise: After you have scaled an image too much it looks blocky. One way of reducing the blockin...
Using the same key in two dictionaries (Python) Question: Here's what I have: from pprint import pprint Names = {} Prices = {} Exposure = {} def AddName(): company_name = input("Please enter company name: ") return company_name def AddSymbol(company_name...
Django development server keeps logging out Question: I set my SESSION_COOKIE_AGE settings to 360 in my settings.py,, but the it keeps logging me out while I am developing my server :(( Why is this happening and how do I prevent this..? Thanks! Here is my settings.py: **settings.py** # Django setting...
Setting up non-blocking socket for Jython for use in Chat server Question: I'm trying to create a Jython(actually monkeyrunner) program which receives messages from other python(CPython because it uses OpenCV) First, I tried to implement a chatting program example(server-side) and I ran into a problem. While the exam...
How to apply an adaptive filter in Python Question: I would like to apply an adaptive filter in Python, but can't find any documentation or examples online of how to implement such an algorithm. I'm familiar with designing "static" filters using the `scipy.signal` toolbox, but what I don't know how to do is design an a...
Returning generator from a function Question: I'm slowly getting to wrap my head around Python generators. While it's not a real life problem for now, I'm still wondering why I can't return a generator from a function. When I define a function with `yield`, it acts as a generator. But if I define it _inside_ another ...
Importing large integers from a mixed datatype file with numpy genfromtxt Question: I have a file with the format: 1 2.5264 24106644528 astring I would like to import the data. I am using: >>> numpy.genfromtxt('myfile.dat',dtype=None) Traceback (most recent call last)...
Income tax calculator and global var problems Question: Complete beginner here. I've been trying to pick up programming in my spare time and don't really have any interactive resources to consult. I've tried my best to get a program working where I've tried to program an income tax calculator. I've pasted my program in...
Modify the list that is being iterated in python Question: I need to update a list while it is being iterated over. Basically, i have a list of tuples called `some_list` Each tuple contains a bunch of strings, such as name and path. What I want to do is go over every tuple, look at the name, then find all the tuples th...
What am I doing wrong pypi missing "Links for" Question: I'm trying to tryout pypi to publish some libraries. So I started with a simple project. I have the following setup.py: import os from distutils.core import setup setup( name='event_amd', packages = ["event_amd"], ...
freeswitch python scripts errno 10 no child processes Question: I' ve got an issue when running freeswitch with some python scripts inside dialplan using django.db models. Whenever it starts it causes errors: freeswitch@ubuntu> 2013-08-15 06:56:08.094348 [ERR] mod_python.c:231 Error importing module ...
Python function that corrects a email domain Question: Okay, I have this function **construct_email(name, domain):** def construct_email(name, domain): if domain == True: print 'True' else: print'None' return name + "@" + domain This function isn't bi...
Embed an interactive 3D plot in PySide Question: What is the best way to embed an interactive 3D plot in a PySide GUI? I have looked at some examples on here of 2D plots embedded in a PySide GUI: [Getting PySide to Work With Matplotlib](http://stackoverflow.com/questions/6723527/getting-pyside-to-work- with-matplotlib...
Terminating python script through emacs Question: I am running a python interpreter through emacs. I often find myself running python scripts and wishing I could terminate them without killing the entire buffer. That is because I do not want to import libraries all over again... Is there a way to tell python to stop e...
Exception: Cannot import python-ntlm module Question: I am using suds 0.4 and running into below error,I read on the web the above issue is fixed since 0.3.8..so am wondering what is wrong here? File "script.py", line 532, in <module> prism = Prism('http://prism:8000/SearchService.svc?wsdl') ...
Best fit from a set of curves to data points Question: I have a set of curves `F={f1, f2, f3,..., fN}`, each of them defined through a set of points, ie: I don't have the _explicit_ form of the functions. So I have a set of `N` tables like so: #f1: x y 1.2 0.5 0.6 5.6 0.3 1.2 ... ...
Python subprocess get output as process finishes Question: Currently I am getting MAC addresses from devices via Bluetooth and I pass these mac addresses one at a time to a method that calls a subprocess and assigns the output to a variable. With that variable I run some filtering functions to get a value from the comm...
Automating Login using python mechanize Question: so this is my first time programming ever and I'm trying to automate logging into a website using python/mechanize. So this is my code: import mechanize import cookielib # Browser br = mechanize.Browser() # Cookie Jar cj = co...
Grabbing the output from the terminal Question: I need to run a proccess in the terminal to grab the output from it. import subprocess subprocess.check_output(["my_util", "some_file.txt", " | grep 'Some data1' | awk '{print $2}'"]) #or subprocess.check_output(["my_util", "full_path/some_...
error with python sympy computing integral for cosine function Question: So I was trying an example directly from the sympy documentation and I am getting a strange error. I am using python 3.2 with sympy 0.7.3. I have been working in the ipython notebook, though I don't think that should make a difference. The error i...
Python IDLE becomes slow on very large program input Question: Why does python idle become so slow when handling very large inputs, when the python command line does not? For example, if I run "aman"*10000000 in python IDLE, it becomes unresponsive, but on python cmd line, it is quick. Answer: I had to research a bi...
Python 2.7.2: plistlib with itunes xml Question: I'm reading an itunes generated xml playlist with plistib. The xml has a utf8 header. When I read the xml with plistib, I get both unicode (e.g., 'Name': u'Don\u2019t You Remember') and byte strings (e.g., 'Name': 'Where Eagles Dare'). Standard advice is to decode what...
Cannot convert array to floats python Question: I'm having a problem that seems like the answer would be easily explained. I'm struggling to convert my array elements to floats (so that I can multiply, add on them etc) import csv import os import glob import numpy as np def get_data(...
Are .pyds decompilable? - Python Question: I was wondering, if I export my game as an .exe and all the extra material is imported, turning it into a .pyd - can you decompile the .pyds? Thanks! Thank you people, I got my answer for any future people who need help: .pyd files are just shared libraries Any tools that all...
Python: How do you iterate over a list of filenames and import them? Question: Suppose I have a folder called "Files" which contains a number of different python files. path = "C:\Python27\Files" os.chdir(path) filelist = os.listdir(path) print(filelist) This gives me a list containing ...
need to compute change in time between start time and end time.(Python) Question: I need to write a program that accepts a start time and end time and computes the change between them in minutes. For example, the start time is 4:30 PM and end time is 9:15 PM then the change in time is 285 min. How do I accomplish this ...
Rearrange a list of points to reach the shortest distance between them Question: I have a list of 2D points for example: 1,1 2,2 1,3 4,5 2,1 The distance between these points is known (using math.hypot for example.) I want to sort the list so that there is a minimum distance between them. I'm OK wi...
words as y-values in pyplot/matplotlib Question: I am trying to learn how to use pylab (along with the rest of its tools). I'm currently trying to understand pyplot, but I need to create a very specific type of plot. It's basically a line plot with words instead of numbers on the y-axis. Something like this: ...
displaying calendar items closest to today using datetime Question: I have a dictionary of my calendar items for a month (_date_ as "key", _items_ in the form of a list as "value") that I want to print out a certain way (That dictionary in included in the code, assigned to `dct`). I only want to display items that are ...
Stream Json with python localy Question: I would like to stream a JSON locally with python (so as another program read it). Is there any package that streams in a clean way the json in a local address? (as I used print but instead of the terminal, a local url). Thanks Answer: This should do it: import...
How to pass an array of integers as a parameter from javascript to python? Question: I have a javascript code that obtains the value of several checked boxes and inserts their value (integers) into an array: var my_list = $('.item:checked').map(function(){return $(this).attr('name');}).get(); I wan...
How to properly import a library (?) in Python Question: I've been trying to use the tldextract library available here. After many attempts, I was able to get it installed. However, now when it comes to run the main file, the compiler says that it can't find any reference to my library. Below the code I used and that ...
Django ModelForm not saving data to database Question: A Django beginner here having a lot of trouble getting forms working. Yes I've worked through the tutorial and browsed the web a lot - what I have is mix of what I'm finding here and at other sites. I'm using Python 2.7 and Django 1.5. (although the official docume...
python Hiding raw_input Question: so this is my code and i want to hide my password, but i dont know how. i have looked around and none of them seem to fit in my coding, this is the current coding. i mean i have seen show="*" and also getpass but i dont know how to place them into this coding. im using python 2.7.3 and...
Python module for HTTP: fill in forms, retrieve result Question: I'd like to use Python to access an HTTP website, fill out a form, submit the form, and retrieve the result. What modules are suitable for the task? Answer: We cannot advise you with detailed instructions since you never gave us details of your problem...
Python logging typeerror Question: Could you please help me, whats wrong. import logging if (__name__ == "__main__"): logging.basicConfig(format='[%(asctime)s] %(levelname)s::%(module)s::%(funcName)s() %(message)s', level=logging.DEBUG) logging.INFO("test") And I can't ru...
Django template dir strange behaviour Question: I am really having problems to set TEMPLATE_DIR correctly after searching through bunch of topics and trying various things. Here are my project settings: #settings.py DEBUG = True TEMPLATE_DEBUG = DEBUG import os PROJECT_PATH = os.path.rea...
Python 2.7 decode error using UTF-8 header: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 Question: Traceback: Traceback (most recent call last): File "venues.py", line 22, in <module> main() File "venues.py", line 19, in main print_category(category, 0) File ...
Running 7zip command line silently via Python Question: I've seen plenty of questions regarding the python execution of a .exe file using popen and mentions of using PIPE to stop output of the process. Apologies if my terminology is incorrect, i'm very new to python. My main aim of this question to to add stdout=PIPE ...
How can I make my default python homebrew? Question: I've recently given up on macports and gone to homebrew. I'm trying to be able to import numpy and scipy. I seem to have installed everything correctly, but when I type python in terminal, it seems to run the default mac python. I'm on OSX 10.8.4 I followed this po...
TypeError when using tkinter (python) Question: I´ve written a testprogram to simulate my error. Here´s the code: from random import * from tkinter import * class match: def __init__(self): self.players = 4*[None] def commandos(self): print("show ...
Confused about python imports Question: I reviewed [the Python 2.7.5 documentation](http://docs.python.org/2/tutorial/modules.html#packages). I am having issues with my real project, but created a small test project here to concisely reproduce the issue. Imagine a package with the following layout stored at ~/Developme...
retrieve sequence alignment score produced by emboss in biopython Question: I'm trying to retrieve the alignment score of two sequences compared using emboss in biopython. The only way that I know is to retrieve it from an output text file produced by emboss. The problem is that there will be hundreds of these files to...
Python webpage source read with special characters Question: I am reading a page source from a webpage, then parsing a value from that source. There I am facing a problem with special characters. In my python controller file iam using `# -*- coding: utf-8 -*-`. But I am reading a webpage source which is using `charset...
Why is my Python code returning an error when I try to fetch YouTube videos for a given keyword? Question: Whenever I try to run my code, I receive the following error: "comment_content error! 'nonetype' object has no attribute 'href'" I am new to Python, and did not write this code myself; it was given to me to use. M...
Why does python print ascii rather than unicode despire that I declare coding=UTF-8? Question: # coding=UTF-8 with open('/home/marius/dev/python/navn/list.txt') as f: lines = f.read().splitlines() print lines The file `/home/marius/dev/python/navn/list.txt` contains a list of strings with...
mongdb pymongo disappearing list of items from collection Question: So I run a local mongodb by running `$ mongod` from the terminal. I then connect to it and create a small database with a python script using `pymongo` : import random import string import pymongo conn = pymon...
Make a python program with PySide an executable Question: I have a python program: import sys from PySide.QtCore import * from PySide.QtGui import * from PySide.QtWebKit import * app = QApplication(sys.argv) web = QWebView() web.load(QUrl("htpp://www.google.com")) ...
Initialize all the classes in a module into nameless objects in a list Question: Is there a way to initialize all classes from a python module into a list of nameless objects? **Example** I have a module `rules` which contains all child classes from a class Rule. Because of that, I'm certain they will all implement a ...
Animate a Histogram in Python Question: I'm trying to animate a histogram over time, and so far the code I have is the following one: import matplotlib.pyplot as plt import numpy as np import time plt.ion() fig = plt.figure() ax = fig.add_subplot(111) alphab = ['A', 'B', 'C',...
Click on any one of "1 2 3 4 5 ..." on a page by using Selenium in Python (e.g., Splinter): Question: I have HTML that looks like the three following sample statements: <a href="javascript:__doPostBack('ctl00$FormContent$gvResults','Page$10')">...</a> <a href="javascript:__doPostBack('ctl00$Form...
sign() much slower in python than matlab? Question: I have a function in python that basically takes the sign of an array (75,150), for example. I'm coming from Matlab and the time execution looks more or less the same less this function. I'm wondering if sign() works very slowly and you know an alternative to do the s...
how to get the integer value of a single pyserial byte in python Question: I'm using pyserial in python 2.7.5 which according to the [docs](http://pyserial.sourceforge.net/pyserial_api.html): > read(size=1) Parameters: size – Number of bytes to read. Returns: > Bytes read from the port. Read size bytes from the ser...
How do I filter nested cases to be filter out python Question: I have an ascii plain text file input file with main case and nested case as below: I want to compare the instances start with '$' between details and @ExtendedAttr = nvp_add functions in input file below for each case under switch($specific-trap), but when...
Python script couldnt detect mismatch when $instance deleted in only one of the value nvp_add in double if else input statement Question: This is continuation question from _stackoverflow_ question below: How do I filter nested cases to be filter out python [How to compare the attributes start with $ in 2 functions and...
Making a Queue for a function so it only runs once at a time in python Question: I have a multithreaded function, which all write to the same log file. How can I make this function (maybe with a function decorator) to add the execution of writing to the log file to a queue. Small example: #!/usr/bin/pyth...
Size of objects in memory during an IPython session (with Guppy?) Question: I recall [reading](http://stackoverflow.com/questions/563840/how-can-i-check- the-memory-usage-of-objects-in-ipython?rq=1) that it is hard to pin down the exact memory usage of objects in Python. However, that thread is from 2009, and since the...
Linking a SWIG wrapper with other libraries Question: I have a C++ function that I want to call from Python. The function itself is pretty simple, but it involves an IPC call that can only be done in C++. To compile that C++ code requires linking a ton of other libraries in. I'm trying to use SWIG for this. I have a Ma...
Add images dynamically based on random number Question: I work on a simple mathematics learning programs for my 4 year old daughter with the help of images. Based on a random number that we can call X, a for loop will run X number of times and print an image X number of times. The image will be selected from the list b...
python pyodbc - connecting to sql server 2008 on windows/python2.7 but not on centOS6.32/python2.6.6 Question: I have the following code: import pyodbc cnxn = pyodbc.connect("DRIVER={SQL Server};" +"SERVER=something.example.com;" +"DATABASE=som...
Python update json file Question: I have python utility i wrote that doing some WMI monitoring, the the data is written in that format example1 CPU = [{'TS':'2013:12:03:30','CPUVALUES':['0','1','15']}] Now i need occasionally update data that will look eventually like following CPU ...
Can't call python script with "python" command Question: I normally program in Java, but started learning Python for a course I'm taking. I couldn't really start the first exercise because the command python count_freqs.py gene.train > gene.counts didn't work, I keep getting "`incorrect syntax`" ...
Multiprocessing with python3 only runs once Question: I have a problem running multiple processes in python3 . My program does the following: 1\. Takes entries from an sqllite database and passes them to an input_queue 2\. Create multiple processes that take items off the input_queue, run it through a function and out...
'datetime.datetime' object has no attribute 'microseconds' Question: I am writing a script in _python_ and I need to know how many milliseconds are between two points in my code. I have a global variable when the program starts like this: from datetime import datetime a=datetime.now() When I n...
UnknownJavaServerError when trying to upload data to the Google app engine data store Question: I am trying to follow the Google app engine [tutorial](https://cloud.google.com/resources/articles/how-to-build-mobile- app-with-app-engine-backend-tutorial#tcbc) This code runs on my local development server. When I execut...
More efficient for loops in Python (single line?) Question: I put together this code which generates a string of 11 random printable ascii characters: import random foo=[] for n in range(11): foo.append(chr(random.randint(32,126))) print "".join(foo) It works fine, but I can't h...
Trying to understand this simple python code Question: I was reading Jeff Knupp's blog and I came across this easy little script: import math def is_prime(n): if n > 1: if n == 2: return True if n % 2 == 0: return False ...
Python, pdb, adding breakpoint which only breaks once Question: I sometimes set breakpoints in deep loop code as follows: import pdb; pdb.set_trace() If I press `c` then it continues, but breaks again on the next iteration of the loop. Is there a way of clearing this breakpoint from within pdb? The...
OpenCV crash on OS X when reading USB cam in separate process Question: I'm running OpenCV 2.4.5 via the cv2 python bindings, using OS X (10.8.4). I'm trying to capture images from a USB webcam in a separate process via the multiprocessing module. Everything seems to work if I use my laptop's (2011 macbook air) interna...
How to remove blank lines in text file python? Question: In my python script, I write specific columns from a text_file to a new_text_file separated by `,` because the new_text_file will later become a csv_file. There are white space lines left over in the new_text_file because of lines I skipped writing over that need...
Sort dict by sub-value in Python Question: I spent some time reading on SOF and am having issues solving this problem. I cannot seem to find how to get the following data structure sorted by the sub- value: data = {} data[1] = {name: "Bob", ...} data[2] = {name: "Carl", ...} data[3] = {nane: ...
Python - Traceback, how to show filename of imported Question: I've got the following: try: package_info = __import__('app') #app.py except: print traceback.extract_tb(sys.exc_info()[-1]) print traceback.tb_lineno(sys.exc_info()[-1]) And what i get from this is: ...
Regex to match only letters between two words Question: Say that I've these two strings: Ultramagnetic MC's and Ultramagnetic MC’s <-- the apostrophe is a different char in Python, but generally speaking, how do I write a regex to match the first string letters against the seco...
Splitting or stripping a variable number of characters from a line of text in Python? Question: I have a large amount of data of this type: array(14) { ["ap_id"]=> string(5) "22755" ["user_id"]=> string(4) "8872" ["exam_type"]=> string(32) "PV Technical S...
ipython pandas plot does not show Question: I am using the anaconda distribution of ipython/Qt console. I want to plot things inline so I type the following from the ipython console: %pylab inline Next I type the tutorial at (<http://pandas.pydata.org/pandas- docs/dev/visualization.html>) into ipyt...
PLS-DA algorithm in python Question: Partial Least Squares (PLS) algorithm is implemented in the scikit-learn library, as documented here: <http://scikit- learn.org/0.12/auto_examples/plot_pls.html> In the case where y is a binary vector, a variant of this algorithm is being used, the Partial least squares Discriminant...
Executing shell command from python Question: I am trying to compile a set of lines and execute them and append the output to text file. Instead of writing the same thing, I used a python script to compile and execute in background. import subprocess subprocess.call(["ifort","-openmp","mod1.f90","mod...
finding and Importing xml file into python Question: I am attempting to import an xml file into python with minidom. >>> from xml.dom import minidom >>> import os >>> xmldoc = minidom.parse('c/Users/WFD/Documents/VXWorks/XML_Parasing_Python') and python cannot find this file even though I h...
eclipse,python, NameError: name <MyModule> is not defined Question: I create the following package in eclipse via `PyDev`: class Repository(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' print("salaam...
How to encode nested Python Protobuf Question: Been stumped on this for a while and pulling what is left of my hair out. Sending non-nested Protobufs from Python to Java and Java to Python without an issue with WebSockets. My problem is sending a nested version over a WebSocket. I believe my issue is on the Python enc...
Python program to manage python script as child Question: I am looking for a python equivalent of following: until python program.py; do echo "Crashed...Restarting..." >&2 sleep 1 done Also, I need to kill program.py when the parent program is killed. Any suggestions? Answer:...
Why is my python script that runs the adb shell monkey command crashing for large values of events? Question: I have written a small python function that runs an adb shell monkey -p -v command along with an adb logcat command using subprocess.popen. For values larger than 100, this program crashes and I'm not sure why....
Most appropriate way to combine features of a class to another? Question: Hey guys I'm new here but hope my question is clear. My code is written in Python. I have a base class representing a general website, this class holds some basic methods to fetch the data from the website and save it. That class is extended by ...
A fast method for calculating the probabilities of items in a distribution using python Question: Is there a quick method or a function than automatically computes probabilities of items in a distribution without importing random? For instance, consider the following distribution (dictionary): y = {"red...
redirecting python logging messages with streams Question: I want to redirect logging messages to some handling method (e.g. in order so save all messages in a queue). Currently I'm trying to make use of logging.StreamHandler in order to write to a StringIO and then read it somewhere else. In my case this might be a th...
Python record audio on detected sound Question: I am looking to have a python script run in the background and use pyaudio to record sound files when the threshold of the microphone has reached a certain point. This is for a monitor on a two way radio network. So hence we only want to record transmitted audio. Tasks i...
Using adb sendevent in python Question: I am running into a strange issue, running `adb shell sendevent x x x` commands from commandline works fine, but when I use any of the following: `subprocess.Popen(['adb', 'shell', 'sendevent', 'x', 'x','x'])` `subprocess.Popen('adb shell sendevent x x x', shell=True)` `subp...
Console Program in C++ Question: I was recently messing around with c++ console programming. I was wondering if there was a way to make text appear on the console for a specific amount of time, then go to some more text. Essentially, I'm trying to create a timer object. Or if you're familiar with python, it would be so...
Is there a faster way to test if two lists have the exact same elements than Pythons built in == operator? Question: If I have two lists, each 800 elements long and filled with integers. Is there a faster way to compare that they have the exact same elements (and short circuit if they don't) than using the built in `==...
Python pandas timeseries resample giving unexpected results Question: The data here is for a bank account with a running balance. I want to resample the data to only use the end of day balance, so the last value given for a day. There can be multiple data points for a day, representing multiple transactions. ...
SQLAlchemy order_by formula result Question: I am a novice in Python. Based on [this](http://stackoverflow.com/questions/592209/find-closest-numeric-value- in-database/) SO post, I created a SQL query using PYODBC to search a MSSQL table of historic option prices and select the option symbol with a strike value closest...
Python/Django: How to convert utf-16 str bytes to unicode? Question: Fellows, I am unable to parse a unicode text file submitted using django forms. Here are the quick steps I performed: 1. Uploaded a text file ( encoding: utf-16 ) ( File contents: `Hello World 13` ) 2. On server side, received the file using `f...
Memory usage keep growing with Python's multiprocessing.pool Question: Here's the program: #!/usr/bin/python import multiprocessing def dummy_func(r): pass def worker(): pass if __name__ == '__main__': pool = multiprocessing.Pool(processes=16) ...
How to install python 2.7.5 as 64bit? Question: When downloading the python 2.7.5 [here](http://www.python.org/getit/), I download the python installer with the link "Python 2.7.5 Mac OS X 64-bit/32-bit x86-64/i386 Installer (for Mac OS X 10.6 and later [2])". Installed the python, I cd the directory "/Library/Framewor...
Most labels update well, except for one Question: I apologize for pasting all of my code. I'm at a loss as to how I should post this question. I did look for other answers throughout this week, but I cannot for the life of me figure this out. I know that there is more I have to do to get this program to work, but I'm j...
Protcol Buffers - Python - Issue with tutorial Question: **Context** * I'm working through this tutorial: <https://developers.google.com/protocol-buffers/docs/pythontutorial> * I've created files by copy and pasting from the above tutorial **Issue** When I run the below file in `python launcher`nothing happens: ...
script working only in spyder console Question: I everybody, I usually use spyder to write in python and I write these simple lines of code for plotting some graph but I can't understand why it doesn't work properly when I run it, but if I copy and paste the lines in the python console it works perfetly. This is the co...
selenium python click on element nothing happens Question: I am trying to click on the Gmail link on the Google frontpage in Selenium with the WebDriver on Python. My code basically replicates the one found here: [Why Cant I Click an Element in Selenium?](http://stackoverflow.com/questions/16511059/why-cant-i-click-an-...
ImportError: cannot import name PyJavaClass Question: I check [my old script](http://code.activestate.com/recipes/502222-creating- java-class-description-files/?in=user-4028109) written in 2007 in Python/Jython and it throw the error: ImportError: cannot import name PyJavaClass What happen with thi...
Python: how do I create a list of combinations from a series of ranges of numbers Question: For a list of numerical values of n length, e. g. `[1, 3, 1, 2, ...]`, I would like to create a list of the lists of all possible combinations of values from `range[x+1]` where x is a value from the list. The output might look s...