code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def unicode2encode(text, charmap): ''' charmap : dictionary which has both encode as key, unicode as value ''' if isinstance(text, (list, tuple)): unitxt = '' for line in text: for val,key in charmap.items(): if key in line: line =...
charmap : dictionary which has both encode as key, unicode as value
def set(self, name: str, value: Union[str, List[str]]) -> None: """ 设置 header """ self._headers[name] = value
设置 header
def radiance_to_bt(arr, wc_, a__, b__): """Convert to BT. """ return a__ + b__ * (C2 * wc_ / (da.log(1 + (C1 * (wc_ ** 3) / arr))))
Convert to BT.
def detach(self): """Detach this socket from the server. This should be done in conjunction with kill(), once all the jobs are dead, detach the socket for garbage collection.""" log.debug("Removing %s from server sockets" % self) if self.sessid in self.server.sockets: ...
Detach this socket from the server. This should be done in conjunction with kill(), once all the jobs are dead, detach the socket for garbage collection.
def function(self, x, y, theta_E, gamma, e1, e2, center_x=0, center_y=0): """ :param x: set of x-coordinates :type x: array of size (n) :param theta_E: Einstein radius of lense :type theta_E: float. :param gamma: power law slope of mass profifle :type gamma: <2 fl...
:param x: set of x-coordinates :type x: array of size (n) :param theta_E: Einstein radius of lense :type theta_E: float. :param gamma: power law slope of mass profifle :type gamma: <2 float :param q: Axis ratio :type q: 0<q<1 :param phi_G: position angel o...
def match(self, pattern, context=None): """ This method returns a (possibly empty) list of strings that match the regular expression ``pattern`` provided. You can also provide a ``context`` as described above. This method calls ``choices`` to get a list of all possible ...
This method returns a (possibly empty) list of strings that match the regular expression ``pattern`` provided. You can also provide a ``context`` as described above. This method calls ``choices`` to get a list of all possible choices and then filters the list by performing a regular ...
def strip_prefix(s, prefix, strict=False): """Removes the prefix, if it's there, otherwise returns input string unchanged. If strict is True, also ensures the prefix was present""" if s.startswith(prefix): return s[len(prefix) :] elif strict: raise WimpyError("string doesn't start with p...
Removes the prefix, if it's there, otherwise returns input string unchanged. If strict is True, also ensures the prefix was present
def _encode_bool(name, value, dummy0, dummy1): """Encode a python boolean (True/False).""" return b"\x08" + name + (value and b"\x01" or b"\x00")
Encode a python boolean (True/False).
def print_param_defaults(self_): """Print the default values of all cls's Parameters.""" cls = self_.cls for key,val in cls.__dict__.items(): if isinstance(val,Parameter): print(cls.__name__+'.'+key+ '='+ repr(val.default))
Print the default values of all cls's Parameters.
def ephem(self, *args, **kwargs): """Create an Ephem object which is a subset of this one Take the same keyword arguments as :py:meth:`ephemeris` Return: Ephem: """ return self.__class__(self.ephemeris(*args, **kwargs))
Create an Ephem object which is a subset of this one Take the same keyword arguments as :py:meth:`ephemeris` Return: Ephem:
def _attach_original_exception(self, exc): """ Often, a retry will be raised inside an "except" block. This Keep track of the first exception for debugging purposes """ original_exception = sys.exc_info() if original_exception[0] is not None: exc.original_exception = ori...
Often, a retry will be raised inside an "except" block. This Keep track of the first exception for debugging purposes
def register_target(self, target: Target): """Register a `target` instance in this build context. A registered target is saved in the `targets` map and in the `targets_by_module` map, but is not added to the target graph until target extraction is completed (thread safety considerations...
Register a `target` instance in this build context. A registered target is saved in the `targets` map and in the `targets_by_module` map, but is not added to the target graph until target extraction is completed (thread safety considerations).
def score_samples(self, X, lengths=None): """Compute the log probability under the model and compute posteriors. Parameters ---------- X : array-like, shape (n_samples, n_features) Feature matrix of individual samples. lengths : array-like of integers, shape (n_sequ...
Compute the log probability under the model and compute posteriors. Parameters ---------- X : array-like, shape (n_samples, n_features) Feature matrix of individual samples. lengths : array-like of integers, shape (n_sequences, ), optional Lengths of the individ...
def getPrevUrl(self, url, data): """Find previous URL.""" prevUrl = None if self.prevSearch: try: prevUrl = self.fetchUrl(url, data, self.prevSearch) except ValueError as msg: # assume there is no previous URL, but print a warning ...
Find previous URL.
def get_diskinfo(opts, show_all=False, local_only=False): ''' Returns a list holding the current disk info. Stats are divided by the outputunit. ''' disks = [] outunit = opts.outunit label_map = get_label_map(opts) # get mount info try: with open(mntfname) as infile: ...
Returns a list holding the current disk info. Stats are divided by the outputunit.
def unpack_unordered_pairs(self, pairs): """Unpack an unordered list of value pairs taking DelayPacking exceptions into account to resolve circular references . Used to unpack dictionary items when the order is not guarennteed by the serializer. When item order change between packing ...
Unpack an unordered list of value pairs taking DelayPacking exceptions into account to resolve circular references . Used to unpack dictionary items when the order is not guarennteed by the serializer. When item order change between packing and unpacking, references are not guaranteed to...
def relcurveto(self, h1x, h1y, h2x, h2y, x, y): '''Draws a curve relatively to the last point. ''' if self._path is None: raise ShoebotError(_("No current path. Use beginpath() first.")) self._path.relcurveto(h1x, h1y, h2x, h2y, x, y)
Draws a curve relatively to the last point.
def next_doc_with_tag(self, doc_tag): """ Returns the next document with the specified tag. Empty string is no doc is found. """ while True: try: doc = next(self) if doc.tag == doc_tag: return doc except StopIte...
Returns the next document with the specified tag. Empty string is no doc is found.
def surrounding_nodes(self, position): """ Returns nearest node indices and direction of opposite node. :param position: Position inside the mesh to search nearest node for as (x,y,z) :return: Nearest node indices and direction of opposite node. """ n_node_index, n_node_positio...
Returns nearest node indices and direction of opposite node. :param position: Position inside the mesh to search nearest node for as (x,y,z) :return: Nearest node indices and direction of opposite node.
def get_maxloss_rupture(dstore, loss_type): """ :param dstore: a DataStore instance :param loss_type: a loss type string :returns: EBRupture instance corresponding to the maximum loss for the given loss type """ lti = dstore['oqparam'].lti[loss_type] ridx = dstore.get_attr('r...
:param dstore: a DataStore instance :param loss_type: a loss type string :returns: EBRupture instance corresponding to the maximum loss for the given loss type
def bit_reversal(qubits: List[int]) -> Program: """ Generate a circuit to do bit reversal. :param qubits: Qubits to do bit reversal with. :return: A program to do bit reversal. """ p = Program() n = len(qubits) for i in range(int(n / 2)): p.inst(SWAP(qubits[i], qubits[-i - 1])) ...
Generate a circuit to do bit reversal. :param qubits: Qubits to do bit reversal with. :return: A program to do bit reversal.
def tangent_bundle(self): """The tangent bundle associated with `domain` using `partition`. The tangent bundle of a space ``X`` of functions ``R^d --> F`` can be interpreted as the space of vector-valued functions ``R^d --> F^d``. This space can be identified with the power space ``X^d`...
The tangent bundle associated with `domain` using `partition`. The tangent bundle of a space ``X`` of functions ``R^d --> F`` can be interpreted as the space of vector-valued functions ``R^d --> F^d``. This space can be identified with the power space ``X^d`` as used in this implementat...
def temporary(self, path): """Establishes a temporary build root, restoring the prior build root on exit.""" if path is None: raise ValueError('Can only temporarily establish a build root given a path.') prior = self._root_dir self._root_dir = path try: yield finally: self._roo...
Establishes a temporary build root, restoring the prior build root on exit.
def copy_non_ecf(props, target): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] """ Copies non-ECF properties from ``props`` to ``target`` :param props: An input dictionary :param target: The dictionary to copy non-ECF properties to :return: The ``target`` dictionary """ tar...
Copies non-ECF properties from ``props`` to ``target`` :param props: An input dictionary :param target: The dictionary to copy non-ECF properties to :return: The ``target`` dictionary
def derive_fields(self): """ Derives our fields. """ if self.fields: return self.fields else: fields = [] for field in self.object_list.model._meta.fields: if field.name != 'id': fields.append(field.name) ...
Derives our fields.
def get_contigs(self): '''Returns a dictionary of contig_name -> pyfastaq.Sequences.Fasta object''' contigs = {} pyfastaq.tasks.file_to_dict(self.contigs_fasta, contigs) return contigs
Returns a dictionary of contig_name -> pyfastaq.Sequences.Fasta object
def cleanup(self): """ Cleans up the key value store. In detail: 1. Deletes all key store references for image_files that do not exist and all key references for its thumbnails *and* their image_files. 2. Deletes or updates all invalid thumbnail keys """ for ke...
Cleans up the key value store. In detail: 1. Deletes all key store references for image_files that do not exist and all key references for its thumbnails *and* their image_files. 2. Deletes or updates all invalid thumbnail keys
def check_index(i): """ Checks and parses an index spec, must be a one-dimensional array [i0, i1, ...] """ i = asarray(i) if (i.ndim > 1) or (size(i) < 1): raise Exception("Index must be one-dimensional and non-singleton") return i
Checks and parses an index spec, must be a one-dimensional array [i0, i1, ...]
def _get(self, operation, field): """Get tracked position for a given operation and field.""" self._check_exists() query = {Mark.FLD_OP: operation.name, Mark.FLD_MARK + "." + field: {"$exists": True}} return self._track.find_one(query)
Get tracked position for a given operation and field.
def read_data(self, scaling_factor=1E-9, strain_headers=None): ''' Reads the data from the csv file :param float scaling_factor: Scaling factor used for all strain values (default 1E-9 for nanostrain) :param list strain_headers: List of the variables...
Reads the data from the csv file :param float scaling_factor: Scaling factor used for all strain values (default 1E-9 for nanostrain) :param list strain_headers: List of the variables in the file that correspond to strain parameters :returns: ...
def from_stream(cls, stream, marker_code, offset): """ Return a generic |_Marker| instance for the marker at *offset* in *stream* having *marker_code*. """ if JPEG_MARKER_CODE.is_standalone(marker_code): segment_length = 0 else: segment_length = st...
Return a generic |_Marker| instance for the marker at *offset* in *stream* having *marker_code*.
def get_call_repr(func, *args, **kwargs): """Return the string representation of the function call. :param func: A callable (e.g. function, method). :type func: callable :param args: Positional arguments for the callable. :param kwargs: Keyword arguments for the callable. :return: String repres...
Return the string representation of the function call. :param func: A callable (e.g. function, method). :type func: callable :param args: Positional arguments for the callable. :param kwargs: Keyword arguments for the callable. :return: String representation of the function call. :rtype: str
def transition(self): """ Implements a QAM-like transition. This function assumes ``program`` and ``program_counter`` instance variables are set appropriately, and that the wavefunction simulator and classical memory ``ram`` instance variables are in the desired QAM input state....
Implements a QAM-like transition. This function assumes ``program`` and ``program_counter`` instance variables are set appropriately, and that the wavefunction simulator and classical memory ``ram`` instance variables are in the desired QAM input state. :return: whether the QAM should ...
def _merge_args(qCmd, parsed_args, _extra_values, value_specs): """Merge arguments from _extra_values into parsed_args. If an argument value are provided in both and it is a list, the values in _extra_values will be merged into parsed_args. @param parsed_args: the parsed args from known options @p...
Merge arguments from _extra_values into parsed_args. If an argument value are provided in both and it is a list, the values in _extra_values will be merged into parsed_args. @param parsed_args: the parsed args from known options @param _extra_values: the other parsed arguments in unknown parts @pa...
def data(ctx, path): """List EDC data for [STUDY] [ENV] [SUBJECT]""" _rws = partial(rws_call, ctx) if len(path) == 0: _rws(ClinicalStudiesRequest(), default_attr='oid') elif len(path) == 1: _rws(StudySubjectsRequest(path[0], 'Prod'), default_attr='subjectkey') elif len(path) == 2: ...
List EDC data for [STUDY] [ENV] [SUBJECT]
def find_window_id(pattern, method='mru', error='raise'): """ xprop -id 0x00a00007 | grep "WM_CLASS(STRING)" """ import utool as ut winid_candidates = XCtrl.findall_window_ids(pattern) if len(winid_candidates) == 0: if error == 'raise': availab...
xprop -id 0x00a00007 | grep "WM_CLASS(STRING)"
def classify(label_dict,image_fname=None,image_label=None): '''tries to classify a DICOM image based on known string patterns (with fuzzy matching) Takes the label from the DICOM header and compares to the entries in ``label_dict``. If it finds something close it will return the image type, otherwise it wi...
tries to classify a DICOM image based on known string patterns (with fuzzy matching) Takes the label from the DICOM header and compares to the entries in ``label_dict``. If it finds something close it will return the image type, otherwise it will return ``None``. Alternatively, you can supply your own string, ...
def diff_encode(line, transform): """ Differentially encode a shapely linestring or ring. """ coords = [transform(x, y) for (x, y) in line.coords] pairs = zip(coords[:], coords[1:]) diffs = [(x2 - x1, y2 - y1) for ((x1, y1), (x2, y2)) in pairs] return coords[:1] + [(x, y) for (x, y) in diffs i...
Differentially encode a shapely linestring or ring.
def set_board_options(self, options, team_context, id): """SetBoardOptions. Update board options :param {str} options: options to updated :param :class:`<TeamContext> <azure.devops.v5_0.work.models.TeamContext>` team_context: The team context for the operation :param str id: iden...
SetBoardOptions. Update board options :param {str} options: options to updated :param :class:`<TeamContext> <azure.devops.v5_0.work.models.TeamContext>` team_context: The team context for the operation :param str id: identifier for board, either category plural name (Eg:"Stories") or gui...
async def remove_all_pumps_async(self, reason): """ Stops all partition pumps (Note this might be wrong and need to await all tasks before returning done). :param reason: A reason for closing. :type reason: str :rtype: bool """ pump_tasks = [self.remove_p...
Stops all partition pumps (Note this might be wrong and need to await all tasks before returning done). :param reason: A reason for closing. :type reason: str :rtype: bool
def parse_info(raw_info, apply_tag=None): """ Parse raw rdoinfo metadata inplace. :param raw_info: raw info to parse :param apply_tag: tag to apply :returns: dictionary containing all packages in rdoinfo """ parse_releases(raw_info) parse_packages(raw_info, apply_tag=apply_tag) retu...
Parse raw rdoinfo metadata inplace. :param raw_info: raw info to parse :param apply_tag: tag to apply :returns: dictionary containing all packages in rdoinfo
def action(self, *args, **kwargs): """the default action for Support Classifiers invokes any derivied _action function, trapping any exceptions raised in the process. We are obligated to catch these exceptions to give subsequent rules the opportunity to act and perhaps mitigate the erro...
the default action for Support Classifiers invokes any derivied _action function, trapping any exceptions raised in the process. We are obligated to catch these exceptions to give subsequent rules the opportunity to act and perhaps mitigate the error. An error during the action applica...
def _aggregate_on_chunks(x, f_agg, chunk_len): """ Takes the time series x and constructs a lower sampled version of it by applying the aggregation function f_agg on consecutive chunks of length chunk_len :param x: the time series to calculate the aggregation of :type x: numpy.ndarray :param f_...
Takes the time series x and constructs a lower sampled version of it by applying the aggregation function f_agg on consecutive chunks of length chunk_len :param x: the time series to calculate the aggregation of :type x: numpy.ndarray :param f_agg: The name of the aggregation function that should be an...
def get_parent_data(tree, node, current): """ Recurse up the tree getting parent data :param tree: The tree :param node: The current node :param current: The current list :return: The hierarchical dictionary """ if not current: current = [] ...
Recurse up the tree getting parent data :param tree: The tree :param node: The current node :param current: The current list :return: The hierarchical dictionary
def gradient_rgb( self, text=None, fore=None, back=None, style=None, start=None, stop=None, step=1, linemode=True, movefactor=0): """ Return a black and white gradient. Arguments: text : String to colorize. fore : Foreground color, ...
Return a black and white gradient. Arguments: text : String to colorize. fore : Foreground color, background will be gradient. back : Background color, foreground will be gradient. style : Name of style to use for the gra...
def read_backend(self, client=None): '''The read :class:`stdnet.BackendDatServer` for this instance. It can be ``None``. ''' session = self.session if session: return session.model(self).read_backend
The read :class:`stdnet.BackendDatServer` for this instance. It can be ``None``.
def average_over_area(q, x, y): """Averages a quantity `q` over a rectangular area given a 2D array and the x and y vectors for sample locations, using the trapezoidal rule""" area = (np.max(x) - np.min(x))*(np.max(y) - np.min(y)) integral = np.trapz(np.trapz(q, y, axis=0), x) return integral/a...
Averages a quantity `q` over a rectangular area given a 2D array and the x and y vectors for sample locations, using the trapezoidal rule
def create_api_vlan(self): """Get an instance of Api Vlan services facade.""" return ApiVlan( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of Api Vlan services facade.
def get_valid_filename(s, max_length=FILENAME_MAX_LENGTH): """ Returns the given string converted to a string that can be used for a clean filename. Removes leading and trailing spaces; converts anything that is not an alphanumeric, dash or underscore to underscore; converts behave examples separator ` ...
Returns the given string converted to a string that can be used for a clean filename. Removes leading and trailing spaces; converts anything that is not an alphanumeric, dash or underscore to underscore; converts behave examples separator ` -- @` to underscore. It also cuts the resulting name to `max_length...
def get_absolute_url_link(self, text=None, cls=None, icon_class=None, **attrs): """Gets the html link for the object.""" if text is None: text = self.get_link_text() return build_link(href=self.get_absolute_url(), text=text, ...
Gets the html link for the object.
def FanOut(self, obj, parent=None): """Expand values from various attribute types. Strings are returned as is. Dictionaries are returned with a key string, and an expanded set of values. Other iterables are expanded until they flatten out. Other items are returned in string format. Args: ...
Expand values from various attribute types. Strings are returned as is. Dictionaries are returned with a key string, and an expanded set of values. Other iterables are expanded until they flatten out. Other items are returned in string format. Args: obj: The object to expand out. paren...
def get_old_filename(diff_part): """ Returns the filename for the original file that was changed in a diff part. """ regexps = ( # e.g. "+++ a/foo/bar" r'^--- a/(.*)', # e.g. "+++ /dev/null" r'^\-\-\- (.*)', ) for regexp in regexps: r = re.compile(regexp, ...
Returns the filename for the original file that was changed in a diff part.
def multi_zset(self, name, **kvs): """ Return a dictionary mapping key/value by ``keys`` from zset ``names`` :param string name: the zset name :param list keys: a list of keys :return: the number of successful creation :rtype: int >>> ssdb.multi_zset('zs...
Return a dictionary mapping key/value by ``keys`` from zset ``names`` :param string name: the zset name :param list keys: a list of keys :return: the number of successful creation :rtype: int >>> ssdb.multi_zset('zset_4', a=100, b=80, c=90, d=70) 4 >>> s...
def load_learner(path:PathOrStr, file:PathLikeOrBinaryStream='export.pkl', test:ItemList=None, **db_kwargs): "Load a `Learner` object saved with `export_state` in `path/file` with empty data, optionally add `test` and load on `cpu`. `file` can be file-like (file or buffer)" source = Path(path)/file if is_pathli...
Load a `Learner` object saved with `export_state` in `path/file` with empty data, optionally add `test` and load on `cpu`. `file` can be file-like (file or buffer)
def verify_signature(args): """ Verify a previously signed binary image, using the ECDSA public key """ key_data = args.keyfile.read() if b"-BEGIN EC PRIVATE KEY" in key_data: sk = ecdsa.SigningKey.from_pem(key_data) vk = sk.get_verifying_key() elif b"-BEGIN PUBLIC KEY" in key_data: ...
Verify a previously signed binary image, using the ECDSA public key
def parse_model_file(path): """Parse a file as a list of model reactions The file format is detected and the file is parsed accordinly. The file is specified as a file path that will be opened for reading. Path can be given as a string or a context. """ context = FilePathContext(path) for...
Parse a file as a list of model reactions The file format is detected and the file is parsed accordinly. The file is specified as a file path that will be opened for reading. Path can be given as a string or a context.
def _busy_wait_ms(self, ms): """Busy wait for the specified number of milliseconds.""" start = time.time() delta = ms/1000.0 while (time.time() - start) <= delta: pass
Busy wait for the specified number of milliseconds.
def open_recruitment(self, n=1): """Return initial experiment URL list, plus instructions for finding subsequent recruitment events in experiemnt logs. """ logger.info("Opening HotAir recruitment for {} participants".format(n)) recruitments = self.recruit(n) message = "Re...
Return initial experiment URL list, plus instructions for finding subsequent recruitment events in experiemnt logs.
def AddOperands(self, lhs, rhs): """Add an operand.""" if isinstance(lhs, Expression) and isinstance(rhs, Expression): self.args = [lhs, rhs] else: raise errors.ParseError( 'Expected expression, got {0:s} {1:s} {2:s}'.format( lhs, self.operator, rhs))
Add an operand.
def get_batch_unlock_gain( channel_state: NettingChannelState, ) -> UnlockGain: """Collect amounts for unlocked/unclaimed locks and onchain unlocked locks. Note: this function does not check expiry, so the values make only sense during settlement. Returns: gain_from_partner_locks: locks amo...
Collect amounts for unlocked/unclaimed locks and onchain unlocked locks. Note: this function does not check expiry, so the values make only sense during settlement. Returns: gain_from_partner_locks: locks amount received and unlocked on-chain gain_from_our_locks: locks amount which are unlocked...
def copy_contents(self, fileinstance, progress_callback=None, chunk_size=None, **kwargs): """Copy this file instance into another file instance.""" if not fileinstance.readable: raise ValueError('Source file instance is not readable.') if not self.size == 0: ...
Copy this file instance into another file instance.
def _item_sources(self): """List of places to look-up items for key-completion""" return [self.data_vars, self.coords, {d: self[d] for d in self.dims}, LevelCoordinatesSource(self)]
List of places to look-up items for key-completion
def evaluate(self, dataset, metric='auto', missing_value_action='auto'): """ Evaluate the model on the given dataset. Parameters ---------- dataset : SFrame Dataset in the same format used for training. The columns names and types of the dataset must be ...
Evaluate the model on the given dataset. Parameters ---------- dataset : SFrame Dataset in the same format used for training. The columns names and types of the dataset must be the same as that used in training. metric : str, optional Name of the ev...
def _index2word(self): """Mapping from indices to words. WARNING: this may go out-of-date, because it is a copy, not a view into the Vocab. :return: a list of strings """ # TODO(kelvinguu): it would be nice to just use `dict.viewkeys`, but unfortunately those are not indexable ...
Mapping from indices to words. WARNING: this may go out-of-date, because it is a copy, not a view into the Vocab. :return: a list of strings
def is_likely_link(text): '''Return whether the text is likely to be a link. This function assumes that leading/trailing whitespace has already been removed. Returns: bool ''' text = text.lower() # Check for absolute or relative URLs if ( text.startswith('http://') ...
Return whether the text is likely to be a link. This function assumes that leading/trailing whitespace has already been removed. Returns: bool
def forward(self, agent_qs, states): """Forward pass for the mixer. Arguments: agent_qs: Tensor of shape [B, T, n_agents, n_actions] states: Tensor of shape [B, T, state_dim] """ bs = agent_qs.size(0) states = states.reshape(-1, self.state_dim) ag...
Forward pass for the mixer. Arguments: agent_qs: Tensor of shape [B, T, n_agents, n_actions] states: Tensor of shape [B, T, state_dim]
def _get_table_info(self): """Inspect the base to get field names""" self.fields = [] self.field_info = {} self.cursor.execute('PRAGMA table_info (%s)' %self.name) for field_info in self.cursor.fetchall(): fname = field_info[1].encode('utf-8') self....
Inspect the base to get field names
def requirements(collector): """Just print out the requirements""" out = sys.stdout artifact = collector.configuration['dashmat'].artifact if artifact not in (None, "", NotSpecified): if isinstance(artifact, six.string_types): out = open(artifact, 'w') else: out =...
Just print out the requirements
async def create( cls, node: Union[Node, str], interface_type: InterfaceType = InterfaceType.PHYSICAL, *, name: str = None, mac_address: str = None, tags: Iterable[str] = None, vlan: Union[Vlan, int] = None, parent: Union[Interface, int] = None, pa...
Create a `Interface` in MAAS. :param node: Node to create the interface on. :type node: `Node` or `str` :param interface_type: Type of interface to create (optional). :type interface_type: `InterfaceType` :param name: The name for the interface (optional). :type name: `s...
def format_help(help): """Formats the help string.""" help = help.replace("Options:", str(crayons.normal("Options:", bold=True))) help = help.replace( "Usage: pipenv", str("Usage: {0}".format(crayons.normal("pipenv", bold=True))) ) help = help.replace(" check", str(crayons.red(" check", bo...
Formats the help string.
def __if_not_basestring(text_object): """Convert to str""" converted_str = text_object if not isinstance(text_object, str): converted_str = str(text_object) return converted_str
Convert to str
def _ReadMemberFooter(self, file_object): """Reads a member footer. Args: file_object (FileIO): file-like object to read from. Raises: FileFormatError: if the member footer cannot be read. """ file_offset = file_object.get_offset() member_footer = self._ReadStructure( file_...
Reads a member footer. Args: file_object (FileIO): file-like object to read from. Raises: FileFormatError: if the member footer cannot be read.
def characters (self, data): """ Print characters. @param data: the character data @type data: string @return: None """ data = data.encode(self.encoding, "ignore") self.fd.write(data)
Print characters. @param data: the character data @type data: string @return: None
def load_modes(self, input_modes=None): """ Loads modes (GameMode objects) to be supported by the game object. Four default modes are provided (normal, easy, hard, and hex) but others could be provided either by calling load_modes directly or passing a list of GameMode objects to ...
Loads modes (GameMode objects) to be supported by the game object. Four default modes are provided (normal, easy, hard, and hex) but others could be provided either by calling load_modes directly or passing a list of GameMode objects to the instantiation call. :param input_modes: A list...
def multi_subplots_time(DataArray, SubSampleN=1, units='s', xlim=None, ylim=None, LabelArray=[], show_fig=True): """ plot the time trace on multiple axes Parameters ---------- DataArray : array-like array of DataObject instances for which to plot the PSDs SubSampleN : int, optional ...
plot the time trace on multiple axes Parameters ---------- DataArray : array-like array of DataObject instances for which to plot the PSDs SubSampleN : int, optional Number of intervals between points to remove (to sub-sample data so that you effectively have lower sample rate t...
def logout(self): """logout func (quit browser)""" try: self.browser.quit() except Exception: raise exceptions.BrowserException(self.brow_name, "not started") return False self.vbro.stop() logger.info("logged out") return True
logout func (quit browser)
def auth_user(self, username, password): """ Authenticate the user in database :param username: Username/Login :param password: User password :return: Returns a dict represrnting the user """ password_hash = hashlib.sha512(password.encode("utf-8")).hexdigest() ...
Authenticate the user in database :param username: Username/Login :param password: User password :return: Returns a dict represrnting the user
def make_source_mask(data, snr, npixels, mask=None, mask_value=None, filter_fwhm=None, filter_size=3, filter_kernel=None, sigclip_sigma=3.0, sigclip_iters=5, dilate_size=11): """ Make a source mask using source segmentation and binary dilation. Parameters -----...
Make a source mask using source segmentation and binary dilation. Parameters ---------- data : array_like The 2D array of the image. snr : float The signal-to-noise ratio per pixel above the ``background`` for which to consider a pixel as possibly being part of a source. n...
def start_drag(self, sprite, cursor_x = None, cursor_y = None): """start dragging given sprite""" cursor_x, cursor_y = cursor_x or sprite.x, cursor_y or sprite.y self._mouse_down_sprite = self._drag_sprite = sprite sprite.drag_x, sprite.drag_y = self._drag_sprite.x, self._drag_sprite.y ...
start dragging given sprite
def stellar_luminosity2(self, steps=10000): """ DEPRECATED: ADW 2017-09-20 Compute the stellar luminosity (L_Sol; average per star). Uses "sample" to generate mass sample and pdf. The range of integration only covers the input isochrone data (no extrapolation used), but...
DEPRECATED: ADW 2017-09-20 Compute the stellar luminosity (L_Sol; average per star). Uses "sample" to generate mass sample and pdf. The range of integration only covers the input isochrone data (no extrapolation used), but this seems like a sub-percent effect if the isochrone g...
def design(self, max_stimuli=-1, max_inhibitors=-1, max_experiments=10, relax=False, configure=None): """ Finds all optimal experimental designs using up to :attr:`max_experiments` experiments, such that each experiment has up to :attr:`max_stimuli` stimuli and :attr:`max_inhibitors` inhibitors....
Finds all optimal experimental designs using up to :attr:`max_experiments` experiments, such that each experiment has up to :attr:`max_stimuli` stimuli and :attr:`max_inhibitors` inhibitors. Each optimal experimental design is appended in the attribute :attr:`designs` as an instance of :class:`caspo.cor...
def getAsKmlGridAnimation(self, tableName, timeStampedRasters=[], rasterIdFieldName='id', rasterFieldName='raster', documentName='default', alpha=1.0, noDataValue=0, discreet=False): """ Return a sequence of rasters with timestamps as a kml with time markers for animation....
Return a sequence of rasters with timestamps as a kml with time markers for animation. :param tableName: Name of the table to extract rasters from :param timeStampedRasters: List of dictionaries with keys: rasterId, dateTime rasterId = a unique integer identifier used to locate the raste...
def _evolve(self, state, qargs=None): """Evolve a quantum state by the QuantumChannel. Args: state (QuantumState): The input statevector or density matrix. qargs (list): a list of QuantumState subsystem positions to apply the operator on. Retu...
Evolve a quantum state by the QuantumChannel. Args: state (QuantumState): The input statevector or density matrix. qargs (list): a list of QuantumState subsystem positions to apply the operator on. Returns: QuantumState: the output quantum...
def Run(self): """Event loop.""" if data_store.RelationalDBEnabled(): data_store.REL_DB.RegisterMessageHandler( self._ProcessMessageHandlerRequests, self.well_known_flow_lease_time, limit=100) data_store.REL_DB.RegisterFlowProcessingHandler(self.ProcessFlow) try: ...
Event loop.
def update_headers(self, headers: Optional[LooseHeaders]) -> None: """Update request headers.""" self.headers = CIMultiDict() # type: CIMultiDict[str] # add host netloc = cast(str, self.url.raw_host) if helpers.is_ipv6_address(netloc): netloc = '[{}]'.format(netloc)...
Update request headers.
def get_bucket_website_config(self, bucket): """ Get the website configuration of a bucket. @param bucket: The name of the bucket. @return: A C{Deferred} that will fire with the bucket's website configuration. """ details = self._details( method=b"GET...
Get the website configuration of a bucket. @param bucket: The name of the bucket. @return: A C{Deferred} that will fire with the bucket's website configuration.
def modify(self, modification, parameters): """ Apply a single modification to an MFD parameters. Reflects the modification method and calls it passing ``parameters`` as keyword arguments. See also :attr:`MODIFICATIONS`. Modifications can be applied one on top of another. The l...
Apply a single modification to an MFD parameters. Reflects the modification method and calls it passing ``parameters`` as keyword arguments. See also :attr:`MODIFICATIONS`. Modifications can be applied one on top of another. The logic of stacking modifications is up to a specific MFD i...
def show_lbaas_pool(self, lbaas_pool, **_params): """Fetches information for a lbaas_pool.""" return self.get(self.lbaas_pool_path % (lbaas_pool), params=_params)
Fetches information for a lbaas_pool.
def tagsInString_process(self, d_DICOM, astr, *args, **kwargs): """ This method substitutes DICOM tags that are '%'-tagged in a string template with the actual tag lookup. For example, an output filename that is specified as the following string: %PatientAge-%Patien...
This method substitutes DICOM tags that are '%'-tagged in a string template with the actual tag lookup. For example, an output filename that is specified as the following string: %PatientAge-%PatientID-output.txt will be parsed to 006Y-4412364-ouptut.txt ...
def add_clause(self, clause): """Add a new clause to the existing query. :param clause: The clause to add :type clause: MongoClause :return: None """ if clause.query_loc == MongoClause.LOC_MAIN: self._main.append(clause) elif clause.query_loc == Mongo...
Add a new clause to the existing query. :param clause: The clause to add :type clause: MongoClause :return: None
def inspect_file(self, commit, path): """ Returns info about a specific file. Params: * commit: A tuple, string, or Commit object representing the commit. * path: Path to file. """ req = proto.InspectFileRequest(file=proto.File(commit=commit_from(commit), path=pa...
Returns info about a specific file. Params: * commit: A tuple, string, or Commit object representing the commit. * path: Path to file.
def create_marginalized_hist(ax, values, label, percentiles=None, color='k', fillcolor='gray', linecolor='navy', linestyle='-', title=True, expected_value=None, expected_color='red', rotated=False, ...
Plots a 1D marginalized histogram of the given param from the given samples. Parameters ---------- ax : pyplot.Axes The axes on which to draw the plot. values : array The parameter values to plot. label : str A label to use for the title. percentiles : {None, float o...
def _calculate_num_queries(self): """ Calculate the total number of request and response queries. Used for count header and count table. """ request_totals = self._totals("request") response_totals = self._totals("response") return request_totals[2] + response_to...
Calculate the total number of request and response queries. Used for count header and count table.
def admin_url_params(request, params=None): """ given a request, looks at GET and POST values to determine which params should be added. Is used to keep the context of popup and picker mode. """ params = params or {} if popup_status(request): params[IS_POPUP_VAR] = '1' pick_type = po...
given a request, looks at GET and POST values to determine which params should be added. Is used to keep the context of popup and picker mode.
async def on_raw_762(self, message): """ End of metadata. """ # No way to figure out whose query this belongs to, so make a best guess # it was the first one. if not self._metadata_queue: return nickname = self._metadata_queue.pop() future = self._pending['me...
End of metadata.
def config_generator(search_space, max_search, rng, shuffle=True): """Generates config dicts from the given search space Args: search_space: (dict) A dictionary of parameters to search over. See note below for more details. max_search: (int) The maximum number of...
Generates config dicts from the given search space Args: search_space: (dict) A dictionary of parameters to search over. See note below for more details. max_search: (int) The maximum number of configurations to search. If max_search is None, do a full gr...
def message_loop(self, t_q, r_q): """Loop through messages and execute tasks""" t_msg = {} while t_msg.get("state", "") != "__DIE__": try: t_msg = t_q.get(True, self.cycle_sleep) # Poll blocking self.task = t_msg.get("task", "") # __DIE__ has no task...
Loop through messages and execute tasks
def _interpolate_doy_calendar(source, doy_max): """Interpolate from one set of dayofyear range to another Interpolate an array defined over a `dayofyear` range (say 1 to 360) to another `dayofyear` range (say 1 to 365). Parameters ---------- source : xarray.DataArray Array with `dayofyea...
Interpolate from one set of dayofyear range to another Interpolate an array defined over a `dayofyear` range (say 1 to 360) to another `dayofyear` range (say 1 to 365). Parameters ---------- source : xarray.DataArray Array with `dayofyear` coordinates. doy_max : int Largest day of ...
def get_discovery_doc(self, services, hostname=None): """JSON dict description of a protorpc.remote.Service in discovery format. Args: services: Either a single protorpc.remote.Service or a list of them that implements an api/version. hostname: string, Hostname of the API, to override the v...
JSON dict description of a protorpc.remote.Service in discovery format. Args: services: Either a single protorpc.remote.Service or a list of them that implements an api/version. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. ...
def deepest_common_ancestor(goterms, godag): ''' This function gets the nearest common ancestor using the above function. Only returns single most specific - assumes unique exists. ''' # Take the element at maximum depth. return max(common_parent_go_ids(goterms, godag), key=lambd...
This function gets the nearest common ancestor using the above function. Only returns single most specific - assumes unique exists.