code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def done(self, msg_handle): """acknowledge completion of message""" self.sqs_client.delete_message( QueueUrl=self.queue_url, ReceiptHandle=msg_handle.handle, )
acknowledge completion of message
def Parser(grammar, **actions): r"""Make a parsing function from a peglet grammar, defining the grammar's semantic actions with keyword arguments. The parsing function maps a string to a results tuple or raises Unparsable. (It can optionally take a rule name to start from, by default the first in t...
r"""Make a parsing function from a peglet grammar, defining the grammar's semantic actions with keyword arguments. The parsing function maps a string to a results tuple or raises Unparsable. (It can optionally take a rule name to start from, by default the first in the grammar.) It doesn't necessarily ...
def get_random_value(field): """ Calls the dispatch method (``get_factory_func``) and passes the field obj argument to the callable returned. Returns: random value depending on field type and constraints in the field object """ func = get_factory_func(field) if field.de...
Calls the dispatch method (``get_factory_func``) and passes the field obj argument to the callable returned. Returns: random value depending on field type and constraints in the field object
def update_cluster(cluster_ref, cluster_spec): ''' Updates a cluster in a datacenter. cluster_ref The cluster reference. cluster_spec The cluster spec (vim.ClusterConfigSpecEx). Defaults to None. ''' cluster_name = get_managed_object_name(cluster_ref) log.trace('Upd...
Updates a cluster in a datacenter. cluster_ref The cluster reference. cluster_spec The cluster spec (vim.ClusterConfigSpecEx). Defaults to None.
def GLI(self, pm=False): ''' 判斷乖離 ''' return list(self.a.ckMAO(self.a.MAO(3,6)[0][1], pm=pm))[0]
判斷乖離
def compute_positive_association(self, visible, hidden_probs, hidden_states): """Compute positive associations between visible and hidden units. :param visible: visible units :param hidden_probs: hidden units probabilities :param hidden_states: hidde...
Compute positive associations between visible and hidden units. :param visible: visible units :param hidden_probs: hidden units probabilities :param hidden_states: hidden units states :return: positive association = dot(visible.T, hidden)
def geweke(x, seg_length, seg_stride, end_idx, ref_start, ref_end=None, seg_start=0): """ Calculates Geweke conervergence statistic for a chain of data. This function will advance along the chain and calculate the statistic for each step. Parameters ---------- x : numpy.array ...
Calculates Geweke conervergence statistic for a chain of data. This function will advance along the chain and calculate the statistic for each step. Parameters ---------- x : numpy.array A one-dimensional array of data. seg_length : int Number of samples to use for each Geweke c...
def computeScaledProbabilities( listOfScales=[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0], listofkValues=[64, 128, 256], kw=32, n=1000, numWorkers=10, nTrials=1000, ): """ Compute the impact of S on match probabilities for a fixed value of n. """ # Create arguments for t...
Compute the impact of S on match probabilities for a fixed value of n.
def chunk_cache(method): """ Caches chunks of default data. This decorator caches generated default data so as to avoid recomputing it on a subsequent queries to the provider. """ @functools.wraps(method) def wrapper(self, context): # Defer to the method if no caching is enable...
Caches chunks of default data. This decorator caches generated default data so as to avoid recomputing it on a subsequent queries to the provider.
def print_treemap(self, format=None, output=sys.stdout, **kwargs): """ Print the matrix for self's nodes. Args: format (str): output format (csv, json or text). output (file): file descriptor on which to write. """ treemap = self.as_treemap() tree...
Print the matrix for self's nodes. Args: format (str): output format (csv, json or text). output (file): file descriptor on which to write.
def get_default_config(self): """ Return the default config for the handler """ config = super(StatsiteHandler, self).get_default_config() config.update({ 'host': '', 'tcpport': 1234, 'udpport': 1234, 'timeout': 5, }) ...
Return the default config for the handler
def parse_time(block_time): """Take a string representation of time from the blockchain, and parse it into datetime object. """ return datetime.strptime(block_time, timeFormat).replace(tzinfo=timezone.utc)
Take a string representation of time from the blockchain, and parse it into datetime object.
def _CheckInstallSuccess(self): """Checks if the installer installed correctly.""" if not os.path.exists(self.install_path): raise RuntimeError("Install failed, no files at: %s" % self.install_path) try: output = subprocess.check_output(["sc", "query", self.service_name]) service_running ...
Checks if the installer installed correctly.
def show_vcs_output_vcs_nodes_vcs_node_info_node_num(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, "vcs-nod...
Auto Generated Code
def flex_flow(self): """ :rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowList """ if self._flex_flow is None: self._flex_flow = FlexFlowList(self) return self._flex_flow
:rtype: twilio.rest.flex_api.v1.flex_flow.FlexFlowList
def get_data(self): """ Retrieve the relation data for each unit involved in a relation and, if complete, store it in a list under `self[self.name]`. This is automatically called when the RelationContext is instantiated. The units are sorted lexographically first by the service...
Retrieve the relation data for each unit involved in a relation and, if complete, store it in a list under `self[self.name]`. This is automatically called when the RelationContext is instantiated. The units are sorted lexographically first by the service ID, then by the unit ID. Thus,...
def _refresh(self, http): """Refreshes the access token. Since the underlying App Engine app_identity implementation does its own caching we can skip all the storage hoops and just to a refresh using the API. Args: http: unused HTTP object Raises: ...
Refreshes the access token. Since the underlying App Engine app_identity implementation does its own caching we can skip all the storage hoops and just to a refresh using the API. Args: http: unused HTTP object Raises: AccessTokenRefreshError: When the ...
def runAndWait(self): ''' Called by the engine to start an event loop, process all commands in the queue at the start of the loop, and then exit the loop. ''' self._push(self._engine.endLoop, tuple()) self._driver.startLoop()
Called by the engine to start an event loop, process all commands in the queue at the start of the loop, and then exit the loop.
def _set_autobw_threshold_table(self, v, load=False): """ Setter method for autobw_threshold_table, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/autobw_threshold_table (container) If this variable is read-only (config: false) in the source YANG file, then _set_autobw_threshold_tab...
Setter method for autobw_threshold_table, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/autobw_threshold_table (container) If this variable is read-only (config: false) in the source YANG file, then _set_autobw_threshold_table is considered as a private method. Backends looking to popu...
def add_from_dataframe(self, dataframe, data_type_id, name, description): """ Serialize the specified DataFrame and upload it as a new dataset. Parameters ---------- dataframe : pandas.DataFrame Data to serialize. data_type_id : str Format to seri...
Serialize the specified DataFrame and upload it as a new dataset. Parameters ---------- dataframe : pandas.DataFrame Data to serialize. data_type_id : str Format to serialize to. Supported formats are: 'PlainText' 'Gene...
def SerializeExclusiveData(self, writer): """ Serialize object. Args: writer (neo.IO.BinaryWriter): """ self.Code.Serialize(writer) if self.Version >= 1: writer.WriteBool(self.NeedStorage) writer.WriteVarString(self.Name) writer....
Serialize object. Args: writer (neo.IO.BinaryWriter):
def title( self ): """ Returns the title for this scene based on its information. :return <str> """ if ( self.currentMode() == XCalendarScene.Mode.Day ): return self.currentDate().toString('dddd, MMMM dd, yyyy') elif ( self.curre...
Returns the title for this scene based on its information. :return <str>
def uint32_gte(a: int, b: int) -> bool: """ Return a >= b. """ return (a == b) or uint32_gt(a, b)
Return a >= b.
def update(self, *args, **kwargs): """Calls update on each of the systems self.systems.""" for system in self.systems: system.update(self, *args, **kwargs)
Calls update on each of the systems self.systems.
def cpp_prog_builder(build_context, target): """Build a C++ binary executable""" yprint(build_context.conf, 'Build CppProg', target) workspace_dir = build_context.get_workspace('CppProg', target.name) build_cpp(build_context, target, target.compiler_config, workspace_dir)
Build a C++ binary executable
def simulate(self, n=1, t=None): """Simulates the network forward. Simulates either a specific number of events or for a specified amount of simulation time. Parameters ---------- n : int (optional, default: 1) The number of events to simulate. If ``t`` is n...
Simulates the network forward. Simulates either a specific number of events or for a specified amount of simulation time. Parameters ---------- n : int (optional, default: 1) The number of events to simulate. If ``t`` is not given then this parameter is ...
def resample_with_censoring(self,data=[],censored_data=[]): ''' censored_data is full of observations that were censored, meaning a value of x really could have been anything >= x, so this method samples them out to be at least that large ''' filled_in = self._uncensor_da...
censored_data is full of observations that were censored, meaning a value of x really could have been anything >= x, so this method samples them out to be at least that large
def cli(env, volume_id, schedule_type): """Disables snapshots on the specified schedule for a given volume""" if (schedule_type not in ['INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY']): raise exceptions.CLIAbort( '--schedule_type must be INTERVAL, HOURLY, DAILY, or WEEKLY') file_manager = Sof...
Disables snapshots on the specified schedule for a given volume
def length(symlink_components): # type: (List[bytes]) -> int ''' Static method to return the length of the Rock Ridge Symbolic Link record. Parameters: symlink_components - A list containing a string for each of the symbolic link components...
Static method to return the length of the Rock Ridge Symbolic Link record. Parameters: symlink_components - A list containing a string for each of the symbolic link components. Returns: The length of this record in bytes.
def solve(self,problem): """ Solves optimization problem. Parameters ---------- problem : Object """ # Local vars norm2 = self.norm2 norminf = self.norminf parameters = self.parameters # Parameters fea...
Solves optimization problem. Parameters ---------- problem : Object
def vqsr_pipeline(job, uuid, vcf_id, config): """ Runs GATK Variant Quality Score Recalibration. 0: Start 0 --> 1 --> 3 --> 4 --> 5 1: Recalibrate SNPs | | 2: Recalibrate INDELS +-> 2 -+ 3: Apply SNP Recalibration 4: Apply INDEL ...
Runs GATK Variant Quality Score Recalibration. 0: Start 0 --> 1 --> 3 --> 4 --> 5 1: Recalibrate SNPs | | 2: Recalibrate INDELS +-> 2 -+ 3: Apply SNP Recalibration 4: Apply INDEL Recalibration 5: Write VCF to output directory :p...
def list(self, resource): """List metadata keys associated with the given resource. Args: resource (intern.resource.boss.BossResource): List keys associated with this resource. Returns: (list): List of key names. Raises: requests.HTTPError on failur...
List metadata keys associated with the given resource. Args: resource (intern.resource.boss.BossResource): List keys associated with this resource. Returns: (list): List of key names. Raises: requests.HTTPError on failure.
def elapsed(self, label=None, total=True): """Get elapsed time since timer start. Parameters ---------- label : string, optional (default None) Specify the label of the timer for which the elapsed time is required. If it is ``None``, the default timer with label ...
Get elapsed time since timer start. Parameters ---------- label : string, optional (default None) Specify the label of the timer for which the elapsed time is required. If it is ``None``, the default timer with label specified by the ``dfltlbl`` parameter of :meth...
def PARM_DECL(self, cursor): """Handles parameter declarations.""" # try and get the type. If unexposed, The canonical type will work. _type = cursor.type _name = cursor.spelling if (self.is_array_type(_type) or self.is_fundamental_type(_type) or s...
Handles parameter declarations.
def start_refresh(self): """Start redrawing the canvas at the previously set timed interval. """ self.logger.debug("starting timed refresh interval") self.rf_flags['done'] = False self.rf_draw_count = 0 self.rf_timer_count = 0 self.rf_late_count = 0 self.r...
Start redrawing the canvas at the previously set timed interval.
def setup_cachedir(cachedir, mmap_mode=None, bytes_limit=None): """ This function injects a joblib.Memory object in the cache() function (in a thread-specific slot of its 'memories' attribute). """ if not hasattr(cache, 'memories'): cache.memories = {} memory = joblib.Memory( locati...
This function injects a joblib.Memory object in the cache() function (in a thread-specific slot of its 'memories' attribute).
def check(call_fct): """ Decorator for optionable __call__ method It check the given option values """ # wrap the method @wraps(call_fct) def checked_call(self, *args, **kwargs): self.set_options_values(kwargs, parse=False, strict=True) options_val...
Decorator for optionable __call__ method It check the given option values
def get_recurring_payments_profile_details(self, profileid): """Shortcut for the GetRecurringPaymentsProfile method. This returns details for a recurring payment plan. The ``profileid`` is a value included in the response retrieved by the function ``create_recurring_payments_profile``. ...
Shortcut for the GetRecurringPaymentsProfile method. This returns details for a recurring payment plan. The ``profileid`` is a value included in the response retrieved by the function ``create_recurring_payments_profile``. The profile details include the data provided when the profile w...
def format_hooks(self, hooks): ''' Tries to format the hook objects to be more readable Specific to Pecan (not available in the request object) ''' str_hooks = [str(i).split()[0].strip('<') for i in hooks] return [i.split('.')[-1] for i in str_hooks if '.' in i]
Tries to format the hook objects to be more readable Specific to Pecan (not available in the request object)
def write_array_empty(self, key, value): """ write a 0-len array """ # ugly hack for length 0 axes arr = np.empty((1,) * value.ndim) self._handle.create_array(self.group, key, arr) getattr(self.group, key)._v_attrs.value_type = str(value.dtype) getattr(self.group, key)._...
write a 0-len array
def focus_parent(self): """move focus to parent node of currently focussed one""" w, focuspos = self.get_focus() parent = self._tree.parent_position(focuspos) if parent is not None: self.set_focus(parent)
move focus to parent node of currently focussed one
def run(self): """If element is considered hidden, drop the desc_signature node The default handling of signatures by :py:cls:`ObjectDescription` returns a list of nodes with the signature nodes. We are going to remove them if this is a hidden declaration. """ nodes = su...
If element is considered hidden, drop the desc_signature node The default handling of signatures by :py:cls:`ObjectDescription` returns a list of nodes with the signature nodes. We are going to remove them if this is a hidden declaration.
def date(page): """ Return the date, nicely-formatted """ soup = BeautifulSoup(page) try: page_date = soup.find('input', attrs={'name': 'date'})['value'] parsed_date = datetime.strptime(page_date, '%Y-%m-%d') return parsed_date.strftime('%a, %b %d, %Y') except: re...
Return the date, nicely-formatted
def inferred_heat_transport(self): """Calculates the inferred heat transport by integrating the TOA energy imbalance from pole to pole. The method is calculating .. math:: H(\\varphi) = 2 \pi R^2 \int_{-\pi/2}^{\\varphi} cos\phi \ R_{TOA} d\phi where :math:`R_{TOA...
Calculates the inferred heat transport by integrating the TOA energy imbalance from pole to pole. The method is calculating .. math:: H(\\varphi) = 2 \pi R^2 \int_{-\pi/2}^{\\varphi} cos\phi \ R_{TOA} d\phi where :math:`R_{TOA}` is the net radiation at top of atmosphere. ...
def routing_solution_to_ding0_graph(graph, solution): """ Insert `solution` from routing into `graph` Args ---- graph: :networkx:`NetworkX Graph Obj< >` NetworkX graph object with nodes solution: BaseSolution Instance of `BaseSolution` or child class (e.g. `LocalSearchSolution`) (=s...
Insert `solution` from routing into `graph` Args ---- graph: :networkx:`NetworkX Graph Obj< >` NetworkX graph object with nodes solution: BaseSolution Instance of `BaseSolution` or child class (e.g. `LocalSearchSolution`) (=solution from routing) Returns ------- :networkx:`...
def get_zeta_i_j(self, X): ''' Parameters ---------- X : np.array Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the positive class, while X[:,1] is the negative class. None by default Returns ------- np.array of z-scores ''' y_i, y_j = X.T[0], X.T[1] return self.get...
Parameters ---------- X : np.array Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the positive class, while X[:,1] is the negative class. None by default Returns ------- np.array of z-scores
def delete_namespace(self, name, ignore_errors=False): """ deletes a namespace args: name: the name of the namespace ignore_errors(bool): Will ignore if a namespace doesn not exist or there is an error deleting the namespace returns: ...
deletes a namespace args: name: the name of the namespace ignore_errors(bool): Will ignore if a namespace doesn not exist or there is an error deleting the namespace returns: True if deleted False if not deleted ...
def from_bonding(cls, molecule, bond=True, angle=True, dihedral=True, tol=0.1, **kwargs): """ Another constructor that creates an instance from a molecule. Covalent bonds and other bond-based topologies (angles and dihedrals) can be automatically determined. Cannot b...
Another constructor that creates an instance from a molecule. Covalent bonds and other bond-based topologies (angles and dihedrals) can be automatically determined. Cannot be used for non bond-based topologies, e.g., improper dihedrals. Args: molecule (Molecule): Input molec...
def selectSort(list1, list2): """ Razeni 2 poli najednou (list) pomoci metody select sort input: list1 - prvni pole (hlavni pole pro razeni) list2 - druhe pole (vedlejsi pole) (kopirujici pozice pro razeni podle hlavniho pole list1) returns: d...
Razeni 2 poli najednou (list) pomoci metody select sort input: list1 - prvni pole (hlavni pole pro razeni) list2 - druhe pole (vedlejsi pole) (kopirujici pozice pro razeni podle hlavniho pole list1) returns: dve serazena pole - hodnoty se ridi podle p...
def gsea_compute_tensor(data, gmt, n, weighted_score_type, permutation_type, method, pheno_pos, pheno_neg, classes, ascending, processes=1, seed=None, single=False, scale=False): """compute enrichment scores and enrichment nulls. :param data: preprocessed expression datafr...
compute enrichment scores and enrichment nulls. :param data: preprocessed expression dataframe or a pre-ranked file if prerank=True. :param dict gmt: all gene sets in .gmt file. need to call load_gmt() to get results. :param int n: permutation number. default: 1000. :param str method: r...
def upload_gallery_photo(self, gallery_id, source_amigo_id, file_obj, chunk_size=CHUNK_SIZE, force_chunked=False, metadata=None): """ Upload a photo to a dataset's gallery. """ simple_upload_url = 'related_tables/%s/upload' % gal...
Upload a photo to a dataset's gallery.
def ReadHuntResults(self, hunt_id, offset, count, with_tag=None, with_type=None, with_substring=None, with_timestamp=None): """Reads hunt results of a given hunt ...
Reads hunt results of a given hunt using given query options.
def u16(self, name, value=None, align=None): """Add an unsigned 2 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(2, name, value, align)
Add an unsigned 2 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
def with_relations(self, user=None): """ Return a cleaned dictionary including relations :returns: a Repository instance """ repository = self.clean(user=user) try: parent = yield self.get_parent() repository['organisation'] = parent.clean() ...
Return a cleaned dictionary including relations :returns: a Repository instance
def add_include(self, name, module_spec): """Adds a module as an included module. :param name: Name under which the included module should be exposed in the current module. :param module_spec: ModuleSpec of the included module. """ assert name...
Adds a module as an included module. :param name: Name under which the included module should be exposed in the current module. :param module_spec: ModuleSpec of the included module.
def learning_rate_schedule(hparams): """Learning rate schedule based on hparams.""" mlperf_log.transformer_print(key=mlperf_log.OPT_LR, deferred=True) mlperf_log.transformer_print( key=mlperf_log.OPT_LR_WARMUP_STEPS, value=hparams.learning_rate_warmup_steps) step_num = _global_step(hparams) schedu...
Learning rate schedule based on hparams.
def get_values(self): """ returns final values (same result as tf.Session.run()) """ return [self._cache.get(i.name,None) for i in self._original_evals]
returns final values (same result as tf.Session.run())
def set_project_status(project_id, status, **kwargs): """ Set the status of a project to 'X' """ user_id = kwargs.get('user_id') #check_perm(user_id, 'delete_project') project = _get_project(project_id) project.check_write_permission(user_id) project.status = status db.DBSession....
Set the status of a project to 'X'
def _qname(self, name): """Convert name to an XML QName e.g. pdf:Producer -> {http://ns.adobe.com/pdf/1.3/}Producer """ if isinstance(name, QName): return name if not isinstance(name, str): raise TypeError("{} must be str".format(name)) if name ==...
Convert name to an XML QName e.g. pdf:Producer -> {http://ns.adobe.com/pdf/1.3/}Producer
def on_touch_move(self, touch): """If an entity is selected, drag it.""" if hasattr(self, '_lasttouch') and self._lasttouch == touch: return if self.app.selection in self.selection_candidates: self.selection_candidates.remove(self.app.selection) if self.app.select...
If an entity is selected, drag it.
def lins_ccc(y_true, y_pred): """ Lin's Concordance Correlation Coefficient. See https://en.wikipedia.org/wiki/Concordance_correlation_coefficient Parameters ---------- y_true: ndarray vector of true targets y_pred: ndarray vector of predicted targets Returns -----...
Lin's Concordance Correlation Coefficient. See https://en.wikipedia.org/wiki/Concordance_correlation_coefficient Parameters ---------- y_true: ndarray vector of true targets y_pred: ndarray vector of predicted targets Returns ------- float: 1.0 for a perfect ma...
def divide(x: LispNumber, y: LispNumber) -> LispNumber: """Division reducer. If both arguments are integers, return a Fraction. Otherwise, return the true division of x and y.""" if isinstance(x, int) and isinstance(y, int): return Fraction(x, y) return x / y
Division reducer. If both arguments are integers, return a Fraction. Otherwise, return the true division of x and y.
def to_prj(self, filename): """ Saves prj WKT to given file. """ with open(filename, "w") as fp: fp.write(self.prj)
Saves prj WKT to given file.
def allocate_disks(logical_disk, server, raid_config): """Allocate physical disks to a logical disk. This method allocated physical disks to a logical disk based on the current state of the server and criteria mentioned in the logical disk. :param logical_disk: a dictionary of a logical disk ...
Allocate physical disks to a logical disk. This method allocated physical disks to a logical disk based on the current state of the server and criteria mentioned in the logical disk. :param logical_disk: a dictionary of a logical disk from the RAID configuration input to the module. :param...
def f_load(self, recursive=True, load_data=pypetconstants.LOAD_DATA, max_depth=None): """Loads a group from disk. :param recursive: Default is ``True``. Whether recursively all nodes below the current node should be loaded, too. Note that links are ne...
Loads a group from disk. :param recursive: Default is ``True``. Whether recursively all nodes below the current node should be loaded, too. Note that links are never evaluated recursively. Only the linked node will be loaded if it does not exist in the tree, yet...
def daterange(start_date, end_date): """ Yield one date per day from starting date to ending date. Args: start_date (date): starting date. end_date (date): ending date. Yields: date: a date for each day within the range. """ for n in range(int((end_date - start_date).da...
Yield one date per day from starting date to ending date. Args: start_date (date): starting date. end_date (date): ending date. Yields: date: a date for each day within the range.
def write_float(self, value, little_endian=True): """ Pack the value as a float and write 4 bytes to the stream. Args: value (number): the value to write to the stream. little_endian (bool): specify the endianness. (Default) Little endian. Returns: i...
Pack the value as a float and write 4 bytes to the stream. Args: value (number): the value to write to the stream. little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: the number of bytes written.
def decrypt(self, senderKeyMessageBytes): """ :type senderKeyMessageBytes: bytearray """ try: record = self.senderKeyStore.loadSenderKey(self.senderKeyName) if record.isEmpty(): raise NoSessionException("No sender key for: %s" % self.senderKeyName)...
:type senderKeyMessageBytes: bytearray
def confirmation(self, pdu): """Message going upstream.""" if _debug: StreamToPacket._debug("StreamToPacket.confirmation %r", pdu) # hack it up into chunks for packet in self.packetize(pdu, self.upstreamBuffer): self.response(packet)
Message going upstream.
def under_attack(col, queens): """Checks if queen is under attack :param col: Column number :param queens: list of queens :return: True iff queen is under attack """ left = right = col for _, column in reversed(queens): left, right = left - 1, right +...
Checks if queen is under attack :param col: Column number :param queens: list of queens :return: True iff queen is under attack
def print_list(cls, l, output='table'): """ prints a list :param l: the list :param output: the output, default is a table :return: """ def dict_from_list(l): """ returns a dict from a list for printing :param l: the list ...
prints a list :param l: the list :param output: the output, default is a table :return:
def tz(self): """Return the timezone. If none is set use system timezone""" if not self._tz: self._tz = tzlocal.get_localzone().zone return self._tz
Return the timezone. If none is set use system timezone
def common_items_metrics(all_items, common_items): """ Calculates the percentage of common items for each project in each segment and calculates the mean and std of this percentage for each segment. """ segments = common_items.index.unique() metrics = {} for seg in segments: seg_...
Calculates the percentage of common items for each project in each segment and calculates the mean and std of this percentage for each segment.
def write_to_filepath(content, filepath, encoding='utf-8', mode='w', group_writeable=False): """Writes `content` to the `filepath` Creates parent directory if needed, and uses the specified file `mode` and data `encoding`. If `group_writeable` is True, the output file will have permissions to be wri...
Writes `content` to the `filepath` Creates parent directory if needed, and uses the specified file `mode` and data `encoding`. If `group_writeable` is True, the output file will have permissions to be writable by the group (on POSIX systems)
def remove_block(self, name): """ Removes an existing block from the AST. `name` Block name. * Raises a ``ValueError`` exception if `name` hasn't been added. """ if not self._ast or not name in self._block_map: raise ValueError(u"Block '...
Removes an existing block from the AST. `name` Block name. * Raises a ``ValueError`` exception if `name` hasn't been added.
def read_fermi_contact_shift(self): ''' output example: Fermi contact (isotropic) hyperfine coupling parameter (MHz) ------------------------------------------------------------- ion A_pw A_1PS A_1AE A_1c A_tot --------------------------------------...
output example: Fermi contact (isotropic) hyperfine coupling parameter (MHz) ------------------------------------------------------------- ion A_pw A_1PS A_1AE A_1c A_tot ------------------------------------------------------------- 1 -0.002 -0.002...
def encode_conjure_bean_type(cls, obj): # type: (ConjureBeanType) -> Any """Encodes a conjure bean into json""" encoded = {} # type: Dict[str, Any] for attribute_name, field_definition in obj._fields().items(): encoded[field_definition.identifier] = cls.do_encode( ...
Encodes a conjure bean into json
def add_function_signature_help(spec_dict: dict) -> dict: """Add function signature help Simplify the function signatures for presentation to BEL Editor users """ for f in spec_dict["functions"]["signatures"]: for argset_idx, argset in enumerate(spec_dict["functions"]["signatures"][f]["signatur...
Add function signature help Simplify the function signatures for presentation to BEL Editor users
def static(self, uri, file_or_directory, *args, **kwargs): """Create a websocket route from a decorated function :param uri: endpoint at which the socket endpoint will be accessible. :type uri: str :param args: captures all of the positional arguments passed in :type args: tuple(...
Create a websocket route from a decorated function :param uri: endpoint at which the socket endpoint will be accessible. :type uri: str :param args: captures all of the positional arguments passed in :type args: tuple(Any) :param kwargs: captures the keyword arguments passed in ...
def light_curve(self, params): """ Calculate a model light curve. :param params: Transit parameters :type params: A `TransitParams` instance :return: Relative flux :rtype: ndarray :Example: >>> flux = m.light_curve(params) """ #recalculates rsky and fac if necessary if params.t0 != self.t0 or...
Calculate a model light curve. :param params: Transit parameters :type params: A `TransitParams` instance :return: Relative flux :rtype: ndarray :Example: >>> flux = m.light_curve(params)
def markdown_editor(selector): """ Enable markdown editor for given textarea. :returns: Editor template context. """ return dict( selector=selector, extra_settings=mark_safe(simplejson.dumps( dict(previewParserPath=reverse('django_markdown_preview')))))
Enable markdown editor for given textarea. :returns: Editor template context.
def load_limits(self, config=None): """Load the stats limits (except the one in the exclude list).""" # For each plugins, call the load_limits method for p in self._plugins: self._plugins[p].load_limits(config)
Load the stats limits (except the one in the exclude list).
def size_control_valve_l(rho, Psat, Pc, mu, P1, P2, Q, D1=None, D2=None, d=None, FL=0.9, Fd=1, allow_choked=True, allow_laminar=True, full_output=False): r'''Calculates flow coefficient of a control valve passing a liquid according to IEC 60534. Uses a large nu...
r'''Calculates flow coefficient of a control valve passing a liquid according to IEC 60534. Uses a large number of inputs in SI units. Note the return value is not standard SI. All parameters are required. This sizing model does not officially apply to liquid mixtures, slurries, non-Newtonian fluids, or...
def replace_su(network,su_to_replace): """Replace the storage unit su_to_replace with a bus for the energy carrier, two links for the conversion of the energy carrier to and from electricity, a store to keep track of the depletion of the energy carrier and its CO2 emissions, and a variable generator for...
Replace the storage unit su_to_replace with a bus for the energy carrier, two links for the conversion of the energy carrier to and from electricity, a store to keep track of the depletion of the energy carrier and its CO2 emissions, and a variable generator for the storage inflow. Because the ener...
def click_info_switch(f): """Decorator to create eager Click info switch option, as described in: http://click.pocoo.org/6/options/#callbacks-and-eager-options. Takes a no-argument function and abstracts the boilerplate required by Click (value checking, exit on done). Example: @click.opt...
Decorator to create eager Click info switch option, as described in: http://click.pocoo.org/6/options/#callbacks-and-eager-options. Takes a no-argument function and abstracts the boilerplate required by Click (value checking, exit on done). Example: @click.option('--my-option', is_flag=True, ...
def is_inside(directory, fname): """True if fname is inside directory. The parameters should typically be passed to osutils.normpath first, so that . and .. and repeated slashes are eliminated, and the separators are canonical for the platform. The empty string as a dir name is taken as top-of-tre...
True if fname is inside directory. The parameters should typically be passed to osutils.normpath first, so that . and .. and repeated slashes are eliminated, and the separators are canonical for the platform. The empty string as a dir name is taken as top-of-tree and matches everything.
def calculate_fft(data, tbin): """ Function to calculate the Fourier transform of data. Parameters ---------- data : numpy.ndarray 1D or 2D array containing time series. tbin : float Bin size of time series (in ms). Returns ------- freqs : numpy.nd...
Function to calculate the Fourier transform of data. Parameters ---------- data : numpy.ndarray 1D or 2D array containing time series. tbin : float Bin size of time series (in ms). Returns ------- freqs : numpy.ndarray Frequency axis of signal in F...
def message_tc(self, message, max_length=255): """Write data to message_tc file in TcEX specified directory. This method is used to set and exit message in the ThreatConnect Platform. ThreatConnect only supports files of max_message_length. Any data exceeding this limit will be truncat...
Write data to message_tc file in TcEX specified directory. This method is used to set and exit message in the ThreatConnect Platform. ThreatConnect only supports files of max_message_length. Any data exceeding this limit will be truncated by this method. Args: message (str...
def keys_breadth_first(self, include_dicts=False): """a generator that returns all the keys in a set of nested DotDict instances. The keys take the form X.Y.Z""" namespaces = [] for key in self._key_order: if isinstance(getattr(self, key), DotDict): namespace...
a generator that returns all the keys in a set of nested DotDict instances. The keys take the form X.Y.Z
def fetch_data(dataset_name, return_X_y=False, local_cache_dir=None): """Download a data set from the PMLB, (optionally) store it locally, and return the data set. You must be connected to the internet if you are fetching a data set that is not cached locally. Parameters ---------- dataset_name: s...
Download a data set from the PMLB, (optionally) store it locally, and return the data set. You must be connected to the internet if you are fetching a data set that is not cached locally. Parameters ---------- dataset_name: str The name of the data set to load from PMLB. return_X_y: bool (...
def nbytes(self): """The number of bytes for this telemetry packet""" max_byte = -1 for defn in self.fields: byte = defn.bytes if type(defn.bytes) is int else max(defn.bytes) max_byte = max(max_byte, byte) return max_byte + 1
The number of bytes for this telemetry packet
def _get_keywords(self, **kwargs): """Format GET request parameters and keywords.""" if self.jurisdiction and 'jurisdiction_id' not in kwargs: kwargs['jurisdiction_id'] = self.jurisdiction if 'count' in kwargs: kwargs['page_size'] = kwargs.pop('count') if 'start' ...
Format GET request parameters and keywords.
def bottom(self, z: float = 0.0) -> Location: """ :param z: the z distance in mm :return: a Point corresponding to the absolute position of the bottom-center of the well (with the front-left corner of slot 1 as (0,0,0)). If z is specified, returns a point ...
:param z: the z distance in mm :return: a Point corresponding to the absolute position of the bottom-center of the well (with the front-left corner of slot 1 as (0,0,0)). If z is specified, returns a point offset by z mm from bottom-center
def map( self, lens, X=None, clusterer=cluster.DBSCAN(eps=0.5, min_samples=3), cover=Cover(n_cubes=10, perc_overlap=0.1), nerve=GraphNerve(), precomputed=False, remove_duplicate_nodes=False, # These arguments are all deprecated overlap_perc...
Apply Mapper algorithm on this projection and build a simplicial complex. Returns a dictionary with nodes and links. Parameters ---------- lens: Numpy Array Lower dimensional representation of data. In general will be output of `fit_transform`. X: Numpy Array Or...
def _parse_networks(networks): ''' Common logic for parsing the networks ''' networks = salt.utils.args.split_input(networks or []) if not networks: networks = {} else: # We don't want to recurse the repack, as the values of the kwargs # being passed when connecting to th...
Common logic for parsing the networks
def main(): """Quick test for QSUsb class.""" import argparse parser = argparse.ArgumentParser() parser.add_argument('--url', help='QSUSB URL [http://127.0.0.1:2020]', default='http://127.0.0.1:2020') parser.add_argument('--file', help='a test file from /&devices') parser...
Quick test for QSUsb class.
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None): """Retry calling the decorated function using an exponential backoff. original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ExceptionToCheck: the exception to check. may be a tuple of exceptions to check...
Retry calling the decorated function using an exponential backoff. original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ExceptionToCheck: the exception to check. may be a tuple of exceptions to check :type ExceptionToCheck: Exception or tuple :param tries: number of ti...
def put_text(self, key, contents): """Store the given text contents so that they are later retrievable by the given key.""" self._blobservice.create_blob_from_text( self.uuid, key, contents )
Store the given text contents so that they are later retrievable by the given key.
def _push_broks(self): """Push the provided broks objects to the broker daemon Only used on a Broker daemon by the Arbiter :param: broks :type: list :return: None """ data = cherrypy.request.json with self.app.arbiter_broks_lock: logger.debug...
Push the provided broks objects to the broker daemon Only used on a Broker daemon by the Arbiter :param: broks :type: list :return: None
def _get_format(value, quote_mode='always'): """ Returns the quote format depending on the quote_mode. This determines if the key value will be quoted when written to the env file. :param value: :param quote_mode: :return: str :raises: KeyError if the quote_mode is unknown """ ...
Returns the quote format depending on the quote_mode. This determines if the key value will be quoted when written to the env file. :param value: :param quote_mode: :return: str :raises: KeyError if the quote_mode is unknown