End of line anchor $ match even there is extra trailing \n in matched string, so we use \Z instead of $
For example
^\w+$ will match the string abcd\n but ^\w+\Z is not
How about \A and when to use?
hi,
I'm having a problem with a simple program I wrote, I want to perform a certain function according to the users input. I've already used a dictionary as a replacement for a switch to do assignment but when I try to assign functions to the dictionary it doesn't execute them...
The code:
def PrintValuesArea():
## do this
def PrintValuesLength():
## do that
def PrintValuesTime():
## do third
PrintTables={"a":PrintValuesArea,"l":PrintValuesLength,"t":PrintValuesTime}
PrintTables.get(ans.lower()) ## ans is the user input
what did I do wrong? It looks the same as all the examples I've seen....
I have a class that represents undirected edges in a graph. Every edge has two members vertex1 and vertex2 representing the vertices it connects. The problem is, that an edge can be specified two directions. My idea was now to define the hash of an edge as the sum of the hashes of its vertices. This way, the direction plays no role anymore, the hash would be the same. Are there any pitfalls with that?
This line:
used_emails = [row.email for row
in db.execute(select([halo4.c.email], halo4.c.email!=''))]
Returns:
['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']
I use this to find a match:
if recipient in used_emails:
If it finds a match I need to pull another field (halo4.c.code) from the database in the same row. Any suggestions on how to do this?
If you say find C-style syntax to be in the axis of evil are you just hopelessly condemned to suck it up and deal with it if you want to provide your users with cool web 2.0 applications - for example stuff that's generally done using JQuery and Ajax etc? Are there no other choices out there? We're currently building intranet apps using pylons and a bunch of JavaScript along with a bit of Evoque. So obviously for us the world would be a better place if instead something equivalent existed written in like PythonScript. But I've yet to seen anything approaching that aside from the Android system's ASE - but obviously that's something rather unrelated. Still - if browsers could support other scripting languages....
I have an SQLAlchemy ORM class, linked to MySQL, which works great at saving the data I need down to the underlying table. However, I would like to also save the identical data to a second archive table.
Here's some psudocode to try and explain what I mean
my_data = Data() #An ORM Class
my_data.name = "foo"
#This saves just to the 'data' table
session.add(my_data)
#This will save it to the identical 'backup_data' table
my_data_archive = my_data
my_data_archive.__tablename__ = 'backup_data'
session.add(my_data_archive)
#And commits them both
session.commit()
Just a heads up, I am not interested in mapping a class to a JOIN, as in: http://www.sqlalchemy.org/docs/05/mappers.html#mapping-a-class-against-multiple-tables
There are plenty of question asking Which Programming Language Should I Learn? but I have not found an answer yet to the question what really motivates people to learn a specific new language?.
There are the people who think they should learn a new language every year for educational purpose. How do they decide on the languages to be learned?
Then I guess there are people who learn a new language because people around them told it is a fun language and they can build nice things with it.
Of course if the current job requires it people would learn a new language but I think if the language seems to have a potential to earn money (e.g. There are plenty of jobs in Java or ObjectiveC can be used to write apps for the iPhone and make money).
So why are you learning a new language or why have you learned the languages you know?
I'd like to write a subscript that adds a unique identifier (machine time) to a script everytime that it runs. However, each time I edit the script (in IDLE) the indetifiers are over-written. Is there a elegant way of doing this. The script that I wrote appears below.
import os, time
f = open('sys_time_append.py','r')
lines = f.readlines()
f.close()
fout = open('sys_time_append.py','w')
for thisline in lines:
fout.write(thisline)
fout.write('\n#'+str(time.time())+' s r\n')
fout.close()
Thanks for any help.
I need to compare list_a against many others. my problem starts when there's a duplicated item in the other lists (two k's in other_b).
my goal is to filter out all the lists with the same items (up to three matching items).
list_a = ['j','k','a','7']
other_b = ['k', 'j', 'k', 'q']
other_c = ['k','k','9','k']
>>>filter(lambda x: not x in list_a,other_b)
['q']
I need a way that would return ['k', 'q'], because 'k' appears only once in list_a.
comparing list_a and other_c with set() isn't good for my purpose since it will return only one element: k. while I need ['k','9','k']
I hope I was clear enough.
Thank you
my code is :
Hello!~~~
{% if user %}
<p>Logged in as {{ user.first_name }} {{ user.last_name }}.</p>
{% elif openid_user%}
<p>Hello, {{openid_user.nickname}}! Do you want to <a href="{{openid_logout_url}}">Log out?</p>
{% else %}
<p><a href="/login?redirect={{ current_url }}">google Log in</a>.</p>
<p><a href="/twitter">twitter Log in</a>.</p>
<p><a href="/facebook">facebook Log in</a>.</p>
<p><a href="{{openid_login_url}}">openid Log in</a>.</p>
<iframe src="/_openid/login?continue=/"></iframe>
{% endif %}
the error is :
TemplateSyntaxError: Invalid block tag: 'elif'
does not webapp has a 'else if ' ?
thanks
On example, i have 2 apps: alpha and beta
in alpha/models.py import of model from beta.models
and in beta/models.py import of model from alpha.models
manage.py validate says that ImportError: cannot import name ModelName
how to solve this problem?
How to combine two functions together
I have a class controlling some hardware:
class Heater()
def set_power(self,dutycycle, period)
...
def turn_on(self)
...
def turn_off(self)
And a class that connects to a database and handles all data logging fuctionallity for an experiment:
class DataLogger()
def __init__(self)
# Record measurements and controls in a database
def start(self,t)
# Starts a new thread to aqcuire and reccord measuements every t secconds
Now, in my program recipe.py I want to do something like:
log = DataLogger()
@DataLogger_decorator
H1 = Heater()
log.start(60)
H1.set_power(10,100)
H1.turn_on()
sleep(10)
H1.turn_off()
etc
Where all actions on H1 are recorded by the datalogger. I can change any of the classes involved, just looking for an elegant way to do this. Ideally the hardware functions remain separated from the database and DataLogger functions. And ideally the DataLogger is reusable for other controls and measurements.
This is a module named XYZ.
def func(x)
.....
.....
if __name__=="__main__":
print func(sys.argv[1])
Now I have imported this module in another code and want to use the func. How can i use it?
import XYZ
After this, where to give the argument, and syntax on how to call it, please?
I've been searching here and there, and based on this answer I've put together what you see below.
It works, but I need to put some stuff in the user's session, right there inside authenticate.
How would I store acme_token in the user's session, so that it will get cleared if they logged out?
class AcmeUserBackend(object):
# Create a User object if not already in the database?
create_unknown_user = False
def get_user(self, username):
return AcmeUser(id=username)
def authenticate(self, username=None, password=None):
""" Check the username/password and return an AcmeUser. """
acme_token = ask_another_site_about_creds(username, password)
if acme_token:
return AcmeUser(id=username)
return None
##################
from django.contrib.auth.models import User
class AcmeUser(User):
objects = None # we cannot really use this w/o local DB
def save(self):
"""saving to DB disabled"""
pass
def get_group_permissions(self):
"""If you don't make your own permissions module,
the default also will use the DB. Throw it away"""
return [] # likewise with the other permission defs
def get_and_delete_messages(self):
"""Messages are stored in the DB. Darn!"""
return []
Hey Guys,
How would I save JSON outputed by an URL to a file?
e.g from the Twitter search API (this http://search.twitter.com/search.json?q=hi)
Language isn't important.
Thanks!
edit // How would I then append further updates to EOF?
here is post my code:this is no the entire code but enough to explain my doubt.please discard any code line which u find irrelavent
enter code here
saving_tree={}
isLeaf=False
class tree:
global saving_tree
rootNode=None
lispTree=None
def __init__(self,x):
file=x
string=file.readlines()
#print string
self.lispTree=S_expression(string)
self.rootNode=BinaryDecisionNode(0,'Root',self.lispTree)
class BinaryDecisionNode:
global saving_tree
def __init__(self,ind,name,lispTree,parent=None):
self.parent=parent
nodes=lispTree.getNodes(ind)
print nodes
self.isLeaf=(nodes[0]==1)
nodes=nodes[1]#Nodes are stored
self.name=name
self.children=[]
if self.isLeaf: #Leaf Node
print nodes
#Set the leaf data
self.attribute=nodes
print "LeafNode is ",nodes
else:
#Set the question
self.attribute=lispTree.getString(nodes[0])
self.attribute=self.attribute.split()
print "Question: ",self.attribute,self.name
tree={}
tree={str(self.name):self.attribute}
saving_tree=tree
#Add the children
for i in range(1,len(nodes)):#Since node 0 is a question
# print "Adding child ",nodes[i]," who has ",len(nodes)-1," siblings"
self.children.append(BinaryDecisionNode(nodes[i],self.name+str(i),lispTree,self))
print saving_tree
i wanted to save some data in saving_tree{},which i have declared previously and want to use that saving tree in the another function outside the class.when i asked to print saving_tree it printing but,only for that instance.i want the saving_tree{} to have the data to store data of all instance and access it outside.
when i asked for print saving_tree outside the class it prints empty{}..
please tell me the required modification to get my required output and use saving_tree{} outside the class..
Hello all
I am trying to display a simple graph using pydot.
My question is that is there any way to display the graph without writing it to a file as currently I use write function to first draw and then have to use the Image module to show the files.
However is there any way that the graph directly gets printed on the screen without being saved ??
Also as an update I would like to ask in this same question that I observe that while the image gets saved very quickly when I use the show command of the Image module it takes noticeable time for the image to be seen .... Also sometimes I get the error that the image could'nt be opened because it was either deleted or saved in unavailable location which is not correct as I am saving it at my Desktop..... Does anyone know what's happening and is there a faster way to get the image loaded.....
Thanks a lot....
How would I delete all corresponding dictionaries in a list of dictionaries based on one of the dictionaries having a character in it.
data = [
{ 'x' : 'a', 'y' : '1' },
{ 'x' : 'a', 'y' : '1/1' },
{ 'x' : 'a', 'y' : '2' },
{ 'x' : 'b', 'y' : '1' },
{ 'x' : 'b', 'y' : '1' },
{ 'x' : 'b', 'y' : '1' },
]
For example, how would I delete all of the x = a due to one of the y in the x=a having a / in it? Based on the example data above, here is where I would like to get to:
cleaneddata = [
{ 'x' : 'b', 'y' : '1' },
{ 'x' : 'b', 'y' : '1' },
{ 'x' : 'b', 'y' : '1' },
]
what is the current state of user authentication? is it good to go with openid or another alternative, or we still have to write our own user/password?
I need to throw ValidationError containing anchor.
if not profile.activated():
raise ValidationError('Your profile is not activated. <a href="{% url resend_activation_key %}">Resend activation key</a>.')
What I need to modify to make this work?
I have a Django Model with updated_by and an approved_by fields, both are ForeignKey fields to the built-in (auth) User models.
I am aware that with updated_by, it's easy enough to simply over-ride the .save() method on the Model, and shove the request.user in that field before saving.
However, for approved_by, this field should only ever be filled in when a related field (date_approved) is first filled in. I'm somewhat certain that I can check this logically, and fill in the field if the previous value was empty.
What is the proper way to check the previous value of a field before saving an object?
I do not anticipate that date_approved will ever be changed or updated, nor should there be any reason to ever update the approved_by entry.
UPDATE:
Regarding forms/validation, I should have mentioned that none of the fields in question are seen by or editable by users of the site. If I have misunderstood, I'm sorry, but I'm not sure how forms and validation apply to my question.
I'm using SQLAlchemy and I can create tables that I have defined in /model/__init__.py but I have defined my classes, tables and their mappings in other files found in the /model directory.
For example I have a profile class and a profile table which are defined and mapped in /model/profile.py
To create the tables I run:
paster setup-app development.ini
But my problem is that the tables that I have defined in /model/__init__.py are created properly but the table definitions found in /model/profile.py are not created. How can I execute the table definitions found in the /model/profile.py so that all my tables can be created?
Thanks for the help!