Is there a way to find what function called the current function? So for example:
def first():
second()
def second():
# print out here what function called this one
Any ideas?
Hi
I'd like to register a system shortcut for my application. For example:
Shortcut 1: minimize application to
tray
Shortcut 2: open my minimized
application
Shortcut 3: do some function...
I want to do each without having focus in my application
is it possible?
I'm developing a GUI in wxPython which allows a user to generate sequences of colours for some toys I'm building. Part of the program needs to load an MP3 (and potentially other formats further down the line) and display it to the user. That shuold be sufficient to get started but later I'd like to add features like identifying beats and some crude frequency analysis.
Is there any simple way of loading / understanding an MP3's contents to display a plot of it's amplitudes to the screen using wxWidgets?
I later intend to port to C++/wxWidgets for speed and to avoid having to distribute wxPython.
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?
I have given my code below, have problem in implementing a function
I want the text in lineedit with objectname 'host' in a string say 'shost'. when the user click the pushbutton with name 'connect'.How do i do it? I tried and failed. How to implement this function?
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
le = QLineEdit()
le.setObjectName("host")
le.setText("Host")
pb = QPushButton()
pb.setObjectName("connect")
pb.setText("Connect")
layout.addWidget(le)
layout.addWidget(pb)
self.setLayout(layout)
self.connect(pb, SIGNAL("clicked()"),self.button_click)
self.setWindowTitle("Learning")
def button_click(self):
#i want the text in lineedit with objectname
#'host' in a string say 'shost'. when the user click
# the pushbutton with name connect.How do i do it?
# I tried and failed. How to implement this function?
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
Now how do i implement the function "def button_click(self):" ? I have just started with pyQt!
Write an iterative program that finds the largest number of McNuggets that cannot be bought in exact quantity. Your program should print the answer in the following format (where the correct number is provided in place of n):
"Largest number of McNuggets that cannot be bought in exact quantity: n"
n = # some ridiculously large number, omitted
N = [int(i) for i in str(n)]
maxProduct = 0
for i in range(0,len(N)-4):
newProduct = 1
is_cons = 0
for j in range(i,i+4):
if N[j] == N[j+1] - 1:
is_cons += 1
if is_cons == 5:
for j in range(i,i+5):
newProduct *= N[j]
if newProduct > maxProduct:
maxProduct = newProduct
print maxProduct
I've been working on this problem for hours now and I can't get this to work. I've tried doing this algorithm on paper and it works just fine.. Could you give me hints what's wrong ?
Starting from an Html input like this:
<p>
<a href="http://www.foo.com" rel="nofollow">this is foo</a>
<a href="http://www.bar.com" rel="nofollow">this is bar</a>
</p>
is it possible to modify the <a> node values ("this i foo" and "this is bar") adding the suffix "PARSED" to the value without recreating the all link?
The result need to be like this:
<p>
<a href="http://www.foo.com" rel="nofollow">this is foo_PARSED</a>
<a href="http://www.bar.com" rel="nofollow">this is bar_PARSED</a>
</p>
And code should be something like:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for link_tag in soup.findAll('a'):
link_tag.string = link_tag.string + '_PARSED' #This obviously does not work
I have models...
class Item(models.Model):
name = models.CharField('Item Name', max_length = 30)
item_code = models.CharField(max_length = 10)
color = models.CharField(max_length = 150, null = True, blank = True)
size = models.CharField(max_length = 30, null = True, blank = True)
fabric_code = models.CharField(max_length = 30, null = True, blank = True)
I have values in Item. in Item model name field has the similar values..(but the other values of record are change). I want to select the name field values distinctly(ie similar values select only ones). in one box(like combo box).
What kind of form or views i use??
Is there a way to test the html from the response of:
response = self.client.get('/user/login/')
I want a detailed check like input ids, and other attributes. Also, how about sessions that has been set? is it possible to check their values in the test?
I have an application in Django 1.2.
Language is selectable (I18N and Locale = True)
When I select the english lang. in the site, the admin works OK. But when I change to any other language this is what happens with date inputs (spanish example):
Correctly, the input accepts the spanish format %d/%m/%Y (Even selecting from the calendar, the date inserts as expected). But when I save the form and load it again, the date shows in the english form: %Y-%m-%d
The real problem is that when I load the form to change any other text field and try to save it I get an error telling me to enter a valid date, so I have to write all dates again or change the language in the site to use the admin.
I haven't specified anything for DATE_INPUT_FORMATS in settings nor have I overridden forms or models.
Surely I am missing something but I can't find it. Can anybody give me a hint?
Hey everyone.
I've got a Django app serving a webpage with an HTML5 element. There's a wierd "feature", turning the video element to be non-seekable: video.seekable returns a timeRanges object with length=0, whereas it should be length=1.
This means I can't edit the video. JavaScript can't do anything either.
The thing is, when I upload the problematic webpage, statically - no Django, just plain HTML/JS/CSS - to my website for testing, it works fine - length=1.
However, if I try to serve the same static page on my Django dev server still gives the same problem.
I am using Django's static serving for dev/debug purposes - Do you have any idea what is causing this, or how can I fix it?
Thanks.
Hi folks,
I need to setup temporary User models for each visitors, where the visitors are obviously tied by session data.
I might not be aware of it, but does Django support attaching data to Anonymous users?
The only way, I am currently aware of, is to use the session dictionary part of the request object.
Help would be very much appreciated!
Using Tastypie and GeoDjango, I'm trying to return results of buildings located within 1 mile of a point.
The TastyPie documentation states that distance lookups are not yet supported, but I am finding examples of people getting it work, such as this discussion and this discussion on StackOverflow, but no working code examples that can be applied.
The idea that I am trying to work with is if I append a GET command to the end of a URL, then nearby locations are returned, for example:
http://website.com/api/?format=json&building_point__distance_lte=[{"type": "Point", "coordinates": [153.09537, -27.52618]},{"type": "D", "m" : 1}]
But when I try that, all I get back is:
{"error": "Invalid resource lookup data provided (mismatched type)."}
I've been pouring over the Tastypie document for days now and just can't figure out how to implement this.
I'd provide more examples, but I know they'd be all terrible. All advice is appreciated, thank you!
A minimal example:
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
winWidth = 683
winHeight = 784
screen = QtGui.QDesktopWidget().availableGeometry()
screenCenterX = (screen.width() - winWidth) / 2
screenCenterY = (screen.height() - winHeight) / 2
self.setGeometry(screenCenterX, screenCenterY, winWidth, winHeight)
layout = QtGui.QVBoxLayout()
layout.addWidget(FormA())
mainWidget = QtGui.QWidget()
mainWidget.setLayout(layout)
self.setCentralWidget(mainWidget)
FormA is a QFrame with a VBoxLayout that can expand to an arbitrary number of entries.
In the code posted above, if the entries in the forms can't fit in the window then the window itself grows. I'd prefer for the window to become scrollable. I've also tried the following...
replacing
mainWidget = QtGui.QWidget()
mainWidget.setLayout(layout)
self.setCentralWidget(mainWidget)
with
mainWidget = QtGui.QScrollArea()
mainWidget.setLayout(layout)
self.setCentralWidget(mainWidget)
results in the forms and entries shrinking if they can't fit in the window.
Replacing it with
mainWidget = QtGui.QWidget()
mainWidget.setLayout(layout)
scrollWidget = QtGui.QScrollArea()
scrollWidget.setWidget(mainWidget)
self.setCentralWidget(scrollWidget)
results in the mainwidget (composed of the forms) being scrunched in the top left corner of the window, leaving large blank areas on the right and bottom of it, and still isn't scrollable.
I can't set a limit on the size of the window because I wish for it to be resizable.
How can I make this window scrollable?
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 for
def countSubStringMatch(target,key):
and
def countSubStringMatchRecursive (target, key):
For the 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.
I have to send out letters to certain clients and I have a standard letter that I need to use. I want to replace some of the text inside the body of the message with variables.
Here is my maturity_letter models.py
class MaturityLetter(models.Model):
default = models.BooleanField(default=False, blank=True)
body = models.TextField(blank=True)
footer = models.TextField(blank=True)
Now the body has a value of this:
Dear [primary-firstname],
AN IMPORTANT REMINDER…
You have a [product] that is maturing on [maturity_date] with [financial institution].
etc
Now I would like to replace everything in brackets with my template variables.
This is what I have in my views.py so far:
context = {}
if request.POST:
start_form = MaturityLetterSetupForm(request.POST)
if start_form.is_valid():
agent = request.session['agent']
start_date = start_form.cleaned_data['start_date']
end_date = start_form.cleaned_data['end_date']
investments = Investment.objects.all().filter(maturity_date__range=(start_date, end_date), plan__profile__agent=agent).order_by('maturity_date')
inv_form = MaturityLetterInvestments(investments, request.POST)
if inv_form.is_valid():
sel_inv = inv_form.cleaned_data['investments']
context['sel_inv'] = sel_inv
maturity_letter = MaturityLetter.objects.get(id=1)
context['mat_letter'] = maturity_letter
context['inv_form'] = inv_form
context['agent'] = agent
context['show_report'] = True
Now if I loop through the sel_inv I get access to sel_inv.maturity_date, etc but I am lost in how to replace the text.
On my template, all I have so far is:
{% if show_letter %}
{{ mat_letter.body }} <br/>
{{ mat_letter.footer }}
{% endif %}
Much appreciated.
I am working on large numpy arrays, and some native numpy operations are too slow for my needs (for example simple operations such as "bitwise" A&B).
I started looking into writing C extensions to try and improve performance. As a test case, I tried the example given here, implementing a simple trace calculation. I was able to get it to work, but was surprised by the performance: for a (1000,1000) numpy array, numpy.trace() was about 1000 times faster than the C extension!
This happens whether I run it once or many times. Is this expected? Is the C extension overhead that bad? Any ideas how to speed things up?
Hi all,
Let's say we have these classes:
class Foo(object):
_bar = ""
def __init__(self):
self.bar = "hello"
def getBar(self):
return self._bar
def setBar(self, bar):
self._bar = bar
def getAttributes(self):
for attr in self.__dict__:
print attr
bar = property(getBar, setBar)
class Child(Foo):
def __init__(self):
super(Child, self).__init__()
self.a = ""
self.b = ""
if I do something like:
child = Child()
child.getAttributes()
I get all the attributes from parent and child. How could I get the attributes only from the parent?
Thanks in advance!
Its been mentioned in other answers about getting the same code running for both the def get(self) and the def post(self) for any given request. I was wondering what techniques people use, I was thinking of:
class ListSubs(webapp.RequestHandler):
def get(self):
self._run()
def post(self):
self._run()
def _run(self):
self.response.out.write("This works nicely!")
I have 2 lists
old_name_list = [a-1234, a-1235, a-1236]
new_name_list = [(a-1235, a-5321), (a-1236, a-6321), (a-1234, a-4321), ... ]
I want to search recursively if the elements in old_name_list exist in new_name_list and returns the associated value with it, for eg. the first element in old_name_list returns a-4321, second element returns a-5321, and so on until old_name_list finishes.
I have tried the following and it doesn't work
for old_name, new_name in zip(old_name_list, new_name_list):
if old_name in new_name[0]:
print new_name[1]
Is the method I am doing wrong or I have to make some minor changes to it? Thank you in advance.
As an experiment, I did this:
letters=['a','b','c','d','e','f','g','h','i','j','k','l']
for i in letters:
letters.remove(i)
print letters
The last print shows that not all items were removed ? (every other was).
IDLE 2.6.2
>>> ================================ RESTART ================================
>>>
['b', 'd', 'f', 'h', 'j', 'l']
>>>
What's the explanation for this ? How it could this be re-written to remove every item ?
I have written the following script. It opens a file, reads each line from it splitting by new line character and deleting first character in line. If line exists it's being added to array. Next each element of array is splitted by whitespace, sorted alphabetically and joined again. Every line is printed because script is fired from console and writes everything to file using standard output. I'd like to optimize this code to be more pythonic. Any ideas ?
import sys
def main():
filename = sys.argv[1]
file = open(filename)
arr = []
for line in file:
line = line[1:].replace("\n", "")
if line:
arr.append(line)
for line in arr:
lines = line.split(" ")
lines.sort(key=str.lower)
line = ''.join(lines)
print line
if __name__ == '__main__':
main()
def activate(self,shell):
self.shell = shell
self.action = gtk.Action ('foo','bar','baz',None)
self.activate_id = self.action.connect ('activate', self.call_bk_fn,self.shell)
self.action_group = gtk.ActionGroup ('hot_key_action_group')
self.action_group.add_action_with_accel (self.action, "<control>E")
uim = shell.get_ui_manager ()
uim.insert_action_group (self.action_group, 0)
uim.ensure_update ()
def call_bk_fn(self,shell):
print('hello world')
i am using the above code in a plugin for rhythmbox ,and here i am trying to register the key ctr+e so that the call_bk_fn gets called whenever the key combination is pressed , but its not working why is that so ?