code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def member_of(self, group): if isinstance(group, Group): group = group.name return self.groups.filter(name=group).exists()
Returns whether a user is a member of a certain group. Args: group The name of a group (string) or a group object Returns: Boolean
def install(self): domain_settings = DomainSettings.get() with root(): if os.path.exists(self.SMBCONF_FILE): os.remove(self.SMBCONF_FILE) if domain_settings.mode == 'ad': domain_settings.adminpass = make_password(15) domain_settings...
Installation procedure, it writes basic smb.conf and uses samba-tool to provision the domain
def fingerprint(self): if self.num_vertices == 0: return np.zeros(20, np.ubyte) else: return sum(self.vertex_fingerprints)
A total graph fingerprint The result is invariant under permutation of the vertex indexes. The chance that two different (molecular) graphs yield the same fingerprint is small but not zero. (See unit tests.)
def get_package_name_in_pipfile(self, package_name, dev=False): key = "dev-packages" if dev else "packages" section = self.parsed_pipfile.get(key, {}) package_name = pep423_name(package_name) for name in section.keys(): if pep423_name(name) == package_name: re...
Get the equivalent package name in pipfile
def _walk_modules(modules, class_name, path, ignored_formats, args): for module in _iter_modules(modules=modules, class_name=class_name, path=path, ignored_formats=ignored_formats, args=ar...
Helper generator that traverses modules in returns a flattened iterator.
def whitespace_around_keywords(logical_line): r for match in KEYWORD_REGEX.finditer(logical_line): before, after = match.groups() if '\t' in before: yield match.start(1), "E274 tab before keyword" elif len(before) > 1: yield match.start(1), "E272 multiple spaces b...
r"""Avoid extraneous whitespace around keywords. Okay: True and False E271: True and False E272: True and False E273: True and\tFalse E274: True\tand False
def _fetch_options(self, merge): cmd = tuple() for option in FETCH_DEFAULTS: value = merge.get(option, self.defaults.get(option)) if value: cmd += ("--%s" % option, str(value)) return cmd
Get the fetch options from the given merge dict.
def get_urls(self): urls = super(TreeAdmin, self).get_urls() if django.VERSION < (1, 10): from django.views.i18n import javascript_catalog jsi18n_url = url(r'^jsi18n/$', javascript_catalog, {'packages': ('treebeard',)}) else: from django.views.i18n import Java...
Adds a url to move nodes to this admin
def get_marathon_task( task_name, inactive=False, completed=False ): return get_service_task('marathon', task_name, inactive, completed)
Get a dictionary describing a named marathon task
def get_type(self, idx): _type = self.get_type_ref(idx) if _type == -1: return "AG:ITI: invalid type" return self.get_string(_type)
Return the resolved type name based on the index This returns the string associated with the type. :param int idx: :return: the type name :rtype: str
def _aggregate_metrics(self, session_group): if (self._request.aggregation_type == api_pb2.AGGREGATION_AVG or self._request.aggregation_type == api_pb2.AGGREGATION_UNSET): _set_avg_session_metrics(session_group) elif self._request.aggregation_type == api_pb2.AGGREGATION_MEDIAN: _set_median_s...
Sets the metrics of the group based on aggregation_type.
def _request(self, method, body=None, raise_exc=True, headers=None, files=None): headers = headers or {} if body and 'Content-Type' not in headers: headers.update({'Content-Type': 'application/json'}) response = self._core.session.request( method, self.uri, ...
Fetches HTTP response using the passed http method. Raises HALNavigatorError if response is in the 400-500 range.
def copy(self, new_grab=None): obj = self.__class__() obj.process_grab(new_grab if new_grab else self.grab) copy_keys = ('status', 'code', 'head', 'body', 'total_time', 'connect_time', 'name_lookup_time', 'url', 'charset', '_unicode_body', ...
Clone the Response object.
def _get_broadcasts(tables): tables = set(tables) casts = tz.keyfilter( lambda x: x[0] in tables and x[1] in tables, _BROADCASTS) if tables - set(tz.concat(casts.keys())): raise ValueError('Not enough links to merge all tables.') return casts
Get the broadcasts associated with a set of tables. Parameters ---------- tables : sequence of str Table names for which broadcasts have been registered. Returns ------- casts : dict of `Broadcast` Keys are tuples of strings like (cast_name, onto_name).
def get(self, request): sections = self.generate_sections() if self.paginated: p = Paginator(sections, 25) page = request.GET.get('page') try: sections = p.page(page) except PageNotAnInteger: sections = p.page(1) ...
View for HTTP GET method. Returns template and context from generate_page_title and generate_sections to populate template.
def mouse_press_event(self, x, y, button): if button == 1: print("Left mouse button pressed @", x, y) if button == 2: print("Right mouse button pressed @", x, y)
Reports left and right mouse button presses + position
def add_metric_group_definition(self, definition): assert isinstance(definition, FakedMetricGroupDefinition) group_name = definition.name if group_name in self._metric_group_defs: raise ValueError("A metric group definition with this name " "already exist...
Add a faked metric group definition. The definition will be used: * For later addition of faked metrics responses. * For returning the metric-group-info objects in the response of the Create Metrics Context operations. For defined metric groups, see chapter "Metric groups" i...
def as_dict(self): d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "structure": self.structure.as_dict(), "frequencies": list(self.frequencies), "densities": list(self.densities), "pdos": []} if len(self.pdos)...
Json-serializable dict representation of CompletePhononDos.
def param_redirect(request, viewname, *args): url = reverse(viewname, PARAMS_URL_CONF, args) params = request.GET.urlencode().split('&') if hasattr(request, 'cparam'): for k, v in request.cparam.items(): params.append('{0}={1}'.format(k, v)) new_params = '&'.join(x for x in params if...
Redirect and keep URL parameters if any.
def _close_pidfile(self): if self._pid_fd is not None: os.close(self._pid_fd) try: os.remove(self.pidfile) except OSError as ex: if ex.errno != errno.ENOENT: raise
Closes and removes the PID file.
def ToOBMag(self, wave, flux, area=None): area = area if area else refs.PRIMARY_AREA bin_widths = \ binning.calculate_bin_widths(binning.calculate_bin_edges(wave)) arg = flux * bin_widths * area return -1.085736 * N.log(arg)
Convert to ``obmag``. .. math:: \\textnormal{obmag} = -2.5 \\; \\log(\\delta \\lambda \\; \\times \\; \\textnormal{area} \\; \\times \\; \\textnormal{photlam}) where :math:`\\delta \\lambda` represent bin widths derived from :func:`~pysynphot.binning.calculate_bin_edges` and ...
def serialize_to_file( root_processor, value, xml_file_path, encoding='utf-8', indent=None ): serialized_value = serialize_to_string(root_processor, value, indent) with open(xml_file_path, 'w', encoding=encoding) as xml_file: xml_file.write(serialized_value)
Serialize the value to an XML file using the root processor. :param root_processor: Root processor of the XML document. :param value: Value to serialize. :param xml_file_path: Path to the XML file to which the serialized value will be written. :param encoding: Encoding of the file. :param indent: I...
def build_pipelines_lsst_io_configs(*, project_name, copyright=None): sys.setrecursionlimit(2000) c = {} c = _insert_common_sphinx_configs( c, project_name=project_name) c = _insert_html_configs( c, project_name=project_name, short_project_name=project_name) c...
Build a `dict` of Sphinx configurations that populate the ``conf.py`` of the main pipelines_lsst_io Sphinx project for LSST Science Pipelines documentation. The ``conf.py`` file can ingest these configurations via:: from documenteer.sphinxconfig.stackconf import \ build_pipelines_lsst_io...
def wait(self, *, block=True, timeout=None): cleared = not self.backend.decr(self.key, 1, 1, self.ttl) if cleared: self.backend.wait_notify(self.key_events, self.ttl) return True if block: return self.backend.wait(self.key_events, timeout) return False
Signal that a party has reached the barrier. Warning: Barrier blocking is currently only supported by the stub and Redis backends. Warning: Re-using keys between blocking calls may lead to undefined behaviour. Make sure your barrier keys are always unique ...
def get_graphql_schema_from_orientdb_schema_data(schema_data, class_to_field_type_overrides=None, hidden_classes=None): if class_to_field_type_overrides is None: class_to_field_type_overrides = dict() if hidden_classes is None: hidden_classes = se...
Construct a GraphQL schema from an OrientDB schema. Args: schema_data: list of dicts describing the classes in the OrientDB schema. The following format is the way the data is structured in OrientDB 2. See the README.md file for an example of how to query this data...
def has_publish_permission(self, request, obj=None): if is_automatic_publishing_enabled(self.model): return False user_obj = request.user if not user_obj.is_active: return False if user_obj.is_superuser: return True if user_obj.has_perm('%s.can...
Determines if the user has permissions to publish. :param request: Django request object. :param obj: The object to determine if the user has permissions to publish. :return: Boolean.
def azureContainerSAS(self, *args, **kwargs): return self._makeApiCall(self.funcinfo["azureContainerSAS"], *args, **kwargs)
Get Shared-Access-Signature for Azure Container Get a shared access signature (SAS) string for use with a specific Azure Blob Storage container. The `level` parameter can be `read-write` or `read-only` and determines which type of credentials are returned. If level is read-write, it w...
def css_number(self, path, default=NULL, ignore_spaces=False, smart=False, make_int=True): try: text = self.css_text(path, smart=smart) return find_number(text, ignore_spaces=ignore_spaces, make_int=make_int) except IndexError: ...
Find number in normalized text of node which matches the given css path.
def predict(self, date, obs_code=568): time = Time(date, scale='utc', precision=6) jd = ctypes.c_double(time.jd) self.orbfit.predict.restype = ctypes.POINTER(ctypes.c_double * 5) self.orbfit.predict.argtypes = [ ctypes.c_char_p, ctypes.c_double, ctypes.c_int ] predict = self.orbf...
use the bk predict method to compute the location of the source on the given date.
def average_datetimes(dt_list): if sys.version_info < (3, 3): import time def timestamp_func(dt): return time.mktime(dt.timetuple()) else: timestamp_func = datetime.timestamp total = [timestamp_func(dt) for dt in dt_list] return datetime.fromtimestamp(sum(total) / len...
Average a series of datetime objects. .. note:: This function assumes all datetime objects are naive and in the same time zone (UTC). Args: dt_list (iterable): Datetime objects to average Returns: Average datetime as a datetime object
def marginalize_out(node_indices, tpm): return tpm.sum(tuple(node_indices), keepdims=True) / ( np.array(tpm.shape)[list(node_indices)].prod())
Marginalize out nodes from a TPM. Args: node_indices (list[int]): The indices of nodes to be marginalized out. tpm (np.ndarray): The TPM to marginalize the node out of. Returns: np.ndarray: A TPM with the same number of dimensions, with the nodes marginalized out.
def _get_per_location_glob(tasks, outputs, regexes): paths = [o.path for o in outputs] matches = [r.search(p) for r, p in zip(regexes, paths)] for m, p, t in zip(matches, paths, tasks): if m is None: raise NotImplementedError("Couldn't deduce datehour representation in output path %r of ...
Builds a glob listing existing output paths. Esoteric reverse engineering, but worth it given that (compared to an equivalent contiguousness guarantee by naive complete() checks) requests to the filesystem are cut by orders of magnitude, and users don't even have to retrofit existing tasks anyhow.
def reader(stream): string = stream.read() decoder = json.JSONDecoder().raw_decode index = START.match(string, 0).end() while index < len(string): obj, end = decoder(string, index) item = Item() item.primitive = obj yield item index = END.match(string, end).end()
Read Items from a stream containing a JSON array.
def has_files(the_path): the_path = Path(the_path) try: for _ in the_path.walkfiles(): return True return False except OSError as ex: if ex.errno == errno.ENOENT: return False else: raise
Given a path, returns whether the path has any files in it or any subfolders. Works recursively.
def search_nn(self, point, dist=None): return next(iter(self.search_knn(point, 1, dist)), None)
Search the nearest node of the given point point must be an actual point, not a node. The nearest node to the point is returned. If a location of an actual node is used, the Node with this location will be returned (not its neighbor). dist is a distance function, expecting two points a...
def polarity_as_string(self, add_colour=True): with self._mutex: if self.polarity == self.PROVIDED: result = 'Provided', ['reset'] elif self.polarity == self.REQUIRED: result = 'Required', ['reset'] if add_colour: return utils.b...
Get the polarity of this interface as a string. @param add_colour If True, ANSI colour codes will be added to the string. @return A string describing the polarity of this interface.
def fit_row(connection, row, unique_keys): new_columns = [] for column_name, column_value in list(row.items()): new_column = sqlalchemy.Column(column_name, get_column_type(column_value)) if not column_name in list(_State.table.columns.keys()): n...
Takes a row and checks to make sure it fits in the columns of the current table. If it does not fit, adds the required columns.
def fetch_coords(self, query): q = query.add_query_parameter(req='coord') return self._parse_messages(self.get_query(q).content)
Pull down coordinate data from the endpoint.
def element_should_be_disabled(self, locator, loglevel='INFO'): if self._element_find(locator, True, True).is_enabled(): self.log_source(loglevel) raise AssertionError("Element '%s' should be disabled " "but did not" % locator) self._info("El...
Verifies that element identified with locator is disabled. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements.
def del_functions(self, names): if isinstance(names, string_types): names = [names] for name in names: self._functionlib.pop(name)
Removes the specified function names from the function library. Functions are removed from this instance of the array; all copies and slices of this array will also have the functions removed. Parameters ---------- names : (list of) string(s) Name or list of names o...
def _check_pool_attr(self, attr, req_attr=None): if req_attr is None: req_attr = [] self._check_attr(attr, req_attr, _pool_attrs) if attr.get('ipv4_default_prefix_length') is not None: try: attr['ipv4_default_prefix_length'] = \ int(att...
Check pool attributes.
def do_GET(self): if self.path.endswith("http_manifest.json"): try: manifest = self.generate_http_manifest() self.send_response(200) self.end_headers() self.wfile.write(manifest) except dtoolcore.DtoolCoreTypeError: ...
Override inherited do_GET method. Include logic for returning a http manifest when the URL ends with "http_manifest.json".
def installedApp(self): try: return self._installedApp except: self._installedApp = runConfigs.get() return self._installedApp
identify the propery application to launch, given the configuration
def iter_ensure_instance(iterable, types): ensure_instance(iterable, Iterable) [ ensure_instance(item, types) for item in iterable ]
Iterate over object and check each item type >>> iter_ensure_instance([1,2,3], [str]) Traceback (most recent call last): TypeError: >>> iter_ensure_instance([1,2,3], int) >>> iter_ensure_instance(1, int) Traceback (most recent call last): TypeError:
def is_equal(self, other): other = StringCell.coerce(other) empties = [None,''] if self.value in empties and other.value in empties: return True return self.value == other.value
Whether two strings are equal
def _handle_request_noblock(self): try: request, client_address = self.get_request() except socket.error: return if self.verify_request(request, client_address): try: self.process_request(request, client_address) except: ...
Handle one request, without blocking.
def __pathToTuple(self, path): if not path or path.count('/') > 2: raise YTFS.PathConvertError("Bad path given") try: split = path.split('/') except (AttributeError, TypeError): raise TypeError("Path has to be string") if split[0]: raise YT...
Convert directory or file path to its tuple identifier. Parameters ---------- path : str Path to convert. It can look like /, /directory, /directory/ or /directory/filename. Returns ------- tup_id : tuple Two element tuple identifier of directory...
def _get_template(querystring_key, mapping): default = None try: template_and_keys = mapping.items() except AttributeError: template_and_keys = mapping for template, key in template_and_keys: if key is None: key = PAGE_LABEL default = template if k...
Return the template corresponding to the given ``querystring_key``.
def wait(self, timeout=None): self.__stopped.wait(timeout) return self.__stopped.is_set()
Waits for the client to stop its loop
def ExecuteCommandFromClient(command): cmd = command.cmd args = command.args time_limit = command.time_limit res = client_utils_common.Execute(cmd, args, time_limit) (stdout, stderr, status, time_used) = res stdout = stdout[:10 * 1024 * 1024] stderr = stderr[:10 * 1024 * 1024] yield rdf_client_action.Ex...
Executes one of the predefined commands. Args: command: An `ExecuteRequest` object. Yields: `rdf_client_action.ExecuteResponse` objects.
def can_process_matrix(entry, matrix_tags): if len(matrix_tags) == 0: return True count = 0 if 'tags' in entry: for tag in matrix_tags: if tag in entry['tags']: count += 1 return count > 0
Check given matrix tags to be in the given list of matric tags. Args: entry (dict): matrix item (in yaml). matrix_tags (list): represents --matrix-tags defined by user in command line. Returns: bool: True when matrix entry can be processed.
def main(self) -> None: path = ask_path("where should the config be stored?", ".snekrc") conf = configobj.ConfigObj() tools = self.get_tools() for tool in tools: conf[tool] = getattr(self, tool)() conf.filename = path conf.write() print("Written config...
The main function for generating the config file
def sort_timeplaceentries(self, timeentry, placeentry) -> Tuple[Any, Any]: if self._timeaxis: return placeentry, timeentry return timeentry, placeentry
Return a |tuple| containing the given `timeentry` and `placeentry` sorted in agreement with the currently selected `timeaxis`. >>> from hydpy.core.netcdftools import NetCDFVariableBase >>> from hydpy import make_abc_testable >>> NCVar = make_abc_testable(NetCDFVariableBase) >>> ...
def get_seconds(self): parsed = self.parse_hh_mm_ss() total_seconds = parsed.second total_seconds += parsed.minute * 60.0 total_seconds += parsed.hour * 60.0 * 60.0 return total_seconds
Gets seconds from raw time :return: Seconds in time
def request_password_reset(self, user, base_url): user.generate_password_link() db.session.add(user) db.session.commit() events.password_change_requested_event.send(user) self.send_password_change_message(user, base_url)
Regenerate password link and send message
def tokens(self, instance): if not instance.pk: return "-" totp = TOTP(instance.bin_key, instance.step, instance.t0, instance.digits) tokens = [] for offset in range(-instance.tolerance, instance.tolerance + 1): totp.drift = instance.drift + offset tok...
Just display current acceptable TOTP tokens
def seq_view_shot(self, ): if not self.cur_seq: return i = self.seq_shot_tablev.currentIndex() item = i.internalPointer() if item: shot = item.internal_data() self.view_shot(shot)
View the shot that is selected in the table view of the sequence page :returns: None :rtype: None :raises: None
def transformer_wikitext103_l4k_memory_v0(): hparams = transformer_wikitext103_l4k_v0() hparams.split_targets_chunk_length = 64 hparams.split_targets_max_chunks = 64 hparams.split_targets_strided_training = True hparams.add_hparam("memory_type", "transformer_xl") target_tokens_per_batch = 4096 hparams.bat...
HParams for training languagemodel_wikitext103_l4k with memory.
def get_parsed_context(pipeline, context_in_string): logger.debug("starting") if 'context_parser' in pipeline: parser_module_name = pipeline['context_parser'] logger.debug(f"context parser found: {parser_module_name}") parser_module = pypyr.moduleloader.get_module(parser_module_name) ...
Execute get_parsed_context handler if specified. Dynamically load the module specified by the context_parser key in pipeline dict and execute the get_parsed_context function on that module. Args: pipeline: dict. Pipeline object. context_in_string: string. Argument string used to initialize...
def get_version(version): if len(version) > 2 and version[2] is not None: if isinstance(version[2], int): str_version = "%s.%s.%s" % version[:3] else: str_version = "%s.%s_%s" % version[:3] else: str_version = "%s.%s" % version[:2] return str_version
Dynamically calculate the version based on VERSION tuple.
def max_brightness(self): self._max_brightness, value = self.get_cached_attr_int(self._max_brightness, 'max_brightness') return value
Returns the maximum allowable brightness value.
def remove_root_log(self, log_id): if self._catalog_session is not None: return self._catalog_session.remove_root_catalog(catalog_id=log_id) return self._hierarchy_session.remove_root(id_=log_id)
Removes a root log. arg: log_id (osid.id.Id): the ``Id`` of a log raise: NotFound - ``log_id`` is not a root raise: NullArgument - ``log_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *complianc...
def generate_id(self): if self.use_repeatable_ids: self.repeatable_id_counter += 1 return 'autobaked-{}'.format(self.repeatable_id_counter) else: return str(uuid4())
Generate a fresh id
def validate_on_submit(self): valid = FlaskWtf.validate_on_submit(self) if not self._schema or not self.is_submitted(): return valid data = dict() for field in self._fields: data[field] = self._fields[field].data result = self.schema.process(data, context=...
Extend validate on submit to allow validation with schema
def get_selected_tab(self): selected = self.request.GET.get(self.param_name, None) if selected: try: tab_group, tab_name = selected.split(SEPARATOR) except ValueError: return None if tab_group == self.get_id(): self._sel...
Returns the tab specific by the GET request parameter. In the event that there is no GET request parameter, the value of the query parameter is invalid, or the tab is not allowed/enabled, the return value of this function is None.
def complement(self): if self.is_empty: return StridedInterval.top(self.bits) if self.is_top: return StridedInterval.empty(self.bits) y_plus_1 = StridedInterval._modular_add(self.upper_bound, 1, self.bits) x_minus_1 = StridedInterval._modular_sub(self.lower_bound,...
Return the complement of the interval Refer section 3.1 augmented for managing strides :return:
def _check_current_value(gnome_kwargs, value): current_value = __salt__['gnome.get'](**gnome_kwargs) return six.text_type(current_value) == six.text_type(value)
Check the current value with the passed value
def get_class_doc(klass, config=default_config): if config.exclude_class: for ex in config.exclude_class: if ex.match(klass.__name__): return None nested_doc = [] class_dict = klass.__dict__ for item in dir(klass): if item in class_dict.keys(): app...
Return doc for a class.
def main(self): self._setup_task_manager() self._setup_source_and_destination() self.task_manager.blocking_start(waiting_func=self.waiting_func) self.close() self.config.logger.info('done.')
this main routine sets up the signal handlers, the source and destination crashstorage systems at the theaded task manager. That starts a flock of threads that are ready to shepherd crashes from the source to the destination.
def num_samples(self, sr=None): native_sr = self.sampling_rate num_samples = units.seconds_to_sample(self.duration, native_sr) if sr is not None: ratio = float(sr) / native_sr num_samples = int(np.ceil(num_samples * ratio)) return num_samples
Return the number of samples. Args: sr (int): Calculate the number of samples with the given sampling-rate. If None use the native sampling-rate. Returns: int: Number of samples
def ratio(self, col: str, ratio_col: str="Ratio"): try: df = self.df.copy() df[ratio_col] = df[[col]].apply( lambda x: 100 * x / float(x.sum())) self.df = df except Exception as e: self.err(e, self.ratio, "Can not calculate ratio")
Add a column whith the percentages ratio from a column :param col: column to calculate ratio from :type col: str :param ratio_col: new ratio column name, defaults to "Ratio" :param ratio_col: str, optional :example: ``ds2 = ds.ratio("Col 1")``
def _get_attrs(self, names): assert isinstance(names, str) names = names.replace(",", " ").split(" ") res = [] for n in names: if n == "": continue if n not in self.__dict__: raise KeyError("Unknown name for Container attribute: '{}...
Convenience function to extract multiple attributes at once :param names: string of names separated by comma or space :return:
def dbg_repr(self, max_display=10): s = repr(self) + "\n" if len(self.chosen_statements) > max_display: s += "%d SimRuns in program slice, displaying %d.\n" % (len(self.chosen_statements), max_display) else: s += "%d SimRuns in program slice.\n" % len(self.chosen_statemen...
Debugging output of this slice. :param max_display: The maximum number of SimRun slices to show. :return: A string representation.
def exec_before_request_actions(actions, **kwargs): groups = ("before", "before_" + flask.request.method.lower()) return execute_actions(actions, limit_groups=groups, **kwargs)
Execute actions in the "before" and "before_METHOD" groups
def get_static_properties(self): return {tags.tag: tags.get('VALUE') for tags in self.bnmodel.find('STATICPROPERTIES')}
Returns a dictionary of STATICPROPERTIES Examples -------- >>> reader = XBNReader('xbn_test.xml') >>> reader.get_static_properties() {'FORMAT': 'MSR DTAS XML', 'VERSION': '0.2', 'CREATOR': 'Microsoft Research DTAS'}
def enterEvent(self, event): super(XViewPanelItem, self).enterEvent(event) self._hovered = True self.update()
Mark the hovered state as being true. :param event | <QtCore.QEnterEvent>
def _get_data_volumes(vm_): ret = [] volumes = vm_['volumes'] for key, value in six.iteritems(volumes): if 'disk_size' not in volumes[key].keys(): raise SaltCloudConfigError( 'The volume \'{0}\' is missing \'disk_size\''.format(key) ) if 'disk_type' no...
Construct a list of optional data volumes from the cloud profile
def pop(self, key, default=None): return self._dictionary.pop(key.lower(), default)
Remove the key and return the associated value or default if not found Args: key (str): The key to remove default (obj): The value to return if key is not present
def addPrivateCertificate(self, subjectName, existingCertificate=None): if existingCertificate is None: assert '@' not in subjectName, "Don't self-sign user certs!" mainDN = DistinguishedName(commonName=subjectName) mainKey = KeyPair.generate() mainCertReq = mainK...
Add a PrivateCertificate object to this store for this subjectName. If existingCertificate is None, add a new self-signed certificate.
def find(self, soup): for tag in soup.recursiveChildGenerator(): if self.match_criterion(tag): yield tag
Yield tags matching the tag criterion from a soup. There is no need to override this if you are satisfied with finding tags that match match_criterion. Args: soup: A BeautifulSoup to search through. Yields: BeautifulSoup Tags that match the criterion.
def _print(self, force_flush=False): self._stream_flush() next_perc = self._calc_percent() if self.update_interval: do_update = time.time() - self.last_time >= self.update_interval elif force_flush: do_update = True else: do_update = next_perc ...
Prints formatted percentage and tracked time to the screen.
def where(self, **kwargs): clauses = copy(self.clauses) for dimension, condition in kwargs.items(): if dimension in self.clauses: raise Exception('There should be only one clause for {}'.format(dimension)) if dimension not in self.schema: raise Exc...
Return a new Dataset refined using the given condition :param kwargs: a map of `dimension` => `condition` to filter the elements of the dataset. `condition` can either be an exact value or a callable returning a boolean value. If `condition` is a value, it is converted to a ...
def send_raw_packet(self, packet: str): data = packet + '\r\n' log.debug('writing data: %s', repr(data)) self.transport.write(data.encode())
Encode and put packet string onto write buffer.
def add_user_rating(self, item_type, item_id, item_rating): raw_response = requests_util.run_request('put', self.API_BASE_URL + '/user/ratings/%s/%d/%d' % (item_type, item_id, item_rating), ...
Adds the rating for the item indicated for the current user. :param item_type: One of: series, episode, banner. :param item_id: The TheTVDB id of the item. :param item_rating: The rating from 0 to 10. :return:
def remove_empty_cols(records): records = list(records) seqstrs = [str(rec.seq) for rec in records] clean_cols = [col for col in zip(*seqstrs) if not all(c == '-' for c in col)] clean_seqs = [''.join(row) for row in zip(*clean_cols)] for rec, cle...
Remove all-gap columns from aligned SeqRecords.
def collect_directories(self, directories): directories = util.to_absolute_paths(directories) if not self.recursive: return self._remove_blacklisted(directories) recursive_dirs = set() for dir_ in directories: walk_iter = os.walk(dir_, followlinks=True) ...
Collects all the directories into a `set` object. If `self.recursive` is set to `True` this method will iterate through and return all of the directories and the subdirectories found from `directories` that are not blacklisted. if `self.recursive` is set to `False` this will return all...
def area2lonlat(dataarray): area = dataarray.attrs['area'] lons, lats = area.get_lonlats_dask() lons = xr.DataArray(lons, dims=['y', 'x'], attrs={'name': "longitude", 'standard_name': "longitude", 'units': 'degrees_east'},...
Convert an area to longitudes and latitudes.
def open_url(self, url, sleep_after_open=2): self.zap.urlopen(url) time.sleep(sleep_after_open)
Access a URL through ZAP.
def map_position(pos): posiction_dict = dict(zip(range(1, 17), [i for i in range(30, 62) if i % 2])) return posiction_dict[pos]
Map natural position to machine code postion
def process_bind_param(self, obj, dialect): value = obj or {} if isinstance(obj, flask_cloudy.Object): value = {} for k in self.DEFAULT_KEYS: value[k] = getattr(obj, k) return super(self.__class__, self).process_bind_param(value, dialect)
Get a flask_cloudy.Object and save it as a dict
def get_log_id(cls, id): conn = Qubole.agent() r = conn.get_raw(cls.element_path(id) + "/logs") return r.text
Fetches log for the command represented by this id Args: `id`: command id
def clean_line(str, delimiter): return [x.strip() for x in str.strip().split(delimiter) if x != '']
Split string on given delimiter, remove whitespace from each field.
def height(self): alloc_h = self.alloc_h if self.parent and isinstance(self.parent, graphics.Scene): alloc_h = self.parent.height min_height = (self.min_height or 0) + self.margin_top + self.margin_bottom h = alloc_h if alloc_h is not None and self.fill else min_height ...
height in pixels
def get_entries(self, start=0, end=0, data_request=None, steam_ids=None): message = MsgProto(EMsg.ClientLBSGetLBEntries) message.body.app_id = self.app_id message.body.leaderboard_id = self.id message.body.range_start = start message.body.range_end = end message.body.lead...
Get leaderboard entries. :param start: start entry, not index (e.g. rank 1 is ``start=1``) :type start: :class:`int` :param end: end entry, not index (e.g. only one entry then ``start=1,end=1``) :type end: :class:`int` :param data_request: data being requested :type data...
def policy(self, observations): input_data = self.input_block(observations) policy_base_output = self.policy_backbone(input_data) policy_params = self.action_head(policy_base_output) return policy_params
Calculate only action head for given state
def deleteByOrigIndex(self, index): result = [] result_tracker = [] for counter, row in enumerate(self.table): if self.index_track[counter] != index: result.append(row) result_tracker.append(self.index_track[counter]) self.table = result ...
Removes a single entry from the list given the index reference. The index, in this instance, is a reference to the *original* list indexing as seen when the list was first inserted into PLOD. An example: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs":...
def LDA_discriminants(x, labels): try: x = np.array(x) except: raise ValueError('Impossible to convert x to a numpy array.') eigen_values, eigen_vectors = LDA_base(x, labels) return eigen_values[(-eigen_values).argsort()]
Linear Discriminant Analysis helper for determination how many columns of data should be reduced. **Args:** * `x` : input matrix (2d array), every row represents new sample * `labels` : list of labels (iterable), every item should be label for \ sample with corresponding index **Returns:...
def check_signature(signature, key, data): if isinstance(key, type(u'')): key = key.encode() digest = 'sha1=' + hmac.new(key, data, hashlib.sha1).hexdigest() if isinstance(digest, type(u'')): digest = digest.encode() if isinstance(signature, type(u'')): signature = signature.enco...
Compute the HMAC signature and test against a given hash.
def purge(root=os.path.join(base.data_dir(), 'models')): r root = os.path.expanduser(root) files = os.listdir(root) for f in files: if f.endswith(".params"): os.remove(os.path.join(root, f))
r"""Purge all pretrained model files in local file store. Parameters ---------- root : str, default '$MXNET_HOME/models' Location for keeping the model parameters.
def add(self, resource): if isinstance(resource, collections.Iterable): for r in resource: self.resources.append(r) else: self.resources.append(resource)
Add a resource or an iterable collection of resources to this container. Must be implemented in derived class.