Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
368,800
def get_info(self, symbol, as_of=None): version = self._read_metadata(symbol, as_of=as_of, read_preference=None) handler = self._read_handler(version, symbol) if handler and hasattr(handler, ): return handler.get_info(version) return {}
Reads and returns information about the data stored for symbol Parameters ---------- symbol : `str` symbol name for the item as_of : `str` or int or `datetime.datetime` Return the data as it was as_of the point in time. `int` : specific version number...
368,801
def set_installed_packages(): global INSTALLED_PACKAGES, REQUIRED_VERSION if INSTALLED_PACKAGES: return if os.path.exists(BIN_PYTHON): pip = subprocess.Popen( (BIN_PYTHON, , , ), stdout=subprocess.PIPE, stderr=subprocess.PIPE ) (stdou...
Idempotently caches the list of packages installed in the virtualenv. Can be run safely before the virtualenv is created, and will be rerun afterwards.
368,802
def _writeStructureLink(self, link, fileObject, replaceParamFile): fileObject.write( % link.type) fileObject.write( % link.numElements) weirs = link.weirs culverts = link.culverts for weir in weirs: fileObject.write( % weir.type) ...
Write Structure Link to File Method
368,803
def _get_top_states(saltenv=): alt_states = [] try: returned = __salt__[]() for i in returned[saltenv]: alt_states.append(i) except Exception: raise return alt_states
Equivalent to a salt cli: salt web state.show_top
368,804
def _select_word_cursor(self): cursor = TextHelper(self.editor).word_under_mouse_cursor() if (self._previous_cursor_start != cursor.selectionStart() and self._previous_cursor_end != cursor.selectionEnd()): self._remove_decoration() self._add_decoration(cu...
Selects the word under the mouse cursor.
368,805
def _part_cls_for(cls, content_type): if content_type in cls.part_type_for: return cls.part_type_for[content_type] return cls.default_part_type
Return the custom part class registered for *content_type*, or the default part class if no custom class is registered for *content_type*.
368,806
def adult(display=False): dtypes = [ ("Age", "float32"), ("Workclass", "category"), ("fnlwgt", "float32"), ("Education", "category"), ("Education-Num", "float32"), ("Marital Status", "category"), ("Occupation", "category"), ("Relationship", "category"), ("Race", "category"), ("S...
Return the Adult census data in a nice package.
368,807
def setup(self): if self.dry_run is not True: self.client = self._get_client() self._disable_access_key()
Method runs the plugin
368,808
def do_AUTOCOMPLETE(cmd, s): s = list(preprocess_query(s))[0] keys = [k.decode() for k in DB.smembers(edge_ngram_key(s))] print(white(keys)) print(magenta(.format(len(keys))))
Shows autocomplete results for a given token.
368,809
def needs_renewal(name, window=None): acme.needs_renewaldev.example.comacme.certdev.example.comYour certificate is still good if window is not None and window in (, , True): return True return _renew_by(name, window) <= datetime.datetime.today()
Check if a certificate needs renewal :param name: CommonName of cert :param window: Window in days to renew earlier or True/force to just return True Code example: .. code-block:: python if __salt__['acme.needs_renewal']('dev.example.com'): __salt__['acme.cert']('dev.example.com'...
368,810
def replace_namespace_finalize(self, name, body, **kwargs): kwargs[] = True if kwargs.get(): return self.replace_namespace_finalize_with_http_info(name, body, **kwargs) else: (data) = self.replace_namespace_finalize_with_http_info(name, body, **kwargs) ...
replace_namespace_finalize # noqa: E501 replace finalize of the specified Namespace # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespace_finalize(name, body, async_req=...
368,811
def cross_fade(self): response = self.avTransport.GetCrossfadeMode([ (, 0), ]) cross_fade_state = response[] return bool(int(cross_fade_state))
bool: The speaker's cross fade state. True if enabled, False otherwise
368,812
def find_version(project, source, force_init): file_opener = FileOpener() finder = FindVersion(project, source, file_opener, force_init=force_init) if finder.PROJECT is None: raise TypeError("Next step will fail without project name") if not finder.validate_current_versions(): ...
Entry point to just find a version and print next :return:
368,813
def _analyze_indexed_fields(indexed_fields): result = {} for field_name in indexed_fields: if not isinstance(field_name, basestring): raise TypeError( % (field_name,)) if not in field_name: if field_name in result: raise ValueError( % field_name) result[field_name] = None e...
Internal helper to check a list of indexed fields. Args: indexed_fields: A list of names, possibly dotted names. (A dotted name is a string containing names separated by dots, e.g. 'foo.bar.baz'. An undotted name is a string containing no dots, e.g. 'foo'.) Returns: A dict whose keys are undotted ...
368,814
def assert_allclose(actual, desired, rtol=1.e-5, atol=1.e-8, err_msg=, verbose=True): r return assert_allclose_np(actual, desired, rtol=rtol, atol=atol, err_msg=err_msg, verbose=verbose)
r"""wrapper for numpy.testing.allclose with default tolerances of numpy.allclose. Needed since testing method has different values.
368,815
def update_user(self, user_id, **kwargs): api = self._get_api(iam.AccountAdminApi) user = User._create_request_map(kwargs) body = iam.UserUpdateReq(**user) return User(api.update_user(user_id, body))
Update user properties of specified user. :param str user_id: The ID of the user to update (Required) :param str username: The unique username of the user :param str email: The unique email of the user :param str full_name: The full name of the user :param str password: The pass...
368,816
def initialize_registry(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger): try: backend.reset(args.force) except ExistingBackendError: return 1 log.info("Resetting the index ...") backend.index.reset() try: backend.index.upload("reset", {}) exc...
Initialize the registry and the index. :param args: :class:`argparse.Namespace` with "backend", "args", "force" and "log_level". :param backend: Backend which is responsible for working with model files. :param log: Logger supplied by supply_backend :return: None
368,817
def needs_to_run(G, target, in_mem_shas, from_store, settings): force = settings["force"] sprint = settings["sprint"] if(force): sprint("Target rebuild is being forced so {} needs to run".format(target), level="verbose") return True node_dict = get_the_node_dict(G, t...
Determines if a target needs to run. This can happen in two ways: (a) If a dependency of the target has changed (b) If an output of the target is missing Args: The graph we are going to build The name of the target The dictionary of the current shas held in memory The dictio...
368,818
def filter_by_transcript_expression( self, transcript_expression_dict, min_expression_value=0.0): return self.filter_above_threshold( key_fn=lambda effect: effect.transcript_id, value_dict=transcript_expression_dict, threshold=min_...
Filters effects to those which have an associated transcript whose expression value in the transcript_expression_dict argument is greater than min_expression_value. Parameters ---------- transcript_expression_dict : dict Dictionary mapping Ensembl transcript IDs to e...
368,819
def _color(str_, fore_color=None, back_color=None, styles=None): _init_colorama() colored = "" if not styles: styles = [] if fore_color: colored += getattr(colorama.Fore, fore_color.upper(), ) if back_color: colored += getattr(colorama.Back, ba...
Return the string wrapped with the appropriate styling escape sequences. Args: str_ (str): The string to be wrapped. fore_color (str, optional): Any foreground color supported by the `Colorama`_ module. back_color (str, optional): Any background color supported by the `Colorama`_ ...
368,820
async def get_counts(self): fs = (hashtable.itemcounts() for hashtable in self.hashtables) return await asyncio.gather(*fs)
see :class:`datasketch.MinHashLSH`.
368,821
def replay_scope(self, sess): current_replay = self.replay(sess) try: self.set_replay(sess, True) yield finally: self.set_replay(sess, current_replay)
Enters a replay scope that unsets it at the end.
368,822
def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True): param_keys = set() param_str = [] for key, type_info, desc in zip(arg_names, arg_types, arg_descs): if key in param_keys and remove_dup: continue if key == : continue param_keys.add(ke...
Build argument docs in python style. arg_names : list of str Argument names. arg_types : list of str Argument type information. arg_descs : list of str Argument description information. remove_dup : boolean, optional Whether remove duplication or not. Returns ...
368,823
def invoke(invocation): (invocation.module_path, invocation.module_source) = get_module_data(invocation.module_name) planner = _get_planner(invocation) if invocation.wrap_async: response = _invoke_async_task(invocation, planner) elif planner.should_fork(): response = _invoke_i...
Find a Planner subclass corresnding to `invocation` and use it to invoke the module. :param Invocation invocation: :returns: Module return dict. :raises ansible.errors.AnsibleError: Unrecognized/unsupported module type.
368,824
def _MakeExecutable(self, metadata_script): mode = os.stat(metadata_script).st_mode os.chmod(metadata_script, mode | stat.S_IEXEC)
Add executable permissions to a file. Args: metadata_script: string, the path to the executable file.
368,825
def infer(self, sensationList, reset=True, objectName=None): self._unsetLearningMode() statistics = collections.defaultdict(list) if objectName is not None: if objectName not in self.objectRepresentationsL2: raise ValueError("The provided objectName was not given during" ...
Infer on a given set of sensations for a single object. The provided sensationList is a list of sensations, and each sensation is a mapping from cortical column to a tuple of three SDR's respectively corresponding to the locationInput, the coarseSensorInput, and the sensorInput. For example, the i...
368,826
def add_item(self, api_token, content, **kwargs): params = { : api_token, : content } return self._post(, params, **kwargs)
Add a task to a project. :param token: The user's login token. :type token: str :param content: The task description. :type content: str :param project_id: The project to add the task to. Default is ``Inbox`` :type project_id: str :param date_string: The deadline...
368,827
def write_question(self, question): self.write_name(question.name) self.write_short(question.type) self.write_short(question.clazz)
Writes a question to the packet
368,828
def get_singlesig_privkey(privkey_info, blockchain=, **blockchain_opts): if blockchain == : return btc_get_singlesig_privkey(privkey_info, **blockchain_opts) else: raise ValueError(.format(blockchain))
Given a private key bundle, get the (single) private key
368,829
def insert(self, rectangle): rectangle = np.asanyarray(rectangle, dtype=np.float64) for child in self.child: if child is not None: attempt = child.insert(rectangle) if attempt is not None: return attempt if self.occupied:...
Insert a rectangle into the bin. Parameters ------------- rectangle: (2,) float, size of rectangle to insert
368,830
def insert_base_bank_options(parser): def match_type(s): err_msg = "must be a number between 0 and 1 excluded, not %r" % s try: value = float(s) except ValueError: raise argparse.ArgumentTypeError(err_msg) if value <= 0 or value >= 1: raise a...
Adds essential common options for template bank generation to an ArgumentParser instance.
368,831
def _fix_dot_imports(not_consumed): names = {} for name, stmts in not_consumed.items(): if any( isinstance(stmt, astroid.AssignName) and isinstance(stmt.assign_type(), astroid.AugAssign) for stmt in stmts ): continue for stmt in s...
Try to fix imports with multiple dots, by returning a dictionary with the import names expanded. The function unflattens root imports, like 'xml' (when we have both 'xml.etree' and 'xml.sax'), to 'xml.etree' and 'xml.sax' respectively.
368,832
def wait_for_net(self, timeout=None, wait_polling_interval=None): if timeout is None: timeout = self._timeout if wait_polling_interval is None: wait_polling_interval = self._wait_polling_interval self._logger.info("Waiting for network connection") poll_w...
Wait for the device to be assigned an IP address. :param timeout: Maximum time to wait for an IP address to be defined :param wait_polling_interval: Interval at which to poll for ip address.
368,833
def _send_request(self, request, **kwargs): log.debug(LOG_CHECK, "Send request %s with %s", request, kwargs) log.debug(LOG_CHECK, "Request headers %s", request.headers) self.url_connection = self.session.send(request, **kwargs) self.headers = self.url_connection.headers ...
Send GET request.
368,834
def setup_argument_parser(): if not in os.environ: os.environ[] = str(shutil.get_terminal_size().columns) parser = argparse.ArgumentParser( prog=, formatter_class=argparse.RawDescriptionHelpFormatter, description=, add_help=False ) parser._negati...
Setup command line parser
368,835
def transform_file(ELEMS, ofname, EPO, TREE, opt): "transform/map the elements of this file and dump the output on " BED4_FRM = "%s\t%d\t%d\t%s\n" log.info("%s (%d) elements ..." % (opt.screen and "screening" or "transforming", ELEMS.shape[0])) with open(ofname, ) as out_fd: if opt.screen: ...
transform/map the elements of this file and dump the output on 'ofname
368,836
def _sorted_resource_labels(labels): head = [label for label in TOP_RESOURCE_LABELS if label in labels] tail = sorted(label for label in labels if label not in TOP_RESOURCE_LABELS) return head + tail
Sort label names, putting well-known resource labels first.
368,837
def db_file(self, value): assert not os.path.isfile(value), "%s already exists" % value self._db_file = value
Setter for _db_file attribute
368,838
def get_or_create( cls, name: sym.Symbol, module: types.ModuleType = None ) -> "Namespace": return cls._NAMESPACES.swap(Namespace.__get_or_create, name, module=module)[ name ]
Get the namespace bound to the symbol `name` in the global namespace cache, creating it if it does not exist. Return the namespace.
368,839
def emit_db_sequence_updates(engine): if engine and engine.name == : conn = engine.connect() qry = for (qry, qual_name) in list(conn.execute(qry)): (lastval, ) = conn.execute(qry).first() nextval = int(lastval) + 1 yield "ALTER SEQUENCE %s ...
Set database sequence objects to match the source db Relevant only when generated from SQLAlchemy connection. Needed to avoid subsequent unique key violations after DB build.
368,840
def find_by_b64ids(self, _ids, **kwargs): return self.find_by_ids([ObjectId(base64.b64decode(_id)) for _id in _ids], **kwargs)
Pass me a list of base64-encoded ObjectId
368,841
def get_or_create_edge(self, source: Node, target: Node, relation: str, bel: str, sha512: str, data: EdgeData, evidence: Optional[E...
Create an edge if it does not exist, or return it if it does. :param source: Source node of the relation :param target: Target node of the relation :param relation: Type of the relation between source and target node :param bel: BEL statement that describes the relation :param s...
368,842
def execute(self, proxy, method, args): try: result = getattr(proxy, method)(raw_xml=self.options.xml, *tuple(args)) except xmlrpc.ERRORS as exc: self.LOG.error("While calling %s(%s): %s" % (method, ", ".join(repr(i) for i in args), exc)) self.return_code = e...
Execute given XMLRPC call.
368,843
def reload(self): instance_pb = self._client.instance_admin_client.get_instance(self.name) self._update_from_pb(instance_pb)
Reload the metadata for this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_reload_instance] :end-before: [END bigtable_reload_instance]
368,844
def _attempt_command_recovery(command, ack, serial_conn): with serial_with_temp_timeout(serial_conn, RECOVERY_TIMEOUT) as device: response = _write_to_device_and_return(command, ack, device) if response is None: log.debug("No valid response during _attempt_command_recovery") raise R...
Recovery after following a failed write_and_return() atempt
368,845
def save_report_to_html(self): html = self.page().mainFrame().toHtml() if self.report_path is not None: html_to_file(html, self.report_path) else: msg = self.tr() raise InvalidParameterError(msg)
Save report in the dock to html.
368,846
def create_queue(self, queue_name, metadata=None, fail_on_exist=False, timeout=None): _validate_not_none(, queue_name) request = HTTPRequest() request.method = request.host = self._get_host() request.path = _get_path(queue_name) request.query = [(, _int_to_str(t...
Creates a queue under the given account. :param str queue_name: The name of the queue to create. A queue name must be from 3 through 63 characters long and may only contain lowercase letters, numbers, and the dash (-) character. The first and last letters in the queue ...
368,847
def merging_cli(debug=False): parser = argparse.ArgumentParser() parser.add_argument(, , help=) parser.add_argument(, , help=) parser.add_argument(, , help=) parser.add_argument(, , help=) parse...
simple commandline interface of the merging module. This function is called when you use the ``discoursegraphs`` application directly on the command line.
368,848
def gradient(self): grad = {} for i, f in enumerate(self._covariances): for varname, g in f.gradient().items(): grad[f"{self._name}[{i}].{varname}"] = g return grad
Sum of covariance function derivatives. Returns ------- dict ∂K₀ + ∂K₁ + ⋯
368,849
def make_pdb(self, ligands=True, alt_states=False, pseudo_group=False, header=True, footer=True): base_filters = dict(ligands=ligands, pseudo_group=pseudo_group) restricted_mol_types = [x[0] for x in base_filters.items() if not x[1]] in_groups = [x for x in self.filter_mol_types(restric...
Generates a PDB string for the Assembly. Parameters ---------- ligands : bool, optional If `True`, will include ligands in the output. alt_states : bool, optional If `True`, will include alternate conformations in the output. pseudo_group : bool, optional...
368,850
def _find_convertable_object(self, data): data = list(data) convertable_object_idxs = [ idx for idx, obj in enumerate(data) if obj.get() in self.pod_types.keys() ] if len(convertable_object_idxs) < 1: raise Exception("K...
Get the first instance of a `self.pod_types`
368,851
def strip_prefix(string, prefix, regex=False): if not isinstance(string, six.string_types) or not isinstance(prefix, six.string_types): msg = \ .format(s=type(string), p=type(prefix)) raise TypeError(msg) if not regex: prefix = re.escape(prefix) if not prefix.star...
Strip the prefix from the string If 'regex' is specified, prefix is understood as a regular expression.
368,852
def posterior_marginals(self, x, mask=None): with tf.name_scope("smooth"): x = tf.convert_to_tensor(value=x, name="x") (_, filtered_means, filtered_covs, predicted_means, predicted_covs, _, _) = self.forward_filter( x, mask=mask) (smoothed_means, smoothed_covs) = self.back...
Run a Kalman smoother to return posterior mean and cov. Note that the returned values `smoothed_means` depend on the observed time series `x`, while the `smoothed_covs` are independent of the observed series; i.e., they depend only on the model itself. This means that the mean values have shape `concat...
368,853
def user_in_group(user, group): if isinstance(group, Group): return user_is_superuser(user) or group in user.groups.all() elif isinstance(group, six.string_types): return user_is_superuser(user) or user.groups.filter(name=group).exists() raise TypeError(" argument must be a string or a ...
Returns True if the given user is in given group
368,854
def from_devanagari(self, data): from indic_transliteration import sanscript return sanscript.transliterate(data=data, _from=sanscript.DEVANAGARI, _to=self.name)
A convenience method
368,855
def version(self, value): if value is not None: assert type(value) is unicode, " attribute: type is not !".format( "version", value) self.__version = value
Setter for **self.__version** attribute. :param value: Attribute value. :type value: unicode
368,856
def getImports(pth): if not os.path.isfile(pth): pth = check_extract_from_egg(pth)[0][0] if is_win or is_cygwin: if pth.lower().endswith(".manifest"): return [] try: return _getImports_pe(pth) except Exception, exception: ...
Forwards to the correct getImports implementation for the platform.
368,857
def get(cont=None, path=None, local_file=None, return_bin=False, profile=None): swift_conn = _auth(profile) if cont is None: return swift_conn.get_account() if path is None: return swift_conn.get_container(cont) if return_bin is True: return swift_conn.get_object(cont, pa...
List the contents of a container, or return an object from a container. Set return_bin to True in order to retrieve an object wholesale. Otherwise, Salt will attempt to parse an XML response. CLI Example to list containers: .. code-block:: bash salt myminion swift.get CLI Example to list...
368,858
def someoneKnownSeen(self, home=None, camera=None): try: cam_id = self.cameraByName(camera=camera, home=home)[] except TypeError: logger.warning("personSeenByCamera: Camera name or home is unknown") return False if self.lastEvent[cam_id][] ==...
Return True if someone known has been seen
368,859
def numToDigits(num, places): s = str(num) if len(s) < places: return ("0" * (places - len(s))) + s elif len(s) > places: return s[len(s)-places: ] else: return s
Helper, for converting numbers to textual digits.
368,860
def comb_jit(N, k): INTP_MAX = np.iinfo(np.intp).max if N < 0 or k < 0 or k > N: return 0 if k == 0: return 1 if k == 1: return N if N == INTP_MAX: return 0 M = N + 1 nterms = min(k, N - k) val = 1 for j in range(1, nterms + 1): ...
Numba jitted function that computes N choose k. Return `0` if the outcome exceeds the maximum value of `np.intp` or if N < 0, k < 0, or k > N. Parameters ---------- N : scalar(int) k : scalar(int) Returns ------- val : scalar(int)
368,861
def _score_macro_average(self, n_classes): all_fpr = np.unique(np.concatenate([self.fpr[i] for i in range(n_classes)])) avg_tpr = np.zeros_like(all_fpr) for i in range(n_classes): avg_tpr += interp(all_fpr, self.fpr[i], self.tpr[i]) avg_t...
Compute the macro average scores for the ROCAUC curves.
368,862
def node_rank(self): nodes = self.postorder() node_rank = {} for node in nodes: max_rank = 0 for child in self[node].nodes(): some_rank = node_rank[child] + 1 max_rank = max(max_rank, some_rank) node_rank[node] = max_ra...
Returns the maximum rank for each **topological node** in the ``DictGraph``. The rank of a node is defined as the number of edges between the node and a node which has rank 0. A **topological node** has rank 0 if it has no incoming edges.
368,863
def fit_transform(self, X, **kwargs): tasklogger.log_start() self.fit(X) embedding = self.transform(**kwargs) tasklogger.log_complete() return embedding
Computes the diffusion operator and the position of the cells in the embedding space Parameters ---------- X : array, shape=[n_samples, n_features] input data with `n_samples` samples and `n_dimensions` dimensions. Accepted data types: `numpy.ndarray`, ...
368,864
def move_pos(self, line=1, column=1): return self.chained(move.pos(line=line, column=column))
Move the cursor to a new position. Default: line 1, column 1
368,865
def fhi_header(filename, ppdesc): lines = _read_nlines(filename, 4) try: header = _dict_from_lines(lines[:4], [0, 3, 6, 3]) except ValueError: header = _dict_from_lines(lines[:3], [0, 3, 6]) summary = lines[0] return NcAbinitHeader...
Parse the FHI abinit header. Example: Troullier-Martins psp for element Sc Thu Oct 27 17:33:22 EDT 1994 21.00000 3.00000 940714 zatom, zion, pspdat 1 1 2 0 2001 .00000 pspcod,pspxc,lmax,lloc,mmax,r2well 1.80626423934776 .22824404...
368,866
def _is_undefok(arg, undefok_names): if not arg.startswith(): return False if arg.startswith(): arg_without_dash = arg[2:] else: arg_without_dash = arg[1:] if in arg_without_dash: name, _ = arg_without_dash.split(, 1) else: name = arg_without_dash if name in undefok_names: return...
Returns whether we can ignore arg based on a set of undefok flag names.
368,867
def _create_extended_jinja_tags(self, nodes): jinja_a = None jinja_b = None ext_node = None ext_nodes = [] for node in nodes: if isinstance(node, EmptyLine): continue if node.has_children(): node.children = sel...
Loops through the nodes and looks for special jinja tags that contains more than one tag but only one ending tag.
368,868
def action_set(self, hostname=None, action=None, subdoms=None, *args): "Adds a hostname to the LB, or alters an existing one" usage = "set <hostname> <action> <subdoms> [option=value, ...]" if hostname is None: sys.stderr.write("You must supply a hostname.\n") sys.stderr....
Adds a hostname to the LB, or alters an existing one
368,869
def load_model_by_id(self, model_id): with open(os.path.join(self.path, str(model_id) + ".json")) as fin: json_str = fin.read().replace("\n", "") load_model = json_to_graph(json_str) return load_model
Get the model by model_id Parameters ---------- model_id : int model index Returns ------- load_model : Graph the model graph representation
368,870
def endpoint_get(service, region=None, profile=None, interface=None, **connection_args): v2v3 auth(profile, **connection_args) services = service_list(profile, **connection_args) if service not in services: return {: } service_id = services[service][] endpoints = endpoint_list(profile, *...
Return a specific endpoint (keystone endpoint-get) CLI Example: .. code-block:: bash salt 'v2' keystone.endpoint_get nova [region=RegionOne] salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne]
368,871
def append_instances(cls, inst1, inst2): msg = inst1.equal_headers(inst2) if msg is not None: raise Exception("Cannot appent instances: " + msg) result = cls.copy_instances(inst1) for i in xrange(inst2.num_instances): result.add_instance(inst2.get_instanc...
Merges the two datasets (one-after-the-other). Throws an exception if the datasets aren't compatible. :param inst1: the first dataset :type inst1: Instances :param inst2: the first dataset :type inst2: Instances :return: the combined dataset :rtype: Instances
368,872
def generate_filterbank_header(self, nchans=1, ): gp_head = self.read_first_header() fb_head = {} telescope_str = gp_head.get("TELESCOP", "unknown") if telescope_str in (, ): fb_head["telescope_id"] = 6 elif telescope_str in (, ): fb_head["telesc...
Generate a blimpy header dictionary
368,873
def _ActionDatabase(self, cmd, args = None, commit = True, error = True): goodlogging.Log.Info("DB", "Database Command: {0} {1}".format(cmd, args), verbosity=self.logVerbosity) with sqlite3.connect(self._dbPath) as db: try: if args is None: result = db.execute(cmd) else: ...
Do action on database. Parameters ---------- cmd : string SQL command. args : tuple [optional : default = None] Arguments to be passed along with the SQL command. e.g. cmd="SELECT Value FROM Config WHERE Name=?" args=(fieldName, ) commit : boolean [optional : default...
368,874
def set_servers(self, servers): self.servers = [_Host(s, self.debug, dead_retry=self.dead_retry, socket_timeout=self.socket_timeout, flush_on_reconnect=self.flush_on_reconnect) for s in servers] self._init_buckets()
Set the pool of servers used by this client. @param servers: an array of servers. Servers can be passed in two forms: 1. Strings of the form C{"host:port"}, which implies a default weight of 1. 2. Tuples of the form C{("host:port", weight)}, where C{weight} is an int...
368,875
def main(argv): import argparse description = parser = argparse.ArgumentParser(prog=, description=description) parser.add_argument(, nargs=, type=int, help=) parser.add_argument(, action=, default=False, required=False, help=) parser.add_argument(, action=, default=...
This function sets up a command-line option parser and then calls fetch_and_write_mrca to do all of the real work.
368,876
def forceupdate(self, *args, **kw): self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
Like a bulk :meth:`forceput`.
368,877
def post_process_images(self, doctree): super(AbstractSlideBuilder, self).post_process_images(doctree) relative_base = ( [] * doctree.attributes.get()[len(self.srcdir) + 1:].count() ) for node in doctree.traverse(nodes.image): if ...
Pick the best candidate for all image URIs.
368,878
def call_actions_parallel_future(self, service_name, actions, **kwargs): job_responses = self.call_jobs_parallel_future( jobs=({: service_name, : [action]} for action in actions), **kwargs ) def parse_results(results): for job in results: ...
This method is identical in signature and behavior to `call_actions_parallel`, except that it sends the requests and then immediately returns a `FutureResponse` instead of blocking waiting on responses and returning a generator. Just call `result(timeout=None)` on the future response to block for an ava...
368,879
def name2idfobject(idf, groupnamess=None, objkeys=None, **kwargs): if not objkeys: objkeys = idfobjectkeys(idf) for objkey in objkeys: idfobjs = idf.idfobjects[objkey.upper()] for idfobj in idfobjs: for key, val in kwargs.items(): try: ...
return the object, if the Name or some other field is known. send filed in **kwargs as Name='a name', Roughness='smooth' Returns the first find (field search is unordered) objkeys -> if objkeys=['ZONE', 'Material'], search only those groupnames -> not yet coded
368,880
def _set_sfm_walk(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=sfm_walk.sfm_walk, is_container=, presence=False, yang_name="sfm-walk", rest_name="sfm-walk", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=Tru...
Setter method for sfm_walk, mapped from YANG variable /sysmon/sfm_walk (container) If this variable is read-only (config: false) in the source YANG file, then _set_sfm_walk is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_sfm_walk() dire...
368,881
def _compute_vs30_star_factor(self, imt, vs30): v1 = self._compute_v1_factor(imt) vs30_star = vs30.copy() vs30_star[vs30_star >= v1] = v1 return vs30_star, v1
Compute and return vs30 star factor, equation 5, page 77.
368,882
def _obtain_api_token(self, username, password): data = self._request("POST", "auth/apitoken", {"username": username, "password": password}, reestablish_session=False) return data["api_token"]
Use username and password to obtain and return an API token.
368,883
def query_value(stmt, args=(), default=None): for row in query(stmt, args, TupleFactory): return row[0] return default
Execute a query, returning the first value in the first row of the result set. If the query returns no result set, a default value is returned, which is `None` by default.
368,884
def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs): if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_date, start, end)
Array or Matrix of random date generator. :returns: 1d or 2d array of datetime.date
368,885
def get_default_configfile_path(): base = homebase.user_config_dir( app_author=CONF_AUTHOR, app_name=CONF_APP, roaming=False, use_virtualenv=False, create=False) path = os.path.join(base, CONF_FILENAME) return path
Return the default configuration-file path. Typically returns a user-local configuration file; e.g: ``~/.config/dwave/dwave.conf``. Returns: str: Configuration file path. Examples: This example displays the default configuration file on an Ubuntu Unix system runnin...
368,886
def run(self, writer, reader): self._page_data = self.initialize_page_data() self._set_lastpage() if not self.term.is_a_tty: self._run_notty(writer) else: self._run_tty(writer, reader)
Pager entry point. In interactive mode (terminal is a tty), run until ``process_keystroke()`` detects quit keystroke ('q'). In non-interactive mode, exit after displaying all unicode points. :param writer: callable writes to output stream, receiving unicode. :type writer: call...
368,887
def search(self, query, fetch_messages=False, thread_limit=5, message_limit=5): data = {"query": query, "snippetLimit": thread_limit} j = self._post( self.req_url.SEARCH_MESSAGES, data, fix_request=True, as_json=True ) result = j["payload"]["search_snippets"][query] ...
Searches for messages in all threads :param query: Text to search for :param fetch_messages: Whether to fetch :class:`models.Message` objects or IDs only :param thread_limit: Max. number of threads to retrieve :param message_limit: Max. number of messages to retrieve :type threa...
368,888
def create(self, alpha_sender): data = values.of({: alpha_sender, }) payload = self._version.create( , self._uri, data=data, ) return AlphaSenderInstance(self._version, payload, service_sid=self._solution[], )
Create a new AlphaSenderInstance :param unicode alpha_sender: An Alphanumeric Sender ID string, up to 11 characters. :returns: Newly created AlphaSenderInstance :rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance
368,889
def setup_legacy_graph(native, options_bootstrapper, build_configuration): bootstrap_options = options_bootstrapper.bootstrap_options.for_global_scope() return EngineInitializer.setup_legacy_graph_extended( bootstrap_options.pants_ignore, bootstrap_options.pants_workdir, bootstrap_options...
Construct and return the components necessary for LegacyBuildGraph construction.
368,890
def _escaped(self): chars = self._token_info[] count = len(chars) if count and chars[count - 1] == self.ESCAPE: chars.pop() return True else: return False
Escape character is at end of accumulated token character list.
368,891
def raw(self): escape_dict = {: r, : r, : r, : r, : r, : r, : r, : r, \, ...
Try to transform str to raw str" ... this will not work every time
368,892
def get_search_for_slugs(self, slug): return _get_request(_SLUG_SEARCH.format(c_api=_C_API_BEGINNING, api=_API_VERSION, slug=_format_query(slug), at=self.access_token))
Search for a particular slug
368,893
def cd(path): _cdhist.append(pwd()) path = abspath(path) os.chdir(path) return path
Change working directory. Returns absolute path to new working directory.
368,894
def remove(self, item): self.items.pop(item) self._remove_dep(item) self.order = None self.changed(code_changed=True)
Remove an item from the list.
368,895
def update_or_create(cls, name, external_endpoint=None, vpn_site=None, trust_all_cas=True, with_status=False): if external_endpoint: for endpoint in external_endpoint: if not in endpoint: raise ValueError( ) ...
Update or create an ExternalGateway. The ``external_endpoint`` and ``vpn_site`` parameters are expected to be a list of dicts with key/value pairs to satisfy the respective elements create constructor. VPN Sites will represent the final state of the VPN site list. ExternalEndpoint that are ...
368,896
def prefetch(self, bucket, key): resource = entry(bucket, key) return self.__io_do(bucket, , resource)
镜像回源预取文件: 从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源,具体规格参考 http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html Args: bucket: 待获取资源所在的空间 key: 代获取资源文件名 Returns: 一个dict变量,成功返回NULL,失败返回{"error": "<errMsg string>"} 一个ResponseInfo对象
368,897
def get_object(cls, api_token): acct = cls(token=api_token) acct.load() return acct
Class method that will return an Account object.
368,898
def __objecthasfields(bunchdt, data, commdct, idfobject, places=7, **kwargs): for key, value in list(kwargs.items()): if not isfieldvalue( bunchdt, data, commdct, idfobject, key, value, places=places): return False return True
test if the idf object has the field values in kwargs
368,899
def get_value(self, dictionary): if html.is_html_input(dictionary): if self.field_name not in dictionary: if getattr(self.root, , False): return empty return self.default_empty_html ret = dictionary[se...
Given the *incoming* primitive data, return the value for this field that should be validated and transformed to a native value.