code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def open(self, options): """ Open and import the refrenced schema. @param options: An options dictionary. @type options: L{options.Options} @return: The referenced schema. @rtype: L{Schema} """ if self.opened: return self.opened = True ...
Open and import the refrenced schema. @param options: An options dictionary. @type options: L{options.Options} @return: The referenced schema. @rtype: L{Schema}
def nodeInLanguageStem(_: Context, n: Node, s: ShExJ.LanguageStem) -> bool: """ http://shex.io/shex-semantics/#values **nodeIn**: asserts that an RDF node n is equal to an RDF term s or is in a set defined by a :py:class:`ShExJ.IriStem`, :py:class:`LiteralStem` or :py:class:`LanguageStem`. ...
http://shex.io/shex-semantics/#values **nodeIn**: asserts that an RDF node n is equal to an RDF term s or is in a set defined by a :py:class:`ShExJ.IriStem`, :py:class:`LiteralStem` or :py:class:`LanguageStem`. The expression `nodeInLanguageStem(n, s)` is satisfied iff: #) `s` is a :p...
def handle_option_error(error): """Raises exception if error in option command found. Purpose: As of tmux 2.4, there are now 3 different types of option errors: - unknown option - invalid option - ambiguous option Before 2.4, unknown option was the user. All errors raised will have the b...
Raises exception if error in option command found. Purpose: As of tmux 2.4, there are now 3 different types of option errors: - unknown option - invalid option - ambiguous option Before 2.4, unknown option was the user. All errors raised will have the base error of :exc:`exc.OptionError`. So...
def _factorize_array(values, na_sentinel=-1, size_hint=None, na_value=None): """Factorize an array-like to labels and uniques. This doesn't do any coercion of types or unboxing before factorization. Parameters ---------- values : ndarray na_sentinel : int, default -1 s...
Factorize an array-like to labels and uniques. This doesn't do any coercion of types or unboxing before factorization. Parameters ---------- values : ndarray na_sentinel : int, default -1 size_hint : int, optional Passsed through to the hashtable's 'get_labels' method na_value : ob...
def igetattr(self, name, context=None): """Inferred getattr, which returns an iterator of inferred statements.""" try: return bases._infer_stmts(self.getattr(name, context), context, frame=self) except exceptions.AttributeInferenceError as error: raise exceptions.Inferenc...
Inferred getattr, which returns an iterator of inferred statements.
def deserialize(data): """ Create instance from serial data """ # Import module & get class try: module = import_module(data.get('class').get('module')) cls = getattr(module, data.get('class').get('name')) except ImportError: raise Impo...
Create instance from serial data
def setEventCallback(self, event, callback): """ Set a function to call for a given event. event must be one of: TRANSFER_COMPLETED TRANSFER_ERROR TRANSFER_TIMED_OUT TRANSFER_CANCELLED TRANSFER_STALL TRANSFER_NO_DEVICE ...
Set a function to call for a given event. event must be one of: TRANSFER_COMPLETED TRANSFER_ERROR TRANSFER_TIMED_OUT TRANSFER_CANCELLED TRANSFER_STALL TRANSFER_NO_DEVICE TRANSFER_OVERFLOW
def uuid4(self, cast_to=str): """ Generates a random UUID4 string. :param cast_to: Specify what type the UUID should be cast to. Default is `str` :type cast_to: callable """ # Based on http://stackoverflow.com/q/41186818 return cast_to(uuid.UUID(int=self.generator...
Generates a random UUID4 string. :param cast_to: Specify what type the UUID should be cast to. Default is `str` :type cast_to: callable
def normalize_linefeeds(self, a_string): """Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.` :param a_string: A string that may have non-normalized line feeds i.e. output returned from device, or a device prompt :type a_string: str """ newline = re.compile("(\r\r\r\n|\r\r\n|...
Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.` :param a_string: A string that may have non-normalized line feeds i.e. output returned from device, or a device prompt :type a_string: str
def get_data(self, query, fields_convert_map, encoding='utf-8', auto_convert=True, include_hidden=False, header=None): """ If convert=True, will convert field value """ fields_convert_map = fields_convert_map or {} d = self.fields_convert_map.copy() ...
If convert=True, will convert field value
def mcmc_emcee(self, n_walkers, n_run, n_burn, mean_start, sigma_start): """ returns the mcmc analysis of the parameter space """ sampler = emcee.EnsembleSampler(n_walkers, self.cosmoParam.numParam, self.chain.likelihood) p0 = emcee.utils.sample_ball(mean_start, sigma_start, n_wa...
returns the mcmc analysis of the parameter space
def delete_pool(hostname, username, password, name): ''' Delete an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted ''' re...
Delete an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted
def get_ansible_by_id(self, ansible_id): """Return a ansible with that id or None.""" for elem in self.ansible_hosts: if elem.id == ansible_id: return elem return None
Return a ansible with that id or None.
def rightsibling(node): """ Return Right Sibling of `node`. >>> from anytree import Node >>> dan = Node("Dan") >>> jet = Node("Jet", parent=dan) >>> jan = Node("Jan", parent=dan) >>> joe = Node("Joe", parent=dan) >>> rightsibling(dan) >>> rightsibling(jet) Node('/Dan/Jan') >...
Return Right Sibling of `node`. >>> from anytree import Node >>> dan = Node("Dan") >>> jet = Node("Jet", parent=dan) >>> jan = Node("Jan", parent=dan) >>> joe = Node("Joe", parent=dan) >>> rightsibling(dan) >>> rightsibling(jet) Node('/Dan/Jan') >>> rightsibling(jan) Node('/Dan/...
def _process_element(self, pos, e): """ Parses an incoming HTML element/node for data. pos -- the part of the element being parsed (start/end) e -- the element being parsed """ tag, class_attr = _tag_and_class_attr(e) start_of_message = tag == '...
Parses an incoming HTML element/node for data. pos -- the part of the element being parsed (start/end) e -- the element being parsed
def getWithPrompt(self): """Interactively prompt for parameter value""" if self.prompt: pstring = self.prompt.split("\n")[0].strip() else: pstring = self.name if self.choice: schoice = list(map(self.toString, self.choice)) pstring = pstring...
Interactively prompt for parameter value
def set_rendering_intent(self, rendering_intent): """Set rendering intent variant for sRGB chunk""" if rendering_intent not in (None, PERCEPTUAL, RELATIVE_COLORIMETRIC, SATURATION, ...
Set rendering intent variant for sRGB chunk
def get_position(self, dt): """Given dt in [0, 1], return the current position of the tile.""" return self.sx + self.dx * dt, self.sy + self.dy * dt
Given dt in [0, 1], return the current position of the tile.
def porttree_matches(name): ''' Returns a list containing the matches for a given package name from the portage tree. Note that the specific version of the package will not be provided for packages that have several versions in the portage tree, but rather the name of the package (i.e. "dev-python/p...
Returns a list containing the matches for a given package name from the portage tree. Note that the specific version of the package will not be provided for packages that have several versions in the portage tree, but rather the name of the package (i.e. "dev-python/paramiko").
def render(value): """ This function finishes the url pattern creation by adding starting character ^ end possibly by adding end character at the end :param value: naive URL value :return: raw string """ # Empty urls if not value: # use case: wild card imports return r'^$' ...
This function finishes the url pattern creation by adding starting character ^ end possibly by adding end character at the end :param value: naive URL value :return: raw string
def selected(self, request, tag): """ Render a selected attribute on the given tag if the wrapped L{Option} instance is selected. """ if self.option.selected: tag(selected='selected') return tag
Render a selected attribute on the given tag if the wrapped L{Option} instance is selected.
def create_groups(iam_client, groups): """ Create a number of IAM group, silently handling exceptions when entity already exists . :param iam_client: AWS API client for IAM :param groups: Name of IAM groups to be created. ...
Create a number of IAM group, silently handling exceptions when entity already exists . :param iam_client: AWS API client for IAM :param groups: Name of IAM groups to be created. :return: None
def _adjusted_script_code(self, script): ''' Checks if the script code pased in to the sighash function is already length-prepended This will break if there's a redeem script that's just a pushdata That won't happen in practice Args: script (bytes): the spend...
Checks if the script code pased in to the sighash function is already length-prepended This will break if there's a redeem script that's just a pushdata That won't happen in practice Args: script (bytes): the spend script Returns: (bytes): the length-prep...
def parse_model_group(path, group): """Parse a structured model group as obtained from a YAML file Path can be given as a string or a context. """ context = FilePathContext(path) for reaction_id in group.get('reactions', []): yield reaction_id # Parse subgroups for reaction_id in...
Parse a structured model group as obtained from a YAML file Path can be given as a string or a context.
def _Decode(self, codec_name, data): """Decode data with the given codec name.""" try: return data.decode(codec_name, "replace") except LookupError: raise RuntimeError("Codec could not be found.") except AssertionError: raise RuntimeError("Codec failed to decode")
Decode data with the given codec name.
def writeList(self, register, data): """Write bytes to the specified register.""" self._idle() self._transaction_start() self._i2c_start() self._i2c_write_bytes([self._address_byte(False), register] + data) self._i2c_stop() response = self._transaction_end() ...
Write bytes to the specified register.
def dev(): """Define dev stage""" env.roledefs = { 'web': ['192.168.1.2'], 'lb': ['192.168.1.2'], } env.user = 'vagrant' env.backends = env.roledefs['web'] env.server_name = 'django_search_model-dev.net' env.short_server_name = 'django_search_model-dev' env.stat...
Define dev stage
def backup_db( aws_access_key_id, aws_secret_access_key, bucket_name, s3_folder, database, mysql_host, mysql_port, db_user, db_pass, db_backups_dir, backup_aging_time): """ dumps databases into /backups, uploads to s3, d...
dumps databases into /backups, uploads to s3, deletes backups older than a month fab -f ./fabfile.py backup_dbs :param aws_access_key_id: :param aws_secret_access_key: :param bucket_name: :param database: :param mysql_host: :param mysql_port: :param db_pass: :param db_backups_dir: ...
def breakRankTies(self, oldsym, newsym): """break Ties to form a new list with the same integer ordering from high to low Example old = [ 4, 2, 4, 7, 8] (Two ties, 4 and 4) new = [60, 2 61,90,99] res = [ 4, 0, 3, 1, 2] * * This tie is broken i...
break Ties to form a new list with the same integer ordering from high to low Example old = [ 4, 2, 4, 7, 8] (Two ties, 4 and 4) new = [60, 2 61,90,99] res = [ 4, 0, 3, 1, 2] * * This tie is broken in this case
def getAngle(self, mode='deg'): """ return bend angle :param mode: 'deg' or 'rad' :return: deflecting angle in RAD """ if self.refresh is True: self.getMatrix() try: if self.mflag: if mode == 'deg': return self...
return bend angle :param mode: 'deg' or 'rad' :return: deflecting angle in RAD
def _ConvertDictToObject(self, json_dict): """Converts a JSON dict into a path specification object. The dictionary of the JSON serialized objects consists of: { '__type__': 'PathSpec' 'type_indicator': 'OS' 'parent': { ... } ... } Here '__type__' indicates the obje...
Converts a JSON dict into a path specification object. The dictionary of the JSON serialized objects consists of: { '__type__': 'PathSpec' 'type_indicator': 'OS' 'parent': { ... } ... } Here '__type__' indicates the object base type in this case this should be 'Path...
def most_similar(self, keyword, num): """ input: keyword term of top n output: keyword result in json formmat """ try: result = self.model.most_similar(keyword, topn = num) # most_similar return a list return {'key':keyword, 'value':result, 'similarity':1}...
input: keyword term of top n output: keyword result in json formmat
def get_asset_notification_session(self, asset_receiver, proxy): """Gets the notification session for notifications pertaining to asset changes. arg: asset_receiver (osid.repository.AssetReceiver): the notification callback arg proxy (osid.proxy.Proxy): a proxy ...
Gets the notification session for notifications pertaining to asset changes. arg: asset_receiver (osid.repository.AssetReceiver): the notification callback arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetNotificationSession) - an ...
def get_set(self, flag, new): """ Return the boolean value of 'flag'. If 'new' is set, the flag is updated, and the value before update is returned. """ old = self._is_set(flag) if new is True: self._set(flag) elif new is False: sel...
Return the boolean value of 'flag'. If 'new' is set, the flag is updated, and the value before update is returned.
def remove_trailing(needle, haystack): """Remove trailing needle string (if exists). >>> remove_trailing('Test', 'ThisAndThatTest') 'ThisAndThat' >>> remove_trailing('Test', 'ArbitraryName') 'ArbitraryName' """ if haystack[-len(needle):] == needle: return haystack[:-len(needle)] ...
Remove trailing needle string (if exists). >>> remove_trailing('Test', 'ThisAndThatTest') 'ThisAndThat' >>> remove_trailing('Test', 'ArbitraryName') 'ArbitraryName'
def bibitems(self): """List of bibitem strings appearing in the document.""" bibitems = [] lines = self.text.split('\n') for i, line in enumerate(lines): if line.lstrip().startswith(u'\\bibitem'): # accept this line # check if next line is also...
List of bibitem strings appearing in the document.
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): """Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows ...
Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
def _set_access_log(self, config, level): """ Configure access logs """ access_handler = self._get_param( 'global', 'log.access_handler', config, 'syslog', ) # log format for syslog syslog_formatter = logging.Formatter(...
Configure access logs
def classify(self, dataset, missing_value_action='auto'): """ Return predictions for ``dataset``, using the trained supervised_learning model. Predictions are generated as class labels (0 or 1). Parameters ---------- dataset: SFrame Dataset of new obs...
Return predictions for ``dataset``, using the trained supervised_learning model. Predictions are generated as class labels (0 or 1). Parameters ---------- dataset: SFrame Dataset of new observations. Must include columns with the same names as the feature...
def integrate(self, rate, timestep): """Advance a time varying quaternion to its value at a time `timestep` in the future. The Quaternion object will be modified to its future value. It is guaranteed to remain a unit quaternion. Params: rate: numpy 3-array (or array-like) desc...
Advance a time varying quaternion to its value at a time `timestep` in the future. The Quaternion object will be modified to its future value. It is guaranteed to remain a unit quaternion. Params: rate: numpy 3-array (or array-like) describing rotation rates about the glob...
def tree_to_nodes(tree, context=None, metadata=None): """Assembles ``tree`` nodes into object models. If ``context`` is supplied, it will be used to contextualize the contents of the nodes. Metadata will pass non-node identifying values down to child nodes, if not overridden (license, timestamps, etc) ...
Assembles ``tree`` nodes into object models. If ``context`` is supplied, it will be used to contextualize the contents of the nodes. Metadata will pass non-node identifying values down to child nodes, if not overridden (license, timestamps, etc)
def _grid_widgets(self): """ Place the widgets in the correct positions :return: None """ if self.__label: self._header_label.grid(row=0, column=1, columnspan=3, sticky="nw", padx=5, pady=(5, 0)) self._bold_button.grid(row=1, column=1, sticky="nswe", padx=5, p...
Place the widgets in the correct positions :return: None
def set_mem_per_proc(self, mem_mb): """Set the memory per process in megabytes""" super().set_mem_per_proc(mem_mb) self.qparams["mem_per_cpu"] = self.mem_per_proc
Set the memory per process in megabytes
def setup_seq_signals(self, ): """Setup the signals for the sequence page :returns: None :rtype: None :raises: None """ log.debug("Setting up sequence page signals.") self.seq_prj_view_pb.clicked.connect(self.seq_view_prj) self.seq_shot_view_pb.clicked.co...
Setup the signals for the sequence page :returns: None :rtype: None :raises: None
def get_file_from_s3(job, s3_url, encryption_key=None, per_file_encryption=True, write_to_jobstore=True): """ Download a supplied URL that points to a file on Amazon S3. If the file is encrypted using sse-c (with the user-provided key or with a hash of the usesr provided master key) th...
Download a supplied URL that points to a file on Amazon S3. If the file is encrypted using sse-c (with the user-provided key or with a hash of the usesr provided master key) then the encryption keys will be used when downloading. The file is downloaded and written to the jobstore if requested. :param...
def gdal2np_dtype(b): """ Get NumPy datatype that corresponds with GDAL RasterBand datatype Input can be filename, GDAL Dataset, GDAL RasterBand, or GDAL integer dtype """ dt_dict = gdal_array.codes if isinstance(b, str): b = gdal.Open(b) if isinstance(b, gdal.Dataset): b = b...
Get NumPy datatype that corresponds with GDAL RasterBand datatype Input can be filename, GDAL Dataset, GDAL RasterBand, or GDAL integer dtype
def cluster_coincs(stat, time1, time2, timeslide_id, slide, window, argmax=numpy.argmax): """Cluster coincident events for each timeslide separately, across templates, based on the ranking statistic Parameters ---------- stat: numpy.ndarray vector of ranking values to maximize time1: nu...
Cluster coincident events for each timeslide separately, across templates, based on the ranking statistic Parameters ---------- stat: numpy.ndarray vector of ranking values to maximize time1: numpy.ndarray first time vector time2: numpy.ndarray second time vector tim...
def compat_string(value): """ Provide a python2/3 compatible string representation of the value :type value: :rtype : """ if isinstance(value, bytes): return value.decode(encoding='utf-8') return str(value)
Provide a python2/3 compatible string representation of the value :type value: :rtype :
def chat_post_message(self, channel, text, **params): """chat.postMessage This method posts a message to a channel. https://api.slack.com/methods/chat.postMessage """ method = 'chat.postMessage' params.update({ 'channel': channel, 'text': text, ...
chat.postMessage This method posts a message to a channel. https://api.slack.com/methods/chat.postMessage
def redirect_legacy_content(request): """Redirect from legacy /content/id/version to new /contents/uuid@version. Handles collection context (book) as well. """ routing_args = request.matchdict objid = routing_args['objid'] objver = routing_args.get('objver') filename = routing_args.get('fil...
Redirect from legacy /content/id/version to new /contents/uuid@version. Handles collection context (book) as well.
def _transschema(x): """ Transform a schema, once loaded from its YAML representation, to its final internal representation """ if isinstance(x, tuple): return x.__class__(_transschema(x[0]), *x[1:]) elif isinstance(x, dict): return dict((_qualify_map(key, _transschema(val)) for ...
Transform a schema, once loaded from its YAML representation, to its final internal representation
def make_context(self, info_name, args, parent=None, **extra): """This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. :param info_name: the info name for this invokation....
This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. :param info_name: the info name for this invokation. Generally this is the most descriptive name fo...
def H3(self): "Correlation." multiplied = np.dot(self.levels[:, np.newaxis] + 1, self.levels[np.newaxis] + 1) repeated = np.tile(multiplied[np.newaxis], (self.nobjects, 1, 1)) summed = (repeated * self.P).sum(2).sum(1) h3 = (summed - self.mux * self.mu...
Correlation.
def errors_to_json(errors): """Convert the errors to JSON.""" out = [] for e in errors: out.append({ "check": e[0], "message": e[1], "line": 1 + e[2], "column": 1 + e[3], "start": 1 + e[4], "end": 1 + e[5], "extent":...
Convert the errors to JSON.
def normalize(symbol_string, strict=False): """Normalize an encoded symbol string. Normalization provides error correction and prepares the string for decoding. These transformations are applied: 1. Hyphens are removed 2. 'I', 'i', 'L' or 'l' are converted to '1' 3. 'O' or 'o' are con...
Normalize an encoded symbol string. Normalization provides error correction and prepares the string for decoding. These transformations are applied: 1. Hyphens are removed 2. 'I', 'i', 'L' or 'l' are converted to '1' 3. 'O' or 'o' are converted to '0' 4. All characters are converte...
def decompress(obj, return_type="bytes"): """ De-compress it to it's original. :param obj: Compressed object, could be bytes or str. :param return_type: if bytes, then return bytes; if str, then use base64.b64decode; if obj, then use pickle.loads return an object. """ if isinstance(obj,...
De-compress it to it's original. :param obj: Compressed object, could be bytes or str. :param return_type: if bytes, then return bytes; if str, then use base64.b64decode; if obj, then use pickle.loads return an object.
def status(self,verbose=0): """Print a status of all jobs currently being managed.""" self._update_status() self._group_report(self.running,'Running') self._group_report(self.completed,'Completed') self._group_report(self.dead,'Dead') # Also flush the report queues ...
Print a status of all jobs currently being managed.
def created_by_column(self, obj): """ Return user who first created an item in Django admin """ try: first_addition_logentry = admin.models.LogEntry.objects.filter( object_id=obj.pk, content_type_id=self._get_obj_ct(obj).pk, action_flag=admin.m...
Return user who first created an item in Django admin
def delete_zone(server, token, domain): """Delete specific zone. Argument: server: TonicDNS API server token: TonicDNS API authentication token domain: Specify domain name x-authentication-token: token """ method = 'DELETE' uri = 'https://' + server + '/zone/' + domai...
Delete specific zone. Argument: server: TonicDNS API server token: TonicDNS API authentication token domain: Specify domain name x-authentication-token: token
def how_many(self): """ Ascertain where to start downloading, and how many entries. """ if self.linkdates != []: # What follows is a quick sanity check: if the entry date is in the # future, this is probably a mistake, and we just count the entry # dat...
Ascertain where to start downloading, and how many entries.
def common_vector_root(vec1, vec2): """ Return common root of the two vectors. Args: vec1 (list/tuple): First vector. vec2 (list/tuple): Second vector. Usage example:: >>> common_vector_root([1, 2, 3, 4, 5], [1, 2, 8, 9, 0]) [1, 2] Returns: list: Common pa...
Return common root of the two vectors. Args: vec1 (list/tuple): First vector. vec2 (list/tuple): Second vector. Usage example:: >>> common_vector_root([1, 2, 3, 4, 5], [1, 2, 8, 9, 0]) [1, 2] Returns: list: Common part of two vectors or blank list.
def radec2azel(ra_deg: float, dec_deg: float, lat_deg: float, lon_deg: float, time: datetime, usevallado: bool = False) -> Tuple[float, float]: """ sky coordinates (ra, dec) to viewing angle (az, el) Parameters ---------- ra_deg : float or numpy.ndarray of float ...
sky coordinates (ra, dec) to viewing angle (az, el) Parameters ---------- ra_deg : float or numpy.ndarray of float ecliptic right ascension (degress) dec_deg : float or numpy.ndarray of float ecliptic declination (degrees) lat_deg : float observer latitude [-90, 90] ...
def _func_addrs_from_prologues(self): """ Scan the entire program image for function prologues, and start code scanning at those positions :return: A list of possible function addresses """ # Pre-compile all regexes regexes = list() for ins_regex in self.project...
Scan the entire program image for function prologues, and start code scanning at those positions :return: A list of possible function addresses
def group_singles2array(input, **params): """ Creates array of strings or ints from objects' fields :param input: list of objects :param params: :return: list """ PARAM_FIELD_KEY = 'field.key' PARAM_FIELD_ARRAY = 'field.array' PARAM_FIELD_SINGLE = 'field.single' field_key = para...
Creates array of strings or ints from objects' fields :param input: list of objects :param params: :return: list
async def _on_receive_array(self, array): """Parse channel array and call the appropriate events.""" if array[0] == 'noop': pass # This is just a keep-alive, ignore it. else: wrapper = json.loads(array[0]['p']) # Wrapper appears to be a Protocol Buffer messag...
Parse channel array and call the appropriate events.
def parse_object_type_definition(lexer: Lexer) -> ObjectTypeDefinitionNode: """ObjectTypeDefinition""" start = lexer.token description = parse_description(lexer) expect_keyword(lexer, "type") name = parse_name(lexer) interfaces = parse_implements_interfaces(lexer) directives = parse_directiv...
ObjectTypeDefinition
def migrate_case(adapter: MongoAdapter, scout_case: dict, archive_data: dict): """Migrate case information from archive.""" # update collaborators collaborators = list(set(scout_case['collaborators'] + archive_data['collaborators'])) if collaborators != scout_case['collaborators']: LOG.info(f"se...
Migrate case information from archive.
def select_dict(conn, query: str, params=None, name=None, itersize=5000): """Return a select statement's results as dictionary. Parameters ---------- conn : database connection query : select query string params : query parameters. name : server side cursor name. defaults to client side. ...
Return a select statement's results as dictionary. Parameters ---------- conn : database connection query : select query string params : query parameters. name : server side cursor name. defaults to client side. itersize : number of records fetched by server.
def VGGFace(include_top=True, model='vgg16', weights='vggface', input_tensor=None, input_shape=None, pooling=None, classes=None): """Instantiates the VGGFace architectures. Optionally loads weights pre-trained on VGGFace datasets. Note that when using TensorFlow, for ...
Instantiates the VGGFace architectures. Optionally loads weights pre-trained on VGGFace datasets. Note that when using TensorFlow, for best performance you should set `image_data_format="channels_last"` in your Keras config at ~/.keras/keras.json. The model and the weights are compatible with bo...
def commit_and_quit(self): """ Commits and closes the currently open configration. Saves a step by not needing to manually close the config. Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root"...
Commits and closes the currently open configration. Saves a step by not needing to manually close the config. Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() ...
def handle(self, line_info): """Try to get some help for the object. obj? or ?obj -> basic information. obj?? or ??obj -> more details. """ normal_handler = self.prefilter_manager.get_handler_by_name('normal') line = line_info.line # We need to make sure that w...
Try to get some help for the object. obj? or ?obj -> basic information. obj?? or ??obj -> more details.
def getServiceDependencies(self): """ This methods returns a list with the analyses services dependencies. :return: a list of analysis services objects. """ calc = self.getCalculation() if calc: return calc.getCalculationDependencies(flat=True) return ...
This methods returns a list with the analyses services dependencies. :return: a list of analysis services objects.
def list_plugins(path, user): ''' List plugins in an installed wordpress path path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.list_plugins /var/www/html apache ''' ret = [] resp ...
List plugins in an installed wordpress path path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.list_plugins /var/www/html apache
def get_server_setting(settings, server=_DEFAULT_SERVER): ''' Get the value of the setting for the SMTP virtual server. :param str settings: A list of the setting names. :param str server: The SMTP server name. :return: A dictionary of the provided settings and their values. :rtype: dict ...
Get the value of the setting for the SMTP virtual server. :param str settings: A list of the setting names. :param str server: The SMTP server name. :return: A dictionary of the provided settings and their values. :rtype: dict CLI Example: .. code-block:: bash salt '*' win_smtp_serv...
def init(): """ Initializes this module """ global ORG global LEXER global MEMORY global INITS global AUTORUN_ADDR global NAMESPACE ORG = 0 # Origin of CODE INITS = [] MEMORY = None # Memory for instructions (Will be initialized with a Memory() instance) AUTORUN_ADDR =...
Initializes this module
def rule_operation(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa") index_key = ET.SubElement(rule, "index") index_key.text = kwargs.pop('index') operation = ET...
Auto Generated Code
def deferral(): """Defers a function call when it is being required like Go. :: with deferral() as defer: sys.setprofile(f) defer(sys.setprofile, None) # do something. """ deferred = [] defer = lambda f, *a, **k: deferred.append((f, a, k)) try: ...
Defers a function call when it is being required like Go. :: with deferral() as defer: sys.setprofile(f) defer(sys.setprofile, None) # do something.
def url(self, name): """ Ask blobstore api for an url to directly serve the file """ key = blobstore.create_gs_key('/gs' + name) return images.get_serving_url(key)
Ask blobstore api for an url to directly serve the file
def append(self, name, value): """ Appends the string ``value`` to the value at ``key``. If ``key`` doesn't already exist, create it with a value of ``value``. Returns the new length of the value at ``key``. :param name: str the name of the redis key :param value: st...
Appends the string ``value`` to the value at ``key``. If ``key`` doesn't already exist, create it with a value of ``value``. Returns the new length of the value at ``key``. :param name: str the name of the redis key :param value: str :return: Future()
def addworkdays(self, date, offset): """ Add work days to a given date, ignoring holidays. Note: By definition, a zero offset causes the function to return the initial date, even it is not a work date. An offset of 1 represents the next work date, rega...
Add work days to a given date, ignoring holidays. Note: By definition, a zero offset causes the function to return the initial date, even it is not a work date. An offset of 1 represents the next work date, regardless of date being a work date or not. ...
def write_patch_file(self, patch_file, lines_to_write): """Write lines_to_write to a the file called patch_file :param patch_file: file name of the patch to generate :param lines_to_write: lines to write to the file - they should be \n terminated :type lines_to_write: list[str] ...
Write lines_to_write to a the file called patch_file :param patch_file: file name of the patch to generate :param lines_to_write: lines to write to the file - they should be \n terminated :type lines_to_write: list[str] :return: None
def backwardeuler(dfun, xzero, timerange, timestep): '''Backward Euler method integration. This function wraps BackwardEuler. :param dfun: Derivative function of the system. The differential system arranged as a series of first-order equations: \dot{X} = dfun(t, x) ...
Backward Euler method integration. This function wraps BackwardEuler. :param dfun: Derivative function of the system. The differential system arranged as a series of first-order equations: \dot{X} = dfun(t, x) :param xzero: The initial condition of the sy...
async def call_async(self, method_name: str, *args, rpc_timeout: float = None, **kwargs): """ Send JSON RPC request to a backend socket and receive reply (asynchronously) :param method_name: Method name :param args: Args that will be passed to the remote function :param float rp...
Send JSON RPC request to a backend socket and receive reply (asynchronously) :param method_name: Method name :param args: Args that will be passed to the remote function :param float rpc_timeout: Timeout in seconds for Server response, set to None to disable the timeout :param kwargs: K...
def set_rotation(self, rotation): """Set the rotation of the stereonet in degrees clockwise from North.""" self._rotation = np.radians(rotation) self._polar.set_theta_offset(self._rotation + np.pi / 2.0) self.transData.invalidate() self.transAxes.invalidate() self._set_li...
Set the rotation of the stereonet in degrees clockwise from North.
def get_features_by_ids(self, ids=None, threshold=0.0001, func=np.mean, get_weights=False): ''' Returns features for which the mean loading across all specified studies (in ids) is >= threshold. ''' weights = self.data.ix[ids].apply(func, 0) above_thresh = wei...
Returns features for which the mean loading across all specified studies (in ids) is >= threshold.
def sigPerms(s): """Generate all possible signatures derived by upcasting the given signature. """ codes = 'bilfdc' if not s: yield '' elif s[0] in codes: start = codes.index(s[0]) for x in codes[start:]: for y in sigPerms(s[1:]): yield x + y ...
Generate all possible signatures derived by upcasting the given signature.
def locateChild(self, context, segments): """ Return a statically defined child or a child defined by a sessionless site root plugin or an avatar from guard. """ shortcut = getattr(self, 'child_' + segments[0], None) if shortcut: res = shortcut(context) ...
Return a statically defined child or a child defined by a sessionless site root plugin or an avatar from guard.
def stubs_clustering(network,use_reduced_coordinates=True, line_length_factor=1.0): """Cluster network by reducing stubs and stubby trees (i.e. sequentially reducing dead-ends). Parameters ---------- network : pypsa.Network use_reduced_coordinates : boolean If True, do not average clust...
Cluster network by reducing stubs and stubby trees (i.e. sequentially reducing dead-ends). Parameters ---------- network : pypsa.Network use_reduced_coordinates : boolean If True, do not average clusters, but take from busmap. line_length_factor : float Factor to multiply the cr...
def _findAssociatedConfigSpecFile(self, cfgFileName): """ Given a config file, find its associated config-spec file, and return the full pathname of the file. """ # Handle simplest 2 cases first: co-located or local .cfgspc file retval = "."+os.sep+self.__taskName+".cfgspc" if o...
Given a config file, find its associated config-spec file, and return the full pathname of the file.
def importaccount(ctx, account, role): """ Import an account using an account password """ from peerplaysbase.account import PasswordKey password = click.prompt("Account Passphrase", hide_input=True) account = Account(account, peerplays_instance=ctx.peerplays) imported = False if role == "...
Import an account using an account password
def load_batch(self, fn_batch): """ Loads a batch with the given prefixes. The prefixes is the full path to the training example minus the extension. """ # TODO Assumes targets are available, which is how its distinct from # utils.load_batch_x(). These functions need to change n...
Loads a batch with the given prefixes. The prefixes is the full path to the training example minus the extension.
def check_req(req): """Checks if a given req is the latest version available.""" if not isinstance(req, Requirement): return None info = get_package_info(req.name) newest_version = _get_newest_version(info) if _is_pinned(req) and _is_version_range(req): return None current_spe...
Checks if a given req is the latest version available.
def detect_c3_function_shadowing(contract): """ Detects and obtains functions which are indirectly shadowed via multiple inheritance by C3 linearization properties, despite not directly inheriting from each other. :param contract: The contract to check for potential C3 linearization shadowing within. ...
Detects and obtains functions which are indirectly shadowed via multiple inheritance by C3 linearization properties, despite not directly inheriting from each other. :param contract: The contract to check for potential C3 linearization shadowing within. :return: A list of list of tuples: (contract, functio...
def request_permissions(self, permissions): """ Return a future that resolves with the results of the permission requests """ f = self.create_future() #: Old versions of android did permissions at install time if self.api_level < 23: f.set_result({p...
Return a future that resolves with the results of the permission requests
def matrix(mat): """Convert a ROOT TMatrix into a NumPy matrix. Parameters ---------- mat : ROOT TMatrixT A ROOT TMatrixD or TMatrixF Returns ------- mat : numpy.matrix A NumPy matrix Examples -------- >>> from root_numpy import matrix >>> from ROOT import ...
Convert a ROOT TMatrix into a NumPy matrix. Parameters ---------- mat : ROOT TMatrixT A ROOT TMatrixD or TMatrixF Returns ------- mat : numpy.matrix A NumPy matrix Examples -------- >>> from root_numpy import matrix >>> from ROOT import TMatrixD >>> a = TMa...
def build_query_fragment(query): """ <query xmlns="http://basex.org/rest"> <text><![CDATA[ (//city/name)[position() <= 5] ]]></text> </query> """ root = etree.Element('query', nsmap={None: 'http://basex.org/rest'}) text = etree.SubElement(root, 'text') text.text = etree.CDATA(query.s...
<query xmlns="http://basex.org/rest"> <text><![CDATA[ (//city/name)[position() <= 5] ]]></text> </query>
def add_before(self, pipeline): """Add a Pipeline to be applied before this processing pipeline. Arguments: pipeline: The Pipeline or callable to apply before this Pipeline. """ if not isinstance(pipeline, Pipeline): pipeline = Pipeline(pipeline) ...
Add a Pipeline to be applied before this processing pipeline. Arguments: pipeline: The Pipeline or callable to apply before this Pipeline.
def send_sms(self, text, **kw): """ Send an SMS. Since Free only allows us to send SMSes to ourselves you don't have to provide your phone number. """ params = { 'user': self._user, 'pass': self._passwd, 'msg': text } kw.setde...
Send an SMS. Since Free only allows us to send SMSes to ourselves you don't have to provide your phone number.
def add_uid(self, uid, selfsign=True, **prefs): """ Add a User ID to this key. :param uid: The user id to add :type uid: :py:obj:`~pgpy.PGPUID` :param selfsign: Whether or not to self-sign the user id before adding it :type selfsign: ``bool`` Valid optional keyw...
Add a User ID to this key. :param uid: The user id to add :type uid: :py:obj:`~pgpy.PGPUID` :param selfsign: Whether or not to self-sign the user id before adding it :type selfsign: ``bool`` Valid optional keyword arguments are identical to those of self-signatures for :py:meth...
def Hakim_Steinberg_Stiel(T, Tc, Pc, omega, StielPolar=0): r'''Calculates air-water surface tension using the reference fluids methods of [1]_. .. math:: \sigma = 4.60104\times 10^{-7} P_c^{2/3}T_c^{1/3}Q_p \left(\frac{1-T_r}{0.4}\right)^m Q_p = 0.1574+0.359\omega-1.769\chi-13.69\chi^2-0.5...
r'''Calculates air-water surface tension using the reference fluids methods of [1]_. .. math:: \sigma = 4.60104\times 10^{-7} P_c^{2/3}T_c^{1/3}Q_p \left(\frac{1-T_r}{0.4}\right)^m Q_p = 0.1574+0.359\omega-1.769\chi-13.69\chi^2-0.51\omega^2+1.298\omega\chi m = 1.21+0.5385\omega-14.61\...