code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
index_dir = os.path.join(root_dir, index_name) try: if not os.path.exists(index_dir): os.makedirs(index_dir) return create_in(index_dir, schema), index_dir else: return open_dir(index_dir), index_dir except Exception as e: logger.error("Init ...
def _init_index(root_dir, schema, index_name)
Creates new index or opens existing. Args: root_dir (str): root dir where to find or create index. schema (whoosh.fields.Schema): schema of the index to create or open. index_name (str): name of the index. Returns: tuple ((whoosh.index.FileIndex, str)): first element is index, ...
2.52933
2.566363
0.98557
if os.path.exists(self.index_dir): rmtree(self.index_dir) self.index = None
def reset(self)
Resets index by removing index directory.
4.774557
2.816438
1.695246
datasets = [] for dataset in self.index.searcher().documents(): res = DatasetSearchResult() res.vid = dataset['vid'] res.b_score = 1 datasets.append(res) return datasets
def all(self)
Returns list with all indexed datasets.
8.631023
6.572473
1.313208
query_string = self._make_query_from_terms(search_phrase) self._parsed_query = query_string schema = self._get_generic_schema() parser = QueryParser('doc', schema=schema) query = parser.parse(query_string) datasets = defaultdict(DatasetSearchResult) #...
def search(self, search_phrase, limit=None)
Finds datasets by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to return. None means without limit. Returns: list of DatasetSearchResult instances.
4.325168
4.292297
1.007658
expanded_terms = self._expand_terms(terms) cterms = '' if expanded_terms['doc']: cterms = self.backend._and_join(expanded_terms['doc']) if expanded_terms['keywords']: if cterms: cterms = self.backend._and_join( cter...
def _make_query_from_terms(self, terms)
Creates a query for dataset from decomposed search terms. Args: terms (dict or unicode or string): Returns: tuple: First element is str with FTS query, second is parameters of the query.
3.915278
3.742343
1.04621
schema = Schema( vid=ID(stored=True, unique=True), # Object id title=NGRAMWORDS(), keywords=KEYWORD, # Lists of coverage identifiers, ISO time values and GVIDs, source names, source abbrev doc=TEXT) # Generated document for the core of the topic search...
def _get_generic_schema(self)
Returns whoosh's generic schema of the dataset.
39.812634
29.650993
1.342708
assert vid is not None, 'vid argument can not be None.' writer = self.index.writer() writer.delete_by_term('vid', vid) writer.commit()
def _delete(self, vid=None)
Deletes given dataset from index. Args: vid (str): dataset vid.
4.76758
4.034636
1.181663
with self.index.searcher() as searcher: result = searcher.search(Term('vid', dataset.vid)) return bool(result)
def is_indexed(self, dataset)
Returns True if dataset is already indexed. Otherwise returns False.
5.179154
4.770299
1.085708
self._parsed_query = search_phrase schema = self._get_generic_schema() parser = QueryParser('name', schema=schema) query = parser.parse(search_phrase) class PosSizeWeighting(scoring.WeightingModel): def scorer(self, searcher, fieldname, text, qf=1): ...
def search(self, search_phrase, limit=None)
Finds identifier by search phrase.
3.705555
3.677245
1.007699
writer = self.index.writer() all_names = set([x['name'] for x in self.index.searcher().documents()]) if identifier['name'] not in all_names: writer.add_document(**identifier) writer.commit()
def _index_document(self, identifier, force=False)
Adds identifier document to the index.
3.900417
3.500575
1.114222
schema = Schema( identifier=ID(stored=True), # Partition versioned id type=ID(stored=True), name=NGRAM(phrase=True, stored=True, minsize=2, maxsize=8)) return schema
def _get_generic_schema(self)
Returns whoosh's generic schema.
11.086365
6.37551
1.738898
assert identifier is not None, 'identifier argument can not be None.' writer = self.index.writer() writer.delete_by_term('identifier', identifier) writer.commit()
def _delete(self, identifier=None)
Deletes given identifier from index. Args: identifier (str): identifier of the document to delete.
4.689446
4.255545
1.101961
with self.index.searcher() as searcher: result = searcher.search(Term('identifier', identifier['identifier'])) return bool(result)
def is_indexed(self, identifier)
Returns True if identifier is already indexed. Otherwise returns False.
4.543922
4.251641
1.068746
partitions = [] for partition in self.index.searcher().documents(): partitions.append( PartitionSearchResult(dataset_vid=partition['dataset_vid'], vid=partition['vid'], score=1)) return partitions
def all(self)
Returns list with all indexed partitions.
10.673352
8.211451
1.299813
query_string = self._make_query_from_terms(search_phrase) self._parsed_query = query_string schema = self._get_generic_schema() parser = QueryParser('doc', schema=schema) query = parser.parse(query_string) logger.debug('Searching partitions using `{}` query.'.fo...
def search(self, search_phrase, limit=None)
Finds partitions by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to generate. None means without limit. Yields: PartitionSearchResult instances.
4.37253
3.878562
1.127358
expanded_terms = self._expand_terms(terms) cterms = '' if expanded_terms['doc']: cterms = self.backend._or_join(expanded_terms['doc']) keywords = expanded_terms['keywords'] frm_to = self._from_to_as_term(expanded_terms['from'], expanded_terms['to']) ...
def _make_query_from_terms(self, terms)
returns a FTS query for partition created from decomposed search terms. args: terms (dict or str): returns: str containing fts query.
4.056048
3.670252
1.105114
# The wackiness with the conversion to int and str, and adding ' ', is because there # can't be a space between the 'TO' and the brackets in the time range # when one end is open from_year = '' to_year = '' def year_or_empty(prefix, year, suffix): t...
def _from_to_as_term(self, frm, to)
Turns from and to into the query format. Args: frm (str): from year to (str): to year Returns: FTS query str with years range.
5.380726
5.098816
1.055289
if force: self._delete(vid=document['vid']) writer = self.index.writer() writer.add_document(**document) writer.commit()
def _index_document(self, document, force=False)
Adds parition document to the index.
5.473767
4.623498
1.183902
#l.debug("Copying %d bytes of memory with id %s." % (len(self.mem), self.id)) c = SimSymbolicDbgMemory( mem=self.mem.branch(), memory_id=self.id, endness=self.endness, abstract_backer=self._abstract_backer, read_strategies=[ s.copy() f...
def copy(self, _)
Return a copy of the SimMemory.
4.515317
3.985415
1.13296
from ambry.orm.exc import NotFoundError if not hasattr(self, 'partition'): return None if not self.name: return None try: try: return self.partition.column(self.name) except AttributeError: return...
def column(self)
Return the ambry column
3.598909
3.076852
1.169672
builder = SyslogHandlerBuilder( progname, address=address, proto=proto, facility=facility, fmt=fmt, datefmt=datefmt) return builder.get_handler()
def get_handler(progname, address=None, proto=None, facility=None, fmt=None, datefmt=None, **_)
Helper function to create a Syslog handler. See `ulogger.syslog.SyslogHandlerBuilder` for arguments and supported keyword arguments. Returns: (obj): Instance of `logging.SysLogHandler`
3.003315
3.118247
0.963142
allowed_values = ["MAVEN", "NPM", "COCOA_POD", "GENERIC_PROXY"] if repository_type not in allowed_values: raise ValueError( "Invalid value for `repository_type` ({0}), must be one of {1}" .format(repository_type, allowed_values) ) ...
def repository_type(self, repository_type)
Sets the repository_type of this TargetRepositoryRest. :param repository_type: The repository_type of this TargetRepositoryRest. :type: str
2.491299
2.500886
0.996167
from ambry.library import new_library from ambry.run import get_runconfig import traceback assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) put = outqueue.put get = inqueue.get if hasattr(inqueue, '_writer'): inqueue._writer.close() outqueue._reader...
def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None)
Custom worker for bundle operations :param inqueue: :param outqueue: :param initializer: :param initargs: :param maxtasks: :return:
6.274269
6.354947
0.987305
import os import signal # Have the child processes ignore the keyboard interrupt, and other signals. Instead, the parent will # catch these, and clean up the children. signal.signal(signal.SIGINT, signal.SIG_IGN) #signal.signal(signal.SIGTERM, sigterm_handler) os.environ['AMBRY_DB'] ...
def init_library(database_dsn, accounts_password, limited_run = False)
Child initializer, setup in Library.process_pool
3.996188
3.85935
1.035456
source = b.source(source_name) with b.progress.start('build_mp',stage,message="MP build", source=source) as ps: ps.add(message='Running source {}'.format(source.name), source=source, state='running') r = b.build_source(stage, source, ps, force) return r
def build_mp(b, stage, source_name, force)
Ingest a source, using only arguments that can be pickled, for multiprocessing access
10.277049
8.887166
1.156392
with b.progress.start('coalesce_mp',0,message="MP coalesce {}".format(partition_name)) as ps: r = b.unify_partition(partition_name, None, ps) return r
def unify_mp(b, partition_name)
Unify all of the segment partitions for a parent partition, then run stats on the MPR file
14.681382
16.717237
0.878218
source = b.source(source_name) with b.progress.start('ingest_mp',0,message="MP ingestion", source=source) as ps: r = b._ingest_source(source, ps, clean_files) return r
def ingest_mp(b, stage, source_name, clean_files)
Ingest a source, using only arguments that can be pickled, for multiprocessing access
11.319262
10.421226
1.086174
for i in range(self._processes - len(self._pool)): w = self.Process(target=self._worker_f, args=(self._inqueue, self._outqueue, self._initializer, self._initargs, self._maxtasksperchild)) ...
def _repopulate_pool(self)
Bring the number of pool processes up to the specified number, for use after reaping workers which have exited.
3.679724
3.15434
1.166559
from os.path import normpath from ambry.dbexceptions import ConfigurationError root = p = self._config.filesystem[name].format(root=self._root) if args: args = [e.strip() for e in args] p = join(p, *args) if not isdir(p) and mkdir: ...
def _compose(self, name, args, mkdir=True)
Get a named filesystem entry, and extend it into a path with additional path arguments
5.851188
5.322948
1.099238
return self._compose(name, args, mkdir=False)
def compose(self, name, *args)
Compose, but don't create base directory
20.49934
13.134715
1.560699
if not self._config.library.database: return 'sqlite:///{root}/library.db'.format(root=self._root) return self._config.library.database.format(root=self._root)
def database_dsn(self)
Substitute the root dir into the database DSN, for Sqlite
4.787047
4.014712
1.192376
header_parts = {} for i, h in enumerate(headers): header_parts[h] = 'row[{}]'.format(i) body_code = 'lambda row: [{}]'.format(','.join(header_parts.get(c.name, 'None') for c in table.columns)) header_code = 'lambda row: [{}]'.format( ','.join(header_parts.get(c.name, "'{}'".format...
def make_table_map(table, headers)
Create a function to map from rows with the structure of the headers to the structure of the table.
2.859676
2.666104
1.072605
for k, v in iteritems(pl): if v and len(v) > 0: if head_pipe and k != 'source': # Can't put anything before the source. v.insert(0, head_pipe) if tail_pipe: v.append(tail_pipe)
def augment_pipeline(pl, head_pipe=None, tail_pipe=None)
Augment the pipeline by adding a new pipe section to each stage that has one or more pipes. Can be used for debugging :param pl: :param DebugPipe: :return:
4.15092
4.459822
0.930737
# TODO: Always use unicode within ambry. from six import text_type, binary_type if isinstance(s, text_type): ascii_ = s.encode('ascii', 'ignore') elif isinstance(s, binary_type): ascii_ = s.decode('utf-8').encode('ascii', 'ignore') else: raise Exception('Unknown text typ...
def _to_ascii(s)
Converts given string to ascii ignoring non ascii. Args: s (text or binary): Returns: str:
3.776687
3.66819
1.029578
from time import time # rows, rate = pl.sink.report_progress() return (self.i, round(float(self.i) / float(time() - self._start_time), 2))
def report_progress(self)
This function can be called from a higher level to report progress. It is usually called from an alarm signal handler which is installed just before starting an operation: :return: Tuple: (process description, #records, #total records, #rate)
13.14411
12.65547
1.038611
parts = v.split(',') slices = [] for part in parts: p = part.split(':') if len(p) == 1: slices.append(int(p[0])) elif len(p) == 2: slices.append(tuple(p)) else: raise ValueError("Too many...
def parse(v)
Parse a slice string, of the same form as used by __getitem__ >>> Slice.parse("2:3,7,10:12") :param v: Input string :return: A list of tuples, one for each element of the slice string
2.927267
2.608466
1.122218
return [c.name for c in self.source.dest_table.columns][1:]
def process_header(self, headers)
Ignore the incomming header and replace it with the destination header
18.994143
15.127299
1.25562
from ambry.orm import Column if not n: return 'column{}'.format(i) mn = Column.mangle_name(str(n).strip()) return mn
def mangle_column_name(self, i, n)
Override this method to change the way that column names from the source are altered to become column names in the schema. This method is called from :py:meth:`mangle_header` for each column in the header, and :py:meth:`mangle_header` is called from the RowGenerator, so it will alter the row both when t...
7.304486
9.130453
0.800014
from itertools import chain def maybe_int(v): try: return int(v) except ValueError: return None if not self.initialized: self.data_start_line = 1 self.data_end_line = None self.header_lines = ...
def init(self)
Deferred initialization b/c the object con be constructed without a valid source
2.114565
2.101874
1.006038
end = self._end_time if self._end_time else time.time() return self._count / (end - self._start_time)
def rate(self)
Report the insertion rate in records per second
5.917785
4.726204
1.252122
pl = Pipeline(bundle=self.bundle) for group_name, pl_segment in iteritems(self): if group_name not in subset: continue pl[group_name] = pl_segment return pl
def _subset(self, subset)
Return a new pipeline with a subset of the sections
6.828404
5.240204
1.30308
# Create a context for evaluating the code for each pipeline. This removes the need # to qualify the class names with the module import ambry.etl import sys # ambry.build comes from ambry.bundle.files.PythonSourceFile#import_bundle eval_locals = dict(list(locals...
def configure(self, pipe_config)
Configure from a dict
4.809218
4.766098
1.009047
for segment_name, pipes in iteritems(self): if target_segment_name and segment_name != target_segment_name: raise Exception() repl_pipes = [] found = False for pipe in pipes: if isinstance(pipe, repl_class): ...
def replace(self, repl_class, replacement, target_segment_name=None)
Replace a pipe segment, specified by its class, with another segment
3.137206
3.147362
0.996773
partition.localize() self._add_partition(connection, partition) fdw_table = partition.vid view_table = '{}_v'.format(fdw_table) if materialize: with connection.cursor() as cursor: view_exists = self._relation_exists(connection, view_table) ...
def install(self, connection, partition, table_name=None, columns=None, materialize=False, logger=None)
Creates FDW or materialize view for given partition. Args: connection: connection to postgresql partition (orm.Partition): materialize (boolean): if True, create read-only table. If False create virtual table. Returns: str: name of the created table.
2.958599
2.79593
1.05818
query_tmpl = 'CREATE INDEX ON {table_name} ({column});' table_name = '{}_v'.format(partition.vid) for column in columns: query = query_tmpl.format(table_name=table_name, column=column) logger.debug('Creating postgres index.\n column: {}, query: {}'.format(colu...
def index(self, connection, partition, columns)
Create an index on the columns. Args: connection: partition (orm.Partition): columns (list of str):
3.916403
3.811334
1.027567
if getattr(self, '_connection', None): logger.debug('Closing postgresql connection.') self._connection.close() self._connection = None if getattr(self, '_engine', None): self._engine.dispose()
def close(self)
Closes connection to database.
3.299722
2.936924
1.12353
# TODO: This is the first candidate for optimization. Add field to partition # with table name and update it while table creation. # Optimized version. # # return partition.mpr_table or raise exception # Not optimized version. # # first check eit...
def _get_mpr_table(self, connection, partition)
Returns name of the postgres table who stores mpr data. Args: connection: connection to postgres db who stores mpr data. partition (orm.Partition): Returns: str: Raises: MissingTableError: if partition table not found in the db.
4.461438
4.13389
1.079235
logger.debug('Creating foreign table for partition.\n partition: {}'.format(partition.name)) with connection.cursor() as cursor: postgres_med.add_partition(cursor, partition.datafile, partition.vid)
def _add_partition(self, connection, partition)
Creates FDW for the partition. Args: connection: partition (orm.Partition):
12.344311
12.458832
0.990808
if not getattr(self, '_connection', None): logger.debug( 'Creating new connection.\n dsn: {}' .format(self._dsn)) d = parse_url_to_dict(self._dsn) self._connection = psycopg2.connect( database=d['path'].strip('/'), u...
def _get_connection(self)
Returns connection to the postgres database. Returns: connection to postgres database who stores mpr data.
4.602559
4.716836
0.975773
# execute query with connection.cursor() as cursor: cursor.execute(query) if fetch: return cursor.fetchall() else: cursor.execute('COMMIT;')
def _execute(self, connection, query, fetch=True)
Executes given query and returns result. Args: connection: connection to postgres database who stores mpr data. query (str): sql query fetch (boolean, optional): if True, fetch query result and return it. If False, do not fetch. Returns: iterable with qu...
2.729039
3.729433
0.731757
schema_name, table_name = relation.split('.') exists_query = ''' SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = %s AND c.relname = %s AND (c.relkin...
def _relation_exists(cls, connection, relation)
Returns True if relation exists in the postgres db. Otherwise returns False. Args: connection: connection to postgres database who stores mpr data. relation (str): name of the table, view or materialized view. Note: relation means table, view or materialized view he...
2.045526
2.184446
0.936405
u = ("https://api.worldbank.org/v2/countries/{}/indicators/CPTOTSAXN" "?format=json&per_page=10000").format(country) r = requests.get(u) j = r.json() cpi_data = j[1] # Loop through the rows of the datapackage with the help of data for row in cpi_dat...
def load(self, country="all")
Load data
5.143374
5.208758
0.987447
if not country: country = self.country if country == "all": raise ValueError("You need to specify a country") if not isinstance(date, str) and not isinstance(date, int): date = date.year cpi = self.data.get(country.upper(), {}).get(str(date))...
def get(self, date=datetime.date.today(), country=None)
Get the CPI value for a specific time. Defaults to today. This uses the closest method internally but sets limit to one day.
3.458585
3.282341
1.053695
''' String-based reverse API. Returns subreverse object:: env.root.build_subreverse('user', user_id=1).profile ''' _, subreverse = self._build_url_silent(_name, **kwargs) return subreverse
def build_subreverse(self, _name, **kwargs)
String-based reverse API. Returns subreverse object:: env.root.build_subreverse('user', user_id=1).profile
16.331284
3.894781
4.19312
''' String-based reverse API. Returns URL object:: env.root.build_url('user.profile', user_id=1) Checks that all necessary arguments are provided and all provided arguments are used. ''' used_args, subreverse = self._build_url_silent(_name, **kwargs) ...
def build_url(self, _name, **kwargs)
String-based reverse API. Returns URL object:: env.root.build_url('user.profile', user_id=1) Checks that all necessary arguments are provided and all provided arguments are used.
9.545337
3.90111
2.446826
''' Reverse object converted to `web.URL`. If Reverse is bound to env: * try to build relative URL, * use current domain name, port and scheme as default ''' if '' in self._scope: return self._finalize().as_url if not self._is_endpoin...
def as_url(self)
Reverse object converted to `web.URL`. If Reverse is bound to env: * try to build relative URL, * use current domain name, port and scheme as default
6.340126
4.613477
1.374262
''' Get a copy of the reverse, bound to `env` object. Can be found in env.root attribute:: # done in iktomi.web.app.Application env.root = Reverse.from_handler(app).bind_to_env(env) ''' return self.__class__(self._scope, self._location, ...
def bind_to_env(self, bound_env)
Get a copy of the reverse, bound to `env` object. Can be found in env.root attribute:: # done in iktomi.web.app.Application env.root = Reverse.from_handler(app).bind_to_env(env)
7.756771
2.700884
2.871938
'''Parse string and get URL instance''' # url must be idna-encoded and url-quotted if six.PY2: if isinstance(url, six.text_type): url = url.encode('utf-8') parsed = urlparse(url) netloc = parsed.netloc.decode('utf-8') # XXX HACK else:#...
def from_url(cls, url, show_host=True)
Parse string and get URL instance
3.479638
3.272298
1.063362
'''Set values in QuerySet MultiDict''' if args and kwargs: raise TypeError('Use positional args or keyword args not both') query = self.query.copy() if args: mdict = MultiDict(args[0]) for k in mdict.keys(): if k in query: ...
def qs_set(self, *args, **kwargs)
Set values in QuerySet MultiDict
2.922071
2.544094
1.14857
'''Add value to QuerySet MultiDict''' query = self.query.copy() if args: mdict = MultiDict(args[0]) for k, v in mdict.items(): query.add(k, v) for k, v in kwargs.items(): query.add(k, v) return self._copy(query=query)
def qs_add(self, *args, **kwargs)
Add value to QuerySet MultiDict
3.08268
2.487651
1.239193
'''Delete value from QuerySet MultiDict''' query = self.query.copy() for key in set(keys): try: del query[key] except KeyError: pass return self._copy(query=query)
def qs_delete(self, *keys)
Delete value from QuerySet MultiDict
4.906362
3.49815
1.402559
'''Get a value from QuerySet MultiDict''' return self.query.get(key, default=default)
def qs_get(self, key, default=None)
Get a value from QuerySet MultiDict
9.680854
5.454251
1.774919
''' Gets human-readable representation of the url (as unicode string, IRI according RFC3987) ''' query = (u'?' + u'&'.join(u'{}={}'.format(urlquote(k), urlquote(v)) for k, v in six.iteritems(self.query)) if self.query else '') ...
def get_readable(self)
Gets human-readable representation of the url (as unicode string, IRI according RFC3987)
3.736402
2.531863
1.475752
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.cancel_with_http_info(id, **kwargs) else: (data) = self.cancel_with_http_info(id, **kwargs) return data
def cancel(self, id, **kwargs)
Cancel running build. 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.531983
1.698194
0.902125
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_ssh_credentials_with_http_info(id, **kwargs) else: (data) = self.get_ssh_credentials_with_http_info(id, **kwargs) return data
def get_ssh_credentials(self, id, **kwargs)
Gets ssh credentials for a build This GET request is for authenticated users only. The path for the endpoint is not restful to be able to authenticate this GET request only. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` ...
1.433793
1.567883
0.914477
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_builds_in_distributed_recordset_of_product_release_with_http_info(id, **kwargs) else: (data) = self.get_all_builds_in_distributed_recordset_of_product_release_with_http_info(id...
def get_all_builds_in_distributed_recordset_of_product_release(self, id, **kwargs)
Gets all BuildRecords distributed for Product Version 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.308666
1.466353
0.892463
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_by_product_version_id_with_http_info(version_id, **kwargs) else: (data) = self.get_all_by_product_version_id_with_http_info(version_id, **kwargs) return data
def get_all_by_product_version_id(self, version_id, **kwargs)
Gets all Product Releases of the Specified Product Version 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.338667
1.539212
0.869709
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_support_level_with_http_info(**kwargs) else: (data) = self.get_all_support_level_with_http_info(**kwargs) return data
def get_all_support_level(self, **kwargs)
Gets all Product Releases Support Level 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(respo...
1.480947
1.662307
0.890898
'''Declarative metaclass automatically adding (merging) __table_args__ to mapped classes. Example: Meta = TableArgsMeta({ 'mysql_engine': 'InnoDB', 'mysql_default charset': 'utf8', } Base = declarative_base(name='Base', metaclass=Meta) class MyClass(Bas...
def TableArgsMeta(table_args)
Declarative metaclass automatically adding (merging) __table_args__ to mapped classes. Example: Meta = TableArgsMeta({ 'mysql_engine': 'InnoDB', 'mysql_default charset': 'utf8', } Base = declarative_base(name='Base', metaclass=Meta) class MyClass(Base): ...
3.855517
2.642121
1.459251
"my cell magic" from IPython import get_ipython parts = line.split() w_var_name = parts.pop(0) w = get_ipython().ev(w_var_name) w.query(cell).close()
def warehouse_query(line, cell)
my cell magic
7.4331
5.608084
1.325426
data = list_product_releases_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
def list_product_releases(page_size=200, page_index=0, sort="", q="")
List all ProductReleases
3.3915
3.564342
0.951508
data = update_release_raw(id, **kwargs) if data: return utils.format_json(data)
def update_release(id, **kwargs)
Update an existing ProductRelease with new information
5.307832
6.107386
0.869084
for provider in self._providers: if provider.identifier == identifier: return provider return None
def get(self, identifier)
get provider by id
4.695487
3.245687
1.446685
for provider in self._providers: if source_in is not None: if provider.identifier not in source_in: continue try: result = provider.search(keyword=keyword) except Exception as e: logger.exception(st...
def search(self, keyword, source_in=None, **kwargs)
search song/artist/album by keyword TODO: search album or artist
2.989057
3.158007
0.946501
def get_score(standby): score = 1 # 分数占比关系: # title + album > artist # artist > title > album if song.artists_name != standby.artists_name: score -= 0.4 if song.title != standby.title: score -= 0.3 ...
def list_song_standby(self, song, onlyone=True)
try to list all valid standby Search a song in all providers. The typical usage scenario is when a song is not available in one provider, we can try to acquire it from other providers. Standby choosing strategy: search from all providers, select two song from each provide. Thos...
3.194576
3.059472
1.044159
components = name.split('.') clazz = components.pop() mod = __import__('.'.join(components)) components += [clazz] for comp in components[1:]: mod = getattr(mod, comp) return mod
def import_class_by_string(name)
Return a class by importing its module from a fully qualified string.
2.84745
2.967788
0.959452
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_for_build_configuration_with_http_info(configuration_id, **kwargs) else: (data) = self.get_all_for_build_configuration_with_http_info(configuration_id, **kwargs) re...
def get_all_for_build_configuration(self, configuration_id, **kwargs)
Gets the Build Records linked to a specific Build 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.376525
1.573183
0.874994
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_for_project_with_http_info(name, **kwargs) else: (data) = self.get_all_for_project_with_http_info(name, **kwargs) return data
def get_all_for_project(self, name, **kwargs)
Gets the Build Records produced from the BuildConfiguration by name. 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.432177
1.619393
0.884391
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_for_project_0_with_http_info(project_id, **kwargs) else: (data) = self.get_all_for_project_0_with_http_info(project_id, **kwargs) return data
def get_all_for_project_0(self, project_id, **kwargs)
Gets the Build Records linked to a specific Project 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.354926
1.564405
0.866097
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_attributes_with_http_info(id, **kwargs) else: (data) = self.get_attributes_with_http_info(id, **kwargs) return data
def get_attributes(self, id, **kwargs)
Get Build Record attributes. 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.50388
1.645357
0.914014
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_build_configuration_audited_with_http_info(id, **kwargs) else: (data) = self.get_build_configuration_audited_with_http_info(id, **kwargs) return data
def get_build_configuration_audited(self, id, **kwargs)
Gets the audited build configuration for specific build record 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.438875
1.569437
0.916809
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_built_artifacts_with_http_info(id, **kwargs) else: (data) = self.get_built_artifacts_with_http_info(id, **kwargs) return data
def get_built_artifacts(self, id, **kwargs)
Gets artifacts built for specific Build Record 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): >>> pprin...
1.457654
1.669338
0.873193
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_completed_or_runnning_with_http_info(id, **kwargs) else: (data) = self.get_completed_or_runnning_with_http_info(id, **kwargs) return data
def get_completed_or_runnning(self, id, **kwargs)
Deprecated, use /builds/{id} 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.408572
1.508967
0.933468
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_dependency_artifacts_with_http_info(id, **kwargs) else: (data) = self.get_dependency_artifacts_with_http_info(id, **kwargs) return data
def get_dependency_artifacts(self, id, **kwargs)
Gets dependency artifacts for specific Build Record 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.456594
1.671649
0.871351
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_dependency_graph_with_http_info(id, **kwargs) else: (data) = self.get_dependency_graph_with_http_info(id, **kwargs) return data
def get_dependency_graph(self, id, **kwargs)
Gets dependency graph for a Build Record (running or completed). 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.47166
1.565639
0.939974
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_logs_with_http_info(id, **kwargs) else: (data) = self.get_logs_with_http_info(id, **kwargs) return data
def get_logs(self, id, **kwargs)
Gets logs for specific Build Record 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.489194
1.645593
0.904959
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_repour_logs_with_http_info(id, **kwargs) else: (data) = self.get_repour_logs_with_http_info(id, **kwargs) return data
def get_repour_logs(self, id, **kwargs)
Gets repour logs for specific Build Record 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(re...
1.41077
1.593018
0.885596
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.put_attribute_with_http_info(id, key, value, **kwargs) else: (data) = self.put_attribute_with_http_info(id, key, value, **kwargs) return data
def put_attribute(self, id, key, value, **kwargs)
Add attribute to the BuildRecord. 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.43012
1.572753
0.90931
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.query_by_attribute_with_http_info(key, value, **kwargs) else: (data) = self.query_by_attribute_with_http_info(key, value, **kwargs) return data
def query_by_attribute(self, key, value, **kwargs)
Get Build Records by attribute. 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.436062
1.608851
0.892601
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.remove_attribute_with_http_info(id, key, **kwargs) else: (data) = self.remove_attribute_with_http_info(id, key, **kwargs) return data
def remove_attribute(self, id, key, **kwargs)
Remove attribute from BuildRecord. 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.47013
1.626203
0.904026
if (self.category == 'mem' and options.CGC_ZERO_FILL_UNCONSTRAINED_MEMORY in self.state.options): # CGC binaries zero-fill the memory for any allocated region # Reference: (https://github.com/CyberGrandChallenge/libcgc/blob/master/allocate.md) return...
def get_unconstrained_bytes(self, name, bits, source=None, key=None, inspect=True, events=True, **kwargs)
Get some consecutive unconstrained bytes. :param name: Name of the unconstrained variable :param bits: Size of the unconstrained variable :param source: Where those bytes are read from. Currently it is only used in under-constrained symbolic execution so that we can track th...
4.422683
4.142837
1.067549
allowed_values = ["MVN", "NPM"] if build_type not in allowed_values: raise ValueError( "Invalid value for `build_type` ({0}), must be one of {1}" .format(build_type, allowed_values) ) self._build_type = build_type
def build_type(self, build_type)
Sets the build_type of this BuildConfigurationRest. :param build_type: The build_type of this BuildConfigurationRest. :type: str
2.012658
1.920356
1.048065
client = paramiko.SSHClient() # save hostname and username on the instance - this is a ugly hack # but I don't see any other way to do that for now. Note that # this is only used for SshSession.__str__. client.hostname = host client.username = username if username is not None: k...
def ssh_client(host, username=None, password=None, **kwargs)
Create a new :class:`paramiko.SSHClient`, connect it and return the instance. This is a simple wrapper around the connect method that add some good defaults when using username/password to connect.
3.581017
3.782119
0.946828
warningsShown = [] def warnExplicit(*args): warningsShown.append(args) origExplicit = warnings.warn_explicit try: warnings.warn_explicit = warnExplicit result = f(*args, **kwargs) finally: warnings.warn_explicit = origExplicit if not warningsShown: ...
def failUnlessWarns(self, category, message, filename, f, *args, **kwargs)
Fail if the given function doesn't generate the specified warning when called. It calls the function, checks the warning, and forwards the result of the function if everything is fine. @param category: the category of the warning to check. @param message: the output message of the warning to check. ...
4.632683
4.825355
0.960071
handler = logging.StreamHandler() if not fmt: # ex: 2017-08-26T14:47:44.968+00:00 <progname> (<PID>) INFO: <msg> fmt_prefix = '%(asctime)s.%(msecs)03dZ ' fmt_suffix = ' (%(process)d) %(levelname)s: ' + '%(message)s' fmt = fmt_prefix + progname + fmt_suffix if not datefm...
def _setup_default_handler(progname, fmt=None, datefmt=None, **_)
Create a Stream handler (default handler). Args: progname (str): Name of program. fmt (:obj:`str`, optional): Desired log format if different than the default; uses the same formatting string options supported in the stdlib's `logging` module. datefmt (:obj:`str`, op...
2.78233
3.001115
0.927099
for h in handlers: if h == 'stream': handler = _setup_default_handler(progname, **kwargs) else: handler_module_path = 'ulogger.{}'.format(h) try: handler_module = import_module( handler_module_path, package='ulogger') ...
def setup_logging(progname, level, handlers, **kwargs)
Setup logging to stdout (stream), syslog, or stackdriver. Attaches handler(s) and sets log level to the root logger. Example usage: import logging from ulogger import setup_logging setup_logging('my_awesome_program', 'INFO', ['stream']) logging.info('ohai') Args: ...
2.751319
2.737081
1.005202
''' key: memory address(int) or register name(str) size: size of object in bytes ''' project = load_project() if key in project.arch.registers: if size is None: size = project.arch.registers[key][1] size *= 8 s = claripy...
def sim(self, key, size=None)
key: memory address(int) or register name(str) size: size of object in bytes
2.977587
2.58363
1.152482
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.add_distributed_artifact_with_http_info(id, **kwargs) else: (data) = self.add_distributed_artifact_with_http_info(id, **kwargs) return data
def add_distributed_artifact(self, id, **kwargs)
Adds an artifact to the list of distributed artifacts for this product milestone 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_functio...
1.460718
1.636864
0.892388
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.cancel_milestone_close_with_http_info(id, **kwargs) else: (data) = self.cancel_milestone_close_with_http_info(id, **kwargs) return data
def cancel_milestone_close(self, id, **kwargs)
Cancel Product Milestone Release 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): >>> pprint(res...
1.430637
1.617685
0.884373
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.close_milestone_with_http_info(id, **kwargs) else: (data) = self.close_milestone_with_http_info(id, **kwargs) return data
def close_milestone(self, id, **kwargs)
Close/Release a Product Milestone 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.499871
1.672879
0.896581