Given a list of numbers how to find differences between every (i)-th and (i+1)-th of its elements? Should one better use lambda or maybe lists comprehension?
I found a lot of links on metaclasses, and most of them mention that they are useful for implementing factory methods. Can you show me an example of using metaclasses to implement the design pattern?
Hello
I would like to remove urls from a string replace them with their titles of the original contents.
For example:
mystring = "Ah I like this site: http://www.stackoverflow.com. Also I must say I like http://www.digg.com"
sanitize(mystring) # it becomes "Ah I like this site: Stack Overflow. Also I must say I like Digg - The Latest News Headlines, Videos and Images"
For replacing url to the title, I have written this snipplet:
#get_title: string -> string
def get_title(url):
"""Returns the title of the input URL"""
output = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
return output.title.string
I have lines of data which I want to parse.
The data looks like this:
a score=216 expect=1.05e-06
a score=180 expect=0.0394
What I want to do is to have a subroutine
that parse them and return 2 values (score and expect) for
each line.
However this function of mine doesn't seem to work:
def scoreEvalFromMaf(mafLines):
for word in mafLines[0]:
if word.startswith("score="):
theScore = word.split('=')[1]
theEval = word.split('=')[2]
return [theScore, theEval]
raise Exception("encountered an alignment without a score")
Please advice what's the right way to do it?
I've been getting RuntimeError: maximum recursion depth exceeded when trying to pickle a highly-recursive tree object. Much like this asker here.
He solved his problem by setting the recursion limit higher with sys.setrecursionlimit. But I don't want to do that: I think that's more of a workaround than a solution. Because I want to be able to pickle my trees even if they have 10,000 nodes in them. (It currently fails at around 200.)
(Also, every platform's true recursion limit is different, and I would really like to avoid opening this can of worms.)
Is there any way to solve this at the fundamental level? If only the pickle module would pickle using a loop instead of recursion, I wouldn't have had this problem. Maybe someone has an idea how I can cause something like this to happen, without rewriting the pickle module?
Any other idea how I can solve this problem will be appreciated.
Write two functions, called countSubStringMatch and countSubStringMatchRecursive that take two arguments, a key string and a target string. These functions iteratively and recursively count the number of instances of the key in the target string. You should complete definitions forthe remaining problems, we are going to explore other substring matching ideas. These problems can be solved with either an iterative function or a recursive one. You are welcome to use either approach, though you may find iterative approaches more intuitive in these cases of matching linear structures
Hi peoples, I'm building a pdf document with reportlab, using the Paragraph class:
doc = SimpleDocTemplate(response, leftMargin=lateral_margin, rightMargin=lateral_margin,
topMargin=top_bottom_margin, bottomMargin=top_bottom_margin)
Document = []
Document.append(Paragraph("bla bla bla bla", my_style))
doc.build(Document)
Now I want to add at the end of every page a string, how can I do that??
I'm not sure if there is even anything out there to do this. Is there any libraries out there that can reword sentences to any degree of accuracy? It doesnt have to be too intelligent.
Hi there,
is there any straight forward way of finding a key by knowing the value within a dictionary?
all I can think of is this:
key = [i for key,value in dict.items() if value=='value' ][0]
Any ideas?
this is my code:
f = open('text/a.log', 'wb')
f.write('hahaha')
f.close()
and it is not create a new file when not exist
how to do this ,
thanks
updated
class MyThread(threading.Thread):
def run(self):
f = open('a.log', 'w')
f.write('hahaha')
f.close()
error is :
Traceback (most recent call last):
File "D:\Python25\lib\threading.py", line 486, in __bootstrap_inner
self.run()
File "D:\zjm_code\helloworld\views.py", line 15, in run
f = open('a.log', 'w')
File "d:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1188, in __init__
raise IOError('invalid mode: %s' % mode)
IOError: invalid mode: w
I am doing this in my code,
HOST = '192.168.1.3'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
query_details = {"page" : page, "query" : query, "type" : type}
s.send(str(query_details))
#data = eval(pickle.loads(s.recv(4096)))
data = s.recv(16384)
But I am continually getting EOF at the last line. The code I am sending with,
self.request.send(pickle.dumps(results))
Hi
I have a very rudimentary question.
Assume I call a function, e.g.,
def foo():
x = 'hello world'
How do I get the function to return x in such a way that I can use it as the input for another function or use the variable within the body of a program?
When I use return and call the variable within another functions I get a NameError.
Thanks,
S :-)
Is it possible to use a Perl hash in a manner that has O(log(n)) lookup and insertion?
By default, I assume the lookup is O(n) since it's represented by an unsorted list.
I know I could create a data structure to satisfy this (ie, a tree, etc) however, it would be nicer if it was built in and could be used as a normal hash (ie, with %)
I have a list containing a tuples and long integers the list looks like this:
table = [(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]
How do i convert the table to look like a formal list?
so the output would be:
table = ['1','1','1','2','2','2','3','3']
For information purposes the data was obtained from a mysql database.
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?
I have this HTTP Request and I want to display only the Authorization section (base64 Value) : any help ?
This Request is stored on a variable called hreq
I have tried this :
reg = re.search(r"Authorization:\sBasic\s(.*)\r", hreq)
print reg.group()
but doesn't work
Here is the request :
HTTP Request:
Path: /dynaform/custom.js
Http-Version: HTTP/1.1
Host: 192.168.1.254
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://domain.com/userRpm/StatusRpm.htm
Authorization: Basic YWhtEWa6MDfGcmVlc3R6bGH
I want to display the value YWhtEWa6MDfGcmVlc3R6bGH
Please I need your help
thanks in advance experts
I have a directory called "notes" within the notes I have categories which are named "science", "maths" ... within those folder are sub-categories, such as "Quantum Mechanics", "Linear Algebra".
./notes
--> ./notes/maths
------> ./notes/maths/linear_algebra
--> ./notes/physics/
------> ./notes/physics/quantum_mechanics
My problem is that I don't know how to put the categories and subcategories into TWO SEPARATE list/array.
filtered=[]
text="any.pdf"
if "doc" and "pdf" and "xls" and "jpg" not in text:
filtered.append(text)
print(filtered)
This is my first Post in Stack Overflow, so excuse if there's something annoying in Question, The Code suppose to append text if text doesn't include any of these words:doc,pdf,xls,jpg.
It works fine if Its like:
if "doc" in text:
elif "jpg" in text:
elif "pdf" in text:
elif "xls" in text:
else:
filtered.append(text)
I don't know how to explain this correctly but just some sample for you guys so that you can really get what Im trying to say.
Today is April 09, 2010
7 days from now is April 16,2010
Im looking for a php code, which can give me the exact date giving the number of days interval prior to the current date.
I've been looking for a thread which can solve or even give a hint on how to solve this one but I found none.
Hi,
I create a combo box using PyGTK:
fileAttrCombo = gtk.ComboBox();
I want to attach a signal handler for this combo box. This signal handler handles when user change selection in the combo box.
What is be the best approach to do this ?
I have created some program for this.But printed a,b,c values are not correct.Please check this weather it is correct or not?
n=input("Enter the no.of McNuggets:")
a,b,c=0,0,0
count=0
for a in range(n):
if 6*a+9*b+20*c==n:
count=count+1
break
else:
for b in range(n):
if 6*a+9*b+20*c==n:
count=count+1
break
else:
for c in range(n):
if 6*a+9*b+20*c==n:
count=count+1
break
if count>0:
print "It is possible to buy exactly",n,"packs of McNuggetss",a,b,c
else:
print "It is not possible to buy"