positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def create_target_group(name, protocol, port, vpc_id, region=None, key=None, keyid=None, profile=None, health_check_protocol='HT...
Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless you specify a port override when ...
def base_mortality_rate(self, index: pd.Index) -> pd.Series: """Computes the base mortality rate for every individual. Parameters ---------- index : A representation of the simulants to compute the base mortality rate for. Returns ------- ...
Computes the base mortality rate for every individual. Parameters ---------- index : A representation of the simulants to compute the base mortality rate for. Returns ------- The base mortality rate for all simulants in the index.
def schedule(func, time, channel="default"): """Run `func` at a later `time` in a dedicated `channel` Given an arbitrary function, call this function after a given timeout. It will ensure that only one "job" is running within the given channel at any one time and cancel any currently running job if...
Run `func` at a later `time` in a dedicated `channel` Given an arbitrary function, call this function after a given timeout. It will ensure that only one "job" is running within the given channel at any one time and cancel any currently running job if a new job is submitted before the timeout.
def icon(self): """Get QIcon from wrapper""" if self._icon is None: self._icon = QIcon(self.pm()) return self._icon
Get QIcon from wrapper
def radiansBetween(self, other): ''' :param: other - Line subclass :return: float Returns the angle measured between two lines in radians with a range of [0, 2 * math.pi]. ''' # a dot b = |a||b| * cos(theta) # a dot b / |a||b| = cos(theta) # cos-...
:param: other - Line subclass :return: float Returns the angle measured between two lines in radians with a range of [0, 2 * math.pi].
def GetMessages(self, formatter_mediator, event): """Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. eve...
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def fasta(self, key='vdj_nt', append_chain=True): ''' Returns the sequence pair as a fasta string. If the Pair object contains both heavy and light chain sequences, both will be returned as a single string. By default, the fasta string contains the 'vdj_nt' sequence for each chain. To c...
Returns the sequence pair as a fasta string. If the Pair object contains both heavy and light chain sequences, both will be returned as a single string. By default, the fasta string contains the 'vdj_nt' sequence for each chain. To change, use the <key> option to select an alternate sequence. ...
def level(self, value): """Build profile URI from level. Level should be an integer 0,1,2 """ self.compliance = self.compliance_prefix + \ ("%d" % value) + self.compliance_suffix
Build profile URI from level. Level should be an integer 0,1,2
def prepare_to_store(self, entity, value): """Prepare `value` for storage. Called by the Model for each Property, value pair it contains before handing the data off to an adapter. Parameters: entity(Model): The entity to which the value belongs. value: The value bei...
Prepare `value` for storage. Called by the Model for each Property, value pair it contains before handing the data off to an adapter. Parameters: entity(Model): The entity to which the value belongs. value: The value being stored. Raises: RuntimeError: If...
def error(self, exc): """ log an error message: :param exc: exception message """ msg = 'trying to execute a step in the environment: \n' \ ' - Exception: %s' % exc if self.logger is not None: self.logger.error(msg) self.by_cons...
log an error message: :param exc: exception message
def processRequest(cls, ps, **kw): """invokes callback that should return a (request,response) tuple. representing the SOAP request and response respectively. ps -- ParsedSoap instance representing HTTP Body. request -- twisted.web.server.Request """ resource = kw['resour...
invokes callback that should return a (request,response) tuple. representing the SOAP request and response respectively. ps -- ParsedSoap instance representing HTTP Body. request -- twisted.web.server.Request
def transaction(self, compare, success=None, failure=None): """ Perform a transaction. Example usage: .. code-block:: python etcd.transaction( compare=[ etcd.transactions.value('/doot/testing') == 'doot', etcd.transac...
Perform a transaction. Example usage: .. code-block:: python etcd.transaction( compare=[ etcd.transactions.value('/doot/testing') == 'doot', etcd.transactions.version('/doot/testing') > 0, ], success=[...
def RegisterLateBindingCallback(target_name, callback, **kwargs): """Registers a callback to be invoked when the RDFValue named is declared.""" _LATE_BINDING_STORE.setdefault(target_name, []).append((callback, kwargs))
Registers a callback to be invoked when the RDFValue named is declared.
def on_timer(self, event): '''Main Loop.''' state = self.state self.loopStartTime = time.time() if state.close_event.wait(0.001): self.timer.Stop() self.Destroy() return # Check for resizing self.checkReszie() if self.r...
Main Loop.
def genl_send_simple(sk, family, cmd, version, flags): """Send a Generic Netlink message consisting only of a header. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L84 This function is a shortcut for sending a Generic Netlink message without any message payload. The message will only ...
Send a Generic Netlink message consisting only of a header. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L84 This function is a shortcut for sending a Generic Netlink message without any message payload. The message will only consist of the Netlink and Generic Netlink headers. The hea...
def _resolve(self, path, migration_file): """ Resolve a migration instance from a file. :param migration_file: The migration file :type migration_file: str :rtype: orator.migrations.migration.Migration """ name = "_".join(migration_file.split("_")[4:]) m...
Resolve a migration instance from a file. :param migration_file: The migration file :type migration_file: str :rtype: orator.migrations.migration.Migration
def reset_instance_attribute(self, instance_id, attribute): """ Resets an attribute of an instance to its default value. :type instance_id: string :param instance_id: ID of the instance :type attribute: string :param attribute: The attribute to reset. Valid values are: ...
Resets an attribute of an instance to its default value. :type instance_id: string :param instance_id: ID of the instance :type attribute: string :param attribute: The attribute to reset. Valid values are: kernel|ramdisk :rtype: bool :return: ...
def _log_message(self, level, freerun_entry, msg): """ method performs logging into log file and the freerun_entry """ self.logger.log(level, msg) assert isinstance(freerun_entry, FreerunProcessEntry) event_log = freerun_entry.event_log if len(event_log) > MAX_NUMBER_OF_EVENTS: ...
method performs logging into log file and the freerun_entry
def sendall_stderr(self, s): """ Send data to the channel's "stderr" stream, without allowing partial results. Unlike L{send_stderr}, this method continues to send data from the given string until all data has been sent or an error occurs. Nothing is returned. @...
Send data to the channel's "stderr" stream, without allowing partial results. Unlike L{send_stderr}, this method continues to send data from the given string until all data has been sent or an error occurs. Nothing is returned. @param s: data to send to the client as "stderr" o...
def _dispatch(name, *args, **kwargs): """ Dispatch to apply. """ def outer(self, *args, **kwargs): def f(x): x = self._shallow_copy(x, groupby=self._groupby) return getattr(x, name)(*args, **kwargs) return self._groupby.apply(f) ...
Dispatch to apply.
def get_status(self): ''' Get the status of the report and its sub-reports. :rtype: str :return: report status ('passed', 'failed' or 'error') ''' status = self.get('status') if status == Report.PASSED: for sr_name in self._sub_reports: ...
Get the status of the report and its sub-reports. :rtype: str :return: report status ('passed', 'failed' or 'error')
def has_in_collaborators(self, collaborator): """ :calls: `GET /repos/:owner/:repo/collaborators/:user <http://developer.github.com/v3/repos/collaborators>`_ :param collaborator: string or :class:`github.NamedUser.NamedUser` :rtype: bool """ assert isinstance(collaborator...
:calls: `GET /repos/:owner/:repo/collaborators/:user <http://developer.github.com/v3/repos/collaborators>`_ :param collaborator: string or :class:`github.NamedUser.NamedUser` :rtype: bool
def _get_kdjd(cls, df, n_days): """ Get the D of KDJ D = 2/3 × (prev. D) +1/3 × (curr. K) 2/3 and 1/3 are the smooth parameters. :param df: data :param n_days: calculation range :return: None """ k_column = 'kdjk_{}'.format(n_days) d_col...
Get the D of KDJ D = 2/3 × (prev. D) +1/3 × (curr. K) 2/3 and 1/3 are the smooth parameters. :param df: data :param n_days: calculation range :return: None
def main(): """Measure capnp serialization performance of a network containing a simple python region that in-turn contains a Random instance. """ engine.Network.registerPyRegion(__name__, SerializationTestPyRegion.__name__) try: _runTest() finally: engine.Networ...
Measure capnp serialization performance of a network containing a simple python region that in-turn contains a Random instance.
def _advance_new_study_id(self): """ ASSUMES the caller holds the _doc_counter_lock ! Returns the current numeric part of the next study ID, advances the counter to the next value, and stores that value in the file in case the server is restarted. """ c = self._next_study...
ASSUMES the caller holds the _doc_counter_lock ! Returns the current numeric part of the next study ID, advances the counter to the next value, and stores that value in the file in case the server is restarted.
def countByValue(self): """Apply countByValue to every RDD.abs :rtype: DStream .. warning:: Implemented as a local operation. Example: >>> import pysparkling >>> sc = pysparkling.Context() >>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1) ...
Apply countByValue to every RDD.abs :rtype: DStream .. warning:: Implemented as a local operation. Example: >>> import pysparkling >>> sc = pysparkling.Context() >>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1) >>> ( ... ssc ...
def container_rename_folder(object_id, input_params={}, always_retry=False, **kwargs): """ Invokes the /container-xxxx/renameFolder API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FrenameFolder """ return DXHTTPReq...
Invokes the /container-xxxx/renameFolder API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FrenameFolder
def set_fc_volume(self, port_id, target_wwn, target_lun=0, boot_prio=1, initiator_wwnn=None, initiator_wwpn=None): """Set FibreChannel volume information to configuration. :param port_id: Physical port ID. :param target_wwn: WWN of target. :pa...
Set FibreChannel volume information to configuration. :param port_id: Physical port ID. :param target_wwn: WWN of target. :param target_lun: LUN number of target. :param boot_prio: Boot priority of the volume. 1 indicates the highest priority. :param initiator_wwn...
async def on_raw_301(self, message): """ User is away. """ target, nickname, message = message.params info = { 'away': True, 'away_message': message } if nickname in self.users: self._sync_user(nickname, info) if nickname in self._pend...
User is away.
def get_jvm_options(self): """Return the options to run this JVM with. These are options to the JVM itself, such as -Dfoo=bar, -Xmx=1g, -XX:-UseParallelGC and so on. Thus named because get_options() already exists (and returns this object's Pants options). """ ret = [] for opt in self.get_opti...
Return the options to run this JVM with. These are options to the JVM itself, such as -Dfoo=bar, -Xmx=1g, -XX:-UseParallelGC and so on. Thus named because get_options() already exists (and returns this object's Pants options).
def QA_util_stamp2datetime(timestamp): """ datestamp转datetime pandas转出来的timestamp是13位整数 要/1000 It’s common for this to be restricted to years from 1970 through 2038. 从1970年开始的纳秒到当前的计数 转变成 float 类型时间 类似 time.time() 返回的类型 :param timestamp: long类型 :return: 类型float """ try: retur...
datestamp转datetime pandas转出来的timestamp是13位整数 要/1000 It’s common for this to be restricted to years from 1970 through 2038. 从1970年开始的纳秒到当前的计数 转变成 float 类型时间 类似 time.time() 返回的类型 :param timestamp: long类型 :return: 类型float
def idfreader1(fname, iddfile, theidf, conv=True, commdct=None, block=None): """read idf file and return bunches""" versiontuple = iddversiontuple(iddfile) # import pdb; pdb.set_trace() block, data, commdct, idd_index = readidf.readdatacommdct1( fname, iddfile=iddfile, commdct=co...
read idf file and return bunches
def load(stream): """Parse the LHA document and produce the corresponding Python object. Accepts a string or a file-like object.""" if isinstance(stream, str): string = stream else: string = stream.read() tokens = tokenize(string) return parse(tokens)
Parse the LHA document and produce the corresponding Python object. Accepts a string or a file-like object.
def update_notification_list(self, apps=None, schema_editor=None, verbose=False): """Updates the notification model to ensure all registered notifications classes are listed. Typically called from a post_migrate signal. Also, in tests you can register a notification and the Notificatio...
Updates the notification model to ensure all registered notifications classes are listed. Typically called from a post_migrate signal. Also, in tests you can register a notification and the Notification class (not model) will automatically call this method if the named notifica...
def domain(self, expparams): """ Returns a list of ``Domain``s, one for each input expparam. :param numpy.ndarray expparams: Array of experimental parameters. This array must be of dtype agreeing with the ``expparams_dtype`` property, or, in the case where ``n_outcomes_...
Returns a list of ``Domain``s, one for each input expparam. :param numpy.ndarray expparams: Array of experimental parameters. This array must be of dtype agreeing with the ``expparams_dtype`` property, or, in the case where ``n_outcomes_constant`` is ``True``, ``None`` shou...
def __find_hidden_analyses(self, docs): """ Jätab meelde, millised analüüsid on nn peidetud ehk siis mida ei tule arvestada lemmade järelühestamisel: *) kesksõnade nud, dud, tud mitmesused; *) muutumatute sõnade sõnaliigi mitmesus; *) oleviku 'olema' mitmesus...
Jätab meelde, millised analüüsid on nn peidetud ehk siis mida ei tule arvestada lemmade järelühestamisel: *) kesksõnade nud, dud, tud mitmesused; *) muutumatute sõnade sõnaliigi mitmesus; *) oleviku 'olema' mitmesus ('nad on' vs 'ta on'); *) asesõnade ai...
async def create_source_event_stream( schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, ) -> Union[AsyncIterable[Any], ExecutionRes...
Create source even stream Implements the "CreateSourceEventStream" algorithm described in the GraphQL specification, resolving the subscription source event stream. Returns a coroutine that yields an AsyncIterable. If the client provided invalid arguments, the source stream could not be created, ...
def _case_stmt(self, stmt: Statement, sctx: SchemaContext) -> None: """Handle case statement.""" self._handle_child(CaseNode(), stmt, sctx)
Handle case statement.
def wrap_kwargs_to_initdict(init_kwargs_fn: InitKwargsFnType, typename: str, check_result: bool = True) \ -> InstanceToInitDictFnType: """ Wraps a function producing a ``KwargsDict``, making it into a function producing an ``InitDict``. """...
Wraps a function producing a ``KwargsDict``, making it into a function producing an ``InitDict``.
def primal_and_adjoint_for_tracing(self, node): """Build the primal and adjoint of a traceable function. Args: node: ast.Call node of a function we wish to trace, instead of transform Returns: primal: new ast.Assign node to replace the original primal call adjoint: new ast.Assign node us...
Build the primal and adjoint of a traceable function. Args: node: ast.Call node of a function we wish to trace, instead of transform Returns: primal: new ast.Assign node to replace the original primal call adjoint: new ast.Assign node using the VJP generated in primal to calculate th...
def _location_purge_all(delete=False, verbosity=0): """Purge all data locations.""" if DataLocation.objects.exists(): for location in DataLocation.objects.filter(Q(purged=False) | Q(data=None)): location_purge(location.id, delete, verbosity) else: logger.info("No data locations")
Purge all data locations.
def deny(cls, action, **kwargs): """Deny the given action need. :param action: The action to deny. :returns: A :class:`invenio_access.models.ActionNeedMixin` instance. """ return cls.create(action, exclude=True, **kwargs)
Deny the given action need. :param action: The action to deny. :returns: A :class:`invenio_access.models.ActionNeedMixin` instance.
def revnet_164_cifar(): """Tiny hparams suitable for CIFAR/etc.""" hparams = revnet_cifar_base() hparams.bottleneck = True hparams.num_channels = [16, 32, 64] hparams.num_layers_per_block = [8, 8, 8] return hparams
Tiny hparams suitable for CIFAR/etc.
def run_tm_noise_experiment(dim = 2048, cellsPerColumn=1, num_active = 40, activationThreshold=16, initialPermanence=0.8, connectedPermanence=0.50, minT...
Run an experiment tracking the performance of the temporal memory given noise. The number of active cells and the dimensions of the TM are fixed. We track performance by comparing the cells predicted to be active with the cells actually active in the sequence without noise at every timestep, and averaging acro...
def _SetCompleted(self): """Atomically marks the breakpoint as completed. Returns: True if the breakpoint wasn't marked already completed or False if the breakpoint was already completed. """ with self._lock: if self._completed: return False self._completed = True ...
Atomically marks the breakpoint as completed. Returns: True if the breakpoint wasn't marked already completed or False if the breakpoint was already completed.
def set_hyperparams(self, new_params): """Sets the free hyperparameters to the new parameter values in new_params. Parameters ---------- new_params : :py:class:`Array` or other Array-like, (len(:py:attr:`self.free_params`),) New parameter values, ordered as dictated ...
Sets the free hyperparameters to the new parameter values in new_params. Parameters ---------- new_params : :py:class:`Array` or other Array-like, (len(:py:attr:`self.free_params`),) New parameter values, ordered as dictated by the docstring for the class.
def unique(values): """ Hash table-based unique. Uniques are returned in order of appearance. This does NOT sort. Significantly faster than numpy.unique. Includes NA values. Parameters ---------- values : 1d array-like Returns ------- numpy.ndarray or ExtensionArray T...
Hash table-based unique. Uniques are returned in order of appearance. This does NOT sort. Significantly faster than numpy.unique. Includes NA values. Parameters ---------- values : 1d array-like Returns ------- numpy.ndarray or ExtensionArray The return can be: * Ind...
def download(name, options): """ download a file or all files in a directory """ dire = os.path.dirname(name) # returns the directory name fName = os.path.basename(name) # returns the filename fNameOnly, fExt = os.path.splitext(fName) dwn = 0 if fileExists(fName, dire) and not fileExis...
download a file or all files in a directory
def main(): """Main""" import sys import h5py handler = logging.StreamHandler(sys.stderr) formatter = logging.Formatter(fmt=_DEFAULT_LOG_FORMAT, datefmt=_DEFAULT_TIME_FORMAT) handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) LOG.setLevel(...
Main
def dict2dzn( objs, declare=False, assign=True, declare_enums=True, wrap=True, fout=None ): """Serializes the objects in input and produces a list of strings encoding them into dzn format. Optionally, the produced dzn is written on a file. Supported types of objects include: ``str``, ``int``, ``float``...
Serializes the objects in input and produces a list of strings encoding them into dzn format. Optionally, the produced dzn is written on a file. Supported types of objects include: ``str``, ``int``, ``float``, ``set``, ``list`` or ``dict``. List and dict are serialized into dzn (multi-dimensional) arra...
def random_variant(variants, weights): """ A generator that, given a list of variants and a corresponding list of weights, returns one random weighted selection. """ total = 0 accumulator = [] for w in weights: total += w accumulator.append(total) r = randint(0, total - ...
A generator that, given a list of variants and a corresponding list of weights, returns one random weighted selection.
def _get_entity_id_if_container_metric(self, labels): """ Checks the labels indicate a container metric, then extract the container id from them. :param labels :return str or None """ if CadvisorPrometheusScraperMixin._is_container_metric(labels): pod...
Checks the labels indicate a container metric, then extract the container id from them. :param labels :return str or None
def parse_host(entity, default_port=DEFAULT_PORT): """Validates a host string Returns a 2-tuple of host followed by port where port is default_port if it wasn't specified in the string. :Parameters: - `entity`: A host or host:port string where host could be a hostname or IP...
Validates a host string Returns a 2-tuple of host followed by port where port is default_port if it wasn't specified in the string. :Parameters: - `entity`: A host or host:port string where host could be a hostname or IP address. - `default_port`: The port number to use...
def _verify_same_spaces(self): """Verifies that all the envs have the same observation and action space.""" # Pre-conditions: self._envs is initialized. if self._envs is None: raise ValueError("Environments not initialized.") if not isinstance(self._envs, list): tf.logging.warning("Not ch...
Verifies that all the envs have the same observation and action space.
def decode(self, binSequence): """decodes a binary sequence to return a string""" try: binSeq = iter(binSequence[0]) except TypeError, te: binSeq = binSequence ret = '' for b in binSeq : ch = '' for c in self.charToBin : if b & self.forma[self.charToBin[c]] > 0 : ch += c +'/' if c...
decodes a binary sequence to return a string
def satisfy_custom_matcher(self, args, kwargs): """Return a boolean indicating if the args satisfy the stub :return: Whether or not the stub accepts the provided arguments. :rtype: bool """ if not self._custom_matcher: return False try: return sel...
Return a boolean indicating if the args satisfy the stub :return: Whether or not the stub accepts the provided arguments. :rtype: bool
def get_arg_or_attr(self, name, default=None): """Returns flow argument, as provided with sitegate decorators or attribute set as a flow class attribute or default.""" if name in self.flow_args: return self.flow_args[name] try: return getattr(self, name) ...
Returns flow argument, as provided with sitegate decorators or attribute set as a flow class attribute or default.
def update_views(self): """Update stats views.""" # Call the father's method super(Plugin, self).update_views() # Add specifics informations # Alert for i in self.stats: ifrealname = i['interface_name'].split(':')[0] # Convert rate in bps ( to be ...
Update stats views.
def mod(self): """ Cached compiled binary of the Generic_Code class. To clear cache invoke :meth:`clear_mod_cache`. """ if self._mod is None: self._mod = self.compile_and_import_binary() return self._mod
Cached compiled binary of the Generic_Code class. To clear cache invoke :meth:`clear_mod_cache`.
def xline(self): """ Interact with segy in crossline mode Returns ------- xline : Line or None Raises ------ ValueError If the file is unstructured Notes ----- .. versionadded:: 1.1 """ if self.unstruc...
Interact with segy in crossline mode Returns ------- xline : Line or None Raises ------ ValueError If the file is unstructured Notes ----- .. versionadded:: 1.1
def update_coordinates(self, points, mesh=None, render=True): """ Updates the points of the an object in the plotter. Parameters ---------- points : np.ndarray Points to replace existing points. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional ...
Updates the points of the an object in the plotter. Parameters ---------- points : np.ndarray Points to replace existing points. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses l...
def reset_coord(self): """ Reset the source location based on the init_skycoord values @return: """ (x, y, idx) = self.world2pix(self.init_skycoord.ra, self.init_skycoord.dec, usepv=True) self.updat...
Reset the source location based on the init_skycoord values @return:
def remove_vertex(self, vertex): """ Remove vertex from G """ try: self.vertices.pop(vertex) except KeyError: raise GraphInsertError("Vertex %s doesn't exist." % (vertex,)) if vertex in self.nodes: self.nodes.pop(vertex) ...
Remove vertex from G
def load_configuration(working_dir): """ Load the system configuration and set global variables Return the configuration of the node on success. Return None on failure """ import nameset.virtualchain_hooks as virtualchain_hooks # acquire configuration, and store it globally opts = conf...
Load the system configuration and set global variables Return the configuration of the node on success. Return None on failure
def joint(node): """Merge the bodies of primal and adjoint into a single function. Args: node: A module with the primal and adjoint function definitions as returned by `reverse_ad`. Returns: func: A `Module` node with a single function definition containing the combined primal and adjoin...
Merge the bodies of primal and adjoint into a single function. Args: node: A module with the primal and adjoint function definitions as returned by `reverse_ad`. Returns: func: A `Module` node with a single function definition containing the combined primal and adjoint.
def read(self, size:int=None): """ :param size: number of characters to read from the buffer :return: string that has been read from the buffer """ if size: result = self._buffer[0:size] self._buffer = self._buffer[size:] return result ...
:param size: number of characters to read from the buffer :return: string that has been read from the buffer
def force_delete(func, path, exc_info): """Error handler for `shutil.rmtree()` equivalent to `rm -rf`. Usage: `shutil.rmtree(path, onerror=force_delete)` From stackoverflow.com/questions/1889597 """ os.chmod(path, stat.S_IWRITE) func(path)
Error handler for `shutil.rmtree()` equivalent to `rm -rf`. Usage: `shutil.rmtree(path, onerror=force_delete)` From stackoverflow.com/questions/1889597
def relevantindices(self) -> List[int]: """A |list| of all currently relevant indices, calculated as an intercection of the (constant) class attribute `RELEVANT_VALUES` and the (variable) property |IndexMask.refindices|.""" return [idx for idx in numpy.unique(self.refindices.values) ...
A |list| of all currently relevant indices, calculated as an intercection of the (constant) class attribute `RELEVANT_VALUES` and the (variable) property |IndexMask.refindices|.
def update_displayed_information(self): """ Update all the graphs that are being displayed """ for source in self.controller.sources: source_name = source.get_source_name() if (any(self.graphs_menu.active_sensors[source_name]) or any(self.summary_menu.active_...
Update all the graphs that are being displayed
def swap(self, position: int) -> None: """ Perform a SWAP operation on the stack. """ idx = -1 * position - 1 try: self.values[-1], self.values[idx] = self.values[idx], self.values[-1] except IndexError: raise InsufficientStack("Insufficient stack ...
Perform a SWAP operation on the stack.
def authenticate_credentials(self, payload): """ Returns an active user that matches the payload's user id and email. """ User = get_user_model() username = jwt_get_username_from_payload(payload) if not username: msg = _('Invalid payload.') raise ...
Returns an active user that matches the payload's user id and email.
def deurlform_app(parser, cmd, args): # pragma: no cover """ decode a query string into its key value pairs. """ parser.add_argument('value', help='the query string to decode') args = parser.parse_args(args) return ' '.join('%s=%s' % (key, value) for key, values in deurlform(args.value).items(...
decode a query string into its key value pairs.
def build_query(self, **filters): """ Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields that have been "registered" in `view.fields`. Default behavior is to `OR` terms for the same parameters, and `AND` between parameters. Any query...
Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields that have been "registered" in `view.fields`. Default behavior is to `OR` terms for the same parameters, and `AND` between parameters. Any querystring parameters that are not registered in `view.fie...
def local_check (self): """ Warn about empty host names. Else call super.local_check(). """ if not self.host: self.set_result(_("Host is empty"), valid=False) return super(TelnetUrl, self).local_check()
Warn about empty host names. Else call super.local_check().
def disallow(self): """ Description of disallowed objects. Disallow must be a type name, a nested schema or a list of those. Type name must be one of ``string``, ``number``, ``integer``, ``boolean``, ``object``, ``array``, ``null`` or ``any``. """ value = self._...
Description of disallowed objects. Disallow must be a type name, a nested schema or a list of those. Type name must be one of ``string``, ``number``, ``integer``, ``boolean``, ``object``, ``array``, ``null`` or ``any``.
def explore_show_head(self, uri, check_headers=None): """Do HEAD on uri and show infomation. Will also check headers against any values specified in check_headers. """ print("HEAD %s" % (uri)) if (re.match(r'^\w+:', uri)): # Looks like a URI respo...
Do HEAD on uri and show infomation. Will also check headers against any values specified in check_headers.
def send_to_address(self, asset_id, to_addr, value, fee=None, change_addr=None, id=None, endpoint=None): """ Args: asset_id: (str) asset identifier (for NEO: 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', for GAS: '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee79...
Args: asset_id: (str) asset identifier (for NEO: 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', for GAS: '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7') to_addr: (str) destination address value: (int/decimal) transfer amount fee: (...
def decode_iter(data, codec_options=DEFAULT_CODEC_OPTIONS): """Decode BSON data to multiple documents as a generator. Works similarly to the decode_all function, but yields one document at a time. `data` must be a string of concatenated, valid, BSON-encoded documents. :Parameters: - `da...
Decode BSON data to multiple documents as a generator. Works similarly to the decode_all function, but yields one document at a time. `data` must be a string of concatenated, valid, BSON-encoded documents. :Parameters: - `data`: BSON data - `codec_options` (optional): An instance of ...
def fromaligns(args): """ %prog fromaligns out.aligns Convert aligns file (old MCscan output) to anchors file. """ p = OptionParser(fromaligns.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) alignsfile, = args fp...
%prog fromaligns out.aligns Convert aligns file (old MCscan output) to anchors file.
def loopback_interface(self): """ Loopback interfaces for this node. This will return empty if the engine is not a layer 3 firewall type:: >>> engine = Engine('dingo') >>> for node in engine.nodes: ... for loopback in node.loopback_interface: ...
Loopback interfaces for this node. This will return empty if the engine is not a layer 3 firewall type:: >>> engine = Engine('dingo') >>> for node in engine.nodes: ... for loopback in node.loopback_interface: ... loopback ... ...
def filterVerticalLines(arr, min_line_length=4): """ Remove vertical lines in boolean array if linelength >=min_line_length """ gy = arr.shape[0] gx = arr.shape[1] mn = min_line_length-1 for i in range(gy): for j in range(gx): if arr[i,j]: for d ...
Remove vertical lines in boolean array if linelength >=min_line_length
def numpy_bins(self) -> List[np.ndarray]: """Numpy-like bins (if available).""" return [binning.numpy_bins for binning in self._binnings]
Numpy-like bins (if available).
def libvlc_audio_output_list_release(p_list): '''Frees the list of available audio output modules. @param p_list: list with audio outputs for release. ''' f = _Cfunctions.get('libvlc_audio_output_list_release', None) or \ _Cfunction('libvlc_audio_output_list_release', ((1,),), None, ...
Frees the list of available audio output modules. @param p_list: list with audio outputs for release.
def rexponweib(alpha, k, loc=0, scale=1, size=None): """ Random exponentiated Weibull variates. """ q = np.random.uniform(size=size) r = flib.exponweib_ppf(q, alpha, k) return loc + r * scale
Random exponentiated Weibull variates.
def run_check(participants, config, reference_time): """For each participant, if they've been active for longer than the experiment duration + 2 minutes, we take action. """ recruiters_with_late_participants = defaultdict(list) for p in participants: timeline = ParticipationTime(p, reference...
For each participant, if they've been active for longer than the experiment duration + 2 minutes, we take action.
def mutate_rows( self, table_name, entries, app_profile_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Mutates multiple rows in a batch. Each individual row is muta...
Mutates multiple rows in a batch. Each individual row is mutated atomically as in MutateRow, but the entire batch is not executed atomically. Example: >>> from google.cloud import bigtable_v2 >>> >>> client = bigtable_v2.BigtableClient() >>> ...
def get_filtered_keys(self, suffix, *args, **kwargs): """Returns the index key for the given args "value" (`args`) Parameters ---------- kwargs: dict use_lua: bool Default to ``True``, if scripting is supported. If ``True``, the process of rea...
Returns the index key for the given args "value" (`args`) Parameters ---------- kwargs: dict use_lua: bool Default to ``True``, if scripting is supported. If ``True``, the process of reading from the sorted-set, extracting the primary ...
def selected_canvas_agglayer(self): """Obtain the canvas aggregation layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer """ if self.lstCanvasAggLayers.selectedItems(): item = self.lstCanvasAggLayers.currentItem() ...
Obtain the canvas aggregation layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer
def json_to_config(dic, full = False): """ Converts a JSON-decoded config dictionary to a python dictionary. When materializing the full view, the values in the dictionary will be instances of ApiConfig, instead of strings. @param dic: JSON-decoded config dictionary. @param full: Whether to materialize th...
Converts a JSON-decoded config dictionary to a python dictionary. When materializing the full view, the values in the dictionary will be instances of ApiConfig, instead of strings. @param dic: JSON-decoded config dictionary. @param full: Whether to materialize the full view of the config data. @return: Pyth...
def _thread(self): """ Thread entry point: does the job once, stored results, and dies. """ # Get args, kwargs = self._jobs.get() # Stop thread when (None, None) comes in if args is None and kwargs is None: return None # Wrappers should exit as well # Work ...
Thread entry point: does the job once, stored results, and dies.
def _indent(text, prefix, predicate=None): """Adds 'prefix' to the beginning of selected lines in 'text'. If 'predicate' is provided, 'prefix' will only be added to the lines where 'predicate(line)' is True. If 'predicate' is not provided, it will default to adding 'prefix' to all non-empty lines that ...
Adds 'prefix' to the beginning of selected lines in 'text'. If 'predicate' is provided, 'prefix' will only be added to the lines where 'predicate(line)' is True. If 'predicate' is not provided, it will default to adding 'prefix' to all non-empty lines that do not consist solely of whitespace characters...
def to_compressed_string(val, max_length=0): """Converts val to a compressed string. A compressed string is one with no leading or trailing spaces. If val is None, or is blank (all spaces) None is returned. If max_length > 0 and the stripped val is greater than max_length, val[:max_length] is returned. ""...
Converts val to a compressed string. A compressed string is one with no leading or trailing spaces. If val is None, or is blank (all spaces) None is returned. If max_length > 0 and the stripped val is greater than max_length, val[:max_length] is returned.
def get_all_attributes(klass_or_instance): """Get all attribute members (attribute, property style method). """ pairs = list() for attr, value in inspect.getmembers( klass_or_instance, lambda x: not inspect.isroutine(x)): if not (attr.startswith("__") or attr.endswith("__")): ...
Get all attribute members (attribute, property style method).
def unmap_namespace(self, plain_target_ns): """Given a plain target namespace, return the corresponding source namespace. """ # Return the same namespace if there are no included namespaces. if not self._regex_map and not self._plain: return plain_target_ns s...
Given a plain target namespace, return the corresponding source namespace.
def _get_mdm(cls, df, windows): """ -DM, negative directional moving accumulation If window is not 1, return the SMA of -DM. :param df: data :param windows: range :return: """ window = cls.get_only_one_positive_int(windows) column_name = 'mdm_{}'...
-DM, negative directional moving accumulation If window is not 1, return the SMA of -DM. :param df: data :param windows: range :return:
def interpolate(G, f_subsampled, keep_inds, order=100, reg_eps=0.005, **kwargs): r"""Interpolate a graph signal. Parameters ---------- G : Graph f_subsampled : ndarray A graph signal on the graph G. keep_inds : ndarray List of indices on which the signal is sampled. order : ...
r"""Interpolate a graph signal. Parameters ---------- G : Graph f_subsampled : ndarray A graph signal on the graph G. keep_inds : ndarray List of indices on which the signal is sampled. order : int Degree of the Chebyshev approximation (default = 100). reg_eps : floa...
def cache_cleaned(name=None, user=None, force=False): ''' Ensure that the given package is not cached. If no package is specified, this ensures the entire cache is cleared. name The name of the package to remove from the cache, or None for all packages ...
Ensure that the given package is not cached. If no package is specified, this ensures the entire cache is cleared. name The name of the package to remove from the cache, or None for all packages user The user to run NPM with force Force cleaning of cache. Required for npm@5 ...
def _get_c_string(data, position): """Decode a BSON 'C' string to python unicode string.""" end = data.index(b"\x00", position) return _utf_8_decode(data[position:end], None, True)[0], end + 1
Decode a BSON 'C' string to python unicode string.
def rename(self, mapping): """ Rename fields :param mapping: a dict in the format {'oldkey1': 'newkey1', ...} """ for old_key, new_key in mapping: self.dict[new_key] = self.dict[old_key] del self.dict[old_key]
Rename fields :param mapping: a dict in the format {'oldkey1': 'newkey1', ...}
def _rectify(settings): """ Rectify (and validate) the given settings using the functions in :data:`_settings_rectifiers`. """ for key, rectifier in _settings_rectifiers.items(): try: new_value = rectifier['func'](settings[key]) if new_value is False: rais...
Rectify (and validate) the given settings using the functions in :data:`_settings_rectifiers`.