text
stringlengths
81
112k
Convert timeout to float. Return None if timeout is None, 0 or 0.0. timeout=None disables timeouts in Requests. def _timeout_to_float(self, timeout): """Convert timeout to float. Return None if timeout is None, 0 or 0.0. timeout=None disables timeouts in Requests. """...
Print the RedBaron syntax tree for a Python module. def main(): """Print the RedBaron syntax tree for a Python module.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("path", help="Python module path") args...
Join a base and a relative path and return an absolute path to the resulting location. Args: base_path: str Relative or absolute path to prepend to ``rel_path``. rel_path: str Path relative to the location of the module file from which this function is called. Returns: ...
Convert a path that is relative to the module from which this function is called, to an absolute path. Args: rel_path: str Path relative to the location of the module file from which this function is called. Returns: str : Absolute path to the location specified by ``rel_path``. def...
Returns: str : Current state of the wrapper as XML def get_xml(self, encoding='unicode'): """Returns: str : Current state of the wrapper as XML """ return xml.etree.ElementTree.tostring(self._root_el, encoding)
Returns: str : Current state of the wrapper as a pretty printed XML string. def get_pretty_xml(self, encoding='unicode'): """Returns: str : Current state of the wrapper as a pretty printed XML string. """ return d1_common.xml.reformat_to_pretty_xml( xml.etree.Elem...
Args: el_name : str Name of element that is the base of the branch to retrieve. el_idx : int Index of element to use as base in the event that there are multiple sibling elements with the same name. Returns: str : XML fragment rooted at ``el``. def get_xml_below_element(...
Args: xpath_str : str XPath matching the elements for which to search. Returns: list : List of elements matching ``xpath_str``. If there are no matching elements, an empty list is returned. def get_element_by_xpath(self, xpath_str, namespaces=None): """ Args: xpath_str...
Args: el_name : str Name of element to get. el_idx : int Index of element to use as base in the event that there are multiple sibling elements with the same name. Returns: element : The selected element. def get_element_by_name(self, el_name, el_idx=0): """ A...
Args: attr_key : str Name of attribute for which to search el_idx : int Index of element to use as base in the event that there are multiple sibling elements with the same name. Returns: Element containing an attribute key named ``attr_key``. def get_element_by_attr_key(...
Args: el_name : str Name of element to update. el_text : str Text to set for element. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. def set_element_text(self, el_name, el_text, el_idx=0): """ ...
Args: attr_key : str Name of attribute for which to search el_text : str Text to set for element. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. def set_element_text_by_attr_key(self, attr_key, el_text, ...
Return the value of the selected attribute in the selected element. Args: attr_key : str Name of attribute for which to search el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. Returns...
Set the value of the selected attribute of the selected element. Args: attr_key : str Name of attribute for which to search attr_val : str Text to set for the attribute. el_idx : int Index of element to use in the event that there are multiple...
Return the text of the selected element as a ``datetime.datetime`` object. The element text must be a ISO8601 formatted datetime Args: el_name : str Name of element to use. tz : datetime.tzinfo Timezone in which to return the datetime. - Withou...
Set the text of the selected element to an ISO8601 formatted datetime. Args: el_name : str Name of element to update. dt : datetime.datetime Date and time to set tz : datetime.tzinfo Timezone to set - Without a timezone, other con...
Replace element. Select element that has the same name as ``root_el``, then replace the selected element with ``root_el`` ``root_el`` can be a single element or the root of an element tree. Args: root_el : element New element that will replace the existing elemen...
Replace element. Select element that has the same name as ``xml_str``, then replace the selected element with ``xml_str`` - ``xml_str`` must have a single element in the root. - The root element in ``xml_str`` can have an arbitrary number of children. Args: xml_str :...
Compile SQL for this function. def as_sql(self, compiler, connection): # pylint: disable=arguments-differ """Compile SQL for this function.""" sql, params = super().as_sql(compiler, connection) params.append(self.path) return sql, params
Annotate Storage objects with a specific JSON path. :param path: Path to get inside the stored object, which can be either a list of path components or a comma-separated string :param field: Optional output field name def with_json_path(self, path, field=None): """Annot...
Return only a specific JSON path of Storage objects. :param path: Path to get inside the stored object, which can be either a list of path components or a comma-separated string def get_json_path(self, path): """Return only a specific JSON path of Storage objects. :par...
Load `json` field from `Storage` object. def _get_storage(self): """Load `json` field from `Storage` object.""" if self._json is None: self._json = Storage.objects.get(**self._kwargs).json
Perform forward migration. def database_forwards(self, app_label, schema_editor, from_state, to_state): """Perform forward migration.""" Process = from_state.apps.get_model('flow', 'Process') # pylint: disable=invalid-name Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=inv...
Deconstruct operation. def deconstruct(self): """Deconstruct operation.""" return ( self.__class__.__name__, [], { 'process': self.process, 'field': self._raw_field, 'schema': self.schema, 'default': sel...
Migrate process schema. :param process: Process instance :param schema: Process schema to migrate :param from_state: Database model state :return: True if the process was migrated, False otherwise def migrate_process_schema(self, process, schema, from_state): """Migrate process...
Migrate data objects. :param data: Queryset containing all data objects that need to be migrated :param from_state: Database model state def migrate_data(self, data, from_state): """Migrate data objects. :param data: Queryset containing all data objects that need ...
Deconstruct operation. def deconstruct(self): """Deconstruct operation.""" return ( self.__class__.__name__, [], { 'process': self.process, 'field': self._raw_field, 'new_field': self.new_field, } )
Migrate process schema. :param process: Process instance :param schema: Process schema to migrate :param from_state: Database model state :return: True if the process was migrated, False otherwise def migrate_process_schema(self, process, schema, from_state): """Migrate process...
Migrate data objects. :param data: Queryset containing all data objects that need to be migrated :param from_state: Database model state def migrate_data(self, data, from_state): """Migrate data objects. :param data: Queryset containing all data objects that need ...
Perform forward migration. def database_forwards(self, app_label, schema_editor, from_state, to_state): """Perform forward migration.""" from resolwe.flow.models.data import DataQuerySet # pylint: disable=protected-access Data = from_state.apps.get_model('flow', 'Data') # pylint: disa...
Perform forward migration. def database_forwards(self, app_label, schema_editor, from_state, to_state): """Perform forward migration.""" from resolwe.flow.models.data import DataQuerySet # pylint: disable=protected-access Data = from_state.apps.get_model('flow', 'Data') # pylint: disa...
Migrate process schema. :param process: Process instance :param schema: Process schema to migrate :param from_state: Database model state :return: True if the process was migrated, False otherwise def migrate_process_schema(self, process, schema, from_state): """Migrate process...
Perform forward migration. def database_forwards(self, app_label, schema_editor, from_state, to_state): """Perform forward migration.""" Process = from_state.apps.get_model('flow', 'Process') # pylint: disable=invalid-name # Validate process types to ensure consistency. errors = valid...
Home page. Root of web server should redirect to here. def home(request): """Home page. Root of web server should redirect to here. """ if request.path.endswith('/'): return django.http.HttpResponseRedirect(request.path[:-1]) return django.http.HttpResponse( generate_status_...
Handle 404s outside of the valid API URL endpoints Note: Cannot raise NotFound() here, as this method is not covered by the GMN middleware handler that catches DataONE exceptions raised by normal views. def error_404(request, exception): """Handle 404s outside of the valid API URL endpoints Note: Cannot ra...
Return total free space available on the disk on which the object storage resides (in bytes) def get_obj_store_free_space_bytes(): """Return total free space available on the disk on which the object storage resides (in bytes)""" obj_store_path = django.conf.settings.OBJECT_STORE_PATH if platform.s...
Function to numerically determine the physical Higgs VEV and mass given the parameters of the Higgs potential. def m2Lambda_to_vMh2(m2, Lambda, C): """Function to numerically determine the physical Higgs VEV and mass given the parameters of the Higgs potential.""" try: v = (sqrt(2 * m2 / Lamb...
Function to numerically determine the parameters of the Higgs potential given the physical Higgs VEV and mass. def vMh2_to_m2Lambda(v, Mh2, C): """Function to numerically determine the parameters of the Higgs potential given the physical Higgs VEV and mass.""" if C['phi'] == 0 and C['phiBox'] == 0 and ...
r"""Function to numerically determine the hypercharge gauge coupling in terms of $\bar e$, $\bar g$, v, and the Wilson coefficients. def get_gpbar(ebar, gbar, v, C): r"""Function to numerically determine the hypercharge gauge coupling in terms of $\bar e$, $\bar g$, v, and the Wilson coefficients.""" i...
Get the running parameters in SMEFT. def smeftpar(scale, C, basis): """Get the running parameters in SMEFT.""" # start with a zero dict and update it with the input values MW = p['m_W'] # MZ = p['m_Z'] GF = p['GF'] Mh = p['m_h'] vb = sqrt(1 / sqrt(2) / GF) v = vb # TODO _d = vMh2_t...
Get the running effective SM parameters. def smpar(C): """Get the running effective SM parameters.""" m2 = C['m2'].real Lambda = C['Lambda'].real v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) / (sqrt(2) * Lambda**(5 / 2)) * C['phi']) GF = 1 / (sqrt(2) * v**2) # TODO Mh2 = 2 * m2 * (1 -...
Translations necessary for class-8 coefficients to go from a basis with only non-redundant WCxf operators to a basis where the Wilson coefficients are symmetrized like the operators. def scale_8(b): """Translations necessary for class-8 coefficients to go from a basis with only non-redundant WCxf ...
Symmetrize the Wilson coefficient arrays. Note that this function does not take into account the symmetry factors that occur when transitioning from a basis with only non-redundant operators (like in WCxf) to a basis where the Wilson coefficients are symmetrized like the operators. See `symmetrize_nonr...
Convert a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values to a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values. This is needed for the output in WCxf format. def arrays2wcxf(C): """Convert a dictio...
Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values. This is needed for the parsing of input in WCxf format. def wcxf2arrays(d): """Co...
Add arrays with zeros for missing Wilson coefficient keys def add_missing(C): """Add arrays with zeros for missing Wilson coefficient keys""" C_out = C.copy() for k in (set(WC_keys) - set(C.keys())): C_out[k] = np.zeros(C_keys_shape[k]) return C_out
Convert a 1D array containing C values to a dictionary. def C_array2dict(C): """Convert a 1D array containing C values to a dictionary.""" d = OrderedDict() i=0 for k in C_keys: s = C_keys_shape[k] if s == 1: j = i+1 d[k] = C[i] else: j = i \ ...
Convert an OrderedDict containing C values to a 1D array. def C_dict2array(C): """Convert an OrderedDict containing C values to a 1D array.""" return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])
Symmetrize the Wilson coefficient arrays. This function takes into account the symmetry factors that occur when transitioning from a basis with only non-redundant operators (like in WCxf) to a basis where the Wilson coefficients are symmetrized like the operators. def symmetrize_nonred(C): """Symm...
Undo the scaling applied in `scale_dict`. def unscale_dict(C): """Undo the scaling applied in `scale_dict`.""" C_out = {k: _scale_dict[k] * v for k, v in C.items()} for k in C_symm_keys[8]: C_out['qqql'] = unscale_8(C_out['qqql']) return C_out
Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values. In contrast to `wcxf2arrays`, here the numpy arrays fulfill the same symmetry re...
Nudge manager at the end of every Data object save event. def commit_signal(data_id): """Nudge manager at the end of every Data object save event.""" if not getattr(settings, 'FLOW_MANAGER_DISABLE_AUTO_CALLS', False): immediate = getattr(settings, 'FLOW_MANAGER_SYNC_AUTO_CALLS', False) async_to...
Run newly created (spawned) processes. def manager_post_save_handler(sender, instance, created, **kwargs): """Run newly created (spawned) processes.""" if instance.status == Data.STATUS_DONE or instance.status == Data.STATUS_ERROR or created: # Run manager at the end of the potential transaction. Other...
Delete Entity when last Data object is deleted. def delete_entity(sender, instance, **kwargs): """Delete Entity when last Data object is deleted.""" # 1 means that the last Data object is going to be deleted. Entity.objects.annotate(num_data=Count('data')).filter(data=instance, num_data=1).delete()
Delete the Relation object when the last Entity is removed. def delete_relation(sender, instance, **kwargs): """Delete the Relation object when the last Entity is removed.""" def process_signal(relation_id): """Get the relation and delete it if it has no entities left.""" try: relat...
Start the actual execution; instantiate the executor and run. async def run_executor(): """Start the actual execution; instantiate the executor and run.""" parser = argparse.ArgumentParser(description="Run the specified executor.") parser.add_argument('module', help="The module from which to instantiate th...
Validate file at {sciobj_path} against schema selected via formatId and raise InvalidRequest if invalid. Validation is only performed when: - SciMeta validation is enabled - and Object size is below size limit for validation - and formatId designates object as a Science Metadata object which is re...
Perform application initialization. def ready(self): """Perform application initialization.""" # Initialize the type extension composer. from . composer import composer composer.discover_extensions() is_migrating = sys.argv[1:2] == ['migrate'] if is_migrating: ...
Convert to internal value. def to_internal_value(self, data): """Convert to internal value.""" user = getattr(self.context.get('request'), 'user') queryset = self.get_queryset() permission = get_full_perm('view', queryset.model) try: return get_objects_for_user( ...
Dump the dict to json in DynamoDB Format You can use any other simplejson or json options :param dct - the dict to dump :param as_dict - returns the result as python dict (useful for DynamoDB boto3 library) or as json sting :returns: DynamoDB json format. def dumps(dct, as_dict=False, *...
DynamoDB object hook to return python values def object_hook(dct): """ DynamoDB object hook to return python values """ try: # First - Try to parse the dct as DynamoDB parsed if 'BOOL' in dct: return dct['BOOL'] if 'S' in dct: val = dct['S'] try: ...
Loads dynamodb json format to a python dict. :param s - the json string or dict (with the as_dict variable set to True) to convert :returns python dict object def loads(s, as_dict=False, *args, **kwargs): """ Loads dynamodb json format to a python dict. :param s - the json string or dict (w...
Returns the size (in meters) of a tile def tileSize(self, zoom): "Returns the size (in meters) of a tile" assert zoom in range(0, len(self.RESOLUTIONS)) return self.tileSizePx * self.RESOLUTIONS[int(zoom)]
Returns the bounds of a tile in LV03 (EPSG:21781) def tileBounds(self, zoom, tileCol, tileRow): "Returns the bounds of a tile in LV03 (EPSG:21781)" assert zoom in range(0, len(self.RESOLUTIONS)) # 0,0 at top left: y axis down and x axis right tileSize = self.tileSize(zoom) minX...
Returns a tile address based on a zoom level and \ a point in the tile def tileAddress(self, zoom, point): "Returns a tile address based on a zoom level and \ a point in the tile" [x, y] = point assert x <= self.MAXX and x >= self.MINX assert y <= self.MAXY and y >= self...
Determine if an extent intersects this instance extent def intersectsExtent(self, extent): "Determine if an extent intersects this instance extent" return \ self.extent[0] <= extent[2] and self.extent[2] >= extent[0] and \ self.extent[1] <= extent[3] and self.extent[3] >= extent...
Yields the tileBounds, zoom, tileCol and tileRow def iterGrid(self, minZoom, maxZoom): "Yields the tileBounds, zoom, tileCol and tileRow" assert minZoom in range(0, len(self.RESOLUTIONS)) assert maxZoom in range(0, len(self.RESOLUTIONS)) assert minZoom <= maxZoom for zoom in xr...
Returns the number of tiles over x at a given zoom level def numberOfXTilesAtZoom(self, zoom): "Returns the number of tiles over x at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return maxCol - minCol + 1
Retruns the number of tiles over y at a given zoom level def numberOfYTilesAtZoom(self, zoom): "Retruns the number of tiles over y at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return maxRow - minRow + 1
Returns the total number of tile at a given zoom level def numberOfTilesAtZoom(self, zoom): "Returns the total number of tile at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return (maxCol - minCol + 1) * (maxRow - minRow + 1)
Return the total number of tiles for this instance extent def totalNumberOfTiles(self, minZoom=None, maxZoom=None): "Return the total number of tiles for this instance extent" nbTiles = 0 minZoom = minZoom or 0 if maxZoom: maxZoom = maxZoom + 1 else: maxZ...
Return the zoom level for a given resolution def getZoom(self, resolution): "Return the zoom level for a given resolution" assert resolution in self.RESOLUTIONS return self.RESOLUTIONS.index(resolution)
Return lower and higher zoom level given a resolution def _getZoomLevelRange(self, resolution, unit='meters'): "Return lower and higher zoom level given a resolution" assert unit in ('meters', 'degrees') if unit == 'meters' and self.unit == 'degrees': resolution = resolution / self....
Return the closest zoom level for a given resolution Parameters: resolution -- max. resolution unit -- unit for output (default='meters') def getClosestZoom(self, resolution, unit='meters'): """ Return the closest zoom level for a given resolution Parameters: ...
Return the maximized zoom level for a given resolution Parameters: resolution -- max. resolution unit -- unit for output (default='meters') def getCeilingZoom(self, resolution, unit='meters'): """ Return the maximized zoom level for a given resolution Parameters:...
Returns the scale at a given zoom level def getScale(self, zoom): """Returns the scale at a given zoom level""" if self.unit == 'degrees': resolution = self.getResolution(zoom) * EPSG4326_METERS_PER_UNIT else: resolution = self.getResolution(zoom) return resoluti...
Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based on the instance's extent or a user defined extent. Generic method that works with regular and irregular pyramids. Parameters: zoom -- the zoom for which we want the bounding addresses extent (optional) ...
Return the parent tile(s) for an irregular (not following quadindex) and regular tiling scheme Parameters: zoom -- the zoom level a the child tile row -- the row of the child tile col -- the col of the child tile zoomParent -- the target zoom of the parent...
Enable loggly if it is configured and not debug/testing. def enable_loggly(graph): """ Enable loggly if it is configured and not debug/testing. """ if graph.metadata.debug or graph.metadata.testing: return False try: if not graph.config.logging.loggly.token: return Fal...
Build a dictionary configuration from conventions and configuration. def make_dict_config(graph): """ Build a dictionary configuration from conventions and configuration. """ formatters = {} handlers = {} loggers = {} # create the console handler formatters["ExtraFormatter"] = make_ex...
Create the default json formatter. def make_json_formatter(graph): """ Create the default json formatter. """ return { "()": graph.config.logging.json_formatter.formatter, "fmt": graph.config.logging.json_required_keys, }
Create the stream handler. Used for console/debug output. def make_stream_handler(graph, formatter): """ Create the stream handler. Used for console/debug output. """ return { "class": graph.config.logging.stream_handler.class_, "formatter": formatter, "level": graph.config.log...
Create the loggly handler. Used for searchable aggregation. def make_loggly_handler(graph, formatter): """ Create the loggly handler. Used for searchable aggregation. """ base_url = graph.config.logging.loggly.base_url loggly_url = "{}/inputs/{}/tag/{}".format( base_url, ...
Create third party library logging level configurations. Tunes down overly verbose logs in commonly used libraries. def make_library_levels(graph): """ Create third party library logging level configurations. Tunes down overly verbose logs in commonly used libraries. """ # inject the default...
Redirects the current request if there is a matching Redirect model with the current request URL as the old_path field. def process_request(self, request): """ Redirects the current request if there is a matching Redirect model with the current request URL as the old_path field. ...
The results of context_func will be executed and applied to a ContextLogger instance for the execution of func. The resulting ContextLogger instance will be available on parent.logger for the duration of func. :param context_func: callable which provides dictionary-like context information :param func:...
Monkey patched version of Django's SiteManager.get_current() function. Returns the current Site based on a given request or the SITE_ID in the project's settings. If a request is given attempts to match a site with domain matching request.get_host(). If a request is not given or a site cannot be found ...
Monkey patched version of Django's SiteManager._get_site_by_id() function. Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site. This allows for the use of an in-memory cache for Site models, avoiding one or more DB hits on every request made to the Django application, but also allo...
Monkey patched version of Django's SiteManager._get_site_by_request() function. Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site. This allows for the use of an in-memory cache for Site models, avoiding one or more DB hits on every request made to the Django application, but also...
Truncates a string, starting from 'lim' chars. The given object can be a string, or something that can be casted to a string. >>> import string >>> str_brief(string.uppercase) 'ABCDEFGHIJKLMNOPQRST...' >>> str_brief(2 ** 50, lim=10, dots='0') '11258999060' def str_brief(obj, lim=20, dots='...'...
returns a map volume_name -> volume, cg_name->cg scope is either None or CG or Volume def get_mirror_resources_by_name_map(self, scope=None): """ returns a map volume_name -> volume, cg_name->cg scope is either None or CG or Volume """ volumes_mirrors_by_name = dict...
return a list of the port names of XIV host def get_host_port_names(self, host_name): """ return a list of the port names of XIV host """ port_names = list() host = self.get_hosts_by_name(host_name) fc_ports = host.fc_ports iscsi_ports = host.iscsi_ports port_names...
return a list of the port names under XIV CLuster def get_cluster_port_names(self, cluster_name): """ return a list of the port names under XIV CLuster """ port_names = list() for host_name in self.get_hosts_by_clusters()[cluster_name]: port_names.extend(self.get_hosts_by_name(h...
remove all stale clients from pool def flush(self): """remove all stale clients from pool""" now = time.time() to_remove = [] for k, entry in self.pool.items(): if entry.timestamp < now: entry.client.close() to_remove.append(k) for k i...
Gets an existing connection or opens a new one def get(self, user, password, endpoints): """Gets an existing connection or opens a new one """ now = time.time() # endpoints can either be str or list if isinstance(endpoints, str): endpoints = [endpoints] for e...
>>> size(1024) '1 KB' def size(value: int, suffixes: list = None) -> str: """ >>> size(1024) '1 KB' """ suffixes = suffixes or [ 'bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] order = int(log2(value) / 10) if value else 0 return '{:.4g} {}'.format(value / (1 << (order ...
>>> parse_size('1M') 1048576 >>> parse_size('512K512K') 1048576 >>> parse_size('512K 512K') 1048576 >>> parse_size('512K 512K 4') 1048580 def parse_size(value): """ >>> parse_size('1M') 1048576 >>> parse_size('512K512K') 1048576 >>> parse_size('512K 512K') 104857...
>>> parse_duration('1h') 3600 >>> parse_duration('1m') 60 >>> parse_duration('1m 2s') 62 >>> parse_duration('1') 1 def parse_duration(value): """ >>> parse_duration('1h') 3600 >>> parse_duration('1m') 60 >>> parse_duration('1m 2s') 62 >>> parse_duration('1') ...
send css_event and if fails send custom_event instead Args: action (ACTIONS): the action causing the event properties (dict): the action additional properties event_severity (string): the event severity Raises: XCLIError: if the xcli.cmd.custom_event faile...
creates a mirror and returns a mirror object. resource_type must be 'vol' or 'cg', target name must be a valid target from target_list, mirror type must be 'sync' or 'async', slave_resource_name would be the slave_vol or slave_cg name def _create_mirror(self, resourc...