Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
381,500
def slideshow(self, **kwargs): for label, cycle in self.items(): cycle.plot(title=label, tight_layout=True)
Produce slides show of the different cycles. One plot per cycle.
381,501
def get_year(self): 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.
381,502
def fetch_aliases(self, seq_id, current_only=True, translate_ncbi_namespace=None): return [dict(r) for r in self.find_aliases(seq_id=seq_id, current_only=current_only, translate_ncbi_namespace=translat...
return list of alias annotation records (dicts) for a given seq_id
381,503
async def observer_orm_notify(self, message): @database_sync_to_async def get_observers(table): return list( Observer.objects.filter( dependencies__table=table, subscribers__isnull=False ) .distinct() ...
Process notification from ORM.
381,504
def _from_lattice_vectors(self): degreeConvsersion = 180.0 / np.pi vector_magnitudes = np.linalg.norm(self.lattice_vectors, axis=1) a_dot_b = np.dot(self.lattice_vectors[0], self.lattice_vectors[1]) b_dot_c = np.dot(self.lattice_vectors[1], self.lattice_vectors[2]) a_d...
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.
381,505
def _logger_levels(self): return { : logging.DEBUG, : logging.INFO, : logging.WARNING, : logging.ERROR, : logging.CRITICAL, }
Return log levels.
381,506
def get_conn(self): service = self.get_service() project = self._get_field() return BigQueryConnection( service=service, project_id=project, use_legacy_sql=self.use_legacy_sql, location=self.location, num_retries=self.num_retri...
Returns a BigQuery PEP 249 connection object.
381,507
def _prepare_app(self, app): obj = app[key] for name, pattern in obj.items(): obj[name] = self._prepare_pattern(obj[name])
Normalize app data, preparing it for the detection phase.
381,508
def run_mapper(self, stdin=sys.stdin, stdout=sys.stdout): self.init_hadoop() self.init_mapper() outputs = self._map_input((line[:-1] for line in stdin)) if self.reducer == NotImplemented: self.writer(outputs, stdout) else: self.internal_writer(out...
Run the mapper on the hadoop node.
381,509
def from_onnx(self, graph): self.model_metadata = self.get_graph_metadata(graph) for init_tensor in graph.initializer: if not init_tensor.name.strip(): raise ValueError("Tensor's name is required.") self._params[init_tensor.name] = self....
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...
381,510
def multisorted(items, *keys): if len(keys) == 0: keys = [asc()] for key in reversed(keys): items = sorted(items, key=key.func, reverse=key.reverse) return items
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 ...
381,511
def weight_from_comm(self, v, comm): return _c_louvain._MutableVertexPartition_weight_from_comm(self._partition, 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`
381,512
def merge_dicts(*dicts, **kwargs): cls = kwargs.get("cls", None) if cls is None: for d in dicts: if isinstance(d, dict): cls = d.__class__ break else: raise TypeError("cannot infer cls as none of the passed objects is of type dict...
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...
381,513
def _to_dict(self): _dict = {} if hasattr(self, ) and self.sentence is not None: _dict[] = self.sentence if hasattr(self, ) and self.subject is not None: _dict[] = self.subject._to_dict() if hasattr(self, ) and self.action is not None: _dict[]...
Return a json dictionary representing this model.
381,514
def _parse_v_parameters(val_type, val, filename, param_name): if val_type == "logical": val = [i == "T" for i in val.split()] elif val_type == "int": try: val = [int(i) for i in val.split()] except ValueError: val = _parse_from_incar...
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...
381,515
def get_nested_attribute(obj, attribute): parent, attr = resolve_nested_attribute(obj, attribute) if not parent is None: attr_value = getattr(parent, attr) else: attr_value = None return attr_value
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 ...
381,516
def check_length_of_shape_or_intercept_names(name_list, num_alts, constrained_param, list_title): if len(name_list) != (num_alts - constrained_param): msg_1 = "{} is of...
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...
381,517
def window_open_config(self, temperature, duration): _LOGGER.debug("Window open config, temperature: %s duration: %s", temperature, duration) self._verify_temperature(temperature) if duration.seconds < 0 and duration.seconds > 3600: raise ValueError value = struct.p...
Configures the window open behavior. The duration is specified in 5 minute increments.
381,518
def QA_SU_save_index_min(engine, client=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})
381,519
def write_json(obj, path): 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=) as target: target.write(obj_str)
Escribo un objeto a un archivo JSON con codificación UTF-8.
381,520
def random_choice(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.
381,521
def create_parser(subparsers): parser = subparsers.add_parser( , help=, usage="%(prog)s", add_help=False) args.add_titles(parser) parser.set_defaults(subcommand=) return parser
create parser
381,522
def quit(self): if self.is_running == True: warning_planarrad_running = QtGui.QMessageBox.warning(self.ui.quit, , "PlanarRad is running. Stop it before quit !", ...
This function quits PlanarRad, checking if PlanarRad is running before.
381,523
def setRandomParams(self): params = sp.randn(self.getNumberParams()) self.setParams(params)
set random hyperparameters
381,524
def _submit_request(self, url, params=None, data=None, headers=None, method="GET"): if headers is None: headers = {} if self._auth_header is not None: headers[] = self._auth_header try: if method == : result =...
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. ...
381,525
def get_suggested_field_names(type_: GraphQLOutputType, field_name: str) -> List[str]: if is_object_type(type_) or is_interface_type(type_): possible_field_names = list(type_.fields) return suggestion_list(field_name, possible_field_names) return []
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.
381,526
def get_tokens_list(self, registry_address: PaymentNetworkID): tokens_list = views.get_token_identifiers( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, ) return tokens_list
Returns a list of tokens the node knows about
381,527
def load_readers(filenames=None, reader=None, reader_kwargs=None, ppp_config_dir=None): reader_instances = {} reader_kwargs = reader_kwargs or {} reader_kwargs_without_filter = reader_kwargs.copy() reader_kwargs_without_filter.pop(, None) if ppp_config_dir is None: ppp...
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...
381,528
def disable_scanners_by_ids(self, scanner_ids): scanner_ids = .join(scanner_ids) self.logger.debug(.format(scanner_ids)) return self.zap.ascan.disable_scanners(scanner_ids)
Disable a list of scanner IDs.
381,529
def add_audio(self, customization_id, audio_name, audio_resource, contained_content_type=None, allow_overwrite=None, content_type=None, **kwargs): if customization_id is None: ...
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...
381,530
def write(self, data, mode=): 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()`
381,531
def coneSearch(self, center, radius=3*u.arcmin, magnitudelimit=25): self.magnitudelimit = magnitudelimit self.speak(.format(center, radius, magnitudelimit)) coordinatetosearch = .format(center) table = astroquery.mast.Catalogs.query_region(coordinates=center, radius...
Run a cone search of the GALEX archive
381,532
def pretty(price, currency, *, abbrev=True, trim=True): currency = validate_currency(currency) price = validate_price(price) space = if nospace(currency) else fmtstr = if trim: fmtstr = .format(price, x=decimals(currency)).rstrip().rstrip() else: fmtstr = .format(price).rstrip().rstrip() if abbrev: i...
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 ...
381,533
def refresh_all_states(self): header = BASE_HEADERS.copy() header[] = self.__cookie request = requests.get( BASE_URL + "refreshAllStates", headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False self.login() ...
Update all states.
381,534
def text(self, text): if text: if not isinstance(text, str): text = _pformat(text) text += self.m( , more=dict(len=len(text)) ) self.__message.attach(_MIMEText(text, , ))
.. seealso:: :attr:`text`
381,535
def add_alias(self, alias): aliases = self.list_aliases() if alias in aliases: logger.debug("Alias %s already exists on %s.", alias, self.anonymize_url(self.index_url)) return alias_data = % (self.index, alias) r = self.requests.post(self.url ...
Add an alias to the index set in the elastic obj :param alias: alias to add :returns: None
381,536
def _get_cl_dependency_code(self): 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.
381,537
def get_checkcode(cls, id_number_str): if len(id_number_str) != 17: return False, -1 id_regex = if not re.match(id_regex, id_number_str): return False, -1 items = [int(item) for item in id_number_str] factors = (7, 9, 10, 5...
计算身份证号码的校验位; :param: * id_number_str: (string) 身份证号的前17位,比如 3201241987010100 :returns: * 返回类型 (tuple) * flag: (bool) 如果身份证号格式正确,返回 True;格式错误,返回 False * checkcode: 计算身份证前17位的校验码 举例如下:: from fishbase.fish_data import * pri...
381,538
def namedlist(objname, fieldnames): class NamedListTemplate(list): __name__ = objname _fields = fieldnames def __init__(self, L=None, **kwargs): if L is None: L = [None]*len(fieldnames) super().__init__(L) for k, v in kwargs.items(): ...
like namedtuple but editable
381,539
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 ...
381,540
def connection_made(self, address): 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.
381,541
def restore_point(cls, cluster_id_label, s3_location, backup_id, table_names, overwrite=True, automatic=True): conn = Qubole.agent(version=Cluster.api_version) parameters = {} parameters[] = s3_location parameters[] = backup_id parameters[] = table_names paramete...
Restoring cluster from a given hbase snapshot id
381,542
def get_mathjax_header(https=False): if cfg[].lower() == : if https: mathjax_path = "https://d3eoax9i5htok0.cloudfront.net/mathjax/2.1-latest" else: mathjax_path = "http://cdn.mathjax.org/mathjax/2.1-latest" else: mathjax_path = "/vendors/MathJax" if cfg...
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...
381,543
def arcs(self): all_arcs = [] for l1, l2 in self.byte_parser._all_arcs(): fl1 = self.first_line(l1) fl2 = self.first_line(l2) if fl1 != fl2: all_arcs.append((fl1, fl2)) return sorted(all_arcs)
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.
381,544
def parse_dom(dom): root = dom.getElementsByTagName("graphml")[0] graph = root.getElementsByTagName("graph")[0] name = graph.getAttribute() g = Graph(name) for node in graph.getElementsByTagName("node"): n = g.a...
Parse dom into a Graph. :param dom: dom as returned by minidom.parse or minidom.parseString :return: A Graph representation
381,545
def display_png(*objs, **kwargs): raw = kwargs.pop(,False) if raw: for obj in objs: publish_png(obj) else: display(*objs, include=[,])
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...
381,546
def get_instance(self, payload): return AuthRegistrationsCredentialListMappingInstance( self._version, payload, account_sid=self._solution[], domain_sid=self._solution[], )
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 ...
381,547
def deleted(self): 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.
381,548
def input(self, data): self._lexer.lineno = 1 return self._lexer.input(data)
Reset the lexer and feed in new input. :param data: String of input data.
381,549
def on_excepthandler(self, node): return (self.run(node.type), node.name, node.body)
Exception handler...
381,550
def _get_on_crash(dom): * node = ElementTree.fromstring(get_xml(dom)).find() 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>
381,551
def get_issue_remotelinks(self, issue_key, global_id=None, internal_id=None): return self.get_issue_remote_links(issue_key, global_id, internal_id)
Compatibility naming method with get_issue_remote_links()
381,552
def resolve_url(url, directory=None, permissions=None): u = urlparse(url) if directory is None: directory = os.getcwd() filename = os.path.join(directory,os.path.basename(u.path)) if u.scheme == or u.scheme == : if os.path.isfile(u.path): if os.path.isf...
Resolves a URL to a local file, and returns the path to that file.
381,553
def handle_twitter_http_error(e, error_count, call_counter, time_window_start, wait_period): if e.error_code == 401: raise e elif e.error_code == 404: raise e elif e.error_code == 429: error_count += 0.5 call_counter = 0 wait_p...
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...
381,554
def getTextualNode(self, textId, subreference=None, prevnext=False, metadata=False): text = CtsText( urn=textId, retriever=self.endpoint ) if metadata or prevnext: return text.getPassagePlus(reference=subreference) else: return tex...
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 ...
381,555
def output_colored(code, text, is_bold=False): if is_bold: code = % code return % (code, text)
Create function to output with color sequence
381,556
def fromhdf5(source, where=None, name=None, condition=None, condvars=None, start=None, stop=None, step=None): return HDF5View(source, where=where, name=name, condition=condition, condvars=condvars, start=start, stop=stop, step=step)
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...
381,557
def load_array_elements(self, array, start_idx, no_of_elements): concrete_start_idxes = self.concretize_load_idx(start_idx) if len(concrete_start_idxes) == 1: concrete_start_idx = concrete_start_idxes[0] load_values = [self._load_array...
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.
381,558
def _get(self, scheme, host, port, path, assert_key=None): url = % (scheme, host, port, path) try: request = urllib2.Request(url) if self.config[] and self.config[]: base64string = base64.standard_b64encode( % (self.config[], self.co...
Execute a ES API call. Convert response into JSON and optionally assert its structure.
381,559
def export(self, class_name, method_name, export_data=False, export_dir=, export_filename=, export_append_checksum=False, **kwargs): self.class_name = class_name self.method_name = method_name est = self.estimator self.n_classes ...
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...
381,560
def convert_path(path): 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
381,561
def _threaded_start(self): 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
381,562
def _is_under_root(self, full_path): if (path.abspath(full_path) + path.sep)\ .startswith(path.abspath(self.root) + path.sep): return True else: return False
Guard against arbitrary file retrieval.
381,563
def value(self, x): 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.
381,564
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.
381,565
def _write_ini(source_dict, namespace_name=None, level=0, indent_size=4, output_stream=sys.stdout): options = [ value for value in source_dict.values() if isinstance(value, Option) ] options.sort(key=lambda x: x.name) indent...
this function prints the components of a configobj ini file. It is recursive for outputing the nested sections of the ini file.
381,566
def release(ctx, yes, latest): m = RepoManager(ctx.obj[]) api = m.github_repo() if latest: latest = api.releases.latest() if latest: click.echo(latest[]) elif m.can_release(): branch = m.info[] version = m.validate_version() name = % version ...
Create a new release in github
381,567
def status(queue, munin, munin_config): 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
381,568
def connect(self): self.logger.debug( "Connecting... (address = %s, port = %s, clientId = %s, username = %s)" % (self.address, self.port, self.clientId, self.username) ) try: self.connectEvent.clear() self.client.connect(self.address, port...
Connect the client to IBM Watson IoT Platform using the underlying Paho MQTT client # Raises ConnectionException: If there is a problem establishing the connection.
381,569
def split_on_condition(seq, condition): 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
381,570
def html5_serialize_simple_color(simple_color): red, green, blue = simple_color result = u format_string = result += format_string.format(red) result += format_string.format(green) result += format_string.format(blue) return result
Apply the serialization algorithm for a simple color from section 2.4.6 of HTML5.
381,571
def walk(self, top, topdown=True, ignore_file_handler=None): tree = self.git_object_by_path(top) if tree is None: raise IOError(errno.ENOENT, "No such file") for x in self._walk(tree, topdown): yield x
Directory tree generator. See `os.walk` for the docs. Differences: - no support for symlinks - it could raise exceptions, there is no onerror argument
381,572
def _restore_base_estimators(self, kernel_cache, out, X, cv): train_folds = {fold: train_index for fold, (train_index, _) in enumerate(cv)} for idx, fold, _, est in out: if idx in kernel_cache: if not hasattr(est, ): raise ValueError( ...
Restore custom kernel functions of estimators for predictions
381,573
def revise_helper(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
381,574
async def analog_write(self, pin, value): if PrivateConstants.ANALOG_MESSAGE + pin < 0xf0: command = [PrivateConstants.ANALOG_MESSAGE + pin, value & 0x7f, (value >> 7) & 0x7f] await self._send_command(command) else: await self.extended_...
Set the selected pin to the specified value. :param pin: PWM pin number :param value: Pin value (0 - 0x4000) :returns: No return value
381,575
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None): tz_offset = datetime_to_timezone( datetime.datetime.now(), tz=tz_from).strftime() tz_offset = tz_offset[:3] + + tz_offset[3:] date = parse_date(str(date_str) + tz_offset) if tz_from != tz_to: date = datetime_to_timezo...
get timezone as tz_offset
381,576
def dump_code(disassembly, pc = None, bLowercase = True, bits = None): if not disassembly: return table = Table(sep = )...
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...
381,577
def get_check(self, check): chk = self._check_manager.get(check) chk.set_entity(self) return chk
Returns an instance of the specified check.
381,578
def log_cdf_laplace(x, name="log_cdf_laplace"): with tf.name_scope(name): x = tf.convert_to_tensor(value=x, name="x") lower_solution = -np.log(2.) + x safe_exp_neg_x = tf.exp(-tf.abs(x)) upper_solution = tf.math.log1p(-0.5 * safe_exp_neg_x) return tf.wher...
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...
381,579
def fopen(name, mode=, buffering=-1): f = _fopen(name, mode, buffering) return _FileObjectThreadWithContext(f, mode, buffering)
Similar to Python's built-in `open()` function.
381,580
def remove_input_link(self, process_code, input_code): process = self.database[][process_code] exchanges = process[] initial_count = len(exchanges) new_exchanges = [e for e in exchanges if...
Remove an input (technosphere or biosphere exchange) from a process, resolving all parameter issues
381,581
def run(self, start_command_srv): if start_command_srv: self._command_server.start() self._drop_privs() self._task_runner.start() self._reg_sighandle...
Setup daemon process, start child forks, and sleep until events are signalled. `start_command_srv` Set to ``True`` if command server should be started.
381,582
def fetchallfirstvalues(self, sql: str, *args) -> List[Any]: rows = self.fetchall(sql, *args) return [row[0] for row in rows]
Executes SQL; returns list of first values of each row.
381,583
def _handle_template_param_value(self): 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.
381,584
def exception_log_and_respond(exception, logger, message, status_code): 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.
381,585
def cover(session): session.interpreter = session.install(, ) session.run(, , , ) session.run(, )
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.
381,586
def run_coroutine_threadsafe(coro, loop): if not asyncio.iscoroutine(coro): raise TypeError() future = concurrent.futures.Future() def callback(): try: _chain_future(asyncio.ensure_future(coro, loop=loop), future) except Exception as exc: if future.set_r...
Submit a coroutine object to a given event loop. Return a concurrent.futures.Future to access the result.
381,587
def add_bindings(self, g: Graph) -> "PrefixLibrary": 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
381,588
def _debug_check(self): old_end = 0 old_sort = "" for segment in self._list: if segment.start <= old_end and segment.sort == old_sort: raise AngrCFGError("Error in SegmentList: blocks are not merged") old_end = segment.end ...
Iterates over list checking segments with same sort do not overlap :raise: Exception: if segments overlap space with same sort
381,589
def Normal(cls, mean: , variance: , batch_size: Optional[int] = None) -> Tuple[Distribution, ]: if mean.scope != variance.scope: raise ValueError() loc = mean.tensor scale = tf.sqrt(variance.tensor) dist = tf.distributions.Normal(loc, scale) ...
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: ...
381,590
def _get_primary_index_in_altered_table(self, diff): primary_index = {} for index in self._get_indexes_in_altered_table(diff).values(): if index.is_primary(): primary_index = {index.get_name(): index} return primary_index
:param diff: The table diff :type diff: orator.dbal.table_diff.TableDiff :rtype: dict
381,591
def contains(self, column, value): df = self.df[self.df[column].str.contains(value) == True] if df is None: self.err("Can not select contained data") return self.df = df
Set the main dataframe instance to rows that contains a string value in a column
381,592
def setup(app): app.info() app.add_role(, ghissue_role) app.add_role(, ghissue_role) app.add_role(, ghuser_role) app.add_role(, ghcommit_role) app.add_config_value(, None, ) return
Install the plugin. :param app: Sphinx application context.
381,593
def cyan(cls, string, auto=False): return cls.colorize(, string, auto=auto)
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
381,594
def require_dataset(self, name, shape, dtype=None, exact=False, **kwargs): return self._write_op(self._require_dataset_nosync, name, shape=shape, dtype=dtype, exact=exact, **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 tuple of ints Array shape. dtype : string or dtype, optional ...
381,595
def submit_order(id_or_ins, amount, side, price=None, position_effect=None): order_book_id = assure_order_book_id(id_or_ins) env = Environment.get_instance() if ( env.config.base.run_type != RUN_TYPE.BACKTEST and env.get_instrument(order_book_id).type == "Future" ): if "88" ...
通用下单函数,策略可以通过该函数自由选择参数下单。 :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...
381,596
def called_alts_from_genotype(self): if not in self.FORMAT: return None genotype_indexes = set([int(x) for x in self.FORMAT[].split()]) alts = set() for i in genotype_indexes: if i == 0: alts.add(self.REF) else: ...
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
381,597
def get_2d_markers_linearized( self, component_info=None, data=None, component_position=None, index=None ): return self._get_2d_markers( data, component_info, component_position, index=index )
Get 2D linearized markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array.
381,598
def _create_table_and_update_context(node, context): schema_type_name = sql_context_helpers.get_schema_type_name(node, context) table = context.compiler_metadata.get_table(schema_type_name).alias() context.query_path_to_selectable[node.query_path] = table return table
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.
381,599
def vx(self,*args,**kwargs): out= self._orb.vx(*args,**kwargs) if len(out) == 1: return out[0] else: return out
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 ...