text
stringlengths
81
112k
Run the ``before_run`` callbacks and queue to ``on_start`` callbacks. :param tornado.ioloop.IOLoop io_loop: loop to start the app on. def start(self, io_loop): """ Run the ``before_run`` callbacks and queue to ``on_start`` callbacks. :param tornado.ioloop.IOLoop io_loop: loop to start...
Asynchronously stop the application. :param tornado.ioloop.IOLoop io_loop: loop to run until all callbacks, timeouts, and queued calls are complete Call this method to start the application shutdown process. The IOLoop will be stopped once the application is completely shut...
Given a combo file name (joinfile), combine the sourcefiles into a single monolithic file. Returns a string containing the combo file, or None if the specified file can not be combo'd. def combine_files(joinfile, sourcefiles, client): """ Given a combo file name (joinfile), combine the sourcef...
Let's face it... pushing this stuff to S3 is messy. A lot of different things need to be calculated for each file and they have to be in a certain order as some variables rely on others. def sync(client=None, force=False, verbose=True): """ Let's face it... pushing this stuff to S3 is messy...
Enable all offline cpus def enable_all_cpu(self): ''' Enable all offline cpus ''' for cpu in self.__get_ranges("offline"): fpath = path.join("cpu%i"%cpu,"online") self.__write_cpu_file(fpath, b"1")
Enable all offline cpus, and reset max and min frequencies files rg: range or list of threads to reset def reset(self, rg=None): ''' Enable all offline cpus, and reset max and min frequencies files rg: range or list of threads to reset ''' if type(rg) == int: ...
Disable all threads attached to the same core def disable_hyperthread(self): ''' Disable all threads attached to the same core ''' to_disable = [] online_cpus = self.__get_ranges("online") for cpu in online_cpus: fpath = path.join("cpu%i"%cpu,"topology","thre...
Disable cpus rg: range or list of threads to disable def disable_cpu(self, rg): ''' Disable cpus rg: range or list of threads to disable ''' if type(rg) == int: rg= [rg] to_disable= set(rg) & set(self.__get_ranges("online")) for cpu in to_di...
Enable cpus rg: range or list of threads to enable def enable_cpu(self, rg): ''' Enable cpus rg: range or list of threads to enable ''' if type(rg) == int: rg= [rg] to_disable= set(rg) & set(self.__get_ranges("offline")) for cpu in to_disabl...
Set cores frequencies freq: int frequency in KHz rg: list of range of cores setMaxfeq: set the maximum frequency, default to true setMinfreq: set the minimum frequency, default to true setSpeed: only set the frequency, default to true def set_frequencies(self, freq, rg=None, se...
Set governors gov: str name of the governor rg: list of range of cores def set_governors(self, gov, rg=None): ''' Set governors gov: str name of the governor rg: list of range of cores ''' to_change = self.__get_ranges("online") if type(rg) == i...
Get all possible frequencies def get_available_frequencies(self): ''' Get all possible frequencies ''' fpath = path.join("cpu0","cpufreq","scaling_available_frequencies") data = self.__read_cpu_file(fpath).rstrip("\n").split() return data
Configure a previously initialized instance of the class. def configure(self, endpoint=None, **kwargs): """Configure a previously initialized instance of the class.""" if endpoint: kwargs['endpoint'] = endpoint keywords = self._keywords.copy() keywords.update(kwargs) ...
Configure the endpoint with a schema and end slash. def _configure_endpoint(self, endpoint): """Configure the endpoint with a schema and end slash.""" if not endpoint.startswith('http'): endpoint = 'https://' + endpoint if not endpoint.endswith('/'): endpoint += '/' ...
Perform a get request. def get(self, *args, **kwargs): """Perform a get request.""" if 'convert' in kwargs: conversion = kwargs.pop('convert') else: conversion = True kwargs = self._get_keywords(**kwargs) url = self._create_path(*args) request = s...
Format GET request parameters and keywords. def _get_keywords(self, **kwargs): """Format GET request parameters and keywords.""" if self.jurisdiction and 'jurisdiction_id' not in kwargs: kwargs['jurisdiction_id'] = self.jurisdiction if 'count' in kwargs: kwargs['page_siz...
Format start and end dates. def _format_dates(self, start, end): """Format start and end dates.""" start = self._split_date(start) end = self._split_date(end) return start, end
Split apart a date string. def _split_date(self, time): """Split apart a date string.""" if isinstance(time, str): month, day, year = [int(t) for t in re.split(r'-|/', time)] if year < 100: # Quick hack for dates < 2000. year += 2000 t...
Convert content to Python data structures. def convert(self, content, conversion): """Convert content to Python data structures.""" if not conversion: data = content elif self.format == 'json': data = json.loads(content) elif self.format == 'xml': con...
Retrieve the standard discovery file that provides routing information. >>> Three().discovery() {'discovery': 'data'} def discovery(self, url=None): """ Retrieve the standard discovery file that provides routing information. >>> Three().discovery() {'di...
Retrieve information about available services. You can also enter a specific service code argument. >>> Three().services() {'all': {'service_code': 'data'}} >>> Three().services('033') {'033': {'service_code': 'data'}} def services(self, code=None, **kwargs): """ ...
Retrieve open requests. You can also enter a specific service code argument. >>> Three('api.city.gov').requests() {'all': {'requests': 'data'}} >>> Three('api.city.gov').requests('123') {'123': {'requests': 'data'}} def requests(self, code=None, **kwargs): """ R...
Retrieve a specific request using its service code ID. >>> Three('api.city.gov').request('12345') {'request': {'service_code': {'12345': 'data'}}} def request(self, id, **kwargs): """ Retrieve a specific request using its service code ID. >>> Three('api.city.gov').request('123...
Post a new Open311 request. >>> t = Three('api.city.gov') >>> t.post('123', address='123 Any St', name='Zach Williams', ... phone='555-5555', description='My issue description.', ... media=open('photo.png', 'rb')) {'successful': {'request': 'post'}} def post(self,...
Configure keyword arguments for Open311 POST requests. def _post_keywords(self, **kwargs): """Configure keyword arguments for Open311 POST requests.""" if self.jurisdiction and 'jurisdiction_id' not in kwargs: kwargs['jurisdiction_id'] = self.jurisdiction if 'address' in kwargs: ...
Retrieve a service request ID from a token. >>> Three('api.city.gov').token('12345') {'service_request_id': {'for': {'token': '12345'}}} def token(self, id, **kwargs): """ Retrieve a service request ID from a token. >>> Three('api.city.gov').token('12345') {'service_re...
Helper function for building an attribute dictionary. This is combination of the same method from Django<=1.10 and Django1.11+ def build_attrs(self, base_attrs, extra_attrs=None, **kwargs): """ Helper function for building an attribute dictionary. This is combination of the same method ...
Load up the CSV file as a pandas dataframe def to_dataframe(self, **kwargs): """Load up the CSV file as a pandas dataframe""" return pandas.io.parsers.read_csv(self.path, sep=self.d, **kwargs)
Generates a sorted list of elementary intervals def get_elementary_intervals(self, features): """Generates a sorted list of elementary intervals""" coords = [] try: for interval in features: if len(interval) != 3: raise SyntaxError('Interval malfo...
recursively builds a BST based on the elementary intervals. each node is an array: [interval value, left descendent nodes, right descendent nodes, [ids]]. nodes with no descendents have a -1 value in left/right descendent positions. for example, a node with two empty descendents: [5...
Accessory function to check if a point is within a range def pt_within(self, pt, subject): """Accessory function to check if a point is within a range""" try: if pt >= int(subject[0]) and pt <= int(subject[1]): return True except ValueError: raise ValueEr...
Accessory function to check if a range is fully within another range def is_within(self, query, subject): """Accessory function to check if a range is fully within another range""" if self.pt_within(query[0], subject) and self.pt_within(query[1], subject): return True return False
Accessory function to check if two ranges overlap def overlap(self, query, subject): """Accessory function to check if two ranges overlap""" if (self.pt_within(query[0], subject) or self.pt_within(query[1], subject) or self.pt_within(subject[0], query) or self.pt_within(subject[1], query))...
Recursively inserts id data into nodes def recursive_insert(self, node, coord, data, start, end): """Recursively inserts id data into nodes""" if node[0] != -1: left = (start, node[0]) right = (node[0], end) #if left is totally within coord if self.is_wi...
loops through all the data and inserts them into the empty tree def insert_data(self, node, data, start, end): """loops through all the data and inserts them into the empty tree""" for item in data: self.recursive_insert(node, [item[0], item[1]], item[-1], start, end)
trims the tree for any empty data nodes def trim_tree(self, node): """trims the tree for any empty data nodes""" data_len = len(node[-1]) if node[1] == -1 and node[2] == -1: if data_len == 0: return 1 else: return 0 else: ...
recursively finds ids within a range def find(self, node, interval, start, end): """recursively finds ids within a range""" data = [] if len(interval) != 2: raise SyntaxError('Interval malformed %s. Allways specify start and end position for interval.' % str(interval)) ...
wrapper for find def find_range(self, interval): """wrapper for find""" return self.find(self.tree, interval, self.start, self.end)
pretty prints the tree with indentation def pprint(self, ind): """pretty prints the tree with indentation""" pp = pprint.PrettyPrinter(indent=ind) pp.pprint(self.tree)
Return core view of given model or None def get_model_core(model): """ Return core view of given model or None """ model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name)) return registered_model_cores.get(model_label)
r"""Return a object representation of a VCS repository. :returns: instance of a repository object :rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or :class:`libvcs.hg.MercurialRepo`. Usage Example:: >>> from libvcs.shortcuts import create_repo >>> r = crea...
r"""Return a object representation of a VCS repository via pip-style url. :returns: instance of a repository object :rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or :class:`libvcs.hg.MercurialRepo`. Usage Example:: >>> from libvcs.shortcuts import create_repo_fro...
Set the directory, the script path and the outfile path def set_paths(self, base_dir, script_path): """Set the directory, the script path and the outfile path""" # Make absolute paths # if 'change_dir' in self.kwargs: self.kwargs['change_dir'] = DirectoryPath(os.path.abspath(self.kw...
The list of parameters to give to the `sbatch` command. def slurm_params(self): """The list of parameters to give to the `sbatch` command.""" # Main loop # result = OrderedDict() for param, info in self.slurm_headers.items(): if not info['needed'] and not param in self.kwarg...
The script to be submitted to the SLURM queue. def script(self): """The script to be submitted to the SLURM queue.""" self.shebang_header = self.shebang_headers[self.language] self.slurm_header = [self.slurm_headers[k]['tag'] % v for k,v in self.slurm_params.items()] self.script_heade...
Make the script and return a FilePath object pointing to the script above. def make_script(self): """Make the script and return a FilePath object pointing to the script above.""" self.script_path.write(self.script) self.script_path.permissions.make_executable() return self.script_path
What is the status of the job ? def status(self): """What is the status of the job ?""" # If there is no script it is either ready or a lost duplicate # if not self.script_path.exists: if self.name in jobs.names: return "DUPLICATE" if self.name not in jobs.names: ret...
Get the existing job information dictionary def info(self): """Get the existing job information dictionary""" if self.name not in jobs: return {'status': self.status} else: return jobs[self.name]
Will call self.launch() after performing some checks def run(self): """Will call self.launch() after performing some checks""" # Check already exists # if self.status == "READY": return self.launch() # Check name conflict # if self.status == "DUPLICATE": message = "Job with sam...
Make the script file and return the newly created job id def launch(self): """Make the script file and return the newly created job id""" # Make script file # self.make_script() # Do it # sbatch_out = sh.sbatch(self.script_path) jobs.expire() # Message # ...
A convenience method to run the same result as a SLURM job but locally in a non-blocking way. Useful for testing. def run_locally(self): """A convenience method to run the same result as a SLURM job but locally in a non-blocking way. Useful for testing.""" self.thread = threading.Thread...
Runs the equivalent command locally in a blocking way. def execute_locally(self): """Runs the equivalent command locally in a blocking way.""" # Make script file # self.make_script() # Do it # with open(self.kwargs['out_file'], 'w') as handle: sh.python(self.script_p...
If you have run the query in a non-blocking way, call this method to pause until the query is finished. def wait_locally(self): """If you have run the query in a non-blocking way, call this method to pause until the query is finished.""" try: self.thread.join(sys.maxint) # maxint timeou...
find the next major/minor/trivial version number if applicable def replace_version_tag(self): """find the next major/minor/trivial version number if applicable""" version_tag = self.arguments.get('<version>') special_keywords = ['current', 'latest'] if version_tag in special_keywords: ...
returns a 2-tuple (usage, options) def parse_docopt_string(docopt_string): """returns a 2-tuple (usage, options)""" from re import match, DOTALL only_usage_pattern = r"""\s+Usage:\s+(?P<usage>.*)\s+""" usage_and_options_pattern = r"""\s+Usage:\s+(?P<usage>.*)\s+Options:\s+(?P<options>.*)\s+""" usag...
Returns concrete widget that will be used for rendering table filter. def get_widget(self, request): """ Returns concrete widget that will be used for rendering table filter. """ widget = self.widget if isinstance(widget, type): widget = widget() return widge...
Returns the base remote media URL. In this case, we can safely make some assumptions on the URL string based on bucket names, and having public ACL on. args: with_ssl: (bool) If True, return an HTTPS url. def remote_media_url(self, with_ssl=False): """ Returns...
distroinfo Command-Line Interface def distroinfo(cargs, version=__version__): """ distroinfo Command-Line Interface """ code = 1 args = docopt(__doc__, argv=cargs) try: if args['--version']: if not version: version = 'N/A' print(version) ...
Trasform pyston exceptions to Is-core exceptions and raise it def _get_error_response(self, exception): """ Trasform pyston exceptions to Is-core exceptions and raise it """ response_exceptions = { MimerDataException: HTTPBadRequestResponseException, NotAllowedEx...
Intended to be used in case of erroneous input data def reprompt_error(self, message=None): """ Intended to be used in case of erroneous input data """ try: session_id = session.sessionId self.session_machines.rollback_fsm(session_id) current_state = ...
Use in cases when you need to move in given step depending on input def move_to_step(self, step): """ Use in cases when you need to move in given step depending on input """ if step not in self._scenario_steps.keys(): raise UndefinedState("step {} not defined in scenario".fo...
Get current state for user session or None if session doesn't exist def get_current_state(self): """ Get current state for user session or None if session doesn't exist """ try: session_id = session.sessionId return self.session_machines.current_state(session_id)...
Get context help, depending on the current step. If no help for current step was specified in scenario description file, default one will be returned. def get_help(self): """ Get context help, depending on the current step. If no help for current step was specified in scenario descripti...
Runs all enabled tests. def run(self): ''' Runs all enabled tests. ''' # Run all tests. for cls in self.get_test_classes(): # Print informational message. self.logger.info('Running {cls.__name__} test...'.format(cls=cls)) # Create new test i...
Raises an warning if the executable *tool_name* is not found. def check_executable(tool_name): """Raises an warning if the executable *tool_name* is not found.""" result = subprocess.call(['which', tool_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result != 0: message = "The executable...
Calls sys.exit() if the module *mod_name* is not found. def check_module(mod_name): """Calls sys.exit() if the module *mod_name* is not found.""" # Special cases # if mod_name in module_name: mod_name = module_name[mod_name] # Use a try except block # try: __import__(mod_name) except Im...
Generate the IIIF image key. def iiif_image_key(obj): """Generate the IIIF image key.""" if isinstance(obj, ObjectVersion): bucket_id = obj.bucket_id version_id = obj.version_id key = obj.key else: bucket_id = obj.get('bucket') version_id = obj.get('version_id') ...
Generate IIIF image URL from the UI application. def ui_iiif_image_url(obj, version='v2', region='full', size='full', rotation=0, quality='default', image_format='png'): """Generate IIIF image URL from the UI application.""" return u'{prefix}{version}/{identifier}/{region}/{size}/{rotatio...
Body of a non-terminal is always a :class:`Sequence`. For an s-expr to match, it must be of the form:: ['name'] + [sexpr-0, ..., sexpr-n] where the first list contains a name of the non-terminal, and the second one matches its body sequence. def matches(self, sexp): ''' ...
Render appropriate template with embed flag. def preview(file): """Render appropriate template with embed flag.""" params = deepcopy(current_app.config['IIIF_PREVIEWER_PARAMS']) if 'image_format' not in params: params['image_format'] = \ 'png' if file.has_extensions('.png') else 'jpg' ...
Wraps Django Model __getattribute__ method making translation in templates less painful def get_translated_attribute(instance, attr): """ Wraps Django Model __getattribute__ method making translation in templates less painful """ # If its class has no translatable fields, returns attribute try: if not hasattr...
Set an auth decorator applied for views. If DEBUG is on, we serve the view without authenticating. Default is 'django.contrib.auth.decorators.login_required'. Can also be 'django.contrib.admin.views.decorators.staff_member_required' or a custom decorator. def secure(view): """Set an auth decorator ...
Importa las traducciones a partir de un archivo PO. Ten en cuenta que el archivo PO ha de ser generado desde esta aplicación, de forma que los comentarios sirvan como id de traducción (lo metemos nosotros en la exportación). def import_translations(request, language): """ Importa las traducciones a partir de un a...
creates a new cluster def up(cloud_init, use_snapshots, upgrade_image, snapshot_cluster, snapshot_time): """ creates a new cluster """ try: cloud_config = CloudConfig() ci = None if cloud_init: ci = CloudInit() cloud_controller = CloudController(cloud_confi...
destroys an existing cluster def down(force): """ destroys an existing cluster """ try: cloud_config = CloudConfig() cloud_controller = CloudController(cloud_config) cloud_controller.down(force) except CloudComposeException as ex: print(ex)
deletes launch configs and auto scaling group def cleanup(): """ deletes launch configs and auto scaling group """ try: cloud_config = CloudConfig() cloud_controller = CloudController(cloud_config) cloud_controller.cleanup() except CloudComposeException as ex: print(...
builds the cloud_init script def build(): """ builds the cloud_init script """ try: cloud_config = CloudConfig() config_data = cloud_config.config_data('cluster') cloud_init = CloudInit() print(cloud_init.build(config_data)) except CloudComposeException as ex: ...
Send pending signals over the message bus. If a list of SIGNAL_NAMES is specified, flushes only those signals. If no SIGNAL_NAMES are specified, flushes all signals. def flush(signal_names, exclude, wait): """Send pending signals over the message bus. If a list of SIGNAL_NAMES is specified, flushes o...
Send a potentially huge number of pending signals over the message bus. This command assumes that the number of pending signals might be huge, so that they might not fit into memory. However, it is not very smart in handling concurrent senders. It is mostly useful when recovering from long periods of d...
Show all signal types. def signals(): """Show all signal types.""" signalbus = current_app.extensions['signalbus'] for signal_model in signalbus.get_signal_models(): click.echo(signal_model.__name__)
Show the number of pending signals by signal type. def pending(): """Show the number of pending signals by signal type.""" signalbus = current_app.extensions['signalbus'] pending = [] total_pending = 0 for signal_model in signalbus.get_signal_models(): count = signal_model.query.count() ...
Crea la clave única de la caché def _create_key(lang, instance): """Crea la clave única de la caché""" model_name = instance.__class__.__name__ return "{0}__{1}_{2}".format(lang,model_name,instance.id)
Indica si la caché está caducada def _cache_is_expired(): """Indica si la caché está caducada""" now = timezone.now() timediff = TransCache.SINGLETON_CREATION_DATETIME - now return (timediff.total_seconds() > TransCache.SINGLETON_EXPIRATION_MAX_SECONDS)
Factoría del singleton, o crea una nueva o devuelve la existente def factory(): """Factoría del singleton, o crea una nueva o devuelve la existente""" if not TransCache.SINGLETON or TransCache._cache_is_expired(): TransCache.SINGLETON = TransCache() TransCache.SINGLETON_CREATION...
Establece en la instancia actual los atributos de traducción y la almacena en un diccionario de claves _create_key y valores el objeto con los atributos dinámicos. def set(self, lang, instance): """ Establece en la instancia actual los atributos de traducción y la almacena en un...
Indica si la caché tiene un objeto igual a éste con los atributos dinámicos de traducción def has(self, lang, instance): """ Indica si la caché tiene un objeto igual a éste con los atributos dinámicos de traducción """ instance_key = TransCache._create_key(lang, instance...
Obtiene una instancia igual a ésta, pero con los atributos dinámicos de traduccción def get(self, lang, instance): """ Obtiene una instancia igual a ésta, pero con los atributos dinámicos de traduccción """ instance_key = TransCache._create_key(lang, instance) re...
Create the thumbnail for an image. def create_thumbnail(uuid, thumbnail_width): """Create the thumbnail for an image.""" # size = '!' + thumbnail_width + ',' size = thumbnail_width + ',' # flask_iiif doesn't support ! at the moment thumbnail = IIIFImageAPI.get('v2', uuid, size, 0, 'default', 'jpg')
Search and clean price value. Convert raw price string presented in any localization as a valid number string with an optional decimal point. If raw price does not contain valid price value or contains more than one price value, then return default value. If default value not set, then raise Value...
Price decimal value from raw string. Extract price value from input raw string and present as Decimal number. If raw price does not contain valid price value or contains more than one price value, then return default value. If default value not set, then raise ValueError. :param str raw_price...
Return a list of (timestamp, duration) sets for test result. def flotify(result, num=50): """ Return a list of (timestamp, duration) sets for test result. """ results = list(TestResult.objects.filter(test=result.test, site=result.site)[:num]) results.reverse() return [[get_timestamp(result.run_...
Gets "something" from self, which could be an attribute or a callable with either 0 or 1 arguments (besides self). Stolen from django.contrib.syntication.feeds.Feed. def __get_dynamic_attr(self, attname, arg, default=None): """ Gets "something" from self, which could be an attr...
Append global tags configured for the client to the tags given then converts the data into InfluxDB Line protocol and sends to to socket def metric(self, measurement_name, values, tags=None, timestamp=None): """ Append global tags configured for the client to the tags given then convert...
Sends the given data to the socket via UDP def send(self, data): """ Sends the given data to the socket via UDP """ try: self.socket.sendto(data.encode('utf8') + b'\n', (self.host, self.port)) except (socket.error, RuntimeError): # Socket errors should fa...
Send the data in a separate thread via HTTP POST. HTTP introduces some overhead, so to avoid blocking the main thread, this issues the request in the background. def send(self, data): """ Send the data in a separate thread via HTTP POST. HTTP introduces some overhead, so to avoi...
Return an escaped string of comma separated value_name: value pairs def get_output_values(self): """ Return an escaped string of comma separated value_name: value pairs """ # Handle primitive values here and implicitly convert them to a dict because # it allows the API to be sim...
Return an escaped string of comma separated tag_name: tag_value pairs Tags should be sorted by key before being sent for best performance. The sort should match that from the Go bytes. Compare function (http://golang.org/pkg/bytes/#Compare). def get_output_tags(self): """ Return an esc...
Converts the given metrics as a single line of InfluxDB line protocol def to_line_protocol(self): """ Converts the given metrics as a single line of InfluxDB line protocol """ tags = self.get_output_tags() return u"{0}{1} {2}{3}".format( self.get_output_measurement(...
Formats either measurement names, tag names or tag values. Measurement name and any optional tags separated by commas. Measurement names, tag keys, and tag values must escape any spaces, commas or equal signs using a backslash (\). For example: \ and \,. All tag values are stored as strings and should...
Integers are numeric values that do not include a decimal and are followed by a trailing i when inserted (e.g. 1i, 345i, 2015i, -10i). Note that all values must have a trailing i. If they do not they will be written as floats. Floats are numeric values that are not followed by a trailing i. (e.g. 1, 1.0, -...