rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
return Branch.get_checkoutdir(self)
if self.checkoutdir: return os.path.join(self.checkoutroot, self.checkoutdir) else: return os.path.join(self.checkoutroot, self.get_module_basename())
def srcdir(self): return Branch.get_checkoutdir(self)
if raw_input() == 'n': self.player.set_state(gst.STATE_NULL) self.playmode = False break else: time.sleep(1) loop.quit()
rlist, _, _ = select([sys.stdin], [], [], 1) if rlist: s = sys.stdin.readline() if s[0] == 'n': self.player.set_state(gst.STATE_NULL) self.playmode = False break
def start(self): rets = json.loads(urllib2.urlopen(self.ch).read()) for r in rets['song']: song_uri = r['url'] self.playmode = True print u'正在播放: '+r['title']+u' 歌手: '+r['artist'] self.player.set_property("uri", song_uri) self.player.set_state(gst.STATE_PLAYING) while self.playmode: if raw_input() == 'n': self.play...
def play(self):
def start(self):
def play(self): rets = json.loads(urllib2.urlopen(self.ch).read()) for r in rets['song']: song_uri = r['url'] self.playmode = True print u'正在播放: '+r['title']+u' 歌手: '+r['artist'] self.player.set_property("uri", song_uri) self.player.set_state(gst.STATE_PLAYING) while self.playmode: if raw_input() == 'n': self.play...
def start(self): self.play()
def play(self): rets = json.loads(urllib2.urlopen(self.ch).read()) for r in rets['song']: song_uri = r['url'] self.playmode = True print u'正在播放: '+r['title']+u' 歌手: '+r['artist'] self.player.set_property("uri", song_uri) self.player.set_state(gst.STATE_PLAYING) while self.playmode: if raw_input() == 'n': self.play...
def fm(doubanfm):
channel_info = u''' 0 私人兆赫 1 华语兆赫 2 欧美兆赫 3 70兆赫 4 80兆赫 5 90兆赫 6 粤语兆赫 7 摇滚兆赫 8 轻音乐兆赫 9 民谣兆赫 ''' print channel_info c = raw_input('请输入您想听的频道数字:') doubanfm = DoubanFM_CLI(c) use_info = u''' 跳过输入n,加心输入f,删歌输入d ''' print use_info while 1:
def start(self): self.get_songlist() for r in self.songlist: song_uri = r['url'] self.playmode = True print u'正在播放: '+r['title']+u' 歌手: '+r['artist'] self.player.set_property("uri", song_uri) self.player.set_state(gst.STATE_PLAYING) while self.playmode: c = self.control(r) if c == 'next' or c == 'del': self.player....
thread.exit()
def fm(doubanfm): thread.start_new_thread(doubanfm.start, ()) gobject.threads_init() loop = glib.MainLoop() loop.run() thread.exit()
def vm_purge(xencache, xenvm)
def vm_purge(xencache, xenvm):
def vm_purge(xencache, xenvm) """ remove VM and all it assets """ log.debug("in vm_purge()") # protect certain VMs if 'prod' in myvm.fqdn: # stubbing this off for now, but if true, should not execute following code pass for existing_vm in myvm.is_existing_vm(): vbd, vif, existing_VDIs = [], [], [] existing_VBDs = xen...
myvm.start(mv.vm_uuid)
myvm.start(myvm.vm_uuid)
def add_to_cobbler(cobbler_server, token, xenvm): """ add the VM to cobbler """ log.debug("in add_to_cobbler()") # add new system vm_id = cobbler.new_system(token) cobbler.modify_system(vm_id, 'name', xenvm.fqdn, token) cobbler.modify_system(vm_id, 'hostname', xenvm.fqdn, token) cobbler.modify_system(vm_id, 'profile',...
self.vm_uuid = xenapi.VM.clone(self.xensession, xenapi.VM.get_by_name_label(self.xensession, self.vm_template)['Value'][0], self.name)
self.vm_uuid = xenapi.VM.clone(self.xensession, xenapi.VM.get_by_name_label(self.xensession, self.vm_template)['Value'][0], self.name)['Value']
def create(self): """ this section will create the disk image for the VM, set its properties and prepare it to boot """
'SR' : str(xenapi.SR.get_by_name_label(self.xensession, self.aggr)[0]) ,
'SR' : str(xenapi.SR.get_by_name_label(self.xensession, self.aggr)['Value'][0]) ,
def create(self): """ this section will create the disk image for the VM, set its properties and prepare it to boot """
class cobbler():
class cobbler:
def __init__(self, xensession): self.xensession = xensession self.all_sr_records = self._query_sr_records() self.all_vm_records = self._query_vm_records() self.vm_templates = self._query_xen_templates() self.sr_aggr = self._query_shared_storage()
try: log.debug("first attempt to boot VM %s" % myvm.vm_uuid) xenapi.VM.start(xensession, myvm.vm_uuid) except:
log.debug("first attempt to boot VM %s" % myvm.vm_uuid) autostart_return = xenapi.VM.start(xensession, myvm.vm_uuid, False, True) if autostart_return['Status'] == 'Failure': print autostart_return['Value']
def get_options(): """ command-line options """ log.debug("in get_options()") usage = "usage: %prog -f <FILE> [options]" OptionParser = optparse.OptionParser parser = OptionParser(usage) required = optparse.OptionGroup(parser, "Required") optional = optparse.OptionGroup(parser, "Optional") required.add_option("-f", ...
try: log.debug("second attempt to boot VM %s" % myvm.vm_uuid) xenapi.VM.start(xensession, myvm.vm_uuid) except: log.debug("second attempt failed. trying 1 more times...") try: log.debug("third attempt to boot VM %s" % myvm.vm_uuid) xenapi.VM.start(xensession, myvm.vm_uuid) except:
log.debug("second attempt to boot VM %s" % myvm.vm_uuid) autostart_return = xenapi.VM.start(xensession, myvm.vm_uuid, False, True) if autostart_return == 'Failure': log.debug("second attempt failed. trying 1 more time...") log.debug("third attempt to boot VM %s" % myvm.vm_uuid) autostart_return = xenapi.VM.start(xenses...
def get_options(): """ command-line options """ log.debug("in get_options()") usage = "usage: %prog -f <FILE> [options]" OptionParser = optparse.OptionParser parser = OptionParser(usage) required = optparse.OptionGroup(parser, "Required") optional = optparse.OptionGroup(parser, "Optional") required.add_option("-f", ...
xenapi.VM.add_to_other_config(self.xensession, self.vm_uuid, 'FQDN', myvm.fqdn)
def get_options(): """ command-line options """ log.debug("in get_options()") usage = "usage: %prog -f <FILE> [options]" OptionParser = optparse.OptionParser parser = OptionParser(usage) required = optparse.OptionGroup(parser, "Required") optional = optparse.OptionGroup(parser, "Optional") required.add_option("-f", ...
print autostart_return['Value']
def get_options(): """ command-line options """ log.debug("in get_options()") usage = "usage: %prog -f <FILE> [options]" OptionParser = optparse.OptionParser parser = OptionParser(usage) required = optparse.OptionGroup(parser, "Required") optional = optparse.OptionGroup(parser, "Optional") required.add_option("-f", ...
xenapi.VM.start(vm_uuid, False, True)
xenapi.VM.start(vm_uuid, True, True)
def start(self): log.info('Booting %s' % self.name)
print now()
def run(self, finish):
timeInHours = math.ceil(timeInSecs/60)
timeInHours = math.ceil(timeInSecs/3600.0)
def getExecutionCost(self): timeInSecs = self.getExecutionTime() timeInHours = math.ceil(timeInSecs/60) return timeInHours * self.scenario.wn_cost
read('src', 'hurry', 'zoperesource', 'README.txt')
read('src', 'zope', 'fanstatic', 'README.txt')
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
name='hurry.zoperesource',
name='zope.fanstatic',
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
description="hurry.resource integration for Zope.",
description="Fanstatic integration for Zope.",
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
author='Martijn Faassen', author_email='faassen@startifact.com', url='http://pypi.python.org/pypi/hurry.zoperesource', license='ZPL',
author='Zope Foundation and Contributors', author_email='zope-dev@zope.org', url='http://pypi.python.org/pypi/zope.fanstatic', license='ZPL 2.1',
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
namespace_packages=['hurry'],
namespace_packages=['zope'],
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
global g_output_verbosity_level; if g_output_verbosity_level == 0 or message == "": PrintLine(message); else: PrintWrappedLine(message);
global g_output_verbosity_level, g_newline; Print(message + g_newline);
def PrintLine(message = ""): global g_output_verbosity_level; if g_output_verbosity_level == 0 or message == "": PrintLine(message); else: PrintWrappedLine(message);
def PrintLine(line): global g_newline; Print(line + g_newline);
def PrintLine(line): global g_newline; Print(line + g_newline);
encoded_shellcode = encoder_settings["function"](base_address, TEST_X86_SHELLCODE, *encoder_function_args)
encoded_shellcode = encoder_settings["function"](base_address, shellcode, *encoder_function_args)
def RunEncoderTest(encoder_settings, base_address, test_args, int3): for i in range(len(test_args)): test_args[i] = test_args[i].replace("%shellcode%", "con") if (encoder_settings["architecture"] == "x86"): shellcode_file = TEST_X86_SHELLCODE_FILE shellcode = TEST_X86_SHELLCODE test_command = TEST_X86 elif (encoder_set...
raise e
raise
def RunEncoderTest(encoder_settings, base_address, test_args, int3): for i in range(len(test_args)): test_args[i] = test_args[i].replace("%shellcode%", "con") if (encoder_settings["architecture"] == "x86"): shellcode_file = TEST_X86_SHELLCODE_FILE shellcode = TEST_X86_SHELLCODE test_command = TEST_X86 elif (encoder_set...
formid=None, **kw):
formid='deform', **kw):
def __init__(self, schema, action='.', method='POST', buttons=(), formid=None, **kw): field.Field.__init__(self, schema, **kw) _buttons = [] for button in buttons: if isinstance(button, basestring): button = Button(button) _buttons.append(button) self.action = action self.method = method self.buttons = _buttons self.fo...
widget = self.item_widget.clone()
widget = item_widget.clone()
def deserialize(self, pstruct): result = []
self.assertEqual(browser.get_text(error_node), 'Incomplete')
self.assertEqual(browser.get_text(error_node), 'Required')
def test_submit_empty(self): browser.open(self.url) browser.wait_for_page_to_load("30000") browser.click("submit") browser.wait_for_page_to_load("30000") self.failUnless(browser.get_text('css=.errorMsgLbl')) error_node = 'css=#error-deformField1' self.assertEqual(browser.get_text(error_node), 'Incomplete') self.assertE...
'Incomplete')
'Required')
def test_submit_empty(self): browser.open(self.url) browser.wait_for_page_to_load("30000") browser.click('submit') browser.wait_for_page_to_load("30000") self.failUnless(browser.is_element_present('css=.errorMsgLbl')) self.assertEqual(browser.get_text('css=#error-deformField1'), 'Required') self.assertEqual(browser.get...
'Incomplete')
'Required')
def test_submit_invalid_number(self): browser.open(self.url) browser.wait_for_page_to_load("30000") browser.type('deformField1', 'notanumber') browser.click('submit') browser.wait_for_page_to_load("30000") self.failUnless(browser.is_element_present('css=.errorMsgLbl')) self.assertEqual(browser.get_text('css=#error-defo...
browser.click( '//html/body/div/div/div/form/fieldset/ul/li/div/li/div/ul/li/input') browser.click( '//html/body/div/div/div/form/fieldset/ul/li/div/li[2]/div/ul/li[2]/input[1]')
browser.click('dom=document.forms[0].elements[5]') browser.click('dom=document.forms[0].elements[11]')
def test_submit_two_filled(self): browser.open(self.url) browser.wait_for_page_to_load("30000") browser.click('deformField1-seqAdd') browser.click('deformField1-seqAdd') browser.click( '//html/body/div/div/div/form/fieldset/ul/li/div/li/div/ul/li/input') browser.click( '//html/body/div/div/div/form/fieldset/ul/li/div/l...
'Incomplete')
'Required')
def test_submit_empty(self): browser.open(self.url) browser.wait_for_page_to_load("30000") browser.click('submit') browser.wait_for_condition( 'selenium.browserbot.getCurrentWindow().jQuery.active == 0', "30000") self.failUnless(browser.is_element_present('css=.errorMsgLbl')) self.assertEqual(browser.get_text('css=#err...
'Incomplete')
'Required')
def test_submit_invalid(self): browser.open(self.url) browser.wait_for_page_to_load("30000") browser.type('deformField1', 'notanumber') browser.click('submit') browser.wait_for_condition( 'selenium.browserbot.getCurrentWindow().jQuery.active == 0', "30000") self.failUnless(browser.is_element_present('css=.errorMsgLbl')...
def _makeOne(self, schema, renderer=None):
def _makeOne(self, **kw):
def _makeOne(self, schema, renderer=None): from deform.widget import RadioChoiceWidget return RadioChoiceWidget(schema, renderer=renderer)
return RadioChoiceWidget(schema, renderer=renderer)
return RadioChoiceWidget(**kw)
def _makeOne(self, schema, renderer=None): from deform.widget import RadioChoiceWidget return RadioChoiceWidget(schema, renderer=renderer)
widget = self._makeOne(schema, renderer=renderer) widget.default = 'default' widget.serialize(None) self.assertEqual(renderer.template, widget.template) self.assertEqual(renderer.kw['widget'], widget)
field = DummyField(schema, renderer) field.default = 'default' widget = self._makeOne() widget.serialize(field, None) self.assertEqual(renderer.template, widget.template) self.assertEqual(renderer.kw['field'], field)
def test_serialize_None(self): renderer = DummyRenderer() schema = DummySchema() widget = self._makeOne(schema, renderer=renderer) widget.default = 'default' widget.serialize(None) self.assertEqual(renderer.template, widget.template) self.assertEqual(renderer.kw['widget'], widget) self.assertEqual(renderer.kw['cstruct'...
widget = self._makeOne(schema, renderer=renderer)
field = DummyField(schema, renderer) widget = self._makeOne()
def test_serialize_not_None(self): renderer = DummyRenderer() schema = DummySchema() widget = self._makeOne(schema, renderer=renderer) cstruct = 'abc' widget.serialize(cstruct) self.assertEqual(renderer.template, widget.template) self.assertEqual(renderer.kw['widget'], widget) self.assertEqual(renderer.kw['cstruct'], c...
widget.serialize(cstruct) self.assertEqual(renderer.template, widget.template) self.assertEqual(renderer.kw['widget'], widget)
widget.serialize(field, cstruct) self.assertEqual(renderer.template, widget.template) self.assertEqual(renderer.kw['field'], field)
def test_serialize_not_None(self): renderer = DummyRenderer() schema = DummySchema() widget = self._makeOne(schema, renderer=renderer) cstruct = 'abc' widget.serialize(cstruct) self.assertEqual(renderer.template, widget.template) self.assertEqual(renderer.kw['widget'], widget) self.assertEqual(renderer.kw['cstruct'], c...
schema = DummySchema() widget = self._makeOne(schema) result = widget.deserialize(None)
widget = self._makeOne() field = DummyField() result = widget.deserialize(field, None)
def test_deserialize_None(self): schema = DummySchema() widget = self._makeOne(schema) result = widget.deserialize(None) self.assertEqual(result, '')
schema = DummySchema() widget = self._makeOne(schema) result = widget.deserialize('true')
widget = self._makeOne() field = DummyField() result = widget.deserialize(field, 'true')
def test_deserialize_other(self): schema = DummySchema() widget = self._makeOne(schema) result = widget.deserialize('true') self.assertEqual(result, 'true')
def _makeOne(self, schema, renderer=None):
def _makeOne(self, **kw):
def _makeOne(self, schema, renderer=None): from deform.widget import CheckedPasswordWidget return CheckedPasswordWidget(schema, renderer=renderer)
return CheckedPasswordWidget(schema, renderer=renderer)
return CheckedPasswordWidget(**kw)
def _makeOne(self, schema, renderer=None): from deform.widget import CheckedPasswordWidget return CheckedPasswordWidget(schema, renderer=renderer)
widget = self._makeOne(schema, renderer=renderer) widget.serialize(None) self.assertEqual(renderer.template, widget.template) self.assertEqual(renderer.kw['widget'], widget)
field = DummyField(schema, renderer) field.default = None widget = self._makeOne() widget.serialize(field, None) self.assertEqual(renderer.template, widget.template) self.assertEqual(renderer.kw['field'], field)
def test_serialize_None_no_default(self): renderer = DummyRenderer() schema = DummySchema() widget = self._makeOne(schema, renderer=renderer) widget.serialize(None) self.assertEqual(renderer.template, widget.template) self.assertEqual(renderer.kw['widget'], widget) self.assertEqual(renderer.kw['cstruct'], '')
schema = DummySchema() widget = self._makeOne(schema) result = widget.deserialize({'password':'password', 'confirm':'not'})
widget = self._makeOne() field = DummyField() result = widget.deserialize(field, {'password':'password', 'confirm':'not'})
def test_deserialize_nonmatching(self): schema = DummySchema() widget = self._makeOne(schema) result = widget.deserialize({'password':'password', 'confirm':'not'}) self.assertEqual(result, 'password') self.assertEqual(widget.error.msg, 'Password did not match confirmation')
self.assertEqual(widget.error.msg,
self.assertEqual(field.error.msg,
def test_deserialize_nonmatching(self): schema = DummySchema() widget = self._makeOne(schema) result = widget.deserialize({'password':'password', 'confirm':'not'}) self.assertEqual(result, 'password') self.assertEqual(widget.error.msg, 'Password did not match confirmation')
schema = DummySchema() widget = self._makeOne(schema) result = widget.deserialize({'password':'password', 'confirm':'password'})
widget = self._makeOne() field = DummyField() result = widget.deserialize(field, {'password':'password', 'confirm':'password'})
def test_deserialize_matching(self): schema = DummySchema() widget = self._makeOne(schema) result = widget.deserialize({'password':'password', 'confirm':'password'}) self.assertEqual(result, 'password') self.assertEqual(widget.error, None)
self.assertEqual(widget.error, None)
self.assertEqual(field.error, None)
def test_deserialize_matching(self): schema = DummySchema() widget = self._makeOne(schema) result = widget.deserialize({'password':'password', 'confirm':'password'}) self.assertEqual(result, 'password') self.assertEqual(widget.error, None)
class TestForm(unittest.TestCase): def _makeOne(self, schema, **kw): from deform.widget import Form return Form(schema, **kw) def test_ctor_string_buttons(self): schema = DummySchema() form = self._makeOne(schema, buttons=('a', 'b')) self.assertEqual(form.buttons[0].name, 'a') self.assertEqual(form.buttons[1].name, 'b...
class TestFormWidget(unittest.TestCase): def _makeOne(self, **kw): from deform.widget import FormWidget return FormWidget(**kw) def test_template(self): form = self._makeOne() self.assertEqual(form.template, 'form')
def test_handle_error(self): schema = DummySchema() widget = self._makeOne(schema) inner = DummyWidget() inner_invalid = DummyInvalid() inner_invalid.pos = 0 error = DummyInvalid(inner_invalid) widget.sequence_widgets = [inner] widget.handle_error(error) self.assertEqual(widget.error, error) self.assertEqual(inner.erro...
pyfits.PrimaryHDU(data.astype(numpy.int16), header).writeto(outfile, output_verify='silentfix', clobber=True)
hdu = pyfits.PrimaryHDU(data, header) hdu.scale('int16', '', bscale = 1.0, bzero = 32768.0) hdu.writeto(outfile, output_verify='silentfix', clobber=True)
def saveScience(data, header, basedir, fieldid, visitid, filterid, snapid, ccdid, ampid): # CFHTLS/%(field)/raw/v%(visitid)-f%(filterid)/s%(snapid)/c%(ccdid)-a%(ampid).fits # I think CFHTLS is redundant here, we can move this dir structure en masse into CFHTLS # outdir = '%s/CFHTLS/%s/raw/v%s-f%s/s%s' % (basedir, fie...
pyfits.PrimaryHDU(data.astype(numpy.int16), header).writeto(outfile, output_verify='silentfix', clobber=True)
hdu = pyfits.PrimaryHDU(data, header) hdu.writeto(outfile, output_verify='silentfix', clobber=True)
def saveCalibration(data, header, basedir, dtype, dateid, ccdid, ampid, filter = None): # CFHTLS/%(dtype)/v%(dateid)/c%(ccdid)-a%(ampid).fits # -- or -- # CFHTLS/%(dtype)/v%(dateid)-f%(filterid)/c%(ccdid)-a%(ampid).fits if filter == None: #outdir = '%s/CFHTLS/%s/v%s' % (basedir, dtype, dateid) outdir = '%s/%s/v%s' % (...
if 0:
if 1:
def saveCalibration(data, header, basedir, dtype, dateid, ccdid, ampid, filter = None): # CFHTLS/%(dtype)/v%(dateid)/c%(ccdid)-a%(ampid).fits # -- or -- # CFHTLS/%(dtype)/v%(dateid)-f%(filterid)/c%(ccdid)-a%(ampid).fits if filter == None: #outdir = '%s/CFHTLS/%s/v%s' % (basedir, dtype, dateid) outdir = '%s/%s/v%s' % (...
NotOverriddenWarning: `varietes.B.f()` is not overriden
NotOverriddenWarning: `lib.varietes.B.f()` is not overriden
... def f(self, x, y): return x * y
varietes.idict(eggs='spam', ham='eggs')
lib.varietes.idict(eggs='spam', ham='eggs')
def is_html_color(s): ''' >>> is_html_color('#000000') True >>> is_html_color('#ffffff') True >>> is_html_color('#FFFFFF') True >>> is_html_color('#c0c0f0') True >>> is_html_color('') False >>> is_html_color('#bcdefg') False >>> is_html_color('#ffffff ') False >>> is_html_color(' #ffffff') False ''' return bool(_is_htm...
def is_dirty(key = None):
def is_dirty(self, key=None):
def is_dirty(key = None): if key is None: return self._dirty new_value = self[key] try: return self._old_data[key] == new_value except KeyError: return True
if self._line_width != MAPAREA_LINE_MIN_WIDTH:
if self._line_width != djvu.const.MAPAREA_LINE_MIN_WIDTH:
def _get_sexpr_extra(self): result = [] if self._line_arrow: result += (djvu.const.MAPAREA_ARROW,), if self._line_width != MAPAREA_LINE_MIN_WIDTH: result += (djvu.const.MAPAREA_LINE_WIDTH, self._line_width), if self._line_color != djvu.const.MAPAREA_LINE_COLOR_DEFAULT: result += (djvu.const.MAPAREA_LINE_COLOR, self._li...
title = u'%s — %s' % (APPLICATION_NAME, os.path.basename(self.path))
base_path = os.path.basename(self.path) if isinstance(base_path, str): base_path = base_path.decode(system_encoding, 'replace') title = u'%s — %s' % (APPLICATION_NAME, base_path)
def update_title(self): if self.path is None: title = APPLICATION_NAME else: title = u'%s — %s' % (APPLICATION_NAME, os.path.basename(self.path)) self.SetTitle(title)
dialog = gui.dialogs.ProgressDialog(
dialog = dialogs.ProgressDialog(
def job(): try: sed.commit() except Exception, exception: pass else: exception = None queue.put(exception)
dialog = gui.dialogs.NumberEntryDialog(
dialog = dialogs.NumberEntryDialog(
def on_goto_page(self, event): dialog = gui.dialogs.NumberEntryDialog( parent = self, message = _('Go to page') + ':', prompt = '', caption = _('Go to page'), value = self.page_no + 1, min = 1, max = len(self.document.pages) ) try: rc = dialog.ShowModal() if rc == wx.ID_OK: self.page_no = dialog.GetValue() - 1 finally:...
node.line_arrow = self._edit_line_arrow.GetValue()
node.line_arrow = self._edit_arrow.GetValue()
def get_node(self): shape = SHAPES[self._edit_shape.GetSelection()] model_class = shape.model_class node = model_class.from_maparea(self._node, owner=None) node.uri = self._edit_uri.GetValue() node.target = self._edit_target.GetValue() or None node.comment = self._edit_comment.GetValue() if self._edit_border_none.GetVa...
return object.__new__(cls, sexpr, owner)
return object.__new__(cls)
def __new__(cls, sexpr, owner): if len(sexpr) == 6 and isinstance(sexpr[5], djvu.sexpr.StringExpression): cls = LeafNode else: cls = InnerNode return object.__new__(cls, sexpr, owner)
NotOverriddenWarning: `lib.varietes.B.f()` is not overriden
NotOverriddenWarning: `lib.varietes.B.f()` is not overridden
... def f(self, x, y): return x * y
'`%s.%s.%s()` is not overriden' % (cls.__module__, cls.__name__, f.__name__),
'`%s.%s.%s()` is not overridden' % (cls.__module__, cls.__name__, f.__name__),
def new_f(self, *args, **kwargs): cls = type(self) warnings.warn( '`%s.%s.%s()` is not overriden' % (cls.__module__, cls.__name__, f.__name__), category = NotOverriddenWarning, stacklevel = 2 ) return f(self, *args, **kwargs)
setSpec = e('string(oai:setSpec/text())') setName = e('string(oai:setName/text())')
setSpec = unicode(e('string(oai:setSpec/text())')) setName = unicode(e('string(oai:setName/text())'))
def buildSets(self, namespaces, tree): evaluator = etree.XPathEvaluator(tree, namespaces=namespaces) # first find resumption token if available token = evaluator.evaluate( 'string(/oai:OAI-PMH/oai:ListSets/oai:resumptionToken/text())') if token.strip() == '': token = None set_nodes = evaluator.evaluate( '/oai:OAI-PMH/o...
return urllib2.HTTPDefaultErrorHandler(self, req, fp, code, msg, hdrs)
return urllib2.HTTPDefaultErrorHandler.http_error_default(self, req, fp, code, msg, hdrs)
def http_error_default(self, req, fp, code, msg, hdrs): if code >= 400: return urllib2.HTTPDefaultErrorHandler(self, req, fp, code, msg, hdrs) else: result = urllib2.HTTPError( req.get_full_url(), code, msg, hdrs, fp) result.status = code return result
if 'USERPROFILE' in os.environ:
if 'APPDATA' in os.environ: homepath = os.environ["APPDATA"] elif 'USERPROFILE' in os.environ:
def __init__(self, url, proxy=None): if not url.endswith('/'): url = url + '/' self.url = url if 'USERPROFILE' in os.environ: homepath = os.path.join(os.environ["USERPROFILE"], "Local Settings", "Application Data") elif 'HOME' in os.environ: homepath = os.environ["HOME"] else: homepath = '' self.cookie_file = os....
remotepath = ui.expandpath('default-push', 'default')
remotepath = ui.expandpath(ui.expandpath('reviewboard', 'default-push'), 'default')
def remoteparent(ui, repo, rev, upstream=None): if upstream: remotepath = ui.expandpath(upstream) else: remotepath = ui.expandpath('default-push', 'default') remoterepo = hg.repository(ui, remotepath) try: # from Mercurial 1.6 from mercurial import discovery out = discovery.findoutgoing(repo, remoterepo) except ImportE...
self.rb_user = raw_input('Username: ')
self.rb_user = mercurial.ui.ui().prompt('Username: ')
def find_user_password(self, realm, uri): if uri.startswith(self.rb_url): if self.rb_user is None or self.rb_pass is None: print "==> HTTP Authentication Required" print 'Enter username and password for "%s" at %s' % \ (realm, urlparse(uri)[1]) self.rb_user = raw_input('Username: ') self.rb_pass = getpass.getpass('Pass...
urllib2.HTTPBasicAuthHandler(password_mgr)
urllib2.HTTPBasicAuthHandler(password_mgr), urllib2.HTTPDigestAuthHandler(password_mgr)
def __init__(self, url, proxy=None): if not url.endswith('/'): url = url + '/' self.url = url if 'APPDATA' in os.environ: homepath = os.environ["APPDATA"] elif 'USERPROFILE' in os.environ: homepath = os.path.join(os.environ["USERPROFILE"], "Local Settings", "Application Data") elif 'HOME' in os.environ: homepath ...
username = raw_input('Username: ')
username = mercurial.ui.ui().prompt('Username: ')
def login(self, username=None, password=None): if not username and not password and self.has_valid_cookie(): return
raise util.Abort(_(msg))
raise util.Abort(_(str(msg)))
def getdiff(ui, repo, r, parent): '''return diff for the specified revision''' output = "" for chunk in patch.diff(repo, parent.node(), r.node()): output += chunk return output
self.delegate.socket_did_disconnect(err)
self.delegate.socket_did_disconnect(self, err)
def close(self, err=None): if self.socket != None: self.socket.close() self.socket = None if (self.connected or self.accepting) and hasattr(self.delegate, 'socket_did_disconnect'): self.delegate.socket_did_disconnect(err) self.connected = False self.accepting = False
self.assertRaises(Exception, test_view('stock_forecast'))
test_view('stock_forecast')
def test0005views(self): ''' Test views. ''' self.assertRaises(Exception, test_view('stock_forecast'))
utils.system ('make') utils.system ('make prefix=%s install' % topdir)
utils.system('patch -p1 < ../00_arches.patch') utils.system('make') utils.system('make prefix=%s install' % topdir)
def setup(tarball, topdir): srcdir = os.path.join(topdir, 'src') utils.extract_tarball_to_dir(tarball, srcdir) os.chdir(srcdir) utils.system ('make') utils.system ('make prefix=%s install' % topdir) os.chdir(topdir)
def initialize(self, interval = 1):
def initialize(self, interval=1): """ Set sar interval and verify what flags the installed sar supports. @param interval: Interval used by sar to produce system data. """
def initialize(self, interval = 1): self.interval = interval
cmd = "/usr/bin/sar -o %s %d 0" % (raw, self.interval) p = subprocess.Popen(cmd, shell=True, stdout=logfile, \ stderr=subprocess.STDOUT) self.pid = p.pid
cmd = self.cmd % (raw, self.interval) self.sar_process = subprocess.Popen(cmd, shell=True, stdout=logfile, stderr=subprocess.STDOUT)
def start(self, test): logfile = open(os.path.join(test.profdir, "sar"), 'w') # Save the sar data as binary, convert to text after the test. raw = os.path.join(test.profdir, "sar.raw") cmd = "/usr/bin/sar -o %s %d 0" % (raw, self.interval) p = subprocess.Popen(cmd, shell=True, stdout=logfile, \ stderr=subprocess.STDOUT...
os.kill(self.pid, 15)
self.sar_process.terminate()
def stop(self, test): os.kill(self.pid, 15)
try: remote_source = self._encode_remote_paths(source) local_dest = utils.sh_escape(dest) rsync = self._make_rsync_cmd([remote_source], local_dest, delete_dest, preserve_symlinks) utils.run(rsync) except error.CmdError, e:
try_scp = not self.use_rsync if self.use_rsync: try: remote_source = self._encode_remote_paths(source) local_dest = utils.sh_escape(dest) rsync = self._make_rsync_cmd([remote_source], local_dest, delete_dest, preserve_symlinks) utils.run(rsync) except error.CmdError, e: logging.warn("trying scp, rsync failed: %s" % e) ...
def get_file(self, source, dest, delete_dest=False, preserve_perm=True, preserve_symlinks=False): """ Copy files from the remote host to a local path.
try: local_sources = [utils.sh_escape(path) for path in source] rsync = self._make_rsync_cmd(local_sources, remote_dest, delete_dest, preserve_symlinks) utils.run(rsync) except error.CmdError, e:
try_scp = not self.use_rsync if self.use_rsync: try: local_sources = [utils.sh_escape(path) for path in source] rsync = self._make_rsync_cmd(local_sources, remote_dest, delete_dest, preserve_symlinks) utils.run(rsync) except error.CmdError, e: logging.warn("trying scp, rsync failed: %s" % e) try_scp = True if try_scp:
def send_file(self, source, dest, delete_dest=False, preserve_symlinks=False): """ Copy files from a local path to the remote host.
DUMMY_CONTROL = object()
DUMMY_CONTROL = '%(server)r %(label_name)r %(plan_id)r'
def _setup_test_launch_atomic_group_job(self, name): DUMMY_CONTROL = object() DUMMY_EXECUTION_INFO = MockExecutionInfo() DUMMY_QUEUE_ENTRIES_REQUEST = MockQueueEntriesRequest()
'control_file': DUMMY_CONTROL,
'control_file': control_file,
def _setup_test_launch_atomic_group_job(self, name): DUMMY_CONTROL = object() DUMMY_EXECUTION_INFO = MockExecutionInfo() DUMMY_QUEUE_ENTRIES_REQUEST = MockQueueEntriesRequest()
keyvals = {'server': self.engine._server, 'label_name': self.engine._label_name, 'plan_id': self.engine._plan_id}
def _setup_test_launch_atomic_group_job(self, name): DUMMY_CONTROL = object() DUMMY_EXECUTION_INFO = MockExecutionInfo() DUMMY_QUEUE_ENTRIES_REQUEST = MockQueueEntriesRequest()
'queue_entries': DUMMY_QUEUE_ENTRIES_REQUEST.queue_entries, 'keyvals': keyvals}
'queue_entries': DUMMY_QUEUE_ENTRIES_REQUEST.queue_entries}
def _setup_test_launch_atomic_group_job(self, name): DUMMY_CONTROL = object() DUMMY_EXECUTION_INFO = MockExecutionInfo() DUMMY_QUEUE_ENTRIES_REQUEST = MockQueueEntriesRequest()
result = host.run('ls /usr/bin/python*')
result = host.run('ls /usr/bin/python[0-9]*')
def list_remote_pythons(host): """List out installed pythons on host.""" result = host.run('ls /usr/bin/python*') return result.stdout.splitlines()
def write_to_file(file_path, contents):
def write_to_file(filename, data, compress=False):
def write_to_file(file_path, contents): """ Write contents to a given file path specified. If not specified, the file will be created. @param file_path: Path to a given file. @param contents: File contents. """ file_object = open(file_path, 'w') file_object.write(contents) file_object.close()
will be created.
will be created. Optionally, compress the destination file.
def write_to_file(file_path, contents): """ Write contents to a given file path specified. If not specified, the file will be created. @param file_path: Path to a given file. @param contents: File contents. """ file_object = open(file_path, 'w') file_object.write(contents) file_object.close()
@param contents: File contents. """ file_object = open(file_path, 'w') file_object.write(contents) file_object.close()
@param data: File contents. @param compress: Whether the file is going to be compressed at the end of the data write process. """ f = open(filename, 'w') try: f.write(data) finally: f.close() if compress: s, o = commands.getstatusoutput('bzip2 %s' % filename) if s: syslog.syslog("File %s compression failed: %s" % (fil...
def write_to_file(file_path, contents): """ Write contents to a given file path specified. If not specified, the file will be created. @param file_path: Path to a given file. @param contents: File contents. """ file_object = open(file_path, 'w') file_object.write(contents) file_object.close()
full_exe_path = commands.getoutput('strings %s | grep "_="' % path).strip("_=") if full_exe_path.startswith("./"): pwd = commands.getoutput('strings %s | grep "^PWD="' % path).strip("PWD=") full_exe_path = os.path.join(pwd, full_exe_path.strip("./")) return {'core_file': path, 'full_exe_path': full_exe_path}
full_exe_path = None output = commands.getoutput('gdb -c %s batch' % path) path_pattern = re.compile("Core was generated by `([^\0]+)'", re.IGNORECASE) match = re.findall(path_pattern, output) for m in match: m = m.split(" ")[0] if os.path.isfile(m): full_exe_path = m break if full_exe_path is None: syslog.syslog("Co...
def get_info_from_core(path): """ Reads a core file and extracts a dictionary with useful core information. Right now, the only information extracted is the full executable name. @param path: Path to core file. """ # Here we are getting the executable full path in a very inelegant way :( # Since the 'right' solution f...
(crashed_pid, time, uid, signal, hostname, exe) = sys.argv[1:]
(crashed_pid, crash_time, uid, signal, hostname, exe) = sys.argv[1:]
def get_info_from_core(path): """ Reads a core file and extracts a dictionary with useful core information. Right now, the only information extracted is the full executable name. @param path: Path to core file. """ # Here we are getting the executable full path in a very inelegant way :( # Since the 'right' solution f...
write_to_file(core_tmp_path, core_file)
core_tmp_path = write_to_file(core_tmp_path, core_file) processing_succeed = False
def get_info_from_core(path): """ Reads a core file and extracts a dictionary with useful core information. Right now, the only information extracted is the full executable name. @param path: Path to core file. """ # Here we are getting the executable full path in a very inelegant way :( # Since the 'right' solution f...
syslog.syslog(syslog.LOG_INFO, "Writing core files to %s" %
syslog.syslog("Writing core files to %s" %
def get_info_from_core(path): """ Reads a core file and extracts a dictionary with useful core information. Right now, the only information extracted is the full executable name. @param path: Path to core file. """ # Here we are getting the executable full path in a very inelegant way :( # Since the 'right' solution f...
write_to_file(core_path, core_file)
core_path = write_to_file(core_path, core_file, compress=True) processing_succeed = True
def get_info_from_core(path): """ Reads a core file and extracts a dictionary with useful core information. Right now, the only information extracted is the full executable name. @param path: Path to core file. """ # Here we are getting the executable full path in a very inelegant way :( # Since the 'right' solution f...
gdb_command = 'bt full\n' write_to_file(gdb_command_path, gdb_command)
def get_info_from_core(path): """ Reads a core file and extracts a dictionary with useful core information. Right now, the only information extracted is the full executable name. @param path: Path to core file. """ # Here we are getting the executable full path in a very inelegant way :( # Since the 'right' solution f...
gdb_cmd = ('gdb -e %s -c %s -x %s -n -batch -quiet' % (exe_path, core_tmp_path, gdb_command_path)) backtrace = commands.getoutput(gdb_cmd) backtrace = backtrace.decode('utf-8', 'ignore')
if exe_path is not None: gdb_command = 'bt full\n' write_to_file(gdb_command_path, gdb_command) gdb_cmd = ('gdb -e %s -c %s -x %s -n -batch -quiet' % (exe_path, core_tmp_path, gdb_command_path)) backtrace = commands.getoutput(gdb_cmd) backtrace = backtrace.decode('utf-8', 'ignore') else: exe_path = "Unknown" backtr...
def get_info_from_core(path): """ Reads a core file and extracts a dictionary with useful core information. Right now, the only information extracted is the full executable name. @param path: Path to core file. """ # Here we are getting the executable full path in a very inelegant way :( # Since the 'right' solution f...
format_dict = {} format_dict['program'] = exe_path format_dict['pid'] = crashed_pid format_dict['signal'] = signal format_dict['hostname'] = hostname format_dict['time'] = time format_dict['backtrace'] = backtrace report = """Autotest crash report Program: %(program)s PID: %(pid)s Signal: %(signal)s Hostname: %(hostn...
report = "Program: %s\n" % exe_path report += "PID: %s\n" % crashed_pid report += "Signal: %s\n" % signal report += "Hostname: %s\n" % hostname report += "Time of the crash: %s\n" % time.ctime(float(crash_time)) report += "Program backtrace:\n%s\n" % backtrace syslog.syslog("Application %s, PID %s crashed" %
def get_info_from_core(path): """ Reads a core file and extracts a dictionary with useful core information. Right now, the only information extracted is the full executable name. @param path: Path to core file. """ # Here we are getting the executable full path in a very inelegant way :( # Since the 'right' solution f...
syslog.syslog(syslog.LOG_INFO, "Writing core files and reports to %s" %
syslog.syslog("Writing core files and reports to %s" %
def get_info_from_core(path): """ Reads a core file and extracts a dictionary with useful core information. Right now, the only information extracted is the full executable name. @param path: Path to core file. """ # Here we are getting the executable full path in a very inelegant way :( # Since the 'right' solution f...
write_to_file(core_path, core_file)
core_path = write_to_file(core_path, core_file, compress=True)
def get_info_from_core(path): """ Reads a core file and extracts a dictionary with useful core information. Right now, the only information extracted is the full executable name. @param path: Path to core file. """ # Here we are getting the executable full path in a very inelegant way :( # Since the 'right' solution f...
if os.path.isdir(core_tmp_dir): shutil.rmtree(core_tmp_dir)
if processing_succeed: if os.path.isdir(core_tmp_dir): shutil.rmtree(core_tmp_dir) else: syslog.syslog("Crash handler failed to process the core file. " "A copy of the file was kept at %s" % core_tmp_path)
def get_info_from_core(path): """ Reads a core file and extracts a dictionary with useful core information. Right now, the only information extracted is the full executable name. @param path: Path to core file. """ # Here we are getting the executable full path in a very inelegant way :( # Since the 'right' solution f...
print 'Error: Unable to find GWT, is GWT installed?\n'
logging.error('Unable to find GWT. ' 'You can use utils/build_externals.py to install it.')
def find_gwt_dir(): """See if GWT is installed in site-packages or in the system, site-packages is favored over a system install. """ site_gwt = os.path.join(_AUTOTEST_DIR, 'site-packages', 'gwt') if os.path.isdir(site_gwt): return site_gwt if not os.path.isdir(_DEFAULT_GWT_DIR): print 'Error: Unable to find GWT, is ...