text
stringlengths
226
34.5k
calculate multiple sine sweeps one after another Question: I'm writing a Python program to generate multiple sine sweeps one after another with varying starting and ending frequencies and varying time intervals. One example would be: 1. sweep from 0Hz to 170Hz in 1 millisecond 2. sweep from 170Hz to 170Hz in 1 m...
How can read two field of a csv file separately in python? Question: I want to read two column of a csv file separately, but when I wrote code like below python just show first column and nothing for second, but in the csv file the second column also has lots of rows. import csv import pprint ...
How to merge two CSV files by Python based on the common information in both files? Question: Evans, Great thanks. It is almost the expected result. Please kindly take a hand to modify as follows. We need a little change. Please take a look at the image. In the present result, each record in fileOne search the similar ...
xlwings wipes out my EXCEL addin Question: I own a professional Addin for EXCEL called Valuesoft. It performs several calculations related to equity (stockmarket) data. It is a 160K dll file and works fine from EXCEL including from VBA scripts. However, as soon as an EXCEL file (Workbook) is opened using xlwings from P...
Can the [a-zA-Z] Python regex pattern be made to match and replace non-ASCII Unicode characters? Question: In the following regular expression, I would like each character in the string replaced with an 'X', but it isn't working. In Python 2.7: >>> import re >>> re.sub(u"[a-zA-Z]","X","dfäg") 'X...
Python - Position of last character in sequence using similar method to one here Question: def PositionLast(x,s): position = -1 for i in s: position +=1 if i == x: return position Is what I have so far - just returns the first. Is there a way using simi...
upload file with post params Question: I want send file to url with some post params like "chat_id", "caption" and file must be sended as 'photo' field-name. but I found only methods to send only POST params without file or sending only file without POST params and custom file name param.. This code send only `para...
Python py pyfirmata code is showing the incorrect value Question: I write the following code to check the value of input pin but it never shows the digital value as input. I don't know what is wrong. Can any one explain it ? from pyfirmata import ArduinoMega, util board = ArduinoMega('COM3') ...
Trouble adding data to Solr with python? Question: I am using python 3.4.3 and sunburnt to add some document to Solr(5.2.1). The following code is directly from the Sunburnt documentation: import sunburnt si=sunburnt.SolrInterface("http://localhost:8983/solr/") document = {"id":"0553573...
Error: object() takes no parameters , cant resolve it Question: this is python file im trying to make A*algorithm , but cant get it to work, I need some help , its an awesome code , its been run in latest python version for windows from queue import PriorityQueue class State(object): ...
Can Golang multiply strings like Python can? Question: Python can multiply strings like so: Python 3.4.3 (default, Mar 26 2015, 22:03:40) [GCC 4.9.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> x = 'my new text is this long' >>> y = '#' * len(x) ...
Python how to save dictionary with cyrillic symbols into json file Question: #!/usr/bin/env python # -*- coding: utf-8 -*- import json d = {'a':'текст', 'b':{ 'a':'текст2', 'b':'текст3' }} print(d) w = open('log', 'w') json.dump(d,w...
Create a list property in Python Question: I am starting OOP with Python 3 and I find the concept of `property` really interesting. I need to encapsulate a private list, but how could I use this paradigm for lists? Here's my naive try: class Foo: """ Naive try to create a list property.. and ob...
TypeError: Can't convert 'bytes' object to str implicitly for tweepy Question: from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener ckey='' csecret='' atoken='' asecret='' class listener(StreamListener): def on_data...
How to plot a CVS file with python? My plot comes up blank Question: I have the code below that seems to run without issues until I try to plot it. A blank plot will show when asked to plot. import numpy as np import matplotlib.pyplot as plt data = np.genfromtxt('/home/oem/Documents/620157.c...
Python: plot timestamp data frame matplotlib Question: I am plotting values over the time (i.e. hourly) I have a dataframe `dfout` as following val x y ID time 0 6.0 48.730304 11.594837 0efd2316-feb9-461c-b102-045aef8e22fe ...
Improve performance of a for loop in Python (possibly with numpy or numba) Question: I want to improve the performance of the `for` loop in this function. import numpy as np import random def play_game(row, n=1000000): """Play the game! This game is a kind of random walk. ...
Jython "Attribute not found" Question: I'm attempting to use some of the tkinter functionality in JES, on v3.4. But I'm getting an error after import. Code begin with this: import Turtle import math myPen = Turtle.turtle() window = Turtle.screen() Returns the error > The error was:cla...
IP scan then do certain job and play MP3 only once Question: I have the following code here. What I want to do is I want to script to scan my ip address then do certain job. My problem is the MP3 is always repeating every 30 seconds even if I did not turn off my phone WIFI which is carrying the IP of the hostname. I'...
SQLAlchemy instantiate object from ORM fails with AttributeError: mapper Question: I've been trying to get a decent-sized project going with SQLAlchemy on the backend. I have table models across multiple files, a declarative base in its own file, and a helper file to wrap common SQLAlchemy functions, and driver file. ...
BeautifulSoup - How to remove nested tags with no text and blank space from the end of HTML Question: I'm trying to use BeautifulSoup to remove tags that have no text inside of them. For example I have the following tags: <p> <p> <br/> </p> </p> or <p> ...
Multiprocess Python 3 Question: I have a script that loops over an array of numbers, those numbers are passed to a function which calls and API. It returns JSON data which is then written to a CSV. for label_number in label_array: call_api(domain, api_call_1, api_call_2, label_number, api_key) ...
why can't i center my menubar/navigation Question: I'm new with **html** and **css** but I'm making a responsive dropdown menu and I cant find why my menu/navigation bar won't center in the desktop version. I found the menu from [here](http://www.cssscript.com/pure-css-mobile- compatible-responsive-dropdown-menu/) and...
How can I create a new page to confluence with Python Question: I am trying to create a new page into confluence using Python's `xmlrpclib`. I already know how to update content of an existing page, but how can I create a totally new page? I have used following script to update content: import xmlrpclib...
Look for text with BeautifulSoup in a web page with multiple html tags? Question: Thanks for your help. I am trying to extract text from a web page using BeautifulSoup and Python. I have done it lots of times with different web pages and always got the information I needed, but this time the html source code from the ...
Unable to see image on Google app engine web Question: I Just want to show image on Google app Engine Website. I am new to Google app engine. I made changes in App.yaml and Main.py app.yaml looks like : application: simplegraph-007 version: 1 runtime: python27 api_version: 1 threadsafe: y...
"Inconsistent number of matrix lines compared to the number of labels" runtime exception error when importing large CSV file into Gephi Question: The full error is "java.lang.RuntimeException: java.lang.Exception: Inconsistent number of matrix lines compared to the number of labels." I am trying to pull an adjacency m...
Python Hangman not working Question: So, I've finished my Hangman project for a coding class and it's stuck in a loop where it just keeps asking if you want to play, after that it defines the word to play but it also TELLS you which word to play you're going to play. I think the chained whiles and ifs have some wrong v...
Scraping a web page, using xpath, returning text for the result Question: I'm scraping a web page with lxml in Python, and trying to get the text under the Table named (Table3). Under this table as you can see in the code below number of tr's and then 4 td's under each tr. **What I want is to print the text of td1 und...
How to fit a double Gaussian distribution in Python? Question: I am trying to obtain a double Gaussian distribution for data ([link](https://drive.google.com/file/d/0BwwhEMUIYGyTbkVwVGpoUDA2OGs/view?usp=sharing)) using Python. The raw data is of the form: [![enter image description here](http://i.stack.imgur.com/Q1Wy0...
drawing a barcode with turtle graphics on python Question: I know that there are crazy short cuts to doing a lot of things with Python, which is where I'm running into trouble with this project for my intro CIS class. I've searched for variations of my question, but without luck.. SO: the project is to make our "turtl...
django.contrib.auth utf-8 ascii python 'Unicode-objects must be encoded before hashing' Question: I have a Django web project that was originally authored on a Linux machine (UTF-8) and I cloned the git repository code to my windows machine. When accessing Django's admin interface running from the built-in development ...
breaking a loop in the middle python Question: i am trying to have a loop that keeps functioning until something is inputted which will break the loop. However if i put in 'stop = input()' in the loop then it has to go through that first before doing anything else. my code is like this: (it uses some minecraft commands...
How to output python graphs from terminal? Question: I am very new to Python. Just installed it yesterday on Ubuntu 15.04. Now I am trying to output a parabola from the terminal. As far I understand I can not output any drawing on terminal so how can I see the graph? I did : `sudo apt-get install python-numpy python-s...
Sum of lists for each element of list1 with all in list2 Question: I want make script that reads lines from file, than takes slices from each line, combines all slices from 1 line with all slices from 2 line, then combines all slices from previous step with 3rd line. For example, we have Stackoverflow (...
python won't accept the value of a variable Question: This runs and scrapes links exactly how I want it except python doesn't recognize the value of "scraped_pages" when I run it in the terminal scraped pages will increment by 1 every loop but it just carries on when the integer is higher than "page_nums". when I set "...
Printing the output that is a list of file names to a text file Question: I have made a Python program that checks the files in a folder and returns a list of the ones that end with .txt. Now i want to output that to a file. Here is my code: import os import os.path import sys f=open("E:...
Python can't import urllib2 (gives an error) Question: I just started with programming, I wanted to import the urllib resource but when I just use this code: import urllib2 It worked 2 months ago (took a break). It gives me this error: Traceback (most recent call last): Fil...
Check_mk syntax to to make python add new hosts Question: I´m using Check_mk and i was trying to implement a python script to run via cfengine to add automatically new installed hosts. I´m having some trouble with both using pycurl or running and external curl. An example of the command i want to be able to pycurl is:...
Reconstructing a binary tree from infix and prefix expressions [python] Question: Ive been spending hours on trying to figure out how to do this, I know the function "buildtree" has to be called recursively to draw but I just cant figure it out, I just need a spoon-fed answer which I can then study, I have tried to do ...
Python: How to Call a function in another file Question: I am making a text-based floor game for learning purposes. I want all of the moving-around functions to be in a separate python file but I am having issues getting them to work together. I have the main game called `floors.py` and the map file is `floormap.py`. ...
Testing headless firefox using selenium but it is throwing an error Question: I am trying to test headless firefox using Selenium and the below code is giving correct result. From a fresh Ubuntu 14.04 install I did the following sudo apt-get install python-pip firefox xvfb pip install seleni...
Python - 2nd 'for' loop in function not working Question: I may be missing the obvious here, and if so please excuse the noob (which I am) question. I am trying to iterate through the lines in a text file. The first `for` works fine; however, the 2nd `for` does not. The `print(eachLine)`command does not print anything,...
dictionary update sequence element #0 has length 4; 2 is required Question: I'm new here and django world.. I tried to find an answer about this error, but I didn't find one that fix my problem. **urls.py** from django.conf.urls import include, url, patterns from django.contrib import admin from...
XQuery absolute path in python lxml Question: I have an XML document from which I want to extract the absolute path to a specific node (mynode) for later use. I retrieve the node like this: from StringIO import StringIO from lxml import etree xml = """ <a1> <b1> <c1>c...
Date formats and its difference in python Question: I have two dates in below formats: d1 = "Fri, 16 Oct 2015 18:06:37 +0530" d2 = "Thu, 1 Oct 2015 17:12:00 +0530" I need to find the number of days between these two dates. Answer: I like the dateutil library: from dateutil impo...
How can ı make a program that can run cmd comands in python3.x Question: I trying to make a program that can access other computers in the same network by using the cmd command. I have an administrator password that work in all computers in our network. But I don't know how to make a program that includes cmd commands?...
Why doesn't sys.stdout.write work in python2? Question: #!/usr/bin/python import sys def main(): f=open("a",'r') line1=f.readlines() f.close() try: sys.stdout.write(line1) except: print "?" if __name__ == "__main__": ...
How to detect a laser line in an image using Python Question: What's the quickest most reliable method of detecting a roughly horizontal red laser line in an image using Python? I'm working on a small project related to 3d laser scanning, and I need to be able to detect the laser in an image in order to calculate dista...
How to select rows where hours and minutes = 0 using da.searchcursor Question: I am trying to exclude some results from numerous tables in an arc.sde database and the only field I can use is a date field. I have researche the Python2 site and tried to understand page 8.1 regarding datetime etc but not been able to achi...
Python : file.seek(10000000000, 2000000000). Python int too large to convert to C long Question: im developing a program that downloads "big files" from the internet (from 200mb to 5Gb) using threads and file.seek to find a offset and insert the data to a main file, but when i try to set the offset above the 2147483647...
supervisord python import error Question: I'm trying to daemonize my bash script which starts running python script inside. Here is my program section of supervisord.conf [program:source] directory=/home/vagrant/ command=/usr/local/bin/python /home/vagrant/start.py process_name=%(program_nam...
Parsing a book into chapters – Python Question: I have a large book stored in a single plain text file and want to parse it in order to create individual files for each chapter. I some simple regex that finds each chapter title, but I'm struggling at capturing all of the text in between. import re ...
Compile Latex file using a python script Question: I am able to use python script to create a LaTeX file, but I want to take that file and compile it, so it creates a pdf by using a python script. I have seen some things using os and subprocess but I really don't understand it. Answer: Try this out. ...
Class is in sys.modules but cannot be used. Why? Question: I have a file `MySQL.py` which contains a class `MySQL` defined like so: class MySQL: ... all stuff that is not important here In other file (test.py), which is in the same directory I do a conditional loading of this `MySQL` class....
Extract columns from file to another file Question: I got a text file with 17 columns and a few 100s lines. How do I extract only column nr2, 14 and 16 to another file with only those 3 columns with a python script? I want to make a file with 17 columns to a new file with only 3 of those Answer: you can use `nympy`: ...
how to save date and time using localtime in Django? Question: So I am trying to learn Python and Django... Great language and framework. That said, please excuse me for my seemingly very dumb question. I have a Django project which won't be used outside a single timezone, so it doesn't really make much sense to save...
Getting same process details as task manager in Windows Question: I have written a program to get memory details of the current running processes using `psutil` in Python 3. The problem is that the values I get are not the same as those from the Windows Task Manager. Specifically, how do I obtain the private working se...
Plotting the graph on the complex plain Question: I would like to plot the graphic of function: `w(s) = 1/(1+s)`. `s` is the product of the imaginary unit (`1j`) and the variable called `omega`; i.e. `s = 1j*omega`. How I can plot that in the complex axis (Real and Imaginary) using Python (2.7 or 3.4) and `matplotlib...
Python connect to MySQL database on web server Question: I wanted to know the process of connecting to a MySQL database that is hosted on a web server. I have a basic free webserver for testing on 000webhost on which I created a MySQL database. I have the credentials for the database which I will pretend are host - m...
Python (spyder) - name 'debugfile' is not defined Question: I'm a beginner at programming and I need to do it for a university course. The programme I'm using is Spyder (downloaded last night) and I have to code in 'python'. I've downloaded the version required, but I can't seem to run a simple code. # -...
Quiverkey reference arrow is not being displayed Question: The reference arrow is missing in my quiverkey and I can't figure out why. Can someone see what I'm doing wrong? I originally wasn't using gridspec, but I needed to so that my figures scaled correctly. When I wasn't using gridspec, the reference arrow was show...
Python, Sort List Question: I'm trying to get it so that it finds the average of the numbers inside the list, then sorts the averages by highest average. Here's what I have o far: d = defaultdict(list) for name, score in ListAvg: d[name].append(score) print(d.items()) This currently...
PyCharm type hinting doesn't work with overloaded operators Question: This was sort of touched on in [this thread](http://stackoverflow.com/questions/31231541/pycharm-type-error- message/31367247#31367247), but never resolved. I have a vector class: class Vector2D(object): # ... ...
Alternatives to pyipc lib for IPC with python Question: I use for an old project pyipc a Python binings to System V interprocess communication mechanisms: <https://pypi.python.org/pypi/pyipc/> that work well, I use it like this: from ipc import Semaphore, MessageQueue ... But it seems not main...
(Django) CSRF Verification for AJAX requests working in Chrome but not Firefox Question: As the title states, my (Django) CSRF verification is working in Chrome but not Firefox and I'd like to know why so I can fix this. I have this included in the _head_ tag of my **base.html** file from which all other files in my a...
In python, when using sqlite3 where are databases stored physically? Question: Sorry for the basic questions. I'm starting to work with Python. I'm using Windows 10, Python 3.5, Notepad++ as editor. Python is installed in `z:\python35` and scripts are in `z:\python\sqlite`, then my script is really simple: ...
Find all numbers in a string in Python 3 Question: Newbie here, been searching the net for hours for an answer. string = "44-23+44*4522" # string could be longer How do I make it a list, so the output is: [44, 23, 44, 4522] Answer: Using the regular expressions as suggested by...
Installing Network-x Question: How do I download and install network-x for python version 3.4.0 on mac? Can someone give me a step by step guide on installing network-x? I tried to quick 'quick install' as suggested by github. When I try to import it on python it gives me an import error saying no modules were found. ...
Using Memcache in Django/Python 3,4 with Heroku Question: I have been following [this tutorial](https://devcenter.heroku.com/articles/django-memcache#further- reading-and-resources) so that I can use Memcache on my app on Heroku. However I ran into issues when using `cache.get()` in Heroku's shell (it works fine on my ...
Implementing large data set causing "string index out of range" error in Python? Question: I am trying to implement the following code: with open('datapath') as f: k_mers = f.read() k_mers_parsed = [] for i in k_mers.split('\n'): k_mers_parsed.append(i) genome = k_mers...
Interaction with python's matplotlib figure: assign value to selected features Question: Is it possible to select an area inside a matplotlib's figure window to which assign the value, say, 0? For example, let's say I want to write a script that, at a certain point, shows the image inside a figure window (pyplot.imshow...
Split one large .xml file in more .xml files (python) Question: I've been trying to split one large .xml file in more .xml files in python for a few days now. The thing is I haven't really succeeded yet. So here I am asking for your help. My large .xml file looks like this: <Root> <Testcase> ...
How to modify SPSS output files with Python? Question: I'm making custom tables in SPSS, but when the cell values (percentages) are rounded to 1 decimal, they sometimes add up to 99,9 or 100,1 in stead of 100,0. My boss asked my to have everything neatly add up to 100. This means slightly changing some values in the ou...
Error trying to open JSON tweet file Question: I'm getting the following error when attempting to open a json file. Traceback (most recent call last): File "C:\Python34\test.py", line 5, in <module> data = json.load(data_file) File "C:\Python34\lib\json\__init__.py", line 268, in load par...
How to get a value from json dictionary in python? Question: The result of running my code is something like: b'{"username":"test","available":false,"status":"unavailable","failed_reason":null,"callback_url":"http://www.twitter.com/"}' How can I actually get the value of [username] from this respon...
How to create a simple message box with a Python script a plattform-independend way? Question: I have simple Python3-script. It is not a application - just a helper script. Normaly it would do its job without any human readable output. But when an error happens I want to have a message window. I know there are some u...
Python going through links randomly in a list Question: so here is my code import random import webbrowser results = [] with open("al.txt") as inputfile: for line in inputfile: results.append(line.strip().split(',')) x = (random.choice(results)) webb...
How to check if a MySQL connection is open in Python? Question: I am using MySQLdb (<http://mysql-python.sourceforge.net/>). It seems that connection.open and connection.sqlstate() do not work for me. Below is the code: def open(self): #TODO: check the connection's status # self.__conn.op...
Plot text is lost when importing matplotlib images to Microsoft Word 2013 Question: I am using `matplotlib 1.4.3` on `python 2.7` and am saving my plots as ".eps" files on my linux server. For my research paper, I need to include these images into `MS Word 2013` where the text of my research lies. However, when I impo...
how to handle os.system sigkill signal inside python? Question: I have a python script where I call a lengthy process from the operating system after a long while the process that I call get terminated by the system by SIGKILL signal , is it possible to handle this from inside python like try and catch situation ?? w...
Reading a specific number of lines of a .csv in python Question: I have a csv file that I am trying to read into python and then I want to store the first two columns in a variable called name and gender. The current code I am using is the following: import csv infile = open('blue.csv', 'r') csvf...
python: file paths no longer work with imp Question: I recently started using imports to better organize my code in python. My original code in `file1.py` used the line: def foo(): files = [f for f in os.listdir('.') if os.path.isfile(f)] print files #do stuff here.... Which...
python 3 import TypeError error Question: I'm having a bizarre app startup error and was wondering if someone might know how to debug/resolve it. I'm running a Flask app using python 3. I kick things off by running: `python manage.py runserver` and the stacktrace below is generated: Traceback (most rece...
DataFrame object has no attribute 'sample' Question: Simple code like this won't work anymore on my python shell: import pandas as pd df=pd.read_csv("K:/01. Personal/04. Models/10. Location/output.csv",index_col=None) df.sample(3000) The error I get is: AttributeError: 'DataF...
Embedded Python in C++ Threading error Question: Recently, I needed to create a tool to scrape a page's source so I could parse out of a public database, for a project that I'm working on. Python seemed like an easy solution but it was a pain getting it up and running and currently I have it half working (saves source ...
ElasticSearch using python Question: I am using python to import file into `ElasticSearch`. Simple data I can Import but facing issue when there is combination of letters and numbers as well special characters. I am using below script: from datetime import datetime from elasticsearch import Elastics...
How to write to named pipe with the threading module in Python? Question: I am trying to write a program which communicates to an external program through named pipes. The python script does not know when the external program opens up the named pipe/file for reading, so the python script need to open the pipe in blocki...
Convert .txt to .xls from nested folders Question: I found a Python script to convert .txt to .xls and it is working: [Converting multiple tab-delimited .txt files into multiple .xls files](http://stackoverflow.com/questions/17110674/converting-multiple-tab- delimited-txt-files-into-multiple-xls-files) : ...
ImportError: No module named django_crontab Question: I am trying to set up some cron jobs in Linux using django-crontab 0.6 (which is installed). I have added 'django_crontab' to INSTALLED_APPS in settings, and I have specified the jobs using: CRONJOBS = [ ('0 0 * * *', 'proj.app.cron.update_ent...
Why should I use CamelCase for namedtuple? Question: Assuming this code snippet (ipython) In [1]: from collections import namedtuple In [2]: type(namedtuple) Out[2]: function you can see that factory function `namedtuple` is a `function`, of course. I can't see any hint in PEP-8 to use the ...
Python-opencv Error import cv2 ImportError: dlopen after update of OS X EI Captain Question: I have this error when import cv2 after update the system of OS X EI Captain import cv2 ImportError: dlopen(/usr/local/lib/python2.7/site-packages/cv2.so, 2): Library not loaded: lib/libopencv_shape.3.0....
Bulls and Cows Game - Python programming for beginners Question: I am a beginer programming Python and for a evaluation assignment I was asked to program a Bulls and Cows game using very simple code. I have some code already written, but can't seem to make the function work. The function should be able to compare the f...
Plotting a function with matplotlib Question: So I have defined a function, and for some reason the terminal is returning the following error: TypeError: only length-1 arrays can be converted to Python scalars I'm not sure what I have done wrong exactly? Here is my self-contained function with cor...
Can't launch ipython after El Capitan upgrade Question: Does anyone know how to undo the changes to paths and permissions wrought by upgrading to El Capitan. Specifically, it appears that OS X is now using the system python instead of my Canopy installation. These look ok: Michaels-Mac-mini:~ mellis$ wh...
Error when running Duplicity on AWS Linux Question: I have installed Duplicity on some AWS EC2 instances using the folowing command yum -y install duplicity rsync gpg python python-devel python-pip -- enablerepo=epel This was based on an approach described here <https://rtcamp.com/tutorials/bac...
python cffi parsing error when defining a struct Question: I am trying to use `python-cffi` to wrap C code. The following `example_build.py` shows an attempt to wrap `lstat()` call: import cffi ffi = cffi.FFI() ffi.set_source("_cstat", """ #include <sys/types.h> ...
Scrape booking.com with Python against AJAX requests Question: I am trying to scrape data from booking.com and almost everything is working now but I am not able to get the prices, I read so far that it is because those prices are loaded via AJAX calls. Here is my code: import requests import re ...
How to install imapclient Question: I’m trying to use the IMAP client library: <https://imapclient.readthedocs.org/en/stable/> I download the zip: <https://pypi.python.org/pypi/IMAPClient/0.13> Next I used windows command prompt and pip to install: Ran: `pip install imapclient` This placed/created a director in m...
No module named serial Question: and I got a question when I run my Python code. I installed Python 2.7 on Windows 7, bit 64. I got an error "No module named serial" when I compiled my code: import serial ser = serial.Serial("COM5", 9600) ser.write("Hello world") x = ser.readl...