Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
362,800
def validate(self, instance, value): if self.cast: value = bool(value) if not isinstance(value, BOOLEAN_TYPES): self.error(instance, value) return value
Checks if value is a boolean
362,801
def base_path(main_path, fmt): if not fmt: return os.path.splitext(main_path)[0] fmt = long_form_one_format(fmt) fmt_ext = fmt[] suffix = fmt.get() prefix = fmt.get() base, ext = os.path.splitext(main_path) if ext != fmt_ext: raise InconsistentPath(u"Notebook path was...
Given a path and options for a format (ext, suffix, prefix), return the corresponding base path
362,802
def get_bin(self): if self._lookup_session is None: mgr = get_provider_manager(, runtime=self._runtime, proxy=self._proxy) self._lookup_session = mgr.get_bin_lookup_session(proxy=getattr(self, "_proxy", None)) return self._lookup_session.get_bin(Id(self._my_map[]))
Gets the ``Bin`` at this node. return: (osid.resource.Bin) - the bin represented by this node *compliance: mandatory -- This method must be implemented.*
362,803
def isqrt(n): if n == 0: return n, 1 if n < 0: raise ValueError() a, b, c = 1, n, 1 def divisors(): yield 2 yield 3 k = 5 while k * k <= b: yield k k += 2 yield k k += 4 for k in...
given a non-negative integer n, return a pair (a,b) such that n = a * a * b where b is a square-free integer. If n is a perfect square, then a is its square root and b is one.
362,804
def get_security_group_dict(): client = get_ec2_client() response = client.describe_security_groups() assert is_good_response(response) result = OrderedDict() ec2 = get_ec2_resource() for security_group_response in response[]: key = get_name(security_group_response.get(, [])) if not key or key ...
Returns dictionary of named security groups {name: securitygroup}.
362,805
def solve_quadratic(a, b, c): discRoot = math.sqrt((b * b) - 4 * a * c) root1 = (-b - discRoot) / (2 * a) root2 = (-b + discRoot) / (2 * a) return (root1, root2)
>>> solve_quadratic(1.0, 2.0, 1.0) (-1.0, -1.0)
362,806
def bit_string_index(text): n = len(text) k = text.count("1") if text.count("0") != n - k: raise VisualizationError("s must be a string of 0 and 1") ones = [pos for pos, char in enumerate(text) if char == "1"] return lex_index(n, k, ones)
Return the index of a string of 0s and 1s.
362,807
def scale_dict_wet(C): return {k: v / _scale_dict[k] for k, v in C.items()}
To account for the fact that arXiv:Jenkins:2017jig uses a flavour non-redundant basis in contrast to WCxf, symmetry factors of two have to be introduced in several places for operators that are symmetric under the interchange of two currents.
362,808
def filter_keys(d, keys, use_wildcards=False, list_of_dicts=False, deepcopy=True): list_of_dicts = if list_of_dicts else None flatd = flatten(d, list_of_dicts=list_of_dicts) def is_in(a, bs): if use_wildcards: for b in bs: try: i...
filter dict by certain keys Parameters ---------- d : dict keys: list use_wildcards : bool if true, can use * (matches everything) and ? (matches any single character) list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy valu...
362,809
def find_substring(substring, suffix_tree, edge_repo): assert isinstance(substring, str) assert isinstance(suffix_tree, SuffixTree) assert isinstance(edge_repo, EventSourcedRepository) if not substring: return -1 if suffix_tree.case_insensitive: substring = substring.lower() ...
Returns the index if substring in tree, otherwise -1.
362,810
def _libvirt_creds(): g_cmd = u_cmd = try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split()[1] except IndexError: ...
Returns the user and group that the disk images should be owned by
362,811
def get_default_user_groups(self, **kwargs): kwargs[] = True if kwargs.get(): return self.get_default_user_groups_with_http_info(**kwargs) else: (data) = self.get_default_user_groups_with_http_info(**kwargs) return data
Get default user groups customer preferences # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_default_user_groups(async_req=True) >>> result = thread.get() ...
362,812
def extract_files(filename, includes): lines = open(filename).readlines() files = {} lines = [l.strip() for l in lines if in l] for l in lines: matchedfile = re.search(](.+?)["\, l) if matchedfile is None: matchedfile = re.se...
Extract the files to be added based on the includes
362,813
def broadcast(self, command, *args, **kwargs): criterion = kwargs.pop(, self.BROADCAST_FILTER_ALL) for index, user in items(self.users()): if criterion(user, command, *args, **kwargs): self.notify(user, command, *args, **kwargs)
Notifies each user with a specified command.
362,814
def _extract_image_urls(arg: Message_T) -> List[str]: arg_as_msg = Message(arg) return [s.data[] for s in arg_as_msg if s.type == and in s.data]
Extract all image urls from a message-like object.
362,815
def _log_prefix(self, prefix, request): cached_guid_response = self._cache.get_cached_response(self.guid_key) cached_guid = cached_guid_response.get_value_or_default(u"without_guid") return u"{} request ".format(prefix, request.method, request.path, cached_gui...
Returns a formatted prefix for logging for the given request.
362,816
def create(self, bucket, descriptor, force=False): buckets = bucket if isinstance(bucket, six.string_types): buckets = [bucket] descriptors = descriptor if isinstance(descriptor, dict): descriptors = [descriptor] for bucket in ...
https://github.com/frictionlessdata/tableschema-pandas-py#storage
362,817
def get_issue(self, number): assert isinstance(number, (int, long)), number headers, data = self._requester.requestJsonAndCheck( "GET", self.url + "/issues/" + str(number) ) return github.Issue.Issue(self._requester, headers, data, completed=True)
:calls: `GET /repos/:owner/:repo/issues/:number <http://developer.github.com/v3/issues>`_ :param number: integer :rtype: :class:`github.Issue.Issue`
362,818
def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params): X_train, y_train = _safe_split(est, x, y, train_index) train_params = fit_params.copy() est.set_params(**parameters) est.fit(X_train, y_train, **train_params) test_predict_params ...
Train survival model on given data and return its score on test data
362,819
def MigrateArtifacts(): artifacts = data_store.REL_DB.ReadAllArtifacts() if artifacts: logging.info("Deleting %d artifacts from REL_DB.", len(artifacts)) for artifact in data_store.REL_DB.ReadAllArtifacts(): data_store.REL_DB.DeleteArtifact(Text(artifact.name)) else: logging.info("No arti...
Migrates Artifacts from AFF4 to REL_DB.
362,820
def delete_subscription(self, subscription_id): url = self.SUBSCRIPTIONS_ID_URL % subscription_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
Delete single subscription
362,821
def locale_negotiator(request): locale = if request.accept_language: locale = request.accept_language.best_match(LANGUAGES) locale = LANGUAGES.get(locale, ) return locale
Locale negotiator base on the `Accept-Language` header
362,822
def _unarmor(pem_bytes): if not isinstance(pem_bytes, byte_cls): raise TypeError(unwrap( , _type_name(pem_bytes) )) state = headers = {} base64_data = b object_type = None found_start = False found_end = False for line in pem_bytes.s...
Convert a PEM-encoded byte string into one or more DER-encoded byte strings :param pem_bytes: A byte string of the PEM-encoded data :raises: ValueError - when the pem_bytes do not appear to be PEM-encoded bytes :return: A generator of 3-element tuples in the format: (object_type, ...
362,823
def _njobs(self): ret = super(self.__class__, self)._njobs or [0] ret[0] += 1 return ret
%(InteractiveBase._njobs)s
362,824
def isobaric_expansion_l(self): rdodecane dV_dT = self.VolumeLiquid.TP_dependent_property_derivative_T(self.T, self.P) Vm = self.Vml if dV_dT and Vm: return isobaric_expansion(V=Vm, dV_dT=dV_dT)
r'''Isobaric (constant-pressure) expansion of the liquid phase of the chemical at its current temperature and pressure, in units of [1/K]. .. math:: \beta = \frac{1}{V}\left(\frac{\partial V}{\partial T} \right)_P Utilizes the temperature-derivative method of :obj:`thermo.v...
362,825
def getOneMessage ( self ): ( mbytes, hbytes ) = self._findMessageBytes ( self.buffer ) if not mbytes: return None msgdata = self.buffer[:mbytes] self.buffer = self.buffer[mbytes:] hdata = msgdata[:hbytes] elems = hdata.split ( ) cmd...
I pull one complete message off the buffer and return it decoded as a dict. If there is no complete message in the buffer, I return None. Note that the buffer can contain more than once message. You should therefore call me in a loop until I return None.
362,826
def setProperty(self, prop, *args, **kwargs): f = self.__setAttrs.get(prop) if not f: raise KeyError( % prop) f(self, *args, **kwargs)
Set the value of a property by sending an event on the root window. See the corresponding method for the required arguments. For example, for the property _NET_WM_STATE, look for :meth:`setWmState`
362,827
def symlink_to(self, target, target_is_directory=False): if self._closed: self._raise_closed() self._accessor.symlink(target, self, target_is_directory)
Make this path a symlink pointing to the given path. Note the order of arguments (self, target) is the reverse of os.symlink's.
362,828
def fill_tree(comments): if not comments: return it = iter(comments) first = next(it) extra_path_items = imap(_mark_as_root_path, first.root_path) return chain(extra_path_items, [first], it)
Insert extra comments in the comments list, so that the root path of the first comment is always visible. Use this in comments' pagination to fill in the tree information. The inserted comments have an ``added_path`` attribute.
362,829
def get_new_working_set(self): new_list_of_ips = None while True: try: new_list_of_ips = self.q_monitor_ips.get_nowait() self.q_monitor_ips.task_done() if type(new_list_of_ips) is MonitorPluginStopSignal: raise Stop...
Get a new list of IPs to work with from the queue. This returns None if there is no update. Read all the messages from the queue on which we get the IP addresses that we have to monitor. We will ignore all of them, except the last one, since maybe we received two updates in a row, but ...
362,830
def save_and_close_attributes(self): if not self.saveable(): raise AttributeError("Cannot save attribute file without a valid file") if not self._db_closed: self._db_closed = True if not self._read_only: self.save_attributes() self...
Performs the same function as save_attributes but also closes the attribute file.
362,831
async def get_state_json( self, rr_state_builder: Callable[[, str, int], Awaitable[Tuple[str, int]]], fro: int, to: int) -> (str, int): LOGGER.debug( , rr_state_builder.__name__, fro, to) rv = awai...
Get rev reg state json, and its timestamp on the distributed ledger, from cached rev reg state frames list or distributed ledger, updating cache as necessary. Raise BadRevStateTime if caller asks for a state in the future. On return of any previously existing rev reg state frame, alway...
362,832
def tridiag(below=None, diag=None, above=None, name=None): def _pad(x): shape = tf.concat([tf.shape(input=x)[:-1], [1]], axis=0) z = tf.zeros(shape, dtype=x.dtype) return tf.concat([z, x, z], axis=-1) def _add(*x): s = None for y in x: if y is None: continue el...
Creates a matrix with values set above, below, and on the diagonal. Example: ```python tridiag(below=[1., 2., 3.], diag=[4., 5., 6., 7.], above=[8., 9., 10.]) # ==> array([[ 4., 8., 0., 0.], # [ 1., 5., 9., 0.], # [ 0., 2., 6., 10.], # ...
362,833
def detectUbuntuTablet(self): if UAgentInfo.deviceUbuntu in self.__userAgent \ and UAgentInfo.deviceTablet in self.__userAgent: return True return False
Return detection of an Ubuntu Mobile OS tablet Detects a tablet running the Ubuntu Mobile OS.
362,834
def get_reference(self, refobj): c = cmds.listConnections("%s.referencenode" % refobj, d=False) return c[0] if c else None
Return the reference node that the reftrack node is connected to or None if it is imported. :param refobj: the reftrack node to query :type refobj: str :returns: the reference node :rtype: str | None :raises: None
362,835
def d2gauss(x,m_y,sigma): return gauss(x,m_y,sigma)*[-1/sigma**2 + (n-m_y)**2/sigma**4 for n in x]
returns the second derivative of the gaussian with mean m_y, and standard deviation sigma, calculated at the points of x.
362,836
def search_list(kb, value=None, match_type=None, page=None, per_page=None, unique=False): page = page or 1 per_page = per_page or 10 if kb.kbtype == models.KnwKB.KNWKB_TYPES[]: query = api.query_kb_mappings( kbid=kb....
Search "mappings to" for knowledge.
362,837
def create_unclaimed_draft(self, test_mode=False, files=None, file_urls=None, draft_type=None, subject=None, message=None, signers=None, cc_email_addresses=None, signing_redirect_url=None, form_fields_per_document=None, metadata=None, use_preexisting_fields=False, allow_decline=False): d signing_re...
Creates a new Draft that can be claimed using the claim URL Creates a new Draft that can be claimed using the claim URL. The first authenticated user to access the URL will claim the Draft and will be shown either the "Sign and send" or the "Request signature" page with the Draft loaded...
362,838
def columnize(items, separator=, displaywidth=80): if not items : return matrix, info = compute_item_matrix(items, separator_size=len(separator), displaywidth=displaywidth) fmatrix = [filter(None, x) for x in matrix] sjoin = lambda x : separator.join([ y.ljust(w, ) for y, w in zip(x, info[...
Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. separator : str, optional [default is two spaces] The string that separates columns. displaywidth : int, optional [default is 80] Width ...
362,839
def normalize(rp_pyxb): def sort(r, a): d1_common.xml.sort_value_list_pyxb(_get_attr_or_list(r, a)) rp_pyxb.preferredMemberNode = set(_get_attr_or_list(rp_pyxb, )) - set( _get_attr_or_list(rp_pyxb, ) ) sort(rp_pyxb, ) sort(rp_pyxb, )
Normalize a ReplicationPolicy PyXB type in place. The preferred and blocked lists are sorted alphabetically. As blocked nodes override preferred nodes, and any node present in both lists is removed from the preferred list. Args: rp_pyxb : ReplicationPolicy PyXB object The object will be ...
362,840
def reload_using_spawn_wait(self): cmd_parts = [sys.executable] + sys.argv env_copy = os.environ.copy() interrupt_main() subprocess.call(cmd_parts, env=env_copy, close_fds=True) sys.exit(0)
Spawn a subprocess and wait until it finishes. :return: None.
362,841
def lte(max_value): def validate(value): if value > max_value: return e("{} is not less than or equal to {}", value, max_value) return validate
Validates that a field value is less than or equal to the value given to this validator.
362,842
def _WriteResponses(self, responses, cursor): query = ("INSERT IGNORE INTO flow_responses " "(client_id, flow_id, request_id, response_id, " "response, status, iterator, timestamp) VALUES ") templates = [] args = [] for r in responses: templates.append("(%s, %s, %s...
Builds the writes to store the given responses in the db.
362,843
def get_asset_spatial_assignment_session_for_repository(self, repository_id, proxy): if not repository_id: raise NullArgument() if not self.supports_asset_spatial_assignment() or not self.supports_visible_federation(): raise Unimplemented() try: from ...
Gets the session for assigning spatial coverage of an asset for the given repository. arg: repository_id (osid.id.Id): the Id of the repository arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetSpatialAssignmentSession) - an AssetSpatialAssignmen...
362,844
def process_hit_event(self, frame): if not self.enabled: return False, False self.hits += 1 if self.cond: try: if not eval_(self.cond, frame.f_globals, frame.f_locals): return False, False except E...
Return (stop_state, delete_temporary) at a breakpoint hit event.
362,845
def select(self, name): return PluginSet(self.group, name, [ plug for plug in self.plugins if plug.name == name])
Returns a new PluginSet that has only the plugins in this that are named `name`.
362,846
def getCollapseRequestsFn(self): collapseRequests_fn = self.config.collapseRequests if collapseRequests_fn is None: collapseRequests_fn = self.master.config.collapseRequests if collapseRequests_fn is None: collapseRequests_fn = True if ...
Helper function to determine which collapseRequests function to use from L{_collapseRequests}, or None for no merging
362,847
def logstart(self, logfname=None, loghead=None, logmode=None, log_output=False, timestamp=False, log_raw_input=False): if self.logfile is not None: raise RuntimeError( % self.logfname) if logfname is not None: self.logfname ...
Generate a new log-file with a default header. Raises RuntimeError if the log has already been started
362,848
def format(self, altitude=None, deg_char=, min_char=, sec_char=): latitude = "%s %s" % ( format_degrees(abs(self.latitude), symbols={ : deg_char, : min_char, : sec_char }), self.latitude >= 0 and or ) longitude = "%s %s" % ( ...
Format decimal degrees (DD) to degrees minutes seconds (DMS)
362,849
def calculate_weights(correlation_matrix, min_wt): np.fill_diagonal(correlation_matrix.values, np.nan) correlation_matrix = correlation_matrix.clip(lower=0) raw_weights = correlation_matrix.mean(axis=1) raw_weights = raw_weights.clip(lower=min_wt) weights = raw_weig...
Calculate a weight for each profile based on its correlation to other replicates. Negative correlations are clipped to 0, and weights are clipped to be min_wt at the least. Args: correlation_matrix (pandas df): Correlations between all replicates min_wt (float): Minimum raw weight when calculating ...
362,850
def sha1(self): with open(self.path, ) as f: return hashlib.sha1(f.read()).hexdigest()
SHA1 hash of the config file itself.
362,851
def load_npy_to_any(path=, name=): file_path = os.path.join(path, name) try: return np.load(file_path).item() except Exception: return np.load(file_path) raise Exception("[!] Fail to load %s" % file_path)
Load `.npy` file. Parameters ------------ path : str Path to the file (optional). name : str File name. Examples --------- - see tl.files.save_any_to_npy()
362,852
def AddUser(self, uid, username, active): user_path = % uid if user_path in mockobject.objects: raise dbus.exceptions.DBusException( % uid, name=MOCK_IFACE + ) self.AddObject(user_path, , { ...
Convenience method to add a user. Return the object path of the new user.
362,853
def kld(p1, p2): return np.sum(np.where(p1 != 0, p1 * np.log(p1 / p2), 0))
Compute Kullback-Leibler divergence between p1 and p2. It assumes that p1 and p2 are already normalized that each of them sums to 1.
362,854
def get_credentials(cmd_args): cmd_credentials = cmd_args.email, cmd_args.key if cmd_credentials != (None, None): cli_logger.debug() return cmd_credentials env_email, env_api_key = get_config_from_env() if env_email is not None: if e...
:return: The email and api_key to use to connect to TagCube. This function will try to get the credentials from: * Command line arguments * Environment variables * Configuration file It will return the first match, in the ord...
362,855
def calculate_ef_diff(ef_structure1, ef_structure2, fpf): ef1, tpf1 = calculate_ef(ef_structure1, fpf, ) ef2, tpf2 = calculate_ef(ef_structure2, fpf, ) var1a, var1d, s2_1 = calculate_ef_var(tpf1, fpf) var2a, var2d, s2_2 = calculate_ef_var(tpf2, fpf) covara, covard = calculate_ef_covar(ef_str...
returns the absolute value of the difference in enrichment factors and corresponding statistics. specifically, |ef1 - ef2|, the 95% confidence interval, and the 2-sided p-value :param score_structure_1: list [(id, best_score, best_query, status, net decoy count, net active count), ...,] :param score_structu...
362,856
def maskrcnn_upXconv_head(feature, num_category, num_convs, norm=None): assert norm in [None, ], norm l = feature with argscope([Conv2D, Conv2DTranspose], data_format=, kernel_initializer=tf.variance_scaling_initializer( scale=2.0, mode=, di...
Args: feature (NxCx s x s): size is 7 in C4 models and 14 in FPN models. num_category(int): num_convs (int): number of convolution layers norm (str or None): either None or 'GN' Returns: mask_logits (N x num_category x 2s x 2s):
362,857
def cosine_similarity(sentence1, sentence2, tf1, tf2, idf_metrics): unique_words1 = frozenset(sentence1) unique_words2 = frozenset(sentence2) common_words = unique_words1 & unique_words2 numerator = 0.0 for term in common_words: numerator += tf1[term]*tf2[te...
We compute idf-modified-cosine(sentence1, sentence2) here. It's cosine similarity of these two sentences (vectors) A, B computed as cos(x, y) = A . B / (|A| . |B|) Sentences are represented as vector TF*IDF metrics. :param sentence1: Iterable object where every item represents word ...
362,858
def cache(self): with open(self.cache_path, "wb") as f: cache = {self.CACHE_REFERENCE_LIST: self._references, self.CACHE_REFERENCE_TYPES: self.reference_types, self.CACHE_REFERENCE_TEMPLATES: self.reference_templates} pickle.dump(cache, ...
Cache the Zotero data.
362,859
def get_field_mapping(self, fields, index=None, doc_type=None, params=None): if fields in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument .") return self.transport.perform_request( "GET", _make_path(index, "_mapping", doc_type, "fie...
Retrieve mapping definition of a specific field. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-field-mapping.html>`_ :arg fields: A comma-separated list of fields :arg index: A comma-separated list of index names :arg doc_type: A comma-separated list of do...
362,860
def build_mmd(target_folder=DEFAULT_LIBRARY_DIR): mmd_dir = tempfile.mkdtemp() mmd_repo = pygit2.clone_repository(, mmd_dir, checkout_branch=) mmd_repo.init_submodules() mmd_repo.update_submodules() build_dir = os.path.join(mmd_dir, ) old_pwd = os.getc...
Build and install the MultiMarkdown shared library.
362,861
def resize_dimension(self, name, new_size): if name not in self.dimension_names: raise ValueError("Shape %s does not have dimension named %s" % (self, name)) return Shape( [Dimension(name, new_size) if d.name == name else d for d in self.dims])
Returns a copy where one dimension has a different size.
362,862
def absent(name, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): 127.0.0.1:2181) scheme Scheme to authenticate with (Default: ) username Username to authenticate (Default: None) password Password t...
Make sure znode is absent name path to znode version Specify the version which should be deleted Default: -1 (always match) recursive Boolean to indicate if children should be recursively deleted Default: False profile Configured Zookeeper profile to a...
362,863
def nps_surveys_1_update(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/nps-api/surveys api_path = "/api/v2/nps/surveys/1" return self.call(api_path, method="PUT", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/nps-api/surveys#update-survey
362,864
def do_hello(self, sin, sout, name=None): name = if name is None else + name r = requests.get( + name) sout.write(r.text + )
Using the /hello GET interface There is one optional argument, "name". This name argument must be provided with proper URL excape codes, like %20 for spaces.
362,865
def BMI(self, params): label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) def BMI_func(): if self.is_N_set(): self.register[] = self.labels[label] return BMI_func
BMI label Branch to the instruction at label if the N flag is set
362,866
def scenarios(self, generate_seed=False): seed = prime_numbers(1000) sweeps_all = self.experiment["sweeps"].keys() if "combinations" in self.experiment: if isinstance(self.experiment["combinations"], list): combinations_in_experiment = {" ": ...
Generator function. Spits out scenarios for this experiment
362,867
def get_block(name, data, newline="\n"): lines = itertools.dropwhile(not_eq(BLOCK_START % name), data) gen = itertools.takewhile(not_eq(BLOCK_END % name), tail(lines)) return gen if newline is None else newline.join(gen)
First block in a list of one line strings containing reStructuredText data. The result is as a joined string with the given newline, or a line generator if it's None. The BLOCK_START and BLOCK_END delimiters are selected with the given name and aren't included in the result.
362,868
def write(self, data, timeout_s=None): self.connected.wait(timeout_s) self.protocol.transport.write(data)
Write to serial port. Waits for serial connection to be established before writing. Parameters ---------- data : str or bytes Data to write to serial port. timeout_s : float, optional Maximum number of seconds to wait for serial connection to be ...
362,869
def updateSolutionTerminal(self): self.solution_terminal.vFunc = ValueFunc(self.cFunc_terminal_,self.CRRA) self.solution_terminal.vPfunc = MargValueFunc(self.cFunc_terminal_,self.CRRA) self.solution_terminal.vPPfunc = MargMargValueFunc(self.cFunc_terminal_,self.CRRA)
Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- none Returns ------- none
362,870
def to_file(self, filepath, codec=, mode=): self.tier_num = len(self.tiers) if mode in [, ]: with open(filepath, ) as f: def writebstr(s): try: bstr = s.encode() except UnicodeError: ...
Write the object to a file. :param str filepath: Path of the fil. :param str codec: Text encoding. :param string mode: Flag to for write mode, possible modes: 'n'/'normal', 's'/'short' and 'b'/'binary'
362,871
def rounding_full(number, is_population=False): if number < 1000 and not is_population: rounding_number = 1 elif number < 1000 and is_population: rounding_number = 10 elif number < 100000: rounding_number = 100 else: rounding_number = 1000 number = int(rounding...
This function performs a rigorous rounding. :param number: The amount to round. :type number: int, float :param is_population: If we should use the population rounding rule, #4062. :type is_population: bool :returns: result and rounding bracket. :rtype: (int, int)
362,872
def update_agent(self, agent_id, **kwargs): url = % agent_id agent = self._api._put(url, data=json.dumps(kwargs)) return Agent(**agent)
Updates an agent
362,873
def QueryUserDefinedFunctions(self, collection_link, query, options=None): if options is None: options = {} path = base.GetPathFromLink(collection_link, ) collection_id = base.GetResourceIdOrFullNameFromLink(collection_link) def fetch_fn(options): return...
Queries user defined functions in a collection. :param str collection_link: The link to the collection. :param (str or dict) query: :param dict options: The request options for the request. :return: Query Iterable of UDFs. :rtype: ...
362,874
def match(self, name, chamber=None): try: return self._manual[chamber][name] except KeyError: pass if chamber == : chamber = None try: return self._codes[chamber][name] except KeyError: pass if chambe...
If this matcher has uniquely seen a matching name, return its value. Otherwise, return None. If chamber is set then the search will be limited to legislators with matching chamber. If chamber is None then the search will be cross-chamber.
362,875
def fetch(self, method, uri, query=None, body=None, **kwargs): if not query: query = {} fetch_url = self.get_fetch_url(uri, query) args = [fetch_url] kwargs.setdefault("timeout", self.timeout) kwargs["headers"] = self.get_fetch_headers(method, kwargs.get("headers", {})...
wrapper method that all the top level methods (get, post, etc.) use to actually make the request
362,876
def list_loadbalancers_on_lbaas_agent(self, lbaas_agent, **_params): return self.get((self.agent_path + self.AGENT_LOADBALANCERS) % lbaas_agent, params=_params)
Fetches a list of loadbalancers hosted by the loadbalancer agent.
362,877
def _get_cubic_root(self): assert_array = [ tf.Assert( tf.logical_not(tf.is_nan(self._dist_to_opt_avg)), [self._dist_to_opt_avg,]), tf.Assert( tf.logical_not(tf.is_nan(self._h_min)), [self._h_min,]), ...
Get the cubic root.
362,878
def is_equal(self, other): properties = [ , , , , , , , , , , , , if self.debug_mode: if if_property == : ...
Equality checker with message :param other: Other Impact Function to be compared. :type other: ImpactFunction :returns: True if both are the same IF, other wise False and the message. :rtype: bool, str
362,879
def find_meta(meta): meta_match = re.search( r"^__{meta}__ = [\"]*)['\"]".format(meta=meta), META_FILE, re.M ) if meta_match: return meta_match.group(1) raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta))
Extract __*meta*__ from META_FILE.
362,880
def add(self, target, args=None, kwargs=None, **options): from furious.async import Async from furious.batcher import Message if self._tasks_inserted: raise errors.ContextAlreadyStartedError( "This Context has already had its tasks inserted.") if no...
Add an Async job to this context. Takes an Async object or the arguments to construct an Async object as arguments. Returns the newly added Async object.
362,881
def plot(self, left, right, labels=None, vertical=True): import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec if not isinstance(left, list): left = [left] left = [self._conv(l) for l in left] right = self._conv(right) hcells, vcell...
Plot left / right DataFrames in specified layout. Parameters ---------- left : list of DataFrames before operation is applied right : DataFrame of operation result labels : list of str to be drawn as titles of left DataFrames vertical : bool If True, use vert...
362,882
def add(clss, func, deprecated_name): @Deprecator(func.__name__, deprecated_name) def _old_function(*args, **kwargs): return func(*args, **kwargs) setattr(clss, deprecated_name, _old_function)
Add the deprecated version of a member function to the given class. Gives a deprecation warning on usage. Args: clss: the class where the deprecated function is to be added func: the actual function that is called by the deprecated version deprecated_name: the deprec...
362,883
def parameter_action(self, text, loc, par): exshared.setpos(loc, text) if DEBUG > 0: print("PARAM:",par) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return index = self.symtab.insert_parameter(par.name, par.type) self.shared.fun...
Code executed after recognising a parameter
362,884
def iter_halfs_double(graph): edges = graph.edges for index1, (atom_a1, atom_b1) in enumerate(edges): for atom_a2, atom_b2 in edges[:index1]: try: affected_atoms1, affected_atoms2, hinge_atoms = graph.get_halfs_double(atom_a1, atom_b1, atom_a2, atom_b2) y...
Select two random non-consecutive bonds that divide the molecule in two
362,885
async def message_fields(self, msg, fields, obj=None): for field in fields: await self.message_field(msg, field, obj) return msg
Load/dump individual message fields :param msg: :param fields: :param obj: :return:
362,886
def proxy_set(self, value): setter = getattr(self, self.proxy_setter) if isinstance(value, (list, tuple, set)): result = setter(*value) elif isinstance(value, dict): result = setter(**value) else: result = setter(value) return result
A helper to easily call the proxy_setter of the field
362,887
def path(self, which=None): if which in ( , , , ): return .format( super(RepositorySet, self).path(which=), which ) return super(RepositorySet, self).path(which)
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: available_repositories /repository_sets/<id>/available_repositories enable /repository_sets/<id>/enable disable /repository_sets/<id>/dis...
362,888
def count(self, eventRegistry): self.setRequestedResult(RequestEventsInfo()) res = eventRegistry.execQuery(self) if "error" in res: print(res["error"]) count = res.get("events", {}).get("totalResults", 0) return count
return the number of events that match the criteria
362,889
def _send_string_clipboard(self, string: str, paste_command: model.SendMode): backup = self.clipboard.text if backup is None: logger.warning("Tried to backup the X clipboard content, but got None instead of a string.") self.clipboard.text = string try: ...
Use the clipboard to send a string.
362,890
def setup_console(output): global console console = ConsoleOutput(output, streamlink) console.json = args.json signal.signal(signal.SIGTERM, signal.default_int_handler)
Console setup.
362,891
def get_token(self): self.token = self._session.fetch_token( token_url=CLOUD_URLS["get_token"][1], client_id=self._client_id, client_secret=self._client_secret )
get current oauth token
362,892
def urlnext(parser, token): bits = token.split_contents() if len(bits) < 2: raise template.TemplateSyntaxError( " takes at least one argument" " (path to a view)" % bits[0] ) viewname = parser.compile_filter(bits[1]) args = [] kwargs = {} asvar = None...
{% url %} copied from Django 1.7.
362,893
def set_value(request, name, value): obj = service.system.namespace.get(name, None) if not obj or service.read_only: raise Http404 obj.status = value if service.redirect_from_setters: return HttpResponseRedirect(reverse(, args=(name, value))) else: return set_ready(reque...
For manual shortcut links to perform set value actions
362,894
def set_evict_number(self, new_evict_number, only_read=False): if not isinstance(new_evict_number, int) or new_evict_number <= 0: self.logger.warning( % new_evict_number) return self.evict_number = new_evict_number
>>> cache = Cache(log_level=logging.WARNING) >>> cache.set_evict_number(10) >>> cache.evict_number 10 >>> cache.set_evict_number('haha') >>> cache.evict_number 10
362,895
def start_asweep(self, start=None, stop=None, step=None): if start: self.amplitude_start = start if stop: self.amplitude_stop = stop if step: self.amplitude_step = step self._write((, Integer), 2)
Starts a amplitude sweep. :param start: Sets the start frequency. :param stop: Sets the target frequency. :param step: Sets the frequency step.
362,896
def int_element(element, name, default=0): element_value = element.find(name) if element_value is not None: try: return int(element_value.text) except (TypeError, ValueError): return default return default
Returns the int value of an element, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param name: The name of the element to evaluate :type name: str :param default: The default value to return if the element is not defined :type default...
362,897
def loads(content, ac_parser=None, ac_dict=None, ac_template=False, ac_context=None, **options): if ac_parser is None: LOGGER.warning("ac_parser was not given but it's must to find correct " "parser to load configurations from string.") return None psr = fi...
:param content: Configuration file's content (a string) :param ac_parser: Forced parser type or ID or parser object :param ac_dict: callable (function or class) to make mapping object will be returned as a result or None. If not given or ac_dict is None, default mapping object used to st...
362,898
def build(ctx, max_revisions, targets, operators, archiver): config = ctx.obj["CONFIG"] from wily.commands.build import build if max_revisions: logger.debug(f"Fixing revisions to {max_revisions}") config.max_revisions = max_revisions if operators: logger.debug(f"Fixing op...
Build the wily cache.
362,899
def import_transcript_from_fs(edx_video_id, language_code, file_name, provider, resource_fs, static_dir): file_format = None transcript_data = get_video_transcript_data(edx_video_id, language_code) if not transcript_data: try: with resource_fs.open(combine(static_dir,...
Imports transcript file from file system and creates transcript record in DS. Arguments: edx_video_id (str): Video id of the video. language_code (unicode): Language code of the requested transcript. file_name (unicode): File name of the transcript file. provider (unicode): Transcri...