code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''Description outputed to console''' command = command or self.__class__.__name__.lower() import inspect _help = u'' _help += u'{}\n'.format(command) if self.__doc__: _help += self._fix_docstring(self.__doc__) +'\n' else: _help += u'{}\n'....
def description(self, argv0='manage.py', command=None)
Description outputed to console
3.816407
3.727345
1.023894
if IBoxReceiver in interfaces: return (IBoxReceiver, Adder(avatarId), lambda: None) raise NotImplementedError()
def requestAvatar(self, avatarId, mind, *interfaces)
Create Adder avatars for any IBoxReceiver request.
14.602676
5.922771
2.465514
''' Unhandled exception handler. You can put any logging, error warning, etc here.''' logger.exception('Exception for %s %s :', env.request.method, env.request.url)
def handle_error(self, env)
Unhandled exception handler. You can put any logging, error warning, etc here.
13.999197
4.704795
2.975517
''' Calls application and handles following cases: * catches `webob.HTTPException` errors. * catches unhandled exceptions, calls `handle_error` method and returns 500. * returns 404 if the app has returned None`. ''' try: resp...
def handle(self, env, data)
Calls application and handles following cases: * catches `webob.HTTPException` errors. * catches unhandled exceptions, calls `handle_error` method and returns 500. * returns 404 if the app has returned None`.
5.676694
2.146827
2.644226
def decorator(function): rkey = key if rkey is None: if isinstance(function, FunctionType): rkey = function.__name__ else: raise NameRequired() if rkey not in self._exposed: self....
def expose(self, key=None)
Expose the decorated method for this L{Exposer} with the given key. A method which is exposed will be able to be retrieved by this L{Exposer}'s C{get} method with that key. If no key is provided, the key is the method name of the exposed method. Use like so:: class MyClas...
2.713452
3.200017
0.847949
if key not in self._exposed: raise MethodNotExposed() rightFuncs = self._exposed[key] T = obj.__class__ seen = {} for subT in inspect.getmro(T): for name, value in subT.__dict__.items(): for rightFunc in rightFuncs: ...
def get(self, obj, key)
Retrieve 'key' from an instance of a class which previously exposed it. @param key: a hashable object, previously passed to L{Exposer.expose}. @return: the object which was exposed with the given name on obj's key. @raise MethodNotExposed: when the key in question was not exposed with ...
4.132183
3.755551
1.100287
# originally from django.utils.encoding while True: try: return path.decode('utf-8') except UnicodeDecodeError as e: repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~") path = path[:e.start] + repercent.encode('ascii') + path[e.end:]
def repercent_broken_unicode(path)
As per section 3.2 of RFC 3987, step three of converting a URI into an IRI, we need to re-percent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence.
3.75396
3.674737
1.021559
r path = url_unquote(path, '%/;?') query = url_unquote(query, '%;/?:@&=+,$#') fragment = url_unquote(fragment, '%;/?:@&=+,$#') return path, query, fragment
def uri_to_iri_parts(path, query, fragment)
r""" Converts a URI parts to corresponding IRI parts in a given charset. Examples for URI versus IRI: :param path: The path of URI to convert. :param query: The query string of URI to convert. :param fragment: The fragment of URI to convert.
4.195644
4.635313
0.905148
import os from ambry.util import AttrDict config = AttrDict() f = os.path.join( os.path.dirname( os.path.realpath(__file__)), 'bundle.yaml') config.update_yaml(f) return config
def default_bundle_config()
Return the default bundle config file as an AttrDict.
4.118802
3.267992
1.260346
l = list() for start in ('ambry/support', 'ambry/bundle/default_files'): for root, dirs, files in os.walk(start): for f in files: if f.endswith('.pyc'): continue path = os.path.join(root, f).replace('ambry/', '') l...
def find_package_data()
Returns package_data, because setuptools is too stupid to handle nested directories. Returns: dict: key is "ambry", value is list of paths.
4.185627
3.509266
1.192736
# The other values should be set when the file object is created with dataset.bsfile() for p in ('mime_type', 'preference', 'state', 'hash', 'modified', 'size', 'contents', 'source_hash', 'data'): setattr(self, p, getattr(of, p)) return self
def update(self, of)
Update a file from another file, for copying
13.935891
12.850578
1.084456
from nbformat import read import msgpack if self.mime_type == 'text/plain': return self.contents.decode('utf-8') elif self.mime_type == 'application/msgpack': # FIXME: Note: I'm not sure that encoding='utf-8' will not break old data. # We n...
def unpacked_contents(self)
:return:
5.545938
5.148398
1.077216
rows = self.unpacked_contents if not rows: return header = rows.pop(0) for row in rows: yield dict(list(zip(header, row)))
def dict_row_reader(self)
Unpacks message pack rows into a stream of dicts.
5.148518
4.112815
1.251823
import hashlib import time new_size = len(contents) self.mime_type = mime_type if mime_type == 'text/plain': self.contents = contents.encode('utf-8') else: self.contents = contents old_hash = self.hash self.hash = hash...
def update_contents(self, contents, mime_type)
Update the contents and set the hash and modification time
2.551653
2.316251
1.101631
d = {p.key: getattr(self, p.key) for p in self.__mapper__.attrs if p.key not in ('contents', 'dataset')} d['modified_datetime'] = self.modified_datetime d['modified_ago'] = self.modified_ago return d
def dict(self)
A dict that holds key/values for all of the properties in the object. :return:
5.217446
5.780244
0.902634
from sqlalchemy import text if not target.id: sql = text('SELECT max(f_id)+1 FROM files WHERE f_d_vid = :did') target.id, = conn.execute(sql, did=target.d_vid).fetchone() if not target.id: target.id = 1 if target.contents and isins...
def before_insert(mapper, conn, target)
event.listen method for Sqlalchemy to set the sequence for this object and create an ObjectNumber value for the id_
3.545474
3.794517
0.934368
try: return klass(data) except UnicodeEncodeError: return text(data) except TypeError: return data
def __deserialize_primitive(self, data, klass)
Deserializes string to primitive type. :param data: str. :param klass: class literal. :return: int, long, float, str, bool.
4.527608
4.998246
0.905839
try: from dateutil.parser import parse timestr = str(datetime.fromtimestamp(string/1000)) return parse(timestr) except ImportError: return string except ValueError: raise ApiException( status=0, ...
def __deserialize_datetime(self, string)
Deserializes string to datetime. The string should be in iso8601 datetime format. :param string: str. :return: datetime.
4.339639
4.615532
0.940225
if isinstance(source, six.string_types): source = six.StringIO(source) # Prepare source lines for reading rows = parse_lines(source) # Get columns if is_namedtuple(wrapper): columns = wrapper._fields wrapper = wrapper._make else: columns = next(rows, None) ...
def un(source, wrapper=list, error_bad_lines=True)
Parse a text stream to TSV If the source is a string, it is converted to a line-iterable stream. If it is a file handle or other object, we assume that we can iterate over the lines in it. The result is a generator, and what it contains depends on whether the second argument is set and what it is ...
4.20056
4.62922
0.907401
strings = (format_collection(item) for item in items) if output is None: return strings else: for s in strings: output.write(s + '\n')
def to(items, output=None)
Present a collection of items as TSV The items in the collection can themselves be any iterable collection. (Single field structures should be represented as one tuples.) With no output parameter, a generator of strings is returned. If an output parameter is passed, it should be a file-like object. Ou...
4.407303
3.708971
1.188282
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_logged_user_with_http_info(**kwargs) else: (data) = self.get_logged_user_with_http_info(**kwargs) return data
def get_logged_user(self, **kwargs)
Gets logged user and in case not existing creates a new one 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.54918
1.659067
0.933765
if not use_history: if args.id: return (args.id, '-i argument') if hasattr(args, 'bundle_ref') and args.bundle_ref: return (args.bundle_ref, 'bundle_ref argument') if 'AMBRY_BUNDLE' in os.environ: return (os.environ['AMBRY_BUNDLE'], 'environment'...
def get_bundle_ref(args, l, use_history=False)
Use a variety of methods to determine which bundle to use :param args: :return:
3.489329
3.510583
0.993946
from ambry.orm.exc import ConflictError ob = l.bundle(args.ref) d = dict( dataset=args.dataset or ob.identity.dataset, revision=args.revision, source=args.source or ob.identity.source, bspace=args.space or ob.identity.bspace, subset=args.subset or ob.identity....
def bundle_variant(args, l, rc)
Create a new bundle as a variant of an existing bundle
4.924408
4.91468
1.001979
from ambry.orm.exc import ConflictError d = dict( dataset=args.dataset, revision=args.revision, source=args.source, bspace=args.space, subset=args.subset, btime=args.time, variation=args.variation) try: ambry_account = rc.accounts.get('...
def bundle_new(args, l, rc)
Create a new bundle
6.14937
6.200509
0.991752
if self.loaded_apps.get(app): return self.loaded_apps.get(app) self.loaded_apps[app] = None initial_data_class = import_string(self.get_class_path(app)) if issubclass(initial_data_class, BaseInitialData): self.log('Loaded app {0}'.format(app)) ...
def load_app(self, app)
Tries to load an initial data class for a specified app. If the specified file does not exist, an error will be raised. If the class does exist, but it isn't a subclass of `BaseInitialData` then None will be returned. :param app: The name of the app in which to load the initial data class. This ...
2.954334
2.232356
1.323415
# don't update this app if it has already been updated if app in self.updated_apps: return # load the initial data class try: initial_data_class = self.load_app(app) except ImportError as e: message = str(e) # Check if th...
def update_app(self, app)
Loads and runs `update_initial_data` of the specified app. Any dependencies contained within the initial data class will be run recursively. Dependency cycles are checked for and a cache is built for updated apps to prevent updating the same app more than once. :param app: The name of the app to...
3.899453
3.46859
1.124218
deduplicated_objs = {} for model in self.model_objs_registered_for_deletion: key = '{0}:{1}'.format( ContentType.objects.get_for_model(model, for_concrete_model=False), model.id ) deduplicated_objs[key] = model # Crea...
def handle_deletions(self)
Manages handling deletions of objects that were previously managed by the initial data process but no longer managed. It does so by mantaining a list of receipts for model objects that are registered for deletion on each round of initial data processing. Any receipts that are from previous rounds and no...
3.676228
3.234538
1.136554
for app in apps.get_app_configs(): self.update_app(app.name) # During update_app, all apps added model objects that were registered for deletion. # Delete all objects that were previously managed by the initial data process self.handle_deletions()
def update_all_apps(self)
Loops through all app names contained in settings.INSTALLED_APPS and calls `update_app` on each one. Handles any object deletions that happened after all apps have been initialized.
12.159297
9.99351
1.216719
# start the call_list with the current app if one wasn't passed in recursively call_list = call_list or [app] # load the initial data class for the app try: initial_data_class = self.load_app(app) except ImportError: raise InitialDataMissingApp(d...
def get_dependency_call_list(self, app, call_list=None)
Recursively detects any dependency cycles based on the specific app. A running list of app calls is kept and passed to each function call. If a circular dependency is detected an `InitialDataCircularDependency` exception will be raised. If a dependency does not exist, an `InitialDataMissingApp` ...
4.217838
3.20292
1.316873
self.dataset_index.reset() self.partition_index.reset() self.identifier_index.reset()
def reset(self)
Resets (deletes) all indexes.
7.954668
6.035868
1.3179
if isinstance(terms, (tuple, list)): if len(terms) > 1: return '(' + ' OR '.join(terms) + ')' else: return terms[0] else: return terms
def _or_join(self, terms)
Joins terms using OR operator. Args: terms (list): terms to join Examples: self._or_join(['term1', 'term2']) -> 'term1 OR term2' Returns: str
2.394317
2.638484
0.907459
if len(terms) > 1: return ' AND '.join([self._or_join(t) for t in terms]) else: return self._or_join(terms[0])
def _and_join(self, terms)
Joins terms using AND operator. Args: terms (list): terms to join Examples: self._and_join(['term1']) -> 'term1' self._and_join(['term1', 'term2']) -> 'term1 AND term2' self._and_join(['term1', 'term2', 'term3']) -> 'term1 AND term2 AND term3' R...
2.375204
2.934498
0.809407
if not self.is_indexed(instance) and not force: doc = self._as_document(instance) self._index_document(doc, force=force) logger.debug('{} indexed as\n {}'.format(instance.__class__, pformat(doc))) return True logger.debug('{} already indexed.'.fo...
def index_one(self, instance, force=False)
Indexes exactly one object of the Ambry system. Args: instance (any): instance to index. force (boolean): if True replace document in the index. Returns: boolean: True if document added to index, False if document already exists in the index.
4.405385
4.313819
1.021226
# find tables. assert isinstance(dataset, Dataset) execute = object_session(dataset).connection().execute query = text() columns = u('\n').join( [u(' ').join(list(text_type(e) for e in t)) for t in execute(query, dataset_vid=str(dataset.identity.vid))]) ...
def _as_document(self, dataset)
Converts dataset to document indexed by to FTS index. Args: dataset (orm.Dataset): dataset to convert. Returns: dict with structure matches to BaseDatasetIndex._schema.
5.05441
5.116932
0.987781
ret = { 'keywords': list(), 'doc': list()} if not isinstance(terms, dict): stp = SearchTermParser() terms = stp.parse(terms, term_join=self.backend._and_join) if 'about' in terms: ret['doc'].append(terms['about']) i...
def _expand_terms(self, terms)
Expands terms of the dataset to the appropriate fields. It will parse the search phrase and return only the search term components that are applicable to a Dataset query. Args: terms (dict or str): Returns: dict: keys are field names, values are query strings
6.32552
6.111401
1.035036
schema = ' '.join( u'{} {} {} {} {}'.format( c.id, c.vid, c.name, c.altname, c.description) for c in partition.table.columns) values = '' for stat in partition.stats: if stat.uvalu...
def _as_document(self, partition)
Converts given partition to the document indexed by FTS backend. Args: partition (orm.Partition): partition to convert. Returns: dict with structure matches to BasePartitionIndex._schema.
6.737761
7.061012
0.95422
ret = { 'keywords': list(), 'doc': list(), 'from': None, 'to': None} if not isinstance(terms, dict): stp = SearchTermParser() terms = stp.parse(terms, term_join=self.backend._and_join) if 'about' in terms: ...
def _expand_terms(self, terms)
Expands partition terms to the appropriate fields. Args: terms (dict or str): Returns: dict: keys are field names, values are query strings
3.451693
3.572967
0.966058
place_vids = [] first_type = None for result in self.backend.identifier_index.search(terms): if not first_type: first_type = result.type if result.type != first_type: # Ignore ones that aren't the same type as the best match ...
def _expand_place_ids(self, terms)
Lookups all of the place identifiers to get gvids Args: terms (str or unicode): terms to lookup Returns: str or list: given terms if no identifiers found, otherwise list of identifiers.
6.127015
5.659187
1.082667
return { 'identifier': u('{}').format(identifier['identifier']), 'type': u('{}').format(identifier['type']), 'name': u('{}').format(identifier['name']) }
def _as_document(self, identifier)
Converts given identifier to the document indexed by FTS backend. Args: identifier (dict): identifier to convert. Dict contains at least 'identifier', 'type' and 'name' keys. Returns: dict with structure matches to BaseIdentifierIndex._schema.
3.985337
3.608034
1.104573
from geoid.civick import GVid geo_grains = {} for sl, cls in GVid.sl_map.items(): if '_' not in cls.level: geo_grains[self.stem(cls.level)] = str(cls.nullval().summarize()) return geo_grains
def _geograins(self)
Create a map geographic area terms to the geo grain GVid values
16.367445
11.305414
1.447753
module = self.distribution.ext_modules[0] building_for_windows = self.plat_name in ['win32', 'win-amd64'] if building_for_windows: module.define_macros.append(('_CRT_SECURE_NO_WARNINGS', '1')) module.libraries.append('advapi32') if self.dynamic_linking: module.libraries.append(...
def run(self)
Execute the build command.
4.044821
3.755394
1.07707
'''Droping all tables and custom types (enums) using `engine`. Taken from http://www.sqlalchemy.org/trac/wiki/UsageRecipes/DropEverything This method is more robust than `metadata.drop_all(engine)`. B.c. when you change a table or a type name, `drop_all` does not consider the old one. Thus, DB hold...
def drop_everything(engine)
Droping all tables and custom types (enums) using `engine`. Taken from http://www.sqlalchemy.org/trac/wiki/UsageRecipes/DropEverything This method is more robust than `metadata.drop_all(engine)`. B.c. when you change a table or a type name, `drop_all` does not consider the old one. Thus, DB holds some ...
3.172849
1.840409
1.723991
''' Create tables according sqlalchemy data model. Is not a complex migration tool like alembic, just creates tables that does not exist:: ./manage.py sqla:create_tables [--verbose] [meta_name] ''' def _create_metadata_tables(metadata): for tabl...
def command_create_tables(self, meta_name=None, verbose=False)
Create tables according sqlalchemy data model. Is not a complex migration tool like alembic, just creates tables that does not exist:: ./manage.py sqla:create_tables [--verbose] [meta_name]
4.272938
2.5202
1.695476
''' Drops all tables without dropping a database:: ./manage.py sqla:drop_tables [meta_name] ''' answer = six.moves.input(u'All data will lost. Are you sure? [y/N] ') if answer.strip().lower()!='y': sys.exit('Interrupted') def _drop_metadata_tabl...
def command_drop_tables(self, meta_name=None)
Drops all tables without dropping a database:: ./manage.py sqla:drop_tables [meta_name]
4.139033
3.338882
1.239646
''' Prints current database schema (according sqlalchemy database model):: ./manage.py sqla:schema [name] ''' meta_name = table_name = None if name: if isinstance(self.metadata, MetaData): table_name = name elif '.' in name: ...
def command_schema(self, name=None)
Prints current database schema (according sqlalchemy database model):: ./manage.py sqla:schema [name]
3.09987
2.28681
1.355543
''' Runs generator functions. Run `docs` generator function:: ./manage.py sqla:gen docs Run `docs` generator function with `count=10`:: ./manage.py sqla:gen docs:10 ''' if not names: sys.exit('Please provide generator names') ...
def command_gen(self, *names)
Runs generator functions. Run `docs` generator function:: ./manage.py sqla:gen docs Run `docs` generator function with `count=10`:: ./manage.py sqla:gen docs:10
5.015718
2.649456
1.893112
from sockjs.cyclone.conn import ConnectionInfo return ConnectionInfo(self.request.remote_ip, self.request.cookies, self.request.arguments, self.request.headers, self.request....
def get_conn_info(self)
Return C{ConnectionInfo} object from current transport
7.951632
8.396692
0.946996
parts = statement.to_unicode().split() tables = set() for i, token in enumerate(parts): if token.lower() == 'from' or token.lower().endswith('join'): tables.add(parts[i + 1].rstrip(';')) return list(tables)
def _get_table_names(statement)
Returns table names found in the query. NOTE. This routine would use the sqlparse parse tree, but vnames don't parse very well. Args: statement (sqlparse.sql.Statement): parsed by sqlparse sql statement. Returns: list of str
4.418691
4.421645
0.999332
raise NotImplementedError
def install(self, connection, partition, table_name=None, index_columns=None, materialize=False, logger=None)
Installs partition's mpr to the database to allow to execute sql queries over mpr. Args: connection: partition (orm.Partition): materialize (boolean): if True, create generic table. If False create MED over mpr. Returns: str: name of the created table.
400.262939
366.556244
1.091955
# first install all partitions of the table queries = [] query_tmpl = 'SELECT * FROM {}' for partition in table.partitions: partition.localize() installed_name = self.install(connection, partition) queries.append(query_tmpl.format(installed_n...
def install_table(self, connection, table, logger = None)
Installs all partitons of the table and create view with union of all partitons. Args: connection: connection to database who stores mpr data. table (orm.Table):
5.205624
4.552845
1.143378
self.install_module(connection) statements = sqlparse.parse(sqlparse.format(query, strip_comments=True)) # install all partitions and replace table names in the query. # logger.debug('Finding and installing all partitions from query. \n query: {}'.format(query)) ...
def query(self, connection, query, fetch=True)
Creates virtual tables for all partitions found in the query and executes query. Args: query (str): sql query fetch (bool): fetch result from database if True, do not fetch overwise.
6.357139
6.434142
0.988032
response = utils.checked_api_call(pnc_api.build_configs, 'get_all', q='name==' + name).content if not response: return None return response[0].id
def get_build_configuration_id_by_name(name)
Returns the id of the build configuration matching name :param name: name of build configuration :return: id of the matching build configuration, or None if no match found
6.641065
6.86853
0.966883
response = utils.checked_api_call(pnc_api.build_configs, 'get_all', q='name==' + name).content if not response: return None return response[0]
def get_build_configuration_by_name(name)
Returns the build configuration matching the name :param name: name of build configuration :return: The matching build configuration, or None if no match found
6.846988
7.395272
0.92586
response = utils.checked_api_call(pnc_api.build_configs, 'get_specific', id=search_id) if not response: return False return True
def config_id_exists(search_id)
Test if a build configuration matching search_id exists :param search_id: id to test for :return: True if a build configuration with search_id exists, False otherwise
7.849773
6.165297
1.273219
data = build_raw(id, name, revision, temporary_build, timestamp_alignment, no_build_dependencies, keep_pod_on_failure, force_rebuild, rebuild_mode) if data: return utils.format_json(data)
def build(id=None, name=None, revision=None, temporary_build=False, timestamp_alignment=False, no_build_dependencies=False, keep_pod_on_failure=False, force_rebuild=False, rebuild_mode=common.REBUILD_MODES_DEFAULT)
Trigger a BuildConfiguration by name or ID
2.704019
2.992309
0.903656
data = get_build_configuration_raw(id, name) if data: return utils.format_json(data)
def get_build_configuration(id=None, name=None)
Retrieve a specific BuildConfiguration
5.164254
5.525721
0.934585
data = update_build_configuration_raw(id, **kwargs) if data: return utils.format_json(data)
def update_build_configuration(id, **kwargs)
Update an existing BuildConfiguration with new information :param id: ID of BuildConfiguration to update :param name: Name of BuildConfiguration to update :return:
5.527161
7.402977
0.746613
data = delete_build_configuration_raw(id, name) if data: return utils.format_json(data)
def delete_build_configuration(id=None, name=None)
Delete an existing BuildConfiguration :param id: :param name: :return:
5.203994
7.187694
0.724014
data = list_build_configurations_for_product_raw(id, name, page_size, page_index, sort, q) if data: return utils.format_json_list(data)
def list_build_configurations_for_product(id=None, name=None, page_size=200, page_index=0, sort="", q="")
List all BuildConfigurations associated with the given Product.
2.857274
3.072178
0.930048
data = list_build_configurations_for_project_raw(id, name, page_size, page_index, sort, q) if data: return utils.format_json_list(data)
def list_build_configurations_for_project(id=None, name=None, page_size=200, page_index=0, sort="", q="")
List all BuildConfigurations associated with the given Project.
2.839943
3.081695
0.921552
data = list_build_configurations_for_project_raw(product_id, version_id, page_size, page_index, sort, q) if data: return utils.format_json_list(data)
def list_build_configurations_for_product_version(product_id, version_id, page_size=200, page_index=0, sort="", q="")
List all BuildConfigurations associated with the given ProductVersion
3.163757
3.617385
0.874598
data = add_dependency_raw(id, name, dependency_id, dependency_name) if data: return utils.format_json_list(data)
def add_dependency(id=None, name=None, dependency_id=None, dependency_name=None)
Add an existing BuildConfiguration as a dependency to another BuildConfiguration.
4.486815
4.654839
0.963903
data = remove_dependency_raw(id, name, dependency_id, dependency_name) if data: return utils.format_json_list(data)
def remove_dependency(id=None, name=None, dependency_id=None, dependency_name=None)
Remove a BuildConfiguration from the dependency list of another BuildConfiguration
4.320901
4.304311
1.003854
data = list_product_versions_for_build_configuration_raw(id, name, page_size, page_index, sort, q) if data: return utils.format_json_list(data)
def list_product_versions_for_build_configuration(id=None, name=None, page_size=200, page_index=0, sort="", q="")
List all ProductVersions associated with a BuildConfiguration
2.741682
2.900501
0.945244
data = remove_product_version_from_build_configuration_raw(id, name, product_version_id) if data: return utils.format_json_list(data)
def add_product_version_to_build_configuration(id=None, name=None, product_version_id=None)
Associate an existing ProductVersion with a BuildConfiguration
4.51984
4.945083
0.914007
data = remove_product_version_from_build_configuration_raw(id, name, product_version_id) if data: return utils.format_json_list(data)
def remove_product_version_from_build_configuration(id=None, name=None, product_version_id=None)
Remove a ProductVersion from association with a BuildConfiguration
3.310376
3.421068
0.967644
data = list_revisions_of_build_configuration_raw(id, name, page_size, page_index, sort) if data: return utils.format_json_list(data)
def list_revisions_of_build_configuration(id=None, name=None, page_size=200, page_index=0, sort="")
List audited revisions of a BuildConfiguration
3.032727
3.243332
0.935065
data = get_revision_of_build_configuration_raw(revision_id, id, name) if data: return utils.format_json_list(data)
def get_revision_of_build_configuration(revision_id, id=None, name=None)
Get a specific audited revision of a BuildConfiguration
3.917993
3.928202
0.997401
data = list_build_configurations_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
def list_build_configurations(page_size=200, page_index=0, sort="", q="")
List all BuildConfigurations
3.416285
3.620869
0.943499
newabbr = tzabbr() newabbr.abbr = abbr newabbr.name = name newabbr.region = region newabbr.zone = zone newabbr.dst = dst if abbr not in all: all[abbr] = newabbr if not region in regions: regions[region] = {} assert abbr not in regions[region] regions[region][abbr] = newabbr
def tzabbr_register(abbr, name, region, zone, dst)
Register a new timezone abbreviation in the global registry. If another abbreviation with the same name has already been registered it new abbreviation will only be registered in region specific dictionary.
2.240777
2.352496
0.95251
License = create_license_object(**kwargs) response = utils.checked_api_call(pnc_api.licenses, 'create_new', body=License) if response: return utils.format_json(response.content)
def create_license(**kwargs)
Create a new License
7.445652
6.816576
1.092286
response = utils.checked_api_call( pnc_api.licenses, 'get_specific', id= id) if response: return utils.format_json(response.content)
def get_license(id)
Get a specific License by either ID or fullname
8.66126
7.868603
1.100737
response = utils.checked_api_call(pnc_api.licenses, 'delete', id=license_id) if response: return utils.format_json(response.content)
def delete_license(license_id)
Delete a License by ID
6.007742
6.402328
0.938368
updated_license = pnc_api.licenses.get_specific(id=license_id).content for key, value in iteritems(kwargs): if value: setattr(updated_license, key, value) response = utils.checked_api_call( pnc_api.licenses, 'update', id=int(license_id), body=update...
def update_license(license_id, **kwargs)
Replace the License with given ID with a new License
3.328225
3.398343
0.979367
response = utils.checked_api_call(pnc_api.licenses, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q) if response: return utils.format_json_list(response.content)
def list_licenses(page_size=200, page_index=0, sort="", q="")
List all Licenses
3.584061
3.673395
0.975681
''' Apply transformations to the image. New transformations can be defined as methods:: def do__transformationname(self, img, transformation, params): 'returns new image with transformation applied' ... def new_size__transformationname(s...
def transform(self, img, transformation, params)
Apply transformations to the image. New transformations can be defined as methods:: def do__transformationname(self, img, transformation, params): 'returns new image with transformation applied' ... def new_size__transformationname(self, size, target_si...
11.211387
4.037916
2.776528
'''Choose a resizer depending an image size''' sw, sh = size if sw >= sh * self.rate: return self.hor_resize else: return self.vert_resize
def get_resizer(self, size, target_size)
Choose a resizer depending an image size
9.871841
6.763692
1.459534
if song in self._songs: return self._songs.append(song) logger.debug('Add %s to player playlist', song)
def add(self, song)
往播放列表末尾添加一首歌曲
5.456991
5.074498
1.075376
if song in self._songs: return if self._current_song is None: self._songs.append(song) else: index = self._songs.index(self._current_song) self._songs.insert(index + 1, song)
def insert(self, song)
在当前歌曲后插入一首歌曲
2.40336
2.153122
1.116221
if song in self._songs: if self._current_song is None: self._songs.remove(song) elif song == self._current_song: next_song = self.next_song # 随机模式下或者歌单只剩一首歌曲,下一首可能和当前歌曲相同 if next_song == self.current_song: ...
def remove(self, song)
Remove song from playlist. O(n) If song is current song, remove the song and play next. Otherwise, just remove it.
3.075699
3.014252
1.020385
self._last_song = self.current_song if song is None: self._current_song = None # add it to playlist if song not in playlist elif song in self._songs: self._current_song = song else: self.insert(song) self._current_song = so...
def current_song(self, song)
设置当前歌曲,将歌曲加入到播放列表,并发出 song_changed 信号 .. note:: 该方法理论上只应该被 Player 对象调用。
3.587393
3.559035
1.007968
if not self._songs or len(self._songs) <= len(self._bad_songs): logger.debug('No good song in playlist.') return None good_songs = [] if direction > 0: song_list = self._songs[base:] + self._songs[0:base] else: song_list = self._s...
def _get_good_song(self, base=0, random_=False, direction=1)
从播放列表中获取一首可以播放的歌曲 :param base: base index :param random: random strategy or not :param direction: forward if > 0 else backword >>> pl = Playlist([1, 2, 3]) >>> pl._get_good_song() 1 >>> pl._get_good_song(base=1) 2 >>> pl._bad_songs = [2] ...
2.303844
2.391415
0.963381
# 如果没有正在播放的歌曲,找列表里面第一首能播放的 if self.current_song is None: return self._get_good_song() if self.playback_mode == PlaybackMode.random: next_song = self._get_good_song(random_=True) else: current_index = self._songs.index(self.current_song) ...
def next_song(self)
next song for player, calculated based on playback_mode
2.836242
2.686564
1.055713
if self.current_song is None: return self._get_good_song(base=-1, direction=-1) if self.playback_mode == PlaybackMode.random: previous_song = self._get_good_song(direction=-1) else: current_index = self._songs.index(self.current_song) pre...
def previous_song(self)
previous song for player to play NOTE: not the last played song
3.189915
3.176675
1.004168
self._state = value self.state_changed.emit(value)
def state(self, value)
set player state, emit state changed signal outer object should not set state directly, use ``pause`` / ``resume`` / ``stop`` / ``play`` method instead.
4.529884
3.58913
1.262112
if song is not None and song == self.current_song: logger.warning('The song is already under playing.') else: self._playlist.current_song = song
def play_song(self, song)
播放指定歌曲 如果目标歌曲与当前歌曲不相同,则修改播放列表当前歌曲, 播放列表会发出 song_changed 信号,player 监听到信号后调用 play 方法, 到那时才会真正的播放新的歌曲。如果和当前播放歌曲相同,则忽略。 .. note:: 调用方不应该直接调用 playlist.current_song = song 来切换歌曲
6.649409
6.189969
1.074223
logger.debug('Player received song changed signal') if song is not None: logger.info('Try to play song: %s' % song) if song.url: self.play(song.url) else: self._playlist.mark_as_bad(song) self.play_next() ...
def _on_song_changed(self, song)
播放列表 current_song 发生变化后的回调 判断变化后的歌曲是否有效的,有效则播放,否则将它标记为无效歌曲。 如果变化后的歌曲是 None,则停止播放。
5.145318
4.608255
1.116544
# download the pom pom_path = download_pom(repo_url, artifact) if pom_path: pom_dir = os.path.split(pom_path)[0] # get effective pom eff_pom = get_effective_pom(pom_dir, repo_url, mvn_repo_local) shutil.rmtree(pom_dir, True) if not eff_pom: return N...
def _read_managed_gavs(artifact, repo_url=None, mgmt_type=MGMT_TYPE.DEPENDENCIES, mvn_repo_local=None)
Reads all artifacts managed in dependencyManagement section of effective pom of the given artifact. It places the repo_url in settings.xml and then runs help:effective-pom with these settings. There should be the POM with its parent and dependencies available in the repository and there should also be all plugi...
3.534969
2.850392
1.24017
global effective_pom_cache pom_file = None try: pom_file = open(os.path.join(pom_dir, "pom.xml")) pom = pom_file.read() finally: if pom_file: pom_file.close() artifact = MavenArtifact(pom=pom) gav = artifact.get_gav() eff_pom = None if repo_url ...
def get_effective_pom(pom_dir, repo_url, mvn_repo_local, profiles=None, additional_params=None)
Gets the effective pom from the downloaded pom. There has to be complete source tree (at least the pom tree) in case that the root pom contains some modules. :param pom_dir: directory where the pom is prepared (including potential patches) :param repo_url: repository URL, where all dependencies needed to r...
1.793618
1.877613
0.955265
work_dir = os.getcwd() os.chdir(pom_dir) try: if repo_url: settings_filename = create_mirror_settings(repo_url) else: settings_filename = None args = ["mvn", "clean"] if mvn_repo_local: args.extend(["-s", settings_filename]) ...
def alter_poms(pom_dir, additional_params, repo_url=None, mvn_repo_local=None)
Runs mvn clean command with provided additional parameters to perform pom updates by pom-manipulation-ext.
2.377917
2.344777
1.014134
pom_file = None try: pom_file = open("pom.xml") pom = pom_file.read() finally: if pom_file: pom_file.close() artifact = MavenArtifact(pom=pom) if artifact.modules: return True else: return False
def pom_contains_modules()
Reads pom.xml in current working directory and checks, if there is non-empty modules tag.
2.797201
2.703937
1.034492
result = urlparse.urljoin(nexus_base_url, "content/groups/") result = urlparse.urljoin(result, "%s%s%s/" % (prefix, mead_tag, suffix)) return result
def get_repo_url(mead_tag, nexus_base_url, prefix="hudson-", suffix="")
Creates repository Nexus group URL composed of: <nexus_base_url>/content/groups/<prefix><mead_tag><suffix> :param mead_tag: name of the MEAD tag used to create the proxy URL in settings.xml :param nexus_base_url: the base URL of a Nexus instance :param prefix: Nexus group name prefix, default is "h...
2.660693
2.790414
0.953512
if not pom_url: pom_url = urlparse.urljoin(repo_url, "%s/" % string.replace(artifact.groupId, ".", "/")) pom_url = urlparse.urljoin(pom_url, "%s/" % artifact.artifactId) pom_url = urlparse.urljoin(pom_url, "%s/" % artifact.version) pom_url = urlparse.urljoin(pom_url, "%s-%s.pom"...
def download_pom(repo_url=None, artifact=None, pom_url=None, target_dir=None)
Downloads a pom file with give GAV (as array) or from given pom_url and saves it as pom.xml into target_dir. :param repo_url: repository URL from which the pom should be downloaded, mandatory only if no pom_url provided :param artifact: MavenArtifact instance, mandatory only if no pom_url provided :param p...
2.002666
2.007888
0.997399
cwd = os.getcwd() settings_path = os.path.join(cwd, "settings.xml") settings_file = None try: settings_file = open(settings_path, "w") settings_file.write('<?xml version="1.0" encoding="UTF-8"?>\n') settings_file.write('<settings xmlns="http://maven.apache.org/SETTINGS/1.0....
def create_mirror_settings(repo_url)
Creates settings.xml in current working directory, which when used makes Maven use given repo URL as a mirror of all repositories to look at. :param repo_url: the repository URL to use :returns: filepath to the created file
1.41751
1.39633
1.015168
action = uri + '/search/get' data = { 's': s, 'type': stype, 'offset': offset, 'total': total, 'limit': 60 } resp = self.request('POST', action, data) if resp['code'] == 200: return resp['result']['s...
def search(self, s, stype=1, offset=0, total='true', limit=60)
get songs list from search keywords
2.994397
2.675784
1.119073
action = uri + '/artist/' + str(artist_id) data = self.request('GET', action) return data
def artist_infos(self, artist_id)
:param artist_id: artist_id :return: { code: int, artist: {artist}, more: boolean, hotSongs: [songs] }
6.129772
5.363574
1.142852
action = uri + '/album/' + str(album_id) data = self.request('GET', action) if data['code'] == 200: return data['album']
def album_infos(self, album_id)
:param album_id: :return: { code: int, album: { album } }
4.173126
3.394324
1.229442
url_add = uri + '/playlist/manipulate/tracks' trackIds = '["' + str(mid) + '"]' data_add = { 'tracks': str(mid), # music id 'pid': str(pid), # playlist id 'trackIds': trackIds, # music id str 'op': op # opation } dat...
def op_music_to_playlist(self, mid, pid, op)
:param op: add or del
4.600539
4.475926
1.027841
url = uri + '/mv/detail?id=' + str(mvid) return self.request('GET', url)
def get_mv_detail(self, mvid)
Get mv detail :param mvid: mv id :return:
5.55384
5.99087
0.927051
# tv 表示翻译。-1:表示要翻译,1:不要 url = uri + '/song/lyric?' + 'id=' + str(mid) + '&lv=1&kv=1&tv=-1' return self.request('GET', url)
def get_lyric_by_songid(self, mid)
Get song lyric :param mid: music id :return: { lrc: { version: int, lyric: str }, tlyric: { version: int, lyric: str } sgc: bool, qfy: bool, sfy: bool, ...
8.755244
8.709151
1.005292