code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def genre(self): """ Cette routine convertit les indications morphologiques, données dans le fichier lemmes.la, pour exprimer le genre du mot dans la langue courante. :return: Genre :rtype: str """ _genre = "" if " m." in self._indMorph: _genre += "m" ...
Cette routine convertit les indications morphologiques, données dans le fichier lemmes.la, pour exprimer le genre du mot dans la langue courante. :return: Genre :rtype: str
def cli(ctx, uuid, output_format="gzip"): """Download pre-prepared data by UUID Output: The downloaded content """ return ctx.gi.io.download(uuid, output_format=output_format)
Download pre-prepared data by UUID Output: The downloaded content
def cummedian(expr, sort=None, ascending=True, unique=False, preceding=None, following=None): """ Calculate cumulative median of a sequence expression. :param expr: expression for calculation :param sort: name of the sort column :param ascending: whether to sort in ascending order ...
Calculate cumulative median of a sequence expression. :param expr: expression for calculation :param sort: name of the sort column :param ascending: whether to sort in ascending order :param unique: whether to eliminate duplicate entries :param preceding: the start point of a window :param foll...
def create(self, export): """ Create and start processing a new Export. :param Export export: The Export to create. :rtype: Export """ target_url = self.client.get_url(self._URL_KEY, 'POST', 'create') r = self.client.request('POST', target_url, json=export._seria...
Create and start processing a new Export. :param Export export: The Export to create. :rtype: Export
def _truncate(p_str, p_repl): """ Returns p_str with truncated and ended with '...' version of p_repl. Place of the truncation is calculated depending on p_max_width. """ # 4 is for '...' and an extra space at the end text_lim = _columns() - len(escape_ansi(p_str)) - 4 truncated_str = re.su...
Returns p_str with truncated and ended with '...' version of p_repl. Place of the truncation is calculated depending on p_max_width.
def iter_tree(jottapath, JFS): """Get a tree of of files and folders. use as an iterator, you get something like os.walk""" filedirlist = JFS.getObject('%s?mode=list' % jottapath) log.debug("got tree: %s", filedirlist) if not isinstance(filedirlist, JFSFileDirList): yield ( '', tuple(), tuple() ...
Get a tree of of files and folders. use as an iterator, you get something like os.walk
def new(cls, alias, sealed_obj, algorithm, key, key_size): """ Helper function to create a new SecretKeyEntry. :returns: A loaded :class:`SecretKeyEntry` instance, ready to be placed in a keystore. """ timestamp = int(time.time()) * 1000 raise NotImplementedEr...
Helper function to create a new SecretKeyEntry. :returns: A loaded :class:`SecretKeyEntry` instance, ready to be placed in a keystore.
def _get_sliced(self,slice,df=None): """ Returns a sliced DataFrame Parameters ---------- slice : tuple(from,to) from : str to : str States the 'from' and 'to' values which will get rendered as df.ix[from:to] df : DataFrame If omitted then the QuantFigure.DataFrame is resampled. ...
Returns a sliced DataFrame Parameters ---------- slice : tuple(from,to) from : str to : str States the 'from' and 'to' values which will get rendered as df.ix[from:to] df : DataFrame If omitted then the QuantFigure.DataFrame is resampled.
def InitializeUpload(self, http_request, http=None, client=None): """Initialize this upload from the given http_request.""" if self.strategy is None: raise exceptions.UserError( 'No upload strategy set; did you call ConfigureRequest?') if http is None and client is No...
Initialize this upload from the given http_request.
async def related_artists(self) -> List[Artist]: """Get Spotify catalog information about artists similar to a given artist. Similarity is based on analysis of the Spotify community’s listening history. Returns ------- artists : List[Artits] The artists deemed simil...
Get Spotify catalog information about artists similar to a given artist. Similarity is based on analysis of the Spotify community’s listening history. Returns ------- artists : List[Artits] The artists deemed similar.
def evaluate_impl(expression, params=None): '''Implementation of CalculatorImpl::evaluate(), also shared by FunctionImpl::call(). In the latter case, `params` are the parameter values passed to the function; in the former case, `params` is just an empty list.''' which = expression.which() if ...
Implementation of CalculatorImpl::evaluate(), also shared by FunctionImpl::call(). In the latter case, `params` are the parameter values passed to the function; in the former case, `params` is just an empty list.
def commit_and_try_merge2master(git_action, file_content, study_id, auth_info, parent_sha, commit_msg='', merged_sha=None): ...
Actually make a local Git commit and push it to our remote
def plural(self): ''' Tries to scrape the plural version from vandale.nl. ''' element = self._first('NN') if element: if re.search('meervoud: ([\w|\s|\'|\-|,]+)', element, re.U): results = re.search('meervoud: ([\w|\s|\'|\-|,]+)', element, re.U).groups()[0].split(', ') results = [x.replace('ook ', '')...
Tries to scrape the plural version from vandale.nl.
def task_verify(self, task): ''' return False if any of 'taskid', 'project', 'url' is not in task dict or project in not in task_queue ''' for each in ('taskid', 'project', 'url', ): if each not in task or not task[each]: logger.error('...
return False if any of 'taskid', 'project', 'url' is not in task dict or project in not in task_queue
def default_error_handler(exception): """ Default error handler Will display an error page with the corresponding error code from template directory, for example, a not found will load a 404.html etc. Will first look in userland app templates and if not found, fallback to boiler templates to dis...
Default error handler Will display an error page with the corresponding error code from template directory, for example, a not found will load a 404.html etc. Will first look in userland app templates and if not found, fallback to boiler templates to display a default page. :param exception: Except...
def l2_log_loss(event_times, predicted_event_times, event_observed=None): r""" Calculates the l2 log-loss of predicted event times to true event times for *non-censored* individuals only. .. math:: 1/N \sum_{i} (log(t_i) - log(q_i))**2 Parameters ---------- event_times: a (n,) array of ...
r""" Calculates the l2 log-loss of predicted event times to true event times for *non-censored* individuals only. .. math:: 1/N \sum_{i} (log(t_i) - log(q_i))**2 Parameters ---------- event_times: a (n,) array of observed survival times. predicted_event_times: a (n,) array of predicte...
def in6_getifaddr(): """ Returns a list of 3-tuples of the form (addr, scope, iface) where 'addr' is the address of scope 'scope' associated to the interface 'ifcace'. This is the list of all addresses of all interfaces available on the system. """ ret = [] try: fdesc = open...
Returns a list of 3-tuples of the form (addr, scope, iface) where 'addr' is the address of scope 'scope' associated to the interface 'ifcace'. This is the list of all addresses of all interfaces available on the system.
def _workflow_complete(workflow_stage_dict: dict): """Check if the workflow is complete. This function checks if the entire workflow is complete. This function is used by `execute_processing_block`. Args: workflow_stage_dict (dict): Workflow metadata dictionary. Returns: bool, Tr...
Check if the workflow is complete. This function checks if the entire workflow is complete. This function is used by `execute_processing_block`. Args: workflow_stage_dict (dict): Workflow metadata dictionary. Returns: bool, True if the workflow is complete, otherwise False.
def init(argv): """ Bootstrap the whole thing :param argv: list of command line arguments """ # Setting initial configuration values config.set_default({ # driver section "driver": {}, # fs section "fs": {}, # MongoDB section "mongodb": {}, })...
Bootstrap the whole thing :param argv: list of command line arguments
def printText (self, stream=None): """Prints a text representation of this sequence to the given stream or standard output. """ if stream is None: stream = sys.stdout stream.write('# seqid : %u\n' % self.seqid ) stream.write('# version : %u\n' % self.version ) ...
Prints a text representation of this sequence to the given stream or standard output.
def nameddict(name, props): """ Point = nameddict('Point', ['x', 'y']) pt = Point(x=1, y=2) pt.y = 3 print pt """ class NamedDict(object): def __init__(self, *args, **kwargs): self.__store = {}.fromkeys(props) if args: for i, k in enumerate(pro...
Point = nameddict('Point', ['x', 'y']) pt = Point(x=1, y=2) pt.y = 3 print pt
def create_fixed_rate_shipping(cls, fixed_rate_shipping, **kwargs): """Create FixedRateShipping Create a new FixedRateShipping This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_fixed_rate...
Create FixedRateShipping Create a new FixedRateShipping This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_fixed_rate_shipping(fixed_rate_shipping, async=True) >>> result = thread.get() ...
def ggplot2_style(ax): """ Styles an axes to appear like ggplot2 Must be called after all plot and axis manipulation operations have been carried out (needs to know final tick spacing) """ #set the style of the major and minor grid lines, filled blocks ax.grid(True, 'major', color='w', lines...
Styles an axes to appear like ggplot2 Must be called after all plot and axis manipulation operations have been carried out (needs to know final tick spacing)
def _count(self, cmd, collation=None): """Internal count helper.""" with self._socket_for_reads() as (sock_info, slave_ok): res = self._command( sock_info, cmd, slave_ok, allowable_errors=["ns missing"], codec_options=self.__write_response_code...
Internal count helper.
def send_last_message(self, message_type, data, connection_id, callback=None, one_way=False): """ Send a message of message_type and close the connection. :param connection_id: the identity for the connection to send to :param message_type: validator_pb2.Message...
Send a message of message_type and close the connection. :param connection_id: the identity for the connection to send to :param message_type: validator_pb2.Message.* enum value :param data: bytes serialized protobuf :return: future.Future
def add_listener(self, listener, message_type, data=None, one_shot=False): """Add a listener that will receice incoming messages.""" lst = self._one_shots if one_shot else self._listeners if message_type not in lst: lst[message_type] = [] lst[message_type].append(Listener(l...
Add a listener that will receice incoming messages.
def cull_nonmatching_trees(nexson, tree_id, curr_version=None): """Modifies `nexson` and returns it in version 1.2.1 with any tree that does not match the ID removed. Note that this does not search through the NexSON for every node, edge, tree that was deleted. So the resulting NexSON may have brok...
Modifies `nexson` and returns it in version 1.2.1 with any tree that does not match the ID removed. Note that this does not search through the NexSON for every node, edge, tree that was deleted. So the resulting NexSON may have broken references !
def get_tile_locations_by_gid(self, gid): """ Search map for tile locations by the GID Return (int, int, int) tuples, where the layer is index of the visible tile layers. Note: Not a fast operation. Cache results if used often. :param gid: GID to be searched for :rtyp...
Search map for tile locations by the GID Return (int, int, int) tuples, where the layer is index of the visible tile layers. Note: Not a fast operation. Cache results if used often. :param gid: GID to be searched for :rtype: generator of tile locations
def setup_daemon_log_file(cfstore): """ Attach file handler to RASH logger. :type cfstore: rash.config.ConfigStore """ level = loglevel(cfstore.daemon_log_level) handler = logging.FileHandler(filename=cfstore.daemon_log_path) handler.setLevel(level) logger.setLevel(level) logger.ad...
Attach file handler to RASH logger. :type cfstore: rash.config.ConfigStore
def p2sh_input(outpoint, stack_script, redeem_script, sequence=None): ''' OutPoint, str, str, int -> TxIn Create a signed legacy TxIn from a p2pkh prevout ''' if sequence is None: sequence = guess_sequence(redeem_script) stack_script = script_ser.serialize(stack_script) redeem_scrip...
OutPoint, str, str, int -> TxIn Create a signed legacy TxIn from a p2pkh prevout
def item_frequency(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots an item frequency of the sarray provided as input, and returns the resulting Plot object. The function supports SArrays with dtype str. Parameters ---------- sa : SArray The data t...
Plots an item frequency of the sarray provided as input, and returns the resulting Plot object. The function supports SArrays with dtype str. Parameters ---------- sa : SArray The data to get an item frequency for. Must have dtype str xlabel : str (optional) The text label for...
def get_auth_token(self, user_payload): """ Create a JWT authentication token from ``user_payload`` Args: user_payload(dict, required): A `dict` containing required information to create authentication token """ now = datetime.utcnow() payload...
Create a JWT authentication token from ``user_payload`` Args: user_payload(dict, required): A `dict` containing required information to create authentication token
def makeWidget(self, qscreen: QtGui.QScreen): # (re)create the widget, do the same for children # how children are placed on the parent widget, depends on the subclass self.window = self.ContainerWindow( self.signals, self.title, self.parent) # send to correct x-screen ...
TODO: activate after gpu-hopping has been debugged self.screenmenu = ScreenMenu(self.window) self.screenmenu.screen_1.triggered.connect(self.test_slot) self.screenmenu.screen_2.triggered.connect(self.test_slot)
def _map_exercise_row_to_dict(self, row): """ Convert dictionary keys from raw CSV Exercise format to ricecooker keys. """ row_cleaned = _clean_dict(row) license_id = row_cleaned[CONTENT_LICENSE_ID_KEY] if license_id: license_dict = dict( licen...
Convert dictionary keys from raw CSV Exercise format to ricecooker keys.
def next_generation(self, mut_rate=0, max_mut_amt=0, log_base=10): '''Generates the next population from a previously evaluated generation Args: mut_rate (float): mutation rate for new members (0.0 - 1.0) max_mut_amt (float): how much the member is allowed to mutate ...
Generates the next population from a previously evaluated generation Args: mut_rate (float): mutation rate for new members (0.0 - 1.0) max_mut_amt (float): how much the member is allowed to mutate (0.0 - 1.0, proportion change of mutated parameter) log_base (...
def write(self, transport, protocol, *data): """Generates and sends a command message unit. :param transport: An object implementing the `.Transport` interface. It is used by the protocol to send the message. :param protocol: An object implementing the `.Protocol` interface. ...
Generates and sends a command message unit. :param transport: An object implementing the `.Transport` interface. It is used by the protocol to send the message. :param protocol: An object implementing the `.Protocol` interface. :param data: The program data. :raises Attribu...
def execute(self, eopatch): """ Compute composite array merging temporal frames according to the compositing method :param eopatch: eopatch holding time-series :return: eopatch with composite image of time-series """ feature_type, feature_name = next(self.feature(eopatch...
Compute composite array merging temporal frames according to the compositing method :param eopatch: eopatch holding time-series :return: eopatch with composite image of time-series
def to_jsondict(self, encode_string=base64.b64encode): """ This method returns a JSON style dict to describe this object. The returned dict is compatible with json.dumps() and json.loads(). Suppose ClassName object inherits StringifyMixin. For an object like the following:: ...
This method returns a JSON style dict to describe this object. The returned dict is compatible with json.dumps() and json.loads(). Suppose ClassName object inherits StringifyMixin. For an object like the following:: ClassName(Param1=100, Param2=200) this method would prod...
def _create_latent_variables(self): """ Creates model latent variables Returns ---------- None (changes model attributes) """ self.latent_variables.add_z('Sigma^2 irregular', fam.Flat(transform='exp'), fam.Normal(0,3)) self.latent_variables.add_z('Constant', fa...
Creates model latent variables Returns ---------- None (changes model attributes)
def as_tensor_dict(self, padding_lengths: Dict[str, Dict[str, int]] = None) -> Dict[str, DataArray]: """ Pads each ``Field`` in this instance to the lengths given in ``padding_lengths`` (which is keyed by field name, then by padding key, the same as the return value in ...
Pads each ``Field`` in this instance to the lengths given in ``padding_lengths`` (which is keyed by field name, then by padding key, the same as the return value in :func:`get_padding_lengths`), returning a list of torch tensors for each field. If ``padding_lengths`` is omitted, we will call ``...
def dotilt(dec, inc, bed_az, bed_dip): """ Does a tilt correction on a direction (dec,inc) using bedding dip direction and bedding dip. Parameters ---------- dec : declination directions in degrees inc : inclination direction in degrees bed_az : bedding dip direction bed_dip : beddi...
Does a tilt correction on a direction (dec,inc) using bedding dip direction and bedding dip. Parameters ---------- dec : declination directions in degrees inc : inclination direction in degrees bed_az : bedding dip direction bed_dip : bedding dip Returns ------- dec,inc : a tup...
def on_directory_button_clicked(self): """Show a dialog to choose directory. .. versionadded: 3.3 """ # noinspection PyCallByClass,PyTypeChecker self.output_directory.setText(QFileDialog.getExistingDirectory( self, self.tr('Select download directory')))
Show a dialog to choose directory. .. versionadded: 3.3
def get_tu(source, lang='c', all_warnings=False, flags=None): """Obtain a translation unit from source and language. By default, the translation unit is created from source file "t.<ext>" where <ext> is the default file extension for the specified language. By default it is C, so "t.c" is the default f...
Obtain a translation unit from source and language. By default, the translation unit is created from source file "t.<ext>" where <ext> is the default file extension for the specified language. By default it is C, so "t.c" is the default file name. Supported languages are {c, cpp, objc}. all_warni...
def systemInformationType2bis(): """SYSTEM INFORMATION TYPE 2bis Section 9.1.33""" a = L2PseudoLength(l2pLength=0x15) b = TpPd(pd=0x6) c = MessageType(mesType=0x2) # 00000010 d = NeighbourCellsDescription() e = RachControlParameters() f = Si2bisRestOctets() packet = a / b / c / d / e / ...
SYSTEM INFORMATION TYPE 2bis Section 9.1.33
def changeset_info(changeset): """Return a dictionary with id, user, user_id, bounds, date of creation and all the tags of the changeset. Args: changeset: the XML string of the changeset. """ keys = [tag.attrib.get('k') for tag in changeset.getchildren()] keys += ['id', 'user', 'uid', '...
Return a dictionary with id, user, user_id, bounds, date of creation and all the tags of the changeset. Args: changeset: the XML string of the changeset.
def snapshot(name, suffix=None, connection=None, username=None, password=None): ''' Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: userna...
Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param passw...
def load_auth(configfile): """Get authentication data from the AUTH_CONF file.""" logging.debug('Loading habitica auth data from %s' % configfile) try: cf = open(configfile) except IOError: logging.error("Unable to find '%s'." % configfile) exit(1) config = configparser.Sa...
Get authentication data from the AUTH_CONF file.
def delete(self, name=None): "Delete the shelve data file." logger.info('clearing shelve data') self.close() for path in Path(self.create_path.parent, self.create_path.name), \ Path(self.create_path.parent, self.create_path.name + '.db'): logger.debug(f'clearing {...
Delete the shelve data file.
def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. ...
Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.
def plot_mask_cells(mask_cells, padding=16): """Plots cells with their true mask, predicted mask. Parameters ---------- mask_cells: list of tuples (`true_mask`, `predicted_mask`, `cell`) padding: int (default=16) Padding around mask to remove. """ fig, axes = plt.subplots(len(mask_c...
Plots cells with their true mask, predicted mask. Parameters ---------- mask_cells: list of tuples (`true_mask`, `predicted_mask`, `cell`) padding: int (default=16) Padding around mask to remove.
def setEditorData(self, spinBox, index): """Sets the data to be displayed and edited by the editor from the data model item specified by the model index. Args: spinBox (BigIntSpinbox): editor widget. index (QModelIndex): model data index. """ if index.isValid(): ...
Sets the data to be displayed and edited by the editor from the data model item specified by the model index. Args: spinBox (BigIntSpinbox): editor widget. index (QModelIndex): model data index.
def run(items, background=None): """Detect copy number variations from batched set of samples using GATK4 CNV calling. TODO: implement germline calling with DetermineGermlineContigPloidy and GermlineCNVCaller """ if not background: background = [] paired = vcfutils.get_paired(items + background) ...
Detect copy number variations from batched set of samples using GATK4 CNV calling. TODO: implement germline calling with DetermineGermlineContigPloidy and GermlineCNVCaller
def readSignal(self, chn, start=0, n=None): """ Returns the physical data of signal chn. When start and n is set, a subset is returned Parameters ---------- chn : int channel number start : int start pointer (default is 0) n : int ...
Returns the physical data of signal chn. When start and n is set, a subset is returned Parameters ---------- chn : int channel number start : int start pointer (default is 0) n : int length of data to read (default is None, by which the comple...
def to_json(self, path, root_array=True, mode=WRITE_MODE, compression=None): """ Saves the sequence to a json file. If root_array is True, then the sequence will be written to json with an array at the root. If it is False, then the sequence will be converted from a sequence of (Key, Val...
Saves the sequence to a json file. If root_array is True, then the sequence will be written to json with an array at the root. If it is False, then the sequence will be converted from a sequence of (Key, Value) pairs to a dictionary so that the json root is a dictionary. :param path: path to wr...
def handle_invocation(self, message): """ Passes the invocation request to the appropriate callback. """ req_id = message.request_id reg_id = message.registration_id if reg_id in self._registered_calls: handler = self._registered_calls[reg_id][REGISTERED_C...
Passes the invocation request to the appropriate callback.
def restore_db(release=None): """ Restores backup back to version, uses current version by default. """ assert "mysql_user" in env, "Missing mysqL_user in env" assert "mysql_password" in env, "Missing mysql_password in env" assert "mysql_host" in env, "Missing mysql_host in env" assert "mys...
Restores backup back to version, uses current version by default.
def pca(X, n_components=2, random_state=None): """Initialize an embedding using the top principal components. Parameters ---------- X: np.ndarray The data matrix. n_components: int The dimension of the embedding space. random_state: Union[int, RandomState] If the value...
Initialize an embedding using the top principal components. Parameters ---------- X: np.ndarray The data matrix. n_components: int The dimension of the embedding space. random_state: Union[int, RandomState] If the value is an int, random_state is the seed used by the rando...
def scourCoordinates(data, options, force_whitespace=False, control_points=[], flags=[]): """ Serializes coordinate data with some cleanups: - removes all trailing zeros after the decimal - integerize coordinates if possible - removes extraneous whitespace - adds space...
Serializes coordinate data with some cleanups: - removes all trailing zeros after the decimal - integerize coordinates if possible - removes extraneous whitespace - adds spaces between values in a subcommand if required (or if force_whitespace is True)
async def Claim(self, claims): ''' claims : typing.Sequence[~SingularClaim] Returns -> typing.Sequence[~ErrorResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='Singular', request='Claim', version=2, ...
claims : typing.Sequence[~SingularClaim] Returns -> typing.Sequence[~ErrorResult]
def index_search_document(self, *, index): """ Create or replace search document in named index. Checks the local cache to see if the document has changed, and if not aborts the update, else pushes to ES, and then resets the local cache. Cache timeout is set as "cache_expiry" ...
Create or replace search document in named index. Checks the local cache to see if the document has changed, and if not aborts the update, else pushes to ES, and then resets the local cache. Cache timeout is set as "cache_expiry" in the settings, and defaults to 60s.
def validate(self, raw_data, **kwargs): """Convert the raw_data to a float. """ try: converted_data = float(raw_data) super(FloatField, self).validate(converted_data, **kwargs) return raw_data except ValueError: raise ValidationException(s...
Convert the raw_data to a float.
def slideshow(self, **kwargs): """ Uses matplotlib to plot the evolution of the structural relaxation. Args: ax_list: List of axes. If None a new figure is produced. Returns: `matplotlib` figure """ for i, cycle in enumerate(self.cycles): ...
Uses matplotlib to plot the evolution of the structural relaxation. Args: ax_list: List of axes. If None a new figure is produced. Returns: `matplotlib` figure
async def connect(self): """Create connection pool asynchronously. """ self.pool = await aiopg.create_pool( loop=self.loop, timeout=self.timeout, database=self.database, **self.connect_params)
Create connection pool asynchronously.
def add_connector(self, connector_type, begin_x, begin_y, end_x, end_y): """Add a newly created connector shape to the end of this shape tree. *connector_type* is a member of the :ref:`MsoConnectorType` enumeration and the end-point values are specified as EMU values. The returned conne...
Add a newly created connector shape to the end of this shape tree. *connector_type* is a member of the :ref:`MsoConnectorType` enumeration and the end-point values are specified as EMU values. The returned connector is of type *connector_type* and has begin and end points as specified.
def _load_key(private_object): """ Loads a private key into a PrivateKey object :param private_object: An asn1crypto.keys.PrivateKeyInfo object :return: A PrivateKey object """ if libcrypto_version_info < (1,) and private_object.algorithm == 'dsa' and private_object.hash_algo ...
Loads a private key into a PrivateKey object :param private_object: An asn1crypto.keys.PrivateKeyInfo object :return: A PrivateKey object
def beds_to_boolean(beds, ref=None, beds_sorted=False, ref_sorted=False, **kwargs): """ Compare a list of bed files or BedTool objects to a reference bed file and create a boolean matrix where each row is an interval and each column is a 1 if that file has an interval that overlaps t...
Compare a list of bed files or BedTool objects to a reference bed file and create a boolean matrix where each row is an interval and each column is a 1 if that file has an interval that overlaps the row interval and a 0 otherwise. If no reference bed is provided, the provided bed files will be merged in...
def classifiers(self): """ Returns the list of base classifiers. :return: the classifier list :rtype: list """ objects = javabridge.get_env().get_object_array_elements( javabridge.call(self.jobject, "getClassifiers", "()[Lweka/classifiers/Classifier;")) ...
Returns the list of base classifiers. :return: the classifier list :rtype: list
def for_default_graph(*args, **kwargs): """Creates a bookkeeper for the default graph. Args: *args: Arguments to pass into Bookkeeper's constructor. **kwargs: Arguments to pass into Bookkeeper's constructor. Returns: A new Bookkeeper. Raises: ValueError: If args or kwargs are provided and the B...
Creates a bookkeeper for the default graph. Args: *args: Arguments to pass into Bookkeeper's constructor. **kwargs: Arguments to pass into Bookkeeper's constructor. Returns: A new Bookkeeper. Raises: ValueError: If args or kwargs are provided and the Bookkeeper already exists.
def multihistogram(args): """ %prog multihistogram *.histogram species Plot the histogram based on a set of K-mer hisotograms. The method is based on Star et al.'s method (Atlantic Cod genome paper). """ p = OptionParser(multihistogram.__doc__) p.add_option("--kmin", default=15, type="int",...
%prog multihistogram *.histogram species Plot the histogram based on a set of K-mer hisotograms. The method is based on Star et al.'s method (Atlantic Cod genome paper).
def eval_autoregressive(self, features=None, decode_length=50): """Autoregressive eval. Quadratic time in decode_length. Args: features: an map of string to `Tensor` decode_length: an integer. How many additional timesteps to decode. Returns: logits: `Tensor` losses: a dictio...
Autoregressive eval. Quadratic time in decode_length. Args: features: an map of string to `Tensor` decode_length: an integer. How many additional timesteps to decode. Returns: logits: `Tensor` losses: a dictionary: {loss-name (string): floating point `Scalar`}. Contains...
def get_simple_devices_info(self): """Get basic device info from Vera.""" j = self.data_request({'id': 'sdata'}).json() self.scenes = [] items = j.get('scenes') for item in items: self.scenes.append(VeraScene(item, self)) if j.get('temperature'): ...
Get basic device info from Vera.
def enqueue(self, name=None, action=None, method=None, wait_url=None, wait_url_method=None, workflow_sid=None, **kwargs): """ Create a <Enqueue> element :param name: Friendly name :param action: Action URL :param method: Action URL method :param wait_url:...
Create a <Enqueue> element :param name: Friendly name :param action: Action URL :param method: Action URL method :param wait_url: Wait URL :param wait_url_method: Wait URL method :param workflow_sid: TaskRouter Workflow SID :param kwargs: additional attributes ...
def enable_servicegroup_passive_svc_checks(self, servicegroup): """Enable passive service checks for a servicegroup Format of the line that triggers function call:: ENABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS;<servicegroup_name> :param servicegroup: servicegroup to enable :type serv...
Enable passive service checks for a servicegroup Format of the line that triggers function call:: ENABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS;<servicegroup_name> :param servicegroup: servicegroup to enable :type servicegroup: alignak.objects.servicegroup.Servicegroup :return: None
def create_random_ind_grow(self, depth=0): "Random individual using grow method" lst = [] self._depth = depth self._create_random_ind_grow(depth=depth, output=lst) return lst
Random individual using grow method
def rsa_check_base64_sign_str(self, cipher, sign, b64=True): """ 验证服务端数据 ``rsa`` 签名 """ with open(self.key_file) as fp: key_ = RSA.importKey(fp.read()) v = pkcs.new(key_) sign = base64.b64decode(sign) if b64 else sign cipher = helper.t...
验证服务端数据 ``rsa`` 签名
def stepfiles_iterator(path_prefix, wait_minutes=0, min_steps=0, path_suffix=".index", sleep_sec=10): """Continuously yield new files with steps in filename as they appear. This is useful for checkpoint files or other files whose names differ just in an integer marking the number of steps ...
Continuously yield new files with steps in filename as they appear. This is useful for checkpoint files or other files whose names differ just in an integer marking the number of steps and match the wildcard path_prefix + "*-[0-9]*" + path_suffix. Unlike `tf.contrib.training.checkpoints_iterator`, this implem...
def load_external_types(self, path): """ Given a path to a python package or module, load that module, search for all defined variables inside of it that do not start with _ or __ and inject them into the type system. If any of the types cannot be injected, silently ignore them unless v...
Given a path to a python package or module, load that module, search for all defined variables inside of it that do not start with _ or __ and inject them into the type system. If any of the types cannot be injected, silently ignore them unless verbose is True. If path points to a module it sh...
def add(self,dimlist,dimvalues): ''' add dimensions :parameter dimlist: list of dimensions :parameter dimvalues: list of values for dimlist ''' for i,d in enumerate(dimlist): self[d] = dimvalues[i] self.set_ndims()
add dimensions :parameter dimlist: list of dimensions :parameter dimvalues: list of values for dimlist
def get_safe_struct(self): """ Describes a structure inside tile folder of ESA product .SAFE structure. :return: nested dictionaries representing .SAFE structure :rtype: dict """ # pylint: disable=too-many-branches safe = {} main_folder = self.get_main_fo...
Describes a structure inside tile folder of ESA product .SAFE structure. :return: nested dictionaries representing .SAFE structure :rtype: dict
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'tense') and self.tense is not None: _dict['tense'] = self.tense return _d...
Return a json dictionary representing this model.
def _events(self, using_url, filters=None, limit=None): """ A long-polling method that queries Syncthing for events.. Args: using_url (str): REST HTTP endpoint filters (List[str]): Creates an "event group" in Syncthing to only receive events that ...
A long-polling method that queries Syncthing for events.. Args: using_url (str): REST HTTP endpoint filters (List[str]): Creates an "event group" in Syncthing to only receive events that have been subscribed to. limit (int): The number of ...
def sep_dist_clay(ConcClay, material): """Return the separation distance between clay particles.""" return ((material.Density/ConcClay)*((np.pi * material.Diameter ** 3)/6))**(1/3)
Return the separation distance between clay particles.
def get_edges(self, src_ids=[], dst_ids=[], fields={}, format='sframe'): """ get_edges(self, src_ids=list(), dst_ids=list(), fields={}, format='sframe') Return a collection of edges and their attributes. This function is used to find edges by vertex IDs, filter on edge attributes, or lis...
get_edges(self, src_ids=list(), dst_ids=list(), fields={}, format='sframe') Return a collection of edges and their attributes. This function is used to find edges by vertex IDs, filter on edge attributes, or list in-out neighbors of vertex sets. Parameters ---------- src...
def get_query_uri(self): """ Return the uri used for queries on time series data. """ # Query URI has extra path we don't want so strip it off here query_uri = self.service.settings.data['query']['uri'] query_uri = urlparse(query_uri) return query_uri.scheme + ':/...
Return the uri used for queries on time series data.
def connectTo( self, node, cls = None ): """ Creates a connection between this node and the inputed node. :param node | <XNode> cls | <subclass of XNodeConnection> || None :return <XNodeConnection> """ if ( not node ): ...
Creates a connection between this node and the inputed node. :param node | <XNode> cls | <subclass of XNodeConnection> || None :return <XNodeConnection>
def get(self, name: str, default: Optional[Any]=None) -> Any: """Get a named attribute of this instance, or return the default.""" return self.__dict__.get(name, default)
Get a named attribute of this instance, or return the default.
def mark(self, value=1): """Record an event with the meter. By default it will record one event. :param value: number of event to record """ self.counter += value self.m1_rate.update(value) self.m5_rate.update(value) self.m15_rate.update(value)
Record an event with the meter. By default it will record one event. :param value: number of event to record
def _get_ssl(self): """Get an SMTP session with SSL.""" return smtplib.SMTP_SSL( self.server, self.port, context=ssl.create_default_context() )
Get an SMTP session with SSL.
def rand_imancon_NOTWORKING(x, rho): """Iman-Conover Method to generate random ordinal variables. Implementation from Mildenhall (2005) that is NOT working. x : ndarray <obs x cols> matrix with "cols" ordinal variables that are uncorrelated. rho : ndarray Spearman Rank Corr...
Iman-Conover Method to generate random ordinal variables. Implementation from Mildenhall (2005) that is NOT working. x : ndarray <obs x cols> matrix with "cols" ordinal variables that are uncorrelated. rho : ndarray Spearman Rank Correlation Matrix Links * Iman, R.L., ...
def _get_application_tags(self): """Adds tags to the stack if this resource is using the serverless app repo """ application_tags = {} if isinstance(self.Location, dict): if (self.APPLICATION_ID_KEY in self.Location.keys() and self.Location[self.APPLICATIO...
Adds tags to the stack if this resource is using the serverless app repo
def show(self): """Show state.""" msg = '' if self._process: msg += 'server pid: {}\n'.format(self._process.pid) msg += 'server poll: {}\n'.format(self._process.poll()) msg += 'server running: {}\n'.format(self.running()) msg += 'server port: {}\n'.format(...
Show state.
def cdl_addmon(self, source_url, save_path = '/', timeout = 3600): ''' Usage: cdl_addmon <source_url> [save_path] [timeout] - add an offline (cloud) download task and monitor the download progress source_url - the URL to download file from. save_path - path on PCS to save file to. default is to save to root direc...
Usage: cdl_addmon <source_url> [save_path] [timeout] - add an offline (cloud) download task and monitor the download progress source_url - the URL to download file from. save_path - path on PCS to save file to. default is to save to root directory '/'. timeout - timeout in seconds. default is 3600 seconds.
def parse_strike_dip(strike, dip): """ Parses strings of strike and dip and returns strike and dip measurements following the right-hand-rule. Dip directions are parsed, and if the measurement does not follow the right-hand-rule, the opposite end of the strike measurement is returned. Accepts ...
Parses strings of strike and dip and returns strike and dip measurements following the right-hand-rule. Dip directions are parsed, and if the measurement does not follow the right-hand-rule, the opposite end of the strike measurement is returned. Accepts either quadrant-formatted or azimuth-formatted ...
def parseData(self, data, host, port, options): ''' This function will parse the raw syslog data, dynamically create the topic according to the topic specified by the user (if specified) and decide whether to send the syslog data as an event on the master bus, based on the constr...
This function will parse the raw syslog data, dynamically create the topic according to the topic specified by the user (if specified) and decide whether to send the syslog data as an event on the master bus, based on the constraints given by the user. :param data: The raw syslog event ...
def _pack_prms(): """if you introduce new 'save-able' parameter dictionaries, then you have to include them here""" config_dict = { "Paths": prms.Paths.to_dict(), "FileNames": prms.FileNames.to_dict(), "Db": prms.Db.to_dict(), "DbCols": prms.DbCols.to_dict(), "DataSe...
if you introduce new 'save-able' parameter dictionaries, then you have to include them here
def setHorCrossPlotAutoRangeOn(self, axisNumber): """ Sets the horizontal cross-hair plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.horCrossPlotRange...
Sets the horizontal cross-hair plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
def node_contents_str(tag): """ Return the contents of a tag, including it's children, as a string. Does not include the root/parent of the tag. """ if not tag: return None tag_string = '' for child_tag in tag.children: if isinstance(child_tag, Comment): # Beautif...
Return the contents of a tag, including it's children, as a string. Does not include the root/parent of the tag.
def update_limits(self): """ Poll 'Service Limits' check results from Trusted Advisor, if possible. Iterate over all :py:class:`~.AwsLimit` objects for the given services and update their limits from TA if present in TA checks. :param services: dict of service name (string) to ...
Poll 'Service Limits' check results from Trusted Advisor, if possible. Iterate over all :py:class:`~.AwsLimit` objects for the given services and update their limits from TA if present in TA checks. :param services: dict of service name (string) to :py:class:`~._AwsService` objects ...
def parse_int(str_num): """ Given an integer number, return its value, or None if it could not be parsed. Allowed formats: DECIMAL, HEXA (0xnnn, $nnnn or nnnnh) :param str_num: (string) the number to be parsed :return: an integer number or None if it could not be parsedd """ str_num = (str_n...
Given an integer number, return its value, or None if it could not be parsed. Allowed formats: DECIMAL, HEXA (0xnnn, $nnnn or nnnnh) :param str_num: (string) the number to be parsed :return: an integer number or None if it could not be parsedd
def modify_job(self, name, schedule, persist=True): ''' Modify a job in the scheduler. Ignores jobs from pillar ''' # ensure job exists, then replace it if name in self.opts['schedule']: self.delete_job(name, persist) elif name in self._get_schedule(include_op...
Modify a job in the scheduler. Ignores jobs from pillar