code
stringlengths
1
18.2k
def expiring_memoize(obj): """Like memoize, but forgets after 10 seconds.""" cache = obj.cache = {} last_access = obj.last_access = defaultdict(int) @wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if last_access[key] and last_access[key] + 10 < time(): if key in cache: del cache[key] last_acces...
def lru_cache(maxsize=128, maxtime=60): '''Least-recently-used cache decorator. Arguments to the cached function must be hashable. Cache performance statistics stored in f.hits and f.misses. Clear the cache with f.clear(). http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used ''' maxqueue = maxsize * 10 # @...
+= (kwd_mark,) + tuple(sorted(kwds.items())) # record recent use of this key queue_append(key) refcount[key] += 1 # get cache entry or compute if not found try: result, expire_time = cache[key] if expire_time and time() > expire_time: raise KeyError('Expired') wrapper.hits += 1 except KeyError: result = user_function(*...
clear(): cache.clear() queue.clear() refcount.clear() wrapper.hits = wrapper.misses = 0 wrapper.hits = wrapper.misses = 0 wrapper.clear = clear return wrapper return decorating_function
def configure_logging(cfg, custom_level=None): """Don't know what this is for ....""" import itertools as it import operator as op if custom_level is None: custom_level = logging.WARNING for entity in it.chain.from_iterable(it.imap(op.methodcaller('viewvalues'), [cfg] + [cfg.get(k, dict()) for k in ['handlers', 'logger...
def toposort(data): """Dependencies are expressed as a dictionary whose keys are items and whose values are a set of dependent items. Output is a list of sets in topological order. The first set consists of items with no dependences, each subsequent set consists of items that depend upon items in the preceeding sets. >...
= set(item for item, dep in iteritems(data) if not dep) if not ordered: break yield ordered data = {item: (dep - ordered) for item, dep in iteritems(data) if item not in ordered} assert not data, 'Cyclic dependencies exist among these items:\n%s' % '\n'.join( repr(x) for x in list(data.items()))
def md5_for_file(f, block_size=2 ** 20): """Generate an MD5 has for a possibly large file by breaking it into chunks.""" md5 = hashlib.md5() try: # Guess that f is a FLO. f.seek(0) return md5_for_stream(f, block_size=block_size) except AttributeError: # Nope, not a FLO. Maybe string? file_name = f with open(file_name, ...
def make_acro(past, prefix, s): # pragma: no cover """Create a three letter acronym from the input string s. Args: past: A set object, for storing acronyms that have already been created prefix: A prefix added to the acronym before storing in the set s: The string to create the acronym from. """ def _make_acro(s, t=0):...
string if s.startswith('Mc'): if t < 1: return 'Mc' + v[0] if t < 2: return 'Mc' + c[0] if s[0] in v: # Starts with a vowel if t < 1: return vx[0] + cx[0] + cx[1] if t < 2: return vx[0] + vx[1] + cx[0] if s[0] in c and s[1] in c: # Two first consonants if t < 1: return cx[0] + cx[1] + vx[0] if t < 2: return cx[0] + cx[...
if t < 7: return s[0:3] if t < 8: return s[1:4] if t < 9: return s[2:5] if t < 10: return s[3:6] return None for t in six_xrange(11): # Try multiple forms until one isn't in the past acronyms try: a = _make_acro(s, t) if a is not None: if prefix: aps = prefix + a else: aps = a if aps not in past: past.add(aps) return a...
def ensure_dir_exists(path): """Given a file, ensure that the path to the file exists""" import os f_dir = os.path.dirname(path) if not os.path.exists(f_dir): os.makedirs(f_dir) return f_dir
def walk_dict(d): """Walk a tree (nested dicts). For each 'path', or dict, in the tree, returns a 3-tuple containing: (path, sub-dicts, values) where: * path is the path to the dict * sub-dicts is a tuple of (key,dict) pairs for each sub-dict in this dict * values is a tuple of (key,value) pairs for each (non-dict) ite...
in path and pass on res = ('/%s' % k + res[0], res[1], res[2]) yield res
def init_log_rate(output_f, N=None, message='', print_rate=None): """Initialze the log_rate function. Returnas a partial function to call for each event. If N is not specified but print_rate is specified, the initial N is set to 100, and after the first message, the N value is adjusted to emit print_rate messages per s...
def _log_rate(output_f, d, message=None): """Log a message for the Nth time the method is called. d is the object returned from init_log_rate """ if d[2] <= 0: if message is None: message = d[4] # Average the rate over the length of the deque. d[6].append(int(d[3] / (time() - d[1]))) rate = sum(d[6]) / len(d[6]) # Prin...
def count_open_fds(): """return the number of open file descriptors for current process. .. warning: will only work on UNIX-like os-es. http://stackoverflow.com/a/7142094 """ pid = os.getpid() procs = subprocess.check_output( ['lsof', '-w', '-Ff', '-p', str(pid)]) nprocs = len( [s for s in procs.split('\n') if s and s[...
def parse_url_to_dict(url): """Parse a url and return a dict with keys for all of the parts. The urlparse function() returns a wacky combination of a namedtuple with properties. """ p = urlparse(url) return { 'scheme': p.scheme, 'netloc': p.netloc, 'path': p.path, 'params': p.params, 'query': p.query, 'fragment': p.fra...
def set_url_part(url, **kwargs): """Change one or more parts of a URL""" d = parse_url_to_dict(url) d.update(kwargs) return unparse_url_dict(d)
def filter_url(url, **kwargs): """filter a URL by returning a URL with only the parts specified in the keywords""" d = parse_url_to_dict(url) d.update(kwargs) return unparse_url_dict({k: v for k, v in list(d.items()) if v})
def print_yaml(o): """Pretty print an object as YAML.""" print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))
def qualified_class_name(o): """Full name of an object, including the module""" module = o.__class__.__module__ if module is None or module == str.__class__.__module__: return o.__class__.__name__ return module + '.' + o.__class__.__name__
def qualified_name(cls): """Full name of a class, including the module. Like qualified_class_name, but when you already have a class """ module = cls.__module__ if module is None or module == str.__class__.__module__: return cls.__name__ return module + '.' + cls.__name__
def qualified_name_import(cls): """Full name of a class, including the module. Like qualified_class_name, but when you already have a class """ parts = qualified_name(cls).split('.') return "from {} import {}".format('.'.join(parts[:-1]), parts[-1])
def drop_empty(rows): """Transpose the columns into rows, remove all of the rows that are empty after the first cell, then transpose back. The result is that columns that have a header but no data in the body are removed, assuming the header is the first row. """ return zip(*[col for col in zip(*rows) if bool(filter(bo...
def pretty_time(s, granularity=3): """Pretty print time in seconds. COnverts the input time in seconds into a string with interval names, such as days, hours and minutes From: http://stackoverflow.com/a/24542445/1144479 """ intervals = ( ('weeks', 604800), # 60 * 60 * 24 * 7 ('days', 86400), # 60 * 60 * 24 ('hours', 36...
def delete_module(modname, paranoid=None): """ Delete a module.http://stackoverflow.com/a/1668289 :param modname: :param paranoid: :return: """ from sys import modules try: thismod = modules[modname] except KeyError: raise ValueError(modname) these_symbols = dir(thismod) if paranoid: try: paranoid[:] # sequence support...
def _create_class_proxy(cls, theclass): """creates a proxy for the given class""" def make_method(name): def method(self, *args, **kw): return getattr(object.__getattribute__(self, "_obj"), name)(*args, **kw) return method namespace = {} for name in cls._special_names: if hasattr(theclass, name): namespace[name] = make...
def _compute_inflation(value, reference_value): """ Helper function to compute the inflation/deflation based on a value and a reference value """ res = value / float(reference_value) return InflationResult(factor=res, value=res - 1)
def get(self, reference, country, target=datetime.date.today()): """ Get the inflation/deflation value change for the target date based on the reference date. Target defaults to today and the instance's reference and country will be used if they are not provided as parameters """ # Set country & reference to object's c...
def inflate(self, amount, target=datetime.date.today(), reference=None, country=None): """ Inflate a given amount to the target date from a reference date (or the object's reference year if no reference date is provided) in a given country (or objects country if no country is provided). The amount has to be provided as...
def manage(commands, argv=None, delim=':'): ''' Parses argv and runs neccessary command. Is to be used in manage.py file. Accept a dict with digest name as keys and instances of :class:`Cli<iktomi.management.commands.Cli>` objects as values. The format of command is the following:: ./manage.py digest_name:command_name[...
cwords[cword - 1] except IndexError: curr = '' suggest = [] if len(cwords) > 1 and cwords[0] in commands.keys(): value = commands[cwords[0]] if isinstance(value, LazyCli): value = value.get_digest() for cmd_name, _ in value.get_funcs(): cmd_name = cmd_name[8:] suggest.append(cmd_name) if curr == ":": curr = '' else: su...
True kwargs[k] = v else: args.append(item) # trying to get command instance if delim in cmd_name: digest_name, command = cmd_name.split(delim) else: digest_name = cmd_name command = None try: digest = commands[digest_name] except KeyError: _command_list(commands) sys.exit('ERROR: Command "{}" not found'.format(digest_n...
def description(self, argv0='manage.py', command=None): '''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'.format(command) funcs = ...
def requestAvatar(self, avatarId, mind, *interfaces): """ Create Adder avatars for any IBoxReceiver request. """ if IBoxReceiver in interfaces: return (IBoxReceiver, Adder(avatarId), lambda: None) raise NotImplementedError()
def handle_error(self, env): ''' 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(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`. ''' try: response = self.handler(env, data) if response is None: logger.debug(...
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 MyClass: @someExposer....
[] self._exposed[rkey].append(function) return function return decorator
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 this ...
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. """ # originally from django.utils.encoding while True: try: return path.decode('utf-8') except U...
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. """ path = url_unquote(path, '%/;...
def default_bundle_config(): """Return the default bundle config file as an AttrDict.""" 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 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. """ 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('.p...
def update(self, of): """Update a file from another file, for copying""" # 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 unpacked_contents(self): """ :return: """ 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 need utf-8 to make python3 to work....
def dict_row_reader(self): """ Unpacks message pack rows into a stream of dicts. """ rows = self.unpacked_contents if not rows: return header = rows.pop(0) for row in rows: yield dict(list(zip(header, row)))
def update_contents(self, contents, mime_type): """Update the contents and set the hash and modification time""" 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....
def dict(self): """A dict that holds key/values for all of the properties in the object. :return: """ 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 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_""" 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_vi...
def __deserialize_primitive(self, data, klass): """ Deserializes string to primitive type. :param data: str. :param klass: class literal. :return: int, long, float, str, bool. """ try: return klass(data) except UnicodeEncodeError: return text(data) except TypeError: return data
def __deserialize_datetime(self, string): """ Deserializes string to datetime. The string should be in iso8601 datetime format. :param string: str. :return: datetime. """ try: from dateutil.parser import parse timestr = str(datetime.fromtimestamp(string/1000)) return parse(timestr) except ImportError: return string exc...
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 secon...
platform. Since there is no definite order to the fields of a dict, there is no consistent way to format dicts for output. To avoid the asymmetry of a type that can be read but not written, plain dictionary parsing is omitted. """ if isinstance(source, six.string_types): source = six.StringIO(source) # Prepare source l...
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-li...
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): >>> ppri...
def get_bundle_ref(args, l, use_history=False): """ Use a variety of methods to determine which bundle to use :param args: :return: """ 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...
def bundle_variant(args, l, rc): """Create a new bundle as a variant of an existing bundle""" 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, ...
print ds b.build_source_files.sources.objects_to_record() b.commit()
def bundle_new(args, l, rc): """Create a new bundle""" 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('ambry', {}) except: ambry_acc...
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. ...
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...
file for {0}'.format(app)) return else: # This is an actual import error we should know about raise self.log('Checking dependencies for {0}'.format(app)) # get dependency list dependencies = self.get_dependency_call_list(app) # update initial data of dependencies for dependency in dependencies: self.update_app(dependen...
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 previo...
associated model objects that weren't updated for receipt in RegisteredForDeletionReceipt.objects.exclude(register_time=now): try: receipt.model_obj.delete() except: # noqa # The model object may no longer be there, its ctype may be invalid, or it might be protected. # Regardless, the model object cannot be deleted, so...
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. """ for app in apps.get_app_configs(): self.update_app(app.name) # During update_app, all apps added model ...
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 n...
= self.load_app(app) except ImportError: raise InitialDataMissingApp(dep=app) dependencies = initial_data_class.dependencies # loop through each dependency and check recursively for cycles for dep in dependencies: if dep in call_list: raise InitialDataCircularDependency(dep=dep, call_list=call_list) else: self.get_depe...
def reset(self): """ Resets (deletes) all indexes. """ self.dataset_index.reset() self.partition_index.reset() self.identifier_index.reset()
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 """ if isinstance(terms, (tuple, list)): if len(terms) > 1: return '(' + ' OR '.join(terms) + ')' else: return terms[0] else: return terms
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' Returns: str """ if len(terms) > 1: return '...
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. """ if not self.is_indexed(in...
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. """ # find tables. assert isinstance(dataset, Dataset) execute = object_session(dataset).connection().execute quer...
len(parts))]]) # Re-calculate the summarization of grains, since the geoid 0.0.7 package had a bug where state level # summaries had the same value as state-level allvals def resum(g): try: return str(GVid.parse(g).summarize()) except (KeyError, ValueError): return g def as_list(value): """ Converts value to the list. ...
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 """ ret = { 'keywords': ...
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. """ schema = ' '.join( u'{} {} {} {} {}'.format( c.id, c.vid, c.name, c.altname, c.descriptio...
parse gvid '{}' from partition '{}' grain coverage" .format(g, partition.identity.vname)) return g keywords = ( ' '.join(partition.space_coverage) + ' ' + ' '.join([resum(g) for g in partition.grain_coverage if resum(g)]) + ' ' + ' '.join(str(x) for x in partition.time_coverage) ) doc_field = u('{} {} {} {} {} {}').for...
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 """ ret = { 'keywords': list(), 'doc': list(), 'from': None, 'to': None} if not isinstance(terms, dict): stp = SearchTermParser() terms = stp.pa...
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. """ place_vids = [] first_type = None for result in self.backend.identifier_index.search(terms...
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. """ return { 'identifier': u('{}').f...
def _geograins(self): """Create a map geographic area terms to the geo grain GVid values """ 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 parse(self, s, term_join=None): """ Parses search term to Args: s (str): string with search term. or_join (callable): function to join 'OR' terms. Returns: dict: all of the terms grouped by marker. Key is a marker, value is a term. Example: >>> SearchTermParser().parse('table2 from 1978 to 1979 in california') {'to...
list of tokens: #[(3, 'about'), # (0, 'diabetes'), # (3, 'from'), # (4, 2014), # (3, 'to'), # (4, 2016), # (3, 'source'), # (0, 'healthindicators.gov')] # Group the terms by their marker. bymarker = [] for t in toks: if t[0] == self.MARKER: bymarker.append((t[1], [])) else: bymarker[-1][1].append(t) # After grouping to...
the from term isn't an integer, then it is really a source. if t[0] == 'from' and len(t[1]) == 1 and t[1][0][0] != self.YEAR: t[0] = 'source' comps.append(t) # After conversions # [['about', [(0, 'diabetes')]], # ['from', [(4, 2014)]], # ['to', [(4, 2016)]], # ['source', [(0, 'healthindicators.gov')]]] # Join all of th...
if marker == 'about': continue if len(group) > 1 and marker not in self.multiterms: groups[marker], extras = [group[0]], group[1:] if not 'about' in groups: groups['about'] = extras else: groups['about'] += extras if marker == 'by': groups['by'] = [ self.geograins.get(self.stem(e)) for e in group] for marker, terms in ...
def run(self): """Execute the build command.""" 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.a...
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,...
in types: custom_type.drop(conn) trans.commit() except: # pragma: no cover trans.rollback() raise
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] ''' def _create_metadata_tables(metadata): for table in metada...
def command_drop_tables(self, meta_name=None): ''' 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_tables(metadata): table = next(s...
def command_schema(self, name=None): ''' 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: meta_name, table_name = name.split('.', 1) else: meta_name...
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 ''' if not names: sys.exit('Please provide generator names') for name in names: name, count = name, 0 if ':' in name: name, ...
def get_conn_info(self): from sockjs.cyclone.conn import ConnectionInfo """ Return C{ConnectionInfo} object from current transport """ return ConnectionInfo(self.request.remote_ip, self.request.cookies, self.request.arguments, self.request.headers, self.request.path)
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 """ parts = statement.to_unicode().split() tables = set() ...
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 ove...
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): """ # first install all partitions of the table queries = [] query_tmpl = 'SELECT * FROM {}' fo...
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. """ self.install_module(connection) statements = sqlparse.parse(sqlparse.format(query...
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 """ response = utils.checked_api_call(pnc_api.build_configs, 'get_all', q='name==' + name).content...
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 """ response = utils.checked_api_call(pnc_api.build_configs, 'get_all', q='name==' + name).content if not respons...