code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
toyield = start while end is None or toyield < end: yield toyield toyield += delta
def between(start, delta, end=None)
Return an iterator between this date till given end point. Example usage: >>> d = datetime_tz.smartparse("5 days ago") 2008/05/12 11:45 >>> for i in d.between(timedelta(days=1), datetime_tz.now()): >>> print i 2008/05/12 11:45 2008/05/13 11:45 2008/05/14 11:45 200...
5.620063
8.927901
0.629494
return iterate.between(start, datetime.timedelta(days=1), end)
def days(start, end=None)
Iterate over the days between the given datetime_tzs. Args: start: datetime_tz to start from. end: (Optional) Date to end at, if not given the iterator will never terminate. Returns: An iterator which generates datetime_tz objects a day apart.
13.495225
22.050413
0.612017
return iterate.between(start, datetime.timedelta(hours=1), end)
def hours(start, end=None)
Iterate over the hours between the given datetime_tzs. Args: start: datetime_tz to start from. end: (Optional) Date to end at, if not given the iterator will never terminate. Returns: An iterator which generates datetime_tz objects a hour apart.
14.084241
21.123411
0.66676
return iterate.between(start, datetime.timedelta(minutes=1), end)
def minutes(start, end=None)
Iterate over the minutes between the given datetime_tzs. Args: start: datetime_tz to start from. end: (Optional) Date to end at, if not given the iterator will never terminate. Returns: An iterator which generates datetime_tz objects a minute apart.
12.676431
20.897268
0.606607
placeholder, created = page.placeholders.get_or_create( slot=placeholder_slot) if created: log.debug("Create placeholder %r for page %r", placeholder_slot, page.get_title()) else: log.debug("Use existing placeholder %r for page %r", placeholder_slot, ...
def get_or_create_placeholder(page, placeholder_slot, delete_existing=False)
Get or create a placeholder on the given page. Optional: Delete existing placeholder.
2.40835
2.573697
0.935755
for language_code, lang_name in iter_languages(languages): url = page.get_absolute_url() if page.publisher_is_draft: page.publish(language_code) log.info('page "%s" published in %s: %s', page, lang_name, url) else: log.info('published page "%s" alrea...
def publish_page(page, languages)
Publish a CMS page in all given languages.
3.32534
3.144324
1.057569
try: index_page = Page.objects.get(is_home=True, publisher_is_draft=False) except Page.DoesNotExist: log.debug('Create index page in "en" and...') index_page = create_page( title="index in English", template=TEMPLATE_INHERITANCE_MAGIC, language=s...
def create_cms_index_pages(placeholder_slot="content")
create cms home page and fill >content< placeholder with TextPlugin
3.07634
3.022164
1.017926
creator = CmsPluginPageCreator( apphook=apphook, apphook_namespace=apphook_namespace, ) creator.placeholder_slot = placeholder_slot plugin_page = creator.create() return plugin_page
def create_cms_plugin_page(apphook, apphook_namespace, placeholder_slot=None)
Create cms plugin page in all existing languages. Add a link to the index page. :param apphook: e.g...........: 'FooBarApp' :param apphook_namespace: e.g.: 'foobar' :return:
2.547909
3.04456
0.836873
title = self.get_title(language_code, lang_name) assert title != "" title = str(title) # e.g.: evaluate a lazy translation slug = slugify(title) assert slug != "", "Title %r results in empty slug!" % title return slug
def get_slug(self, language_code, lang_name)
Notes: - slug must be unique! - slug is used to check if page already exists! :return: 'slug' string for cms.api.create_page()
7.663158
8.272381
0.926355
try: home_page_draft = Page.objects.get( is_home=True, publisher_is_draft=True) except Page.DoesNotExist: log.error('ERROR: "home page" doesn\'t exists!') raise RuntimeError('no home page') return home_page_draft
def get_home_page(self)
Return the published home page. Used for 'parent' in cms.api.create_page()
5.114906
3.993402
1.280839
assert page.publisher_is_draft == True, "Page '%s' must be a draft!" % page publish_page(page, languages=self.languages)
def publish(self, page)
Publish the page in all languages.
6.703775
5.92218
1.131978
with translation.override(self.default_language_code): # for evaluate the language name lazy translation # e.g.: settings.LANGUAGE_CODE is not "en" self.default_lang_name = dict( self.languages)[self.default_language_code] self.slug = sel...
def create_page(self, **extra_kwargs)
Create page (and page title) in default language extra_kwargs will be pass to cms.api.create_page() e.g.: extra_kwargs={ "soft_root": True, "reverse_id": my_reverse_id, }
2.593736
2.528355
1.025859
for language_code, lang_name in iter_languages(self.languages): try: title = Title.objects.get(page=page, language=language_code) except Title.DoesNotExist: slug = self.get_slug(language_code, lang_name) assert slug != "", "No slug...
def create_title(self, page)
Create page title in all other languages with cms.api.create_title()
2.919154
2.713709
1.075706
return { "plugin_type": 'TextPlugin', # djangocms_text_ckeditor "body": self.get_dummy_text(page, no, placeholder, language_code, lang_name) }
def get_add_plugin_kwargs(self, page, no, placeholder, language_code, lang_name)
Return "content" for create the plugin. Called from self.add_plugins()
4.280779
4.008823
1.067839
for language_code, lang_name in iter_languages(self.languages): for no in range(1, self.dummy_text_count + 1): add_plugin_kwargs = self.get_add_plugin_kwargs( page, no, placeholder, language_code, lang_name) log.info( ...
def add_plugins(self, page, placeholder)
Add a "TextPlugin" in all languages.
4.316565
3.948756
1.093145
placeholder, created = get_or_create_placeholder( page, placeholder_slot, delete_existing=self.delete_first) return placeholder, created
def get_or_create_placeholder(self, page, placeholder_slot)
Add a placeholder if not exists.
5.478471
4.937972
1.109458
if len(placeholder_slot) == 1: raise RuntimeError(placeholder_slot) placeholder, created = self.get_or_create_placeholder( page, placeholder_slot) self.add_plugins(page, placeholder)
def fill_content(self, page, placeholder_slot)
Add a placeholder to the page. Here we add a "TextPlugin" in all languages.
4.624506
4.03425
1.146311
plugin = CMSPlugin.objects.filter(plugin_type=self.apphook) if plugin.exists(): log.debug('Plugin page for "%s" plugin already exist, ok.', self.apphook) raise plugin page, created = super(CmsPluginPageCreator, self).create() if cr...
def create(self)
Create the plugin page in all languages and fill dummy content.
8.51422
6.63904
1.282448
title = "%s %i-%i in %s" % (self.title_prefix, self.current_count, self.current_level, language_code) log.info(title) return title
def get_title(self, language_code, lang_name)
:return: 'title' string for cms.api.create_page()
6.91775
6.177851
1.119766
if self.current_level == 1: # 'root' page return None else: return self.page_data[(self.current_level - 1, self.current_count)]
def get_parent_page(self)
For 'parent' in cms.api.create_page()
5.646404
5.281341
1.069123
# initially copied from SimpleHTTPServer words = pth.split('/') words = filter(None, words) pth = self.location for word in words: # Do not allow path separators other than /, # drive names and . .. drive, word = os.path.splitdrive(wor...
def translate_path(self, pth)
Translate a /-separated PATH to the local filename syntax.
3.919016
3.815279
1.02719
from collections import OrderedDict SKIP_KEYS = () return OrderedDict( (p.key, getattr(self, p.key)) for p in self.__mapper__.attrs if p.key not in SKIP_KEYS)
def dict(self)
A dict that holds key/values for all of the properties in the object. :return:
6.293598
6.597178
0.953983
for c in self.columns: if c.source_header == source_header_or_pos: assert c.st_vid == self.vid return c elif c.position == source_header_or_pos: assert c.st_vid == self.vid return c else: return...
def column(self, source_header_or_pos)
Return a column by name or position :param source_header_or_pos: If a string, a source header name. If an integer, column position :return:
3.227845
3.444039
0.937226
from ..identity import GeneralNumber2 c = self.column(source_header) c_by_pos = self.column(position) datatype = 'str' if datatype == 'unicode' else datatype assert not c or not c_by_pos or c.vid == c_by_pos.vid # Convert almost anything to True / False ...
def add_column(self, position, source_header, datatype, **kwargs)
Add a column to the source table. :param position: Integer position of the column started from 1. :param source_header: Name of the column, as it exists in the source file :param datatype: Python datatype ( str, int, float, None ) for the column :param kwargs: Other source record args. ...
5.308033
5.220478
1.016771
from ..identity import GeneralNumber1 if sequence_id: self.sequence_id = sequence_id self.vid = str(GeneralNumber1('T', self.d_vid, self.sequence_id))
def update_id(self, sequence_id=None)
Alter the sequence id, and all of the names and ids derived from it. This often needs to be don after an IntegrityError in a multiprocessing run
11.622085
12.310925
0.944046
from sqlalchemy import Table from ..orm import Geometry table = Table(table_name, metadata, autoload=True) for c in table.columns: # HACK! Sqlalchemy sees spatialte GEOMETRY types # as NUMERIC if c.name == 'geometry': c.type = Geometry # What about variants? ...
def table_convert_geometry(metadata, table_name)
Get table metadata from the database.
11.742477
11.771497
0.997535
from sqlalchemy import text seq_col = table_class.sequence_id.property.columns[0].name try: parent_col = table_class._parent_col except AttributeError: parent_col = table_class.d_vid.property.columns[0].name assert bool(parent_vid) key = (parent_vid, table_class.__name_...
def next_sequence_id(session, sequence_ids, parent_vid, table_class, force_query = False)
Return the next sequence id for a object, identified by the vid of the parent object, and the database prefix for the child object. On the first call, will load the max sequence number from the database, but subsequence calls will run in process, so this isn't suitable for multi-process operation -- all of ...
3.605613
3.589653
1.004446
from ambry.identity import ObjectNumber d = {} for p in o.__mapper__.attrs: v = getattr(o, p.key) if v is None: d[p.key] = None elif p.key in prop_names: d[p.key] = str(ObjectNumber.increment(v)) else: if not hasattr(v, '__mapper__')...
def incver(o, prop_names)
Increment the version numbers of a set of properties and return a new object
4.250573
4.184502
1.015789
if isinstance(value, string_types): value = value.strip() if value[0] == '[': # It's json encoded, probably try: value = json.loads(value) except ValueError: raise ValueError("Failed to parse JSON: '{}' "....
def coerce(cls, key, value)
Convert plain list to MutationList.
4.525175
3.641308
1.242733
try: idx = query.lower().index('where') query = query[:idx] except ValueError: pass if not query.endswith(';'): query = query.strip() query += ';' result = _view_stmt.parseString(query) return View(result)
def parse_view(query)
Parses asql query to view object. Args: query (str): asql query Returns: View instance: parsed view.
4.176032
4.155872
1.004851
t.name = t.parsed_name t.alias = t.parsed_alias[0] if t.parsed_alias else '' return t
def _flat_alias(t)
Populates token (column or table) fields from parse result.
4.569072
3.725859
1.226314
t.source.name = t.source.parsed_name t.source.alias = t.source.parsed_alias[0] if t.source.parsed_alias else '' return t
def _build_join(t)
Populates join token fields.
4.772161
4.162147
1.146562
from ambry.identity import ObjectNumber, TableNumber, NotObjectNumberError from ambry.orm.exc import NotFoundError try: stmt_str = statement.to_unicode() except AttributeError: stmt_str = statement parts = stmt_str.strip(';').split() new_parts = [] tables = set() ...
def substitute_vids(library, statement)
Replace all of the references to tables and partitions with their vids. This is a bit of a hack -- it ought to work with the parser, but instead it just looks for common SQL tokens that indicate an identifier. :param statement: an sqlstatement. String. :return: tuple: new_statement, set of table vids,...
3.827677
3.404192
1.124401
derefed, tables, partitions = substitute_vids(library, sql) if derefed.lower().startswith('create index') or derefed.lower().startswith('index'): parsed = parse_index(derefed) return FIMRecord(statement=derefed, indexes=[(parsed.source, tuple(parsed.columns))]) elif derefed.lower().s...
def find_indexable_materializable(sql, library)
Parse a statement, then call functions to install, materialize or create indexes for partitions referenced in the statement. :param sql: :param materialize_f: :param install_f: :param index_f: :return:
2.941323
2.869684
1.024964
if not drop: drop = [] if not tables: tables = set() if not install: install = set() if not materialize: materialize = set() if not indexes: indexes = set() if rec: self.update( ...
def update(self, rec=None, drop=None, tables=None, install=None, materialize=None, indexes=None, joins=0, views=0)
Updates current record. Args: rec (FIMRecord):
2.182599
2.30168
0.948263
allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"] if support_level not in allowed_values: raise ValueError( "Invalid value for `support_level` ({0}), must be one of {1}" .format(support_level, allowed_values) ...
def support_level(self, support_level)
Sets the support_level of this ProductReleaseRest. :param support_level: The support_level of this ProductReleaseRest. :type: str
2.555964
2.407274
1.061767
dc = base.DelayedCall(self.seconds() + when, what, a, kw, self.calls.remove, lambda c: None, self.seconds) self.calls.append(dc) self.calls.sort(lambda a, b: cmp(a.getTime(), b.getTime())) r...
def callLater(self, when, what, *a, **kw)
Copied from twisted.internet.task.Clock, r20480. Fixes the bug where the wrong DelayedCall would sometimes be returned.
5.807138
5.01119
1.158834
clock = Clock() dc1 = clock.callLater(10, lambda: None) dc2 = clock.callLater(1, lambda: None) if dc1 is dc2: return True else: return False
def clockIsBroken()
Returns whether twisted.internet.task.Clock has the bug that returns the wrong DelayedCall or not.
4.05454
2.793147
1.451603
global scm_status_cache if config.artifact in scm_status_cache.keys(): result = scm_status_cache[config.artifact] elif not read_modules and (("%s|False" % config.artifact) in scm_status_cache.keys()): result = scm_status_cache["%s|False" % config.artifact] else: result = _ge...
def get_scm_status(config, read_modules=False, repo_url=None, mvn_repo_local=None, additional_params=None)
Gets the artifact status (MavenArtifact instance) from SCM defined by config. Only the top-level artifact is read by default, although it can be requested to read the whole available module structure. :param config: artifact config (ArtifactConfig instance) :param read_modules: if True all modules are read...
1.876395
1.957153
0.958737
logging.debug("Shrinking patch file %s to keep only %s changes.", patch_path, target_file) shrinked_lines = [] patch_file = None try: patch_file = open(patch_path) adding = False search_line = "diff --git a/%s b/%s" % (target_file, target_file) for line in patch_file...
def shrink_patch(patch_path, target_file)
Shrinks a patch on patch_path to contain only changes for target_file. :param patch_path: path to the shrinked patch file :param target_file: filename of a file of which changes should be kept :return: True if the is a section containing changes for target_file, Flase otherwise
2.128437
2.039299
1.04371
allowed_values = ["NEW", "DONE", "REJECTED"] if new_status not in allowed_values: raise ValueError( "Invalid value for `new_status` ({0}), must be one of {1}" .format(new_status, allowed_values) ) self._new_status = new_status
def new_status(self, new_status)
Sets the new_status of this BuildSetStatusChangedEvent. :param new_status: The new_status of this BuildSetStatusChangedEvent. :type: str
1.975317
1.961643
1.006971
allowed_values = ["NEW", "DONE", "REJECTED"] if old_status not in allowed_values: raise ValueError( "Invalid value for `old_status` ({0}), must be one of {1}" .format(old_status, allowed_values) ) self._old_status = old_status
def old_status(self, old_status)
Sets the old_status of this BuildSetStatusChangedEvent. :param old_status: The old_status of this BuildSetStatusChangedEvent. :type: str
1.894796
1.961302
0.966091
''' Run development server with automated reload on code change:: ./manage.py app:serve [host] [port] [level] ''' logging.basicConfig(level=getattr(logging, level.upper()), format=self.format) if self.bootstrap: logger.info('Bootstraping...') ...
def command_serve(self, host='', port='8000', level='debug')
Run development server with automated reload on code change:: ./manage.py app:serve [host] [port] [level]
8.056688
7.110212
1.133115
''' Shell command:: ./manage.py app:shell Executed with `self.shell_namespace` as local variables namespace. ''' from code import interact interact('Namespace {!r}'.format(self.shell_namespace), local=self.shell_namespace)
def command_shell(self)
Shell command:: ./manage.py app:shell Executed with `self.shell_namespace` as local variables namespace.
14.539668
3.840835
3.785549
'''Create mix-in class with all assignments turned into methods decorated with declared_attr. Usage: @declared_mixin def FactoryFunction(): or with base mix-in class[es]: @declared_mixin(BaseMixIn1, BaseMixIn2) def FactoryFunction(): For example: @declared_mi...
def declared_mixin(*bases)
Create mix-in class with all assignments turned into methods decorated with declared_attr. Usage: @declared_mixin def FactoryFunction(): or with base mix-in class[es]: @declared_mixin(BaseMixIn1, BaseMixIn2) def FactoryFunction(): For example: @declared_mixin ...
3.591677
2.058188
1.745068
hash = 0 x = 0 for c in s: hash = (hash << 4) + c x = hash & 0xF0000000 if x: hash ^= (x >> 24) hash &= ~x return (hash & 0x7FFFFFFF)
def elfhash(s)
:param string: bytes >>> import base64 >>> s = base64.b64encode(b'hello world') >>> elfhash(s) 224648685
2.395761
3.255182
0.735984
length = len(l) for index, current in enumerate(l): # current is the last element if length - 1 == index: return current # current is the first element if index == 0: if element < current: return None if current <= element < ...
def find_previous(element, l)
find previous element in a sorted list >>> find_previous(0, [0]) 0 >>> find_previous(2, [1, 1, 3]) 1 >>> find_previous(0, [1, 2]) >>> find_previous(1.5, [1, 2]) 1 >>> find_previous(3, [1, 2]) 2
3.26342
4.378342
0.745355
_old_match_hostname = ssl.match_hostname def _new_match_hostname(cert, hostname): if hostname.endswith('.s3.amazonaws.com'): pos = hostname.find('.s3.amazonaws.com') hostname = hostname[:pos].replace('.', '') + hostname[pos:] return _old_match_hostname(cert, hostn...
def patch_match_hostname()
Fixes https://github.com/boto/boto/issues/2836
2.722045
2.351798
1.157432
from collections import OrderedDict d = OrderedDict( [(p.key, getattr(self, p.key)) for p in self.__mapper__.attrs if p.key not in ('data',)]) if 'list' in self.data: d['bundle_count'] = len(self.data['list']) else: d['bundle_count'] = None ...
def dict(self)
A dict that holds key/values for all of the properties in the object. :return:
3.555833
3.712543
0.957789
from ambry.orm.exc import NotFoundError from requests.exceptions import ConnectionError, HTTPError from boto.exception import S3ResponseError d = {} try: for k, v in self.list(full=True): if not v: continue ...
def update(self)
Cache the list into the data section of the record
4.118878
3.734097
1.103045
if self.is_api: return self._list_api(full=full) else: return self._list_fs(full=full)
def list(self, full=False)
List all of the bundles in the remote
4.124715
4.599006
0.896871
from json import dumps full_list = [ e[1] for e in self._list_fs(full=True) ] remote = self._fs_remote(self.url) remote.setcontents(os.path.join('_meta', 'list.json'), dumps(full_list, indent = 4))
def _update_fs_list(self)
Cache the full list for http access. This creates a meta file that can be read all at once, rather than requiring a list operation like S3 access does
7.80432
6.357092
1.227656
from ambry.orm.exc import NotFoundError if not os.path.exists(package.path): raise NotFoundError("Package path does not exist: '{}' ".format(package.path)) if self.is_api: return self._checkin_api(package, no_partitions=no_partitions, force=force, cb=cb) ...
def checkin(self, package, no_partitions=False, force=False, cb=None)
Check in a bundle package to the remote. :param package: A Database, referencing a sqlite database holding the bundle :param cb: a two argument progress callback: cb(message, num_records) :return:
2.584078
2.741663
0.942522
from six import text_type from fs.errors import ResourceNotFoundError identity = ds.identity d = identity.dict d['summary'] = ds.config.metadata.about.summary d['title'] = ds.config.metadata.about.title meta_stack = self._meta_infos(ds) def ...
def _put_metadata(self, fs_remote, ds)
Store metadata on a pyfs remote
6.0887
5.899819
1.032015
if self.is_api: return self._checkout_api(ref, cb=cb) else: return self._checkout_fs(ref, cb=cb)
def checkout(self, ref, cb=None)
Checkout a bundle from the remote. Returns a file-like object
3.153147
3.044377
1.035728
if self.is_api: return self._remove_api(ref, cb) else: return self._remove_fs(ref, cb)
def remove(self, ref, cb=None)
Check in a bundle to the remote
3.984116
3.88884
1.0245
from ambry.util.ambrys3 import AmbryS3FS from ambry.util import parse_url_to_dict import ssl pd = parse_url_to_dict(url) if account_acessor: account = account_acessor(pd['hostname']) assert account['account_id'] == pd['hostname'] aw...
def s3(self, url, account_acessor=None, access=None, secret=None)
Setup an S3 pyfs, with account credentials, fixing an ssl matching problem
3.205195
2.973947
1.077758
bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("{% withdict %} expects one argument") nodelist = parser.parse(('endwithdict',)) parser.delete_first_token() return WithDictNode( nodelist=nodelist, context_expr=parser.compile_filter(bits[1]) ...
def withdict(parser, token)
Take a complete context dict as extra layer.
2.231017
2.199654
1.014258
extra_context = self.context_expr.resolve(context) if not isinstance(extra_context, dict): raise TemplateSyntaxError("{% withdict %} expects the argument to be a dictionary.") with context.push(**extra_context): return self.nodelist.render(context)
def render(self, context)
Render the tag, with extra context layer.
4.513827
4.068748
1.10939
u'''Wrapper of session maker adding link to a FileManager instance to session.:: file_manager = FileManager(cfg.TRANSIENT_ROOT, cfg.PERSISTENT_ROOT) filesessionmaker(sessionmaker(...), file_manager) ''' registry = WeakKeyDictionary() if file_mana...
def filesessionmaker(sessionmaker, file_manager, file_managers=None)
u'''Wrapper of session maker adding link to a FileManager instance to session.:: file_manager = FileManager(cfg.TRANSIENT_ROOT, cfg.PERSISTENT_ROOT) filesessionmaker(sessionmaker(...), file_manager)
4.91924
3.475526
1.415394
import math c = 0 while 1: if _square_wave: yield ((c % 300) < 150) * 30 + 20 c += 1 else: yield 10 * math.sin(2 * 3.1415926 * c + shift) \ + 20 + 5 * math.sin(2 * 3.1415926 * c * 3 + shift) c += .001
def oscillating_setpoint(_square_wave=False, shift=0)
A basic example of a target that you may want to approximate. If you have a thermostat, this is a temperature setting. This target can't change too often
3.354863
3.483827
0.962982
import subprocess # import random # more predictable version of the metric cmd = ( 'set -o pipefail ' ' ; pgrep -f "^bash.*sleep .*from bash: started relay launcher"' ' | wc -l ' ) # less predictable version of the metric # cmd = 'ps aux|wc -l' while True:...
def bash_echo_metric()
A very basic example that monitors a number of currently running processes
6.709618
6.802121
0.986401
import subprocess import random cmd = ( 'set -o pipefail ' " ; sleep %s " " ; sh -c 'echo from bash: started relay launcher task && sleep %s'" ) for i in range(n): subprocess.Popen( cmd % ((1 + random.random()) * 1, (1 + random.random()) * 4), ...
def bash_echo_warmer(n)
A very basic example of how to create n additional tasks. This is a warmer function with randomly delayed effects on the bash_echo_metric and random task lengths to make the metric less predictable
6.444389
6.488925
0.993137
import subprocess cmd = ( 'set -o pipefile ' ' ; kill `pgrep -f "from bash: started relay launcher task"' ' | tail -n %s` 2>/dev/null' % n) subprocess.Popen(cmd, shell=True, executable='bash').wait()
def bash_echo_cooler(n)
A very basic example of how to destroy n running tasks This is a cooler function
14.034416
14.33467
0.979054
n_increases = sum([ abs(y) - abs(x) > 0 for x, y in zip(errdata, errdata[1:])]) if len(errdata) * 0.5 < n_increases: # most of the time, the next sample is worse than the previous sample # relay is not healthy return 0 else: # most of the time, the next sample is...
def stop_if_mostly_diverging(errdata)
This is an example stop condition that asks Relay to quit if the error difference between consecutive samples is increasing more than half of the time. It's quite sensitive and designed for the demo, so you probably shouldn't use this is a production setting
5.70744
5.282949
1.080351
for dependency in self.dependencies: if dependency.state != Task.State.DONE: return False return True
def has_resolved_dependencies(self)
Return True if all dependencies are in State.DONE
6.367586
3.497625
1.820546
dependencies = [] for dependency in self.dependencies: dependencies.append(dependency.name) return dependencies
def dependencies_as_list(self)
Returns a list of dependency names.
3.404613
2.616841
1.301039
if name in self.tasks.keys(): task = self.tasks[name] else: task = Task(name) self.tasks[name] = task return task
def get_task(self, name)
Get task by name or create it if it does not exists.
2.088585
1.820832
1.14705
self.update_tasks_status() if self.dirty: self.tsort() self.dirty = False for key, task in self.tasks.iteritems(): if task.is_new() and task.has_resolved_dependencies(): return task return None
def get_next(self)
Return next task from the stack that has all dependencies resolved. Return None if there are no tasks with resolved dependencies or is there are no more tasks on stack. Use `count` to check is there are still some task left on the stack. raise ValueError if total ordering is not possible.
6.945284
4.548637
1.526893
self.update_tasks_status() buildable_tasks_count = 0 for key, task in self.tasks.iteritems(): if task.state is Task.State.NEW: if self.are_dependencies_buildable(task): buildable_tasks_count += 1 logging.debug("Buildabl...
def count_buildable_tasks(self)
Count tasks that are new and have dependencies in non FAILED state.
3.177592
2.746543
1.156943
new_tasks = {} for task_name in task_names: task = self.get_task(task_name) if task not in new_tasks: new_tasks[task.name] = task if keep_dependencies: for dependency in task.ordered_dependencies(): if depen...
def filter_tasks(self, task_names, keep_dependencies=False)
If filter is applied only tasks with given name and its dependencies (if keep_keep_dependencies=True) are kept in the list of tasks.
2.434466
2.394262
1.016792
task_dict = {} for key, task in self.tasks.iteritems(): task_dict[task] = task.dependencies # parts = parts.copy() parts = task_dict.copy() result = [] while True: level = set([name for name, deps in parts.iteritems() if not deps]) ...
def tsort(self)
Given a partial ordering, return a totally ordered list. part is a dict of partial orderings. Each value is a set, which the key depends on. The return value is a list of sets, each of which has only dependencies on items in previous entries in the list. raise ValueError if o...
4.33742
3.169288
1.368579
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.build_with_http_info(build_execution_configuration, **kwargs) else: (data) = self.build_with_http_info(build_execution_configuration, **kwargs) return data
def build(self, build_execution_configuration, **kwargs)
Triggers the build execution for a given configuration. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ...
1.583554
1.585661
0.998672
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.build_task_completed_with_http_info(task_id, build_result, **kwargs) else: (data) = self.build_task_completed_with_http_info(task_id, build_result, **kwargs) return data
def build_task_completed(self, task_id, build_result, **kwargs)
Notifies the completion of externally managed build task process. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): ...
1.469882
1.490659
0.986062
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.cancel_bbuild_with_http_info(build_execution_configuration_id, **kwargs) else: (data) = self.cancel_bbuild_with_http_info(build_execution_configuration_id, **kwargs) return...
def cancel_bbuild(self, build_execution_configuration_id, **kwargs)
Cancel the build execution defined with given executionConfigurationId. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(respons...
1.415778
1.50932
0.938024
config = import_module('config') variables = [var for var in dir(config) if not var.startswith('_')] return {var: getattr(config, var) for var in variables}
def _load_config(self)
Load project's config and return dict. TODO: Convert the original dotted representation to hierarchical.
3.416978
3.152548
1.083878
if '.' not in name: raise Exception("Config path should be divided by at least one dot") section_name, var_path = name.split('.', 1) section = Config._data.get(section_name) return section.get(var_path)
def get(name, default=None)
Return variable by name from the project's config. Name can be a dotted path, like: 'rails.db.type'.
6.03783
5.295824
1.140112
'Return last item with a key <= k. Raise ValueError if not found.' i = bisect_right(self._keys, k) if i: return self._items[i - 1] raise ValueError('No item found with key at or below: %r' % (k,))
def find_le(self, k)
Return last item with a key <= k. Raise ValueError if not found.
4.783133
3.236409
1.477914
'Return last item with a key <= k. Raise ValueError if not found.' i = bisect_right(self._keys, k) if i: return i - 1 raise ValueError('No item found with key at or below: %r' % (k,))
def find_le_index(self, k)
Return last item with a key <= k. Raise ValueError if not found.
5.520628
3.636876
1.517959
i = bisect_left(self._keys, k) if i: return self._items[i - 1] raise ValueError('No item found with key below: %r' % (k,))
def find_lt(self, k)
Return last item with a key < k. Raise ValueError if not found.
3.897924
3.538715
1.101508
'Return first item with a key >= equal to k. Raise ValueError if not found' i = bisect_left(self._keys, k) if i != len(self): return i raise ValueError('No item found with key at or above: %r' % (k,))
def find_ge_index(self, k)
Return first item with a key >= equal to k. Raise ValueError if not found
5.429326
3.593242
1.510983
''' Return the current brk value in the debugged process (only x86_64 Linux) ''' # TODO this method is so weird, find a unused address to inject code not # the base address debugger = get_debugger() code = b'\x0f\x05' # syscall rax = debugger.get_reg("rax") rdi = debugger.get_reg...
def get_dbg_brk_linux64()
Return the current brk value in the debugged process (only x86_64 Linux)
4.0874
3.455602
1.182833
''' Return the current brk value in the debugged process (only x86 Linux) ''' # TODO this method is so weird, find a unused address to inject code not # the base address debugger = get_debugger() code = b'\xcd\x80' # int 0x80 eax = debugger.get_reg("eax") ebx = debugger.get_reg("...
def get_dbg_brk_linux32()
Return the current brk value in the debugged process (only x86 Linux)
4.128458
3.537473
1.167064
if loop is None: loop = asyncio.get_event_loop() global reload_hook if hook is not None: reload_hook = hook global task if not task: modify_times = {} executor = ThreadPoolExecutor(1) task = call_periodically( loop, interval, ...
def start( loop: abstract_loop = None, interval: float = 0.5, hook: hook_type = None) -> asyncio.Task
Start the reloader. Create the task which is watching loaded modules and manually added files via ``watch()`` and reloading the process in case of modification. Attach this task to the loop. If ``hook`` is provided, it will be called right before the application goes to the reload stage.
4.60402
4.64915
0.990293
''' `strftime` implementation working before 1900 ''' if _illegal_s.search(fmt): raise TypeError("This strftime implementation does not handle %s") if dt.year > 1900: return dt.strftime(fmt) fmt = fmt.replace('%c', '%a %b %d %H:%M:%S %Y')\ .replace('%Y', str(dt.year...
def strftime(dt, fmt)
`strftime` implementation working before 1900
4.391506
4.033392
1.088787
import tabulate import terminaltables from textwrap import fill from ambry.util.text import getTerminalSize import sys if args.connect: try: l.database.connection.execute('SELECT * FROM pg_stat_activity;') sys.exit(0) except Exception as e: ...
def library_pg(args, l, config)
Report on the operation of a Postgres Library database
2.631764
2.597836
1.01306
# pylint: disable=global-statement global win32timezone_to_en # Try and fetch the key_name for the timezone using # Get(Dynamic)TimeZoneInformation tzi = DTZI_c() kernel32 = ctypes.windll.kernel32 getter = kernel32.GetTimeZoneInformation getter = getattr(kernel32, "GetDynamicTimeZoneInformation", ge...
def _detect_timezone_windows()
Detect timezone on the windows platform.
4.647269
4.609164
1.008267
if salt is None: salt = binascii.hexlify(os.urandom(3))[:5] else: salt = salt.encode('utf-8') raw_password = raw_password.encode('utf-8') hash = hashlib.new(algorithm, salt+raw_password).hexdigest() return '{}${}${}'.format(algorithm, salt.decode('utf-8'), hash)
def encrypt_password(raw_password, algorithm='sha1', salt=None)
Returns a string of the hexdigest of the given plaintext password and salt using the given algorithm ('md5', 'sha1' or other supported by hashlib).
2.156888
2.29166
0.94119
algo, salt, hsh = enc_password.split('$') return enc_password == encrypt_password(raw_password, algorithm=algo, salt=salt)
def check_password(raw_password, enc_password)
Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes.
4.736252
5.118505
0.925319
''' This property will return component which will handle login requests. auth.login(template='login.html') ''' def _login(env, data): form = self._login_form(env) next = env.request.GET.get('next', '/') login_failed = False if...
def login(self, template='login')
This property will return component which will handle login requests. auth.login(template='login.html')
5.598649
4.488503
1.247331
''' This property will return component which will handle logout requests. It only handles POST requests and do not display any rendered content. This handler deletes session id from `storage`. If there is no session id provided or id is incorrect handler silently redirects to ...
def logout(self, redirect_to='/')
This property will return component which will handle logout requests. It only handles POST requests and do not display any rendered content. This handler deletes session id from `storage`. If there is no session id provided or id is incorrect handler silently redirects to login url and ...
9.857444
3.198045
3.082335
allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"] if not set(content).issubset(set(allowed_values)): raise ValueError( "Invalid values for `content` [{0}], must be a subset of [{1}]" .format(", ".join(map(str, set(...
def content(self, content)
Sets the content of this SupportLevelPage. :param content: The content of this SupportLevelPage. :type: list[str]
2.616969
2.278544
1.148527
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_bpm_task_by_id_with_http_info(task_id, **kwargs) else: (data) = self.get_bpm_task_by_id_with_http_info(task_id, **kwargs) return data
def get_bpm_task_by_id(self, task_id, **kwargs)
Get single (recently) active BPM task. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(respon...
1.376952
1.483679
0.928066
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_bpm_tasks_with_http_info(**kwargs) else: (data) = self.get_bpm_tasks_with_http_info(**kwargs) return data
def get_bpm_tasks(self, **kwargs)
List of (recently) active BPM tasks. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response...
1.5385
1.688602
0.911108
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.notify_task_with_http_info(task_id, **kwargs) else: (data) = self.notify_task_with_http_info(task_id, **kwargs) return data
def notify_task(self, task_id, **kwargs)
Notify PNC about a BPM task event. Accepts polymorphic JSON {\"eventType\": \"string\"} based on \"eventType\" field. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the respo...
1.516278
1.57829
0.960709
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.start_r_creation_task_with_single_url_with_http_info(body, **kwargs) else: (data) = self.start_r_creation_task_with_single_url_with_http_info(body, **kwargs) return data
def start_r_creation_task_with_single_url(self, body, **kwargs)
Start Repository Creation task with url autodetect (internal vs. external). This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(res...
1.357348
1.448593
0.937012
assert bool(input_) assert bool(output) input_opened = False output_opened = False try: if isinstance(input_, string_types): if not os.path.isdir(os.path.dirname(input_)): os.makedirs(os.path.dirname(input_)) input_ = open(input_, 'r') ...
def copy_file_or_flo(input_, output, buffer_size=64 * 1024, cb=None)
Copy a file name or file-like-object to another file name or file-like object
1.789655
1.831099
0.977367
self.config = config or {} for key in ['messaging_token', 'number']: if key not in self.config: msg = "Tropo backend config must set '%s'; config is %r" %\ (key, config) raise ImproperlyConfigured(msg) if kwargs: ...
def configure(self, config=None, **kwargs)
We expect all of our config (apart from the ENGINE) to be in a dictionary called 'config' in our INSTALLED_BACKENDS entry
6.388281
5.782669
1.104729
# The signer will also "pickle" the data structure for us signed_program = signing.dumps(program) params = { 'action': 'create', # Required by Tropo 'token': self.config['messaging_token'], # Identify ourselves 'program': signed_program, # Additio...
def execute_tropo_program(self, program)
Ask Tropo to execute a program for us. We can't do this directly; we have to ask Tropo to call us back and then give Tropo the program in the response body to that request from Tropo. But we can pass data to Tropo and ask Tropo to pass it back to us when Tropo calls us back. So...
5.427683
5.151157
1.053682
# Build our program from_ = self.config['number'].replace('-', '') commands = [] for identity in identities: # We'll include a 'message' command for each recipient. # The Tropo doc explicitly says that while passing a list # of destination nu...
def send(self, id_, text, identities, context=None)
Send messages when using RapidSMS 0.14.0 or later. We can send multiple messages in one Tropo program, so we do that. :param id_: Unused, included for compatibility with RapidSMS. :param string text: The message text to send. :param identities: A list of identities to send the ...
8.096085
6.84173
1.183339