positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """ Creates user. Depends on get_username pipeline. """ if user: return {'user': user} if not username: return None email = details.get('email') original_email = None # email is requir...
Creates user. Depends on get_username pipeline.
def _region_code_for_number_from_list(numobj, regions): """Find the region in a list that matches a number""" national_number = national_significant_number(numobj) for region_code in regions: # If leading_digits is present, use this. Otherwise, do full # validation. # Metadata cannot...
Find the region in a list that matches a number
def configure_ghostboxes(self, nghostx=0, nghosty=0, nghostz=0): """ Initialize the ghost boxes. This function only needs to be called it boundary conditions other than "none" or "open" are used. In such a case the number of ghostboxes must be known and is set with this functio...
Initialize the ghost boxes. This function only needs to be called it boundary conditions other than "none" or "open" are used. In such a case the number of ghostboxes must be known and is set with this function. Parameters ---------- nghostx, nghosty, nghostz ...
def waitForResponse(self, timeOut=None): """blocks until the response arrived or timeout is reached.""" self.__evt.wait(timeOut) if self.waiting(): raise Timeout() else: if self.response["error"]: raise Exception(self.response["error"]) ...
blocks until the response arrived or timeout is reached.
def upvoters(self): """获取答案点赞用户,返回生成器. :return: 点赞用户 :rtype: Author.Iterable """ self._make_soup() next_req = '/answer/' + str(self.aid) + '/voters_profile' while next_req != '': data = self._session.get(Zhihu_URL + next_req).json() next_r...
获取答案点赞用户,返回生成器. :return: 点赞用户 :rtype: Author.Iterable
def resolve_att(a, fallback): """ replace '' and 'default' by fallback values """ if a is None: return fallback if a.background in ['default', '']: bg = fallback.background else: bg = a.background if a.foreground in ['default', '']: fg = fallback.foreground else: ...
replace '' and 'default' by fallback values
def pierson(self, ddof=0): """Matrix of pierson linear correlation coefficients (rho values) for each pair of columns https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient >>> Columns([[1, 2, 3], [4, 5, 6]]).pierson() [[1.0, 1.0], [1.0, 1.0]] >>> Columns([...
Matrix of pierson linear correlation coefficients (rho values) for each pair of columns https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient >>> Columns([[1, 2, 3], [4, 5, 6]]).pierson() [[1.0, 1.0], [1.0, 1.0]] >>> Columns([[1, 2, 3], [2.5, 3.5, 4.5]], transpose...
def _latch_file_info(self): """Internal function to update the dictionaries keeping track of input and output files """ self.files.file_dict.clear() self.files.latch_file_info(self.args)
Internal function to update the dictionaries keeping track of input and output files
def abort_thread(): """ This function checks to see if the user has indicated that they want the currently running execution to stop prematurely by marking the running thread as aborted. It only applies to operations that are run within CauldronThreads and not the main thread. """ thread = ...
This function checks to see if the user has indicated that they want the currently running execution to stop prematurely by marking the running thread as aborted. It only applies to operations that are run within CauldronThreads and not the main thread.
def write_data(self, buf): """Send data to the device. If the write fails for any reason, an :obj:`IOError` exception is raised. :param buf: the data to send. :type buf: list(int) :return: success status. :rtype: bool """ bmRequestType = usb....
Send data to the device. If the write fails for any reason, an :obj:`IOError` exception is raised. :param buf: the data to send. :type buf: list(int) :return: success status. :rtype: bool
def get(self, key, default=None): """Retrieve the first value for a marker or None.""" for k, v in self: if k == key: return v return default
Retrieve the first value for a marker or None.
def is_user_in_group(self, user, group): """Test for whether a user is in a group. There is also the ability in the API to test for whether multiple users are members of an LDAP group, but you should just call is_user_in_group over an enumerated list of users. Args: ...
Test for whether a user is in a group. There is also the ability in the API to test for whether multiple users are members of an LDAP group, but you should just call is_user_in_group over an enumerated list of users. Args: user: String username. group: String gr...
def get_user( self, identified_with, identifier, req, resp, resource, uri_kwargs ): """Return default user object.""" return self.user
Return default user object.
def get_symmetric_image(self): """Creates a new DirectedHypergraph object that is the symmetric image of this hypergraph (i.e., identical hypergraph with all edge directions reversed). Copies of each of the nodes' and hyperedges' attributes are stored and used in the new hypergra...
Creates a new DirectedHypergraph object that is the symmetric image of this hypergraph (i.e., identical hypergraph with all edge directions reversed). Copies of each of the nodes' and hyperedges' attributes are stored and used in the new hypergraph. :returns: DirectedHypergraph ...
def some(args): """ %prog some idsfile afastq [bfastq] Select a subset of the reads with ids present in the idsfile. `bfastq` is optional (only if reads are paired) """ p = OptionParser(some.__doc__) opts, args = p.parse_args(args) if len(args) not in (2, 3): sys.exit(not p.pri...
%prog some idsfile afastq [bfastq] Select a subset of the reads with ids present in the idsfile. `bfastq` is optional (only if reads are paired)
def handleOACK(self, pkt): """This method handles an OACK from the server, syncing any accepted options.""" if len(pkt.options.keys()) > 0: if pkt.match_options(self.context.options): log.info("Successful negotiation of options") # Set options to OACK ...
This method handles an OACK from the server, syncing any accepted options.
def _clean_java_out(version_str): """Remove extra environmental information reported in java when querying for versions. Java will report information like _JAVA_OPTIONS environmental variables in the output. """ out = [] for line in version_str.decode().split("\n"): if line.startswith("Pick...
Remove extra environmental information reported in java when querying for versions. Java will report information like _JAVA_OPTIONS environmental variables in the output.
def custom_update(self, data, pred, obj): ''' Updates existing entity proprty based on the predicate input ''' if isinstance(data[pred], str): # for all simple properties of str value data[pred] = str(obj) else: # synonyms, superclasses, and existing_ids have special requirements ...
Updates existing entity proprty based on the predicate input
def _input_likelihood(self, logits: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: """ Computes the (batch_size,) denominator term for the log-likelihood, which is the sum of the likelihoods across all possible state sequences. """ batch_size, sequence_length, num_tags = logi...
Computes the (batch_size,) denominator term for the log-likelihood, which is the sum of the likelihoods across all possible state sequences.
def prepare(self, rule): """ Parse and/or compile given rule into rule tree. :param rule: Filtering grammar rule. :return: Parsed and/or compiled rule. """ if self.parser: rule = self.parser.parse(rule) if self.compiler: rule = self.compil...
Parse and/or compile given rule into rule tree. :param rule: Filtering grammar rule. :return: Parsed and/or compiled rule.
def solar_zenith(self, dateandtime, latitude, longitude): """Calculates the solar zenith angle. :param dateandtime: The date and time for which to calculate the angle. :type dateandtime: :class:`~datetime.datetime` :param latitude: Latitude - Northern latit...
Calculates the solar zenith angle. :param dateandtime: The date and time for which to calculate the angle. :type dateandtime: :class:`~datetime.datetime` :param latitude: Latitude - Northern latitudes should be positive :type latitude: float :par...
def replacebranch(idf, loop, branch, listofcomponents, fluid=None, debugsave=False, testing=None): """It will replace the components in the branch with components in listofcomponents""" if fluid is None: fluid = '' # -------- testing --------...
It will replace the components in the branch with components in listofcomponents
def get_logs(self, request): """ Get logs from log service. Unsuccessful opertaion will cause an LogException. Note: for larger volume of data (e.g. > 1 million logs), use get_log_all :type request: GetLogsRequest :param request: the GetLogs request parameters class. ...
Get logs from log service. Unsuccessful opertaion will cause an LogException. Note: for larger volume of data (e.g. > 1 million logs), use get_log_all :type request: GetLogsRequest :param request: the GetLogs request parameters class. :return: GetLogsResponse ...
def add(self, date_range, library_name): """ Adds the library with the given date range to the underlying collection of libraries used by this store. The underlying libraries should not overlap as the date ranges are assumed to be CLOSED_CLOSED by this function and the rest of the class....
Adds the library with the given date range to the underlying collection of libraries used by this store. The underlying libraries should not overlap as the date ranges are assumed to be CLOSED_CLOSED by this function and the rest of the class. Arguments: date_range: A date range provid...
def cleanup_deployments(self): """ Delete all deployments created in namespaces associated with this backend :return: None """ deployments = self.list_deployments() for deployment in deployments: if deployment.namespace in self.managed_namespaces: ...
Delete all deployments created in namespaces associated with this backend :return: None
def get_parent_bank_ids(self, bank_id): """Gets the parent ``Ids`` of the given bank. arg: bank_id (osid.id.Id): a bank ``Id`` return: (osid.id.IdList) - the parent ``Ids`` of the bank raise: NotFound - ``bank_id`` is not found raise: NullArgument - ``bank_id`` is ``null`` ...
Gets the parent ``Ids`` of the given bank. arg: bank_id (osid.id.Id): a bank ``Id`` return: (osid.id.IdList) - the parent ``Ids`` of the bank raise: NotFound - ``bank_id`` is not found raise: NullArgument - ``bank_id`` is ``null`` raise: OperationFailed - unable to complet...
def discrete_random_draw(data, nb=1): ''' Code from Steve Nguyen''' data = np.array(data) if not data.any(): data = np.ones_like(data) data = data/data.sum() xk = np.arange(len(data)) custm = stats.rv_discrete(name='custm', values=(xk, data)) return custm.rvs(size=nb)
Code from Steve Nguyen
def head(self, n=10): """ Display the top of the file. Args: n (int): Number of lines to display """ r = self.__repr__().split('\n') print('\n'.join(r[:n]), end=' ')
Display the top of the file. Args: n (int): Number of lines to display
def _represent_undefined(self, data): """Raises flag for objects that cannot be represented""" raise RepresenterError( _format("Cannot represent an object: {0!A} of type: {1}; " "yaml_representers: {2!A}, " "yaml_multi_representers: {3!A}", data, type(data...
Raises flag for objects that cannot be represented
def is_uuid(value, **kwargs): """Indicate whether ``value`` contains a :class:`UUID <python:uuid.UUID>` :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate ...
Indicate whether ``value`` contains a :class:`UUID <python:uuid.UUID>` :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates ...
def fields(self, *fields): ''' Only return the specified fields from the object. Accessing a \ field that was not specified in ``fields`` will result in a \ :class:``ommongo.document.FieldNotRetrieved`` exception being \ raised :param fields: Instances of :class...
Only return the specified fields from the object. Accessing a \ field that was not specified in ``fields`` will result in a \ :class:``ommongo.document.FieldNotRetrieved`` exception being \ raised :param fields: Instances of :class:``ommongo.query.QueryField`` specifyin...
def run_process(self, slug, inputs): """Run a new process from a running process.""" def export_files(value): """Export input files of spawned process.""" if isinstance(value, str) and os.path.isfile(value): # TODO: Use the protocol to export files and get the ...
Run a new process from a running process.
def _build_hash_string(self): """Function for build password hash string. Raises: PybooruError: When isn't provide hash string. PybooruError: When aren't provide username or password. PybooruError: When Pybooru can't add password to hash strring. """ ...
Function for build password hash string. Raises: PybooruError: When isn't provide hash string. PybooruError: When aren't provide username or password. PybooruError: When Pybooru can't add password to hash strring.
def snapshots(self, owner=None, restorable_by=None): """ Get all snapshots related to this volume. Note that this requires that all available snapshots for the account be retrieved from EC2 first and then the list is filtered client-side to contain only those for this volume. ...
Get all snapshots related to this volume. Note that this requires that all available snapshots for the account be retrieved from EC2 first and then the list is filtered client-side to contain only those for this volume. :type owner: str :param owner: If present, only the snapsh...
def get_init_container(self, init_command, init_args, env_vars, context_mounts, persistence_outputs, persistence_data): """Pod init container for sett...
Pod init container for setting outputs path.
def sprite(map, sprite, offset_x=None, offset_y=None, cache_buster=True): """ Returns the image and background position for use in a single shorthand property """ map = map.render() sprite_maps = _get_cache('sprite_maps') sprite_map = sprite_maps.get(map) sprite_name = String.unquoted(sp...
Returns the image and background position for use in a single shorthand property
def sbo(self, name): """Build all dependencies of a package """ if (self.meta.rsl_deps in ["on", "ON"] and "--resolve-off" not in self.flag): sys.setrecursionlimit(10000) dependencies = [] requires = SBoGrep(name).requires() if requ...
Build all dependencies of a package
def results(self): """If successfully created, add the cleaned `CifData` and `StructureData` as output nodes to the workchain. The filter and select calculations were successful, so we return the cleaned CifData node. If the `group_cif` was defined in the inputs, the node is added to it. If the...
If successfully created, add the cleaned `CifData` and `StructureData` as output nodes to the workchain. The filter and select calculations were successful, so we return the cleaned CifData node. If the `group_cif` was defined in the inputs, the node is added to it. If the structure should have been pa...
def get_session_id(self): """ get a unique id (shortish string) to allow simple aggregation of log records from multiple sources. This id is used for the life of the running program to allow extraction from all logs. WARING - this can give duplicate sessions when 2 apps hit it ...
get a unique id (shortish string) to allow simple aggregation of log records from multiple sources. This id is used for the life of the running program to allow extraction from all logs. WARING - this can give duplicate sessions when 2 apps hit it at the same time.
def sg_aconv(tensor, opt): r"""Applies a 2-D atrous (or dilated) convolution. Args: tensor: A 4-D `Tensor` (automatically passed by decorator). opt: size: A tuple/list of positive integers of length 2 representing `[kernel height, kernel width]`. Can be an integer if both valu...
r"""Applies a 2-D atrous (or dilated) convolution. Args: tensor: A 4-D `Tensor` (automatically passed by decorator). opt: size: A tuple/list of positive integers of length 2 representing `[kernel height, kernel width]`. Can be an integer if both values are the same. If n...
def number(self, p_todo): """ Returns the line number or text ID of a todo (depends on the configuration. """ if config().identifiers() == "text": return self.uid(p_todo) else: return self.linenumber(p_todo)
Returns the line number or text ID of a todo (depends on the configuration.
def _build_doc(self): """ Raises ------ ValueError * If a URL that lxml cannot parse is passed. Exception * Any other ``Exception`` thrown. For example, trying to parse a URL that is syntactically correct on a machine with no internet ...
Raises ------ ValueError * If a URL that lxml cannot parse is passed. Exception * Any other ``Exception`` thrown. For example, trying to parse a URL that is syntactically correct on a machine with no internet connection will fail. See...
def _build_model_factories(store): """Generate factories to construct objects from schemata""" result = {} for schemaname in store: schema = None try: schema = store[schemaname]['schema'] except KeyError: schemata_log("No schema found for ", schemaname, lv...
Generate factories to construct objects from schemata
def __list_uniques(self, date_range, field_name): """Retrieve a list of unique values in a given field within a date range. :param date_range: :param field_name: :return: list of unique values. """ # Get project list s = Search(using=self._es_conn, index=self._e...
Retrieve a list of unique values in a given field within a date range. :param date_range: :param field_name: :return: list of unique values.
def get_regex(regex): """ Ensure we have a compiled regular expression object. >>> import re >>> get_regex('string') # doctest: +ELLIPSIS <_sre.SRE_Pattern object at 0x...> >>> pattern = re.compile(r'string') >>> get_regex(pattern) is pattern True >>> get...
Ensure we have a compiled regular expression object. >>> import re >>> get_regex('string') # doctest: +ELLIPSIS <_sre.SRE_Pattern object at 0x...> >>> pattern = re.compile(r'string') >>> get_regex(pattern) is pattern True >>> get_regex(3) # doctest: +ELLIPSIS ...
def replace_u_end_month(month): """Find the latest legitimate month.""" month = month.lstrip('-') if month == 'uu' or month == '1u': return '12' if month == 'u0': return '10' if month == '0u': return '09' if month[1] in ['1', '2']: # 'u1' or 'u2' return mo...
Find the latest legitimate month.
def get_string(ea): """Read the string at the given ea. This function uses IDA's string APIs and does not implement any special logic. """ # We get the item-head because the `GetStringType` function only works on the head of an item. string_type = idc.GetStringType(idaapi.get_item_head(ea)) if...
Read the string at the given ea. This function uses IDA's string APIs and does not implement any special logic.
def _repr(self, *args, **kwargs): """Return a __repr__ string from the arguments provided to __init__. @param args: list of arguments to __init__ @param kwargs: dictionary of keyword arguments to __init__ @return: __repr__ string """ # Remove unnecessary empty keywords ...
Return a __repr__ string from the arguments provided to __init__. @param args: list of arguments to __init__ @param kwargs: dictionary of keyword arguments to __init__ @return: __repr__ string
def decode(self, query): """I transform query parameters into an L{OpenIDRequest}. If the query does not seem to be an OpenID request at all, I return C{None}. @param query: The query parameters as a dictionary with each key mapping to one value. @type query: dict ...
I transform query parameters into an L{OpenIDRequest}. If the query does not seem to be an OpenID request at all, I return C{None}. @param query: The query parameters as a dictionary with each key mapping to one value. @type query: dict @raises ProtocolError: When ...
def prj_create_user(self, *args, **kwargs): """Create a new project :returns: None :rtype: None :raises: None """ if not self.cur_prj: return user = self.create_user(projects=[self.cur_prj]) if user: userdata = djitemdata.UserItemD...
Create a new project :returns: None :rtype: None :raises: None
def set_ytick_labels(self, row, column, labels): """Manually specify the y-axis tick labels. :param row,column: specify the subplot. :param labels: list of tick labels. """ subplot = self.get_subplot_at(row, column) subplot.set_ytick_labels(labels)
Manually specify the y-axis tick labels. :param row,column: specify the subplot. :param labels: list of tick labels.
def add_transform_columns(self): """ add transformed values to the Pst.parameter_data attribute """ for col in ["parval1","parlbnd","parubnd","increment"]: if col not in self.parameter_data.columns: continue self.parameter_data.loc[:,col+"_trans"] = (self...
add transformed values to the Pst.parameter_data attribute
def put(self, path=None, url_kwargs=None, **kwargs): """ Sends a PUT request. :param path: The HTTP path (either absolute or relative). :param url_kwargs: Parameters to override in the generated URL. See `~hyperlink.URL`. :param **kwargs: Opti...
Sends a PUT request. :param path: The HTTP path (either absolute or relative). :param url_kwargs: Parameters to override in the generated URL. See `~hyperlink.URL`. :param **kwargs: Optional arguments that ``request`` takes. :return: response object
async def login(cls, credentials: AuthenticationCredentials, config: Config) -> 'Session': """Checks the given credentials for a valid login and returns a new session. The mailbox data is shared between concurrent and future sessions, but only for the lifetime of the process....
Checks the given credentials for a valid login and returns a new session. The mailbox data is shared between concurrent and future sessions, but only for the lifetime of the process.
def permissions(self, perms): """ A decorator that sets a list of permissions for a function. :param perms: The list of permission instances or classes. :return: A function """ if not isinstance(perms, (list, tuple)): perms = [perms] instances = [] ...
A decorator that sets a list of permissions for a function. :param perms: The list of permission instances or classes. :return: A function
def get_regions(self): """GetRegions. [Preview API] :rtype: :class:`<ProfileRegions> <azure.devops.v5_1.profile-regions.models.ProfileRegions>` """ response = self._send(http_method='GET', location_id='b129ca90-999d-47bb-ab37-0dcf784ee633', ...
GetRegions. [Preview API] :rtype: :class:`<ProfileRegions> <azure.devops.v5_1.profile-regions.models.ProfileRegions>`
def required_opts(opt, parser, opt_list, required_by=None): """Check that all the opts are defined Parameters ---------- opt : object Result of option parsing parser : object OptionParser instance. opt_list : list of strings required_by : string, optional the option ...
Check that all the opts are defined Parameters ---------- opt : object Result of option parsing parser : object OptionParser instance. opt_list : list of strings required_by : string, optional the option that requires these options (if applicable)
def preprocessing(self, algorithms): """Apply preprocessing algorithms. Parameters ---------- algorithms : a list objects Preprocessing allgorithms which get applied in order. Examples -------- >>> import preprocessing >>> a = HandwrittenData...
Apply preprocessing algorithms. Parameters ---------- algorithms : a list objects Preprocessing allgorithms which get applied in order. Examples -------- >>> import preprocessing >>> a = HandwrittenData(...) >>> preprocessing_queue = [(prepro...
def previous_row(self): """Move to previous row from currently selected row.""" row = self.currentIndex().row() rows = self.source_model.rowCount() if row == 0: row = rows self.selectRow(row - 1)
Move to previous row from currently selected row.
def get_available_tf_versions(include_prerelease=False): """Return available Terraform versions.""" tf_releases = json.loads( requests.get('https://releases.hashicorp.com/index.json').text )['terraform'] tf_versions = sorted([k # descending for k, _v in tf_releases['ve...
Return available Terraform versions.
def load_raw_rules(cls, url): "Load raw rules from url or package file." raw_rules = [] filename = url.split('/')[-1] # e.g.: easylist.txt try: with closing(request.get(url, stream=True)) as file: file.raise_for_status() # lines = 0 # to...
Load raw rules from url or package file.
def initialize_ocean_and_thresholds(world, ocean_level=1.0): """ Calculate the ocean, the sea depth and the elevation thresholds :param world: a world having elevation but not thresholds :param ocean_level: the elevation representing the ocean level :return: nothing, the world will be changed ""...
Calculate the ocean, the sea depth and the elevation thresholds :param world: a world having elevation but not thresholds :param ocean_level: the elevation representing the ocean level :return: nothing, the world will be changed
def output(memory, ofile=None): """ Filters the output removing useless preprocessor #directives and writes it to the given file or to the screen if no file is passed """ for m in memory: m = m.rstrip('\r\n\t ') # Ensures no trailing newlines (might with upon includes) if m and m[0] == ...
Filters the output removing useless preprocessor #directives and writes it to the given file or to the screen if no file is passed
def listProcessingEras(self, processing_version=''): """ Returns all processing eras in dbs """ conn = self.dbi.connection() try: result = self.pelst.execute(conn, processing_version) return result finally: if conn: conn...
Returns all processing eras in dbs
def limit_pos(p, se_pos, nw_pos): """ Limits position p to stay inside containing state :param p: Position to limit :param se_pos: Bottom/Right boundary :param nw_pos: Top/Left boundary :return: """ if p > se_pos: _update(p, se_pos) eli...
Limits position p to stay inside containing state :param p: Position to limit :param se_pos: Bottom/Right boundary :param nw_pos: Top/Left boundary :return:
def dump_autogen_code(fpath, autogen_text, codetype='python', fullprint=None, show_diff=None, dowrite=None): """ Helper that write a file if -w is given on command line, otherwise it just prints it out. It has the opption of comparing a diff to the file. """ import utool as ut ...
Helper that write a file if -w is given on command line, otherwise it just prints it out. It has the opption of comparing a diff to the file.
def _strip_column_name(col_name, keep_paren_contents=True): """ Utility script applying several regexs to a string. Intended to be used by `strip_column_names`. This function will: 1. replace informative punctuation components with text 2. (optionally) remove text within parentheses ...
Utility script applying several regexs to a string. Intended to be used by `strip_column_names`. This function will: 1. replace informative punctuation components with text 2. (optionally) remove text within parentheses 3. replace remaining punctuation/whitespace with _ 4. strip...
def numpy_to_texture(image): """Convert a NumPy image array to a vtk.vtkTexture""" if not isinstance(image, np.ndarray): raise TypeError('Unknown input type ({})'.format(type(image))) if image.ndim != 3 or image.shape[2] != 3: raise AssertionError('Input image must be nn by nm by RGB') g...
Convert a NumPy image array to a vtk.vtkTexture
def click_chain(self, selectors_list, by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT, spacing=0): """ This method clicks on a list of elements in succession. 'spacing' is the amount of time to wait between clicks. (sec) """ if self.timeout_multiplier and timeout == se...
This method clicks on a list of elements in succession. 'spacing' is the amount of time to wait between clicks. (sec)
def abi_splitext(filename): """ Split the ABINIT extension from a filename. "Extension" are found by searching in an internal database. Returns "(root, ext)" where ext is the registered ABINIT extension The final ".nc" is included (if any) >>> assert abi_splitext("foo_WFK") == ('foo_', 'WFK') ...
Split the ABINIT extension from a filename. "Extension" are found by searching in an internal database. Returns "(root, ext)" where ext is the registered ABINIT extension The final ".nc" is included (if any) >>> assert abi_splitext("foo_WFK") == ('foo_', 'WFK') >>> assert abi_splitext("/home/guido...
def __cyrillic_to_roman(self, word): """ Transliterate a Russian word into the Roman alphabet. A Russian word whose letters consist of the Cyrillic alphabet are transliterated into the Roman alphabet in order to ease the forthcoming stemming process. :param word: The wo...
Transliterate a Russian word into the Roman alphabet. A Russian word whose letters consist of the Cyrillic alphabet are transliterated into the Roman alphabet in order to ease the forthcoming stemming process. :param word: The word that is transliterated. :type word: unicode ...
def adapt(self, d, x): """ Adapt weights according one desired value and its input. **Args:** * `d` : desired value (float) * `x` : input array (1-dimensional array) """ y = np.dot(self.w, x) e = d - y R1 = np.dot(np.dot(np.dot(self.R,x),x.T),se...
Adapt weights according one desired value and its input. **Args:** * `d` : desired value (float) * `x` : input array (1-dimensional array)
def delegate(self, success, **kwargs): """Delegate success/failure to the right method.""" if success: self.succeeded(**kwargs) else: self.failed(**kwargs)
Delegate success/failure to the right method.
def get_variables(self) -> Set[str]: """Find all the variables specified in a format string. This returns a list of all the different variables specified in a format string, that is the variables inside the braces. """ variables = set() for cmd in self._cmd: ...
Find all the variables specified in a format string. This returns a list of all the different variables specified in a format string, that is the variables inside the braces.
def list_certificates(self, **kwargs): """List certificates registered to organisation. Currently returns partially populated certificates. To obtain the full certificate object: `[get_certificate(certificate_id=cert['id']) for cert in list_certificates]` :param int limit: The number o...
List certificates registered to organisation. Currently returns partially populated certificates. To obtain the full certificate object: `[get_certificate(certificate_id=cert['id']) for cert in list_certificates]` :param int limit: The number of certificates to retrieve. :param str ord...
def make_data(self, message): """ make data string from message according to transport_content_type Returns: str: message data """ if not isinstance(message, Message): return message return message.export(self.transport_content_type)
make data string from message according to transport_content_type Returns: str: message data
def add(self, count, timestamp=None): """Add a value at the specified time to the series. :param count: The number of work items ready at the specified time. :param timestamp: The timestamp to add. Defaults to None, meaning current time. It should be strictly greater (ne...
Add a value at the specified time to the series. :param count: The number of work items ready at the specified time. :param timestamp: The timestamp to add. Defaults to None, meaning current time. It should be strictly greater (newer) than the last added timestamp.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id if hasattr(self, 'field') and self.field is not None: _dict['field'] = ...
Return a json dictionary representing this model.
def find_version(file_path): """ Scrape version information from specified file path. """ with open(file_path, 'r') as f: file_contents = f.read() version_match = re.search(r"^__version__\s*=\s*['\"]([^'\"]*)['\"]", file_contents, re.M) if version_match: ...
Scrape version information from specified file path.
def cmd_output(self, args): '''handle output commands''' if len(args) < 1 or args[0] == "list": self.cmd_output_list() elif args[0] == "add": if len(args) != 2: print("Usage: output add OUTPUT") return self.cmd_output_add(args[1...
handle output commands
def _inform_if_path_does_not_exist(path): """ If the path does not exist, print a message saying so. This is intended to be helpful to users if they specify a custom path that eg cannot find. """ expanded_path = get_expanded_path(path) if not os.path.exists(expanded_path): print('Could n...
If the path does not exist, print a message saying so. This is intended to be helpful to users if they specify a custom path that eg cannot find.
def lookup(self, short_url): ''' Lookup an URL shortened with `is.gd - v.gd url service <http://is.gd/developers.php>`_ and return the real url :param short_url: the url shortened with .gd service :type short_url: str. :returns: str. -- T...
Lookup an URL shortened with `is.gd - v.gd url service <http://is.gd/developers.php>`_ and return the real url :param short_url: the url shortened with .gd service :type short_url: str. :returns: str. -- The original url that was shortened with .gd service ...
def ShowInfo(self): """Shows information about available hashers, parsers, plugins, etc.""" self._output_writer.Write( '{0:=^80s}\n'.format(' log2timeline/plaso information ')) plugin_list = self._GetPluginData() for header, data in plugin_list.items(): table_view = views.ViewsFactory.Get...
Shows information about available hashers, parsers, plugins, etc.
def triggerHapticPulse(self, unControllerDeviceIndex, unAxisId, usDurationMicroSec): """ Trigger a single haptic pulse on a controller. After this call the application may not trigger another haptic pulse on this controller and axis combination for 5ms. This function is deprecated in favor of th...
Trigger a single haptic pulse on a controller. After this call the application may not trigger another haptic pulse on this controller and axis combination for 5ms. This function is deprecated in favor of the new IVRInput system.
def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=ke...
Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name
def send(self, data=None, headers=None, ttl=0, gcm_key=None, reg_id=None, content_encoding="aes128gcm", curl=False, timeout=None): """Encode and send the data to the Push Service. :param data: A serialized block of data (see encode() ). :type data: str :param headers: A dic...
Encode and send the data to the Push Service. :param data: A serialized block of data (see encode() ). :type data: str :param headers: A dictionary containing any additional HTTP headers. :type headers: dict :param ttl: The Time To Live in seconds for this message if the ...
def read(self, num): """Read ``num`` number of bytes from the stream. Note that this will automatically resets/ends the current bit-reading if it does not end on an even byte AND ``self.padded`` is True. If ``self.padded`` is True, then the entire stream is treated as a bitstream. ...
Read ``num`` number of bytes from the stream. Note that this will automatically resets/ends the current bit-reading if it does not end on an even byte AND ``self.padded`` is True. If ``self.padded`` is True, then the entire stream is treated as a bitstream. :num: number of bytes to read...
def calculate_tensor_to_probability_map_output_shapes(operator): ''' Allowed input/output patterns are ONNX < 1.2 1. [1, C] ---> ---> A map 2. [1, C_1, ..., C_n] ---> A map ONNX >= 1.2 1. [N, C] ---> ---> A sequence of maps 2. [N, C_1, ..., C_n] ---> A sequence of maps ...
Allowed input/output patterns are ONNX < 1.2 1. [1, C] ---> ---> A map 2. [1, C_1, ..., C_n] ---> A map ONNX >= 1.2 1. [N, C] ---> ---> A sequence of maps 2. [N, C_1, ..., C_n] ---> A sequence of maps Note that N must be 1 currently if you're using ONNX<1.2 because old ZipMa...
def create_matching_kernel(source_psf, target_psf, window=None): """ Create a kernel to match 2D point spread functions (PSF) using the ratio of Fourier transforms. Parameters ---------- source_psf : 2D `~numpy.ndarray` The source PSF. The source PSF should have higher resolution ...
Create a kernel to match 2D point spread functions (PSF) using the ratio of Fourier transforms. Parameters ---------- source_psf : 2D `~numpy.ndarray` The source PSF. The source PSF should have higher resolution (i.e. narrower) than the target PSF. ``source_psf`` and ``target_...
def type_errors(self, context=None): """Get a list of type errors which can occur during inference. Each TypeError is represented by a :class:`BadBinaryOperationMessage`, which holds the original exception. :returns: The list of possible type errors. :rtype: list(BadBinaryOpera...
Get a list of type errors which can occur during inference. Each TypeError is represented by a :class:`BadBinaryOperationMessage`, which holds the original exception. :returns: The list of possible type errors. :rtype: list(BadBinaryOperationMessage)
def plot_summary_distributions(df,ax=None,label_post=False,label_prior=False, subplots=False,figsize=(11,8.5),pt_color='b'): """ helper function to plot gaussian distrbutions from prior and posterior means and standard deviations Parameters ---------- df : pandas.Data...
helper function to plot gaussian distrbutions from prior and posterior means and standard deviations Parameters ---------- df : pandas.DataFrame a dataframe and csv file. Must have columns named: 'prior_mean','prior_stdev','post_mean','post_stdev'. If loaded from a csv file, c...
def _update_limits_from_api(self): """ Query EC2's DescribeAccountAttributes API action and update the network interface limit, as needed. Updates ``self.limits``. More info on the network interface limit, from the docs: 'This limit is the greater of either the default limit (35...
Query EC2's DescribeAccountAttributes API action and update the network interface limit, as needed. Updates ``self.limits``. More info on the network interface limit, from the docs: 'This limit is the greater of either the default limit (350) or your On-Demand Instance limit multiplied ...
def apply_to_event(self, event, hint=None): # type: (Dict[str, Any], Dict[str, Any]) -> Optional[Dict[str, Any]] """Applies the information contained on the scope to the given event.""" def _drop(event, cause, ty): # type: (Dict[str, Any], Callable, str) -> Optional[Any] ...
Applies the information contained on the scope to the given event.
def _parse_signal_lines(signal_lines): """ Extract fields from a list of signal line strings into a dictionary. """ n_sig = len(signal_lines) # Dictionary for signal fields signal_fields = {} # Each dictionary field is a list for field in SIGNAL_SPECS.index: signal_fields[field...
Extract fields from a list of signal line strings into a dictionary.
def create(self, friendly_name=None, description=None): """Creates the Dataset with the specified friendly name and description. Args: friendly_name: (optional) the friendly name for the dataset if it is being created. description: (optional) a description for the dataset if it is being created. ...
Creates the Dataset with the specified friendly name and description. Args: friendly_name: (optional) the friendly name for the dataset if it is being created. description: (optional) a description for the dataset if it is being created. Returns: The Dataset. Raises: Exception if th...
def clone(self, config, **kwargs): """Make a clone of this analysis instance.""" gta = GTAnalysis(config, **kwargs) gta._roi = copy.deepcopy(self.roi) return gta
Make a clone of this analysis instance.
def crescent_data(model_type='Full', num_inducing=10, seed=default_seed, kernel=None, optimize=True, plot=True): """ Run a Gaussian process classification on the crescent data. The demonstration calls the basic GP classification model and uses EP to approximate the likelihood. :param model_type: type of mo...
Run a Gaussian process classification on the crescent data. The demonstration calls the basic GP classification model and uses EP to approximate the likelihood. :param model_type: type of model to fit ['Full', 'FITC', 'DTC']. :param inducing: number of inducing variables (only used for 'FITC' or 'DTC'). :t...
def _get_converter(self, converter_str): """find converter function reference by name find converter by name, converter name follows this convention: Class.method or: method The first type of converter class/function must be available in current modul...
find converter function reference by name find converter by name, converter name follows this convention: Class.method or: method The first type of converter class/function must be available in current module. The second type of converter must be avai...
def query(cls, volume=None, state=None, offset=None, limit=None, api=None): """ Query (List) exports. :param volume: Optional volume identifier. :param state: Optional import sate. :param api: Api instance. :return: Collection object. """ ap...
Query (List) exports. :param volume: Optional volume identifier. :param state: Optional import sate. :param api: Api instance. :return: Collection object.
def host(value): """ Validates that the value is a valid network location """ if not value: return (True, "") try: host,port = value.split(":") except ValueError as _: return (False, "value needs to be <host>:<port>") try: int(port) except ValueError as _: ...
Validates that the value is a valid network location