text stringlengths 226 34.5k |
|---|
Python with Mysql - pdf file insertion during runtime
Question: I have a script that stores results in pdf format in a particular folder. I
want to create a mysql database ( which is successful with the below code ),
and populate the pdf results to it. what would be the best way , storing the
file as such , or as refer... |
Python search data within all XML elements
Question: Newbie - I am trying to use lxml to find "error" in any element (sample XML
file below, but it should work regardless to how nested the tags are):
<test>
<test1>
error
</test1>
<test2>
<test3>
error
... |
pydev multithread debugging
Question: I'm trying to debug an application which makes use of the pynetdicom library.
I'm not sure how relevant that specific detail is, however what IS relevant is
that it makes heavy use of multithreading to run background socket listener
tasks without blocking the main thread. The store... |
python one more stupid debug
Question: sorry, i am a bit of a pain but i damaged my code, i cannot understand what is
wrong. I just removed a if statement but now it appears the timedelta is not
recognized anymore and it breaks the code. I am pretty sure i havent removed
any of the reference though. I am scratching my ... |
sh: Syntax error: Bad fd number
Question: I need some help in running this code. I took this code from
(<http://easybioinfo.free.fr/?q=content/amber-trajectory-gromacs-xtc-
conversion>). I am trying to convert amber trajectory to gromacs trajectory.
When I execute this code, I get some errors. I paste the errors below... |
Python function scoping with import
Question: I have the following modules:
main.py
import my_import
my_import.a_func()
my_import.py
FOO = "foo"
BAR = []
def a_func():
BAR.append("bar") #ok
FOO = FOO + "foo" #UnboundLocalError:
... |
Handling unhandled exception in GUI
Question: I am mostly writing a small tools for tech savvy people, e.g. programmers,
engineers etc. As those tools are usually quick hacks improved over time I
know that there are going to be unhandled exceptions and the users are not
going to mind. I would like the user to be able t... |
subprocess and Type Str doesnt support the buffer API
Question: I have
cmd = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE)
for line in cmd.stdout:
columns = line.split(' ')
print (columns[3])
have error in line 3 Type Str doesnt support the buffer API.
What am i doing w... |
Appending a subprocess to a list seems to just append the subprocess object location in python?
Question: Using the following command at the console prints the local MAC address of
wlan0's NIC. I want to integrate this into a script where the 0th sublist of a
list will be filled with the local MAC in exer
... |
(Python Newb) Writing to file what is printed?
Question: Thanks to the kindness on this website i've installed
2.7/setuptools/feedparser all without issue.. I've figured out feedparser and
it works without issue.
I've been reading tutorials on how to write to file (text) via python, i've
had moderate success doing thi... |
Sort list of tuples by value Python
Question: I've got a list of tuples as the example:
result = [(1, 6.06), (2, 6.23), (3, 7.03), (4, 6.88), (5, 6.43), (6, 6.57)]
How can I sort the list by value in descending order?
Answer: Probably something like:
result.sort(key=lambda x:x[1],r... |
Python 3.3 - urllib.request - import error
Question: When I try to run the following Python 3.3 code on OS X 10.8 in PyCharm 2.7
(or run the .py file with the Python 3.3/2.7.3 launcher):
import urllib.request
f = urllib.request.urlopen('http://www.python.org/')
print(f.read(300))
I get the ... |
Creating an OSX PyQt app using Pyinstaller 2, PyQt4 and Qt5
Question: I am trying to package a PyQt program for OSX using PyInstaller 2, where PyQt4
(4.10) has been built against Qt 5.0.2 (from Git). The following simple
example doesn't work.
import sys
from PyQt4.QtGui import QApplication, QMessageB... |
Python: Appending a to a list from a dictionary
Question: This is going to be long but I don't know how else to effectively explain
this.
So I have 2 files that I am reading in. The first one has a list of
characters.The second file is a list of 3 characters and then it's matching
identifier character(separated by a t... |
Python islice is reading the same lines
Question: I have a big log-file (> 1GB) which should be analysed, so I wrote a python-
program. I have used `islice` so I could read the file in chunks (10,000
lines) so my server won't run out of memory.
I've looked up some `islice` solutions on stackoverflow and implemented on... |
Raspberry Pi - Rainforest EMU-2 - Python - Read time from SCE smart meter
Question: I am now to programming in Python and this is my first project. Any help would
be appreciated.
I recently obtained a device from Rainforest that reads my electric meter. The
unit has a USB port accessible via USB. I managed to hook the... |
Segmentation fault (core dumped). Using C module in python
Question: I am newbie in python and I am trying to launch python script with a module
writen on C. I am getting Segmentation fault (core dumped) error when I am
trying to launch python script. Here is a C code:
// input_device.c
#include "P... |
prevent the closure of command Prompt with Python when an "exception" occurs
Question: I have a script in Python 2.7 converted in executable with py2exe. The INPUT
data is a text file where the delimiter need to be valid following this
function:
# Check if delimeter is valid
def get_parse(filename, d... |
Create hierarchical python object where arguments to methods are from hierarchy
Question: There is an existing module I use containing a class that has methods with
string arguments that take the form:
existing_object.existing_method("arg1")
or
existing_object.existing_method("arg1:a... |
What option do I need in setup.py to create the package in the right directory?
Question: I am using `setup.py` to create a python package, which I want to install via
`pip`. To correctly install the files under
lib/python2.7/site-packages/<package-name>
I used the following option in `setup.py`:
... |
running script multiple times simultaniously in python 2.7
Question: Hello I am trying to run a script multiple times but would like this to take
place at the same time from what I understood i was to use subprocess and
threading together however when i run it it still looks like it is being
executed sequentially can s... |
python threading in a loop
Question: I have a project that requires a bunch of large matrices, which are stored in
~200 MB files, to be cross-correlated (i.e. FFT * conj(FFT)) with each other.
The number of files is such that I can't just load them all up and then do my
processing. On the other hand, reading in each fi... |
Principal Component Analysis (PCA) - accessing shape
Question: I am a beginner in python and I am trying to apply Principal Component
Analysis (PCA) to a set of images. I want to put the images in a matrix to be
able to perform PCA. I am still at the beginning but I am having errors.
import numpy as np
... |
python: writing HTML in python function. syntaxError: expected an intended block
Question: i am trying to generate a html checkbox within a python function. this is my
code
import HTML
def CreateEvent(str):
"This prints a passed string into this function"
print str;
return;
... |
Gtk/python and portability
Question: How do programmers write portable UI code that works on multiple
distributions? I am considering desktop distributions and not
specialized/embedded distributions. For writing UI applications, you have to
assume certain things will be available on the platform either as standard or
b... |
"StackHash_0a9e error" when exit from python
Question: I'm a beginner of python,I wrote a small program, when I exit the program,
sometimes (more than 50% probability) it show an error.This occurred only
after I **exit** the program.Could you please help me to find is there
something wrong with my code.
Really thanks.... |
How to package a python program with pyqt4 module by cxfreeze
Question: I wrote a program using PyQt4.QtGui and QtCore,I packaged it into exe,and it
works good on my computer,but it can't run on others' computer
**The error is this:**
cx_Freeze: Python error in main script
--------------------------... |
python how to access input params in MagicMock?
Question: I want to add a unit test for the function 'method_a':
def method_a(some_thing):
#some logic here
return update({'a':1}, request=some_thing)
def update(value, request):
if request:
return value.update({'b... |
Memcached doesnt allow to cache item larger that 1mb limit even if it was overrided
Question: Using `python-memcached==1.48`
Terminal:
memcached -I 10m
Python:
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "licens... |
Why does my parallel performance top out?
Question: I've been playing around with Python a lot lately, and in comparing numerous
parallelization packages, I noticed that the performance increase from serial
to parallel seems to top out at 6 processes instead of 8--the number of cores
my MacBook Pro (OS X 10.8.2) has.
... |
Opening multiple python files from folder
Question: I am trying to take a folder which contains 9 files, each containing FASTA
records of separate genes, and remove duplicate records. I want to set it up
so that the script is called with the folder that contains the genes as the
first parameter, and a new folder name t... |
Creating a regular expression in django
Question: New to Django so I'm unsure how to achieve the following...
I have this regular expression
"@£$¥èéùìòÇ\fØø\nÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&'()*+,-./[0-9]:;<=>\?¡[A-Z]ÄÖÑܧ¿[a-z]äöñüà\^\{\}\[~\]\|€"
I have this function:
def validate_GSM_ch... |
Neo4J - Simple "follower" graph
Question: I'm attempting to create a simple Twitter-esque "follower / friend" graph
using Neo4J and Python. The graph would look something like
user_1 FOLLOWS user_2
user_1 FOLLOWS user_3
user_2 FOLLOWS user_1
After a day of reading I thought it best to dive ... |
How to get file names from Web directory - Python code
Question: I would like to know how to get a list of filenames (.jpg image files) that
are stored on a server.
I am looking for code which stores all the filenames (with their extension) in
an Excel table or in the CSV format.
Any tips will be very helpful.
Answ... |
Python: custom logging across all modules
Question: **Task**
I have a collection of scripts and I'd like them to produce unified logging
messages with minimum alterations to modules doing logging the actual
messages.
I've written a small module 'custom_logger' which I plan to call from the main
application once, have... |
run python script as cgi apache server
Question: I am trying to make a python script run as cgi, using an Apache server. My
script looks something like this:
#!/usr/bin/python
import cgi
if __name__ == "__main__":
print("Content-type: text/html")
print("<HTML>")
print... |
Special characters in audio devices name : Pyaudio
Question: I'm currently facing a hard problem. I need to use Pyaudio on a french windows
environnement and the name of the audio devices contains `é` or `è` by
default.
This is the error I get when a special character is present:
u=self.p.get_device_... |
Python: splitting a complex string including parentheses and |
Question: In a test file, I have records in the form
DATA(VALUE1|VALUE2||VALUE4)
and so on.
I'd like to split this string in two passes, the first yielding "DATA", and
the second giving me what's inside the parentheses, split at the "|... |
Python extract values from JSON
Question: I'm looking to extract sets of values from a JSON and write them to a file.
The format of the JSON is as follows:
"interactions": [
{
"type": "free",
"input": [
[ 1, 4594, 119218, 0, [71, 46], [... |
installing my first WSGI
Question: I am installing a flask app with apache modewsgi.
I have solved multiple troubles already: \- environment variables \-
virtualenv \- file permissions
But now I am really stuck with application name. I have no idea what to write
in the "from" directive of WSGI file.
here is my ~user... |
segmentation fault in python
Question: How can I run the following program in python 2.7.3
import sys
sys.setrecursionlimit(2 ** 20)
def f(x):
if (x==0): return 0
else: return f(x-1)+1
print f(200000)
This code receives segmentation fault in Ubuntu.
Answer: The Python ... |
Accessing python parent folder
Question: I've looked through previous answers which seem to suggest I should be able to
use:
from .. import code
though it produces this: ValueError: Attempted relative import beyond toplevel
package
though this doesn't seem to be working. My file structure is as fo... |
Getting a lists of times in Python from 0:0:0 to 23:59:59 and then comparing with datetime values
Question: I was working on code to generate the time for an entire day with 30 second
intervals. I tried using DT.datetime and DT.time but I always end up with
either a datetime value or a timedelta value like (0,2970). Ca... |
Game Development in Python, ruby or LUA?
Question: I have experience in game development in some game engines in Action Script 3
and C++. However, I would like to improve the productivity and so I want to
develop a new project in Python, ruby or LUA. Would it be a good idea? If yes,
which one would you suggest? and wha... |
Using C datatypes with ctypes in python
Question: I tried to use C char pointer datatype in python 3.3. I used following code:
from ctypes import *
firstname = c_char_p("I am a noob programmer".encode("utf-8"))
print(firstname.value)
My desired output was
... |
Graphs in xlsx File overwrite by openpyxl
Question: We need to update xlsx sheet using python script which do some calcualtion and
update one worksheet. I choose openpyxl as it supoort writing/updating xlsx
File. In the Excel sheet contain some graphs also but When I update excel
sheet than graph does not work into exc... |
Basic Python programming, calculating probabilities of random locations falling within regions using arrays of random locations
Question: Consider a 100X100 array.
* Generate an array of several thousand random locations within such an array, e.g. (3,75) and (56, 34).
* Calculate how often one of your random locat... |
displaying files from a directory using Bootstrap Carousel
Question: I am new to JavaScript and started experimenting with Bootstrap Carousel. I
wrote test code that works and displays images when I manually create the
Carousel items, e.g
<div id="myCarousel" class="carousel slide" data-interval="fals... |
how to run my own external command in python script
Question: I wanna to run my own non-system external commands in python.
Such as "sudo insteon on 23". Subprocess and os.system are designed for system
calls.
Does anybody know how to do it?
Thanks
Answer: You can use
[subprocess.Popen](http://docs.python.org/2/li... |
python pexpect: SSHing then updating the date
Question: I have finally have my python pexpect script working except for the most
important part updating the date! I am able to SSH in the box but my second
command does not execute properly. I have been banging my head on the wall
trying to figure out why. I have checked... |
Unexpected Syntax Error using '<' and '>'
Question: I have been set a simple task:
Write a program for a game where the computer generates a random starting
number between 20 and 30. The player and the computer can remove 1,2 or 3 from
the number in turns. Something like this... Starting number : 25 How many do
you wa... |
How to add a filter function in couchdb with python?
Question: I know i can use couchdb.ViewDefinition to create a view for a database.Is
there something similar to create a changes filter function or I can just
create a design document with the filters field?
Answer: Currently there is no such what unless you'll ope... |
RabbitMQ - pika - rabbit.js - node.js
Question: I'm using Python, rabbitmq, pika, rabbit.js and node.js.
The idea is to send messages to clients and act accordingly. There are
multiple types of messages being sent.
So, on the server side I have a method which will receive the message and the
exchange to send the mess... |
qsub python import
Question: I'm running a job on the cluster for the first time. I run it with the
following command:
qsub -cwd -S /usr/bin/python myScript.py
I have a python script that starts with:
import time
import anotherScript
The error I get:
Tracebac... |
Unable to redirect python script result to a text file in windows
Question: Here is my python code.I'm trying to do elastic search in python.
from pyes import *
from pyes.mappings import *
conn = ES('http://search.twitter.com/search.json?q=poplio')
conn.indices.create_index("test-index")
... |
numerical ODE solving in python
Question: I am new to Python so at this moment in time, I can only very basic problems.
How do I numerically solve an ODE in Python?
Consider

\ddot{u}(\phi) = -u + \sqrt{u}
with the following conditions
... |
Naive multiprocessing in Python with NumPy
Question: Despite the warnings and confused feelings I got from the ton of questions
that have been asked on the subject, especially on StackOverflow, I
paralellized a naive version of an embarassingly parallel problem (basically
**read-image-do-stuff-return** for a list of ma... |
manage.py syncdb not working
Question:
DJANGO@linux-l94a:~/Desktop/myblog> ./manage.py syncdb
Traceback (most recent call last):
File "./manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/site-packages/django/core/management/init.py", line 443, ... |
tornado.database Importerror: No module named database
Question: I'm using a fork of Bret Taylor's 'socialcookbook'
(<https://github.com/finiteloop/socialcookbook>) which uses "import
tornado.database" - and it's worked perfectly until yesterday (the 3.01
build?) and now I'm getting an ImportError: no module named data... |
Error importing pymongo in my django app
Question: I'm trying to insert documents into mongodb from django and I'm getting an
error on the import statement for pymongo. I don't have a duplicate file
anywhere called pymongo and I'm pretty sure my virtualenv is set up correctly.
(django-sample-app)ubuntu@d... |
How to get UTC time in Python?
Question: I've search a bunch on StackExchange for a solution but nothing does quite
what I need. In JavaScript, I'm using the following to calculate UTC time
since Jan 1st 1970:
function UtcNow() {
var now = new Date();
var utc = Date.UTC(now.getUTCFullYear... |
Bugs drawing with turtle(python) using onkey() and dictionaries
Question: I decided redo this question as per advice I received, This is an assignment
question I have been given for 1st year uni, python coding. I have bugs in my
code and Can't figure out where to fix them. BUG 1 The turtle starts drawing
when program i... |
Is there a way to add metadata in py files for grouping tests?
Question: Lets say I have the following testcases in different files
* TestOne.py {tags: One, Two}
* TestTwo.py {tags: Two}
* TestThree.py {tags: Three}
Each of which inherits from unittest.TestCase. Is there any ability in python
to embed metadat... |
Python import module vs import _module
Question: While configuring PyDev's [Forced
Builtins](http://pydev.org/manual_101_interpreter.html#PyDevInterpreterConfiguration-
ForcedBuiltins) in Aptana I noticed that some modules were referenced by
default with an `_` (underscore) prefix.
So I open a Python interpreter and t... |
Plotting cosine with Python
Question: I plot a cosine sampled at 400 points in the interval -5 .. +5 using python
for n=1..4:
import matplotlib.pyplot as plt
import numpy
for n in range(1,5):
x = numpy.linspace(-5,5,num=400)
series = numpy.cos(1e4/n*x)
plt.figure()
... |
About piping stdio and subprocess.Popen
Question: I have one Python program, that is opening another Python program via
`subprocess.Popen`. The 1st is supposed to output some text into the console
(just for info), and write some text to the 2nd program it had spawned. Then,
it should wait for the 2nd program to respond... |
Why is my startup script not running
Question: Per various tutorials I've done the following:
created a file called `ftpserver.py` in `/home/root/`
created a file in `/etc/init.d/` called `ftpserver` that looks like this"
#!/bin/sh
python /home/root/ftpserver.py
Upon creation, I ran the follo... |
Issuing application-only requests in Twitter 1.1 using Python
Question: I want to access Twitter 1.1 search endpoint using application-only
authentication. To do the same, I'm trying to implement the steps given on
Twitter API's documentation here -
<https://dev.twitter.com/docs/auth/application-only-auth> (scroll to "... |
How do I parallely check for existence of an item across multiple lists in Python?
Question: As a part of my project, for every word in the dictionary d (shown in the
example code snippet below), I need to check for its existence across
different lists `f1, f2, f3`. I have shown only 3 lists here. And based on the
occu... |
Is there a builtin function version of `and` and/or `or` in Python?
Question: This question is for fun; I don't expect the answer to be useful.
When I see people doing things with `reduce()` in Python, they often take
advantage of a builtin function in Python, often from the `operator` module.
This works:
... |
Adding quotes to words using regex in Python
Question: I am trying to replace each word in a sentence with the same word but quote
(by word I mean just letters, no numbers) using regex.
For example `4 python code` should be converted to `4 "python" "code"`.
But this code produce the wrong result
>>> im... |
python try/except with urllib2 throwing odd exception
Question: Function looks like:
def fetchurl(url):
timeout = 10
try:
res = urllib2.urlopen(url, timeout=timeout)
reader = csv.reader(res)
reader.next() # Trim the CSV header
return re... |
How to assign module name to a variable?
Question: I would like to dynamically let the user chose which body of data he/she would
like to work with. To do this, after the user identifies their "corpus" of
choice, I must import the appropriate corpus. (I am running on Python 2.7.3)
corpora_ls = ["gutenber... |
OpenCV 2.4 estimateAffine3D in Python
Question: I'm trying to use the method cv2.estimateAffine3D but without success. Here is
my code sample :
import numpy as np
import cv2
shape = (1, 4, 3)
source = np.zeros(shape, np.float32)
# [x, y, z]
source[0][0] = [857, 120, 854]
... |
python numpy.convolve to solve convolution integral with limits from 0 to t instead -t to t
Question: I have a convolution integral of the type:

To solve this integral numerically, I would like to use `numpy.convolve()`.
Now, as you can see in the ... |
Python Interpreter Mode - What are some ways to explore Python's modules and its usage
Question: While inside the Python Interpreter:
What are some ways to learn about the packages I have?
>>> man sys
File "<stdin>", line 1
man sys
^
SyntaxError: invalid syntax
... |
Matplotlib and subinterpreter for embedded python in c++
Question: I just added subinterpreter to my c++ embedded python editor to have a clean
interpreter for each execution.
PyThreadState* tmpstate = Py_NewInterpreter();
PyThreadState_Swap(tmpstate);
... run the script ...
Py_EndInt... |
Python Suds Soap Client Error
Question: I am trying to connect to a web service using Python/SUDS.
I have the following code in a single file and I am able to connect
successfully and I receive a response.
class Suds_Connect:
def __init__(self, url, q_user, q_passwd):
logging.ba... |
get value of a variable from a python script
Question: I have a python script that returns a json object. Say, for example i run the
following:
exec('python /var/www/abc/abc.py');
and it returns a json object, how can i assign the `json` object as a variable
in a php script.
### Example python scr... |
Orange Python data load error: "example of invalid length"
Question: I am trying to load a .csv file using python & Orange (machine learning
package) and getting an error. I have 208 columns but in the error I only see
few columns and after that nothing. What does the error mean?
example of invalid lengt... |
ipython install new modules
Question: I am used to the R functionality of installing packages and I am trying to do
the same thing with ipython. Sometimes the following method works but then
again sometimes it doesn't and I would like to finally find out why it only
works half the time.
Normally to install a module (l... |
Django CMS Custom Plugin doesn't render the template
Question: Running a fresh install of django-cms 2.4.0-RC1, django 1.5.1 and python 2.7.
I'm trying to create a very simple custom plugin with a single field. The
plugin registers in the admin and works fine. It successfully stores in the
database. It's just not rende... |
getting an error while using time sleep method in python
Question: There is a weblogic python script that takes a thread dump and sleeps for 10
or 20 seconds then takes another one after time.sleep(30), thread dumps are
working fine, but the sleep method time.sleep(20) is not working.
Tried both `import time` and `fro... |
Django/Python: How to group queryset results by date?
Question: I have a model for image uploads, that looks something like this:
from django.db import models
from django.contrib.auth.models import User
import datetime
class ImageItem(models.Model):
user = models.ForeignKey(User)... |
Python won't run due to ImportError: cannot import MAXREPEAT
Question: I am new to python but have been using both IDLE and EricIDE for a few weeks
without any major problems.
I was editing a program I had written that called `random.randint()` function
and it wouldn't work.
Previously, this program had been working... |
os.walk to find path to file issue (Python 2.7)
Question: I've just starting using python 2.7 and was using the following code to
ascertain the path to a file:
import os, fnmatch
#find the location of sunnyexplorer.exe
def find_files(directory, pattern):
for root, dirs, files in os.w... |
Python lambda to print formatted nested list
Question: Practicing a couple things: lambda functions and string manipulations. I want
to find the most efficient ways of doing this without importing anything.
so here's a short script that reorders a word alphabetically:
def alphabeticalOrder(word):
... |
Efficiently Reading Large Files with ATpy and numpy?
Question: I've looked all over for an answer to this one, but nothing really seems to
fit the bill. I've got very large files that I'm trying to read with ATpy, and
the data comes in the form of numpy arrays. For smaller files the following
code has been sufficient:
... |
python list to dictionary with dates as keys
Question: I'm trying to create a dictionary from this list using dates as keys and
successive items as its value.
lst = ['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm... |
Fast, small, and repetitive matrix multiplication in Python
Question: I'm looking for a way to very quickly multiply together many 4x4 matrices
using Python/Cython/Numpy, can anyone give any suggestions?
To show my current attempt, I have an algorithm which needs to compute
A_1 * A_2 * A_3 * ... * A_N
... |
ComplexWarning when calling convolve2d() in SciPy, why?
Question: When I run
from scipy.signal import convolve2d
convolve2d([[2, 2, 2], [1, 2, 3], [0, 1, 0]], [[0.5], [0.5]], 'valid')
I get
Warning (from warnings module):
File "C:\Program Files\Python 2.7\lib\site-packages\... |
Python 3.3 undefined references with static linking
Question: Operating System: Ubuntu 12.04 x86_64
I've compiled libpython3.3m.a from source, along with the related headers. I
wrote the following Makefile (specifically, look at my CFLAGS variable, which
includes -lpython3.3m)...
BINS=python python-d
... |
Pylint - How to print Pylint's sys.path?
Question: I'm attempting to add modules to my Pylint path so they can be imported by
using the solution as [seen in this
question](http://stackoverflow.com/questions/1899436/pylint-unable-to-import-
error-how-to-set-pythonpath). Unfortunately, the modules I expect should be
avai... |
LinkedIn API Python Key Error 2.7
Question: This code is available online to run a map of your connections in linkedin
This uses linkedin api. I'm able to connect fine and everything runs okay till
the last script of actually writing the data to a csv.
Whenever I run the code
import oauth2 as oauth
... |
Importing django modules from java
Question: I am trying to call some classes from my django project using Java. Here is my
code:
PythonInterpreter interpreter = new PythonInterpreter();
PySystemState sys = Py.getSystemState();
sys.path.append(new PyString("/Librar... |
How to print commands in Python?
Question: I'm not in the programming area but I recently got interested in Python. I was
writing some functions but for debugging I need to see what commands are
running. For instance:
def foo():
for i in xrange(0,5):
a = 1 + i
Is it possible to ... |
Python: How to hash a string into 8 digits?
Question: Is there anyway that I can hash a random string into a 8 digit number without
implementing any algorithms myself? Thanks.
Answer: Yes, you can use the built-in
[_hashlib_](http://docs.python.org/2.7/library/hashlib.html#module-hashlib)
modules or the built-in
[_ha... |
What's the best way to find unique unhashable unorderable types in Python 3
Question: So in Python 2 you could use something like
>>> items = [[1, 2], [3], [3], 4, 'a', 'b', 'a']
>>> from itertools import groupby
>>> [k for k, g in groupby(sorted(items))]
[4, [1, 2], [3], 'a', 'b']
Whic... |
Decoding JSON with Python
Question: Why do I get
> ValueError: No JSON object could be decoded
from this code:
import urllib.request,json
n = urllib.request.urlopen("http://graph.facebook.com/55")
d = json.loads(str(n.readall()))
The full error:
Traceback (most recent... |
Reading Web-Based XML file and parsing it in Python
Question: I am very new to Python and GAE but I am attempting to download an XML file
from the eventful.com api (in XML), parsing it and I will then storing this
information within a database on Google Cloud SQL.
My code so far is as follows which I have managed to w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.