text
stringlengths
81
112k
Retry sending request until timeout or until receiving a response. def _make_request_to_server(self, query_function, raise_for_status=True, time_limit_seconds=2, retry_delay_seconds=0.2): """Retry sending request until timeout or until receiving a response. """ s...
Convenience function for retrieving a resource. If resource does not exist, return None. def _get_resource(self, relative_url, params=None): """Convenience function for retrieving a resource. If resource does not exist, return None. """ response = self._get(relative_url, params=...
Returns the correct Input class for a given data type and gather mode def TaskAttemptInput(input, task_attempt): """Returns the correct Input class for a given data type and gather mode """ (data_type, mode) = _get_input_info(input) if data_type != 'file': return NoOpInput(None, task_...
Run a task asynchronously def execute(task_function, *args, **kwargs): """Run a task asynchronously """ if get_setting('TEST_DISABLE_ASYNC_DELAY'): # Delay disabled, run synchronously logger.debug('Running function "%s" synchronously because '\ 'TEST_DISABLE_ASYNC_DELA...
Run a task asynchronously after at least delay_seconds def execute_with_delay(task_function, *args, **kwargs): """Run a task asynchronously after at least delay_seconds """ delay = kwargs.pop('delay', 0) if get_setting('TEST_DISABLE_ASYNC_DELAY'): # Delay disabled, run synchronously log...
Check for tasks that are no longer sending a heartbeat def check_for_stalled_tasks(): """Check for tasks that are no longer sending a heartbeat """ from api.models.tasks import Task for task in Task.objects.filter(status_is_running=True): if not task.is_responsive(): task.system_err...
Check for TaskAttempts that were never cleaned up def check_for_missed_cleanup(): """Check for TaskAttempts that were never cleaned up """ if get_setting('PRESERVE_ALL'): return from api.models.tasks import TaskAttempt if get_setting('PRESERVE_ON_FAILURE'): for task_attempt in TaskA...
This attempts to execute "retryable_function" with exponential backoff on delay time. 10 retries adds up to about 34 minutes total delay before the last attempt. "human_readable_action_name" is an option input to customize retry message. def execute_with_retries(retryable_function, ...
Export a file from Loom to some file storage location. Default destination_directory is cwd. Default destination_filename is the filename from the file data object associated with the given file_id. def export_file(self, data_object, destination_directory=None, destination_filename...
Like urlparse except it assumes 'file://' if no scheme is specified def _urlparse(path): """Like urlparse except it assumes 'file://' if no scheme is specified """ url = urlparse.urlparse(path) _validate_url(url) if not url.scheme or url.scheme == 'file://': # Normalize path, and set scheme...
Factory method returns LocalFilePattern or GoogleStorageFilePattern def FilePattern(pattern, settings, **kwargs): """Factory method returns LocalFilePattern or GoogleStorageFilePattern """ url = _urlparse(pattern) if url.scheme == 'gs': return GoogleStorageFilePattern(pattern, settings, **kwarg...
Factory method def File(url, settings, retry=False): """Factory method """ parsed_url = _urlparse(url) if parsed_url.scheme == 'gs': return GoogleStorageFile(url, settings, retry=retry) elif parsed_url.scheme == 'file': if parsed_url.hostname == 'localhost' or parsed_url.hostname i...
Factory method to select the right copier for a given source and destination. def Copier(source, destination): """Factory method to select the right copier for a given source and destination. """ if source.type == 'local' and destination.type == 'local': return LocalCopier(source, destination) ...
Scan the data tree on the given data_channel to create a corresponding InputSetGenerator tree. def create_from_data_channel(cls, data_channel): """Scan the data tree on the given data_channel to create a corresponding InputSetGenerator tree. """ gather_depth = cls._get_gather_de...
Returns the correct Output class for a given data type, source type, and scatter mode def TaskAttemptOutput(output, task_attempt): """Returns the correct Output class for a given data type, source type, and scatter mode """ (data_type, mode, source_type) = _get_output_info(output) if data_typ...
Adds a new leaf node at the given index with the given data_object def add_leaf(self, index, data_object, save=False): """Adds a new leaf node at the given index with the given data_object """ assert self.type == data_object.type, 'data type mismatch' if self._get_child_by_index(index) ...
Returns a list [(path1,data_node1),...] with entries only for existing nodes with DataObjects where is_ready==True. Missing nodes or those with non-ready or non-existing data are ignored. def get_ready_data_nodes(self, seed_path, gather_depth): """Returns a list [(path1,data_node1),...] ...
Verify that the given index is consistent with the degree of the node. def _check_index(self, index): """Verify that the given index is consistent with the degree of the node. """ if self.degree is None: raise UnknownDegreeError( 'Cannot access child DataNode on a pa...
Determines if we're running on a GCE instance. def on_gcloud_vm(): """ Determines if we're running on a GCE instance.""" r = None try: r = requests.get('http://metadata.google.internal') except requests.ConnectionError: return False try: if r.headers['Metadata-Flavor'] == '...
Determine the cheapest instance type given a minimum number of cores and minimum amount of RAM (in GB). def get_cheapest_instance_type(cores, memory): """Determine the cheapest instance type given a minimum number of cores and minimum amount of RAM (in GB). """ pricelist = get_gcloud_pricelist() ...
Retrieve latest pricelist from Google Cloud, or use cached copy if not reachable. def get_gcloud_pricelist(): """Retrieve latest pricelist from Google Cloud, or use cached copy if not reachable. """ try: r = requests.get('http://cloudpricingcalculator.appspot.com' '...
Create a base name for the worker instance that will run the specified task run attempt, from this server. Since hostname and step name will be duplicated across workers (reruns, etc.), ensure that at least MIN_TASK_ID_CHARS are preserved in the instance name. Also, prevent names from ending with dashes...
Instance names must start with a lowercase letter. All following characters must be a dash, lowercase letter, or digit. def _sanitize_instance_name(name, max_length): """Instance names must start with a lowercase letter. All following characters must be a dash, lowercase letter, or digit. """ ...
Determines if the cache files have expired, or if it is still valid def is_valid(self, max_age=None): ''' Determines if the cache files have expired, or if it is still valid ''' if max_age is None: max_age = self.cache_max_age if os.path.isfile(self.cache_path_cache): ...
Reads the JSON inventory from the cache file. Returns Python dictionary. def get_all_data_from_cache(self, filename=''): ''' Reads the JSON inventory from the cache file. Returns Python dictionary. ''' data = '' if not filename: filename = self.cache_path_cache with open(fi...
Writes data to file as JSON. Returns True. def write_to_cache(self, data, filename=''): ''' Writes data to file as JSON. Returns True. ''' if not filename: filename = self.cache_path_cache json_data = json.dumps(data) with open(filename, 'w') as cache: cache.wr...
Reads the settings from the gce.ini file. Populates a SafeConfigParser object with defaults and attempts to read an .ini-style configuration from the filename specified in GCE_INI_PATH. If the environment variable is not present, the filename defaults to gce.ini in the current w...
Determine inventory options. Environment variables always take precedence over configuration files. def get_inventory_options(self): """Determine inventory options. Environment variables always take precedence over configuration files.""" ip_type = self.config.get('inventory', 'inventor...
Determine the GCE authorization settings and return a libcloud driver. def get_gce_driver(self): """Determine the GCE authorization settings and return a libcloud driver. """ # Attempt to get GCE params from a configuration file, if one # exists. secrets_path = s...
returns a list of comma separated zones parsed from the GCE_ZONE environment variable. If provided, this will be used to filter the results of the grouped_instances call def parse_env_zones(self): '''returns a list of comma separated zones parsed from the GCE_ZONE environment variable. If provi...
Command line argument processing def parse_cli_args(self): ''' Command line argument processing ''' parser = argparse.ArgumentParser( description='Produce an Ansible Inventory file based on GCE') parser.add_argument('--list', action='store_true', default=True, ...
Loads inventory from JSON on disk. def load_inventory_from_cache(self): ''' Loads inventory from JSON on disk. ''' try: self.inventory = self.cache.get_all_data_from_cache() hosts = self.inventory['_meta']['hostvars'] except Exception as e: print( ...
Do API calls and save data in cache. def do_api_calls_update_cache(self): ''' Do API calls and save data in cache. ''' zones = self.parse_env_zones() data = self.group_instances(zones) self.cache.write_to_cache(data) self.inventory = data
Group all instances def group_instances(self, zones=None): '''Group all instances''' groups = {} meta = {} meta["hostvars"] = {} for node in self.list_nodes(): # This check filters on the desired instance states defined in the # config file with the ins...
Converts a dict to a JSON object and dumps it as a formatted string def json_format_dict(self, data, pretty=False): ''' Converts a dict to a JSON object and dumps it as a formatted string ''' if pretty: return json.dumps(data, sort_keys=True, indent=2) else: ...
Stream stdout and stderr from the task container to this process's stdout and stderr, respectively. def _stream_docker_logs(self): """Stream stdout and stderr from the task container to this process's stdout and stderr, respectively. """ thread = threading.Thread(target=self._st...
Because we allow template ID string values, where serializers normally expect a dict def to_internal_value(self, data): """Because we allow template ID string values, where serializers normally expect a dict """ converted_data = _convert_template_id_to_dict(data) return ...
Compare two identifier (for pre-release/build components). def identifier_cmp(a, b): """Compare two identifier (for pre-release/build components).""" a_cmp, a_is_int = _to_int(a) b_cmp, b_is_int = _to_int(b) if a_is_int and b_is_int: # Numeric identifiers are compared as integers retu...
Compare two identifier list (pre-release/build components). The rule is: - Identifiers are paired between lists - They are compared from left to right - If all first identifiers match, the longest list is greater. >>> identifier_list_cmp(['1', '2'], ['1', '2']) 0 >>> identifier...
Coerce an arbitrary version string into a semver-compatible one. The rule is: - If not enough components, fill minor/patch with zeroes; unless partial=True - If more than 3 dot-separated components, extra components are "build" data. If some "build" data already appeared, ap...
Parse a version string into a Version() object. Args: version_string (str), the version string to parse partial (bool), whether to accept incomplete input coerce (bool), whether to try to map the passed in string into a valid Version. def parse(cls, version_...
Retrieve comparison methods to apply on version components. This is a private API. Args: partial (bool): whether to provide 'partial' or 'strict' matching. Returns: 5-tuple of cmp-like functions. def _comparison_functions(cls, partial=False): """Retrieve compa...
Helper for comparison. Allows the caller to provide: - The condition - The return value if the comparison is meaningless (ie versions with build metadata). def __compare_helper(self, other, condition, notimpl_target): """Helper for comparison. Allows the caller to ...
Check whether a Version satisfies the Spec. def match(self, version): """Check whether a Version satisfies the Spec.""" return all(spec.match(version) for spec in self.specs)
Select the best compatible version among an iterable of options. def select(self, versions): """Select the best compatible version among an iterable of options.""" options = list(self.filter(versions)) if options: return max(options) return None
Handle django.db.migrations. def deconstruct(self): """Handle django.db.migrations.""" name, path, args, kwargs = super(VersionField, self).deconstruct() kwargs['partial'] = self.partial kwargs['coerce'] = self.coerce return name, path, args, kwargs
Converts any value to a base.Version field. def to_python(self, value): """Converts any value to a base.Version field.""" if value is None or value == '': return value if isinstance(value, base.Version): return value if self.coerce: return base.Versio...
Converts any value to a base.Spec field. def to_python(self, value): """Converts any value to a base.Spec field.""" if value is None or value == '': return value if isinstance(value, base.Spec): return value return base.Spec(value)
Make the drone move left. def move_left(self): """Make the drone move left.""" self.at(ardrone.at.pcmd, True, -self.speed, 0, 0, 0)
Make the drone move right. def move_right(self): """Make the drone move right.""" self.at(ardrone.at.pcmd, True, self.speed, 0, 0, 0)
Make the drone rise upwards. def move_up(self): """Make the drone rise upwards.""" self.at(ardrone.at.pcmd, True, 0, 0, self.speed, 0)
Make the drone decent downwards. def move_down(self): """Make the drone decent downwards.""" self.at(ardrone.at.pcmd, True, 0, 0, -self.speed, 0)
Make the drone move forward. def move_forward(self): """Make the drone move forward.""" self.at(ardrone.at.pcmd, True, 0, -self.speed, 0, 0)
Make the drone move backwards. def move_backward(self): """Make the drone move backwards.""" self.at(ardrone.at.pcmd, True, 0, self.speed, 0, 0)
Make the drone rotate left. def turn_left(self): """Make the drone rotate left.""" self.at(ardrone.at.pcmd, True, 0, 0, 0, -self.speed)
Make the drone rotate right. def turn_right(self): """Make the drone rotate right.""" self.at(ardrone.at.pcmd, True, 0, 0, 0, self.speed)
Toggle the drone's emergency state. def reset(self): """Toggle the drone's emergency state.""" self.at(ardrone.at.ref, False, True) time.sleep(0.1) self.at(ardrone.at.ref, False, False)
Wrapper for the low level at commands. This method takes care that the sequence number is increased after each at command and the watchdog timer is started to make sure the drone receives a command at least every second. def at(self, cmd, *args, **kwargs): """Wrapper for the low level ...
Shutdown the drone. This method does not land or halt the actual drone, but the communication with the drone. You should call it at the end of your application to close all sockets, pipes, processes and threads related with this object. def halt(self): """Shutdown the drone. ...
Makes the drone move (translate/rotate). Parameters: lr -- left-right tilt: float [-1..1] negative: left, positive: right fb -- front-back tilt: float [-1..1] negative: forwards, positive: backwards vv -- vertical speed: float [-1..1] negative: go down, positive: rise ...
Basic behaviour of the drone: take-off/landing, emergency stop/reset) Parameters: seq -- sequence number takeoff -- True: Takeoff / False: Land emergency -- True: Turn off the engines def ref(host, seq, takeoff, emergency=False): """ Basic behaviour of the drone: take-off/landing, emergency st...
Makes the drone move (translate/rotate). Parameters: seq -- sequence number progressive -- True: enable progressive commands, False: disable (i.e. enable hovering mode) lr -- left-right tilt: float [-1..1] negative: left, positive: right rb -- front-back tilt: float [-1..1] negative: forwar...
Set configuration parameters of the drone. def config(host, seq, option, value): """Set configuration parameters of the drone.""" at(host, 'CONFIG', seq, [str(option), str(value)])
Sends control values directly to the engines, overriding control loops. Parameters: seq -- sequence number m1 -- Integer: front left command m2 -- Integer: front right command m3 -- Integer: back right command m4 -- Integer: back left command def pwm(host, seq, m1, m2, m3, m4): """ Sen...
Control the drones LED. Parameters: seq -- sequence number anim -- Integer: animation to play f -- Float: frequency in HZ of the animation d -- Integer: total duration in seconds of the animation def led(host, seq, anim, f, d): """ Control the drones LED. Parameters: seq -- sequen...
Makes the drone execute a predefined movement (animation). Parameters: seq -- sequcence number anim -- Integer: animation to play d -- Integer: total duration in seconds of the animation def anim(host, seq, anim, d): """ Makes the drone execute a predefined movement (animation). Parameter...
Parameters: command -- the command seq -- the sequence number params -- a list of elements which can be either int, float or string def at(host, command, seq, params): """ Parameters: command -- the command seq -- the sequence number params -- a list of elements which can be either int,...
Decode a navdata packet. def decode(packet): """Decode a navdata packet.""" offset = 0 _ = struct.unpack_from('IIII', packet, offset) s = _[1] state = dict() state['fly'] = s & 1 # FLY MASK : (0) ardrone is landed, (1) ardrone is flying state['video'] = ...
Save VTK data to file. def tofile(self, filename, format = 'ascii'): """Save VTK data to file. """ if not common.is_string(filename): raise TypeError('argument filename must be string but got %s'%(type(filename))) if format not in ['ascii','binary']: raise TypeEr...
Simple helper to get the value of an instance's attribute if it exists. If the instance attribute is callable it will be called and the result will be returned. Optionally accepts a default value to return if the attribute is missing. Defaults to `None` >>> class Foo(object): ... bar = 'b...
Audits the provided customer's subscription against stripe and returns a pair that contains a boolean and a result type. Default result types can be found in zebra.conf.defaults and can be overridden in your project's settings. def audit_customer_subscription(customer, unknown=True): """ Audits th...
Use VtkData(<filename>). def polydata_fromfile(f, self): """Use VtkData(<filename>).""" points = [] data = dict(vertices=[], lines=[], polygons=[], triangle_strips=[]) l = common._getline(f).decode('ascii') k,n,datatype = [s.strip().lower() for s in l.split(' ')] if k!='points': raise V...
Handles all known webhooks from stripe, and calls signals. Plug in as you need. def webhooks(request): """ Handles all known webhooks from stripe, and calls signals. Plug in as you need. """ if request.method != "POST": return HttpResponse("Invalid Request.", status=400) json = si...
Handles all known webhooks from stripe, and calls signals. Plug in as you need. def webhooks_v2(request): """ Handles all known webhooks from stripe, and calls signals. Plug in as you need. """ if request.method != "POST": return HttpResponse("Invalid Request.", status=400) try: ...
Check if obj is number. def is_number(obj): """Check if obj is number.""" return isinstance(obj, (int, float, np.int_, np.float_))
Return sequence. def get_seq(self,obj,default=None): """Return sequence.""" if is_sequence(obj): return obj if is_number(obj): return [obj] if obj is None and default is not None: log.warning('using default value (%s)'%(default)) return self.get_seq(d...
Return sequence of sequences. def get_seq_seq(self,obj,default=None): """Return sequence of sequences.""" if is_sequence2(obj): return [self.get_seq(o,default) for o in obj] else: return [self.get_seq(obj,default)]
Return 3-tuple from number -> (obj,default[1],default[2]) 0-sequence|None -> default 1-sequence -> (obj[0],default[1],default[2]) 2-sequence -> (obj[0],obj[1],default[2]) (3 or more)-sequence -> (obj[0],obj[1],obj[2]) def get_3_tuple(self,obj,default=None): """Return 3-t...
Return list of 3-tuples from sequence of a sequence, sequence - it is mapped to sequence of 3-sequences if possible number def get_3_tuple_list(self,obj,default=None): """Return list of 3-tuples from sequence of a sequence, sequence - it is mapped to sequence of 3-sequen...
Return tuple of 3-tuples def get_3_3_tuple(self,obj,default=None): """Return tuple of 3-tuples """ if is_sequence2(obj): ret = [] for i in range(3): if i<len(obj): ret.append(self.get_3_tuple(obj[i],default)) else: ...
Return list of 3x3-tuples. def get_3_3_tuple_list(self,obj,default=None): """Return list of 3x3-tuples. """ if is_sequence3(obj): return [self.get_3_3_tuple(o,default) for o in obj] return [self.get_3_3_tuple(obj,default)]
Iterate through the application configuration and instantiate the services. def connect(self): """Iterate through the application configuration and instantiate the services. """ requested_services = set( svc.lower() for svc in current_app.config.get('BOTO3_SERVICES',...
Get all clients (with and without associated resources) def clients(self): """ Get all clients (with and without associated resources) """ clients = {} for k, v in self.connections.items(): if hasattr(v.meta, 'client'): # has boto3 resource clie...
Configure the GSSAPI service name, and validate the presence of the appropriate principal in the kerberos keytab. :param app: a flask application :type app: flask.Flask :param service: GSSAPI service name :type service: str :param hostname: hostname the service runs under :type hostname: st...
date to unix timestamp in milliseconds def date_to_timestamp(date): """ date to unix timestamp in milliseconds """ date_tuple = date.timetuple() timestamp = calendar.timegm(date_tuple) * 1000 return timestamp
This function will return a random datetime between two datetime objects. :param start: :param end: def random_date(dt_from, dt_to): """ This function will return a random datetime between two datetime objects. :param start: :param end: """ delta = dt_to - dt_from int_delta = (delta...
transform object to json def object_to_json(obj, indent=2): """ transform object to json """ instance_json = json.dumps(obj, indent=indent, ensure_ascii=False, cls=DjangoJSONEncoder) return instance_json
transform QuerySet to json def qs_to_json(qs, fields=None): """ transform QuerySet to json """ if not fields : fields = [f.name for f in qs.model._meta.fields] # сформируем список для сериализации objects = [] for value_dict in qs.values(*fields): # сохраним порядок полей,...
transform mongoengine.QuerySet to json def mongoqs_to_json(qs, fields=None): """ transform mongoengine.QuerySet to json """ l = list(qs.as_pymongo()) for element in l: element.pop('_cls') # use DjangoJSONEncoder for transform date data type to datetime json_qs = json.dumps(l, ind...
join base_url and some GET-parameters to one; it could be absolute url optionally usage example: c['current_url'] = url_path(request, use_urllib=True, is_full=False) ... <a href="{{ current_url }}">Лабораторный номер</a> def url_path(request, base_url=None, is_full=False, *args, **kwargs)...
create string with GET-params of request usage example: c['sort_url'] = url_params(request, except_params=('sort',)) ... <a href="{{ sort_url }}&sort=lab_number">Лабораторный номер</a> def url_params(request, except_params=None, as_is=False): """ create string with GET-params of re...
Prepare sort params. Add revers '-' if need. Params: params - list of sort parameters request sort_key revers_sort - list or set with keys that need reverse default sort direction except_params - GET-params that will be ignored Example: ...
process sort-parameter value (for example, "-name") return: current_param - field for sorting ("name) current_reversed - revers flag (True) def sort_key_process(request, sort_key='sort'): """ process sort-parameter value (for example, "-name") return: cur...
transform form errors to list like ["field1: error1", "field2: error2"] def transform_form_error(form, verbose=True): """ transform form errors to list like ["field1: error1", "field2: error2"] """ errors = [] for field, err_msg in form.errors.items(): if field == '__all...
to_datetime - приводить ли date к datetime default_dt_to - устанавливать заведомо будущее дефолтное значение для dt_to def process_date_from_to_options(options, to_datetime=False, default_dt_to=False): """ to_datetime - приводить ли date к datetime default_dt_to - устанавливать заведомо буд...
Collect data into chunks of up to length n. :type iterable: Iterable[T] :type n: int :rtype: Iterator[list[T]] def _chunked(iterable, n): """ Collect data into chunks of up to length n. :type iterable: Iterable[T] :type n: int :rtype: Iterator[list[T]] """ it = iter(iterable) ...
Look up gender for a list of names. Can optionally refine search with locale info. May make multiple requests if there are more names than can be retrieved in one call. :param names: List of names. :type names: Iterable[str] :param country_id: Optional ISO 3166-1 alpha-2...
Look up gender for a single name. See :py:meth:`get`. Doesn't support retheader option. def get1(self, name, **kwargs): """ Look up gender for a single name. See :py:meth:`get`. Doesn't support retheader option. """ if 'retheader' in kwargs: r...
Hacky convinience function to dump a couple of python variables in a .mat file. See `awmstools.saveVars`. def saveVarsInMat(filename, varNamesStr, outOf=None, **opts): """Hacky convinience function to dump a couple of python variables in a .mat file. See `awmstools.saveVars`. """ from mlabwra...
Creates a proxy for a variable. XXX create and cache nested proxies also here. def _make_proxy(self, varname, parent=None, constructor=MlabObjectProxy): """Creates a proxy for a variable. XXX create and cache nested proxies also here. """ # FIXME why not just use gensym here? ...