code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def slideshow(self, **kwargs): """ Produce slides show of the different cycles. One plot per cycle. """ for label, cycle in self.items(): cycle.plot(title=label, tight_layout=True)
Produce slides show of the different cycles. One plot per cycle.
def get_year(self): """ Return the year from the database in the format expected by the URL. """ year = super(BuildableDayArchiveView, self).get_year() fmt = self.get_year_format() dt = date(int(year), 1, 1) return dt.strftime(fmt)
Return the year from the database in the format expected by the URL.
def fetch_aliases(self, seq_id, current_only=True, translate_ncbi_namespace=None): """return list of alias annotation records (dicts) for a given seq_id""" return [dict(r) for r in self.find_aliases(seq_id=seq_id, current_only=current_only, ...
return list of alias annotation records (dicts) for a given seq_id
async def observer_orm_notify(self, message): """Process notification from ORM.""" @database_sync_to_async def get_observers(table): # Find all observers with dependencies on the given table. return list( Observer.objects.filter( depen...
Process notification from ORM.
def _from_lattice_vectors(self): """Calculate the angles between the vectors that define the lattice. _from_lattice_vectors will calculate the angles alpha, beta, and gamma from the Lattice object attribute lattice_vectors. """ degreeConvsersion = 180.0 / np.pi vector_m...
Calculate the angles between the vectors that define the lattice. _from_lattice_vectors will calculate the angles alpha, beta, and gamma from the Lattice object attribute lattice_vectors.
def _logger_levels(self): """Return log levels.""" return { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, }
Return log levels.
def get_conn(self): """ Returns a BigQuery PEP 249 connection object. """ service = self.get_service() project = self._get_field('project') return BigQueryConnection( service=service, project_id=project, use_legacy_sql=self.use_legacy_s...
Returns a BigQuery PEP 249 connection object.
def _prepare_app(self, app): """ Normalize app data, preparing it for the detection phase. """ # Ensure these keys' values are lists for key in ['url', 'html', 'script', 'implies']: try: value = app[key] except KeyError: ap...
Normalize app data, preparing it for the detection phase.
def run_mapper(self, stdin=sys.stdin, stdout=sys.stdout): """ Run the mapper on the hadoop node. """ self.init_hadoop() self.init_mapper() outputs = self._map_input((line[:-1] for line in stdin)) if self.reducer == NotImplemented: self.writer(outputs, ...
Run the mapper on the hadoop node.
def from_onnx(self, graph): """Construct symbol from onnx graph. Parameters ---------- graph : onnx protobuf object The loaded onnx graph Returns ------- sym :symbol.Symbol The returned mxnet symbol params : dict A dic...
Construct symbol from onnx graph. Parameters ---------- graph : onnx protobuf object The loaded onnx graph Returns ------- sym :symbol.Symbol The returned mxnet symbol params : dict A dict of name: nd.array pairs, used as pret...
def multisorted(items, *keys): """Sort by multiple attributes. Args: items: An iterable series to be sorted. *keys: Key objects which extract key values from the items. The first key will be the most significant, and the last key the least significant. If no key function...
Sort by multiple attributes. Args: items: An iterable series to be sorted. *keys: Key objects which extract key values from the items. The first key will be the most significant, and the last key the least significant. If no key functions are provided, the items ...
def weight_from_comm(self, v, comm): """ The total number of edges (or sum of weights) to node ``v`` from community ``comm``. See Also -------- :func:`~VertexPartition.MutableVertexPartition.weight_to_comm` """ return _c_louvain._MutableVertexPartition_weight_from_comm(self._partition, v, c...
The total number of edges (or sum of weights) to node ``v`` from community ``comm``. See Also -------- :func:`~VertexPartition.MutableVertexPartition.weight_to_comm`
def merge_dicts(*dicts, **kwargs): """ merge_dicts(*dicts, cls=None) Takes multiple *dicts* and returns a single merged dict. The merging takes place in order of the passed dicts and therefore, values of rear objects have precedence in case of field collisions. The class of the returned merged dict is c...
merge_dicts(*dicts, cls=None) Takes multiple *dicts* and returns a single merged dict. The merging takes place in order of the passed dicts and therefore, values of rear objects have precedence in case of field collisions. The class of the returned merged dict is configurable via *cls*. If it is *None*, the...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'sentence') and self.sentence is not None: _dict['sentence'] = self.sentence if hasattr(self, 'subject') and self.subject is not None: _dict['subject'] = self.s...
Return a json dictionary representing this model.
def _parse_v_parameters(val_type, val, filename, param_name): """ Helper function to convert a Vasprun array-type parameter into the proper type. Boolean, int and float types are converted. Args: val_type: Value type parsed from vasprun.xml. val: Actual string value parsed for vasprun.x...
Helper function to convert a Vasprun array-type parameter into the proper type. Boolean, int and float types are converted. Args: val_type: Value type parsed from vasprun.xml. val: Actual string value parsed for vasprun.xml. filename: Fullpath of vasprun.xml. Used for robust error handl...
def get_nested_attribute(obj, attribute): """ Returns the value of the given (possibly dotted) attribute for the given object. If any of the parents on the nested attribute's name path are `None`, the value of the nested attribute is also assumed as `None`. :raises AttributeError: If any attri...
Returns the value of the given (possibly dotted) attribute for the given object. If any of the parents on the nested attribute's name path are `None`, the value of the nested attribute is also assumed as `None`. :raises AttributeError: If any attribute access along the attribute path fails with ...
def check_length_of_shape_or_intercept_names(name_list, num_alts, constrained_param, list_title): """ Ensures that the length of the parameter names matches the number of pa...
Ensures that the length of the parameter names matches the number of parameters that will be estimated. Will raise a ValueError otherwise. Parameters ---------- name_list : list of strings. Each element should be the name of a parameter that is to be estimated. num_alts : int. Shoul...
def window_open_config(self, temperature, duration): """Configures the window open behavior. The duration is specified in 5 minute increments.""" _LOGGER.debug("Window open config, temperature: %s duration: %s", temperature, duration) self._verify_temperature(temperature) if dura...
Configures the window open behavior. The duration is specified in 5 minute increments.
def QA_SU_save_index_min(engine, client=DATABASE): """save index_min Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_index_min(client=client)
save index_min Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
def write_json(obj, path): """Escribo un objeto a un archivo JSON con codificación UTF-8.""" obj_str = text_type(json.dumps(obj, indent=4, separators=(",", ": "), ensure_ascii=False)) helpers.ensure_dir_exists(os.path.dirname(path)) with io.open(path, "w", encoding='...
Escribo un objeto a un archivo JSON con codificación UTF-8.
def random_choice(sequence): """ Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. """ return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence)
Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence.
def create_parser(subparsers): """ create parser """ parser = subparsers.add_parser( 'version', help='Display version', usage="%(prog)s", add_help=False) args.add_titles(parser) parser.set_defaults(subcommand='version') return parser
create parser
def quit(self): """ This function quits PlanarRad, checking if PlanarRad is running before. """ """ Nothing programmed for displaying a message box when the user clicks on the window cross in order to quit. """ if self.is_running == True: warning_pla...
This function quits PlanarRad, checking if PlanarRad is running before.
def setRandomParams(self): """ set random hyperparameters """ params = sp.randn(self.getNumberParams()) self.setParams(params)
set random hyperparameters
def _submit_request(self, url, params=None, data=None, headers=None, method="GET"): """Submits the given request, and handles the errors appropriately. Args: url (str): the request to send. params (dict): params to be passed along to get/post ...
Submits the given request, and handles the errors appropriately. Args: url (str): the request to send. params (dict): params to be passed along to get/post data (bytes): the data to include in the request. headers (dict): the headers to include in the request. ...
def get_suggested_field_names(type_: GraphQLOutputType, field_name: str) -> List[str]: """Get a list of suggested field names. For the field name provided, determine if there are any similar field names that may be the result of a typo. """ if is_object_type(type_) or is_interface_type(type_): ...
Get a list of suggested field names. For the field name provided, determine if there are any similar field names that may be the result of a typo.
def get_tokens_list(self, registry_address: PaymentNetworkID): """Returns a list of tokens the node knows about""" tokens_list = views.get_token_identifiers( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, ) return tokens_lis...
Returns a list of tokens the node knows about
def load_readers(filenames=None, reader=None, reader_kwargs=None, ppp_config_dir=None): """Create specified readers and assign files to them. Args: filenames (iterable or dict): A sequence of files that will be used to load data from. A ``dict`` object ...
Create specified readers and assign files to them. Args: filenames (iterable or dict): A sequence of files that will be used to load data from. A ``dict`` object should map reader names to a list of filenames for that reader. reader (str or list): The name of t...
def disable_scanners_by_ids(self, scanner_ids): """Disable a list of scanner IDs.""" scanner_ids = ','.join(scanner_ids) self.logger.debug('Disabling scanners with IDs {0}'.format(scanner_ids)) return self.zap.ascan.disable_scanners(scanner_ids)
Disable a list of scanner IDs.
def add_audio(self, customization_id, audio_name, audio_resource, contained_content_type=None, allow_overwrite=None, content_type=None, **kwargs): """ Add an audio resource. ...
Add an audio resource. Adds an audio resource to a custom acoustic model. Add audio content that reflects the acoustic characteristics of the audio that you plan to transcribe. You must use credentials for the instance of the service that owns a model to add an audio resource to it. Add...
def write(self, data, mode='w'): """ Write data to the file. `data` is the data to write `mode` is the mode argument to pass to `open()` """ with open(self.path, mode) as f: f.write(data)
Write data to the file. `data` is the data to write `mode` is the mode argument to pass to `open()`
def coneSearch(self, center, radius=3*u.arcmin, magnitudelimit=25): ''' Run a cone search of the GALEX archive ''' self.magnitudelimit = magnitudelimit # run the query self.speak('querying GALEX, centered on {} with radius {}'.format(center, radius, magnitudelimit)) ...
Run a cone search of the GALEX archive
def pretty(price, currency, *, abbrev=True, trim=True): """ return format price with symbol. Example format(100, 'USD') return '$100' pretty(price, currency, abbrev=True, trim=False) abbrev: True: print value + symbol. Symbol can either be placed before or after value False: print value + currency code. currency...
return format price with symbol. Example format(100, 'USD') return '$100' pretty(price, currency, abbrev=True, trim=False) abbrev: True: print value + symbol. Symbol can either be placed before or after value False: print value + currency code. currency code is placed behind value trim: True: trim float value ...
def refresh_all_states(self): """Update all states.""" header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get( BASE_URL + "refreshAllStates", headers=header, timeout=10) if request.status_code != 200: self.__logged_in = Fals...
Update all states.
def text(self, text): ''' .. seealso:: :attr:`text` ''' if text: if not isinstance(text, str): text = _pformat(text) text += '\n\n' self.m( 'add text to mail', more=dict(len=len(text)) ) ...
.. seealso:: :attr:`text`
def add_alias(self, alias): """Add an alias to the index set in the elastic obj :param alias: alias to add :returns: None """ aliases = self.list_aliases() if alias in aliases: logger.debug("Alias %s already exists on %s.", alias, self.anonymize_url(self.ind...
Add an alias to the index set in the elastic obj :param alias: alias to add :returns: None
def _get_cl_dependency_code(self): """Get the CL code for all the CL code for all the dependencies. Returns: str: The CL code with the actual code. """ code = '' for d in self._dependencies: code += d.get_cl_code() + "\n" return code
Get the CL code for all the CL code for all the dependencies. Returns: str: The CL code with the actual code.
def get_checkcode(cls, id_number_str): """ 计算身份证号码的校验位; :param: * id_number_str: (string) 身份证号的前17位,比如 3201241987010100 :returns: * 返回类型 (tuple) * flag: (bool) 如果身份证号格式正确,返回 True;格式错误,返回 False * checkcode: 计算身份证前17位的校验码 举例如下:: ...
计算身份证号码的校验位; :param: * id_number_str: (string) 身份证号的前17位,比如 3201241987010100 :returns: * 返回类型 (tuple) * flag: (bool) 如果身份证号格式正确,返回 True;格式错误,返回 False * checkcode: 计算身份证前17位的校验码 举例如下:: from fishbase.fish_data import * pri...
def namedlist(objname, fieldnames): 'like namedtuple but editable' class NamedListTemplate(list): __name__ = objname _fields = fieldnames def __init__(self, L=None, **kwargs): if L is None: L = [None]*len(fieldnames) super().__init__(L) ...
like namedtuple but editable
def InitializeNoPrompt(config=None, external_hostname = None, admin_password = None, mysql_hostname = None, mysql_port = None, mysql_username = None, mysql_password = None, ...
Initialize GRR with no prompts. Args: config: config object external_hostname: A hostname. admin_password: A password used for the admin user. mysql_hostname: A hostname used for establishing connection to MySQL. mysql_port: A port used for establishing connection to MySQL. mysql_username: A ...
def connection_made(self, address): """When a connection is made the proxy is available.""" self._proxy = PickleProxy(self.loop, self) for d in self._proxy_deferreds: d.callback(self._proxy)
When a connection is made the proxy is available.
def restore_point(cls, cluster_id_label, s3_location, backup_id, table_names, overwrite=True, automatic=True): """ Restoring cluster from a given hbase snapshot id """ conn = Qubole.agent(version=Cluster.api_version) parameters = {} parameters['s3_location'] = s3_location...
Restoring cluster from a given hbase snapshot id
def get_mathjax_header(https=False): """ Return the snippet of HTML code to put in HTML HEAD tag, in order to enable MathJax support. @param https: when using the CDN, whether to use the HTTPS URL rather than the HTTP one. @type https: bool @note: with new releases of MathJax, update thi...
Return the snippet of HTML code to put in HTML HEAD tag, in order to enable MathJax support. @param https: when using the CDN, whether to use the HTTPS URL rather than the HTTP one. @type https: bool @note: with new releases of MathJax, update this function toghether with $MJV variabl...
def arcs(self): """Get information about the arcs available in the code. Returns a sorted list of line number pairs. Line numbers have been normalized to the first line of multiline statements. """ all_arcs = [] for l1, l2 in self.byte_parser._all_arcs(): f...
Get information about the arcs available in the code. Returns a sorted list of line number pairs. Line numbers have been normalized to the first line of multiline statements.
def parse_dom(dom): """Parse dom into a Graph. :param dom: dom as returned by minidom.parse or minidom.parseString :return: A Graph representation """ root = dom.getElementsByTagName("graphml")[0] graph = root.getElementsByTagName("graph")[0] name = graph.getAttr...
Parse dom into a Graph. :param dom: dom as returned by minidom.parse or minidom.parseString :return: A Graph representation
def display_png(*objs, **kwargs): """Display the PNG representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw png data to display. raw : bool Are the data objects raw data or Python objects that need to be ...
Display the PNG representation of an object. Parameters ---------- objs : tuple of objects The Python objects to display, or if raw=True raw png data to display. raw : bool Are the data objects raw data or Python objects that need to be formatted before display? [default...
def get_instance(self, payload): """ Build an instance of AuthRegistrationsCredentialListMappingInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mappin...
Build an instance of AuthRegistrationsCredentialListMappingInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_registrations_mapping.auth_registrations_credential_list_mapping.AuthRegistrationsCredentialListMappingInstance ...
def deleted(self): """Get the deleted state. Returns: bool: Whether this item is deleted. """ return self.timestamps.deleted is not None and self.timestamps.deleted > NodeTimestamps.int_to_dt(0)
Get the deleted state. Returns: bool: Whether this item is deleted.
def input(self, data): """Reset the lexer and feed in new input. :param data: String of input data. """ # input(..) doesn't reset the lineno. We have to do that manually. self._lexer.lineno = 1 return self._lexer.input(data)
Reset the lexer and feed in new input. :param data: String of input data.
def on_excepthandler(self, node): # ('type', 'name', 'body') """Exception handler...""" return (self.run(node.type), node.name, node.body)
Exception handler...
def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else ''
Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain>
def get_issue_remotelinks(self, issue_key, global_id=None, internal_id=None): """ Compatibility naming method with get_issue_remote_links() """ return self.get_issue_remote_links(issue_key, global_id, internal_id)
Compatibility naming method with get_issue_remote_links()
def resolve_url(url, directory=None, permissions=None): """ Resolves a URL to a local file, and returns the path to that file. """ u = urlparse(url) # create the name of the destination file if directory is None: directory = os.getcwd() filename = os.path.join(directory,os.path...
Resolves a URL to a local file, and returns the path to that file.
def handle_twitter_http_error(e, error_count, call_counter, time_window_start, wait_period): """ This function handles the twitter request in case of an HTTP error. Inputs: - e: A twython.TwythonError instance to be handled. - error_count: Number of failed retries of the call until now. ...
This function handles the twitter request in case of an HTTP error. Inputs: - e: A twython.TwythonError instance to be handled. - error_count: Number of failed retries of the call until now. - call_counter: A counter that keeps track of the number of function calls in the current 15-minu...
def getTextualNode(self, textId, subreference=None, prevnext=False, metadata=False): """ Retrieve a text node from the API :param textId: CtsTextMetadata Identifier :type textId: str :param subreference: CapitainsCtsPassage Reference :type subreference: str :param prevne...
Retrieve a text node from the API :param textId: CtsTextMetadata Identifier :type textId: str :param subreference: CapitainsCtsPassage Reference :type subreference: str :param prevnext: Retrieve graph representing previous and next passage :type prevnext: boolean ...
def output_colored(code, text, is_bold=False): """ Create function to output with color sequence """ if is_bold: code = '1;%s' % code return '\033[%sm%s\033[0m' % (code, text)
Create function to output with color sequence
def fromhdf5(source, where=None, name=None, condition=None, condvars=None, start=None, stop=None, step=None): """ Provides access to an HDF5 table. E.g.:: >>> import petl as etl >>> import tables >>> # set up a new hdf5 table to demonstrate with ... h5file = tables....
Provides access to an HDF5 table. E.g.:: >>> import petl as etl >>> import tables >>> # set up a new hdf5 table to demonstrate with ... h5file = tables.open_file('example.h5', mode='w', ... title='Example file') >>> h5file.create_group('/', 'tes...
def load_array_elements(self, array, start_idx, no_of_elements): """ Loads either a single element or a range of elements from the array. :param array: Reference to the array. :param start_idx: Starting index for the load. :param no_of_elements: Number of elemen...
Loads either a single element or a range of elements from the array. :param array: Reference to the array. :param start_idx: Starting index for the load. :param no_of_elements: Number of elements to load.
def _get(self, scheme, host, port, path, assert_key=None): """ Execute a ES API call. Convert response into JSON and optionally assert its structure. """ url = '%s://%s:%i/%s' % (scheme, host, port, path) try: request = urllib2.Request(url) if self...
Execute a ES API call. Convert response into JSON and optionally assert its structure.
def export(self, class_name, method_name, export_data=False, export_dir='.', export_filename='data.json', export_append_checksum=False, **kwargs): """ Port a trained estimator to the syntax of a chosen programming language. Parameters ---------- ...
Port a trained estimator to the syntax of a chosen programming language. Parameters ---------- :param class_name : string The name of the class in the returned result. :param method_name : string The name of the method in the returned result. :par...
def convert_path(path): """ Convert path to a normalized format """ if os.path.isabs(path): raise Exception("Cannot include file with absolute path {}. Please use relative path instead".format((path))) path = os.path.normpath(path) return path
Convert path to a normalized format
def _threaded_start(self): ''' Spawns a worker thread to do the expiration checks ''' self.active = True self.thread = Thread(target=self._main_loop) self.thread.setDaemon(True) self.thread.start()
Spawns a worker thread to do the expiration checks
def _is_under_root(self, full_path): """Guard against arbitrary file retrieval.""" if (path.abspath(full_path) + path.sep)\ .startswith(path.abspath(self.root) + path.sep): return True else: return False
Guard against arbitrary file retrieval.
def value(self, x): """ converts an integer or FinitField.Value to a value of this FiniteField. """ return x if isinstance(x, FiniteField.Value) and x.field == self else FiniteField.Value(self, x)
converts an integer or FinitField.Value to a value of this FiniteField.
def mk_pools(things, keyfnc=lambda x: x): "Indexes a thing by the keyfnc to construct pools of things." pools = {} sthings = sorted(things, key=keyfnc) for key, thingz in groupby(sthings, key=keyfnc): pools.setdefault(key, []).extend(list(thingz)) return pools
Indexes a thing by the keyfnc to construct pools of things.
def _write_ini(source_dict, namespace_name=None, level=0, indent_size=4, output_stream=sys.stdout): """this function prints the components of a configobj ini file. It is recursive for outputing the nested sections of the ini file.""" options = [ value ...
this function prints the components of a configobj ini file. It is recursive for outputing the nested sections of the ini file.
def release(ctx, yes, latest): """Create a new release in github """ m = RepoManager(ctx.obj['agile']) api = m.github_repo() if latest: latest = api.releases.latest() if latest: click.echo(latest['tag_name']) elif m.can_release('sandbox'): branch = m.info['bra...
Create a new release in github
def status(queue, munin, munin_config): """List queued tasks aggregated by name""" if munin_config: return status_print_config(queue) queues = get_queues(queue) for queue in queues: status_print_queue(queue, munin=munin) if not munin: print('-' * 40)
List queued tasks aggregated by name
def connect(self): """ Connect the client to IBM Watson IoT Platform using the underlying Paho MQTT client # Raises ConnectionException: If there is a problem establishing the connection. """ self.logger.debug( "Connecting... (address = %s, port = %s,...
Connect the client to IBM Watson IoT Platform using the underlying Paho MQTT client # Raises ConnectionException: If there is a problem establishing the connection.
def split_on_condition(seq, condition): """Split a sequence into two iterables without looping twice""" l1, l2 = tee((condition(item), item) for item in seq) return (i for p, i in l1 if p), (i for p, i in l2 if not p)
Split a sequence into two iterables without looping twice
def html5_serialize_simple_color(simple_color): """ Apply the serialization algorithm for a simple color from section 2.4.6 of HTML5. """ red, green, blue = simple_color # 1. Let result be a string consisting of a single "#" (U+0023) # character. result = u'#' # 2. Convert the ...
Apply the serialization algorithm for a simple color from section 2.4.6 of HTML5.
def walk(self, top, topdown=True, ignore_file_handler=None): """Directory tree generator. See `os.walk` for the docs. Differences: - no support for symlinks - it could raise exceptions, there is no onerror argument """ tree = self.git_object_by_path(top) if tree...
Directory tree generator. See `os.walk` for the docs. Differences: - no support for symlinks - it could raise exceptions, there is no onerror argument
def _restore_base_estimators(self, kernel_cache, out, X, cv): """Restore custom kernel functions of estimators for predictions""" train_folds = {fold: train_index for fold, (train_index, _) in enumerate(cv)} for idx, fold, _, est in out: if idx in kernel_cache: if no...
Restore custom kernel functions of estimators for predictions
def revise_helper(query): """ given sql containing a "CREATE TABLE {table_name} AS ({query})" returns table_name, query """ match = re.search(extract_sql_regex, query, re.DOTALL | re.I) return match.group(1), match.group(2)
given sql containing a "CREATE TABLE {table_name} AS ({query})" returns table_name, query
async def analog_write(self, pin, value): """ Set the selected pin to the specified value. :param pin: PWM pin number :param value: Pin value (0 - 0x4000) :returns: No return value """ if PrivateConstants.ANALOG_MESSAGE + pin < 0xf0: command = [Priv...
Set the selected pin to the specified value. :param pin: PWM pin number :param value: Pin value (0 - 0x4000) :returns: No return value
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None): """ get timezone as tz_offset """ tz_offset = datetime_to_timezone( datetime.datetime.now(), tz=tz_from).strftime('%z') tz_offset = tz_offset[:3] + ':' + tz_offset[3:] date = parse_date(str(date_str) + tz_offset) if tz_from != ...
get timezone as tz_offset
def dump_code(disassembly, pc = None, bLowercase = True, bits = None): """ Dump a disassembly. Optionally mark where the program counter is. ...
Dump a disassembly. Optionally mark where the program counter is. @type disassembly: list of tuple( int, int, str, str ) @param disassembly: Disassembly dump as returned by L{Process.disassemble} or L{Thread.disassemble_around_pc}. @type pc: int @param pc: (Optional) Prog...
def get_check(self, check): """ Returns an instance of the specified check. """ chk = self._check_manager.get(check) chk.set_entity(self) return chk
Returns an instance of the specified check.
def log_cdf_laplace(x, name="log_cdf_laplace"): """Log Laplace distribution function. This function calculates `Log[L(x)]`, where `L(x)` is the cumulative distribution function of the Laplace distribution, i.e. ```L(x) := 0.5 * int_{-infty}^x e^{-|t|} dt``` For numerical accuracy, `L(x)` is computed in dif...
Log Laplace distribution function. This function calculates `Log[L(x)]`, where `L(x)` is the cumulative distribution function of the Laplace distribution, i.e. ```L(x) := 0.5 * int_{-infty}^x e^{-|t|} dt``` For numerical accuracy, `L(x)` is computed in different ways depending on `x`, ``` x <= 0: Lo...
def fopen(name, mode='r', buffering=-1): """Similar to Python's built-in `open()` function.""" f = _fopen(name, mode, buffering) return _FileObjectThreadWithContext(f, mode, buffering)
Similar to Python's built-in `open()` function.
def remove_input_link(self, process_code, input_code): """ Remove an input (technosphere or biosphere exchange) from a process, resolving all parameter issues """ # 1. find correct process # 2. find correct exchange # 3. remove that exchange # 4. check for parame...
Remove an input (technosphere or biosphere exchange) from a process, resolving all parameter issues
def run(self, start_command_srv): """ Setup daemon process, start child forks, and sleep until events are signalled. `start_command_srv` Set to ``True`` if command server should be started. """ if start_command_srv: # note, this must be e...
Setup daemon process, start child forks, and sleep until events are signalled. `start_command_srv` Set to ``True`` if command server should be started.
def fetchallfirstvalues(self, sql: str, *args) -> List[Any]: """Executes SQL; returns list of first values of each row.""" rows = self.fetchall(sql, *args) return [row[0] for row in rows]
Executes SQL; returns list of first values of each row.
def _handle_template_param_value(self): """Handle a template parameter's value at the head of the string.""" self._emit_all(self._pop()) self._context ^= contexts.TEMPLATE_PARAM_KEY self._context |= contexts.TEMPLATE_PARAM_VALUE self._emit(tokens.TemplateParamEquals())
Handle a template parameter's value at the head of the string.
def exception_log_and_respond(exception, logger, message, status_code): """Log an error and send jsonified respond.""" logger.error(message, exc_info=True) return make_response( message, status_code, dict(exception_type=type(exception).__name__, exception_message=str(exception)), ...
Log an error and send jsonified respond.
def cover(session): """Run the final coverage report. This outputs the coverage report aggregating coverage from the unit test runs (not system test runs), and then erases coverage data. """ session.interpreter = 'python3.6' session.install('coverage', 'pytest-cov') session.run('coverage', '...
Run the final coverage report. This outputs the coverage report aggregating coverage from the unit test runs (not system test runs), and then erases coverage data.
def run_coroutine_threadsafe(coro, loop): """Submit a coroutine object to a given event loop. Return a concurrent.futures.Future to access the result. """ if not asyncio.iscoroutine(coro): raise TypeError('A coroutine object is required') future = concurrent.futures.Future() def callbac...
Submit a coroutine object to a given event loop. Return a concurrent.futures.Future to access the result.
def add_bindings(self, g: Graph) -> "PrefixLibrary": """ Add bindings in the library to the graph :param g: graph to add prefixes to :return: PrefixLibrary object """ for prefix, namespace in self: g.bind(prefix.lower(), namespace) return self
Add bindings in the library to the graph :param g: graph to add prefixes to :return: PrefixLibrary object
def _debug_check(self): """ Iterates over list checking segments with same sort do not overlap :raise: Exception: if segments overlap space with same sort """ # old_start = 0 old_end = 0 old_sort = "" for segment in self._list: if segment.star...
Iterates over list checking segments with same sort do not overlap :raise: Exception: if segments overlap space with same sort
def Normal(cls, mean: 'TensorFluent', variance: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']: '''Returns a TensorFluent for the Normal sampling op with given mean and variance. Args: mean: The mean parameter of the Normal d...
Returns a TensorFluent for the Normal sampling op with given mean and variance. Args: mean: The mean parameter of the Normal distribution. variance: The variance parameter of the Normal distribution. batch_size: The size of the batch (optional). Returns: ...
def _get_primary_index_in_altered_table(self, diff): """ :param diff: The table diff :type diff: orator.dbal.table_diff.TableDiff :rtype: dict """ primary_index = {} for index in self._get_indexes_in_altered_table(diff).values(): if index.is_primary(...
:param diff: The table diff :type diff: orator.dbal.table_diff.TableDiff :rtype: dict
def contains(self, column, value): """ Set the main dataframe instance to rows that contains a string value in a column """ df = self.df[self.df[column].str.contains(value) == True] if df is None: self.err("Can not select contained data") return ...
Set the main dataframe instance to rows that contains a string value in a column
def setup(app): """Install the plugin. :param app: Sphinx application context. """ app.info('Initializing GitHub plugin') app.add_role('ghissue', ghissue_role) app.add_role('ghpull', ghissue_role) app.add_role('ghuser', ghuser_role) app.add_role('ghcommit', ghcommit_role) app.ad...
Install the plugin. :param app: Sphinx application context.
def cyan(cls, string, auto=False): """Color-code entire string. :param str string: String to colorize. :param bool auto: Enable auto-color (dark/light terminal). :return: Class instance for colorized string. :rtype: Color """ return cls.colorize('cyan', string, ...
Color-code entire string. :param str string: String to colorize. :param bool auto: Enable auto-color (dark/light terminal). :return: Class instance for colorized string. :rtype: Color
def require_dataset(self, name, shape, dtype=None, exact=False, **kwargs): """Obtain an array, creating if it doesn't exist. Other `kwargs` are as per :func:`zarr.hierarchy.Group.create_dataset`. Parameters ---------- name : string Array name. shape : int or ...
Obtain an array, creating if it doesn't exist. Other `kwargs` are as per :func:`zarr.hierarchy.Group.create_dataset`. Parameters ---------- name : string Array name. shape : int or tuple of ints Array shape. dtype : string or dtype, optional ...
def submit_order(id_or_ins, amount, side, price=None, position_effect=None): """ 通用下单函数,策略可以通过该函数自由选择参数下单。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param float amount: 下单量,需为正数 :param side: 多空方向,多(SIDE.BUY)或空(SIDE.SELL) :type side: :class:`~SIDE` enum ...
通用下单函数,策略可以通过该函数自由选择参数下单。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param float amount: 下单量,需为正数 :param side: 多空方向,多(SIDE.BUY)或空(SIDE.SELL) :type side: :class:`~SIDE` enum :param float price: 下单价格,默认为None,表示市价单 :param position_effect: 开平方向,开仓(POSITION...
def called_alts_from_genotype(self): '''Returns a set of the (maybe REF and) ALT strings that were called, using GT in FORMAT. Returns None if GT not in the record''' if 'GT' not in self.FORMAT: return None genotype_indexes = set([int(x) for x in self.FORMAT['GT'].split('/')...
Returns a set of the (maybe REF and) ALT strings that were called, using GT in FORMAT. Returns None if GT not in the record
def get_2d_markers_linearized( self, component_info=None, data=None, component_position=None, index=None ): """Get 2D linearized markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array. """ retu...
Get 2D linearized markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array.
def _create_table_and_update_context(node, context): """Create an aliased table for a SqlNode. Updates the relevant Selectable global context. Args: node: SqlNode, the current node. context: CompilationContext, global compilation state and metadata. Returns: Table, the newly a...
Create an aliased table for a SqlNode. Updates the relevant Selectable global context. Args: node: SqlNode, the current node. context: CompilationContext, global compilation state and metadata. Returns: Table, the newly aliased SQLAlchemy table.
def vx(self,*args,**kwargs): """ NAME: vx PURPOSE: return x velocity at time t INPUT: t - (optional) time at which to get the velocity (can be Quantity) vo= (Object-wide default) physical scale for velocities to use to convert (can be Qua...
NAME: vx PURPOSE: return x velocity at time t INPUT: t - (optional) time at which to get the velocity (can be Quantity) vo= (Object-wide default) physical scale for velocities to use to convert (can be Quantity) use_physical= use to override ...