When I try to write a field that includes whitespace in it, it gets split into multiple fields on the space. What's causing this? It's driving me insane. Thanks
data = open("file.csv", "wb")
w = csv.writer(data)
w.writerow(['word1', 'word2'])
w.writerow(['word 1', 'word2'])
data.close()
I'll get 2 fields(word1,word2) for first example and 3(word,1,word2) for the second.
I have a dictionary of the following form
a = {'100':12,'6':5,'88':3,'test':34, '67':7,'1':64 }
I want to sort this dictionary with respect to key as following
a = {'1':64,'6':5,'67':7,'88':3, '100':12,'test':34 }
Please help
I was unsuccessful browsing web for a solution for the following simple question:
How to draw 3D polygon (say a filled rectangle or triangle) using vertices values?
I have tried many ideas but all failed, see:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
x = [0,1,1,0]
y = [0,0,1,1]
z = [0,1,0,1]
verts = [zip(x, y,z)]
ax.add_collection3d(PolyCollection(verts),zs=z)
plt.show()
I appreciate in advance any idea/comment.
Updates based on the accepted answer:
import mpl_toolkits.mplot3d as a3
import matplotlib.colors as colors
import pylab as pl
import scipy as sp
ax = a3.Axes3D(pl.figure())
for i in range(10000):
vtx = sp.rand(3,3)
tri = a3.art3d.Poly3DCollection([vtx])
tri.set_color(colors.rgb2hex(sp.rand(3)))
tri.set_edgecolor('k')
ax.add_collection3d(tri)
pl.show()
Here is the result:
Is there a cleaner way to write this:
for w in [w for w in words if w != '']:
I want to loop over a dictionary words, but only words that aren't whitespace. Thanks!
I understand the gist of the code, that it forms permutations; however, I was wondering if someone could explain exactly what is going on in the return statement.
def perm(l):
sz = len(l)
print (l)
if sz <= 1:
print ('sz <= 1')
return [l]
return [p[:i]+[l[0]]+p[i:] for i in range(sz) for p in perm(l[1:])]
I need to transform a list into dictionary as follows.
The odd elements has the key, and even number elements has the value.
x = (1,'a',2,'b',3,'c') - {1: 'a', 2: 'b', 3: 'c'}
def set(self, val_):
i = 0
for val in val_:
if i == 0:
i = 1
key = val
else:
i = 0
self.dict[key] = val
My solution seems to long, is there a better way to get the same results?
Hi all,
In the Getting things gnome code base I stumbled upon this import statement
from GTG import _
and have no idea what it means, never seen this in the documentation and a quick so / google search didn't turn anything up.
Thank you all in advance
Paul
Hello,guys! I am trying to run the following test
self.assertRaises(Exception,lambda:
unit_test.testBasic())
where
test.testBasic()
is
class IsPrimeTest(unittest.TestCase):
def assertRaises(self,exception,callable,*args,**kwargs):
print('dfdf')
temp = callable
super().assertRaises(exception,temp,*args,**kwargs)
def testBasic_helper(self):
self.failIf(is_prime(2))
self.assertTrue(is_prime(1))
where prime is a function,and
but in
self.assertRaises(Exception,lambda:
unit_test.testBasic())
the lambda function doesnt throws an exception after
the test
def testBasic_helper(self):
self.failIf(is_prime(2))
self.assertTrue(is_prime(1))
fails
Can somebody offers a solution to the problem?
Looking for best practice advice on what string substitution technique to use when using gettext(). Or do all techniques apply equally?
I can think of at least 3 string techniques:
Classic "%" based formatting:
"My name is %(name)s" % locals()
.format() based formatting:
"My name is {name}".format( locals() )
string.Template.safe_substitute()
import string
template = string.Template( "My name is ${name}" )
template.safe_substitute( locals() )
The advantage of the string.Template technique is that a translated string with with an incorrectly spelled variable reference can still yield a usable string value while the other techniques unconditionally raise an exception. The downside of the string.Template technique appears to be the inability for one to customize how a variable is formatted (padding, justification, width, etc).
I have a request that maps to this class ChatMsg
It takes in 3 get variables, username, roomname, and msg. But it fails on this last line here.
class ChatMsg(webapp.RequestHandler): # this is line 239
def get(self):
username = urllib.unquote(self.request.get('username'))
roomname = urllib.unquote(self.request.get('roomname')) # this is line 242
When it tries to assign roomname, it tells me:
<type 'exceptions.NameError'>: name 'self' is not defined
Traceback (most recent call last):
File "/base/data/home/apps/chatboxes/1.341998073649951735/chatroom.py", line 239, in <module>
class ChatMsg(webapp.RequestHandler):
File "/base/data/home/apps/chatboxes/1.341998073649951735/chatroom.py", line 242, in ChatMsg
roomname = urllib.unquote(self.request.get('roomname'))
what the hell is going on to make self not defined
How to solve this error? i want to pass the values from get_robotxya() and get_ballxya()
and use it in a loop but it seems that it will crash after awhile how do i fix this? i want to get the values whithout it crashing out of the while loop
import socket
import os,sys
import time
from threading import Thread
HOST = '59.191.193.59'
PORT = 5555
COORDINATES = []
def connect():
globals()['client_socket'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST,PORT))
def update_coordinates():
connect()
screen_width = 0
screen_height = 0
while True:
try:
client_socket.send("loc\n")
data = client_socket.recv(8192)
except:
connect();
continue;
globals()['COORDINATES'] = data.split()
if(not(COORDINATES[-1] == "eom" and COORDINATES[0] == "start")):
continue
if (screen_width != int(COORDINATES[2])):
screen_width = int(COORDINATES[2])
screen_height = int(COORDINATES[3])
return
def get_ballxy():
update_coordinates()
ballx = int(COORDINATES[8])
bally = int(COORDINATES[9])
return ballx,bally
def get_robotxya():
update_coordinates()
robotx = int(COORDINATES[12])
roboty = int(COORDINATES[13])
angle = int(COORDINATES[14])
return robotx,roboty,angle
def print_ballxy(bx,by):
print bx
print by
def print_robotxya(rx,ry,a):
print rx
print ry
print a
def activate():
bx,by = get_ballxy()
rx,ry,a = get_robotxya()
print_ballxy(bx,by)
print_robotxya(rx,ry,a)
Thread(target=update_coordinates).start()
while True:
activate()
this is the error i get:
I'm looking for the most efficient way to add an element to a comma-separated string while maintaining alphabetical order for the words:
For example:
string = 'Apples, Bananas, Grapes, Oranges'
addition = 'Cherries'
result = 'Apples, Bananas, Cherries, Grapes, Oranges'
Also, a way to do this but while maintaining IDs:
string = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges'
addition = '62:Cherries'
result = '1:Apples, 4:Bananas, 62:Cherries, 6:Grapes, 23:Oranges'
Sample code is greatly appreciated. Thank you so much.
The users of my app can configure the layout of certain files via a format string.
For example, the config value the user specifies might be:
layout = '%(group)s/foo-%(locale)s/file.txt'
I now need to find all such files that already exist. This seems easy enough using the glob module:
glob_pattern = layout % {'group': '*', 'locale': '*'}
glob.glob(glob_pattern)
However, now comes the hard part: Given the list of glob results, I need to get all those filename-parts that matched a given placeholder, for example all the different "locale" values.
I thought I would generate a regular expression for the format string that I could then match against the list of glob results (or then possibly skipping glob and doing all the matching myself).
But I can't find a nice way to create the regex with both the proper group captures, and escaping the rest of the input.
For example, this might give me a regex that matches the locales:
regex = layout % {'group': '.*', 'locale': (.*)}
But to be sure the regex is valid, I need to pass it through re.escape(), which then also escapes the regex syntax I have just inserted. Calling re.escape() first ruins the format string.
I know there's fnmatch.translate(), which would even give me a regex - but not one that returns the proper groups.
Is there a good way to do this, without a hack like replacing the placeholders with a regex-safe unique value etc.?
Is there possibly some way (a third party library perhaps?) that allows dissecting a format string in a more flexible way, for example splitting the string at the placeholder locations?
Hi,
Need help regarding re.
file = 'file No.WR79050107006 from files'
So what I am trying to do is validate if file string contains WR + 11 digit.
result = re.match('^(\S| )*(?P<sr>(\d){11})(\S| )*', file)
Its validate only 11 digit but not WR before it.
How can I do that?
Using re after matching how can I get the match value ( WR79050107006)
I can do string find
index = file.find('file No.')
and then get the value of next 13 char.
thanks
I'm building an "API API", it basically a wrapper for a in house REST web service that the web app will be making a lot of requests to.
Some of the web service calls need to be GET rather than post, but passing parameters.
Is there a "best practice" way to encode a dictionary into a query string? e.g.: ?foo=bar&bla=blah
I'm looking at the urllib2 docs, and it looks like it decides by itself wether to use POST or GET based on if you pass params or not, but maybe someone knows how to make it transform the params dictionary into a GET request.
Maybe there's a package for something like this out there? It would be great if it supported keep-alive, as the web server will be constantly requesting things from the REST service.
Thanks!
Today I was bitten again by "Mutable default arguments" after many years. I usually don't use mutable default arguments unless needed but I think with time I forgot about that, and today in the application I added tocElements=[] in a pdf generation function's argument list and now 'Table of Content' gets longer and longer after each invocation of "generate pdf" :)
My question is what other things should I add to my list of things to MUST avoid?
1 Mutable default arguments
2 import modules always same way e.g. 'from y import x' and 'import x' are totally different things actually they are treated as different modules
see http://stackoverflow.com/questions/1459236/module-reimported-if-imported-from-different-path
3 Do not use range in place of lists because range() will become an iterator anyway, so things like this will fail, so wrap it by list
myIndexList = [0,1,3]
isListSorted = myIndexList == range(3) # will fail in 3.0
isListSorted = myIndexList == list(range(3)) # will not
same thing can be mistakenly done with xrange e.g myIndexList == xrange(3).
4 Catching multiple exceptions
try:
raise KeyError("hmm bug")
except KeyError,TypeError:
print TypeError
It prints "hmm bug", though it is not a bug, it looks like we are catching exceptions of type KeyError,TypeError but instead we are catching KeyError only as variable TypeError, instead use
try:
raise KeyError("hmm bug")
except (KeyError,TypeError):
print TypeError
Hi i working on scrapy and trying xml feeds first time, below is my code
class TestxmlItemSpider(XMLFeedSpider):
name = "TestxmlItem"
allowed_domains = {"http://www.nasinteractive.com"}
start_urls = [
"http://www.nasinteractive.com/jobexport/advance/hcantexasexport.xml"
]
iterator = 'iternodes'
itertag = 'job'
def parse_node(self, response, node):
title = node.select('title/text()').extract()
job_code = node.select('job-code/text()').extract()
detail_url = node.select('detail-url/text()').extract()
category = node.select('job-category/text()').extract()
print title,";;;;;;;;;;;;;;;;;;;;;"
print job_code,";;;;;;;;;;;;;;;;;;;;;"
item = TestxmlItem()
item['title'] = node.select('title/text()').extract()
.......
return item
result:
File "/usr/lib/python2.7/site-packages/Scrapy-0.14.3-py2.7.egg/scrapy/item.py", line 56, in __setitem__
(self.__class__.__name__, key))
exceptions.KeyError: 'TestxmlItem does not support field: title'
Totally there are 200+ items so i need to loop over and assign the node text to item
but here all the results are displaying at once when we print, actually how can we loop over on nodes in scraping xml files with xmlfeedspider
I'm uploading potentially large files to a web server. Currently I'm doing this:
import urllib2
f = open('somelargefile.zip','rb')
request = urllib2.Request(url,f.read())
request.add_header("Content-Type", "application/zip")
response = urllib2.urlopen(request)
However, this reads the entire file's contents into memory before posting it. How can I have it stream the file to the server?
I have this code:
filenames=["file1","FILE2","file3","fiLe4"]
def alignfilenames():
#build a string that can be used to add labels to the R variables.
#format goal: suffixes=c(".fileA",".fileB")
filestring='suffixes=c(".'
for filename in filenames:
filestring=filestring+str(filename)+'",".'
print filestring[:-3]
#now delete the extra characters
filestring=filestring[-1:-4]
filestring=filestring+')'
print "New String"
print str(filestring)
alignfilenames()
I'm trying to get the string variable to look like this format: suffixes=c(".fileA",".fileB".....) but adding on the final parenthesis is not working. When I run this code as is, I get:
suffixes=c(".file1",".FILE2",".file3",".fiLe4"
New String
)
Any idea what's going on or how to fix it?
is there anyway to show why a "try" failed, and skipped to "except", without writing out all the possible errors by hand, and without ending the program?
example:
try:
1/0
except:
someway to show
"Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
1/0
ZeroDivisionError: integer division or modulo by zero"
i dont want to doif:print error 1, elif: print error 2, elif: etc.... i want to see the error that would be shown had try not been there
I have a list of numbers I am reading left to right. Anytime I encounter a sign change when reading the sequence I want to count it.
X = [-3,2,7,-4,1,-1,1,6,-1,0,-2,1]
X = [-, +, +, -, +, -, +, +, -, -,-,+]
So, in this list there are 8 sign changes.
When Item [0] (in this case -3) is negative it is considered a sign change. Also, any 0 in the list is considered [-].
Any help would be greatly appreciated.
Trying to convert super(B, self).method() into a simple nice bubble() call.
Did it, see below!
Is it possible to get reference to class B in this example?
class A(object): pass
class B(A):
def test(self):
test2()
class C(B): pass
import inspect
def test2():
frame = inspect.currentframe().f_back
cls = frame.[?something here?]
# cls here should == B (class)
c = C()
c.test()
Basically, C is child of B, B is child of A. Then we create c of type C. Then the call to c.test() actually calls B.test() (via inheritance), which calls to test2().
test2() can get the parent frame frame; code reference to method via frame.f_code;
self via frame.f_locals['self']; but type(frame.f_locals['self']) is C (of course), but not B, where method is defined.
Any way to get B?
This code is supposed to be able to sort the items in self.array based upon the order of the characters in self.order. The method sort runs properly until the third iteration, unil for some reason the for loop seems to repeat indefinitely. What is going on here?
class sorting_class:
def __init__(self):
self.array = ['ca', 'bd', 'ac', 'ab'] #An array of strings
self.arrayt = []
self.globali = 0
self.globalii = 0
self.order = ['a', 'b', 'c', 'd'] #Order of characters
self.orderi = 0
self.carry = []
self.leave = []
self.sortedlist = []
def sort(self):
for arrayi in self.arrayt: #This should only loop for the number items in self.arrayt. However, the third time this is run it seems to loop indefinitely.
print ('run', arrayi) #Shows the problem
if self.order[self.orderi] == arrayi[self.globali]:
self.carry.append(arrayi)
else:
if self.globali != 0:
self.leave.append(arrayi)
def srt(self):
self.arrayt = self.array
my.sort() #First this runs the first time.
while len(self.sortedlist) != len(self.array):
if len(self.carry) == 1:
self.sortedlist.append(self.carry)
self.arrayt = self.leave
self.leave = []
self.carry = []
self.globali = 1
self.orderi = 0
my.sort()
elif len(self.carry) == 0:
if len(self.leave) != 0: #Because nothing matches 'aa' during the second iteration, this code runs the third time"
self.arrayt = self.leave
self.globali = 1
self.orderi += 1
my.sort()
else:
self.arrayt = self.array
self.globalii += 1
self.orderi = self.globalii
self.globali = 0
my.sort()
self.orderi = 0
else: #This is what runs the second time.
self.arrayt = self.carry
self.carry = []
self.globali += 1
my.sort()
my = sorting_class()
my.srt()
this is the code, I get error that it can not serialize reference (sumReq)
sumReqClass = GED("http://www.some-service.com/sample", "getSumRequest").pyclass
sumReq = sumReqClass()
rq = GetSumSoapIn()
sum._sumReqObj = sumReq
rs=proxy.GetSum(rq, soapheaders=[credentials])
I get error :
TypeError: bad usage, failed to serialize element reference (http://www.some-service.com/sample, getSumRequest), in: /SOAP-ENV:Body