text
stringlengths
256
65.5k
Im new to Tkinter and am trying to build a simple GUI using grid manager which upon the push of button1, button2 appears along with an adjacent entry box. If you then press button2 the entry box and button2 dissapear. Below is a slice from the GUI code, the button dissapears but the entry box does not: import Tkinter f...
I have an object subclass which implements a dynamic dispatch __ iter __ using a caching generator (I also have a method for invalidating the iter cache) like so: def __iter__(self): print("iter called") if self.__iter_cache is None: iter_seen = {} iter_cache = [] for name in self.__slot...
WSGI is PEP 333 (and PEP3333 for Python 3), a.k.a. Web Server Gateway Interface. It has three parts, but the part you're interested in is how you write a WSGI application. And WSGI app is a callable object that takes two arguments and returns an iterable object (or is a generator). # this is my_app module def app(envir...
In part 1 we covered how to access the project’s layer treeand read its data. Now let’s focus on building and manipulating layer trees.We’ll also look at how to receive updates about changes within a layer tree. Starting with an empty project, first we will get access to the layer tree and create some memorylayers for ...
I want to know the number of CPUs on the local machine in Python. The result should be user/real as output by time(1) when called with an optimally scaling userspace-only program. If you have python2.6 you can simply use import multiprocessing multiprocessing.cpu_count() If you're interested into the number of process...
I have a custom form to which I would like to pass a parameter. Following this example I came up with the following code : class EpisodeCreateForm(forms.Form): def __init__(self, *args, **kwargs): my_arg = kwargs.pop('my_arg') super(EpisodeCreateForm, self).__init__(*args, **kwargs) my_field = f...
I'm in the process of publishing a small sample which illustrates precisely what you're asking about: how to use App Engine service account credentials to access Google Cloud Storage (specifically, to list a formatted Google Cloud Storage bucket). When available, this will be part of the https://code.google.com/p/googl...
Express Re : Résolu ! Ouvrir fenêtre Dépôts As tu respecté ce qu'à écris michel2652 ? si oui, pourquoi as tu ton ancien fichier ? tu dois copier/coller, ce qui implique d'effacer ton ancien dossier /etc/apt/sources.list, en aucuns cas il ne dois resté l'ancien.....:rolleyes: tu enregistres et ensuite, tu relance le log...
You can either use the # coding: UTF-8 if your editor is setup to use save the file with the correct encoding Alternatively you can also encode the characters in to their ASCII-only escape sequence. For example, the escape-sequence for é is \u00E9: FRENCH_MONTHS = [u'NotAMonth', u'Janvier', u'F\u00E9vrier', ...] This ...
I'm a bit of newbie at this and am trying to create a scatter chart with custom bubble sizes and colours. The chart displays fine but how do I get a legend saying what the colours refer to. This is as far as I've got: inc = [] out = [] bal = [] col = [] fig=Figure() ax=fig.add_subplot(111) inc = (30000,20000,70000) out...
I've got some code in a module import pygame from pygame.locals import * import reusable from state import state class TitleState(state.State): def __init__(self): #Create data batches self.soundbatch = reusable.resourceloader.ResourceBatch(path="data/sound", type="ogg") self.imagebatch = re...
Possible Duplicate: How can the built-in range function take a single argument or three? The Python documentation for slice() lists the following method signatures: slice(stop) slice(start,stop[,step]) Here are a few examples of creating a slice object with different numbers of arguments: >>> slice(8) slice(None, 8, No...
jibe [resolu] choix des dépôts Bonjour, Je viens d'installer ma première Ubuntu Je voudrais y installer Clamav (si, si, c'est utile pour scanner les partitions windows dont les virus ont désactivé les antivirus ;-) ) mais je me heurte apparemment à un problème de dépôts... Et pas facile de s'y retrouver dans tous ces p...
I have a rather generic model, as follows: class Keyword(models.Model): ancestors = models.ManyToManyField(Keyword) name = models.CharField() description = models.CharField() Trouble is, I have several different types of keywords, which all have different forms of business logic. Some, for example, are nev...
I'm doing some multiprocessing in Python, using classes, and to do such thing I had to use this approach: def _pickle_method(method): func_name = method.im_func.__name__ obj = method.im_self cls = method.im_class if func_name.startswith('__') and not func_name.endswith('__'): #deal with mangled names ...
Access Control web2py includes a powerful and customizable Role Based Access Control mechanism (RBAC). Here is a definition from Wikipedia: "Role-Based Access Control (RBAC) is an approach to restricting system access to authorized users. It is a newer alternative approach to mandatory access control (MAC) and discreti...
I was playing along with this post, and ended up with running code that I had to halt at 7 minutes due to impatience. I jotted down a Groovy script using Jena to mimic the behavior, and got all the results back in a second or two. Is rdflib known to be slow when it queries over a wire, or is my code using a big ineffic...
I prepared an example that shows how to compile a project like yours with just one SConstruct script (no subsidiary SConscripts) using the SCons VariantDir() function. I decided to do this in a separate answer so that it would be easier to read. The VariantDir() function isnt documented very well, so the behavior you m...
Best bet would be a scripting language, e.g. Python. I don't know if you are a programmer, but making a script taking each entry and converting them shouldn't be too long. Here's a basic python script which accesses a few fields: from pybtex.database.input import bibtex #open a bibtex file parser = bibtex.Parser() bibd...
I just started to use Python logging module and I cannot understand something. I'm writing a script that works in the following way: 1st part (single process): it get some data to compute (it's not important how). Here I create a logger in the following way: import logging logging.basicConfig(format='%(asctime)-6s: %(n...
I want to mark all maxima along a given axis of an array (which shape may be n-dimensional), this works fine along the first one, but for the rest I can't figure it out. I don't want to iterate over axis, because there can be arbritarily many of them. >>> A = range(5)*3 >>> A = array(a).reshape([3,5], order='F') >>> A ...
Possible Duplicate: Django models.Model superclass By default, if you inherit a model class, django will create a separate table for the base class. Is there any way to use base class (so that I can have the same columns in all derived models), but NOT have django create that base table, but instead, create derived tab...
I am having troubles understanding how pandas multiindex work. Specifically: how to merge two dataframes of different index level (by row) how can change index level for a dataframe Using an example from a previous question: d1 = pd.DataFrame( {'StudentID': ["x1", "x10", "x2","x3", "x4", "x5", "x6", "x7", "x8", "x...
I was trying to design a model in django with some auditing fields. Such as created at, created by, updated at and updated by. Those four columns are going to be repeated across all my models in different applications. My first question, is there a way to put those columns and can include them in my class each time i n...
You can't because the builtin-types are coded in C. What you can do is subclass the type: class string(str): def sayHello(self): print(self, "is saying 'hello'") Test: >>> x = string("test") >>> x 'test' >>> x.sayHello() test is saying 'hello' You could also overwrite the str-type with class str(str):, bu...
My Method to post a message to server using C# .NET 4.0 private String postHTTP(String url) { String result = ""; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; string postData = "Data has Posted"; byte[] byteArray = Encoding.UTF8.Ge...
Can you change which values are included and how they are formatted, when you download a report as a CSV file from Toggl? I would like to get the duration of the different tasks in a format that numbers can understand as a duration value. No, it is not possible to change it when downloading. However, you can load it in...
sputnick [JEU] #! /challenge/bash #8 << challenge bash #8 Le challenge est ouvert à tous les langages de scripting ! scripteurs bash, python, perl, ruby… à vos claviers ! Robot web pour récupérer les nouveaux fils des sous-forums Ubuntu de son choix. L'objectif est de réaliser un script qui va parser le forum afin d'y ...
I've running Python 2.6.6. cat tbuild.py #!/usr/bin/env python # -*- coding: utf-8 -*- # from mako.template import Template _template=""" % for v in my_list: ${'abc'.encode('utf-8')} ${'風連町?'.encode('utf-8')} % endfor """ print Template(_template).render_unicode(my_list = [1, 2], ...
henry-006 Re : [script] Pixup : Poster une image rapidement sur un forum ah désolé, moi ch'suis allé direct dans la logithèque, comme un bon bourrin, OS: Ubuntu 12.10 (Quetzal quantal ) 64 bits + Windows XP pro SP2 x32 en double boot PC Medion / Processeur: Intel core2 Duo (CPU 2.80GHz) Mémoire vive:3029 MiB Carte Grap...
This project is archived and is in readonly mode. Unexpected conversion to server time zone upon inserting non-naïve `datetime.datetime` Reported by Sam Homerson | August 17th, 2013 @ 05:15 PM Upon inserting a non-naïve datetime.datetime object, i.e. one with a time zone, psycopg2 converts the timestamp before insertin...
I'm posting this, and getting this error: c.execute("""update resulttest set category=""" + key + ", value=""" + str(value)) OperationalError: (1054, "Unknown column 'composed' in 'field list'") I am trying to update the columns category and field, composed is simply a value in category. Why is this error coming up?
Here is code based on the CSV code from The Practice of Programming by Kernighan and Plauger that has been adapted to deal with your weird malformed CSV data. (It wasn't all that hard to do; I already had the main code working and packaged, so I just had to add the CSV output functions and to modify the advquoted() fun...
So I'm running into a problem where the try: except: mechanism doesn't seem to be working correctly in python. Here are the contents of my two files. pytest1.py import pytest2 class MyError( Exception ): def __init__( self, value ): self.value = value def __str__( self ): return repr( self.value...
Obviously impact drivers and impact wrenches are designed for different purposes, but since they both work on the same principle is there some overlap? Is a small cordless impact wrench just a slightly scaled-up version of a cordless impact driver, with a 1/4" square drive instead of a 1/4" hex drive, or are there furt...
I'm assuming there isn't a word that contains every letter in the alphabet, so which word contains the most? Examples: antidisestablishmentarianism - 12 [antidseblhmr] psychotherapy - 12 [psychotherap] handcraftsmanship - 13 [handcrftsmhip] Among words in a certain word list I found: It has ten words with 16, including...
Tony95 Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Salut à tous je savais pas trop où poster donc je le fais ici. J'ai un petit soucis en GTK, j'aimerais créer une interface permettant de charger et sauvegarder des fichiers mais j'arrive vraiment pas à m'en sortir pour le code. En gros j'ai une fe...
hectorau_ben Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc) Même si tu m'as toujours pas répondu, dofus marche parfaitement, sans AUCUN ralentissement, mais le son ne marche pas ... Même si l'Updater est ouvert et que j'ai activé le son dans le options et biensûr, je n'ai pas trouvé la solu...
I'd like to vectorise the difference of two M x N arrays across different slices in NumPy. Something like this: dA = A[1:,:] - A[:-1,:] dB = B[:,1:] - B[:,:-1] C = dA * dB But since dA is (M-1) x N and dB is M x (N-1), it's not a valid operation. In other words, is there a way to vectorise this loop in NumPy? for i in...
I have plotted a timeseries of carbon fluxes over 16 years at a particular site. I would like the x-axis to have years (1992-2007) instead of year number (1-16). When I set the x-axis to have a min value of 1992 and a max value of 2007, the graph doesnt appear on the plot, but when I dont set the min/max years, it appe...
Piddle Graphics Online by Michal Wallace 06/28/2001 In Generating Graphics With Piddle we generated a gantt chart using piddle and the Python Imaging Library. Now we'll extend this concept to generate graphics in real time on the Web. We'll build on the code from the previous article, making references to it as we go a...
I've compiled a mosaic of 2025 headshots from the avatars of the top Stack Overflow users. (Click the image to view it full-size.) Your task is to write an algorithm that will create an accurate photomosaic of another image using the 48×48 pixel avatars from this 45×45 grid of them. Test Images Here are the test imag...
I am working on an desktop inbox notifier for StackOverflow, using the API with Python. The script I am working on first logs the user in on StackExchange, and then requests authorisation for the application. Assuming the application has been authorised through web-browser interaction of the user. The application shoul...
Is there a way to get the complete django url configuration? For example Django's debugging 404 page does not show included url configs, so this is not the complete configuration. Answer: Thanks to Alasdair, here is an example script: import urls def show_urls(urllist, depth=0): for entry in urllist: print ...
I want to get the output from some shell commands like ls or df in a python script. I see that commands.getoutput('ls') is deprecated but subprocess.call('ls') will only get me the return code. I'll hope there is some simple solution. Use import subprocess process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE...
Yo standard (un stdyo en quelque sorte) Ni une, ni deux, je choppe les sources C++, Python et Python + Jit (Mumba en l'occurrence), je compile et lance les benchs. Rien de très surprenant: $ python RBC_Python.py[ (...) Yo standard (un stdyo en quelque sorte) Ni une, ni deux, je choppe les sources C++, Python et Python ...
What are metaclasses? What do you use them for? A metaclass is the class of a class. Like a class defines how an instance of the class behaves, a metaclass defines how a class behaves. A class is an instance of a metaclass. While in Python you can use arbitrary callables for metaclasses (like Jerub shows), the more use...
Possible Duplicate: Cyclic module dependencies and relative imports in Python Consider the following example of cyclic imports in python: main.py: from pkg import foo pkg/__init.py__: # empty pkg/foo.py: from pkg import bar pkg/bar.py: from pkg import foo Running main.py will cause an exception: Traceback (most rece...
#1426 Le 14/11/2010, à 14:58 xapantu Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux @Xapantu : Ella a maintenant des bugs inadmissibles, des plantages qui sont des régressions d'une année, à peu de choses près ; je voudrais donc savoir : Faut le dire vite quand même. J'ai résolu au moins 3-4 problème...
it is possible to use Python to signal when an mp3 file, or other audio file, has finished playing/reached their end? I know how to play them, as per the BGE code below, but don't how do I check if the are finished? sound = aud.Factory('audio.mp3') #loads mp3 or wav file if not 'play' in ow: #will play sound only onc...
py2port Py2port is a tool for performing two-port and one-port analysis on linear circuits. It was developed for analyzing PCB Power-Distribution-Systems and lossy-transmission lines but can be used as a more general purpose simulation tool. Latest Release Added phase to the forward and reverse gain plots, cleaned up s...
cherrak Re : A quoi ressemble votre environnement - automne/hiver 2011/2012 Ok merci pour la precision ! Dernière modification par cherrak (Le 07/03/2012, à 03:09) Major Grubert Re : A quoi ressemble votre environnement - automne/hiver 2011/2012 Question bête : quel est le paramètre à modifier pour avoir un affichage "...
How can I tell python to scan the current directory for a file called "filenames.txt" and if that file isn't there, to extract it from a zip file called "files.zip"? I know how to work zipfile, I just don't know how to scan the current directory for that file and use if/then loops with it.. import os, zipfile if 'filen...
It was discovered that libMikMod incorrectly handled songs with different channel counts. If a user were tricked into opening a crafted song file, an attacker could cause a denial of service. It was discovered that libMikMod incorrectly handled certain malformed XM, Impulse Tracker, and Ultratracker files. If a user we...
I have some hierarchical data where each Set can have many members and can belong to more than one Set(group) Here are the models: class Set(models.Model): ... groups = models.ManyToManyField('self', through='Membership', symmetrical=False) members = models.ManyToManyField('self', through='Membership', symm...
cmarcx Re : [Script] Client Hubic pour linux ;) Bonjour, J'ai essayé de monter hubic avec la commande : ./hubicmount -l <email> -p <passwd> -o umask=022 -o uid=1000 /media/hubic Mais j'obtiens toujours l'erreur "Unable to login to hubic". Pourtant les logins indiqués sont bons, je fais un copier-coller, et ils fonction...
Dernière news : Fedora-Fr aux 15èmes Rencontres Mondiales du Logiciel Libre Bien le bonjour, bien le bonsoir. Après avoir installé skype en téléchargent la version : J'ai essayé de le lancer, mais un problème surgit.. Impossible de lancer << skype >> L’exécution du processus fils << skype >> a échoué (Aucun fichier ou...
I'm new to python and dbus, but is there a data binding (= a way to send and receive) python classes via dbus-python? My class looks like this: class Item: def __init__(self, one, two, three, four, five, *more): self.one= one self.two= two self.three= three self.four= four se...
MongoDB Schema Design: Data as Documents This is a write-up of Kyle Banker's talk at the 2010 MongoUK conference in London. It was very useful; I only wish I'd been able to note more of it down. Introduction Kyle's advice is to get to know the database by playing with it. Head over to try.mongodb.org and have a play wi...
hectorau_ben Re : [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc) Même si tu m'as toujours pas répondu, dofus marche parfaitement, sans AUCUN ralentissement, mais le son ne marche pas ... Même si l'Updater est ouvert et que j'ai activé le son dans le options et biensûr, je n'ai pas trouvé la solu...
Linux Advanced Routing Tutorial Solving the DMZ Challenge What we need now is to set up a special routing table for all DMZ traffic and create a rule that will plug it in to the routing decision process. The first step is to create and populate the new table and name it "dmz". We can choose any non-reserved table ID an...
A Million-user Comet Application with Mochiweb, Part 3 Written on 04 November 2008 In Part 1 and Part 2 of this series we built a comet application using mochiweb, and learned how to route messages to connected users. We managed to squeeze application memory down to 8KB per connection. We did ye olde c10k test, and obs...
I am beginner in Python and have been facing this problem for some time. Any suggestions to correct the problem would be valuable. Below is the code used to find the shortest path, using Dijkstra's algorithm. I have the cost matrix and the source as Input. def dijkstra(cost_matrix,source): n = 20 dist = [0 for ...
I have a very simple *.py file: import webapp2 from google.appengine.api import users class MainPage(webapp2.RequestHandler): def get(self): user = users.get_current_user() if user: self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Hello, ' + user.nick...
I've been able to use a django form and template to insert data to the database. I can also display the data in a very basic HTML page. However, am completely unable to figure out how I go about editing the data. Am assuming that I can at least reuse the django template I used to create a new database entry to also edi...
henry-006 Re : [script] Pixup : Poster une image rapidement sur un forum ah désolé, moi ch'suis allé direct dans la logithèque, comme un bon bourrin, OS: Ubuntu 12.10 (Quetzal quantal ) 64 bits + Windows XP pro SP2 x32 en double boot PC Medion / Processeur: Intel core2 Duo (CPU 2.80GHz) Mémoire vive:3029 MiB Carte Grap...
I have python 2.7 installed and I'm facing errors while trying to run scripts in Python. The GUI based Launchpad app Ground Control can't start and is facing bugs. But even a simple program can't run: from urllib import urlencode from urllib2 import urlopen pg = urlopen("http://www.beans-r-us.biz/proces.html") text = p...
Update (May 2014): Please note that these instructions are outdated. while it is still possible (and in fact easier) to blog with the Notebook, the exact process has changed now that IPython has an official conversion framework. However, Blogger isn't the ideal platform for that (though it can be made to work). If you ...
The below code is extracting the top headlines from ESPN/college-football. I can grab the title of the article and the link. I can print both of those but I would also like to email them. I can get the title to email but not the href attribute. Any idea what's going on? from urllib import urlopen from BeautifulSoup imp...
В одном проекте я использовал redis для хранения статистики, собираемой из нескольких процессов python на одной машине. Статистика складывалась в redis в hash или словарь. Попробовал заменить место хранения на словарь в питоне и вот, что из этого вышло: from multiprocessing import Pool, Manager, Lock lock = Lock() mana...
I have a code like this: import matplotlib.pyplot as plt from matplotlib.pyplot import * from matplotlib.font_manager import FontProperties fontP = FontProperties() fontP.set_size('xx-small') fig=plt.figure() ax1=fig.add_subplot(111) plot([1,2,3], label="test1") ax1.legend(loc=0, ncol=1, bbox_to_anchor=(0, 0, 1, 1), ...
Try adding in some windows using glade: Open up a terminal, go to your project directory and type "quickly edit" - That will launch glade (gui designer) and it will automatically load in your project's ui files. In glade you can add windows by going to the Toplevels area on the left side and choosing which type of wind...
How to connect to the following url using twisted and get the response from the tracker. udp://tracker.publicbt.com:80/announce?uploaded=0&downloaded=0&compact=1&event=started&peer_id=kovid_agarwal1235467&port=6881&info_hash=3389809f0c9096819294a680beb4adb96a738419&left=763922958 I tried the following code but I am get...
You can split the string into two: def foo(): if conditional(): logger.info("<Conditional's meaning> happened, so we're not " "setting up the interface.") Multiple consecutive strings within the same expression are automatically concatenated into one, at compile time: >>> def foo(): ......
As an assignment, I'm trying to create two classes: One class, Book, looks to see if a book is checked out and returns the title, author and page numbers in a book (these are input variables) and the other class, called Library, adds title - author pairs to a dictionary and sees if some particular book is checked out o...
I have a array which is created as below: im = plt.array(Image.open('Mean.png').convert('L')) I have to convert all its values for an specified range. To do this, I have this function: def translate(value, inputMin, inputMax, outputMin, outputMax): # Figure out how 'wide' each range is leftSpan = inputMax - in...
The basic usefulness for green threads, the way I see it, is to implement a system in which you have a large amount of objects that do high latency operations. A concrete example would be communicating with other machines: def Run(): # Do stuff request_information() # This call might block # Proceed doing m...
This program has been disqualified. Author dllu Submission date 2011-06-14 22:17:45.501924 Rating 7760 Matches played 2497 Win rate 76.57 #This is a DNA werfer. It werfs DNA! import random number_of_predictors = 36 #yes, this really has 36 predictors. predictors=range(number_of_predictors) for i in range(number_of_pred...
sound karligula at March 8th, 2007 10:28 — #1 Hi folks, I'm writing some stuff using midi files and I need to convert the midi time stamps for each midi event into milliseconds. I've searched the web and every document I come across blathers on about quarter notes, tempo, beats per minute, measures, bars, ticks, metron...
Ok so i'm trying to run Python with Bottle.py, thru Apache and mod_wsgi, and it doesn't work so far... I'm running it on windows, using a xampp. python v2.7 the code i added to httpd(Apache config): <VirtualHost *> ServerName example.com WSGIScriptAlias / C:\xampp\htdocs\GetXPathsProject\app.wsgi <Directory C:\xampp\ht...
Just having some problems with xdotool here - great program, but unfortunately hasn't been behaving. from Tkinter import * import os class Ed: def __init__(self,parent): self.button = Button(parent,command=self.passthrough) self.button.pack() parent.geometry('+100+100') def passthrough(self): print '...
I'm using python + matplotlib and I'm having two plots share an axis. If you try to set graph1.set_xticklabels([]) while sharing an axis, it has no effect because it is shared. Is there a way to share the axis AND be able to hide the x axis of one plot? This is a common gotcha when using shared axes. Fortunately, there...
So I'm making a very small program for personal use in tkinter, and I've run into a really strange wall. I'm mixing tkinter with the pywin32 bindings because I really hate everything to do with the syntax and naming conventions of pywin32, and it feels like tkinter gets more done with far less code. The strangeness is ...
Let's say I've two models: class Book(models.Model): name = models.CharField(max_length=50) library = models.ForeignKeyField('Library') class Library(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=50) tel = models.CharField(max_length=50) Is there a...
The boo compiler follows the common design of internally representing code using what’s usually called a heterogeneous abstract syntax tree, ast for short. Code constructs such as class and method definitions, if and while statements, references and all sorts of expressions are represented by specific concrete types ...
For set data to the treeview, I'm using the set_cell_data_func at some columns. source like this: myRenderer = gtk.CellRendererText() column = gtk.TreeViewColumn("col1", myRenderer, text=columnId) column.set_cell_data_func(myRenderer, func1) def func1(self, column, cell, model, iter): cell_name = model.get_value(it...
I'd like to have arrays that start from say an index of 4 and go to 9. I'm not interested in creating memory space for < 4, so how is best to proceed? My 2D code is as follows: arr = [[ 0 for row in range(2)] for col in range(1, 129)] >>> arr[0][0] = 1 >>> arr[128][0] = 1 Traceback (most recent call last): File "<std...
i have a multithreaded library in which i call sleep(3) in different threads. i have written python bindings for it using boost python. now it looks like boost python is messing up with the sleep(3) function as it pauses the whole python program to wait. please consider i have this boostmod.cpp file #include <boost/pyt...
I am trying to plot some data and I am getting this error from the noted line. I googled the line but couldn't find any meaningful discussion on this issue. I am new to Python so trying to figure this stuff out as I go along. pl.figure() ax = pl.subplot(111) ax.plot(Xk[:,0], Xk[:,1], '.') ERROR=>>> twos = (y == 2).n...
Witting Hex to a Text File Hello Guys . Can any one help me to port this python code to C? 1 2 3 4 5 buff = "\x41"*300 exp = buff file=open("file.txt","w") file.write(exp) file.close() And if there is shellcode like this in python. How can we port it to C? header = "http://." buff = "\x41"*17416 esp = "\xED\x1E\x94\x7...
Your first test case has to call the method insert on the list a, whereas all the operations in test2 are handled directly in byte code. Note the CALL_FUNCTION in the disassembly of test1 below. Calling functions is moderately expensive in Python: certainly expensive enough to account for a few percent difference in ru...
I have a large project consisting of sufficiently large number of modules, each printing something to the standard output. Now as the project has grown in size, there are large no. of print statements printing a lot on the std out which has made the program considerably slower. So, I now want to decide at runtime wheth...
I am using google app engine and I am trying to basically allow users to upload code, where it will later be executed by the server. I also have to be able to send variables to the scripts, which is why initially when I was running everything on my desktop, I Imported everything dynamically (as in- the name of the scri...
I solved Problem 10 of Project Euler with the following code, which works through brute force: def isPrime(n): for x in range(2, int(n**0.5)+1): if n % x == 0: return False return True def primeList(n): primes = [] for i in range(2,n): if isPrime(i): primes.append...
Ruby has a couple of well-known libraries for unit testing, mocking and stubbing HTTP interactions. My typical toolset includes RSpec, WebMock and VCR. I had the chance to work on a Python project recently and did some investigation into similar libraries for Python. General testing libraries The two most popular pytho...
The correct answer is, use the validatecommand feature. The problem is, this feature is severely under-documented in the Tkinter world (but quite sufficiently documented in the Tk world). Even though it's not documented well, it has everything you need to do validation without resorting to bindings or tracing variables...
For speed, try using GRequests to check urls asynchronously (not one at a time). Code import grequests urls = [ 'http://www.heroku.com', 'http://tablib.org', 'http://httpbin.org', 'http://python-requests.org', 'http://kennethreitz.com' ] rs = (grequests.get(u) for u in urls) # For even faster status...
I have written a function for adding emails to newsletter base. Until I've added checking validity of sent email it was working flawlessly. Now each time I'm getting "Wrong email" in return. Can anybody see any errors here ? The regex used is : \b[\w\.-]+@[\w\.-]+\.\w{2,4}\b and it is 100% valid (http://gskinner.com/Re...
August 5th, 2014 |Published inDatabase, Tech Talk | 5 Comments Recently I stumbled across a question on Reddit regarding the performance impact of using pgBadger on an active database server. The only real answer to this question is: do not use pgBadger. Before anyone asks—no, you shouldn’t use pgFouine either. This is...
How does Python manage memory? The details of Python memory management depend on the implementation.The standard C implementation of Python uses reference counting todetect inaccessible objects, and a separate mechanism to collectreference cycles, periodically executing a cycle detection algorithmwhich looks for inacce...