text stringlengths 226 34.5k |
|---|
Do I need a lock when using python multi-thread?
Question: Think about this code:
#!/usr/bin/env python
from threading import Thread
count = 0
def test():
global count
for i in range(10):
count = count + 1
if __name__ == '__main__':
... |
Is there a way to view cPickle or Pickle file contents without loading Python in Windows?
Question: I use cPickle to save data sets from each run of a program. Since I sometimes
need to see the outline of the data without running the code, I would like an
easy way to quickly view the contents by just double-clicking on... |
Django: url and content creation results in 500 and no apache error log entry
Question: If i try to open a created url i get an 500 error.
My procedure was:
First `python manage.py startapp black`
I added in `project/settings.py` under `INSTALLED_APPS` `'black',`
I added in `project/urls.py` `url(r'^test/', include... |
gtk python expanding content to fit window
Question: I have this program and, as much as I try I can not make the elements expand
to occupy the area defined for the tire size of the application.
Code:
import smtpClass
import xmlHostes
import pygtk
pygtk.require('2.0')
import gtk
... |
Index similar entries in Python
Question: I have a column of data (easily imported from Google Docs thanks to
[gspread](http://burnash.github.com/gspread/userguide.html#getting-the-entire-
row-or-column)) that I'd like to intelligently align. I ingest entries into a
dictionary. Input can include email, twitter handle o... |
App Engine Python Authentication Custom Redirect
Question:
handlers:
- url: /secure_api/.*
script: _go_app
login: required
auth_fail_action: unauthorized
This code only brings me to a page saying "Login required to view page." Is
there a way to instead redirect to my home page?
Answer... |
Python Bar Plot pylab not reading in all data from csv
Question: I am attempting to create a bar plot of a large text file of data that looks
like the following, storedd in a csv file:
#DowntonPBS, 23
#DowntonAbbey, 12
#Download, 8
#Download:, 2
#Downloads, 2
#DownstairsMixtape, 1
... |
How do I read a text file containing an array and place it in an array? (Python)
Question:
from numpy import *
f = open('matrix.txt', 'r')
x = []
for line in f.readlines():
y = [value for value in line.split()]
x.append(y)
f.close()
x = map(int, x)
a... |
How to define a Django model with a reference to itself?
Question: I'm new to Django and currently write an application, where users can enter
their opinions on some topic.
Every opinion A may have zero or more opinions, which support A and several
(zero or more) opinions, which refute A.
I tried to create a model fo... |
Using Python 3.3 to access blocked webpages
Question: I'm trying to download webpages off the internet. I'm able to steal the HTML
(with URLlib), but I can't download images correctly. There's already a
question for that though. My question is, **is there any way I can use python
to bypass a firewall to access 'blocked... |
Get 10 numbers from the end of the string with Python regex?
Question: I have some strings like -
1. "07870 622103"
2. "(0) 07543 876545"
3. "07321 786543 - not working"
I want to get the last 10 digits of these strings. like -
1. "07870622103"
2. "07543876545"
3. "07... |
unicodedata.unidata_version prints wrong unicode version?
Question:
>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
>>> import unicodedata
>>> unicodedata.unidata_version
'5.2.0'
Which means my Python version should have... |
Inputting data from a text file with multiple numbers on each line - Python
Question: Lets say I have a data file that has this inside it:
23 33 45
91 81 414
28 0 4
7 9 14
8 9 17
1 1 3
38 19 84
How can I import it into a list so that each individual number it its own
item?
... |
What can I do if celery forgets about tasks on a (apparently) random basis?
Question: I have a flask app with sqlalchemy and a celery worker up and running. I use
redis as my broker. Every time someone submits a new message in a
conversation, a worker is started and is supposed to send notification mails
to all people ... |
import a file from different directory
Question: i'm using python 2.7. I have written a script, i need to import a function
from some other file which is there in different folder. my script is in the
path
C:\python\xyz\xls.py
Path of File having function that i need to call is
C:\py... |
How do I implement a sliding window in Python?
Question: I have a matrix for instance
a=[12,2,4,67,8,9,23]
and I would like a code that appends a value say 45 to it and removes the
first value '12' so in essence I want to make
a = [2,4,67,8,9,23,45]
I want to work with regular ... |
AttributeError when using numpy.logical_and with Pandas Series object
Question: I'm confused about the difference between Pandas Series objects when using
`reindex_like` and related features. For example, consider the following
Series objects:
>>> import numpy
>>> import pandas
>>> series = panda... |
Combine items in list
Question: Python3:
dct = {'Mazda': [['Ford', 95], ['Toyota', 20], ['Chrysler', 52], ['Toyota', 5], ['Toyota', 26]]}
I have the above dictionary with the values being a list within a list. What I
would like to do is combine the items within the list that are the same and
add th... |
"object has no attribute" in custom Django model field
Question: I am trying to create a Django model field that represents a duration with
days, hours, minutes and seconds text input fields in the HTML, and stores the
duration in the db using the ical format (RFC5545).
(this is related to my question on [How to creat... |
How can I extract a wrapped C++ type from a Python type using boost::python?
Question: I've wrapped a C++ class using Py++ and everything is working great in Python.
I can instantiate the c++ class, call methods, etc.
I'm now trying to embed some Python into a C++ application. This is also
working fine for the most-pa... |
Transferring specific data from one excel file to another using python
Question: I just started learning Python and I need help with a script my internship
asked me to write.
I have a csv file (sheet1.csv) and I need to extract data from only two of the
columns which have the headers referenceID and PartNumber that co... |
Python OS PostreSQL and quotes
Question: I can find plenty here about quotes in PSQL but nothing that quite fits this
problem.
First it's a kludge. I know it's a kludge but I think I'm stuck with it (open
to other alternatives though)
I have a near black box third-party linux appliance to which I have limited
access ... |
Recurring function call with twisted
Question: I have a basic IRC bot that looks something like this (see below), what I
would like to do is use something like the `_5_mins` function to be called
every 5 mins with a `LoopingCall`
import sys
import re
from twisted.internet import reactor, task, de... |
Python CSV module, add column to the side, not the bottom
Question: I am new in python, and I need some help. I made a python script that takes
two columns from a file and copies them into a "new file". However, every now
and then I need to add columns to the "new file". I need to add the columns on
the side, not the b... |
Python Class Inheritance : dict how to pickle(save, load)
Question: I'm playing around with class inheritances and I'm stuck on how to pickle data
in the class dictionary.
If dump only the dictionary part of self, when I load the dictionary back to
self, self takes on a dict type instead of a class. But if I pickle th... |
How to process xml files in python
Question: I have a ~1GB XML file that has XML tags that I need to fetch data from. I
have the XML file in the following format (I'm only pasting sample data
because the actual file is about a gigabyte in size).
**report.xml**
<report>
<report-name name="ALL_TIME_... |
Python pygame continuos image loading FPS
Question: Using pygame on a linux machine, continuously loading new images and
displaying them slows down the program.
The input images (400x300) are in PPM format to keep the file size constant
(360K) - not to affect IO and avoid any decompression delays.
It starts off at 50... |
ImportError: cannot import name BaseHTTPRequestHandler
Question: I try to run first example from [python
wiki](http://wiki.python.org/moin/BaseHttpServer) and when I try to run it:
$ python BaseHttpServer.py
I get an error **AttributeError: 'module' object has no attribute
'BaseHTTPRequestHandler'*... |
How can I iterate over a data file without code duplication in python?
Question: I want to write a script to process some data files. The data files are just
ascii text with columns of data, here is a simple example...
The first column is an ID number, in this case from 1 to 3. The second column
is a value of interest... |
Alter each for-loop in a function to have error handling executed automatically after each failed iteration
Question: This question follows from [catch errors within generator and continue
afterwards](http://stackoverflow.com/questions/13645112/catch-errors-within-
generator-and-continue-afterwards)
I have about 50 si... |
What happens to file descriptors in Python 3 when .close() fails?
Question: The following Python 3 code exhibits some strange behavior (to me, at least)
when I run it through `strace`:
import os
import sys
if len(sys.argv) != 2:
print('Usage: ecpy <filename>')
sys.exit(1)
try... |
Is "cgi.escape" necessary in a Python application?
Question: Was looking over a developer's code. He did something that I have never seen
before in a Python application. His background is in PHP and is just learning
python, so I don't know if this is perhaps a holdover from the different
system architectures that he is... |
How to add multiple files to py2app?
Question: I have a python script which makes a GUI. When a button 'Run' is pressed in
this GUI it runs a function from an imported package (which I made) like this
from predictmiP import predictor
class MiPFrame(wx.Frame):
[...]
def runmiP(self, ev... |
How to test functions that throw exceptions
Question: > **Possible Duplicate:**
> [How do you test that a Python function throws an
> exception?](http://stackoverflow.com/questions/129507/how-do-you-test-that-
> a-python-function-throws-an-exception)
I have to do white-box and black-box testing so i`m wondering how... |
How to change the layout of a Gtk application on fullscreen?
Question: I'm developing another image viewer using Python and Gtk and the viewer is
currently very simple: it consists of a `GtkWindow` with a `GtkTreeView` on
the left side displaying the list of my images, and a `GtkImage` on the right
side, displaying the... |
Why am I getting DistributionNotFound error when I try to run Pyramid project?
Question: **I installed in my new Windows 8 (x64):**
* python-2.7
* pywin32-218.win32-py2.7
* setuptools-0.6c11.win32-py2.7
* and pyramid (via easy_install)
I tried to run my pyramid project:
pserve I:\Projects\Py... |
Rotation an object around his center using vpython
Question: I'm making a moonlander game using VPython. The moonlander itself must be able
to rotate around his own center, but he rotates around the wrong axis and/or
around his original position instead. The axis and position where it has to
rotate around don't change ... |
Python: Searching for Unicode string in HTML with index/find returns wrong position
Question: I am trying to parse the number of results from the HTML code returned from a
search query, however when I use find/index() it seems to return the wrong
position. The string I am searching for has an accent, so I try searching... |
gtkSwitch in pygtk 2 on windows
Question: I'm creating a python program to switch some hardware devices on and off. The
program has to run on windows. I would really like to use the [gtkSwitch
widget](http://developer.gnome.org/gtk3/3.0/GtkSwitch.html) that was created
in gtk 3.0, because then it is immediately obvious... |
Finding the optimal set of pairwise alignments from a similarity matrix, with some wrinkles, in Python
Question: I am trying to find the best alignment of two sequences from a similarity
matrix. Higher values indicate better alignments.
import numpy as np
a = np.array([
[0,5,5,5,5,5,5,5],
[3,... |
application error on google app engine launcher
Question: I am getting this error while running an application on google app engine
launcher. This is the error i am getting. I have tried reinstalling but it
didnt solve the error. Please tell me where i am going worng?!
<type 'exceptions.ImportError'> Pyt... |
ImportError: cannot import name timezone
Question: After installing django-norel, and running `python manage.py shell`, I get
this error:
>>> from django.utils import timezone
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: cannot import name timezone
... |
With python, how can I connect to and download files from, a WebDAV server?
Question: My school has a webdav file server that contains files that I frequently need
to download. For this server, I have a username and password that I can use to
connect to the server, and If I go to the URL in chrome I can view everything... |
Import error? (PYTHON 3.2)
Question: I have my own module named v_systems, and I'm trying to import that module in
another python file (which is also saved in the same directory as the file
v_systems is saved) I need to import it as `import v_systems as vs` or even if
I try to import as `import v_systems`.
However it ... |
Python and displaying HTML
Question: I've gotten pretty comfortable with Python and now I'm looking to make a
rudimentary web application. I was somewhat scared of Django and the other
Python frameworks so I went caveman on it and decided to generate the HTML
myself using another Python script.
Maybe this is how you d... |
Stream Parse Wiki Xml dump
Question: I'm not sure if this question has been asked before but it has been I couldn't
find it and please pardon my ignorance. I want to parse (stream parse)
wikipedia xml dumps that are about 40 Gigs. I'm trying to use lxml iterparse
aka stream parser to do this job for me but the code I w... |
asynchronous subprocess with Popen
Question: Using Windows 7 + python 2.6, I am trying to run a simulation model in
parallel. I can launch multiple instances of the executable by double-clicking
on them in my file browser. However, asynchronous calls with `Popen` result in
each successive instance interrupting the prev... |
Instantiating an object in a function - Python
Question: I'm relatively new to python but think I have a decent enough understanding,
except for (apparently) the correct way to use the "import" statement. I
assume that's the problem, but I don't know.
I have
from player import player
def initia... |
Twitter Python program giving connection error
Question: I am working on a Twitter data mining application in Python, using the modules
twitter and redis, based upon the book "Mining the Social Web" by Matthew
A.Russell. Whenever I try to get the information of friends and followers
using the redis module, it gives me ... |
Dictionary object to decision tree in Pydot
Question: I have a dictionary object as such:
menu = {'dinner':{'chicken':'good','beef':'average','vegetarian':{'tofu':'good','salad':{'caeser':'bad','italian':'average'}},'pork':'bad'}}
I'm trying to create a graph (decision tree) using pydot with the 'm... |
Downloading YouTube Captions with API in Python with utf-8 characters
Question: I'm using [Jeff's demo code](http://gdata-
samples.googlecode.com/svn/trunk/gdata/captions_demo.py) for using the YouTube
API and Python to interact with captions for my videos. And I have it working
great for my videos in English. Unfortun... |
How to make a list of characters in Python
Question: My exam question asks me to take two letters as inputs, and display all
letters in the alphabet between the two inputs (inclusively). It also needs to
do this in the order the user input them (so GA produces `GFEDCBA` not
`ABCDEFG`). How would I approach this task?
... |
how to include django templates in app installed via pip?
Question: I'm working on a django app ([django-
flux](https://github.com/deanmalmgren/django-flux)) and I'm trying to get it
to properly install with pip from
[pypi](http://pypi.python.org/pypi?name=django-
flux&version=0.1.0&%3aaction=display). From [this blog
... |
I'm trying to print this array to a text file but only boxes show up, why? Python
Question:
import numpy as np
with open('matrix.txt', 'r') as f:
x = []
for line in f:
x.append(map(int, line.split()))
f.close()
a = array(x)
l, v = eig(a)
L = ident... |
Check if image is black
Question: I'm running a Python script under Windows which deals with 480x800 `PNG`
images with 32-bit depth. I need to check if the given image is fully black or
not. After some searching I've found that ImageMagick could help me to achieve
this but unfortunately there's no manual for such task.... |
PythonMagic: How do a composite with a dissolve value?
Question: I like to do this with PythonMagick:
composite -dissolve 40 over.png base.png new.png
I have tried:
import PythonMagick
base = PythonMagick.Image("base.png")
over = PythonMagick.Image("over.png")
base.compos... |
Effective way to get part of string until token
Question: I'm parsing a very big csv (big = tens of gigabytes) file in python and I need
only the value of the first column of every line. I wrote this code, wondering
if there is a better way to do it:
delimiter = ','
f = open('big.csv','r')
for li... |
python-dev installation error: ImportError: No module named apt_pkg
Question: I got stuck in a problem. I am Debian user, and I want to install python-dev,
but when I run the code in the shell as a root:
# aptitude install python-dev
I get the following error:
Traceback (most recent ... |
Using exec vs import in python
Question: In django it's very common to use a `local_settings.py` file to supplement
`settings.py` so that each machine can have different settings. Usually people
do something like this.
try:
from local_settings import *
except ImportError:
print "No lo... |
Get the runpath of a python console-script
Question: Short of it - I need to get a console_script to return to me its current run
path, so that I can override modules it is using at run time.
Here is my basic setup (summarized as best I could):
package_1:
caller_module.py
cons... |
Python : getsize not defined
Question: I am trying to sort the files based on their size and store the log in a file.
But I get an error that says 'getsize' not defined. Please help me fix this.
from ClientConfig import ClientConfig
import os
import os.path
class VerifyFileNSize:
... |
Pig UDF running on AWS EMR with java.lang.NoClassDefFoundError: org/apache/pig/LoadFunc
Question: I am developing an application that try to read log file stored in S3 bucks
and parse it using Elastic MapReduce. Current the log file has following
format
-------------------------------
COLOR=Black
... |
How to parse this special config file in python?
Question: I have some config files and the data format can't be changed.
One of them looks like this:
root {
configuration {
field_a: "aaaa"
field_b: "bbbb"
}
child {
configuration {
field_a: "aaa1"
... |
String segmentation with html tags in python
Question: I am trying to break a string into smaller segments using Python. The various
cases can be:
str1 = "Hello world. This is an ideal example string."
Result: Hello world.
This is an ideal example string.
str2 = "`<H1>`Hello world.`</H1><P>`This is an HTML examp... |
Opening/running Excel file from python
Question: I need to start excel and open a file directly from python. Currently I am
using:
import os
os.system('start excel.exe file.xls')
However I do not get desired result. I want to open a file from local
destination (file is in the same folder with p... |
Way too slow wxPython application getting data from Google Spreadsheet and User input needs speed up solution
Question: I want to make an application that reads out city names, road names, and
distances between them from a Google Spreadsheet with several worksheets.
So far I have the code bellow working right. It read... |
Arduino, python, pyserial and socket
Question: I am trying to write a simple webserver on an Arduino to test a few things,
but I couldn't find my Arduino with Ethernet on it.
"No worries" I thought, "I'll just write a socket server in python that acts
as a proxy for the serial connection".
import socket... |
skip excel lines with python
Question: I am making a Python script that parses an Excel file using the `xlrd`
library. What I would like is to do calculations on different columns `if` the
cells contain a certain value. Otherwise, skip those values. Then store the
output in a dictionary. Here's what I tried to do :
... |
python dictmixin object with property decorator
Question: I was instructed to use more pythonish way of setter and getters @property. So
we have something like this:
from UserDict import DictMixin
class A(dict):
def __init__(self, a, b):
self.a = a
self.b = b
... |
How do I open a .py file in python from a .py file in pypy?
Question: My program currently consists of 2 .py files.
I run the main part of the code in pypy (which is much faster) and then I open
a second file in python that plots my data using `matplotlib.pyplot`.
I have managed to open the using:
subp... |
best way to visualize google map in python
Question: I am wondering which is the best way to visualize google's map using python
and pygtk, for now I have tried this:
import gtk
import webkit
win = gtk.Window()
win.set_default_size(600, 400)
web = webkit.WebView()
web.open('https://go... |
ctypes/C++ segfault accessing member variables
Question: I am no stranger to the python ctypes module, but this is my first attempt at
combining C++, C and Python all in one code. My problem seems to be very
similar to [Seg fault when using ctypes with Python and
C++](http://stackoverflow.com/questions/12142766/seg-fau... |
'==' operator not working correctly in python
Question: Following piece of code is behaving incorrectly in my script :
from ctypes import *
base_addr = c_uint64(0)
base_addr_temp = c_uint64(0)
print base_addr
print base_addr_temp
if(base_addr == base_addr_temp):
print "val"
... |
How to selet a specific Test with python unitest testsuites
Question: I have python unittest code organized as follows:
Maindir
|
|--Dir1
| |
| |-- test_A.py
| |-- test_B.py
| |-- test_C.py
|
|--Dir2
| ...
I assume you get the p... |
Estimating an Affine Transform between Two Images
Question: I have a sample image:

I apply the affine transform with the following warp matrix:
[[ 1.25 0. -128 ]
[ 0. 2. -192 ]]
and crop a 128x128 part from the r... |
Easiest way to draw tree diagrams?
Question: I want to have a program which generates diagrams for trees, ones looking
pretty much like [this](http://i.imgur.com/P11MX.jpg)
It is to be a part of a project I am working on using C#, but if there is a
way to make a Python or Javascript do it, that be okay as well. Maybe ... |
What is the naming convention for Python class references
Question: What is the naming convention for a variable referencing a class in Python?
class MyClass(object):
pass
# which one is correct?
reference_to_class = MyClass
# or
ReferenceToClass = MyClass
Here is ... |
Selecting conserved residues in protein using PyMol script by importing residue list from a text file
Question: I wanted to select certain highly conserved residues in a protein (computed by
a scoring mechanism and listed in a text file - each residue in a single line)
using a PyMol script. The PyMol script below that ... |
python script to open excel workbook, and change the name of the first worksheet and execute stored proc
Question: i have this python script that's supposed to open an excel workbook from
directory and then change the name of the first worksheet and then run a
stored procedure on the first worksheet and the subsequent ... |
Changing str to int in Python
Question: I am new to python. I am trying to make a small elavator program.
The code:
import time
elavator = True
# 0 is B floor // basement
elavatorFloors = [0,1,2,3,4,5]
while elavator == True:
getLevel = input ("Which floor would you like to ... |
Python MultiThreading Queue suddenly stops doing anything
Question: I have a file that contains 600K+ lines of stuff I want to process.
So I use multithreading to speed up the process.
But the problem is for example I use 50 as the number of threads, after
processing 50 lines the script just does nothing else. It d... |
Django 1.5b1: executing django-admin.py causes "No module named settings" error
Question: I've recently installed Django-1.5b1. My system configuration:
* OSX 10.8
* Python 2.7.1
* Virtualenv 1.7.2
When I call **django-admin.py** command I get the following error
(devel)ninja Django-1.5b1: django... |
Loop patchwork in python3
Question: I need to create a patchwork in Python 3. All I have left to do is create a
loop which makes the design border the graphics window. I know I need a for
loop however I am not sure how to do this.
This is what I have so far:
from graphics import *
def main():
... |
calling standard python functions from rubypython
Question: I am trying to use the rubypython gem. Not sure how to call standard python
functions like len and set. In the python examples I see len(text3) and
set(text3).
How do I call these in rubypython?
Here is the link to rubypython: <http://rubypython.rubyforge.or... |
how do i write a program to click a particular link in Python
Question: My program takes an user input and searches it through a particular webpage .
Further i want it to go and click on a particular link and then download the
file present there .
Example :
1. The webpage : <http://www.rcsb.org/pdb/home/home.do>
... |
How can I provide Sphinx documentation for a namedtuple (with autodoc)?
Question: I am trying to document a Python project with Sphinx, but I'm having trouble
combining the `autodoc` extension with a `namedtuple` generated class.
In one document, `gammatone.rst`, I have:
:mod:`gammatone` -- gammatone fi... |
List all files in an online directory with Python?
Question: Hello i was just wondering i'm trying to create a python application that
downloads files from the internet but at the moment it only downloads one file
with the name i know... is there any way that i can get a list of files in an
online directory and downloa... |
Python & lxml / xpath: Parsing XML
Question: I need to get the value from the FLVPath from this link :
<http://www.testpage.com/v2/videoConfigXmlCode.php?pg=video_29746_no_0_extsite>
from lxml import html
sub_r = requests.get("http://www.testpage.co/v2/videoConfigXmlCode.php?pg=video_%s_no_0_ext... |
Python + Sqlite: Unable to determine cause of incorrect number of bindings supplied error
Question: I'll get right into it - I first created a local db for myself:
import sqlite3
conn = sqlite3.connect("tofire.db") #
cursor = conn.cursor()
# create a table
cursor.execu... |
Pickling Django QuerySet
Question:
from myapp.models import MyModel
from cPickle import *
tmp = MyModel.objects.all()[:1]
print(loads(dumps(t, -1)) == t)
#Output is "False"
In my case pickled query result differs from unpickled. I already read here:
<https://docs.djangoproject.com/en/dev... |
UnicodeEncodeError Python when creating .csv file
Question: I am trying to create a .csv file with data that I have stored into a list
from Twitter search API. I have saved the last 100 tweets with a keyword that
I chose (in this case 'reddit') and I am trying to save each tweet into a cell
in a .csv file. My code is b... |
The truth value of an array with more than one element is ambiguous error? python
Question:
from numpy import *
from pylab import *
from math import *
def TentMap(a,x):
if x>= 0 and x<0.5:
return 2.*a*x
elif x>=0.5 and x<=1.:
return 2.*a*(1.-x)
# We... |
How do I plot 3 subplots in the same display window? python
Question:
# Import plotting routines
from pylab import *
# 1D ODE that has a pitchfork bifurcation
# x_dot = r * x - x * x * x
def PitchforkODE(r,x):
return r * x - x * x * x
# 1D Euler
def OneDEuler(r,x,f,dt):
... |
bdate_range AttributeError
Question: The following lines give AttributeError: `'module' object has no attribute
'bdate_range'`.
I think this might have something to do with a circular reference; but, I
don't know where.
import pandas as pd
times = pd.bdate_range(start=pd.datetime(2012,11,14,0,0... |
Is there a way to write a Python script that creates and executes code?
Question: Is there a way in Python to create Python code inside the Python script and
then execute/test it?
My function has the following type of form (as an example)
def f(n):
if n<=3: return [0, 0, 6, 12][n]
return... |
Plotting a differentiated graph from nested lists in Python
Question: I have made a script which produces a graph from data in a nested list
(temperature and changes).
#!/usr/bin/python
import matplotlib.pyplot as plt
temperature = [['65', '65.5', '66', '66.5', '67', '67.5', '68', '68.5', '6... |
about python, I can't understand the example provided in a book
Question: I'm a new learner about python and there are some problems when I try to
repeat the example provided in a guide book. This example is about
recommendation algorithm. This example is trying to implement an item list
which stores the users having r... |
Scale imread matrix in python
Question: I am looking for a way to rescale the matrix given by reading in a png file
using the matplotlib routine imread, e.g.
from pylab import imread, imshow, gray, mean
from matplotlib.pyplot import show
a = imread('spiral.png')
#generates a RGB image, so do
... |
What does "input() already active" mean in python fileinput module?
Question: I'm trying to read 2nd line in text.txt file:
import fileinput
x = 0
for line in fileinput.input([os.path.expandvars("$MYPATH/text.txt")]):
if x < 3:
x += 1
if x == 2:
... |
text process in python
Question: I have data like this:
value1
something text
something text
And I want to change the something text with the value. Example:
value1
value1
value1
Answer: One way:
import sys
file = open('file','r')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.