positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def forge_relationship(self, left_id, left_type, right_id, right_type, rel_type='Related To', rel_date=None, rel_confidence='high', rel_reason=''): """ Forges a relationship between two TLOs. Args: left_id: The CRITs ID of the fi...
Forges a relationship between two TLOs. Args: left_id: The CRITs ID of the first indicator left_type: The CRITs TLO type of the first indicator right_id: The CRITs ID of the second indicator right_type: The CRITs TLO type of the second indicator rel_t...
def get_constraint(self, twig=None, **kwargs): """ Filter in the 'constraint' context :parameter str constraint: name of the constraint (optional) :parameter **kwargs: any other tags to do the filter (except constraint or context) :return: :class:`phoebe.parameters.p...
Filter in the 'constraint' context :parameter str constraint: name of the constraint (optional) :parameter **kwargs: any other tags to do the filter (except constraint or context) :return: :class:`phoebe.parameters.parameters.ParameterSet`
def _Rzderiv(self,R,z,phi=0.,t=0.): """ NAME: _Rzderiv PURPOSE: evaluate the mixed radial, vertical derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time ...
NAME: _Rzderiv PURPOSE: evaluate the mixed radial, vertical derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the mixed radial, vertical deriva...
def make_job_details(self, row_idx): """Create a `JobDetails` from an `astropy.table.row.Row` """ row = self._table[row_idx] job_details = JobDetails.create_from_row(row) job_details.get_file_paths(self._file_archive, self._table_id_array) self._cache[job_details.fullkey] = job_d...
Create a `JobDetails` from an `astropy.table.row.Row`
def dir(): """Return the list of patched function names. Used for patching functions imported from the module. """ dir = [ 'abspath', 'dirname', 'exists', 'expanduser', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink'...
Return the list of patched function names. Used for patching functions imported from the module.
def start(cls, ev=None): """ Start the query to aleph by ISSN. """ ViewController.log_view.add("Beginning AlephReader request..") ViewController.issnbox_error.reset() issn = ViewController.issn.strip() # make sure, that `issn` was filled if not issn: ...
Start the query to aleph by ISSN.
def npoints_between(lon1, lat1, depth1, lon2, lat2, depth2, npoints): """ Find a list of specified number of points between two given ones that are equally spaced along the great circle arc connecting given points. :param float lon1, lat1, depth1: Coordinates of a point to start from. The first...
Find a list of specified number of points between two given ones that are equally spaced along the great circle arc connecting given points. :param float lon1, lat1, depth1: Coordinates of a point to start from. The first point in a resulting list has these coordinates. :param float lon2, l...
def predict(self, encoder_outputs, encoder_decoder_attention_bias): """Return predicted sequence.""" batch_size = tf.shape(encoder_outputs)[0] input_length = tf.shape(encoder_outputs)[1] max_decode_length = input_length + self.params.extra_decode_length symbols_to_logits_fn = self._get_symbols_to_l...
Return predicted sequence.
def jira_role(name, rawtext, text, lineno, inliner, options=None, content=None, oxford_comma=True): """Sphinx role for referencing a JIRA ticket. Examples:: :jira:`DM-6181` -> DM-6181 :jira:`DM-6181,DM-6181` -> DM-6180 and DM-6181 :jira:`DM-6181,DM-6181,DM-6182` -> DM-618...
Sphinx role for referencing a JIRA ticket. Examples:: :jira:`DM-6181` -> DM-6181 :jira:`DM-6181,DM-6181` -> DM-6180 and DM-6181 :jira:`DM-6181,DM-6181,DM-6182` -> DM-6180, DM-6181, and DM-6182
def validate_additional_properties(self, valid_response, response): """Validates additional properties. In additional properties, we only need to compare the values of the dict, not the keys Args: valid_response: An example response (for example generated in ...
Validates additional properties. In additional properties, we only need to compare the values of the dict, not the keys Args: valid_response: An example response (for example generated in _get_example_from_properties(self, spec)) Ty...
def choice_doinst(self): """View doinst.sh file """ if "doinst.sh" in self.sbo_files.split(): doinst_sh = ReadSBo(self.sbo_url).doinst("doinst.sh") fill = self.fill_pager(doinst_sh) self.pager(doinst_sh + fill)
View doinst.sh file
def modify(self, sp=None, ip_port=None, ip_address=None, netmask=None, v6_prefix_length=None, gateway=None, vlan_id=None): """ Modifies a replication interface. :param sp: same as the one in `create` method. :param ip_port: same as the one in `create` method. :par...
Modifies a replication interface. :param sp: same as the one in `create` method. :param ip_port: same as the one in `create` method. :param ip_address: same as the one in `create` method. :param netmask: same as the one in `create` method. :param v6_prefix_length: same as the on...
def run_output(self): """Output finalized data""" for f in logdissect.output.__formats__: ouroutput = self.output_modules[f] ouroutput.write_output(self.data_set['finalized_data'], args=self.args) del(ouroutput) # Output to terminal if sil...
Output finalized data
def from_incomplete_data(cls, vertices, normals=(), texcoords=(), **kwargs): """Return a Mesh with (vertices, normals, texcoords) as arrays, in that order. Useful for when you want a standardized array location format across different amounts of info in each mesh.""" normals = normals if hasa...
Return a Mesh with (vertices, normals, texcoords) as arrays, in that order. Useful for when you want a standardized array location format across different amounts of info in each mesh.
def consecutive_ones_property(sets, universe=None): """ Check the consecutive ones property. :param list sets: is a list of subsets of the ground set. :param groundset: is the set of all elements, by default it is the union of the given sets :returns: returns a list of the ordered groun...
Check the consecutive ones property. :param list sets: is a list of subsets of the ground set. :param groundset: is the set of all elements, by default it is the union of the given sets :returns: returns a list of the ordered ground set where every given set is consecutive, ...
def get_activating_subs(self): """Extract INDRA ActiveForm Statements based on a mutation from BEL. The SPARQL pattern used to extract ActiveForms due to mutations look for a ProteinAbundance as a subject which has a child encoding the amino acid substitution. The object of the statemen...
Extract INDRA ActiveForm Statements based on a mutation from BEL. The SPARQL pattern used to extract ActiveForms due to mutations look for a ProteinAbundance as a subject which has a child encoding the amino acid substitution. The object of the statement is an ActivityType of the same P...
def bind(self, destination='', source='', routing_key='', arguments=None): """Bind an Exchange. :param str destination: Exchange name :param str source: Exchange to bind to :param str routing_key: The routing key to use :param dict arguments: Bind key/value argument...
Bind an Exchange. :param str destination: Exchange name :param str source: Exchange to bind to :param str routing_key: The routing key to use :param dict arguments: Bind key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises...
def getVariants(self, referenceName, startPosition, endPosition, callSetIds=[]): """ Returns an iterator over the specified variants. The parameters correspond to the attributes of a GASearchVariantsRequest object. """ if callSetIds is None: callSe...
Returns an iterator over the specified variants. The parameters correspond to the attributes of a GASearchVariantsRequest object.
def zoom(params, factor): """ Applies a zoom on the current parameters. Computes the top-left plane-space coordinates from the Mandelbrot-space coordinates. :param params: Current application parameters. :param factor: Zoom factor by which the zoom ratio is divided (bigger factor, more zoom) "...
Applies a zoom on the current parameters. Computes the top-left plane-space coordinates from the Mandelbrot-space coordinates. :param params: Current application parameters. :param factor: Zoom factor by which the zoom ratio is divided (bigger factor, more zoom)
def pretty_polyfit_plot(x, y, deg=1, xlabel=None, ylabel=None, **kwargs): """ Convenience method to plot data with trend lines based on polynomial fit. Args: x: Sequence of x data. y: Sequence of y data. deg (int): Degree of polynomial. Defaults to 1. xlabel (str): Label for...
Convenience method to plot data with trend lines based on polynomial fit. Args: x: Sequence of x data. y: Sequence of y data. deg (int): Degree of polynomial. Defaults to 1. xlabel (str): Label for x-axis. ylabel (str): Label for y-axis. \\*\\*kwargs: Keyword args pa...
def retrieve(pdb_id, cache_dir = None, acceptable_sequence_percentage_match = 70.0, require_uniprot_residue_mapping = True, bio_cache = None): '''Creates a PDBML object by using a cached copy of the files if they exists or by retrieving the files from the RCSB. bio_cache should be a klab.bio.cache.py...
Creates a PDBML object by using a cached copy of the files if they exists or by retrieving the files from the RCSB. bio_cache should be a klab.bio.cache.py::BioCache object and is used to avoid reading/downloading cached files repeatedly.
def get_type(var): """ Gets types accounting for numpy Ignore: import utool as ut import pandas as pd var = np.array(['a', 'b', 'c']) ut.get_type(var) var = pd.Index(['a', 'b', 'c']) ut.get_type(var) """ if HAVE_NUMPY and isinstance(var, np.ndarray): ...
Gets types accounting for numpy Ignore: import utool as ut import pandas as pd var = np.array(['a', 'b', 'c']) ut.get_type(var) var = pd.Index(['a', 'b', 'c']) ut.get_type(var)
def static_transition(timestamp, contract_dates, transition, holidays=None, validate_inputs=True): """ An implementation of *get_weights* parameter in roller(). Return weights to tradeable instruments for a given date based on a transition DataFrame which indicates how to roll thro...
An implementation of *get_weights* parameter in roller(). Return weights to tradeable instruments for a given date based on a transition DataFrame which indicates how to roll through the roll period. Parameters ---------- timestamp: pandas.Timestamp The timestamp to return instrument weight...
def loglikelihood(self, x, previous=False): """return log-likelihood of `x` regarding the current sample distribution""" # testing of original fct: MC integrate must be one: mean(p(x_i)) * volume(where x_i are uniformely sampled) # for i in xrange(3): print mean([cma.likelihood(20*r-10, dim * [0...
return log-likelihood of `x` regarding the current sample distribution
def encoded_to_array(encoded): """ Turn a dictionary with base64 encoded strings back into a numpy array. Parameters ------------ encoded : dict Has keys: dtype: string of dtype shape: int tuple of shape base64: base64 encoded string of flat array binary: deco...
Turn a dictionary with base64 encoded strings back into a numpy array. Parameters ------------ encoded : dict Has keys: dtype: string of dtype shape: int tuple of shape base64: base64 encoded string of flat array binary: decode result coming from numpy.tostring R...
def _set_rbridge_id(self, v, load=False): """ Setter method for rbridge_id, mapped from YANG variable /rbridge_id (list) If this variable is read-only (config: false) in the source YANG file, then _set_rbridge_id is considered as a private method. Backends looking to populate this variable should ...
Setter method for rbridge_id, mapped from YANG variable /rbridge_id (list) If this variable is read-only (config: false) in the source YANG file, then _set_rbridge_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_rbridge_id() directly...
def items(self): """ Get list of download items. """ if self.matcher: for item in self._fetch_items(): if self.matcher.match(item): yield item else: for item in self._fetch_items(): yield item
Get list of download items.
def get_tunnel_info_output_tunnel_dest_ip(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_tunnel_info = ET.Element("get_tunnel_info") config = get_tunnel_info output = ET.SubElement(get_tunnel_info, "output") tunnel = ET.SubElement(ou...
Auto Generated Code
def hacking_has_only_comments(physical_line, filename, lines, line_number): """Check for empty files with only comments H104 empty file with only comments """ if line_number == 1 and all(map(EMPTY_LINE_RE.match, lines)): return (0, "H104: File contains nothing but comments")
Check for empty files with only comments H104 empty file with only comments
def format(format_string, cast=lambda x: x): """ A pre-called helper to supply a modern string format (the kind with {} instead of %s), so that it can apply to each value in the column as it is rendered. This can be useful for string padding like leading zeroes, or rounding floating point numbers to a ...
A pre-called helper to supply a modern string format (the kind with {} instead of %s), so that it can apply to each value in the column as it is rendered. This can be useful for string padding like leading zeroes, or rounding floating point numbers to a certain number of decimal places, etc. If given,...
def plot_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, labels=None, color_labels=None, ellipse_outline=False, ellipse_fill=True, show_points=True, **kwargs): """Plot the row principal coordinates.""" utils.valida...
Plot the row principal coordinates.
def text(self, paths, wholetext=False, lineSep=None): """ Loads text files and returns a :class:`DataFrame` whose schema starts with a string column named "value", and followed by partitioned columns if there are any. The text files must be encoded as UTF-8. By default, ...
Loads text files and returns a :class:`DataFrame` whose schema starts with a string column named "value", and followed by partitioned columns if there are any. The text files must be encoded as UTF-8. By default, each line in the text file is a new row in the resulting DataFrame. ...
def attend_on_question(self, query: torch.Tensor, encoder_outputs: torch.Tensor, encoder_output_mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Given a query (which is typically the decoder hidden state), comp...
Given a query (which is typically the decoder hidden state), compute an attention over the output of the question encoder, and return a weighted sum of the question representations given this attention. We also return the attention weights themselves. This is a simple computation, but we have ...
def at(*args, **kwargs): # pylint: disable=C0103 ''' Add a job to the queue. The 'timespec' follows the format documented in the at(1) manpage. CLI Example: .. code-block:: bash salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>] salt '*' at.at 12:05am '/sbin/reboot' ...
Add a job to the queue. The 'timespec' follows the format documented in the at(1) manpage. CLI Example: .. code-block:: bash salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>] salt '*' at.at 12:05am '/sbin/reboot' tag=reboot salt '*' at.at '3:05am +3 days' 'bin/myscri...
def emit_rmic_classes(target, source, env): """Create and return lists of Java RMI stub and skeleton class files to be created from a set of class files. """ class_suffix = env.get('JAVACLASSSUFFIX', '.class') classdir = env.get('JAVACLASSDIR') if not classdir: try: s = sour...
Create and return lists of Java RMI stub and skeleton class files to be created from a set of class files.
def set_item(key,value): """Write JSON content from value argument to cached file and return""" CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key) open(CACHED_KEY_FILE, "wb").write(json.dumps({"_": value}).encode('UTF-8')) return value
Write JSON content from value argument to cached file and return
def Shift(self, value, copy=False): """ Shift the graph left or right by value """ numPoints = self.GetN() if copy: shiftGraph = self.Clone() else: shiftGraph = self X = self.GetX() EXlow = self.GetEXlow() EXhigh = self.GetE...
Shift the graph left or right by value
def toggle(self, key): """ Toggles a boolean key """ val = self[key] assert isinstance(val, bool), 'key[%r] = %r is not a bool' % (key, val) self.pref_update(key, not val)
Toggles a boolean key
def check_sensor(self, helper): """ check the status of the specified sensor """ try: sensor_name, sensor_state, sensor_type = self.sess.get_oids( self.oids['oid_sensor_name'], self.oids['oid_sensor_state'], self.oids['oid_sensor_type']) except health_...
check the status of the specified sensor
def connect(self, sock): """Attach a given socket to a channel""" def cbwrap(*args, **kwargs): """Callback wrapper; passes in response_type""" self.callback(self.response_type, *args, **kwargs) self.sock = sock self.sock.subscribe(self.channel) self.sock....
Attach a given socket to a channel
def enum(number, zone='e164.arpa'): ''' Printable DNS ENUM (telephone number mapping) record. :param number: string :param zone: string >>> print(enum('+31 20 5423 1567')) 7.6.5.1.3.2.4.5.0.2.1.3.e164.arpa. >>> print(enum('+31 97 99 6642', zone='e164.spacephone.org')) 2.4.6.6.9.9.7.9....
Printable DNS ENUM (telephone number mapping) record. :param number: string :param zone: string >>> print(enum('+31 20 5423 1567')) 7.6.5.1.3.2.4.5.0.2.1.3.e164.arpa. >>> print(enum('+31 97 99 6642', zone='e164.spacephone.org')) 2.4.6.6.9.9.7.9.1.3.e164.spacephone.org.
def get_scanner_param_type(self, param): """ Returns type of a scanner parameter. """ assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return None return entry.get('type')
Returns type of a scanner parameter.
def check(text): """Check the text.""" err = "consistency.spacing" msg = "Inconsistent spacing after period (1 vs. 2 spaces)." regex = ["[\.\?!] [A-Z]", "[\.\?!] [A-Z]"] return consistency_check(text, [regex], err, msg)
Check the text.
def AskFileForSave(message=None, savedFileName=None, version=None, defaultLocation=None, dialogOptionFlags=None, location=None, clientName=None, windowTitle=None, actionButtonLabel=None, cancelButtonLabel=None, preferenceKey=None, popupExtension=None, eventProc=None, fileType=None, fileCreator=None, wanted=None, multip...
Original doc: Display a dialog asking the user for a filename to save to. wanted is the return type wanted: FSSpec, FSRef, unicode or string (default) the other arguments can be looked up in Apple's Navigation Services documentation
def fake_print(self): ''' This is the overridden __str__ method for Operation Recursively prints out the actual query to be executed ''' def _fake_run(): kwargs = self.kwargs.copy() kwargs['generate'] = True return _fake_handle_result( getattr(self.migrator, self....
This is the overridden __str__ method for Operation Recursively prints out the actual query to be executed
def minify_ring(mol, verbose=False): """ Minify ring set (similar to SSSR) Limitation: this can not correctly recognize minimum rings in the case of non-outerplanar graph. Note: concept of SSSR is controversial. Roughly reduce the size of cycle basis can help some scaffold-based analysis """ ...
Minify ring set (similar to SSSR) Limitation: this can not correctly recognize minimum rings in the case of non-outerplanar graph. Note: concept of SSSR is controversial. Roughly reduce the size of cycle basis can help some scaffold-based analysis
def minute_trend_times(start, end): """Expand a [start, end) interval for use in querying for minute trends NDS2 requires start and end times for minute trends to be a multiple of 60 (to exactly match the time of a minute-trend sample), so this function expands the given ``[start, end)`` interval to th...
Expand a [start, end) interval for use in querying for minute trends NDS2 requires start and end times for minute trends to be a multiple of 60 (to exactly match the time of a minute-trend sample), so this function expands the given ``[start, end)`` interval to the nearest multiples. Parameters --...
def solve_limited(self, assumptions=[]): """ Solve internal formula using given budgets for conflicts and propagations. """ if self.minisat: if self.use_timer: start_time = time.clock() # saving default SIGINT handler ...
Solve internal formula using given budgets for conflicts and propagations.
def to_indra_statements(graph): """Export this graph as a list of INDRA statements using the :py:class:`indra.sources.pybel.PybelProcessor`. :param pybel.BELGraph graph: A BEL graph :rtype: list[indra.statements.Statement] """ from indra.sources.bel import process_pybel_graph pbp = process_pyb...
Export this graph as a list of INDRA statements using the :py:class:`indra.sources.pybel.PybelProcessor`. :param pybel.BELGraph graph: A BEL graph :rtype: list[indra.statements.Statement]
def connect(): """Try to connect to the router. Returns: u (miniupnc.UPnP): the connected upnp-instance router (string): the connection information """ upnp = miniupnpc.UPnP() upnp.discoverdelay = 200 providers = upnp.discover() if providers > 1: log.debug('multiple ...
Try to connect to the router. Returns: u (miniupnc.UPnP): the connected upnp-instance router (string): the connection information
def single(fun, name, test=None, queue=False, **kwargs): ''' Execute a single state function with the named kwargs, returns False if insufficient data is sent to the command By default, the values of the kwargs will be parsed as YAML. So, you can specify lists values, or lists of single entry key-v...
Execute a single state function with the named kwargs, returns False if insufficient data is sent to the command By default, the values of the kwargs will be parsed as YAML. So, you can specify lists values, or lists of single entry key-value maps, as you would in a YAML salt file. Alternatively, JSON ...
async def destroy_async(self): """Asynchronously close any open management Links and close the Session. Cleans up and C objects for both mgmt Links and Session. """ for _, link in self._mgmt_links.items(): await link.destroy_async() self._session.destroy()
Asynchronously close any open management Links and close the Session. Cleans up and C objects for both mgmt Links and Session.
def _processHandler(self, securityHandler, param_dict): """proceses the handler and returns the cookiejar""" cj = None handler = None if securityHandler is None: cj = cookiejar.CookieJar() elif securityHandler.method.lower() == "token": param_dict['token']...
proceses the handler and returns the cookiejar
def parse_args(parser, modules, args=None): """Set up global configuration for command-line tools. `modules` is an iterable of :class:`yakonfig.Configurable` objects, or anything equivalently typed. This function iterates through those objects and calls :meth:`~yakonfig.Configurable.add_argume...
Set up global configuration for command-line tools. `modules` is an iterable of :class:`yakonfig.Configurable` objects, or anything equivalently typed. This function iterates through those objects and calls :meth:`~yakonfig.Configurable.add_arguments` on each to build up a complete list of com...
def teardown_websocket(self, func: Callable) -> Callable: """Add a teardown websocket function to the Blueprint. This is designed to be used as a decorator, and has the same arguments as :meth:`~quart.Quart.teardown_websocket`. It applies only to requests that are routed to an endpoint ...
Add a teardown websocket function to the Blueprint. This is designed to be used as a decorator, and has the same arguments as :meth:`~quart.Quart.teardown_websocket`. It applies only to requests that are routed to an endpoint in this blueprint. An example usage, .. code-block::...
def isCollapsed( self ): """ Returns whether or not this group box is collapsed. :return <bool> """ if not self.isCollapsible(): return False if self._inverted: return self.isChecked() return not self.isChec...
Returns whether or not this group box is collapsed. :return <bool>
def extract_child_models_of_state(state_m, new_state_class): """Retrieve child models of state model The function extracts the child state and state element models of the given state model into a dict. It only extracts those properties that are required for a state of type `new_state_class`. Transitions ar...
Retrieve child models of state model The function extracts the child state and state element models of the given state model into a dict. It only extracts those properties that are required for a state of type `new_state_class`. Transitions are always left out. :param state_m: state model of which childre...
def get_transactions_filtered(self, asset_id, operation=None): """Get a list of transactions filtered on some criteria """ txids = backend.query.get_txids_filtered(self.connection, asset_id, operation) for txid in txids: yield ...
Get a list of transactions filtered on some criteria
def _ingest_source(self, source, ps, force=None): """Ingest a single source""" from ambry.bundle.process import call_interval try: from ambry.orm.exc import NotFoundError if not source.is_partition and source.datafile.exists: if not source.datafile.is_...
Ingest a single source
def drop(self, table): """ Drop a table from the schema. :param table: The table :type table: str """ blueprint = self._create_blueprint(table) blueprint.drop() self._build(blueprint)
Drop a table from the schema. :param table: The table :type table: str
def allowPatternsForNameChecking(self, patternsFunc, patternsClass): """ Allow name exceptions by given patterns. @param patternsFunc: patterns of special function names @param patternsClass: patterns of special class names """ cfgParser = self.linter.cfgfile_parser ...
Allow name exceptions by given patterns. @param patternsFunc: patterns of special function names @param patternsClass: patterns of special class names
def describe_instances(self, xml_bytes): """ Parse the reservations XML payload that is returned from an AWS describeInstances API call. Instead of returning the reservations as the "top-most" object, we return the object that most developers and their code will be inter...
Parse the reservations XML payload that is returned from an AWS describeInstances API call. Instead of returning the reservations as the "top-most" object, we return the object that most developers and their code will be interested in: the instances. In instances reservation is availabl...
def host(proxy=None): ''' This grain is set by the NAPALM grain module only when running in a proxy minion. When Salt is installed directly on the network device, thus running a regular minion, the ``host`` grain provides the physical hostname of the network device, as it would be on an ordi...
This grain is set by the NAPALM grain module only when running in a proxy minion. When Salt is installed directly on the network device, thus running a regular minion, the ``host`` grain provides the physical hostname of the network device, as it would be on an ordinary minion server. When runni...
def put(self, local, remote, contents=None, quiet=False): """ Puts a local file (or contents) on to the FTP server local can be: a string: path to inpit file a file: opened for reading None: contents are pushed """ remote_dir = os.path...
Puts a local file (or contents) on to the FTP server local can be: a string: path to inpit file a file: opened for reading None: contents are pushed
def fetchGroupInfo(self, *group_ids): """ Get groups' info from IDs, unordered :param group_ids: One or more group ID(s) to query :return: :class:`models.Group` objects, labeled by their ID :rtype: dict :raises: FBchatException if request failed """ threa...
Get groups' info from IDs, unordered :param group_ids: One or more group ID(s) to query :return: :class:`models.Group` objects, labeled by their ID :rtype: dict :raises: FBchatException if request failed
def add_tour_step(self, message, selector=None, name=None, title=None, theme=None, alignment=None, duration=None): """ Allows the user to add tour steps for a website. @Params message - The message to display. selector - The CSS Selector of the Element t...
Allows the user to add tour steps for a website. @Params message - The message to display. selector - The CSS Selector of the Element to attach to. name - If creating multiple tours at the same time, use this to select the tour you wish to add steps to....
def run(self): """Run tracking dependencies """ self.msg.resolving() self.repositories() if self.find_pkg: self.dependencies_list.reverse() self.requires = Utils().dimensional_list(self.dependencies_list) self.dependencies = Utils().remove_dbs(...
Run tracking dependencies
def original_query_sequence_length(self): """Similar to get_get_query_sequence_length, but it also includes hard clipped bases if there is no cigar, then default to trying the sequence :return: the length of the query before any clipping :rtype: int """ if not self.is_aligned() or not self....
Similar to get_get_query_sequence_length, but it also includes hard clipped bases if there is no cigar, then default to trying the sequence :return: the length of the query before any clipping :rtype: int
def dir(cls, label, children): """Return ``FSEntry`` directory object.""" return FSEntry(label=label, children=children, type=u"Directory", use=None)
Return ``FSEntry`` directory object.
def evaluate_tour_P(self, tour): """ Use Cythonized version to evaluate the score of a current tour, with better precision on the distance of the contigs. """ from .chic import score_evaluate_P return score_evaluate_P(tour, self.active_sizes, self.P)
Use Cythonized version to evaluate the score of a current tour, with better precision on the distance of the contigs.
def from_file(cls, filename): """ Read an Fiesta input from a file. Currently tested to work with files generated from this class itself. Args: filename: Filename to parse. Returns: FiestaInput object """ with zopen(filename) as f: ...
Read an Fiesta input from a file. Currently tested to work with files generated from this class itself. Args: filename: Filename to parse. Returns: FiestaInput object
def update_asset_content(self, asset_content_form): """Updates an existing asset content. arg: asset_content_form (osid.repository.AssetContentForm): the form containing the elements to be updated raise: IllegalState - ``asset_content_form`` already used in an ...
Updates an existing asset content. arg: asset_content_form (osid.repository.AssetContentForm): the form containing the elements to be updated raise: IllegalState - ``asset_content_form`` already used in an update transaction raise: InvalidArgument - the form...
def draw_build_target(self, surf): """Draw the build target.""" round_half = lambda v, cond: round(v - 0.5) + 0.5 if cond else round(v) queued_action = self._queued_action if queued_action: radius = queued_action.footprint_radius if radius: pos = self.get_mouse_pos() if pos:...
Draw the build target.
def update_metadata_filters(metadata, jupyter_md, cell_metadata): """Update or set the notebook and cell metadata filters""" cell_metadata = [m for m in cell_metadata if m not in ['language', 'magic_args']] if 'cell_metadata_filter' in metadata.get('jupytext', {}): metadata_filter = metadata_filte...
Update or set the notebook and cell metadata filters
def handle_padding(self, padding): '''Pads the image with transparent pixels if necessary.''' left = padding[0] top = padding[1] right = padding[2] bottom = padding[3] offset_x = 0 offset_y = 0 new_width = self.engine.size[0] new_height = self.eng...
Pads the image with transparent pixels if necessary.
def _load_cached_tlds(self): """ Loads TLDs from cached file to set. :return: Set of current TLDs :rtype: set """ # check if cached file is readable if not os.access(self._tld_list_path, os.R_OK): self._logger.error("Cached file is not readable for c...
Loads TLDs from cached file to set. :return: Set of current TLDs :rtype: set
def bySignificator(self, ID): """ Returns all directions to a significator. """ res = [] for direction in self.table: if ID in direction[2]: res.append(direction) return res
Returns all directions to a significator.
def plot_eval_results(eval_results, metric=None, xaxislabel=None, yaxislabel=None, title=None, title_fontsize='x-large', axes_title_fontsize='large', show_metric_direction=True, metric_direction_font_size='large', subplots_opts=None, subplots_adjust_opts...
Plot the evaluation results from `eval_results`. `eval_results` must be a sequence containing `(param, values)` tuples, where `param` is the parameter value to appear on the x axis and `values` can be a dict structure containing the metric values. `eval_results` can be created using the `results_by_parameter` f...
def add_tooltip_to_highlighted_item(self, index): """ Add a tooltip showing the full path of the currently highlighted item of the PathComboBox. """ self.setItemData(index, self.itemText(index), Qt.ToolTipRole)
Add a tooltip showing the full path of the currently highlighted item of the PathComboBox.
def iter_following(username, number=-1, etag=None): """List the people ``username`` follows. :param str username: (required), login of the user :param int number: (optional), number of users being followed by username to return. Default: -1, return all of them :param str etag: (optional), ETag ...
List the people ``username`` follows. :param str username: (required), login of the user :param int number: (optional), number of users being followed by username to return. Default: -1, return all of them :param str etag: (optional), ETag from a previous request to the same endpoint :r...
def _set_people(self, people): """ Sets who the object is sent to """ if hasattr(people, "object_type"): people = [people] elif hasattr(people, "__iter__"): people = list(people) return people
Sets who the object is sent to
def get_hosts(self): """ Return a list of parsed hosts info, with the limit applied if required. """ limited_hosts = {} if self.limit is not None: # Find hosts and groups of hosts to include for include in self.limit['include']: # Include w...
Return a list of parsed hosts info, with the limit applied if required.
def do_response(self, response_args=None, request=None, **kwargs): """ **Placeholder for the time being** :param response_args: :param request: :param kwargs: request arguments :return: Response information """ links = [Link(href=h, rel=OIC_ISSUER) for h...
**Placeholder for the time being** :param response_args: :param request: :param kwargs: request arguments :return: Response information
def _update_resource_view(self, log=False): # type: () -> bool """Check if resource view exists in HDX and if so, update resource view Returns: bool: True if updated and False if not """ update = False if 'id' in self.data and self._load_from_hdx('resource vi...
Check if resource view exists in HDX and if so, update resource view Returns: bool: True if updated and False if not
def wp_status(self): '''show status of wp download''' try: print("Have %u of %u waypoints" % (self.wploader.count()+len(self.wp_received), self.wploader.expected_count)) except Exception: print("Have %u waypoints" % (self.wploader.count()+len(self.wp_received)))
show status of wp download
def auth(self, request): """ let's auth the user to the Service """ client = self.get_evernote_client() request_token = client.get_request_token(self.callback_url(request)) # Save the request token information for later request.session['oauth_token'] = request...
let's auth the user to the Service
def create_char(self, location, bitmap): """Create a new character. The HD44780 supports up to 8 custom characters (location 0-7). :param location: The place in memory where the character is stored. Values need to be integers between 0 and 7. :type location: int :pa...
Create a new character. The HD44780 supports up to 8 custom characters (location 0-7). :param location: The place in memory where the character is stored. Values need to be integers between 0 and 7. :type location: int :param bitmap: The bitmap containing the character. Thi...
def closed(self) -> bool: '''Return whether the connection is closed.''' return not self.writer or not self.reader or self.reader.at_eof()
Return whether the connection is closed.
def create_tar (archive, compression, cmd, verbosity, interactive, filenames): """Create a TAR archive.""" cmdlist = [cmd, '-c'] add_star_opts(cmdlist, compression, verbosity) cmdlist.append("file=%s" % archive) cmdlist.extend(filenames) return cmdlist
Create a TAR archive.
def write(self): """Write the current queue to a file. We need this to continue an earlier session.""" queue_path = os.path.join(self.config_dir, 'queue') queue_file = open(queue_path, 'wb+') try: pickle.dump(self.queue, queue_file, -1) except Exception: p...
Write the current queue to a file. We need this to continue an earlier session.
def connect(self, path="", headers=None, query=None, timeout=0, **kwargs): """ make the actual connection to the websocket :param headers: dict, key/val pairs of any headers to add to connection, if you would like to override headers just pass in an empty value :param query:...
make the actual connection to the websocket :param headers: dict, key/val pairs of any headers to add to connection, if you would like to override headers just pass in an empty value :param query: dict, any query string params you want to send up with the connection url ...
def validate(self, data): """Validate the data against the schema. """ validator = self._schema.validator(self._id) validator.validate(data)
Validate the data against the schema.
def shutdown_request(self, request): """ Called to shutdown and close an individual request. """ try: request.shutdown(socket.SHUT_WR) except socket.error: pass self.close_request(request)
Called to shutdown and close an individual request.
def run(self): """ If the connection drops, then run_forever will terminate and a reconnection attempt will be made. """ while True: self.connect_lock.acquire() if self.stopped(): return self.__connect() self.connect...
If the connection drops, then run_forever will terminate and a reconnection attempt will be made.
def volumes(self): """This property prepares the list of volumes :return a list of volumes. """ return sys_volumes.VolumeCollection( self._conn, utils.get_subresource_path_by(self, 'Volumes'), redfish_version=self.redfish_version)
This property prepares the list of volumes :return a list of volumes.
def remove_parameter(self, param_id=None, name=None, ref_id=None, ): """ Removes parameters based on function arguments. This can remove parameters based on the following param values: param/@id param/@name param/@ref_id Each input is mutually exclus...
Removes parameters based on function arguments. This can remove parameters based on the following param values: param/@id param/@name param/@ref_id Each input is mutually exclusive. Calling this function with multiple values set will cause an IOCParseError ...
async def _write(self, path, data, *, flags=None, cas=None, acquire=None, release=None): """Sets the key to the given value. Returns: bool: ``True`` on success """ if not isinstance(data, bytes): raise ValueError("value must be bytes") ...
Sets the key to the given value. Returns: bool: ``True`` on success
def is_admin(): """ https://stackoverflow.com/a/19719292 @return: True if the current user is an 'Admin' whatever that means (root on Unix), otherwise False. Warning: The inner function fails unless you have Windows XP SP2 or higher. The failure causes a traceback to be printed and this func...
https://stackoverflow.com/a/19719292 @return: True if the current user is an 'Admin' whatever that means (root on Unix), otherwise False. Warning: The inner function fails unless you have Windows XP SP2 or higher. The failure causes a traceback to be printed and this function to return False.
def _LinearFoldByteStream(self, mapped_value, **unused_kwargs): """Folds the data type into a byte stream. Args: mapped_value (object): mapped value. Returns: bytes: byte stream. Raises: FoldingError: if the data type definition cannot be folded into the byte stream. "...
Folds the data type into a byte stream. Args: mapped_value (object): mapped value. Returns: bytes: byte stream. Raises: FoldingError: if the data type definition cannot be folded into the byte stream.
def _base_iterator( self, circuit: circuits.Circuit, qubit_order: ops.QubitOrderOrList, initial_state: Union[int, np.ndarray], perform_measurements: bool=True, ) -> Iterator['XmonStepResult']: """See definition in `cirq.SimulatesIntermediateState`. If the ini...
See definition in `cirq.SimulatesIntermediateState`. If the initial state is an int, the state is set to the computational basis state corresponding to this state. Otherwise if the initial state is a np.ndarray it is the full initial state. In this case it must be the correct size, be ...