code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def generate_phase_2(phase_1, dim = 40): """ The second step in creating datapoints in the Poirazi & Mel model. This takes a phase 1 vector, and creates a phase 2 vector where each point is the product of four elements of the phase 1 vector, randomly drawn with replacement. """ phase_2 = [] for i in ran...
The second step in creating datapoints in the Poirazi & Mel model. This takes a phase 1 vector, and creates a phase 2 vector where each point is the product of four elements of the phase 1 vector, randomly drawn with replacement.
def create_endpoints_csv_file(self, timeout=-1): """ Creates an endpoints CSV file for a SAN. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its compl...
Creates an endpoints CSV file for a SAN. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: dict: Endpoint CSV File Response...
def add_pic(self, id_, name, desc, rId, x, y, cx, cy): """ Append a ``<p:pic>`` shape to the group/shapetree having properties as specified in call. """ pic = CT_Picture.new_pic(id_, name, desc, rId, x, y, cx, cy) self.insert_element_before(pic, 'p:extLst') return...
Append a ``<p:pic>`` shape to the group/shapetree having properties as specified in call.
def getModelIDFromParamsHash(self, paramsHash): """ Return the modelID of the model with the given paramsHash, or None if not found. Parameters: --------------------------------------------------------------------- paramsHash: paramsHash to look for retval: modelId, or None if not found ...
Return the modelID of the model with the given paramsHash, or None if not found. Parameters: --------------------------------------------------------------------- paramsHash: paramsHash to look for retval: modelId, or None if not found
def add_ip_address(self, ip_address, sync=True): """ add a ip address to this OS instance. :param ip_address: the ip address to add on this OS instance :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the subnet object on list to be added on n...
add a ip address to this OS instance. :param ip_address: the ip address to add on this OS instance :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the subnet object on list to be added on next save(). :return:
def _maximization_step(X, posteriors): """ Update class parameters as below: priors: P(w_i) = sum_x P(w_i | x) ==> Then normalize to get in [0,1] Class means: center_w_i = sum_x P(w_i|x)*x / sum_i sum_x P(w_i|x) """ ### Prior probabilities or class weights sum_post_proba = np.sum...
Update class parameters as below: priors: P(w_i) = sum_x P(w_i | x) ==> Then normalize to get in [0,1] Class means: center_w_i = sum_x P(w_i|x)*x / sum_i sum_x P(w_i|x)
def set_stylesheet(self, subreddit, stylesheet): """Set stylesheet for the given subreddit. :returns: The json response from the server. """ subreddit = six.text_type(subreddit) data = {'r': subreddit, 'stylesheet_contents': stylesheet, 'op': 'sa...
Set stylesheet for the given subreddit. :returns: The json response from the server.
def keys(self): """ Access the keys :returns: twilio.rest.preview.deployed_devices.fleet.key.KeyList :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyList """ if self._keys is None: self._keys = KeyList(self._version, fleet_sid=self._solution['sid'],...
Access the keys :returns: twilio.rest.preview.deployed_devices.fleet.key.KeyList :rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyList
def validate_basic_smoother_resid(): """Compare residuals.""" x, y = sort_data(*smoother_friedman82.build_sample_smoother_problem_friedman82()) plt.figure() for span in smoother.DEFAULT_SPANS: my_smoother = smoother.perform_smooth(x, y, span) _friedman_smooth, resids = run_friedman_smoot...
Compare residuals.
def read_field_report(path, data_flag = "*DATA", meta_data_flag = "*METADATA"): """ Reads a field output report. """ text = open(path).read() mdpos = text.find(meta_data_flag) dpos = text.find(data_flag) mdata = io.StringIO( "\n".join(text[mdpos:dpos].split("\n")[1:])) data = io.StringIO( "\n".join(text...
Reads a field output report.
def matrices_compliance(dsm, complete_mediation_matrix): """ Check if matrix and its mediation matrix are compliant. Args: dsm (:class:`DesignStructureMatrix`): the DSM to check. complete_mediation_matrix (list of list of int): 2-dim array Returns: b...
Check if matrix and its mediation matrix are compliant. Args: dsm (:class:`DesignStructureMatrix`): the DSM to check. complete_mediation_matrix (list of list of int): 2-dim array Returns: bool: True if compliant, else False
def from_mult_iters(cls, name=None, idx=None, **kwargs): """Load values from multiple iters Parameters ---------- name : string, default None Name of the data set. If None (default), the name will be set to ``'table'``. idx: string, default None ...
Load values from multiple iters Parameters ---------- name : string, default None Name of the data set. If None (default), the name will be set to ``'table'``. idx: string, default None Iterable to use for the data index **kwargs : dict of ite...
def asDateTime(self): """Create :py:class:`datetime.datetime` object from a |ASN.1| object. Returns ------- : new instance of :py:class:`datetime.datetime` object """ text = str(self) if text.endswith('Z'): tzinfo = TimeMixIn.UTC ...
Create :py:class:`datetime.datetime` object from a |ASN.1| object. Returns ------- : new instance of :py:class:`datetime.datetime` object
def extract_schemas_from_file(source_path): """Extract schemas from 'source_path'. :returns: a list of ViewSchema objects on success, None if no schemas could be extracted. """ logging.info("Extracting schemas from %s", source_path) try: with open(source_path, 'r') as source_file: ...
Extract schemas from 'source_path'. :returns: a list of ViewSchema objects on success, None if no schemas could be extracted.
def local_bind_hosts(self): """ Return a list containing the IP addresses listening for the tunnels """ self._check_is_started() return [_server.local_host for _server in self._server_list if _server.local_host is not None]
Return a list containing the IP addresses listening for the tunnels
def fill_from_simbad (self, ident, debug=False): """Fill in astrometric information using the Simbad web service. This uses the CDS Simbad web service to look up astrometric information for the source name *ident* and fills in attributes appropriately. Values from Simbad are not always ...
Fill in astrometric information using the Simbad web service. This uses the CDS Simbad web service to look up astrometric information for the source name *ident* and fills in attributes appropriately. Values from Simbad are not always reliable. Returns *self*.
def __calculate_order(self, node_dict): """ Determine a valid ordering of the nodes in which a node is not called before all of it's dependencies. Raise an error if there is a cycle, or nodes are missing. """ if len(node_dict.keys()) != len(set(node_dict.keys())): ra...
Determine a valid ordering of the nodes in which a node is not called before all of it's dependencies. Raise an error if there is a cycle, or nodes are missing.
def dict_sort(d, k): """ Sort a dictionary list by key :param d: dictionary list :param k: key :return: sorted dictionary list """ return sorted(d.copy(), key=lambda i: i[k])
Sort a dictionary list by key :param d: dictionary list :param k: key :return: sorted dictionary list
def remove_backup(name): ''' Remove an IIS Configuration backup from the System. .. versionadded:: 2017.7.0 Args: name (str): The name of the backup to remove Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.r...
Remove an IIS Configuration backup from the System. .. versionadded:: 2017.7.0 Args: name (str): The name of the backup to remove Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.remove_backup backup_20170209
def to_segwizard(segs, target, header=True, coltype=LIGOTimeGPS): """Write the given `SegmentList` to a file in SegWizard format. Parameters ---------- segs : :class:`~gwpy.segments.SegmentList` The list of segments to write. target : `file`, `str` An open file, or file path, to wh...
Write the given `SegmentList` to a file in SegWizard format. Parameters ---------- segs : :class:`~gwpy.segments.SegmentList` The list of segments to write. target : `file`, `str` An open file, or file path, to which to write. header : `bool`, optional Print a column heade...
def map(func, items, pool_size=10): """a parallelized work-alike to the built-in ``map`` function this function works by creating an :class:`OrderedPool` and placing all the arguments in :meth:`put<OrderedPool.put>` calls, then yielding items produced by the pool's :meth:`get<OrderedPool.get>` method. ...
a parallelized work-alike to the built-in ``map`` function this function works by creating an :class:`OrderedPool` and placing all the arguments in :meth:`put<OrderedPool.put>` calls, then yielding items produced by the pool's :meth:`get<OrderedPool.get>` method. :param func: the mapper function to us...
def cmd(send, msg, args): """Handles quotes. Syntax: {command} <number|nick>, !quote --add <quote> --nick <nick> (--approve), !quote --list, !quote --delete <number>, !quote --edit <number> <quote> --nick <nick> !quote --search (--offset <num>) <number> """ session = args['db'] parser = argument...
Handles quotes. Syntax: {command} <number|nick>, !quote --add <quote> --nick <nick> (--approve), !quote --list, !quote --delete <number>, !quote --edit <number> <quote> --nick <nick> !quote --search (--offset <num>) <number>
def _convert_vpathlist(input_obj): """convert from 'list' or 'tuple' object to pgmagick.VPathList. :type input_obj: list or tuple """ vpl = pgmagick.VPathList() for obj in input_obj: # FIXME obj = pgmagick.PathMovetoAbs(pgmagick.Coordinate(obj[0], obj[1])) vpl.append(obj) ...
convert from 'list' or 'tuple' object to pgmagick.VPathList. :type input_obj: list or tuple
def _ReloadArtifacts(self): """Load artifacts from all sources.""" self._artifacts = {} self._LoadArtifactsFromFiles(self._sources.GetAllFiles()) self.ReloadDatastoreArtifacts()
Load artifacts from all sources.
def aggregate(self, key, aggregate, start=None, end=None, namespace=None, percentile=None): """Get an aggregate of all gauge data stored in the specified date range""" return self.make_context(key=key, aggregate=aggregate, start=start, end=end, ...
Get an aggregate of all gauge data stored in the specified date range
def reprovision(vm, image, key='uuid'): ''' Reprovision a vm vm : string vm to be reprovisioned image : string uuid of new image key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.reprovision 18...
Reprovision a vm vm : string vm to be reprovisioned image : string uuid of new image key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.reprovision 186da9ab-7392-4f55-91a5-b8f1fe770543 c02a2044-c1bd-11e...
def refresh_access_token(self, refresh_token): ''' Refreshes the current access token. Gets a new access token, updates client auth and returns it. Args: refresh_token (str): Refresh token to use Returns: The new access token ''' request = ...
Refreshes the current access token. Gets a new access token, updates client auth and returns it. Args: refresh_token (str): Refresh token to use Returns: The new access token
def ms_bot_framework(self) -> list: """Returns list of MS Bot Framework compatible states of the RichMessage instance nested controls. Returns: ms_bf_controls: MS Bot Framework representation of RichMessage instance nested controls. """ ms_bf_controls...
Returns list of MS Bot Framework compatible states of the RichMessage instance nested controls. Returns: ms_bf_controls: MS Bot Framework representation of RichMessage instance nested controls.
def _get_file_handler(package_data_spec, data_files_spec): """Get a package_data and data_files handler command. """ class FileHandler(BaseCommand): def run(self): package_data = self.distribution.package_data package_spec = package_data_spec or dict() for (key,...
Get a package_data and data_files handler command.
def write_collided_alias(collided_alias_dict): """ Write the collided aliases string into the collided alias file. """ # w+ creates the alias config file if it does not exist open_mode = 'r+' if os.path.exists(GLOBAL_COLLIDED_ALIAS_PATH) else 'w+' with open(GLOBAL_COLLIDE...
Write the collided aliases string into the collided alias file.
def setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items", predictionCol="prediction", numPartitions=None): """ setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items", \ predictionCol="prediction", numPartitions=None) """ kwa...
setParams(self, minSupport=0.3, minConfidence=0.8, itemsCol="items", \ predictionCol="prediction", numPartitions=None)
def decompress(data, format=FORMAT_AUTO, memlimit=None, filters=None): """Decompress a block of data. Refer to LZMADecompressor's docstring for a description of the optional arguments *format*, *check* and *filters*. For incremental decompression, use a LZMADecompressor object instead. """ res...
Decompress a block of data. Refer to LZMADecompressor's docstring for a description of the optional arguments *format*, *check* and *filters*. For incremental decompression, use a LZMADecompressor object instead.
def store(self, moments): """ Store object X with weight w """ if len(self.storage) == self.nsave: # merge if we must # print 'must merge' self.storage[-1].combine(moments, mean_free=self.remove_mean) else: # append otherwise # print 'append' ...
Store object X with weight w
def get_new_project_name(self, project_name): """ Return a unique project name for the copy. :param project_name: str: name of project we will copy :return: str """ timestamp_str = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M') return "{} {}".format(project...
Return a unique project name for the copy. :param project_name: str: name of project we will copy :return: str
def addAttachment(self, oid, file_path): """ Adds an attachment to a feature service Input: oid - string - OBJECTID value to add attachment to file_path - string - path to file Output: JSON Repsonse """ if self.hasAttachments == T...
Adds an attachment to a feature service Input: oid - string - OBJECTID value to add attachment to file_path - string - path to file Output: JSON Repsonse
def get_cgroup_item(self, key): """ Returns the value for a given cgroup entry. A list is returned when multiple values are set. """ value = _lxc.Container.get_cgroup_item(self, key) if value is False: return False else: return val...
Returns the value for a given cgroup entry. A list is returned when multiple values are set.
def get_resource_agent_assignment_session_for_bin(self, bin_id): """Gets a resource agent session for the given bin. arg: bin_id (osid.id.Id): the ``Id`` of the bin return: (osid.resource.ResourceAgentAssignmentSession) - a ``ResourceAgentAssignmentSession`` raise: N...
Gets a resource agent session for the given bin. arg: bin_id (osid.id.Id): the ``Id`` of the bin return: (osid.resource.ResourceAgentAssignmentSession) - a ``ResourceAgentAssignmentSession`` raise: NotFound - ``bin_id`` not found raise: NullArgument - ``bin_id`` is ...
def _ensure_coroutine_function(func): """Return a coroutine function. func: either a coroutine function or a regular function Note a coroutine function is not a coroutine! """ if asyncio.iscoroutinefunction(func): return func else: @asyncio.coroutine def coroutine_funct...
Return a coroutine function. func: either a coroutine function or a regular function Note a coroutine function is not a coroutine!
def run( self, server=None, host=None, port=None, enable_pretty_logging=True ): """ 运行 WeRoBot。 :param server: 传递给 Bottle 框架 run 方法的参数,详情见\ `bottle 文档 <https://bottlepy.org/docs/dev/deployment.html#switching-the-server-backend>`_ :param host: 运行时绑定的主机地址 :para...
运行 WeRoBot。 :param server: 传递给 Bottle 框架 run 方法的参数,详情见\ `bottle 文档 <https://bottlepy.org/docs/dev/deployment.html#switching-the-server-backend>`_ :param host: 运行时绑定的主机地址 :param port: 运行时绑定的主机端口 :param enable_pretty_logging: 是否开启 log 的输出格式优化
def QA_fetch_get_stock_block(ip=None, port=None): '板块数据' ip, port = get_mainmarket_ip(ip, port) api = TdxHq_API() with api.connect(ip, port): data = pd.concat([api.to_df(api.get_and_parse_block_info("block_gn.dat")).assign(type='gn'), api.to_df(api.get_and_parse_block_...
板块数据
def MaskSolveSlow(A, b, w=5, progress=True, niter=None): ''' Identical to `MaskSolve`, but computes the solution the brute-force way. ''' # Number of data points N = b.shape[0] # How many iterations? Default is to go through # the entire dataset if niter is None: ...
Identical to `MaskSolve`, but computes the solution the brute-force way.
def snip(tag="",start=-2,write_date=True): """ This function records a previously execute notebook cell into a file (default: ipython_history.py) a tag can be added to sort the cell `start` defines which cell in the history to record. Default is -2, ie. the one executed previously to the ...
This function records a previously execute notebook cell into a file (default: ipython_history.py) a tag can be added to sort the cell `start` defines which cell in the history to record. Default is -2, ie. the one executed previously to the current one.
def remove_class(cls, *args): """Remove classes from the group. Parameters ---------- *args : `type` Classes to remove. """ for cls2 in args: try: del cls.classes[cls2.__name__] except KeyError: pass
Remove classes from the group. Parameters ---------- *args : `type` Classes to remove.
def asn1_generaltime_to_seconds(timestr): """The given string has one of the following formats YYYYMMDDhhmmssZ YYYYMMDDhhmmss+hhmm YYYYMMDDhhmmss-hhmm @return: a datetime object or None on error """ res = None timeformat = "%Y%m%d%H%M%S" try: res = datetime.strptime(timestr, ...
The given string has one of the following formats YYYYMMDDhhmmssZ YYYYMMDDhhmmss+hhmm YYYYMMDDhhmmss-hhmm @return: a datetime object or None on error
def set_remote_config(experiment_config, port, config_file_name): '''Call setClusterMetadata to pass trial''' #set machine_list request_data = dict() request_data['machine_list'] = experiment_config['machineList'] if request_data['machine_list']: for i in range(len(request_data['machine_list...
Call setClusterMetadata to pass trial
def get_ranking(self, alt): """ Description: Returns the ranking of a given alternative in the computed aggregate ranking. An error is thrown if the alternative does not exist. The ranking is the index in the aggregate ranking, which is 0-indexed. ...
Description: Returns the ranking of a given alternative in the computed aggregate ranking. An error is thrown if the alternative does not exist. The ranking is the index in the aggregate ranking, which is 0-indexed. Parameters: alt: the key tha...
def SaltAndPepper(p=0, per_channel=False, name=None, deterministic=False, random_state=None): """ Adds salt and pepper noise to an image, i.e. some white-ish and black-ish pixels. dtype support:: See ``imgaug.augmenters.arithmetic.ReplaceElementwise``. Parameters ---------- p : float ...
Adds salt and pepper noise to an image, i.e. some white-ish and black-ish pixels. dtype support:: See ``imgaug.augmenters.arithmetic.ReplaceElementwise``. Parameters ---------- p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional Probability ...
def next_page(self): """ Fetches next result set. :return: VolumeCollection object. """ for link in self.links: if link.next: return self._load(link.next) raise PaginationError('No more entries.')
Fetches next result set. :return: VolumeCollection object.
def _is_not_archived(sysmeta_pyxb): """Assert that ``sysmeta_pyxb`` does not have have the archived flag set.""" if _is_archived(sysmeta_pyxb): raise d1_common.types.exceptions.InvalidSystemMetadata( 0, 'Archived flag was set. A new object created via create() or update() ' ...
Assert that ``sysmeta_pyxb`` does not have have the archived flag set.
def write_event(self, *args): """ Write an event record:: writer.write_event(datetime.time(12, 34, 56), 'PEV') # -> B123456PEV writer.write_event(datetime.time(12, 34, 56), 'PEV', 'Some Text') # -> B123456PEVSome Text writer.write_event('PEV...
Write an event record:: writer.write_event(datetime.time(12, 34, 56), 'PEV') # -> B123456PEV writer.write_event(datetime.time(12, 34, 56), 'PEV', 'Some Text') # -> B123456PEVSome Text writer.write_event('PEV') # uses utcnow() # -> B121503PEV ...
def needs_distribute_ready(self): '''Determine whether or not we need to redistribute the ready state''' # Try to pre-empty starvation by comparing current RDY against # the last value sent. alive = [c for c in self.connections() if c.alive()] if any(c.ready <= (c.last_ready_sent...
Determine whether or not we need to redistribute the ready state
def tear_down(self): """Tear down the virtual box machine """ if not self.browser_config.get('terminate'): self.warning_log("Skipping terminate") return self.info_log("Tearing down") if self.browser_config.get('platform').lower() == 'linux': ...
Tear down the virtual box machine
def Sens_m_sample(poly, dist, samples, rule="R"): """ First order sensitivity indices estimated using Saltelli's method. Args: poly (chaospy.Poly): If provided, evaluated samples through polynomials before returned. dist (chaopy.Dist): distribution to sample from. ...
First order sensitivity indices estimated using Saltelli's method. Args: poly (chaospy.Poly): If provided, evaluated samples through polynomials before returned. dist (chaopy.Dist): distribution to sample from. samples (int): The number of samples to draw...
def today(boo): """ Return today's date as either a String or a Number, as specified by the User. Args: boo: if true, function returns Number (20151230); if false, returns String ("2015-12-30") Returns: either a Number or a string, dependent upon the user's input """ tod = datetime.strptime(datetim...
Return today's date as either a String or a Number, as specified by the User. Args: boo: if true, function returns Number (20151230); if false, returns String ("2015-12-30") Returns: either a Number or a string, dependent upon the user's input
def maximum(self, node): """ find the max node when node regard as a root node :param node: :return: max node """ temp_node = node while temp_node.right is not None: temp_node = temp_node.right return temp_node
find the max node when node regard as a root node :param node: :return: max node
def _get_values(self, data_blob, dtype_enum, shape_string): """Obtains values for histogram data given blob and dtype enum. Args: data_blob: The blob obtained from the database. dtype_enum: The enum representing the dtype. shape_string: A comma-separated string of numbers denoting shape. R...
Obtains values for histogram data given blob and dtype enum. Args: data_blob: The blob obtained from the database. dtype_enum: The enum representing the dtype. shape_string: A comma-separated string of numbers denoting shape. Returns: The histogram values as a list served to the frontend...
def user(self, obj, with_user_activity=False, follow_flag=None, **kwargs): """Create a stream of the most recent actions by objects that the user is following.""" q = Q() qs = self.public() if not obj: return qs.none() check(obj) if with_user_activity: ...
Create a stream of the most recent actions by objects that the user is following.
def add_parameter_dd(self, dag_tag, node_dict): """ helper function for adding parameters in condition Parameters --------------- dag_tag: etree SubElement the DAG tag is contained in this subelement node_dict: dictionary the decision ...
helper function for adding parameters in condition Parameters --------------- dag_tag: etree SubElement the DAG tag is contained in this subelement node_dict: dictionary the decision diagram dictionary Return --------------- N...
def format_extension(self): """The format extension of asset. Example:: >>> attrs = AssetAttributes(environment, 'js/models.js.coffee') >>> attrs.format_extension '.js' >>> attrs = AssetAttributes(environment, 'js/lib/external.min.js.coffee') ...
The format extension of asset. Example:: >>> attrs = AssetAttributes(environment, 'js/models.js.coffee') >>> attrs.format_extension '.js' >>> attrs = AssetAttributes(environment, 'js/lib/external.min.js.coffee') >>> attrs.format_extension ...
def setParts( self, parts ): """ Sets the path for this edit widget by providing the parts to the path. :param parts | [<str>, ..] """ self.setText(self.separator().join(map(str, parts)))
Sets the path for this edit widget by providing the parts to the path. :param parts | [<str>, ..]
def parse_string_descriptor(string_desc): """Parse a string descriptor of a streamer into a DataStreamer object. Args: string_desc (str): The string descriptor that we wish to parse. Returns: DataStreamer: A DataStreamer object representing the streamer. """ if not isinstance(stri...
Parse a string descriptor of a streamer into a DataStreamer object. Args: string_desc (str): The string descriptor that we wish to parse. Returns: DataStreamer: A DataStreamer object representing the streamer.
def process(self, index=None): """ This will completely process a directory of elevation tiles (as supplied in the constructor). Both phases of the calculation, the single tile and edge resolution phases are run. Parameters ----------- index : int/slice (optional...
This will completely process a directory of elevation tiles (as supplied in the constructor). Both phases of the calculation, the single tile and edge resolution phases are run. Parameters ----------- index : int/slice (optional) Default None - processes all tiles in...
def models_to_table(obj, params=True): r""" Converts a ModelsDict object to a ReST compatible table Parameters ---------- obj : OpenPNM object Any object that has a ``models`` attribute params : boolean Indicates whether or not to include a list of parameter values in t...
r""" Converts a ModelsDict object to a ReST compatible table Parameters ---------- obj : OpenPNM object Any object that has a ``models`` attribute params : boolean Indicates whether or not to include a list of parameter values in the table. Set to False for just a list of ...
def van_image_enc_2d(x, first_depth, reuse=False, hparams=None): """The image encoder for the VAN. Similar architecture as Ruben's paper (http://proceedings.mlr.press/v70/villegas17a/villegas17a.pdf). Args: x: The image to encode. first_depth: The depth of the first layer. Depth is increased in subseq...
The image encoder for the VAN. Similar architecture as Ruben's paper (http://proceedings.mlr.press/v70/villegas17a/villegas17a.pdf). Args: x: The image to encode. first_depth: The depth of the first layer. Depth is increased in subsequent layers. reuse: To reuse in variable scope or not. h...
def adjust_frame(self, pos, absolute_pos): """Adjust stack frame by pos positions. If absolute_pos then pos is an absolute number. Otherwise it is a relative number. A negative number indexes from the other end.""" if not self.curframe: Mmsg.errmsg(self, "No stack.") ...
Adjust stack frame by pos positions. If absolute_pos then pos is an absolute number. Otherwise it is a relative number. A negative number indexes from the other end.
def _lookup_online(word): """Look up word on diki.pl. Parameters ---------- word : str Word too look up. Returns ------- str website HTML content. """ URL = "https://www.diki.pl/{word}" HEADERS = { "User-Agent": ( "Mozilla/5.0 (compatible, MS...
Look up word on diki.pl. Parameters ---------- word : str Word too look up. Returns ------- str website HTML content.
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0): '''Pure python and therefore slow version of the standard library isclose. Works on older versions of python though! Hasn't been unit tested, but has been tested. manual unit testing: from math import isclose as isclose2 from random imp...
Pure python and therefore slow version of the standard library isclose. Works on older versions of python though! Hasn't been unit tested, but has been tested. manual unit testing: from math import isclose as isclose2 from random import uniform for i in range(10000000): a =...
def create_runtime(self, env, # type: MutableMapping[Text, Text] runtime_context # type: RuntimeContext ): # type: (...) -> Tuple[List, Optional[Text]] """ Returns the Singularity runtime list of commands and options.""" an...
Returns the Singularity runtime list of commands and options.
def _iter_enum_member_values(eid, bitmask): """Iterate member values with given bitmask inside the enum Note that `DEFMASK` can either indicate end-of-values or a valid value. Iterate serials to tell apart. """ value = idaapi.get_first_enum_member(eid, bitmask) yield value while value != D...
Iterate member values with given bitmask inside the enum Note that `DEFMASK` can either indicate end-of-values or a valid value. Iterate serials to tell apart.
def info(self, message, payload=None): """DEPRECATED""" if payload: self.log(event=message, payload=payload) else: self.log(event=message) return self
DEPRECATED
def rendered(self): """The rendered wire format for all conditions that have been rendered. Rendered conditions are never cleared. A new :class:`~bloop.conditions.ConditionRenderer` should be used for each operation.""" expressions = {k: v for (k, v) in self.expressions.items() if v is not Non...
The rendered wire format for all conditions that have been rendered. Rendered conditions are never cleared. A new :class:`~bloop.conditions.ConditionRenderer` should be used for each operation.
def windowed_run_events(da, window, dim='time'): """Return the number of runs of a minimum length. Parameters ---------- da: N-dimensional Xarray data array (boolean) Input data array window : int Minimum run length. dim : Xarray dimension (default = 'ti...
Return the number of runs of a minimum length. Parameters ---------- da: N-dimensional Xarray data array (boolean) Input data array window : int Minimum run length. dim : Xarray dimension (default = 'time') Dimension along which to calculate consec...
def post_unpack_merkleblock(d, f): """ A post-processing "post_unpack" to merkleblock messages. It validates the merkle proofs (throwing an exception if there's an error), and returns the list of transaction hashes in "tx_hashes". The transactions are supposed to be sent immediately after the merk...
A post-processing "post_unpack" to merkleblock messages. It validates the merkle proofs (throwing an exception if there's an error), and returns the list of transaction hashes in "tx_hashes". The transactions are supposed to be sent immediately after the merkleblock message.
def set_figure(self, figure, handle=None): """Call this with the Bokeh figure object.""" self.figure = figure self.bkimage = None self._push_handle = handle wd = figure.plot_width ht = figure.plot_height self.configure_window(wd, ht) doc = curdoc() ...
Call this with the Bokeh figure object.
def get_feeds(self, project=None, feed_role=None, include_deleted_upstreams=None): """GetFeeds. [Preview API] Get all feeds in an account where you have the provided role access. :param str project: Project ID or project name :param str feed_role: Filter by this role, either Administrato...
GetFeeds. [Preview API] Get all feeds in an account where you have the provided role access. :param str project: Project ID or project name :param str feed_role: Filter by this role, either Administrator(4), Contributor(3), or Reader(2) level permissions. :param bool include_deleted_upst...
def fix_addresses(start=None, end=None): """Set missing addresses to start and end of IDB. Take a start and end addresses. If an address is None or `BADADDR`, return start or end addresses of the IDB instead. Args start: Start EA. Use `None` to get IDB start. end: End EA. Use `None` t...
Set missing addresses to start and end of IDB. Take a start and end addresses. If an address is None or `BADADDR`, return start or end addresses of the IDB instead. Args start: Start EA. Use `None` to get IDB start. end: End EA. Use `None` to get IDB end. Returns: (start, end...
def resolve_path_from_base(path_to_resolve, base_path): """ If path-to_resolve is a relative path, create an absolute path with base_path as the base. If path_to_resolve is an absolute path or a user path (~), just resolve it to an absolute path and return. """ return os.path.abspath( ...
If path-to_resolve is a relative path, create an absolute path with base_path as the base. If path_to_resolve is an absolute path or a user path (~), just resolve it to an absolute path and return.
def get_list(self): """ Extract from a DSL aggregated response the values for each bucket :return: a list with the values in a DSL aggregated response """ field = self.FIELD_NAME query = ElasticQuery.get_agg(field=field, date_field=se...
Extract from a DSL aggregated response the values for each bucket :return: a list with the values in a DSL aggregated response
def essays(self): """Copy essays from the source profile to the destination profile.""" for essay_name in self.dest_user.profile.essays.essay_names: setattr(self.dest_user.profile.essays, essay_name, getattr(self.source_profile.essays, essay_name))
Copy essays from the source profile to the destination profile.
def adjgraph(args): """ %prog adjgraph adjacency.txt subgraph.txt Construct adjacency graph for graphviz. The file may look like sample below. The lines with numbers are chromosomes with gene order information. genome 0 chr 0 -1 -13 -16 3 4 -6126 -5 17 -6 7 18 5357 8 -5358 5359 -9 -10 -11 ...
%prog adjgraph adjacency.txt subgraph.txt Construct adjacency graph for graphviz. The file may look like sample below. The lines with numbers are chromosomes with gene order information. genome 0 chr 0 -1 -13 -16 3 4 -6126 -5 17 -6 7 18 5357 8 -5358 5359 -9 -10 -11 5362 5360 chr 1 138 6133...
def _vpcs_path(self): """ Returns the VPCS executable path. :returns: path to VPCS """ search_path = self._manager.config.get_section_config("VPCS").get("vpcs_path", "vpcs") path = shutil.which(search_path) # shutil.which return None if the path doesn't exists ...
Returns the VPCS executable path. :returns: path to VPCS
def show_vcs_output_vcs_nodes_vcs_node_info_node_switchname(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_vcs = ET.Element("show_vcs") config = show_vcs output = ET.SubElement(show_vcs, "output") vcs_nodes = ET.SubElement(output, "...
Auto Generated Code
def tag(**tags): """ Tags current transaction. Both key and value of the tag should be strings. """ transaction = execution_context.get_transaction() if not transaction: error_logger.warning("Ignored tags %s. No transaction currently active.", ", ".join(tags.keys())) else: transa...
Tags current transaction. Both key and value of the tag should be strings.
def intake_path_dirs(path): """Return a list of directories from the intake path. If a string, perhaps taken from an environment variable, then the list of paths will be split on the character ":" for posix of ";" for windows. Protocol indicators ("protocol://") will be ignored. """ if isinstan...
Return a list of directories from the intake path. If a string, perhaps taken from an environment variable, then the list of paths will be split on the character ":" for posix of ";" for windows. Protocol indicators ("protocol://") will be ignored.
def toProtocolElement(self): """ Returns the GA4GH protocol representation of this ReferenceSet. """ ret = protocol.ReferenceSet() ret.assembly_id = pb.string(self.getAssemblyId()) ret.description = pb.string(self.getDescription()) ret.id = self.getId() re...
Returns the GA4GH protocol representation of this ReferenceSet.
def send_email(sender, pw, to, subject, content, files=None, service='163'): """send email, recommended use 163 mailbox service, as it is tested. :param sender: str email address of sender :param pw: str password for sender :param to: str email addressee :param subject: str ...
send email, recommended use 163 mailbox service, as it is tested. :param sender: str email address of sender :param pw: str password for sender :param to: str email addressee :param subject: str subject of email :param content: str content of email :param...
def order_modified_volume(self, volume_id, new_size=None, new_iops=None, new_tier_level=None): """Places an order for modifying an existing block volume. :param volume_id: The ID of the volume to be modified :param new_size: The new size/capacity for the volume :param new_iops: The new ...
Places an order for modifying an existing block volume. :param volume_id: The ID of the volume to be modified :param new_size: The new size/capacity for the volume :param new_iops: The new IOPS for the volume :param new_tier_level: The new tier level for the volume :return: Retu...
def unregister_callback(callback_id): """unregister a callback registration""" global _callbacks obj = _callbacks.pop(callback_id, None) threads = [] if obj is not None: t, quit = obj quit.set() threads.append(t) for t in threads: t.join()
unregister a callback registration
def show_image(img:Image, ax:plt.Axes=None, figsize:tuple=(3,3), hide_axis:bool=True, cmap:str='binary', alpha:float=None, **kwargs)->plt.Axes: "Display `Image` in notebook." if ax is None: fig,ax = plt.subplots(figsize=figsize) ax.imshow(image2np(img.data), cmap=cmap, alpha=alpha, **kwargs)...
Display `Image` in notebook.
def accept(self, visitor: "BaseVisitor[ResultT]") -> ResultT: """ Traverses the game in PGN order using the given *visitor*. Returns the *visitor* result. """ if visitor.begin_game() is not SKIP: for tagname, tagvalue in self.headers.items(): visitor.v...
Traverses the game in PGN order using the given *visitor*. Returns the *visitor* result.
def _scan_response(self): """Create scan response data.""" voltage = struct.pack("<H", int(self.voltage*256)) reading = struct.pack("<HLLL", 0xFFFF, 0, 0, 0) response = voltage + reading return response
Create scan response data.
def get_secret(key, *args, **kwargs): """Retrieves a secret.""" env_value = os.environ.get(key.replace('.', '_').upper()) if not env_value: # Backwards compatibility: the deprecated secrets vault return _get_secret_from_vault(key, *args, **kwargs) return env_value
Retrieves a secret.
def rentry_exists_on_disk(self, name): """ Searches through the file/dir entries of the current *and* all its remote directories (repos), and returns True if a physical entry with the given name could be found. The local directory (self) gets searched first, so re...
Searches through the file/dir entries of the current *and* all its remote directories (repos), and returns True if a physical entry with the given name could be found. The local directory (self) gets searched first, so repositories take a lower precedence regarding the ...
def token_submit(self, token_id, json_data={}): """ Submits a given token, along with optional data """ uri = 'tokens/%s' % token_id post_body = json.dumps(json_data) resp, body = self.post(uri, post_body) self.expected_success(200, resp.status) body = json.loads(body) ...
Submits a given token, along with optional data
def _get_ldflags(): """Determine the correct link flags. This attempts dummy compiles similar to how autotools does feature detection. """ # windows gcc does not support linking with unresolved symbols if sys.platform == 'win32': # pragma: no cover (windows) prefix = getattr(sys, 'real_pre...
Determine the correct link flags. This attempts dummy compiles similar to how autotools does feature detection.
def has_port_by_name(self, port_name): '''Check if this component has a port by the given name.''' with self._mutex: if self.get_port_by_name(port_name): return True return False
Check if this component has a port by the given name.
def uninitialize_ui(self): """ Uninitializes the Component ui. :return: Method success. :rtype: bool """ LOGGER.debug("> Uninitializing '{0}' Component ui.".format(self.__class__.__name__)) # Signals / Slots. self.Port_spinBox.valueChanged.disconnect(se...
Uninitializes the Component ui. :return: Method success. :rtype: bool
def is_github_task(task): """Determine if a task is related to GitHub. This function currently looks into the ``schedulerId``, ``extra.tasks_for``, and ``metadata.source``. Args: task (dict): the task definition to check. Returns: bool: True if a piece of data refers to GitHub ...
Determine if a task is related to GitHub. This function currently looks into the ``schedulerId``, ``extra.tasks_for``, and ``metadata.source``. Args: task (dict): the task definition to check. Returns: bool: True if a piece of data refers to GitHub
def list_dir(self, filter_fn=None) -> 'Tuple[Path, ...]': """ * the `self` Path object is assumed to be a directory :param filter_fn: a `None` object or a predicative function `str -> bool` which will be applied on the filename/directory in `self` directory. ...
* the `self` Path object is assumed to be a directory :param filter_fn: a `None` object or a predicative function `str -> bool` which will be applied on the filename/directory in `self` directory. :return: a tuple of Path objects each of whic...
def meanOmega(self,dangle,oned=False,tdisrupt=None,approx=True, higherorder=None): """ NAME: meanOmega PURPOSE: calculate the mean frequency as a function of angle, assuming a uniform time distribution up to a maximum time INPUT: da...
NAME: meanOmega PURPOSE: calculate the mean frequency as a function of angle, assuming a uniform time distribution up to a maximum time INPUT: dangle - angle offset oned= (False) if True, return the 1D offset from the progenitor (along the direction of d...