I am trying to get a list of all existing model fields and properties for a given object. Is there a clean way to instrospect an object so that I can get a dict of fields and properties.
class MyModel(Model)
url = models.TextField()
def _get_location(self):
return "%s/jobs/%d"%(url, self.id)
location = property(_get_location)
What I want is something that returns a dict that looks like this:
{
'id' : 1,
'url':'http://foo',
'location' : 'http://foo/jobs/1'
}
I can use model._meta.fields to get the model fields, but this doesn't give me things that are properties but not real DB fields.
"8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,"
I'm doing a programming challenge where i need to parse this sequence into my sudoku script.
Need to get the above sequence into 8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8.........
I tried re but without success, help is appreciated, thanks.
| random_code | varchar(200) | YES | UNI | NULL | |
MyTable.objects.filter(random_code = None)
Is this correct? Will this SELECT where there is no random code set? Above is my table.
I'd like everything to function correctly, except when it's mobile, the entire site will used a set of specific templates.
Also, I'd like to autodetect if it's mobile. If so, then use that set of templates throughout the entire site.
Hello, I'm developing a web page in Django (using apache server) that needs to call a shell command to enable/dissable some daemons. I'm try to do it with
os.system(service httpd restart 1>$HOME/out 2>$HOME/error)
and this command doesn't return anything. Any idea how can i fix this?
Starting from an Html input like this:
<p>
<a href="http://www.foo.com">this if foo</a>
<a href="http://www.bar.com">this if bar</a>
</p>
using BeautifulSoup, i would like to change this Html in:
<p>
<a href="http://www.foo.com">this if foo</a><b>OK</b>
<a href="http://www.bar.com">this if bar</a><b>OK</b>
</p>
Is it possible to do this using BeautifulSoup?
class a(object):
c=b()# how to call the b method
d=4
def __init__(self):
print self.c
def b(self):
return self.d+1
a()
how to call the 'b' method not in the __init__
thanks
What I wanted is printing out 5 dots that a dot printed per a second using time.sleep(), but the result was 5 dots were printed at once after 5 seconds delay.
Tried both print and sys.stdout.write, same result.
Thanks for any advices.
import time
import sys
def wait_for(n):
"""Wait for {n} seconds. {n} should be an integer greater than 0."""
if not isinstance(n, int):
print 'n in wait_for(n) should be an integer.'
return
elif n < 1:
print 'n in wait_for(n) should be greater than 0.'
return
for i in range(0, n):
sys.stdout.write('.')
time.sleep(1)
sys.stdout.write('\n')
def main():
wait_for(5) # FIXME: doesn't work as expected
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print '\nAborted.'
I'm trying to figure out if there's an elegant and concise way to have a class accessing one of its own properties when "used" as a dictionary, basically redirecting all the methods that'd be implemented in an ordered dictionary to one of its properties.
Currently I'm inheriting from IterableUserDict and explicitly setting its data to another property, and it seems to be working, but I know that UserDict is considered sort of old, and I'm concerned I might be overlooking something.
What I have:
class ConnectionInterface(IterableUserDict):
def __init__(self, hostObject):
self._hostObject= hostObject
self.ports= odict.OrderedDict()
self.inputPorts= odict.OrderedDict()
self.outputPorts= odict.OrderedDict()
self.data= self.ports
This way I expect the object to behave and respond (and be used) the way I mean it to, except I want to get a freebie ordered dictionary behaviour on its property "ports" when it's iterated, items are gotten by key, something is looked up ala if this in myObject, and so on.
Any advice welcome, the above seems to be working fine, but I have an odd itch that I might be missing something.
Thanks in advance.
Is there any "python's Generator" equivalent in JavaScript?
PS:
Python's Generator is very memory efficient when we need to do one time iterate through a big array, hash...
"Generators are iterables, but you can only read them once. It's because they do not store all the values in memory, they generate the values on the fly"
(Python's Generator explained in this thread: The Python yield keyword explained )
I need to control a program by sending commands in utf-8 encoding to its standard input. For this I run the program using subprocess.Popen():
proc = Popen("myexecutable.exe", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
proc.stdin.write(u'ééé'.encode('utf_8'))
If I run this from a cygwin utf-8 console, it works. If I run it from a windows console (encoding ='cp1252') this doesn't work. Is there a way to make this work without having to install a cygwin utf-8 console on each computer I want it to run from ? (NB: I don't need to output anything to console)
I have a model called "Activity" in my django app. in the admin interface, it appears on the screen as "Activitys". how can I override the label on the admin page to make it "Activities" instead?
I see in the archives how to do this for a field, but not for a model itself. thanks!
I am trying to use the ModelForm to add my data. It is working well, except that the ForeignKey dropdown list is showing all values and I only want it to display the values that a pertinent for the logged in user.
Here is my model for ExcludedDate, the record I want to add:
class ExcludedDate(models.Model):
date = models.DateTimeField()
reason = models.CharField(max_length=50)
user = models.ForeignKey(User)
category = models.ForeignKey(Category)
recurring = models.ForeignKey(RecurringExclusion)
def __unicode__(self):
return self.reason
Here is the model for the category, which is the table containing the relationship that I'd like to limit by user:
class Category(models.Model):
name = models.CharField(max_length=50)
user = models.ForeignKey(User, unique=False)
def __unicode__(self):
return self.name
And finally, the form code:
class ExcludedDateForm(ModelForm):
class Meta:
model = models.ExcludedDate
exclude = ('user', 'recurring',)
How do I get the form to display only the subset of categories where category.user equals the logged in user?
Hello all ,
I have a string like "SAB_bARGS_D" . What I want is that the string gets divided into list of characters but whenever there is a _ sign the next character gets appended to the previous one.
So the answer to above should be ['S','A','B_b','A','R','G','S_D']
It can be done by using a for loop traversing through the list but is there an inbuilt function that I can use.....
Thanks a lot
I'm trying to use a third party application located here:
git://github.com/Star2Billing/django-audiofield.git
I'm using Aptana Studio as my IDE. I created my project and then I clicked on the project and imported the app from the github location. It looked like it imported. I wanted to check that it imported properly before beginning any real coding so I performed manage.py validate.
I got a message that stated: "No module named audiofield". I added the app to my Installed Apps settings and followed the installation instructions.
I'm not sure if I'm importing it incorrectly. Also, I'm using virtualenv in Aptana. I'm not sure if this may have added to the problem.
Please help.
the following function parses a CSV file into a list of dictionaries, where each element in the list is a dictionary where the values are indexed by the header of the file (assumed to be the first line.)
this function is very very slow, taking ~6 seconds for a file that's relatively small (less than 30,000 lines.)
how can I speed it up?
def csv2dictlist_raw(filename, delimiter='\t'):
f = open(filename)
header_line = f.readline().strip()
header_fields = header_line.split(delimiter)
dictlist = []
# convert data to list of dictionaries
for line in f:
values = map(tryEval, line.strip().split(delimiter))
dictline = dict(zip(header_fields, values))
dictlist.append(dictline)
return (dictlist, header_fields)
thanks.
This is probably a really silly question but, given the example code at the bottom, how would I get a single list that retain the tuples?
(I've looked at the itertools but it flattens everything)
What I currently get is:
('id', 20, 'integer')
('companyname', 50, 'text')
[('focus', 30, 'text'), ('fiesta',
30, 'text'), ('mondeo', 30, 'text'),
('puma', 30, 'text')]
('contact', 50, 'text')
('email', 50, 'text')
what I would like is a single level list like:
('id', 20, 'integer')
('companyname', 50, 'text')
('focus', 30, 'text')
('fiesta', 30, 'text')
('mondeo', 30, 'text')
('puma', 30, 'text')
('contact', 50, 'text')
('email', 50, 'text')
def getproducts():
temp_list=[]
product_list=['focus','fiesta','mondeo','puma'] #usually this would come from a db
for p in product_list:
temp_list.append((p,30,'text'))
return temp_list
def createlist():
column_title_list = (
("id",20,"integer"),
("companyname",50,"text"),
getproducts(),
("contact",50,"text"),
("email",50,"text"),
)
return column_title_list
for item in createlist():
print item
Thanks
ALJ
I am reading one line at a time from a file, but at the end of each line it adds a '\n'.
example:
line is: 094 234 hii
but my input is: 094 234 hii\n
I want to read line by linem but I don't need to keep the newlines...
My goal is to read a list from every line: I need ['094','234','hii'], not ['094','234','hii\n']
Any advice?
sorry, im sure this is asked a bunch, but i couldnt find it.
in myModule.py:
from myModule.subModule import myClass
i am working on myClass, and want to stay in my ipython session and test it. reload(myModule) doesnt re-compile myClass.
how can i do this?
this is gaema : http://code.google.com/p/gaema/
this demo : http://code.google.com/p/gaema/source/browse/#hg/demos/webapp
only has Google Accounts
i want demo for Facebook and Twitter
thanks
I have a string "one two 9three 52eight four", so I only want to get "one two four", because "three" starts with "9" and "eight" starts with "52".
I tried:
"(?!\d)\w+"
but it's still taking the "three" and "eight". I don't want it.