code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def tqxn(mt, x, n, t): """ n/qx : Probability to die in n years being alive at age x. Probability that x survives n year, and then dies in th subsequent t years """ return tpx(mt, x, t) * qx(mt, x + n)
n/qx : Probability to die in n years being alive at age x. Probability that x survives n year, and then dies in th subsequent t years
def create_routes_and_handler(transmute_func, context): """ return back a handler that is the api generated from the transmute_func, and a list of routes it should be mounted to. """ @wraps(transmute_func.raw_func) def handler(): exc, result = None, None try: args...
return back a handler that is the api generated from the transmute_func, and a list of routes it should be mounted to.
def geometry_checker(geometry): """Perform a cleaning if the geometry is not valid. :param geometry: The geometry to check and clean. :type geometry: QgsGeometry :return: Tuple of bool and cleaned geometry. True if the geometry is already valid, False if the geometry was not valid. A c...
Perform a cleaning if the geometry is not valid. :param geometry: The geometry to check and clean. :type geometry: QgsGeometry :return: Tuple of bool and cleaned geometry. True if the geometry is already valid, False if the geometry was not valid. A cleaned geometry, or None if the geometr...
def read(self, device=None, offset=0, bs=None, count=1): """ Using DIRECT_O read from the block device specified to stdout (Without any optional arguments will read the first 4k from the device) """ volume = self.get_volume(device) block_size = bs or BLOCK_SIZE o...
Using DIRECT_O read from the block device specified to stdout (Without any optional arguments will read the first 4k from the device)
def listen(self): """Start listening.""" _LOGGER.info('Creating Multicast Socket') self._mcastsocket = self._create_mcast_socket() self._listening = True thread = Thread(target=self._listen_to_msg, args=()) self._threads.append(thread) thread.daemon = True ...
Start listening.
def publish (self): ''' Function to publish cmdvel. ''' self.lock.acquire() tw = cmdvel2Twist(self.vel) self.lock.release() if (self.jdrc.getState() == "flying"): self.pub.publish(tw)
Function to publish cmdvel.
def saveThumbnail(self,fileName,filePath): """ URL to the thumbnail used for the item """ if self._thumbnail is None: self.__init() param_dict = {} if self._thumbnail is not None: imgUrl = self.root + "/info/" + self._thumbnail onlineFileName, file_ex...
URL to the thumbnail used for the item
def method(cache_name, key_prefix=None): """Caching decorator for object-level method caches. Cache key generation is delegated to the cache. Args: cache_name (str): The name of the (already-instantiated) cache on the decorated object which should be used to store results o...
Caching decorator for object-level method caches. Cache key generation is delegated to the cache. Args: cache_name (str): The name of the (already-instantiated) cache on the decorated object which should be used to store results of this method. *key_prefix: A constant t...
def read_var_str(self, max_size=sys.maxsize): """ Similar to `ReadString` but expects a variable length indicator instead of the fixed 1 byte indicator. Args: max_size (int): (Optional) maximum number of bytes to read. Returns: bytes: """ length ...
Similar to `ReadString` but expects a variable length indicator instead of the fixed 1 byte indicator. Args: max_size (int): (Optional) maximum number of bytes to read. Returns: bytes:
def pathname(self): """Sluggified path for filenames Slugs to a filename using the follow steps * Decode unicode to approximate ascii * Remove existing hypens * Substitute hyphens for non-word characters * Break up the string as paths """ slug = self.nam...
Sluggified path for filenames Slugs to a filename using the follow steps * Decode unicode to approximate ascii * Remove existing hypens * Substitute hyphens for non-word characters * Break up the string as paths
def _tokenize(self, source, name, filename=None, state=None): """Called by the parser to do the preprocessing and filtering for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. """ source = self.preprocess(source, name, filename) stream = self.lexer.tokenize(sou...
Called by the parser to do the preprocessing and filtering for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
def VShadowPathSpecGetStoreIndex(path_spec): """Retrieves the store index from the path specification. Args: path_spec (PathSpec): path specification. Returns: int: store index or None if not available. """ store_index = getattr(path_spec, 'store_index', None) if store_index is None: location...
Retrieves the store index from the path specification. Args: path_spec (PathSpec): path specification. Returns: int: store index or None if not available.
def videos(self, **kwargs): """ Get the videos that have been added to a TV episode (teasers, clips, etc...). Args: language: (optional) ISO 639 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get...
Get the videos that have been added to a TV episode (teasers, clips, etc...). Args: language: (optional) ISO 639 code. Returns: A dict respresentation of the JSON returned from the API.
def make_items_for(brains_or_objects, endpoint=None, complete=False): """Generate API compatible data items for the given list of brains/objects :param brains_or_objects: List of objects or brains :type brains_or_objects: list/Products.ZCatalog.Lazy.LazyMap :param endpoint: The named URL endpoint for t...
Generate API compatible data items for the given list of brains/objects :param brains_or_objects: List of objects or brains :type brains_or_objects: list/Products.ZCatalog.Lazy.LazyMap :param endpoint: The named URL endpoint for the root of the items :type endpoint: str/unicode :param complete: Fla...
def can_delete_objectives(self): """Tests if this user can delete Objectives. A return of true does not guarantee successful authorization. A return of false indicates that it is known deleting an Objective will result in a PermissionDenied. This is intended as a hint to an appli...
Tests if this user can delete Objectives. A return of true does not guarantee successful authorization. A return of false indicates that it is known deleting an Objective will result in a PermissionDenied. This is intended as a hint to an application that may opt not to offer delete oper...
def get_portal_url_base(self): """ Determine root url of the data service from the url specified. :return: str root url of the data service (eg: https://dataservice.duke.edu) """ api_url = urlparse(self.url).hostname portal_url = re.sub('^api\.', '', api_url) port...
Determine root url of the data service from the url specified. :return: str root url of the data service (eg: https://dataservice.duke.edu)
def running_conversions(self, folder_id=None): """Shows running file converts by folder Note: If folder_id is not provided, ``Home`` folder will be used. Args: folder_id (:obj:`str`, optional): id of the folder to list conversions of files exist in it. Returns:...
Shows running file converts by folder Note: If folder_id is not provided, ``Home`` folder will be used. Args: folder_id (:obj:`str`, optional): id of the folder to list conversions of files exist in it. Returns: list: list of dictionaries, each dictionary r...
def _make_probs(self, *sequences): """ https://github.com/gw-c/arith/blob/master/arith.py """ sequences = self._get_counters(*sequences) counts = self._sum_counters(*sequences) if self.terminator is not None: counts[self.terminator] = 1 total_letters =...
https://github.com/gw-c/arith/blob/master/arith.py
def correctX(args): """ %prog correctX folder tag Run ALLPATHS correction on a folder of paired reads and apply tag. """ p = OptionParser(correctX.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) folder, tag = args tag = tag.split(",...
%prog correctX folder tag Run ALLPATHS correction on a folder of paired reads and apply tag.
def render(self, name=None, template=None, context={}): ''''Render Template meta from jinja2 templates. ''' if isinstance(template, Template): _template = template else: _template = Template.objects.get(name=name) # Maybe cache or save local ? r...
Render Template meta from jinja2 templates.
def tricu(P, k=0): """Cross-diagonal upper triangle.""" tri = numpy.sum(numpy.mgrid[[slice(0,_,1) for _ in P.shape]], 0) tri = tri<len(tri) + k if isinstance(P, Poly): A = P.A.copy() B = {} for key in P.keys: B[key] = A[key]*tri return Poly(B, shape=P.shape, ...
Cross-diagonal upper triangle.
def add_access_list(self, accesslist, rank=None): """ Add an access list to the match condition. Valid access list types are IPAccessList (v4 and v6), IPPrefixList (v4 and v6), AS Path, CommunityAccessList, ExtendedCommunityAccessList. """ self.conditions.append( ...
Add an access list to the match condition. Valid access list types are IPAccessList (v4 and v6), IPPrefixList (v4 and v6), AS Path, CommunityAccessList, ExtendedCommunityAccessList.
def syscall(self, func): ''' Call the func in core context (main loop). func should like:: def syscall_sample(scheduler, processor): something... where processor is a function which accept an event. When calling processor, scheduler directly...
Call the func in core context (main loop). func should like:: def syscall_sample(scheduler, processor): something... where processor is a function which accept an event. When calling processor, scheduler directly process this event without sending i...
def is_tuple_type(tp): """Test if the type is a generic tuple type, including subclasses excluding non-generic classes. Examples:: is_tuple_type(int) == False is_tuple_type(tuple) == False is_tuple_type(Tuple) == True is_tuple_type(Tuple[str, int]) == True class MyCl...
Test if the type is a generic tuple type, including subclasses excluding non-generic classes. Examples:: is_tuple_type(int) == False is_tuple_type(tuple) == False is_tuple_type(Tuple) == True is_tuple_type(Tuple[str, int]) == True class MyClass(Tuple[str, int]): ...
def _get_value_from_match(self, key, match): """ Gets the value of the property in the given MatchObject. Args: key (str): Key of the property looked-up. match (MatchObject): The matched property. Return: The discovered value, as a string o...
Gets the value of the property in the given MatchObject. Args: key (str): Key of the property looked-up. match (MatchObject): The matched property. Return: The discovered value, as a string or boolean.
def get_checkerboard_matrix(kernel_width): """ example matrix for width = 2 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1 :param kernel_width: :return: """ return np.vstack(( np.hstack(( -1 * np.ones((kernel_width, kernel_width)), np.ones...
example matrix for width = 2 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1 :param kernel_width: :return:
def stripped_db_url(url): """Return a version of the DB url with the password stripped out.""" parsed = urlparse(url) if parsed.password is None: return url return parsed._replace( netloc="{}:***@{}".format(parsed.username, parsed.hostname) ).geturl()
Return a version of the DB url with the password stripped out.
def format_config(sensor_graph): """Extract the config variables from this sensor graph in ASCII format. Args: sensor_graph (SensorGraph): the sensor graph that we want to format Returns: str: The ascii output lines concatenated as a single string """ cmdfile = CommandFile("Config...
Extract the config variables from this sensor graph in ASCII format. Args: sensor_graph (SensorGraph): the sensor graph that we want to format Returns: str: The ascii output lines concatenated as a single string
def start(component, exact): # type: (str) -> None """ Create a new release. It will bump the current version number and create a release branch called `release/<version>` with one new commit (the version bump). **Example Config**:: \b version_file: 'src/mypkg/__init__.py' **...
Create a new release. It will bump the current version number and create a release branch called `release/<version>` with one new commit (the version bump). **Example Config**:: \b version_file: 'src/mypkg/__init__.py' **Examples**:: \b $ peltak release start patch ...
def setShadowed(self, state): """ Sets whether or not this toolbar is shadowed. :param state | <bool> """ self._shadowed = state if state: self._colored = False for child in self.findChildren(XToolButton): child.setSh...
Sets whether or not this toolbar is shadowed. :param state | <bool>
def subnet_get(auth=None, **kwargs): ''' Get a single subnet filters A Python dictionary of filter conditions to push down CLI Example: .. code-block:: bash salt '*' neutronng.subnet_get name=subnet1 ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwarg...
Get a single subnet filters A Python dictionary of filter conditions to push down CLI Example: .. code-block:: bash salt '*' neutronng.subnet_get name=subnet1
def add_algorithm(self, parser): """Add the --algorithm option.""" help = 'The HashAlgorithm that will be used to generate the signature (default: %(default)s).' % { 'default': ca_settings.CA_DIGEST_ALGORITHM.name, } parser.add_argument( '--algorithm', metavar='{sha512,...
Add the --algorithm option.
def sphergal_to_rectgal(l,b,d,vr,pmll,pmbb,degree=False): """ NAME: sphergal_to_rectgal PURPOSE: transform phase-space coordinates in spherical Galactic coordinates to rectangular Galactic coordinates (can take vector inputs) INPUT: l - Galactic longitude (rad) b - Gala...
NAME: sphergal_to_rectgal PURPOSE: transform phase-space coordinates in spherical Galactic coordinates to rectangular Galactic coordinates (can take vector inputs) INPUT: l - Galactic longitude (rad) b - Galactic lattitude (rad) d - distance (kpc) vr - line-of-s...
def key(self, *args, **kwargs): """ Return the cache key to use. If you're passing anything but primitive types to the ``get`` method, it's likely that you'll need to override this method. """ if not args and not kwargs: return self.class_path try: ...
Return the cache key to use. If you're passing anything but primitive types to the ``get`` method, it's likely that you'll need to override this method.
def execution(): ''' Collect all the sys.doc output from each minion and return the aggregate CLI Example: .. code-block:: bash salt-run doc.execution ''' client = salt.client.get_local_client(__opts__['conf_file']) docs = {} try: for ret in client.cmd_iter('*', 'sys....
Collect all the sys.doc output from each minion and return the aggregate CLI Example: .. code-block:: bash salt-run doc.execution
def flush(self): # nocover """ Flush to this and the redirected stream """ if self.redirect is not None: self.redirect.flush() super(TeeStringIO, self).flush()
Flush to this and the redirected stream
def data(self): """ Get a cached post-processed result of a GitHub API call. Uses Trac cache to avoid constant querying of the remote API. If a previous API call did not succeed, automatically retries after a timeout. """ if self._next_update and datetime.now() > self._ne...
Get a cached post-processed result of a GitHub API call. Uses Trac cache to avoid constant querying of the remote API. If a previous API call did not succeed, automatically retries after a timeout.
def ternarize(x, thresh=0.05): """ Implemented Trained Ternary Quantization: https://arxiv.org/abs/1612.01064 Code modified from the authors' at: https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py """ shape = x.get_shape() thre_x = tf.stop_gradient(tf.redu...
Implemented Trained Ternary Quantization: https://arxiv.org/abs/1612.01064 Code modified from the authors' at: https://github.com/czhu95/ternarynet/blob/master/examples/Ternary-Net/ternary.py
def from_env(cls, prefix, kms_decrypt=False, aws_profile=None): """ Load database credential from env variable. - host: ENV.{PREFIX}_HOST - port: ENV.{PREFIX}_PORT - database: ENV.{PREFIX}_DATABASE - username: ENV.{PREFIX}_USERNAME - password: ENV.{PREFIX}_PASSWO...
Load database credential from env variable. - host: ENV.{PREFIX}_HOST - port: ENV.{PREFIX}_PORT - database: ENV.{PREFIX}_DATABASE - username: ENV.{PREFIX}_USERNAME - password: ENV.{PREFIX}_PASSWORD :param prefix: str :param kms_decrypt: bool :param aws_p...
def red_ext(request, message=None): ''' The external landing. Also a convenience function for redirecting users who don't have site access to the external page. Parameters: request - the request in the calling function message - a message from the caller function ''' if message: ...
The external landing. Also a convenience function for redirecting users who don't have site access to the external page. Parameters: request - the request in the calling function message - a message from the caller function
def evaluate(data_source, batch_size, ctx=None): """Evaluate the model on the dataset with cache model. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. ctx : mx.cpu() or mx.gpu() The context of the com...
Evaluate the model on the dataset with cache model. Parameters ---------- data_source : NDArray The dataset is evaluated on. batch_size : int The size of the mini-batch. ctx : mx.cpu() or mx.gpu() The context of the computation. Returns ------- loss: float ...
def node_hist_fig( node_color_distribution, title="Graph Node Distribution", width=400, height=300, top=60, left=25, bottom=60, right=25, bgcolor="rgb(240,240,240)", y_gridcolor="white", ): """Define the plotly plot representing the node histogram Param...
Define the plotly plot representing the node histogram Parameters ---------- node_color_distribution: list of dicts describing the build_histogram width, height: integers - width and height of the histogram FigureWidget left, top, right, bottom: ints; number of pixels around the FigureWi...
def __set_URL(self, url): """ URL is stored as a str internally and must not contain ASCII chars. Raised exception in case of detected non-ASCII URL characters may be either UnicodeEncodeError or UnicodeDecodeError, depending on the used Python version's str type and the exact v...
URL is stored as a str internally and must not contain ASCII chars. Raised exception in case of detected non-ASCII URL characters may be either UnicodeEncodeError or UnicodeDecodeError, depending on the used Python version's str type and the exact value passed as URL input data.
def get_events(self, **kwargs): """Retrieve events from server.""" force = kwargs.pop('force', False) response = api.request_sync_events(self.blink, self.network_id, force=force) try: return...
Retrieve events from server.
def _build_sql_query( self): """ *build sql query for the sdss square search* **Key Arguments:** # - **Return:** - None .. todo:: """ self.log.info('starting the ``_build_sql_query`` method') ra1, ra2, dec1, dec2 = ...
*build sql query for the sdss square search* **Key Arguments:** # - **Return:** - None .. todo::
def _update_targets(vesseldicts, environment_dict): """ <Purpose> Connects to the nodes in the vesseldicts and adds them to the list of valid targets. <Arguments> vesseldicts: A list of vesseldicts obtained through SeattleClearinghouseClient calls. <Side Effects> All valid targ...
<Purpose> Connects to the nodes in the vesseldicts and adds them to the list of valid targets. <Arguments> vesseldicts: A list of vesseldicts obtained through SeattleClearinghouseClient calls. <Side Effects> All valid targets that the user can access on the specified nodes are ...
def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: ...
List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*...
def accept(self, origin, protocol): """ Create a new route attached to a L{IBoxReceiver} created by the L{IBoxReceiverFactory} with the indicated protocol. @type origin: C{unicode} @param origin: The identifier of a route on the peer which will be associated with thi...
Create a new route attached to a L{IBoxReceiver} created by the L{IBoxReceiverFactory} with the indicated protocol. @type origin: C{unicode} @param origin: The identifier of a route on the peer which will be associated with this connection. Boxes sent back by the protocol ...
def paintEvent(self, event): """ Draws the pixmap for this widget. :param event | <QPaintEvent> """ pixmap = self.currentPixmap() rect = self.currentPixmapRect() with XPainter(self) as painter: painter.drawPixmap(rect...
Draws the pixmap for this widget. :param event | <QPaintEvent>
def cp(hdfs_src, hdfs_dst): """Copy a file :param hdfs_src: Source (str) :param hdfs_dst: Destination (str) :raises: IOError: If unsuccessful """ cmd = "hadoop fs -cp %s %s" % (hdfs_src, hdfs_dst) rcode, stdout, stderr = _checked_hadoop_fs_command(cmd)
Copy a file :param hdfs_src: Source (str) :param hdfs_dst: Destination (str) :raises: IOError: If unsuccessful
def _readClusterSettings(self): """ Read the current instance's meta-data to get the cluster settings. """ # get the leader metadata mdUrl = "http://169.254.169.254/metadata/instance?api-version=2017-08-01" header = {'Metadata': 'True'} request = urllib.request.Re...
Read the current instance's meta-data to get the cluster settings.
def get_top_paths(self): """ :calls: `GET /repos/:owner/:repo/traffic/popular/paths <https://developer.github.com/v3/repos/traffic/>`_ :rtype: :class:`list` of :class:`github.Path.Path` """ headers, data = self._requester.requestJsonAndCheck( "GET", self.u...
:calls: `GET /repos/:owner/:repo/traffic/popular/paths <https://developer.github.com/v3/repos/traffic/>`_ :rtype: :class:`list` of :class:`github.Path.Path`
def apply(self, s, active=None): """ Apply the REPP's rewrite rules to the input string *s*. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called Returns: a :...
Apply the REPP's rewrite rules to the input string *s*. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called Returns: a :class:`REPPResult` object containing the processed ...
def merge_dict(self, *args, **kwargs): """ Takes variable inputs, compiles them into a dictionary then merges it to the current nomenclate's state :param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be converted to dicts :param kwargs: str, any number of kwargs th...
Takes variable inputs, compiles them into a dictionary then merges it to the current nomenclate's state :param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be converted to dicts :param kwargs: str, any number of kwargs that represent token:value pairs
def _run_train_step(self, data, mode='train'): """Run a single training step. :param data: input data :param mode: 'train' or 'test'. """ epoch_size = ((len(data) // self.batch_size) - 1) // self.num_steps costs = 0.0 iters = 0 step = 0 state = se...
Run a single training step. :param data: input data :param mode: 'train' or 'test'.
def partition_agent(host): """ Partition a node from all network traffic except for SSH and loopback :param hostname: host or IP of the machine to partition from the cluster """ network.save_iptables(host) network.flush_all_rules(host) network.allow_all_traffic(host) network.run_iptabl...
Partition a node from all network traffic except for SSH and loopback :param hostname: host or IP of the machine to partition from the cluster
def get_context_dict(self): """ return a context dict of the desired state """ context_dict = {} for s in self.sections(): for k, v in self.manifest.items(s): context_dict["%s:%s" % (s, k)] = v for k, v in self.inputs.values().items(): context_dict...
return a context dict of the desired state
def unset(self, host, *args): """ Removes settings for a host. Parameters ---------- host : the host to remove settings from. *args : list of settings to removes. """ self.__check_host_args(host, args) remove_idx = [idx for idx, x in enumerate(sel...
Removes settings for a host. Parameters ---------- host : the host to remove settings from. *args : list of settings to removes.
def search_elementnames(self, *substrings: str, name: str = 'elementnames') -> 'Selection': """Return a new selection containing all elements of the current selection with a name containing at least one of the given substrings. >>> from hydpy.core.examples import pre...
Return a new selection containing all elements of the current selection with a name containing at least one of the given substrings. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, _ = prepare_full_example_2() Pass the (sub)strings as positional arguments and, o...
def _create_index_content(words): """Create html string of index file. Parameters ---------- words : list of str List of cached words. Returns ------- str html string. """ content = ["<h1>Index</h1>", "<ul>"] for word in words: content.append( ...
Create html string of index file. Parameters ---------- words : list of str List of cached words. Returns ------- str html string.
def setOverlayAlpha(self, ulOverlayHandle, fAlpha): """Sets the alpha of the overlay quad. Use 1.0 for 100 percent opacity to 0.0 for 0 percent opacity.""" fn = self.function_table.setOverlayAlpha result = fn(ulOverlayHandle, fAlpha) return result
Sets the alpha of the overlay quad. Use 1.0 for 100 percent opacity to 0.0 for 0 percent opacity.
def get_info(self, full=False): " Return printable information about current site. " if full: context = self.as_dict() return "".join("{0:<25} = {1}\n".format( key, context[key]) for key in sorted(context.iterkeys())) return "%s [%s]" % (self.g...
Return printable information about current site.
def ProcessPathSpec(self, mediator, path_spec): """Processes a path specification. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. path_spec (dfvfs.PathSpec): path specification. """ self.last_acti...
Processes a path specification. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. path_spec (dfvfs.PathSpec): path specification.
def b64_decode(data: bytes) -> bytes: """ :param data: Base 64 encoded data to decode. :type data: bytes :return: Base 64 decoded data. :rtype: bytes """ missing_padding = len(data) % 4 if missing_padding != 0: data += b'=' * (4 - missing_padding) return urlsafe_b64decode(dat...
:param data: Base 64 encoded data to decode. :type data: bytes :return: Base 64 decoded data. :rtype: bytes
def slicing_singlevalue(arg, length): """Internally used.""" if isinstance(arg, slice): start, stop, step = arg.indices(length) i = start if step > 0: while i < stop: yield i i += step else: while i > stop: y...
Internally used.
def _check_reach_env(): """Check that the environment supports runnig reach.""" # Get the path to the REACH JAR path_to_reach = get_config('REACHPATH') if path_to_reach is None: path_to_reach = environ.get('REACHPATH', None) if path_to_reach is None or not path.exists...
Check that the environment supports runnig reach.
def volumes(self, assets, dt): """ The volume field's aggregation returns the sum of all volumes between the market open and the `dt` If there has been no data on or before the `dt` the volume is 0. Returns ------- np.array with dtype=int64, in order of assets pa...
The volume field's aggregation returns the sum of all volumes between the market open and the `dt` If there has been no data on or before the `dt` the volume is 0. Returns ------- np.array with dtype=int64, in order of assets parameter.
def _post_init(self): """A post init trigger""" try: return self.postinit() except Exception as exc: return self._onerror(Result.from_exception(exc, uuid=self.uuid))
A post init trigger
def is_active(self): """Determines whether this plugin is active. This plugin is only active if any run has an embedding. Returns: Whether any run has embedding data to show in the projector. """ if not self.multiplexer: return False if self._is_active: # We have already det...
Determines whether this plugin is active. This plugin is only active if any run has an embedding. Returns: Whether any run has embedding data to show in the projector.
def remove_product_version(self, id, product_version_id, **kwargs): """ Removes a product version from the specified config set This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoke...
Removes a product version from the specified config set This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ...
def add_dns(ip, interface='Local Area Connection', index=1): ''' Add the DNS server to the network interface (index starts from 1) Note: if the interface DNS is configured by DHCP, all the DNS servers will be removed from the interface and the requested DNS will be the only one CLI Example: ...
Add the DNS server to the network interface (index starts from 1) Note: if the interface DNS is configured by DHCP, all the DNS servers will be removed from the interface and the requested DNS will be the only one CLI Example: .. code-block:: bash salt '*' win_dns_client.add_dns <ip> <in...
async def load_credentials(self, credentials): """Load existing credentials.""" split = credentials.split(':') self.identifier = split[0] self.srp.initialize(binascii.unhexlify(split[1])) _LOGGER.debug('Loaded AirPlay credentials: %s', credentials)
Load existing credentials.
def _serialize_normalized_array(array, fmt='png', quality=70): """Given a normalized array, returns byte representation of image encoding. Args: array: NumPy array of dtype uint8 and range 0 to 255 fmt: string describing desired file format, defaults to 'png' quality: specifies compression quality from...
Given a normalized array, returns byte representation of image encoding. Args: array: NumPy array of dtype uint8 and range 0 to 255 fmt: string describing desired file format, defaults to 'png' quality: specifies compression quality from 0 to 100 for lossy formats Returns: image data as BytesIO bu...
def start(self): """Start the single-user server in a docker service. You can specify the params for the service through jupyterhub_config.py or using the user_options """ # https://github.com/jupyterhub/jupyterhub/blob/master/jupyterhub/user.py#L202 # By default jupyter...
Start the single-user server in a docker service. You can specify the params for the service through jupyterhub_config.py or using the user_options
def traceroute(target, dport=80, minttl=1, maxttl=30, sport=RandShort(), l4=None, filter=None, timeout=2, verbose=None, **kargs): # noqa: E501 """Instant TCP traceroute traceroute(target, [maxttl=30,] [dport=80,] [sport=80,] [verbose=conf.verb]) -> None # noqa: E501 """ if verbose is None: verbose = c...
Instant TCP traceroute traceroute(target, [maxttl=30,] [dport=80,] [sport=80,] [verbose=conf.verb]) -> None # noqa: E501
def get_weekly_charts(self, chart_kind, from_date=None, to_date=None): """ Returns the weekly charts for the week starting from the from_date value to the to_date value. chart_kind should be one of "album", "artist" or "track" """ method = ".getWeekly" + chart_kind.title(...
Returns the weekly charts for the week starting from the from_date value to the to_date value. chart_kind should be one of "album", "artist" or "track"
def start_rpc_listeners(self): """Configure all listeners here""" self._setup_rpc() if not self.endpoints: return [] self.conn = n_rpc.create_connection() self.conn.create_consumer(self.topic, self.endpoints, fanout=False) ret...
Configure all listeners here
def date_of_birth(self, value): """ The date of birth of the individual. :param value: :return: """ if value: self._date_of_birth = parse(value).date() if isinstance(value, type_check) else value
The date of birth of the individual. :param value: :return:
def load_config(self, path, environments, fill_with_defaults=False): """Will load default.yaml and <environment>.yaml at given path. The environment config will override the default values. :param path: directory where to find your config files. If the last character is not a slash (/) it will ...
Will load default.yaml and <environment>.yaml at given path. The environment config will override the default values. :param path: directory where to find your config files. If the last character is not a slash (/) it will be appended. Example: resources/ :param environments: list of environmen...
def sufar4(ascfile, meas_output='measurements.txt', aniso_output='rmag_anisotropy.txt', spec_infile=None, spec_outfile='specimens.txt', samp_outfile='samples.txt', site_outfile='sites.txt', specnum=0, sample_naming_con='1', user="", locname="unknown", instrument='', static_15_position_m...
Converts ascii files generated by SUFAR ver.4.0 to MagIC files Parameters ---------- ascfile : str input ASC file, required meas_output : str measurement output filename, default "measurements.txt" aniso_output : str anisotropy output filename, MagIC 2 only, "rmag_anisotropy...
def diffuse(self, *args): """ this is a dispatcher of diffuse implementation. Depending of the arguments used. """ mode = diffusingModeEnum.unknown if (isinstance(args[0], str) and (len(args) == 3)): # reveived diffuse(str, any, any) mode = diffus...
this is a dispatcher of diffuse implementation. Depending of the arguments used.
def post_request(profile, resource, payload): """Do a POST request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with....
Do a POST request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource The part of a Github A...
def QA_indicator_RSI(DataFrame, N1=12, N2=26, N3=9): '相对强弱指标RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;' CLOSE = DataFrame['close'] LC = REF(CLOSE, 1) RSI1 = SMA(MAX(CLOSE - LC, 0), N1) / SMA(ABS(CLOSE - LC), N1) * 100 RSI2 = SMA(MAX(CLOSE - LC, 0), N2) / SMA(ABS(CLOSE - LC), N2) * 1...
相对强弱指标RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;
def fdrcorrection(pvals, alpha=0.05): """ benjamini hocheberg fdr correction. inspired by statsmodels """ # Implement copy from GOATools. pvals = np.asarray(pvals) pvals_sortind = np.argsort(pvals) pvals_sorted = np.take(pvals, pvals_sortind) ecdffactor = _ecdf(pvals_sorted) reject = p...
benjamini hocheberg fdr correction. inspired by statsmodels
def save(self, *args, **kwargs): """ automatically update updated date field """ # auto fill updated field with current time unless explicitly disabled auto_update = kwargs.get('auto_update', True) if auto_update: self.updated = now() # remove eventua...
automatically update updated date field
def sys_open(self, buf, flags, mode): """ :param buf: address of zero-terminated pathname :param flags: file access bits :param mode: file permission mode """ filename = self.current.read_string(buf) try: f = self._sys_open_get_file(filename, flags) ...
:param buf: address of zero-terminated pathname :param flags: file access bits :param mode: file permission mode
def prepare_mainsubstituter(): """Prepare and return a |Substituter| object for the main `__init__` file of *HydPy*.""" substituter = Substituter() for module in (builtins, numpy, datetime, unittest, doctest, inspect, io, os, sys, time, collections, itertools, subprocess, scipy, ...
Prepare and return a |Substituter| object for the main `__init__` file of *HydPy*.
def _make_multidim_func(one_d_func, n, *args): """ A helper function to cut down on code repetition. Almost all of the code in qnwcheb, qnwlege, qnwsimp, qnwtrap is just dealing various forms of input arguments and then shelling out to the corresponding 1d version of the function. This routine ...
A helper function to cut down on code repetition. Almost all of the code in qnwcheb, qnwlege, qnwsimp, qnwtrap is just dealing various forms of input arguments and then shelling out to the corresponding 1d version of the function. This routine does all the argument checking and passes things throug...
def get_comments(self): """ :calls: `GET /gists/:gist_id/comments <http://developer.github.com/v3/gists/comments>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.GistComment.GistComment` """ return github.PaginatedList.PaginatedList( github.Gis...
:calls: `GET /gists/:gist_id/comments <http://developer.github.com/v3/gists/comments>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.GistComment.GistComment`
def java_install(self): """ install java :return: """ sudo('apt-get install openjdk-8-jdk -y') java_home = run('readlink -f /usr/bin/java | ' 'sed "s:/jre/bin/java::"') append(bigdata_conf.global_env_home, 'export JAVA_HOME={0}'.format( ...
install java :return:
def _bind_sources_to_destination(self): # type: (SyncCopy) -> # Tuple[blobxfer.models.azure.StorageEntity, # blobxfer.models.azure.StorageEntity] """Bind source storage entity to destination storage entities :param SyncCopy self: this :rtype: tuple :...
Bind source storage entity to destination storage entities :param SyncCopy self: this :rtype: tuple :return: (source storage entity, destination storage entity)
def _reuse_pre_installed_setuptools(env, installer): """ Return whether a pre-installed setuptools distribution should be reused. """ if not env.setuptools_version: return # no prior setuptools ==> no reuse reuse_old = config.reuse_old_setuptools reuse_best = config.reuse_best_...
Return whether a pre-installed setuptools distribution should be reused.
def on_attribute(self, name): """ Decorator for attribute listeners. The decorated function (``observer``) is invoked differently depending on the *type of attribute*. Attributes that represent sensor values or which are used to monitor connection status are updated whenever a m...
Decorator for attribute listeners. The decorated function (``observer``) is invoked differently depending on the *type of attribute*. Attributes that represent sensor values or which are used to monitor connection status are updated whenever a message is received from the vehicle. Attributes wh...
def uridecode(uristring, encoding='utf-8', errors='strict'): """Decode a URI string or string component.""" if not isinstance(uristring, bytes): uristring = uristring.encode(encoding or 'ascii', errors) parts = uristring.split(b'%') result = [parts[0]] append = result.append decode = _de...
Decode a URI string or string component.
def to_bytes(self): """Convert the entire image to bytes. :rtype: bytes """ # grab the chunks we needs out = [PNG_SIGN] # FIXME: it's tricky to define "other_chunks". HoneyView stop the # animation if it sees chunks other than fctl or idat, so we put other # chunks to the end of the file other_...
Convert the entire image to bytes. :rtype: bytes
async def set_position(self, position, wait_for_completion=True): """Set window to desired position. Parameters: * position: Position object containing the target position. * wait_for_completion: If set, function will return after device has reached target positi...
Set window to desired position. Parameters: * position: Position object containing the target position. * wait_for_completion: If set, function will return after device has reached target position.
def generate_ill_conditioned_dot_product(n, c, dps=100): """n ... length of vector c ... target condition number """ # Algorithm 6.1 from # # ACCURATE SUM AND DOT PRODUCT, # TAKESHI OGITA, SIEGFRIED M. RUMP, AND SHIN'ICHI OISHI. assert n >= 6 n2 = round(n / 2) x = numpy.zeros(n) ...
n ... length of vector c ... target condition number
def get_partition_by_name(self, db_name, tbl_name, part_name): """ Parameters: - db_name - tbl_name - part_name """ self.send_get_partition_by_name(db_name, tbl_name, part_name) return self.recv_get_partition_by_name()
Parameters: - db_name - tbl_name - part_name
def changed(self, name): """Returns true if the parameter with the specified name has its value changed by the *first* module procedure in the interface. :arg name: the name of the parameter to check changed status for. """ if self.first: return self.first.changed(na...
Returns true if the parameter with the specified name has its value changed by the *first* module procedure in the interface. :arg name: the name of the parameter to check changed status for.
def env(self, **kw): ''' Allows adding/overriding env vars in the execution context. :param kw: Key-value pairs :return: self ''' self._original_env = kw if self._env is None: self._env = dict(os.environ) self._env.update({k: unicode(v) for k, ...
Allows adding/overriding env vars in the execution context. :param kw: Key-value pairs :return: self