i am using XML as my backend for the application...
LXML is used to parse the xml.
How can i encrypt this xml file to make sure that the data is protected......
thanks in advance.
Before I ask this, do note: I want this for debugging purposes. I know that this is going to be some bad black magic, but I want to use it just during debugging so I could identify my objects more easily.
It's like this. I have some object from class A that creates a few B instances as attributes:
class A(object):
def __init__(self)
self.vanilla_b = B()
self.chocolate_b = B()
class B(object):
def __init__(self):
# ...
What I want is that in B.__init__, it will figure out the "vanilla_b" or whatever attribute name it was given, and then put that as the .name attribute to this specific B.
Then in debugging when I see some B object floating around, I could know which one it is.
Is there any way to do this?
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?
I know this is simple but I can't get it working! I have no probs with insert,update or select commands, Lets say I have a dictionary and I want to populate a table with the column names in the dictionary what is wrong with my one line where I add a column?
##create
con = sqlite3.connect('linksauthor.db')
c = con.cursor()
c.execute('''create table linksauthor (links text)''')
con.commit()
c.close()
##populate author columns
allauthors={'joe':1,'bla':2,'mo':3}
con = sqlite3.connect('linksauthor.db')
c = con.cursor()
for author in allauthors:
print author
print type(author)
c.execute("alter table linksauthor add column '%s' 'float'")%author ##what is wrong here?
con.commit()
c.close()
Hello,
I have a script and I want one function to run at the same time as the other.
Example code I have looked at:
import threading
def MyThread ( threading.thread ):
doing something........
def MyThread2 ( threading.thread ):
doing something........
MyThread().start()
MyThread2().start()
I am having trouble getting this working. I would prefer to get this going using a threaded function rather than a class.
Thanks for any help.
How to call a method using getattr?
I want to create a metaclass, which can call non-existing methods of some other class that start with the word 'oposite_'. The method should have the same number of arguments, but to return the opposite result.
def oposite(func):
return lambda s, *args, **kw: not oposite(s, *args, **kw)
class Negate(type):
def __getattr__(self, name):
if name.startswith('oposite_'):
return oposite(self.__getattr__(name[8:]))
def __init__(self,*args,**kwargs):
self.__getattr__ = Negate.__getattr__
class P(metaclass=Negate):
def yep(self):
return True
But the problem is that
self.__getattr__(sth)
returns a NoneType object.
>>> p = P()
>>> p.oposite_yep()
Traceback (most recent call last):
File "<pyshell#115>", line 1, in <module>
p.oposite_yep()
TypeError: <lambda>() takes at least 1 positional argument (0 given)
How to deal with this?
I want to know if there would be a way to catch exceptions inside called methods.
Example:
def foo(value):
print value
method(x)
This would throw a NameError exception, cause x is not declared.
I'd like to catch this NameError exception inside foo method.
Is there a way?
How do I find out if a connection has been broken using the httplib library? Seems like something so basic yet I can't find the answer on here or google.
Hey guys, new programmer here. I have an assignment for class and I'm stuck... What I need to do is a create a GUI that gives someone a basic arithmetic problem in one box, asks the person to answer it, evaluates it, and tells you if you're right or wrong...
Basically, what I have is this:
[code]
class Lesson(Frame):
def init (self, parent=None):
Frame.init(self, parent)
self.pack()
Lesson.make_widgets(self)
def make_widgets(self):
Label(self, text="").pack(side=TOP)
ent = Entry(self)
self.a = randrange(1,10)
self.b = randrange(1,10)
self.expr = choice(["+","-"])
ent.insert(END, str(self.a) + str(self.expr) + str(self.a))
[/code]
I've broken this down into many little steps and basically, what I'm trying to do right now is insert a default random expression into the first entry widget. When I run this code, I just get a blank Label. Why is that? How can I put a something like "7+7" into the box? If you absolutely need background to the problem, it's question #3 on this link.
http://reed.cs.depaul.edu/lperkovic/csc242/homeworks/Homework8.html
-Thanks for all help in advance.
I know that wasn't clear. Here's what I'm doing specifically. I have my list of dictionaries here:
dict = [{int=0, value=A}, {int=1, value=B}, ... n]
and I want to take them in combinations, so I used itertools and it gave me a tuple (Well, okay it gave me a memory object that I then used enumerate on so I could loop over it and enumerate gave ma tuple):
for (index, tuple) in enumerate(combinations(dict, 2)):
and this is where I have my problem. I want to identify which of the two items in the combination has the bigger 'int' value and which has the smaller value and assign them to variables (I'm actually using more than 2 in the combination so I can't just say if tuple[0]['int'] tuple[1]['int'] and do the assignment because I'd have to list this out a bunch of times and that's hard to manage).
I was going to assign each 'int' value to a variable, sort it in a list, index the 'int' value in the list by 1, 2, 3, 4, 5 ... etc., then go back and access the dictionary I wanted by the int value and then assign the dictionary to a variable so I knew which was bigger. But I have a big list and lists and variable assignments are resource intensive and this is taking a long time (I had only a little bit of that written and it was taking forever to run).
So I was hoping someone knew a fast way to do this. I actually could list out every possible combination of assignmnets using the if/thens but it's just like 5 pages of if/thens and assignments and is hard to read and manage when I want to change it.
You've probably gathered this, but I"m new at programming. thx
I'm sure this is simple but I can't figure it out. I have a list of strings like this(after using sorted on it):
Season 2, Episode 1: A Flight to Remember
Season 2, Episode 20: Anthology of Interest I
Season 2, Episode 2: Mars University
Season 2, Episode 3: When Aliens Attack
....
Season 3, Episode 10: The Luck of the Fryrish
Season 3, Episode 11: The Cyber House Rules
Season 3, Episode 12: Insane in the Mainframe
Season 3, Episode 1: The Honking
Season 3, Episode 2: War Is the H-Word
How can I make them sort out properly? (by episode #, ascending)
I'm doing the following:
from subprocess import PIPE
from subprocess import Popen
file = 'dump.sql.gz'
p1 = Popen(["gzip", "-cd" ,file], stdout=PIPE)
print "Importing temporary file %s" % file
p2 = Popen(["mysql","--default-character-set=utf8", "--user=root" , "--password=something", "--host=localhost", "--port=3306" , 'my_db'],stdin=p1.stdout, stdout=PIPE,stderr=PIPE)
err = p1.communicate()[1]
if err: print err
err = p2.communicate()[1]
if err: print err
But the db is not being populated. No errors are shown, also I have checked p1.stdout and it has the file contents.
Any ideas?
I have this socket server script,
import SocketServer
import shelve
import zlib
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.words = shelve.open('/home/tipu/Dropbox/dev/workspace/search/words.db', 'r');
self.tweets = shelve.open('/home/tipu/Dropbox/dev/workspace/search/tweets.db', 'r');
param = self.request.recv(1024).strip()
try:
result = str(self.words[param])
except KeyError:
result = "set()"
self.request.send(str(result))
if __name__ == "__main__":
HOST, PORT = "localhost", 50007
SocketServer.TCPServer.allow_reuse_address = True
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
And this receiver,
from django.http import HttpResponse
from django.template import Context, loader
import shelve
import zlib
import socket
def index(req, param = ''):
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(param)
data = zlib.decompress(s.recv(131072))
s.close()
print 'Received', repr(data)
t = loader.get_template('index.html')
c = Context({ 'foo' : data })
return HttpResponse(t.render(c))
I am sending strings to the receiver that are in the hundreds of kilobytes. I end up only receiving a portion of it. Is there a way that I can fix that so that the whole string is sent?
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.
I have a PSP page with html embedded. I need to place another for loop so i can insert another %s next to background-color: which will instert a appropriate colour to colour in the html table.
For example i need to insert for z in colours so it can loop over the colours list and insert the correct colour. Where ever i try to insert the for loop it doesnt seem to work it most commonly colours each cell in the table 60 times then moves onto the next cell and repeats itself and crashes my web browser.
The colours are held in a table called colours.
code below:
<table>
<%
s = ''.join(aa[i] for i in table if i in aa)
for i in range(0, len(s), 60):
req.write('<tr><td><TT>%04d</td>' % (i+1));
for k in s[i:i+60]:
req.write('<TT><td><TT><font style="background-color:">%s<font></td>' % (k));
req.write('</TT></tr>')
#end
%>
</table>
Hello everyone. I am using wxPython and Py2exe to create my application and my only problem is loading for example bitmaps.
Ok so lets say I want to add an image to my application, and thats fairly easy using wxPython, and lets say it is on the same directory of my .py so for example:
image = wx.StaticBitmap(self, -1, wx.Bitmap('image.bmp')
Now, this works obviously fine, problem is when I convert to Py2exe, I would like to use the resources from the dlls that I included in the Py2Exe compilation.
So basically what I want to do is to instead of including the images on the same folder as my application in order to work, I would like to use it from the resources so people won't see the images on the folder.
Usually I would use virtualenv and pip for deployment of web applications. With Google App Engine this doesn't work, because all import statement are relative to directory of the application.
The most common approach I saw was to simply copy the packages from site-packages to the directory of the application. This involves manual work and is error-prone.
Another approach was to changes install_lib and install_scripts in ~/.pydisutils.cfg, but this doesn't allow me to use pip in my home directory simultaneously.
Do you have any suggestions for this?
I have this script
SELECT = """
select
coalesce (p.ID,'') as id,
coalesce (p.name,'') as name,
from TABLE as p
"""
self.cur.execute(SELECT)
for row in self.cur.itermap():
xml +=" <item>\n"
xml +=" <id>" + id + "</id>\n"
xml +=" <name>" + name + "</name>\n"
xml +=" </item>\n\n"
#save xml to file here
f = open...
and I need to save data from huge database to file. There are 10 000s (up to 40000) of items in my database and it takes very long time when script runs (1 hour and more) until finish.
How can I take data I need from database and save it to file "at once"? (as quick as possible? I don't need xml output because I can process data from output on my server later. I just need to do it as quickly as possible. Any idea?)
Many thanks!
I've got an app with around half a million 'records', each of which only stores three fields. I'd like to look up records by a string field with a query, but I'm running into problems. If I visit the console page, manually view a record and save it (without making changes) it shows up in a query:
SELECT * FROM wordEntry WHERE wordStr = 'SomeString'
If I don't do this, I get 'no results'. Does appengine need time to update? If so, how much?
(I was also having trouble batch deleting and modifying data, but I was able to break the problem up into smaller chunks.)
it's annoying how sqlite always returns a list of touples! i can see the why this is necessary, but when i am querying a single column, how do i get a plain list?
e.g cursor.fetchall() returns [(u'one',), (u'two',), (u'three',)]
from this, how do i get the simple list [u'one', u'two', u'three']?
I have the following list comprehension which returns a list of coordinate objects for each location.
coordinate_list = [Coordinates(location.latitude, location.longitude)
for location in locations]
This works.
Now suppose the location object has a number_of_times member. I want a list comprehension to generate n Coordinate objects where n is the number_of_times for the particular location. So if a location has number_of_times = 5 then the coordinates for that location will be repeated 5 times in the list. (Maybe this is a case for a for-loop but I'm curious if it can be done via list comprehensions)
So I have a list of tuple like:
[(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
I want this list for a tuple whose number value is equal to something.
So that if I do search(53) it will return 2
Is is an easy way to do that?
import math
def p(n):
return 393000*((288200/393000)^n * math.exp(-(288200/393000)))/math.factorial(n)
print p(3)
When I run it, I get the following error message:
Traceback (most recent call last):
File "poisson.py", line 6, in <module>
print p(3)
File "poisson.py", line 4, in p
return 393000*((288200/393000)^n * math.exp(-(288200/393000)))/math.factoria
l(n)
TypeError: unsupported operand type(s) for ^: 'int' and 'float'
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?