rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if message.has_key('failure reason'): if type(message['failure reason']) != StringType: raise ValueError return
def check_message(message): if type(message) != DictType: raise ValueError if message.has_key('failure reason'): if type(message['failure reason']) != StringType: raise ValueError return check_info(message.get('info')) if type(message.get('announce')) != StringType: raise ValueError
del c.upload del c.download
def connection_lost(self, connection): c = self.connections[connection] d = c.download del c.upload del c.download del self.connections[connection] d.disconnected() self.choker.connection_lost(c)
if n == 0 and newf != f+1:
if x[f:newf] != str(n):
def decode_int(x, f): newf = x.index('e', f) n = long(x[f:newf]) if x[f] == '0' and n != 0: raise ValueError if n == 0 and newf != f+1: raise ValueError return (n, newf+1)
if x[f] == '0' and n != 0: raise ValueError if n == 0 and colon != f + 1: raise ValueError colon = colon + 1
if n < 0: raise ValueError if x[f:colon] != str(n): raise ValueError colon += 1
def decode_string(x, f): colon = x.index(':', f) n = long(x[f:colon]) if x[f] == '0' and n != 0: raise ValueError if n == 0 and colon != f + 1: raise ValueError colon = colon + 1 return (x[colon:colon+n], colon+n)
record['nat'] = 0
def connectback_result(self, result, downloadid, peerid, ip, port): record = self.downloads.get(downloadid, {}).get(peerid) if record is None or record['ip'] != ip or record['port'] != port: return if not record.has_key('nat'): record['nat'] = int(not result) if result: record['nat'] = 0 self.becache1.setdefault(downlo...
self.connecter.connection_flushed(self.connections[connection])
c = self.connections[connection] if c.complete: self.connecter.connection_flushed(c)
def connection_flushed(self, connection): self.connecter.connection_flushed(self.connections[connection])
def choose(self, default, size, saveas, dir, file = file):
def choose(self, default, size, saveas, dir):
def choose(self, default, size, saveas, dir, file = file): return self.file[:-len(ext)]
activity = None, save = save()):
activity = None):
def status(self, fractionDone = None, timeEst = None, downRate = None, upRate = None, activity = None, save = save()): if fractionDone is not None: newpercent = int(fractionDone*100) if newpercent != self.percentDone: self.percentDone = newpercent print self.file + (': %d%%' % newpercent) if activity is not None: print...
else: self.downloader.picker.bump(index)
for d in self.downloader.downloads: d.fix_download_endgame() return false self.downloader.picker.bump(index)
def got_piece(self, index, begin, piece): try: self.active_requests.remove((index, begin, len(piece))) except ValueError: return false if self.downloader.storage.is_endgame(): self.downloader.all_requests.remove((index, begin, len(piece))) for d in self.downloader.downloads: try: if d is not self: d.active_requests.rem...
for i in range(l, length, interval)[1:] + [length-1]:
for i in lrange(l, length, interval)[1:] + [length-1]:
def __init__(self, files, open, exists, getsize, statusfunc, alloc_pause = 3): # can raise IOError and ValueError self.ranges = [] total = 0l so_far = 0l for file, length in files: if length != 0: self.ranges.append((total, total + length, file)) total += length if exists(file): l = getsize(file) if l > length: raise V...
make_meta_file(i, url, flag = flag, progress = callback)
try: make_meta_file(i, url, flag = flag, progress = callback) except ValueError: print_exc()
def callback(x, subtotal = subtotal, total = total, vc = vc): subtotal[0] += x vc(float(subtotal[0]) / total)
if self.id is None:
if not self.id:
def read_peer_id(self, s): if self.id is None: for v in self.encoder.connections.values(): if v.id == s: return None self.id = s if self.locally_initiated: connection.write(self.encoder.my_id) else: self.encoder.everinc = True else: if s != self.id: return None self.complete = True self.encoder.connecter.connection_mad...
connection.write(self.encoder.my_id)
self.connection.write(self.encoder.my_id)
def read_peer_id(self, s): if self.id is None: for v in self.encoder.connections.values(): if v.id == s: return None self.id = s if self.locally_initiated: connection.write(self.encoder.my_id) else: self.encoder.everinc = True else: if s != self.id: return None self.complete = True self.encoder.connecter.connection_mad...
if id and id == self.my_id: return for v in self.connections.values(): if v.id == id:
if id: if id == self.my_id:
def start_connection(self, dns, id): if len(self.connections) >= self.max_initiate: return if id and id == self.my_id: return for v in self.connections.values(): if v.id == id: return try: c = self.raw_server.start_connection(dns) self.connections[c] = Connection(self, c, id) except socketerror: pass
myid = sha(repr(time()) + ' ' + str(getpid())).digest()
myid = (chr(0) * 12) + sha(repr(time()) + ' ' + str(getpid())).digest()[-8:]
def make(f, forcedir = false): if not forcedir: f = path.split(f)[0] if f != '' and not path.exists(f): makedirs(f)
infohash = (chr(0) * 12) + sha(bencode(info)).digest()[-8:]
infohash = sha(bencode(info)).digest()
def make_upload(connection, choker = choker, storagewrapper = storagewrapper, max_slice_length = config['max_slice_length'], max_rate_period = config['max_rate_period'], fudge = config['upload_rate_fudge']): return Upload(connection, choker, storagewrapper, max_slice_length, max_rate_period, fudge)
n = int(n)
n = long(n)
def hours(n): if n == -1: return '<unknown>' if n == 0: return 'complete!' n = int(n) h, r = divmod(n, 60 * 60) m, sec = divmod(r, 60) if h > 1000000: return '<unknown>' if h > 0: return '%d hour %02d min %02d sec' % (h, m, sec) else: return '%d min %02d sec' % (m, sec)
if 'uprate' in info: totalup += info['uprate'] if 'downrate' in info: totaldown += info['downrate']
totalup += info.get('uprate', 0) totaldown += info.get('downrate', 0)
def runmany(d, params): threads = [] deadfiles = [] try: while 1: files = listdir(d) # new files for file in files: if file[-len(ext):] == ext: if file not in [x.getName() for x in threads] + deadfiles: wininfo[file] = {'basex': 2 * len(threads), 'killflag': Event()} statuswin.erase() statuswin.addnstr(0, 0,'new torren...
if not self.only_local_override_ip or ip[:3] == '10.' or ip[:4] in ('192.', '169.', '127.'):
if not self.only_local_override_ip or is_local_ip(ip):
def get(self, connection, path, headers): try: (scheme, netloc, path, pars, query, fragment) = urlparse(path) if self.uq_broken == 1: path = path.replace('+',' ') query = query.replace('+',' ') path = unquote(path)[1:] params = {} for s in query.split('&'): if s != '': i = s.index('=') params[unquote(s[:i])] = unquote(...
def is_local_ip(ip): try: v = [long(x) for x in '.'.split(ip)] if v[0] == 10 or v[:1] in ([192, 168], [169, 254]): return 1 if v[0] == 172 and v[1] >= 16 and v[1] <= 31: return 1 except ValueError: return 0
def expire_downloaders(self): for x in self.times.keys(): for myid, t in self.times[x].items(): if t < self.prevtime: del self.times[x][myid] del self.downloads[x][myid] self.prevtime = time() if (self.keep_dead != 1): for key, value in self.downloads.items(): if len(value) == 0: del self.times[key] del self.downloads[...
for configName, longDescription, shortDescription, defaultValue, usageText in optionDefintions: argDescript = "" if longDescription: if takesArgument(longDescription): sys.stdout.write(longLineForm(longDescription) + " <value>\n") else: sys.stdout.write(longLineForm(longDescription) + "\n")
outArray = [] maxOptLength = 0 for i in optionDefintions: garbage, longDescription, shortDescription, garbage, doc = i
def usage(usageHeading, optionDefintions, msg, exitCode=1): if msg: sys.stderr.write('error: %s\n' % msg) sys.stdout.write('%s\n' % usageHeading) for configName, longDescription, shortDescription, defaultValue, usageText in optionDefintions: argDescript = "" if longDescription: if takesArgument(longDescription): sys.st...
if shortDescription: if takesArgument(shortDescription): sys.stdout.write(shortLineForm(shortDescription) + '<value>\n') else: sys.stdout.write(shortLineForm(shortDescription) + '\n')
lineForm = combinedLineForm(longDescription, shortDescription) if maxOptLength < len(lineForm): maxOptLength = len(lineForm) outArray.append( (lineForm, doc) )
def usage(usageHeading, optionDefintions, msg, exitCode=1): if msg: sys.stderr.write('error: %s\n' % msg) sys.stdout.write('%s\n' % usageHeading) for configName, longDescription, shortDescription, defaultValue, usageText in optionDefintions: argDescript = "" if longDescription: if takesArgument(longDescription): sys.st...
if defaultValue: sys.stdout.write("\tdefault value: %s" % defaultValue) sys.stdout.write("\t%s\n\n" % usageText)
try: import curses curses.initscr() COLS = curses.COLS except: COLS = 80 firstLineString = "%%-%ds : " % maxOptLength bodyLineString = " " * len(firstLineString % "") targetBodyWidth = COLS - len(bodyLineString) - 2 if targetBodyWidth < 10: targetBodyWidth = COLS - 1 firstLineString = firstLineString[:-3] + "\n " bod...
def usage(usageHeading, optionDefintions, msg, exitCode=1): if msg: sys.stderr.write('error: %s\n' % msg) sys.stdout.write('%s\n' % usageHeading) for configName, longDescription, shortDescription, defaultValue, usageText in optionDefintions: argDescript = "" if longDescription: if takesArgument(longDescription): sys.st...
if code == WSAENOBUFS:
if haveWSAENOBUFS and (code == WSAENOBUFS):
def listen_forever(self, handler): self.handler = handler try: while not self.doneflag.isSet(): try: self.pop_external() if len(self.funcs) == 0: period = 2 ** 30 else: period = self.funcs[0][0] - time() if period < 0: period = 0 events = self.poll.poll(period * timemult) if self.doneflag.isSet(): return while len(self...
completedir(argv[1], argv[2], dc)
completedir(argv[1], argv[2], fc = dc)
def dc(v): print v
sellf.url += '&ip=' + quote(ip)
self.url += '&ip=' + quote(ip)
def __init__(self, url, interval, sched, howmany, minpeers, connect, externalsched, amount_left, up, down, port, ip, myid, infohash, timeout, errorfunc): self.url = ('%s?info_hash=%s&peer_id=%s&port=%s' % (url, quote(infohash), quote(myid), str(port))) if ip != '': sellf.url += '&ip=' + quote(ip) self.interval = interv...
storage = Storage(files, open, path.exists, path.getsize, statusfunc)
try: storage = Storage(files, open, path.exists, path.getsize, statusfunc) except IOError, e: errorfunc('trouble accessing files - ' + str(e)) return
def failed(reason, errorfunc = errorfunc, doneflag = doneflag): doneflag.set() if reason is not None: errorfunc(reason)
if v[0] == 10 or v[0] == 127 or v[:1] in ([192, 168], [169, 254]):
if v[0] == 10 or v[0] == 127 or v[:2] in ([192, 168], [169, 254]):
def is_local_ip(ip): try: v = [long(x) for x in ip.split('.')] if v[0] == 10 or v[0] == 127 or v[:1] in ([192, 168], [169, 254]): return 1 if v[0] == 172 and v[1] >= 16 and v[1] <= 31: return 1 except ValueError: return 0
h = HTTP(host)
def readput(url, data): protocol, host, path, g1, g2, g3 = urlparse(url) if protocol == 'http': h = HTTPConnection(host) elif protocol == 'https': h = HTTPSConnection(host) else: raise ValueError, "can't handle protocol '" + protocol + "'" h = HTTP(host) h.putrequest('PUT', path) h.putheader('content-length', str(len(d...
if (self.allowed is not None) and self.allowed.has_key(name):
if (self.allowed is not None) and self.allowed.has_key(name) and self.show_names:
def get(self, connection, path, headers): try: (scheme, netloc, path, pars, query, fragment) = urlparse(path) if self.uq_broken == 1: path = path.replace('+',' ') query = query.replace('+',' ') path = unquote(path)[1:] params = {} for s in query.split('&'): if s != '': i = s.index('=') params[unquote(s[:i])] = unquote(...
self.close_socket(s) self.poll.unregister(sef.socket)
self.server.close() self.poll.unregister(self.server)
def handle_events(self, events): for sock, event in events: if sock == self.server.fileno(): if event & (POLLHUP | POLLERR) != 0: self.close_socket(s) self.poll.unregister(sef.socket) print "lost server socket" else: newsock, addr = self.server.accept() newsock.setblocking(0) nss = SingleSocket(self, newsock) self.sing...
activity = dict.get('activity', None);
def onUpdateStatus(self, dict): fractionDone = dict.get('fractionDone', None); timeEst = dict.get('timeEst', None); downRate = dict.get('downRate', None); upRate = dict.get('upRate', None); activity = dict.get('activity', None); downTotal = dict.get('downTotal', None); upTotal = dict.get('upTotal', None); if fractionDo...
if activity is not None and not self.fin: self.timeEstText.SetLabel(activity)
def onUpdateStatus(self, dict): fractionDone = dict.get('fractionDone', None); timeEst = dict.get('timeEst', None); downRate = dict.get('downRate', None); upRate = dict.get('upRate', None); activity = dict.get('activity', None); downTotal = dict.get('downTotal', None); upTotal = dict.get('upTotal', None); if fractionDo...
frame = wxFrame(None, -1, 'BitTorrent download', size = wxSize(400, 250))
frame = wxFrame(None, -1, 'BitTorrent ' + version + ' download', size = wxSize(400, 250))
def __init__(self, flag): frame = wxFrame(None, -1, 'BitTorrent download', size = wxSize(400, 250)) self.frame = frame self.flag = flag self.fin = false self.shown = false
self.frame.SetTitle('%d%% %s - BitTorrent' % (int(fractionDone*100), self.filename))
self.frame.SetTitle('%d%% %s - BitTorrent %s' % (int(fractionDone*100), self.filename, version))
def onUpdateStatus(self, fractionDone, timeEst, downRate, upRate, activity): if fractionDone is not None and not self.fin: self.gauge.SetValue(int(fractionDone * 1000)) self.frame.SetTitle('%d%% %s - BitTorrent' % (int(fractionDone*100), self.filename)) if timeEst is not None: self.timeEstText.SetLabel(hours(timeEst)) ...
self.frame.SetTitle('%s - Upload - BitTorrent' % (self.filename))
self.frame.SetTitle('%s - Upload - BitTorrent %s' % (self.filename, version))
def onFinishEvent(self): self.timeEstText.SetLabel('Download Succeeded!') self.cancelButton.SetLabel('Finish') self.gauge.SetValue(1000) self.frame.SetTitle('%s - Upload - BitTorrent' % (self.filename)) self.downRateText.SetLabel('')
self.frame.SetTitle(default + '- BitTorrent')
self.frame.SetTitle(default + '- BitTorrent ' + version)
def onChooseFile(self, default, bucket, f, size, dir): if dir: dl = wxDirDialog(self.frame, 'Choose a directory to save to, pick a partial download to resume', join(getcwd(), default), style = wxDD_DEFAULT_STYLE | wxDD_NEW_DIR_BUTTON) else: dl = wxFileDialog(self.frame, 'Choose file to save as, pick a partial download ...
fileDestText.SetLabel(path)
self.fileDestText.SetLabel(path)
def newpath(self, path): fileDestText.SetLabel(path)
if fractionDone is not None:
if fractionDone is not None and not self.fin:
def onUpdateStatus(self, fractionDone, timeEst, downRate, upRate, activity): if fractionDone is not None: self.gauge.SetValue(int(fractionDone * 1000)) newpercent = int(fractionDone*100) if newpercent == 100: self.frame.SetTitle('%s - Upload - BitTorrent' % (self.filename)) else: self.frame.SetTitle('%d%% %s - BitTorre...
newpercent = int(fractionDone*100) if newpercent == 100: self.frame.SetTitle('%s - Upload - BitTorrent' % (self.filename)) else: self.frame.SetTitle('%d%% %s - BitTorrent' % (newpercent, self.filename))
self.frame.SetTitle('%d%% %s - BitTorrent' % (int(fractionDone*100), self.filename))
def onUpdateStatus(self, fractionDone, timeEst, downRate, upRate, activity): if fractionDone is not None: self.gauge.SetValue(int(fractionDone * 1000)) newpercent = int(fractionDone*100) if newpercent == 100: self.frame.SetTitle('%s - Upload - BitTorrent' % (self.filename)) else: self.frame.SetTitle('%d%% %s - BitTorre...
except Exception, e:
except:
def _getAppData(self): if self._realAppData is None: # initialise AppData the first time it's actually needed try: self._realAppData = AppData(self._Application, self._path, self._pid, self._url, self._terms) except Exception, e: import sys, traceback print >> sys.stderr, '(A problem occured in AS_appdata; see first tr...
print >> sys.stderr, '(A problem occured in AS_appdata; see first traceback for actual error.)'
print >> sys.stderr, 'Traceback for AS_appdata error:'
def _getAppData(self): if self._realAppData is None: # initialise AppData the first time it's actually needed try: self._realAppData = AppData(self._Application, self._path, self._pid, self._url, self._terms) except Exception, e: import sys, traceback print >> sys.stderr, '(A problem occured in AS_appdata; see first tr...
print >> sys.stderr, '\n\n\n' return 0
print >> sys.stderr raise RuntimeError, 'An error occured in AS_appdata.'
def _getAppData(self): if self._realAppData is None: # initialise AppData the first time it's actually needed try: self._realAppData = AppData(self._Application, self._path, self._pid, self._url, self._terms) except Exception, e: import sys, traceback print >> sys.stderr, '(A problem occured in AS_appdata; see first tr...
myns._import_ns(value)
myns.import_namespace(value)
def import_namespace(self, ns): for name in ns: value = ns[name] if isinstance(value, namespace): try: myns = self[name] if not isinstance(myns, namespace): raise TypeError('value-namespace conflict') except KeyError: myns = self.new_namespace(name) myns._import_ns(value) else: self[name] = value
...and accessed the same way:
...and accessed the same way, or with [...]:
def __setattr__(self, name, value): obj = self.namespace.new_namespace(self.name) obj[name] = value
self.gngeorc_buffer = None
self.gngeorc_buffer = []
def __init__(self,datarootpath,xgngeoUserDir,gngeoUserDir): #Initial attributes. self.datarootpath = datarootpath self.gngeorc_buffer = None self.paths = { "xgngeoUserDir" : xgngeoUserDir, #XGngeo local configuration directory. "xgngeoConf" : os.path.join(xgngeoUserDir,"xgngeo.conf"), #Path to XGngeo config file. "gnge...
"effect": None,
"effect": "none",
def getDefaultParams(self): """Returns default options for the `gngeorc'/Rom-specific and XGngeo configuration files.""" return { #Gngeo default. #Important path section. "rompath": os.path.expanduser("~/..."), "romrc":os.path.join(prefix,"share","gngeo","romrc"), #Display section. "fullscreen":"false", "interpolation"...
scan_dir_for_roms()
if self.widgets["fileselect_dialog"].get_current_folder(): scan_dir_for_roms()
def update_preview(*args): selection = self.widgets["fileselect_dialog"].get_preview_filename()
"""Indicating whether any BIOS is present on a given directory,
"""Indicating whether any BIOS files are present on a given directory,
def get_bios_presence(self, path,give_type=0): """Indicating whether any BIOS is present on a given directory, with optional information regarding its/their type.""" if give_type: pass else: pass return True
self.updateFile()
self.update_file()
def add_rom(self, name, path, size): "Adding a new Rom to the list, with duplicate entries prevention."
for dir in self.romdir_list: content += dir
for dir in self.romdir_list[1:]: content += "%s\n" % dir
def callback(widget,response): if response==gtk.RESPONSE_APPLY: self.romdir_list = temp_romdir_list #Validating the ROM list.
for line in file.readlines(): self.romdir_list.append(line)
for line in file.readlines(): if line.strip(): self.romdir_list.append(line[:-1])
def callback(widget,response): if response==gtk.RESPONSE_APPLY: self.romdir_list = temp_romdir_list #Validating the ROM list.
self.xgngeoconf_dir = os.path.expanduser("~/.xgngeo") self.xgngeoconf_file = os.path.join(self.xgngeoconf_dir,"xgngeo.conf") self.gngeoDir = os.path.expanduser("~/.gngeo") self.gngeorcPath = os.path.join(self.gngeoDir,"gngeorc")
self.xgngeoUserDir = os.path.expanduser("~/.xgngeo") self.xgngeoConfFile = os.path.join(self.xgngeoUserDir,"xgngeo.conf") self.gngeoUserDir = os.path.expanduser("~/.gngeo") self.gngeorcPath = os.path.join(self.gngeoUserDir,"gngeorc") for dir in (self.xgngeoUserDir,self.gngeoUserDir): if not os.path.isdir(dir): os.mkdi...
def __init__(self,datarootpath): self.datarootpath = datarootpath self.xgngeoconf_dir = os.path.expanduser("~/.xgngeo") #XGngeo local configuration directory. self.xgngeoconf_file = os.path.join(self.xgngeoconf_dir,"xgngeo.conf") #Path to XGngeo config file. self.gngeoDir = os.path.expanduser("~/.gngeo") #Gngeo local c...
return os.path.isfile(self.gngeorcPath),os.path.isfile(self.xgngeoconf_file)
return os.path.isfile(self.gngeorcPath),os.path.isfile(self.xgngeoConfFile)
def exists(self): return os.path.isfile(self.gngeorcPath),os.path.isfile(self.xgngeoconf_file)
for path in self.gngeorcPath,self.xgngeoconf_file:
for path in self.gngeorcPath,self.xgngeoConfFile:
def getParams(self,mamename=None): """Try to get the params of the global or a Rom-specific configuration file. If the file doesn't exist, there is no error but the param dict stays empty.""" if not mamename: #Parsing default main configuration files. dict = [{},{}] i=0 for path in self.gngeorcPath,self.xgngeoconf_file...
path = os.path.join(self.gngeoDir,"%s.cf" % mamename)
path = os.path.join(self.gngeoUserDir,"%s.cf" % mamename)
def getParams(self,mamename=None): """Try to get the params of the global or a Rom-specific configuration file. If the file doesn't exist, there is no error but the param dict stays empty.""" if not mamename: #Parsing default main configuration files. dict = [{},{}] i=0 for path in self.gngeorcPath,self.xgngeoconf_file...
if not os.path.isdir(self.xgngeoconf_dir): os.mkdir(self.xgngeoconf_dir) file = open(self.xgngeoconf_file,"w")
file = open(self.xgngeoConfFile,"w")
def writeGlobalConfig(self,gngeoDict,xgngeoDict,version): #Top comments. :p gngeoContent = "# Gngeo global configuration file.\n\
path = os.path.join(self.gngeoDir,"%s.cf" % mamename)
path = os.path.join(self.gngeoUserDir,"%s.cf" % mamename)
def writeRomConfig(self,dict,mamename,version): path = os.path.join(self.gngeoDir,"%s.cf" % mamename)
def get_bios_presence(self):
def get_bios_presence(self, path):
def get_bios_presence(self): return True
label = gtk.Label(_("The configuration file of Gngeo was not found!\nWe have to create one. Press OK to continue...") % self.configfile.get_path()[0])
label = gtk.Label(_("The configuration file of Gngeo was not found!\nWe have to create one. Press OK to continue..."))
def welcome(self): #Check for Gngeo's home directory if not os.path.isdir(gngeoPath): os.mkdir(gngeoPath)
registerer = _factory_registerer.register
registerer = getFactoryRegistry().register
def _installFactory(self, name, factory, methods, mimetypes, priority): """ calls the register factory utility, that actually links the factory. """ registerer = _factory_registerer.register
self._f()
if self._f is not None: logging.getLogger('SiteError').error( "Cleanup without request close") self._f()
def __del__(self): self._f()
s return None
return None
def getFactoriesFor(self, method, mimetype): try: return self._d[method][mimetype] except:
errService = queryService(object, ErrorReports)
errService = queryService(object, ErrorLogging)
def _logErrorWithErrorReportingService(self, object, request, exc_info): # Record the error with the ErrorReportingService beginErrorHandlingTransaction(request, 'error reporting service') try: errService = queryService(object, ErrorReports) if errService is not None: errService.raising(exc_info, request) # It is impor...
ErrorReports)
ErrorLogging)
def _logErrorWithErrorReportingService(self, object, request, exc_info): # Record the error with the ErrorReportingService beginErrorHandlingTransaction(request, 'error reporting service') try: errService = queryService(object, ErrorReports) if errService is not None: errService.raising(exc_info, request) # It is impor...
if (method == 'POST' and is_xml and env.get('SOAPAction', None)
if (method == 'POST' and is_xml and env.get('HTTP_SOAPACTION', None)
def __call__(self, input_stream, output_steam, env): """See `zope.app.publication.interfaces.IPublicationRequestFactory`""" method = env.get('REQUEST_METHOD', 'GET').upper()
raise Retry
raise Retry(exc_info)
def handleException(self, object, request, exc_info, retry_allowed=True): # This transaction had an exception that reached the publisher. # It must definitely be aborted. transaction.abort()
name = zapi.getDefaultViewName(exception, request)
name = zapi.queryDefaultViewName(exception, request)
def handleException(self, object, request, exc_info, retry_allowed=True): # This transaction had an exception that reached the publisher. # It must definitely be aborted. get_transaction().abort()
if hasattr(ob, '__implements__'):
if providedBy(ob):
def browserDefault(self, request): ob = self.context
self._http = HTTPPublication(db) self._brower = BrowserPublication(db) self._xmlrpc = XMLRPCPublication(db) self._soappub = SOAPPublication(db) self._soapreq = component.queryUtility(interfaces.ISOAPRequestFactory) self._httpreq = component.queryUtility( interfaces.IHTTPRequestFactory, default=HTTPRequest) self._xmlrpc...
self._db = db
def __init__(self, db): """See `zope.app.publication.interfaces.IPublicationRequestFactory`""" self._http = HTTPPublication(db) self._brower = BrowserPublication(db) self._xmlrpc = XMLRPCPublication(db) self._soappub = SOAPPublication(db) self._soapreq = component.queryUtility(interfaces.ISOAPRequestFactory) self._http...
if method in _browser_methods: content_type = env.get('CONTENT_TYPE', '') is_xml = content_type.startswith('text/xml') if (method == 'POST' and is_xml and env.get('HTTP_SOAPACTION', None) and self._soapreq is not None): request = self._soapreq(input_stream, output_steam, env) request.setPublication(self._soappub) elif...
request_class, publication_class = chooseClasses(method, env) request = request_class(input_stream, output_steam, env) request.setPublication(publication_class(self._db)) if IBrowserRequest.providedBy(request): setDefaultSkin(request)
def __call__(self, input_stream, output_steam, env): """See `zope.app.publication.interfaces.IPublicationRequestFactory`""" method = env.get('REQUEST_METHOD', 'GET').upper()
def handleException(self, object, request, exc_info, retry_allowed=True): get_transaction().abort() if retry_allowed and isinstance(exc_info[1], ConflictError): tryToLogWarning('ZopePublication', 'Competing writes/reads at %s' % request.get('PATH_INFO', '???'), exc_info=True) raise Retry
def _logErrorWithErrorReportingService(self, object, request, exc_info):
def handleException(self, object, request, exc_info, retry_allowed=True): # This transaction had an exception that reached the publisher. # It must definitely be aborted. get_transaction().abort()
raise Unauthorized("Name %s begins with an underscore" % `name`)
raise Unauthorized, name
def publishTraverse(self, request, name): ob = self.context if name.startswith('@@'): return getView(ob, name[6:], request)
factory_registerer = zapi.getUtility(IRequestPublicationRegistry)
factory_registerer = getUtility(IRequestPublicationRegistry)
def _installFactory(self, name, factory, methods, mimetypes, priority): """ calls the register factory utility, that actually links the factory. """ factory_registerer = zapi.getUtility(IRequestPublicationRegistry) registerer = factory_registerer.register
'Content-Type: text/plain;charset=iso-8859-1\r\n'
'Content-Type: text/plain;charset=utf-8\r\n'
def testHEADFuxup(self): pub = self.klass(None)
self.assertEqual(' '.join(value[9:]),
self.assertEqual(' '.join(value[-8:]),
def testRetryNotAllowed(self): from ZODB.POSException import ConflictError try: raise ConflictError except: pass self.publication.handleException( self.object, self.request, sys.exc_info(), retry_allowed=False) self.request.response.outputBody() value = self.out.getvalue().split() self.assertEqual(' '.join(value[:6]), ...
if len(sets.Set(priorities)) != len(l)
if len(sets.Set(priorities)) != len(l):
def register(self, method, mimetype, name, priority, factory): """ registers a factory for method+mimetype """
from zope.app.location import LocationPhysicallyLocatable
from zope.app.location.traversing import LocationPhysicallyLocatable
def testTransactionAnnotation(self): from zope.interface import directlyProvides from zope.app.location import LocationPhysicallyLocatable from zope.app.location.interfaces import ILocation from zope.app.traversing.interfaces import IPhysicallyLocatable from zope.app.traversing.interfaces import IContainmentRoot ztapi....
call (cli);
def call(cli): f = ex1.foo_t () f.x = 'this is a test string' f.xx = 1010 cli.call (ex1.FOO_FUNC, f, cb)
bar.y.append ([1,2,3,4]); cli.call (ex1.BAR_FUNC, bar, cb2)
bar.y = [1,2,3,4,5] cli.call (ex1.FOO_BAR, bar, cb2)
def call2(cli): bar = ex1.bar_t () bar.y.append ([1,2,3,4]); cli.call (ex1.BAR_FUNC, bar, cb2)
call2 (cli);
def call2(cli): bar = ex1.bar_t () bar.y.append ([1,2,3,4]); cli.call (ex1.BAR_FUNC, bar, cb2)
z.dump ()
z.warnx ()
def call3(cli): z = ex1.bb_t () z.aa = ex1.A2; z.b.foos = [ex1.foo_t () for i in range(0,2) ] z.b.foos[0].x = "foos[0] = 4" z.b.foos[0].xx = 4 z.b.foos[1].x = "foos[1] = 5" z.b.foos[1].xx = 5 z.b.bar.y = [ 100, 200, 300, 400 ]; z.dump () cli.call (ex1.FOO_BB, z, cb)
sock.connect (('127.0.0.1', 3000))
sock.connect (('127.0.0.1', port))
def call3(cli): z = ex1.bb_t () z.aa = ex1.A2; z.b.foos = [ex1.foo_t () for i in range(0,2) ] z.b.foos[0].x = "foos[0] = 4" z.b.foos[0].xx = 4 z.b.foos[1].x = "foos[1] = 5" z.b.foos[1].xx = 5 z.b.bar.y = [ 100, 200, 300, 400 ]; z.dump () cli.call (ex1.FOO_BB, z, cb)
z.baz = ex1.baz_t () z.baz.get().foos = [ex1.foo_t () for i in range (0,2) ] z.baz.get().foos[0].x = "foos[0] = 4" z.baz.get().foos[0].xx = 4 z.baz.get().foos[1].x = "foos[1] = 5" z.baz.get().foos[1].xx = 5 z.baz.get().bar.y = [ 100, 200, 300, 400 ];
z.baz.alloc () z.baz.p = ex1.baz_t () z.baz.p.foos = [ex1.foo_t () for i in range (0,2) ] z.baz.p.foos[0].x = "foos[0] = 4" z.baz.p.foos[0].xx = 4 z.baz.p.foos[1].x = "foos[1] = 5" z.baz.p.foos[1].xx = 5 z.baz.p.bar.y = [ 100, 200, 300, 400 ];
def call4(cli): z = ex1.fooz_t () z.baz = ex1.baz_t () z.baz.get().foos = [ex1.foo_t () for i in range (0,2) ] z.baz.get().foos[0].x = "foos[0] = 4" z.baz.get().foos[0].xx = 4 z.baz.get().foos[1].x = "foos[1] = 5" z.baz.get().foos[1].xx = 5 z.baz.get().bar.y = [ 100, 200, 300, 400 ]; z.warnx () cli.call (ex1.FOO_FOOZ, ...
image_path, capitalize, cellspacing):
image_path, cellspacing, animate, skip_caps): if animate: count = 0 drw = [] for i in xrange (len (image.layers) -1, -1, -1): if image.layers[i].visible: drw.append(image.layers[i]) count += 1 if count == 3: break
def pyslice(image, drawable, save_path, html_filename, image_basename, image_extension, separate, image_path, capitalize, cellspacing): vert, horz = get_guides(image) if len(vert) == 0 and len(horz) == 0: return gimp.progress_init("Py-Slice") progress_increment = 1 / ((len(horz) + 1) * (len(vert) + 1)) progress = 0....
cellspacing=cellspacing, capitalize=capitalize)
cellspacing=cellspacing, animate=animate)
def check_path(path): path = os.path.abspath(path)
src = slice(image, image_path, image_basename, image_extension, left, right, top, bottom, i, j) if image_relative_path: if image_relative_path.endswith('/'): src_path = image_relative_path + src else: src_path = image_relative_path + '/' + src
if (skip_caps and ( (len(horz) >= 2 and (i == 0 or i == len(horz) )) or (len(vert) >= 2 and (j == 0 or j == len(vert) )) ) ): skip_stub = True
def check_path(path): path = os.path.abspath(path)
src_path = src tw.cell(src_path, right - left, bottom - top)
skip_stub = False if (not animate or skip_stub): src = (image_relative_path + slice (image, None, image_path, image_basename, image_extension, left, right, top, bottom, i, j, "")) else: src = [] for layer, postfix in zip (drw, ("", "hover", "clicked")): src.append (image_relative_path + slice(image, layer, image_path,...
def check_path(path): path = os.path.abspath(path)
def slice(image, image_path, image_basename, image_extension, left, right, top, bottom, i, j): src = "%s-%d-%d.%s" % (image_basename, i, j, image_extension)
def slice(image, drawable, image_path, image_basename, image_extension, left, right, top, bottom, i, j, postfix): if postfix: postfix = "_" + postfix src = "%s_%d_%d%s.%s" % (image_basename, i, j, postfix, image_extension)
def slice(image, image_path, image_basename, image_extension, left, right, top, bottom, i, j): src = "%s-%d-%d.%s" % (image_basename, i, j, image_extension) filename = os.path.join(image_path, src) temp_image = image.duplicate() temp_image.disable_undo() temp_image.crop(right - left, bottom - top, left, top) pdb.gim...
temp_image = image.duplicate()
if not drawable: temp_image = image.duplicate() temp_drawable = temp_image.active_layer else: if image.base_type == INDEXED: original_active = image.active_layer image.active_layer = drawable temp_image = image.duplicate() temp_drawable = temp_image.active_layer image.active_layer = original_active temp_image.disable...
def slice(image, image_path, image_basename, image_extension, left, right, top, bottom, i, j): src = "%s-%d-%d.%s" % (image_basename, i, j, image_extension) filename = os.path.join(image_path, src) temp_image = image.duplicate() temp_image.disable_undo() temp_image.crop(right - left, bottom - top, left, top) pdb.gim...
pdb.gimp_file_save(temp_image, temp_image.active_layer, filename, filename)
if image_extension == "gif" and image.base_type == RGB: pdb.gimp_image_convert_indexed (temp_image,NO_DITHER, MAKE_PALETTE, 255, True, False, False) if image_extension == "jpg" and image.base_type == INDEXED: pdb.gimp_image_convert_rgb (temp_image) pdb.gimp_file_save(temp_image, temp_drawable, filename, filename)
def slice(image, image_path, image_basename, image_extension, left, right, top, bottom, i, j): src = "%s-%d-%d.%s" % (image_basename, i, j, image_extension) filename = os.path.join(image_path, src) temp_image = image.duplicate() temp_image.disable_undo() temp_image.crop(right - left, bottom - top, left, top) pdb.gim...
capitalize=False):
animate=False): self.filename = filename
def __init__(self, filename, cellpadding=0, cellspacing=0, border=0, capitalize=False): self.table_attrs = {}
self.capitalize = capitalize self.html = file(filename, 'w')
self.image_prefix = os.path.basename (filename) self.image_prefix = self.image_prefix.split(".")[0] self.image_prefix = self.image_prefix.replace ("-", "_") self.image_prefix = self.image_prefix.replace (" ", "_") if animate: self.animate = True self.images = [] else: self.animate = False if os.path.exists (filename...
def __init__(self, filename, cellpadding=0, cellspacing=0, border=0, capitalize=False): self.table_attrs = {}
if self.capitalize: s = s.upper() s = s.replace('%S', '%s') else: s = s.lower()
def write(self, s, vals=None): if self.capitalize: s = s.upper() s = s.replace('%S', '%s') else: s = s.lower()
out = '<table'
out = '''<!--HTML SNIPPET GENERATED BY THE GIMP WARNING!! This is NOT a fully valid HTML document, it is rather a piece of HTML generated by the GIMP's py-slice plugin that should be embedded in an HTML or XHTML document to be valid. Replace the href targets in the anchor (<a >) for your URLS to have it working as a ...
def open(self): out = '<table'
out += ' %s=%s' % (attr, value)
out += ' %s="%s"' % (attr, value)
def open(self): out = '<table'
self.write('</table>') self.html.close()
self.write('</table>\n') prefix = self.image_prefix if self.animate: out = """ <script language="javascript" type="text/javascript"> /* Made with The GIMP */ /* Preload images: */ images_%s = new Array(); \n""" % prefix for image in self.images: for type_ in ("plain", "hover", "clicked"): if image.has_key(type_): i...
def close(self): self.write('</table>') self.html.close()
self.write('\t<tr>')
self.write(' <tr>')
def row_start(self): self.write('\t<tr>')
self.write('\t</tr>') def cell(self, src, width, height): out = ('\t\t<td><img alt=" " src="%%s" width="%d" height="%d"></td>' % (width, height)) self.write(out, src)
self.write('</tr>\n') def cell(self, src, width, height, row=0, col=0, skip_stub = False): if isinstance (src, list): prefix = "images_%s" % self.image_prefix self.images.append ({"index" : (row, col), "plain" : src[0]}) out = (' <td><a href="%s"><img alt="" src="%s" ' + 'style="width: %dpx; height: %dpx; border-w...
def row_end(self): self.write('\t</tr>')
"Guillotine implemented ala python, with html output (based on perlotine by Seth Burgess)", "Add guides to an image. Then run this. It will cut along the guides, and give you the html to reassemble the resulting images.",
, """Add guides to an image. Then run this. It will cut along the guides, and give you the html to reassemble the resulting images. If you choose to generate javascript for onmouseover and clicked events, it will use the lower three visible layers on the image for normal, onmouseover and clicked states, in that order....
def cell(self, src, width, height): out = ('\t\t<td><img alt=" " src="%%s" width="%d" height="%d"></td>' % (width, height)) self.write(out, src)