rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
for patchdir in Directory(self.cfg['patches_dir']).values():
for patchdir in Directory(self.patches_dir).values():
def apply(self): """Apply patches.
check_call(['git', 'am', patchdir.abspath], cwd=os.path.join(self.root, 'eggs-mrsd'))
eggdir = os.path.join(self.root, 'eggs-mrsd', patchdir.__name__) try: check_call(['git', 'checkout', '-b', '__mrsd_patched__', 'initial'], cwd=eggdir) except subprocess.CalledProcessError: check_call(['git', 'checkout', 'master'], cwd=eggdir) check_call(['git', 'branch', '-D', '__mrsd_patched__'], cwd=eggdir) check_cal...
def apply(self): """Apply patches.
def __call__(self, egg_name): stock_path = self.parent.cmds['stock'](egg_name) custom_path = os.path.join(self.cfg['custom_eggs_dir'], egg_name) shutil.copytree(stock_path, custom_path, symlinks=True) check_call(['git', 'init'], cwd=custom_path, stdout=PIPE, stderr=PIPE) check_call(['git', 'add', '.'], cwd=custom_pat...
def __call__(self, egg_names=None, pargs=None): if pargs is not None: egg_names = pargs.egg_name eggspaces = self.parent.stock() if not isinstance(egg_names, list): egg_names = [egg_names] for egg_name in egg_names: for name, eggspace in eggspaces.iteritems(): try: stock_path = eggspace[egg_name] except KeyError: conti...
def __call__(self, egg_name): stock_path = self.parent.cmds['stock'](egg_name) custom_path = os.path.join(self.cfg['custom_eggs_dir'], egg_name) # copy the stock egg to customized eggs shutil.copytree(stock_path, custom_path, symlinks=True) # initialize as a git repo and create initial commit check_call(['git', 'init']...
def __call__(self, script=None):
def __call__(self, script=None, pargs=None):
def __call__(self, script=None): """script is the (relative) path to the script """ # For now we return one list for all paths = [os.path.abspath(os.path.join(self.cfg['custom_eggs_dir'], x)) \ for x in os.listdir(self.cfg['custom_eggs_dir'])] return paths
def __call__(self):
def __call__(self, pargs=None):
def __call__(self): """If no arguments are specified, we hook into all known scripts
cmds = object.__getattr(self, 'cmds')
cmds = object.__getattribute__(self, 'cmds')
def __getattr__(self, name): cmds = object.__getattr(self, 'cmds') if name in cmds: return cmds[name]
self.patches = dict() for pkg in os.listdir(patches_dir): self.patches[pkg] = [] pkg_patch_dir = os.path.join(patches_dir, pkg) for patch in os.listdir(pkg_patch_dir): patch = os.path.abspath(patch) self.patches[pkg].append(patch)
def _initialize(self): # read a list of available patches patches_dir = self.cfg.setdefault('patches_dir', 'eggs-patches') patches_dir = os.path.join( self.root or os.curdir, patches_dir, ) if not os.path.isdir(patches_dir): os.mkdir(patches_dir) self.patches = dict() for pkg in os.listdir(patches_dir): self.patches[pk...
return self.patches
return [x for x in Directory(self.cfg['patches_dir'])]
def list(self): """List patches. """ return self.patches
ours = self.cmdset.cfg['develop']
ours = self.cmdset.cfg['develop'].values()
def __call__(self): develop = self.buildout['buildout']['develop'] ours = self.cmdset.cfg['develop'] self.buildout['buildout']['develop'] = str("\n".join([develop] + ours))
channels = pargs.channel if not channels: pyscriptdir = PyScriptDir(os.path.join(self.root, 'bin')) return [x for x in pyscriptdir]
if pargs is not None: channels = pargs.channel if channels is None: pyscriptdir = PyScriptDir(os.path.join(self.root, 'bin')) return [x for x in pyscriptdir]
def __call__(self, channels=None, pargs=None): """So far we just list all distributions used by the current env """ if not self.root: logger.error("Not rooted, run 'mrsd init'.") return if channels is None: channels = pargs.channel if not channels: pyscriptdir = PyScriptDir(os.path.join(self.root, 'bin')) return [x for...
help=self.list.__doc__,
help=self.generate.__doc__,
def init_argparser(self, parser): """Add our arguments to a parser """ actions = parser.add_mutually_exclusive_group() actions.add_argument( '--list', dest='action', action='store_const', const=self.list, help=self.list.__doc__, ) actions.add_argument( '--generate', dest='action', action='store_const', const=self.gener...
help=self.list.__doc__, )
help=self.apply.__doc__, ) parser.set_defaults(action=self.list)
def init_argparser(self, parser): """Add our arguments to a parser """ actions = parser.add_mutually_exclusive_group() actions.add_argument( '--list', dest='action', action='store_const', const=self.list, help=self.list.__doc__, ) actions.add_argument( '--generate', dest='action', action='store_const', const=self.gener...
def list(self, namespace): """List patches for namespace.
def list(self): """List patches.
def list(self, namespace): """List patches for namespace. """ return self.patches
"""Generate patches from customized bdist eggs.
"""Generate patches from customized bdists.
def generate(self, namespace): """Generate patches from customized bdist eggs. """ check_call(['git', 'add', '.'], cwd=target.abspath)
def apply(self, namespace): """Apply patches for namespace.
def apply(self): """Apply patches.
def generate(self, namespace): """Generate patches from customized bdist eggs. """ check_call(['git', 'add', '.'], cwd=target.abspath)
if channels is None: pyscriptdir = PyScriptDir(os.path.join(self.root, 'bin')) return [x for x in pyscriptdir]
def __call__(self, channels=None, pargs=None): """So far we just list all distributions used by the current env """ if not self.root: logger.error("Not rooted, run 'mrsd init'.") return if channels is None: if pargs is not None: channels = pargs.channel if channels is None: pyscriptdir = PyScriptDir(os.path.join(self.r...
for elem in sup.findall('//timezoneData/zoneFormatting/zoneItem'):
for elem in sup.findall('.//timezoneData/zoneFormatting/zoneItem'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tzsup.findall('//timezone'):
for elem in tzsup.findall('.//timezone'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in sup.findall('//territoryContainment/group'):
for elem in sup.findall('.//territoryContainment/group'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in prsup.findall('//plurals/pluralRules'):
for elem in prsup.findall('.//plurals/pluralRules'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
elem = tree.find('//identity/language')
elem = tree.find('.//identity/language')
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
elem = tree.find('//identity/territory')
elem = tree.find('.//identity/territory')
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//territories/territory'):
for elem in tree.findall('.//territories/territory'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//languages/language'):
for elem in tree.findall('.//languages/language'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//variants/variant'):
for elem in tree.findall('.//variants/variant'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//scripts/script'):
for elem in tree.findall('.//scripts/script'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
supelem = sup.find('//weekData')
supelem = sup.find('.//weekData')
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//timeZoneNames/gmtFormat'):
for elem in tree.findall('.//timeZoneNames/gmtFormat'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//timeZoneNames/regionFormat'):
for elem in tree.findall('.//timeZoneNames/regionFormat'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//timeZoneNames/fallbackFormat'):
for elem in tree.findall('.//timeZoneNames/fallbackFormat'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//timeZoneNames/zone'):
for elem in tree.findall('.//timeZoneNames/zone'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//timeZoneNames/metazone'):
for elem in tree.findall('.//timeZoneNames/metazone'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for calendar in tree.findall('//calendars/calendar'):
for calendar in tree.findall('.//calendars/calendar'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//numbers/symbols/*'):
for elem in tree.findall('.//numbers/symbols/*'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//decimalFormats/decimalFormatLength'):
for elem in tree.findall('.//decimalFormats/decimalFormatLength'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//scientificFormats/scientificFormatLength'):
for elem in tree.findall('.//scientificFormats/scientificFormatLength'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//currencyFormats/currencyFormatLength'):
for elem in tree.findall('.//currencyFormats/currencyFormatLength'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//percentFormats/percentFormatLength'):
for elem in tree.findall('.//percentFormats/percentFormatLength'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//currencies/currency'):
for elem in tree.findall('.//currencies/currency'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
for elem in tree.findall('//units/unit'):
for elem in tree.findall('.//units/unit'):
def main(): parser = OptionParser(usage='%prog path/to/cldr') options, args = parser.parse_args() if len(args) != 1: parser.error('incorrect number of arguments') srcdir = args[0] destdir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), '..', 'babel') sup = parse(os.path.join(srcdir, 'supplemental', 'sup...
example, while in french the central europian timezone is usually
example, while in French the central European timezone is usually
def get_timezone_name(dt_or_tzinfo=None, width='long', uncommon=False, locale=LC_TIME): r"""Return the localized display name for the given timezone. The timezone may be specified using a ``datetime`` or `tzinfo` object. >>> from pytz import timezone >>> dt = time(15, 30, tzinfo=timezone('America/Los_Angeles')) >>> ge...
offset = datetime.utcoffset()
offset = datetime.tzinfo.utcoffset(datetime)
def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME): """Return the timezone associated with the given `datetime` object formatted as string indicating the offset from GMT. >>> dt = datetime(2007, 4, 1, 15, 30) >>> get_timezone_gmt(dt, locale='en') u'GMT+00:00' >>> from pytz import timezone >>> tz = time...
def test_singlular_plural_form(self):
def test_singular_plural_form(self):
def test_singlular_plural_form(self): buf = StringIO(r'''msgid "foo"
msgstr[1] "Vohs"''') catalog = pofile.read_po(buf, locale='ja_JP') self.assertEqual(1, len(catalog)) self.assertEqual(1, catalog.num_plurals)
msgstr[1] "Vohs"''') catalog = pofile.read_po(buf, locale='nl_NL') self.assertEqual(1, len(catalog)) self.assertEqual(2, catalog.num_plurals)
def test_singlular_plural_form(self): buf = StringIO(r'''msgid "foo"
self.assertEqual(1, len(message.string))
self.assertEqual(2, len(message.string))
def test_singlular_plural_form(self): buf = StringIO(r'''msgid "foo"
suite.addTest(doctest.DocTestSuite(catalog, optionflags=doctest.ELLIPSIS))
if hasattr(doctest, 'ELLIPSIS'): suite.addTest(doctest.DocTestSuite(catalog, optionflags=doctest.ELLIPSIS)) else: suite.addTest(doctest.DocTestSuite(catalog))
def suite(): suite = unittest.TestSuite() suite.addTest(doctest.DocTestSuite(catalog, optionflags=doctest.ELLIPSIS)) suite.addTest(unittest.makeSuite(MessageTestCase)) suite.addTest(unittest.makeSuite(CatalogTestCase)) return suite
"'": "'",
"'": "&
def __init__(self, context): super(SuperFishQueryBuilder, self).__init__(context)
title=title, description=desc.replace('"', '"'),
title=self.html_escape(title), description=self.html_escape(desc),
def menuitem(item, first=False, last=False, menu_level=0): classes = []
GAGTTTGATCATGGCTCAGATTGAACGCTGGCGGCATGCCTTACACATGCAAGTCGAACGGCAGCGCGGGGCAACCTGGCGGCGAGTGGCGAACGGGTGAGTAATACATCGGAACGTACCCAGAAGTGGGGGATAACGTAGCGAAAGTTACGCTAATACCGCATACGTTCTACGGAAGAAAGTGGGGGATCTTCGGACCTCATGCTTTTGGAGCGGCCGATGTCTGATTAGCTAGTTGGTGAGGTAAAGGCTCACCAAGGCGACGATCAGTAGCTGGTCTGAGAGGACGACCAGCCACACTGGGACTGAGACACGGCCCA...
GAGTTTGATCATGGCTCAGATTGAACGCTGGCGGCATGCCTTACACATGCAAGTCGAACGGCAGCGCGGGGCAACCTGGCGGCGAGTGGCGAACGGGTGAGTAATACATCGGAACGTACCCAGAAGTGGGGGATAACGTAGCGAAAGTTACGCTAATACCGCATACGTTCTACGGAAGAAAGTGGGGGATCTTCGGACCTCATGCTTTTGGAGCGGCCGATGTCTGATTAGCTAGTTGGTGAGGTAAAGGCTCACCAAGGCGACGATCAGTAGCTGGTCTGAGAGGACGACCAGCCACACTGGGACTGAGACACGGCCCA...
def test_pynast_seq_3037(self): """ uclust as pairwise aligner fixes problematic bl2seq alignment Strange alignment issues were found with this sequence in PyNAST 1.0. This tests that a good alignment is achieved with this seqeunce in later versions. """ template_alignment = LoadSeqs(data=template_128453.split('\n')) ...
inBusStop = False
self.inBusStop = False
def endElement(self, name):
def GetWith( self, expression, compare=(lambda a,b:a.find(b) >= 0) ):
def GetWith( self, expression, compare=(lambda a,b:fnmatch.fnmatch(a,b))):
def GetWith( self, expression, compare=(lambda a,b:a.find(b) >= 0) ): """Returns a list of all processes that contain the expression in their command line.""" res = [] for pid, cmdline in self.List().items(): if compare(cmdline, expression): res.append(pid) return res
threads = status["threads"],
threads = int(status["threads"]),
def Info( self, pid ): status = Process.Status(pid) proc_pid = "/proc/%d" % (pid) if not os.path.exists(proc_pid): dict( pid = pid, exists = False, probeStart = self.firstProbe, probeEnd = self.lastProbe ) else: status = Process.Status(pid) started = os.stat(proc_pid)[stat.ST_MTIME] running = time.t...
def __init__( self, variableName, host="0.0.0.0", port=9009, extract=lambda _:_.result):
def __init__( self, variableName, host="0.0.0.0", port=9009, extract=lambda r,_:r):
def __init__( self, variableName, host="0.0.0.0", port=9009, extract=lambda _:_.result): Action.__init__(self) self.host = host self.port = port self.name = variableName self.url = "tcp://%s:%s" % (self.host, self.port) self.extractor = extract self.socket = ZMQPublish.getZMQSocket(self.url)
message = "%s:application/json:%s" % (self.name, json.dumps(self.extractor(runner)))
message = "%s:application/json:%s" % (self.name, json.dumps(self.extractor(runner.result.value, runner)))
def send( self, runner ): # FIXME: I think this is a blocking operation message = "%s:application/json:%s" % (self.name, json.dumps(self.extractor(runner))) # NOTE: ZMQ PUB is asynchronous, ZMQ DOWNSTREAM is not ! self.socket.send(message) return message
pid = Process.GetWith(self.command, lambda a,b:a.find(b) != -1)
pid = Process.GetWith(self.command)
def run( self ): pid = Process.GetWith(self.command, lambda a,b:a.find(b) != -1) if pid: pid = pid[0] info = Process.Info(pid) if info["exists"]: return Success(info) else: return Failure("Process %s does not exists anymore" % (pid)) else: return Failure("Cannot find process with command like: %s" % (self.command))
def __init__( self, rule, extract=lambda _:_, fail=(), success=() ):
def __init__( self, rule, extract=lambda res:res, fail=(), success=() ):
def __init__( self, rule, extract=lambda _:_, fail=(), success=() ): Rule.__init__(self, rule.freq, fail, success) self.extractor = extract self.rule = rule self.previous = None
print repr(line)
def MemoryInfo( self ): """Returns the content of /proc/meminfo as a dictionary 'key' -> 'value' where value is in kB""" res = {} for line in cat("/proc/meminfo").split("\n")[:-1]: line = RE_SPACES.sub(" ", line).strip().split(" ") print repr(line) name, value = line[:2] res[name.replace("(","_").replace(")","_").repla...
return (meminfo["MemTotal"] - meminfo["MemFree"]) / float (meminfo["MemTotal"])
return (meminfo["MemTotal"] - meminfo["MemFree"] - meminfo["Cached"]) / float (meminfo["MemTotal"])
def MemoryUsage( self ): """Returns the memory usage (between 0.0 and 1.0) on this system.""" meminfo = self.MemoryInfo() return (meminfo["MemTotal"] - meminfo["MemFree"]) / float (meminfo["MemTotal"])
usage = 100 - (res[len(res) - 1] * 100.00 / sum(res))
usage = (100 - (res[len(res) - 1] * 100.00 / sum(res))) / 100.0
def CPUUsage( self, cpuStat=None ): if not cpuStat: cpuStat = self.LAST_CPU_STAT stat_now = self.CPUStats() res = [] for i in range(len(cpuStat)): res.append( stat_now[i] - cpuStat[i] ) usage = 100 - (res[len(res) - 1] * 100.00 / sum(res)) return usage
def __init__( self, path=None, stdout=True ):
def __init__( self, path=None, stdout=True, overwrite=False ):
def __init__( self, path=None, stdout=True ): Action.__init__(self) self.path = path self.stdout = stdout
f = file( self.path, 'a')
f = file( self.path, self.overwrite and 'w' or 'a')
def run( self, monitor, service, rule, runner): if runner.hasFailed(): msg = self.failureMessage(monitor, service, rule, runner) + "\n" else: msg = self.successMessage(monitor, service, rule, runner) + "\n" if self.stdout: sys.stdout.write(msg) if self.path: f = file( self.path, 'a') f.write(msg) f.flush() f.close() re...
def __init__( self, message="adasd", path=None, stdout=True, process=lambda _:_ ): Log.__init__(self, path, stdout)
def __init__( self, message, path=None, stdout=True, process=lambda _:_, overwrite=False ): Log.__init__(self, path, stdout, overwrite)
def __init__( self, message="adasd", path=None, stdout=True, process=lambda _:_ ): Log.__init__(self, path, stdout) self.message = message self.processor = process
since_last_run = now() - self.lastRun return self.freq - since_last_run
if self.lastRun == 0: return 0 else: since_last_run = now() - self.lastRun return self.freq - since_last_run def touch( self ): self.lastRun = now()
def shouldRunIn( self ): since_last_run = now() - self.lastRun return self.freq - since_last_run
self.lastRun = now()
self.touch()
def run( self ): self.lastRun = now() return Success()
return "HTTP(%s=\"%s:%s/%s\",timeout=%s)" % (self.method, self.server, self.port, self.uri, self.timeout)
return "HTTP(%s=\"%s:%s%s\",timeout=%s)" % (self.method, self.server, self.port, self.uri, self.timeout)
def __repr__( self ): return "HTTP(%s=\"%s:%s/%s\",timeout=%s)" % (self.method, self.server, self.port, self.uri, self.timeout)
class Bandwith(Rule):
class Bandwidth(Rule):
def run( self ): pid = Process.GetWith(self.command, lambda a,b:a.find(b) != -1) if pid: pid = pid[0] info = Process.Info(pid) if info["exists"]: return Success(info) else: return Failure("Process %s does not exists anymore" % (pid)) else: return Failure("Cannot find process with command like: %s" % (self.command))
self.logger.info("
self.iterationLastDuration = duration self.logger.info(self.getStatusMessage())
def run( self ): Signals.Setup() self.isRunning = True while self.isRunning: it_start = now() next_run = it_start + self.freq for service in self.services: for rule in service.rules: to_wait = rule.shouldRunIn() if to_wait > 0: next_run = min(now() + to_wait, next_run) else: # Create a runner runner = self.runnerForRul...
self.logger.info("No failure action to trigger")
pass
def onRuleEnded( self, runner ): """Callback bound to 'Runner.onRunEnded', trigerred once a rule was executed. If the rule failed, actions will be executed.""" # FIXME: Handle exception rule = runner.runnable service = runner.context if isinstance(runner.result, Success): if rule.success: #self.logger.info("Success ...
html = file.read()
def bs_preprocess(file): """remove distracting whitespaces and newline characters"""
return bs.BeautifulSoup(file, convertEntities = bs.BeautifulStoneSoup.HTML_ENTITIES)
html = re.sub('Medin WebAudit SZTAKI sztr Angol-magyar sztr', ' ', html) return bs.BeautifulSoup(unicode(html, "utf-8"), convertEntities = bs.BeautifulStoneSoup.HTML_ENTITIES)
def bs_preprocess(file): """remove distracting whitespaces and newline characters"""
self.exportChoice.Append("MOHO")
def __init__(self, *args, **kwds): # begin wxGlade: LipsyncFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.panel_2 = wx.Panel(self, -1) self.sizer_5_staticbox = wx.StaticBox(self.panel_2, -1, "Voice List") self.sizer_7_staticbox = wx.StaticBox(self.panel_2, -1, "Current...
self.SetTitle("%s - %s" % (self.doc.name, appTitle))
self.SetTitle("%s [%s] - %s" % (self.doc.name, paths[0], appTitle))
def OnOpen(self, event = None): if not self.CloseDocOK(): return dlg = wx.FileDialog( self, message = "Open Audio or %s File" % appTitle, defaultDir = self.config.Read("WorkingDir", get_main_dir()), defaultFile = "", wildcard = openWildcard, style = wx.OPEN | wx.CHANGE_DIR | wx.FILE_MUST_EXIST) if dlg.ShowModal() == wx...
defaultFile = "", wildcard = saveWildcard, style = wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT)
defaultFile = "%s" % self.doc.soundPath.rsplit('.', 1)[0]+".pgo", wildcard = saveWildcard, style = wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT)
def OnSaveAs(self, event = None): if self.doc is None: return dlg = wx.FileDialog( self, message = "Save %s File" % appTitle, defaultDir = self.config.Read("WorkingDir", get_main_dir()), defaultFile = "", wildcard = saveWildcard, style = wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: sel...
self.SetTitle("%s - %s" % (self.doc.name, appTitle))
self.SetTitle("%s [%s] - %s" % (self.doc.name, dlg.GetPaths()[0], appTitle))
def OnSaveAs(self, event = None): if self.doc is None: return dlg = wx.FileDialog( self, message = "Save %s File" % appTitle, defaultDir = self.config.Read("WorkingDir", get_main_dir()), defaultFile = "", wildcard = saveWildcard, style = wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: sel...
defaultFile = "", wildcard = "Moho switch files (*.dat)|*.dat", style = wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT)
defaultFile = "%s" % self.doc.soundPath.rsplit('.', 1)[0]+".dat", wildcard = "Moho switch files (*.dat)|*.dat", style = wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT)
def OnVoiceExport(self, event): language = self.languageChoice.GetStringSelection() if (self.doc is not None) and (self.doc.currentVoice is not None): exporter = self.exportChoice.GetStringSelection() if exporter == "MOHO": dlg = wx.FileDialog( self, message = "Export Lipsync Data (MOHO)", defaultDir = self.config.Read...
defaultFile = "", wildcard = "Alelo timing files (*.timing)|*.timing", style = wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT)
defaultFile = "%s" % self.doc.soundPath.rsplit('.', 1)[0]+".txt", wildcard = "Alelo timing files (*.txt)|*.txt", style = wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT)
def OnVoiceExport(self, event): language = self.languageChoice.GetStringSelection() if (self.doc is not None) and (self.doc.currentVoice is not None): exporter = self.exportChoice.GetStringSelection() if exporter == "MOHO": dlg = wx.FileDialog( self, message = "Export Lipsync Data (MOHO)", defaultDir = self.config.Read...
exec("import breakdowns.italian_breakdown as breakdown")
exec("import %s as breakdown" % details["breakdown_class"])
def RunBreakdown(self, parentWindow, language, languagemanager): self.phonemes = [] try: text = self.text.strip(strip_symbols) details = languagemanager.language_table[language] if details["type"] == "breakdown": exec("import breakdowns.italian_breakdown as breakdown") pronunciation = breakdown.breakdownWord(text) for ...
outFile.write("%s %d %d\n" % (lastPhoneme_text, lastPhoneme.frame, phoneme.frame-1))
outFile.write("%d %d %s\n" % (lastPhoneme.frame, phoneme.frame-1, lastPhoneme_text))
def ExportAlelo(self, path, language, languagemanager): outFile = open(path, 'w') for phrase in self.phrases: for word in phrase.words: text = word.text.strip(strip_symbols) details = languagemanager.language_table[language] if languagemanager.current_language != language: languagemanager.LoadLanguage(details) language...
outFile.write("%s %d %d\n" % (lastPhoneme_text, lastPhoneme.frame, word.endFrame))
outFile.write("%d %d %s\n" % (lastPhoneme.frame, word.endFrame, lastPhoneme_text))
def ExportAlelo(self, path, language, languagemanager): outFile = open(path, 'w') for phrase in self.phrases: for word in phrase.words: text = word.text.strip(strip_symbols) details = languagemanager.language_table[language] if languagemanager.current_language != language: languagemanager.LoadLanguage(details) language...
self.doc.sound.PlaySegment(float(self.scrubFrame) / float(self.doc.fps), 10.0 / self.doc.fps, 1.0)
self.doc.sound.PlaySegment(float(self.scrubFrame) / float(self.doc.fps), 15.0 / self.doc.fps, 1.0)
def OnMouseDown(self, event): self.isDragging = False self.dragChange = False self.draggingEnd = -1 # which end of the object (beginning or end) are you dragging self.selectedPhrase = None self.selectedWord = None self.selectedPhoneme = None x, y = event.GetPositionTuple() x, y = self.CalcUnscrolledPosition(x, y) self....
self.doc.sound.PlaySegment(float(self.scrubFrame) / float(self.doc.fps), 1.0 / self.doc.fps, 1.0)
self.doc.sound.PlaySegment(float(self.scrubFrame) / float(self.doc.fps), 15.0 / self.doc.fps, 1.0)
def OnMouseMove(self, event): if self.isDragging: x, y = event.GetPositionTuple() x, y = self.CalcUnscrolledPosition(x, y) frame = x / self.frameWidth if frame == self.dragStartFrame: return self.dragStartFrame = -1000 # kick it far out of the way
print "start: %f" % start print "length: %f" % length
def _play(self, start, length): print "start: %f" % start print "length: %f" % length self.isplaying = True startframe = int(round(start * self.wave_reference.getframerate())) samplelen = int(round(length * self.wave_reference.getframerate())) print startframe print samplelen remaining = samplelen chunk = 1024 try: sel...
print startframe print samplelen
def _play(self, start, length): print "start: %f" % start print "length: %f" % length self.isplaying = True startframe = int(round(start * self.wave_reference.getframerate())) samplelen = int(round(length * self.wave_reference.getframerate())) print startframe print samplelen remaining = samplelen chunk = 1024 try: sel...
print self.time
def _play(self, start, length): print "start: %f" % start print "length: %f" % length self.isplaying = True startframe = int(round(start * self.wave_reference.getframerate())) samplelen = int(round(length * self.wave_reference.getframerate())) print startframe print samplelen remaining = samplelen chunk = 1024 try: sel...
if scm_ifce.has_uncommitted_change(file_data.name):
if not in_patch and scm_ifce.has_uncommitted_change(file_data.name):
def _get_patch_overlap_data(patch): ''' Get the data detailing unrefreshed/uncommitted files that will be overlapped by the supplied patch ''' assert is_readable() data = OverlapData(unrefreshed = {}, uncommitted = []) next_index = _get_next_patch_index() applied_patches = get_applied_patch_list() for file_data in patc...
print "HEJ"
def _get_completions(self): """Return a list of possible completions for the string ending at the point. Also set begidx and endidx in the process.""" completions = [] self.begidx = self.l_buffer.point self.endidx = self.l_buffer.point buf=self.l_buffer.line_buffer if self.completer: # get the string to complete while ...
setattr(self, var_name.replace(u'-',u'_'), val)
setattr(self.mode, var_name.replace(u'-',u'_'), val)
def parse_and_bind(self, string): u'''Parse and execute single line of a readline init file.''' try: log(u'parse_and_bind("%s")' % string) if string.startswith(u'#'): return if string.startswith(u'set'): m = re.compile(ur'set\s+([-a-zA-Z0-9]+)\s+(.+)\s*$').match(string) if m: var_name = m.group(1) val = m.group(2) try:...
rep = [ c for c in cprefix ] point=self.l_buffer.point self.l_buffer[self.begidx:self.endidx] = rep self.l_buffer.point = point + len(rep) - (self.endidx - self.begidx)
if len(cprefix) > 0: rep = [ c for c in cprefix ] point=self.l_buffer.point self.l_buffer[self.begidx:self.endidx] = rep self.l_buffer.point = point + len(rep) - (self.endidx - self.begidx)
def complete(self, e): # (TAB) u"""Attempt to perform completion on the text before point. The actual completion performed is application-specific. The default is filename completion.""" completions = self._get_completions() if completions: cprefix = commonprefix(completions) rep = [ c for c in cprefix ] point=self.l_b...
root_logger.addHandler(NULLHandler())
pyreadline_logger.addHandler(NULLHandler())
def close(self): pass
root_logger.addHandler(socket_handler)
pyreadline_logger.addHandler(socket_handler)
def start_socket_log(): root_logger.addHandler(socket_handler)
root_logger.removeHandler(socket_handler)
pyreadline_logger.removeHandler(socket_handler)
def stop_socket_log(): root_logger.removeHandler(socket_handler)
file_handler = logging.handlers.FileHandler(filename, "w") root_logger.addHandler(file_handler)
file_handler = logging.FileHandler(filename, "w") pyreadline_logger.addHandler(file_handler)
def start_file_log(filename): global file_handler file_handler = logging.handlers.FileHandler(filename, "w") root_logger.addHandler(file_handler)
root_logger.removeHandler(file_handler)
pyreadline_logger.removeHandler(file_handler)
def stop_file_log(): global file_handler if file_handler: root_logger.removeHandler(file_handler) file_handler.close() file_handler = None
reward = self.rewards[self.y][self.x]
def Act(self, action): # Express movement as the complex number x + y*i with a probability of # p to move orthogonal to the desired direction of movement. delta = { 'L' : -1, 'R' : 1, 'U' : 1j, 'D' : -1j }[action]
print('usage: ./rl n', file=sys.stderr)
print('usage: ./rl ticks', file=sys.stderr)
def main(argv): if len(argv) <= 1: print('err: incorrect number of arguments', file=sys.stderr) print('usage: ./rl n', file=sys.stderr) return 1 n = int(argv[1]) # Grid world depicted on p.646 of Russel and Norvig (3rd Ed.). world = World(4, 3) world.AddObstacle(1, 1) # Receive a reward of -0.04 each move with a pro...
n = int(argv[1])
ticks = int(argv[1])
def main(argv): if len(argv) <= 1: print('err: incorrect number of arguments', file=sys.stderr) print('usage: ./rl n', file=sys.stderr) return 1 n = int(argv[1]) # Grid world depicted on p.646 of Russel and Norvig (3rd Ed.). world = World(4, 3) world.AddObstacle(1, 1) # Receive a reward of -0.04 each move with a pro...
print('Average Reward = {0}'.format(sum(rewards) / n))
print('Average Reward = {0}'.format(sum(rewards) / len(rewards)))
def main(argv): if len(argv) <= 1: print('err: incorrect number of arguments', file=sys.stderr) print('usage: ./rl n', file=sys.stderr) return 1 n = int(argv[1]) # Grid world depicted on p.646 of Russel and Norvig (3rd Ed.). world = World(4, 3) world.AddObstacle(1, 1) # Receive a reward of -0.04 each move with a pro...
self.last_ping = 0 self.ircobj.delayed_commands.append( (time.time()+5, self._no_ping, [] ) )
def __init__(self, server, port, channel, nick, mysql_server, mysql_port, mysql_database, mysql_user, mysql_password): irclib.SimpleIRCClient.__init__(self) #IRC details self.server = server self.port = port self.target = channel self.channel = channel self.nick = nick #MySQL details self.mysql_server = mysql_server...
def _no_ping(self): if self.last_ping >= 1200: raise irclib.ServerNotConnectedError else: self.last_ping += 10 self.ircobj.delayed_commands.append( (time.time()+10, self._no_ping, [] ) )
def __init__(self, server, port, channel, nick, mysql_server, mysql_port, mysql_database, mysql_user, mysql_password): irclib.SimpleIRCClient.__init__(self) #IRC details self.server = server self.port = port self.target = channel self.channel = channel self.nick = nick #MySQL details self.mysql_server = mysql_server...
connection.disconnect() raise irclib.ServerNotConnectedError
def on_disconnect(self, connection, event): self.on_ping(connection, event)