Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
347,200
def linkify(self, modules): logger.debug("Linkify %s with %s", self, modules) self.linkify_s_by_module(modules)
Link modules and Satellite links :param modules: Module object list :type modules: alignak.objects.module.Modules :return: None
347,201
def getLoggingLocation(self): if sys.platform == "win32": modulePath = os.path.realpath(__file__) modulePath = modulePath[:modulePath.rfind("/")] return modulePath else: return "/tmp" return ""
Return the path for the calcpkg.log file - at the moment, only use a Linux path since I don't know where Windows thinks logs should go.
347,202
def create_result(self, local_path, container_path, permissions, meta, val, dividers): if permissions is NotSpecified: permissions = return Mount(local_path, container_path, permissions)
Default permissions to rw
347,203
def expand_focussed(self): if implementsCollapseAPI(self._tree): w, focuspos = self.get_focus() self._tree.expand(focuspos) self._walker.clear_cache() self.refresh()
Expand currently focussed position; works only if the underlying tree allows it.
347,204
def _get_id_and_model(self, id_or_model): if isinstance(id_or_model, self.collection.model): model = id_or_model elif isinstance(id_or_model, str): model = self.collection.get(id_or_model) else: raise TypeError(.format( ty...
Get both the model and ID of an object that could be an ID or a model. :param id_or_model: The object that could be an ID string or a model object. :param model_collection: The collection to which the model belongs.
347,205
def results_class_wise_metrics(self): results = {} for tag_id, tag_label in enumerate(self.tag_label_list): if tag_label not in results: results[tag_label] = {} results[tag_label][] = { : self.tag_wise[tag_label][], ...
Class-wise metrics Returns ------- dict results in a dictionary format
347,206
def parse(self): parsed = [, , , , , , ] if self._expression is None or len(self._expression) == 0: raise MissingFieldException("ExpressionDescriptor.expression") else: expression_parts_temp = self._expression.split() expression_parts_temp_l...
Parses the cron expression string Returns: A 7 part string array, one part for each component of the cron expression (seconds, minutes, etc.) Raises: MissingFieldException: if _expression is empty or None FormatException: if _expression has wrong format
347,207
def rolling_window(a, window, pad=None): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1], ) out = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) if window % 2 == 0: npre = window // 2 - 1 npost = window // 2 e...
Returns (win, len(a)) rolling - window array of data. Parameters ---------- a : array_like Array to calculate the rolling window of window : int Description of `window`. pad : same as dtype(a) Description of `pad`. Returns ------- array_like An array of ...
347,208
def write_transparency(selection): global themefile, transparency, prefix if themefile == "": return lines = themefile.split() for line in lines: if in line.lower(): try: background = line.split()[1].replace(, ) background = background...
writes transparency as rgba to ~/.Xresources
347,209
def create_from_params(cls, template_model, datastore_name, vm_cluster_model, ip_regex, refresh_ip_timeout, auto_power_on, auto_power_off, wait_for_ip, auto_delete): dic = { : template_model, : datastore_name, : vm_cluster_model, ...
:param VCenterTemplateModel template_model: :param str datastore_name: :param VMClusterModel vm_cluster_model: :param str ip_regex: Custom regex to filter IP addresses :param refresh_ip_timeout: :param bool auto_power_on: :param bool auto_power_off: :param bool wa...
347,210
def collect_random_trajectory(env, timesteps=1000): obs = env.reset() dof = env.dof for t in range(timesteps): action = 0.5 * np.random.randn(dof) obs, reward, done, info = env.step(action) env.render() if t % 100 == 0: print(t)
Run a random policy to collect trajectories. The rollout trajectory is saved to files in npz format. Modify the DataCollectionWrapper wrapper to add new fields or change data formats.
347,211
def all_dags(self, nodes=None): if nodes is None: nodes = sorted(self.state_names.keys()) if len(nodes) > 6: warn("Generating all DAGs of n nodes likely not feasible for n>6!") warn("Attempting to search through {0} graphs".format(2**(len(nodes)*(len(nodes)-1...
Computes all possible directed acyclic graphs with a given set of nodes, sparse ones first. `2**(n*(n-1))` graphs need to be searched, given `n` nodes, so this is likely not feasible for n>6. This is a generator. Parameters ---------- nodes: list of nodes for the DAGs (optional)...
347,212
def calculate_rate(country_code, exception_name): if not country_code or not isinstance(country_code, str_cls) or len(country_code) != 2: raise ValueError() if exception_name and not isinstance(exception_name, str_cls): raise ValueError() country_code = country_code.upper() if c...
Calculates the VAT rate for a customer based on their declared country and any declared exception information. :param country_code: The two-character country code where the user resides :param exception_name: The name of an exception for the country, as returned from vat_moss.decla...
347,213
def pack_header_for_user( self, user, override_access_lifespan=None, override_refresh_lifespan=None, **custom_claims ): token = self.encode_jwt_token( user, override_access_lifespan=override_access_lifespan, override_refresh_li...
Encodes a jwt token and packages it into a header dict for a given user :param: user: The user to package the header for :param: override_access_lifespan: Override's the instance's access lifespan to set a custom duration ...
347,214
def replaceChild(self, new_child: AbstractNode, old_child: AbstractNode) -> AbstractNode: return self._replace_child(new_child, old_child)
Replace an old child with new child.
347,215
def _create_controller_info_record(self, controller_module_name): module = self._controller_modules[controller_module_name] controller_info = None try: controller_info = module.get_info( copy.copy(self._controller_objects[controller_module_name])) exc...
Creates controller info record for a particular controller type. Info is retrieved from all the controller objects spawned from the specified module, using the controller module's `get_info` function. Args: controller_module_name: string, the name of the controller module ...
347,216
def get_host_power_status(self): sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) return GET_POWER_STATE_MAP.get(sushy_system.power_state)
Request the power state of the server. :returns: Power State of the server, 'ON' or 'OFF' :raises: IloError, on an error from iLO.
347,217
def businesstimedelta(self, d1, d2): if d1 > d2: d1, d2, timedelta_direction = d2, d1, -1 else: timedelta_direction = 1 businessdays = self._build_spanning_datetimes(d1, d2) time = datetime.timedelta() if len(businessdays) == 0: ...
Returns a datetime.timedelta with the number of full business days and business time between d1 and d2
347,218
def draw_lnm_samples(**kwargs): nsamples = kwargs.get(, 1) min_mass = kwargs.get(, 5.) max_mass = kwargs.get(, 95.) max_mtotal = min_mass + max_mass lnmmin = log(min_mass) lnmmax = log(max_mass) k = nsamples * int(1.5 + log(1 + 100./nsamples)) aa = np.exp(np.random.uniform(ln...
Draw samples for uniform-in-log model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The second mass
347,219
def getModule(self, moduleName): if moduleName not in self.moduleCache: modulePath = FilePath( athena.jsDeps.getModuleForName(moduleName)._cache.path) cachedModule = self.moduleCache[moduleName] = CachedJSModule( moduleName, modulePath) el...
Retrieve a JavaScript module cache from the file path cache. @returns: Module cache for the named module. @rtype: L{CachedJSModule}
347,220
def convert_schema(raml_schema, mime_type): if mime_type == ContentTypes.JSON: if not isinstance(raml_schema, dict): raise TypeError( .format(str(raml_schema)[:60])) return raml_schema if mime_type == ContentTypes.TEXT_XML: pass
Restructure `raml_schema` to a dictionary that has 'properties' as well as other schema keys/values. The resulting dictionary looks like this:: { "properties": { "field1": { "required": boolean, "type": ..., ...more field options ...
347,221
def _parse_cli_args(): parser = argparse.ArgumentParser() parser.add_argument( , help=, metavar= ) parser.add_argument( , default=1, help=( ), type=int, choices=xrange(0, 10), metavar= ) ...
Parse the arguments from CLI using ArgumentParser :return: The arguments parsed by ArgumentParser :rtype: Namespace
347,222
def is_reassignment_pending(self): in_progress_plan = self.zk.get_pending_plan() if in_progress_plan: in_progress_partitions = in_progress_plan[] self.log.info( .format( count=len(in_progress_partition...
Return True if there are reassignment tasks pending.
347,223
def _Connect(self, banner=None, **kwargs): if not banner: banner = socket.gethostname().encode() conn_str = self.protocol_handler.Connect(self._handle, banner=banner, **kwargs) parts = conn_str.split(b) self._device_state = parts[0] self...
Connect to the device. Args: banner: See protocol_handler.Connect. **kwargs: See protocol_handler.Connect and adb_commands.ConnectDevice for kwargs. Includes handle, rsa_keys, and auth_timeout_ms. Returns: An instance of this class if the device connected su...
347,224
def update_if_outdated(folder): folders = [] while os.path.isdir(folder): folders.append(folder) with open(os.path.join(folder, "info.yml")) as ymlfile: content = yaml.load(ymlfile) folder = os.path.join(utils.get_project_root(), content[]) raw_source_file ...
Check if the currently watched instance (model, feature or preprocessing) is outdated and update it eventually.
347,225
async def update_notifications(self, on_match_open: bool = None, on_tournament_end: bool = None): params = {} if on_match_open is not None: params[] = on_match_open if on_tournament_end is not None: params[] = on_tournament_end assert_or_raise(len(params)...
update participants notifications for this tournament |methcoro| Args: on_match_open: Email registered Challonge participants when matches open up for them on_tournament_end: Email registered Challonge participants the results when this tournament ends Raises: ...
347,226
def _all_insert_into_row(self, row, insert_dict): for key, val in insert_dict.items(): try: row[key] = val except KeyError as ke: self._logger.warning( % key + repr(ke))
Copies data from `insert_dict` into a pytables `row`.
347,227
def get_ancestor_processes(): if not _ANCESTOR_PROCESSES and psutil is not None: proc = psutil.Process(os.getpid()) while proc.parent() is not None: try: _ANCESTOR_PROCESSES.append(proc.parent().exe()) proc = proc.parent() except psutil.Er...
Get a list of the executables of all ancestor processes.
347,228
def transform(self, X): self._check_fitted() X = as_features(X, stack=True) assignments = self.kmeans_fit_.predict(X.stacked_features) return self._group_assignments(X, assignments)
Transform a list of bag features into its bag-of-words representation. Parameters ---------- X : :class:`skl_groups.features.Features` or list of bag feature arrays New data to transform. Returns ------- X_new : integer array, shape [len(X), kmeans.n_cluster...
347,229
def _parse_path(self, path): run = self.settings[] project = self.settings[] username = self.settings[] parts = path.replace("/runs/", "/").split("/") if ":" in parts[-1]: run = parts[-1].split(":")[-1] parts[-1] = parts[-1].split(":")[0] ...
Parses paths in the following formats: url: username/project/runs/run_id path: username/project/run_id docker: username/project:run_id username is optional and will fallback to the current logged in user.
347,230
def get_reflectance_lut(filename): h5f = h5py.File(filename, ) tab = h5f[] wvl = h5f[] azidiff = h5f[] satellite_zenith_secant = h5f[] sun_zenith_secant = h5f[] if HAVE_DASK: tab = from_array(tab, chunks=(10, 10, 10, 10)) wvl = wvl[:] azidiff = from_array(az...
Read the LUT with reflectances as a function of wavelength, satellite zenith secant, azimuth difference angle, and sun zenith secant
347,231
def from_dict(cls, d): return cls( d[], d[], list(d.get(, {}).items()), d.get(, False) )
Instantiate a Role from a dictionary representation.
347,232
def commit(self): last_line, last_col = self.qteWidget.getNumLinesAndColumns() if self.cursorPos is None: self.markerPos = self.qteWidget.qteGetMark() if self.markerPos is None: return ...
Insert the specified text in all selected lines, always at the same column position.
347,233
def get_canonical_headers(cls, req, include=None): if include is None: include = cls.default_include_headers include = [x.lower() for x in include] headers = req.headers.copy() return (cano_headers, signed_headers)
Generate the Canonical Headers section of the Canonical Request. Return the Canonical Headers and the Signed Headers strs as a tuple (canonical_headers, signed_headers). req -- Requests PreparedRequest object include -- List of headers to include in the canonical and signed ...
347,234
def includeme(config): settings = config.registry.settings swagger_versions = get_swagger_versions(settings) config.add_renderer( , , ) settings[] = None settings[] = None if SWAGGER_12 in swagger_versions: settings[] = get_swagger_schema(settings)...
:type config: :class:`pyramid.config.Configurator`
347,235
def poke(url, accesskey=None, secretkey=None, __method__=, **req_args): if accesskey and secretkey: req_args[] = (accesskey, secretkey) tmp = requests.request(__method__.lower(), url, **req_args) tmp.raise_for_status() if tmp.headers.get().find("json") != -1: rv = _convert_to_rod(tm...
Poke the Rancher API. Returns a Rod object instance. Central starting point for the cattleprod package. :param url: The full Rancher URL to the API endpoint. :param accesskey: The rancher access key, optional. :param secretkey: The rancher secret key, optional. :param __method__: Internal method, do...
347,236
def acosh(x): _math = infer_math(x) if _math is math: return _math.acosh(x) else: return _math.arccosh(x)
acosh(x) Hyperbolic arc cos function.
347,237
def unflatten(processed, merge_rules): unflattened = OrderedDict() for key in processed: current_node = unflattened for end, part in enumerate(key, 1): if isinstance(part, IdValue): for node in current_node: ...
Unflattens a processed object into a JSON object.
347,238
def prune(self, filter_func=None, from_stash=, to_stash=): def _prune_filter(state): to_prune = not filter_func or filter_func(state) if to_prune and not state.satisfiable(): if self._hierarchy: self._hierarchy.unreachable_state(state) ...
Prune unsatisfiable states from a stash. This function will move all unsatisfiable states in the given stash into a different stash. :param filter_func: Only prune states that match this filter. :param from_stash: Prune states from this stash. (default: 'active') :param to_stash: P...
347,239
def add_or_filter(self, *values): filt = OrFilter(*values) self.update_filter(filt) return filt
Add a filter using "OR" logic. This filter is useful when matching on one or more criteria. For example, searching for IP 1.1.1.1 and service TCP/443, or IP 1.1.1.10 and TCP/80. Either pair would produce a positive match. .. seealso:: :class:`smc_monitoring.models.filters.OrFilt...
347,240
def get_comments_by_query(self, comment_query): and_list = list() or_list = list() for term in comment_query._query_terms: if in comment_query._query_terms[term] and in comment_query._query_terms[term]: and_list.append( ...
Gets a list of comments matching the given search. arg: comment_query (osid.commenting.CommentQuery): the search query array return: (osid.commenting.CommentList) - the returned ``CommentList`` raise: NullArgument - ``comment_query`` is ``null`` raise...
347,241
def import_class(import_path, name=None): if not name: import_path, name = import_path.rsplit(, 1) mod = import_module(import_path) try: return getattr(mod, name) except AttributeError as e: raise ImportError(e)
Imports and returns class for full class path string. Ex. 'foo.bar.Bogus' -> <class 'foo.bar.Bogus'>
347,242
def get(self, name): pm = self._libeng.engGetVariable(self._ep, name) out = mxarray_to_ndarray(self._libmx, pm) self._libmx.mxDestroyArray(pm) return out
Get variable `name` from MATLAB workspace. Parameters ---------- name : str Name of the variable in MATLAB workspace. Returns ------- array_like Value of the variable `name`.
347,243
def check_dimensional_vertical_coordinate(self, ds): ret_val = [] z_variables = cfutil.get_z_variables(ds) for name in z_variables: variable = ds.variables[name] standard_name = getattr(variable, , None) units = getattr(variable, , None) ...
Check units for variables defining vertical position are valid under CF. CF §4.3.1 The units attribute for dimensional coordinates will be a string formatted as per the udunits.dat file. The acceptable units for vertical (depth or height) coordinate variables are: - uni...
347,244
def predict(self, X): check_rdd(X, (sp.spmatrix, np.ndarray)) return self._spark_predict(SparkSGDClassifier, X)
Distributed method to predict class labels for samples in X. Parameters ---------- X : ArrayRDD containing {array-like, sparse matrix} Samples. Returns ------- C : ArrayRDD Predicted class label per sample.
347,245
def write_single_coil(slave_id, address, value): function = WriteSingleCoil() function.address = address function.value = value return _create_request_adu(slave_id, function.request_pdu)
Return ADU for Modbus function code 05: Write Single Coil. :param slave_id: Number of slave. :return: Byte array with ADU.
347,246
def event_update_list(request, slug): event = get_object_or_404(Event, slug=slug) updates = Update.objects.filter(event__slug=slug) if event.recently_ended(): updates = updates.order_by() else: updates = updates.order_by() return render(request, , { : e...
Returns a list view of updates for a given event. If the event is over, it will be in chronological order. If the event is upcoming or still going, it will be in reverse chronological order.
347,247
def cosine_lesk(context_sentence: str, ambiguous_word: str, pos: str = None, lemma=True, stem=True, hyperhypo=True, stop=True, context_is_lemmatized=False, nbest=False, from_cache=True) -> "wn.Synset": ambiguous_word = lemmatize(ambiguous_word) if...
In line with vector space models, we can use cosine to calculate overlaps instead of using raw overlap counts. Essentially, the idea of using signatures (aka 'sense paraphrases') is lesk-like. :param context_sentence: String, sentence or document. :param ambiguous_word: String, a single word. :para...
347,248
def _time_from_iso8601_time_naive(value): if len(value) == 8: fmt = _TIMEONLY_NO_FRACTION elif len(value) == 15: fmt = _TIMEONLY_W_MICROS else: raise ValueError("Unknown time format: {}".format(value)) return datetime.datetime.strptime(value, fmt).time()
Convert a zoneless ISO8601 time string to naive datetime time :type value: str :param value: The time string to convert :rtype: :class:`datetime.time` :returns: A datetime time object created from the string :raises ValueError: if the value does not match a known format.
347,249
def read_property_to_any(obj, propertyIdentifier, propertyArrayIndex=None): if _debug: read_property_to_any._debug("read_property_to_any %s %r %r", obj, propertyIdentifier, propertyArrayIndex) datatype = obj.get_datatype(propertyIdentifier) if _debug: read_property_to_any._debug(" - datatype: ...
Read the specified property of the object, with the optional array index, and cast the result into an Any object.
347,250
def retrieve(self, request, project, pk=None): job_id, bug_id = map(int, pk.split("-")) job = Job.objects.get(repository__name=project, id=job_id) try: bug_job_map = BugJobMap.objects.get(job=job, bug_id=bug_id) serializer = BugJobMapSerializer(bug_job_map) ...
Retrieve a bug-job-map entry. pk is a composite key in the form bug_id-job_id
347,251
def check_bbox(bbox): for name, value in zip([, , , ], bbox[:4]): if not 0 <= value <= 1: raise ValueError( .format( bbox=bbox, name=name, value=value, ) ) x_min, y_m...
Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums
347,252
def get_weighted_spans(doc, vec, feature_weights): if isinstance(vec, FeatureUnion): return _get_weighted_spans_from_union(doc, vec, feature_weights) else: result = _get_doc_weighted_spans(doc, vec, feature_weights) if result is not None: found_features, doc_weighte...
If possible, return a dict with preprocessed document and a list of spans with weights, corresponding to features in the document.
347,253
def label_absent(name, node=None, apiserver_url=None): ** ret = {: name, : True, : , : {}} node = _guess_node_id(node) apiserver_url = _guess_apiserver(apiserver_url) if apiserver_url is None: return False old_labels = _get_labels(node, apiserver_url) labels = d...
.. versionadded:: 2016.3.0 Delete label to the current node CLI Example: .. code-block:: bash salt '*' k8s.label_absent hw/disktype salt '*' k8s.label_absent hw/disktype kube-node.cluster.local http://kube-master.cluster.local
347,254
def _energy_to_enthalpy(energy): pureA = [energy[0][0],energy[0][1]] pureB = [energy[1][0],energy[1][1]] pureC = [energy[2][0],energy[2][1]] enthalpy = [] for en in energy: c = en[2] conc = [float(i)/sum(c) for i in c] CE = _en_to_enth(en[0],conc,pureA[0],pureB[0]...
Converts energy to enthalpy. This function take the energies stored in the energy array and converts them to formation enthalpy. Parameters --------- energy : list of lists of floats Returns ------- enthalpy : list of lists containing the enthalpies.
347,255
def _text_image(page): img = None alt = page.data.get() or page.data.get() source = _image(page) if source: img = "![%s](%s)" % (alt, source) return img
returns text image URL
347,256
def compute_checksum(filename, max_length=2**20): fid = open(filename, ) crcval = safe_crc(fid.read(max_length)) fid.close() return crcval
Compute the CRC32 checksum for specified file Optional parameter max_length sets the maximum number of bytes used to limit time used with large files. Default = 2**20 (1MB)
347,257
def variance_K(K, verbose=False): c = SP.sum((SP.eye(len(K)) - (1.0 / len(K)) * SP.ones(K.shape)) * SP.array(K)) scalar = (len(K) - 1) / c return 1.0/scalar
estimate the variance explained by K
347,258
def forcemigrate(app=None): if app is None: abort("No app name given.") local("./manage.py migrate {} --fake".format(app)) local("./manage.py migrate {}".format(app))
Force migrations to apply for a given app.
347,259
def dot(src, **kw): cmd = "dot -T%s" % kw.pop(, ) for k, v in list(kw.items()): if v is True: cmd += " -%s" % k else: cmd += " -%s%s" % (k, v) return pipe(cmd, to_bytes(src))
Execute the dot command to create an svg output.
347,260
def create_insight(self, project_owner, project_id, **kwargs): kwargs[] = True if kwargs.get(): return self.create_insight_with_http_info(project_owner, project_id, **kwargs) else: (data) = self.create_insight_with_http_info(project_owner, project_id, **kwargs) ...
Create an insight Create a new insight. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(respon...
347,261
def get_headline(self, name): return self._loop.run_coroutine(self._client.get_headline(name))
Get stored messages for a service. Args: name (string): The name of the service to get messages from. Returns: ServiceMessage: the headline or None if no headline has been set
347,262
def get_context_data(self, **kwargs): context = super(AnimalListAlive, self).get_context_data(**kwargs) context[] = return context
This add in the context of list_type and returns this as Alive.
347,263
def init_db(dbURL, pwd_salt_size=None, pwd_rounds=None): if not dbURL: dbURL = logging.getLogger(__name__).debug("Initializing database: {}".format(dict(url=dbURL, pwd_salt_size=pwd_salt_size, ...
Initialize users database initialize database and create necessary tables to handle users oprations. :param dbURL: database url, as described in :func:`init_proxy`
347,264
def make_dbsource(**kwargs): if in connection.settings_dict.get(): kwargs.setdefault(, connection.settings_dict[]) return mapnik.SQLite(wkb_format=, **kwargs) names = ((, ), (, ), (, ), (, ), (, )) for mopt, dopt in names: val = connection.settings_dict.get(dopt) ...
Returns a mapnik PostGIS or SQLite Datasource.
347,265
def get_session(username, password, locale=DEFAULT_LOCALE, cookie_path=COOKIE_PATH): class UPSAuth(AuthBase): def __init__(self, username, password, locale, cookie_path): self.username = username self.password = password self....
Get UPS HTTP session.
347,266
def pre_filter(self): if self._name in self.PRE_FILTER_FIELDS: val = int(self._value * self.FIELD_SCALE.get(self._name, 1)) return .format( self._rt_cmp, self.PRE_FILTER_FIELDS[self._name], val) return
Return rTorrent condition to speed up data transfer.
347,267
def set_vectors(self, stoi, vectors, dim, unk_init=torch.Tensor.zero_): self.vectors = torch.Tensor(len(self), dim) for i, token in enumerate(self.itos): wv_index = stoi.get(token, None) if wv_index is not None: self.vectors[i] = vectors[wv_index] ...
Set the vectors for the Vocab instance from a collection of Tensors. Arguments: stoi: A dictionary of string to the index of the associated vector in the `vectors` input argument. vectors: An indexed iterable (or other structure supporting __getitem__) that ...
347,268
def handle_unlock( mediator_state: MediatorTransferState, state_change: ReceiveUnlock, channelidentifiers_to_channels: ChannelMap, ) -> TransitionResult[MediatorTransferState]: events = list() balance_proof_sender = state_change.balance_proof.sender channel_identifier = state_ch...
Handle a ReceiveUnlock state change.
347,269
def gsim_imt_dt(sorted_gsims, sorted_imts): dtlist = [(imt, numpy.float32) for imt in sorted_imts] imt_dt = numpy.dtype(dtlist) return numpy.dtype([(str(gsim), imt_dt) for gsim in sorted_gsims])
Build a numpy dtype as a nested record with keys 'idx' and nested (gsim, imt). :param sorted_gsims: a list of GSIM instances, sorted lexicographically :param sorted_imts: a list of intensity measure type strings
347,270
def namespaces(self, psuedo=True): if self._namespaces is None: result = self.call({: , : , : }) self._namespaces = {} self._psuedo_namespaces = {} for nsid in result[][]: if ...
Fetches a list of namespaces for this wiki and returns them as a dictionary of namespace IDs corresponding to namespace names. If *psuedo* is ``True``, the dictionary will also list psuedo-namespaces, which are the "Special:" and "Media:" namespaces (special because they have no content ...
347,271
def attach_file(self, filename, page_id=None, title=None, space=None, comment=None): page_id = self.get_page_id(space=space, title=title) if page_id is None else page_id type = if page_id is not None: extension = os.path.splitext(filename)[-1] content_type = sel...
Attach (upload) a file to a page, if it exists it will update the automatically version the new file and keep the old one. :param title: The page name :type title: ``str`` :param space: The space name :type space: ``str`` :param page_id: The page id to which we would li...
347,272
def p_expression_plus(self, p): p[0] = Plus(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
expression : expression PLUS expression
347,273
def expand(self, url): expand_url = f params = { : url, : self.api_key, : , } response = self._get(expand_url, params=params) if response.ok: return response.text.strip() raise ExpandingErrorException(response.conte...
Expand implementation for Bit.ly Args: url: the URL you want to shorten Returns: A string containing the expanded URL Raises: ExpandingErrorException: If the API Returns an error as response
347,274
def parse(cls, query_str): parsed_query = parse_qs(query_str, keep_blank_values=True, strict_parsing=True) result = cls() for parameter_name in parsed_query.keys(): for parameter_value in parsed_query[parameter_name]: result.add_parameter( parameter_name, parameter_value if len(parameter_value...
Parse string that represent query component from URI :param query_str: string without '?'-sign :return: WURIQuery
347,275
def consent(): config = _config() return render_template( "consent.html", hit_id=request.args["hit_id"], assignment_id=request.args["assignment_id"], worker_id=request.args["worker_id"], mode=config.get("mode"), )
Return the consent form. Here for backwards-compatibility with 2.x.
347,276
def format_registryfield_nodes(field_name, field, field_id, state, lineno): from lsst.pex.config.registry import ConfigurableWrapper choice_dl = nodes.definition_list() for choice_value, choice_class in field.registry.items(): if hasattr(choic...
Create a section node that documents a RegistryField config field. Parameters ---------- field_name : `str` Name of the configuration field (the attribute name of on the config class). field : ``lsst.pex.config.RegistryField`` A configuration field. field_id : `str` ...
347,277
def disconnect(remote_app): if remote_app not in current_oauthclient.disconnect_handlers: return abort(404) ret = current_oauthclient.disconnect_handlers[remote_app]() db.session.commit() return ret
Disconnect user from remote application. Removes application as well as associated information.
347,278
def answers(self): from .author import Author from .answer import Answer self._make_soup() if self._url.endswith(): pager = self.soup.find(, class_=) if pager is None: max_page = 1 else: max_page = in...
获取问题的所有答案. :return: 问题的所有答案,返回生成器 :rtype: Answer.Iterable
347,279
def is_changed(): executed, changed_lines = execute_git(, output=False) merge_not_finished = mod_path.exists() return changed_lines.strip() or merge_not_finished
Checks if current project has any noncommited changes.
347,280
def _set_port_group(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("name",port_group.port_group, yang_name="port-group", rest_name="port-group", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=, e...
Setter method for port_group, mapped from YANG variable /hardware/port_group (list) If this variable is read-only (config: false) in the source YANG file, then _set_port_group is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_port_group()...
347,281
def save_r_df(self, state_key, r_value, action_key=None): if action_key is not None: add_r_df = pd.DataFrame([(state_key, action_key, r_value)], columns=["state_key", "action_key", "r_value"]) else: add_r_df = pd.DataFrame([(state_key, r_value)], columns=["state_key", "r...
Insert or update R-Value in `self.r_df`. Args: state_key: The key of state. r_value: R-Value(Reward). action_key: The key of action if it is nesesary for the parametar of value function. Exceptions: TypeError: If the type of `r_value` i...
347,282
def dist_typo( src, tar, metric=, cost=(1, 1, 0.5, 0.5), layout= ): return Typo().dist(src, tar, metric, cost, layout)
Return the normalized typo distance between two strings. This is a wrapper for :py:meth:`Typo.dist`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison metric : str Supported values include: ``euclidean``, ``manhattan``, ...
347,283
def add_greeting(nc, line): assert type(nc) == dict nc["greeting"] = nc.get("greeting") or "" if not nc["greeting"].endswith("\n"): nc["greeting"] += "\n" nc["greeting"] += line + "\n"
Add one-liner script or several lines (newline separated)
347,284
def create_new_product_version(self, **kwargs): kwargs[] = True if kwargs.get(): return self.create_new_product_version_with_http_info(**kwargs) else: (data) = self.create_new_product_version_with_http_info(**kwargs) return data
Create a new ProductVersion for a Product This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(res...
347,285
def get_extr_lics_comment(self, extr_lics): comment_list = list(self.graph.triples( (extr_lics, RDFS.comment, None))) if len(comment_list) > 1 : self.more_than_one_error() return elif len(comment_list) == 1: return comment_list[0][2] ...
Return license comment or None.
347,286
def plot(self, title=, view=(None, None)): from matplotlib.colors import LinearSegmentedColormap import matplotlib.pyplot as plt if self._interval_set.empty(): print() return plot_order = 15 if self.max_order > plot_order: plotted_mo...
Plot the TimeMoc in a time window. This method uses interactive matplotlib. The user can move its mouse through the plot to see the time (at the mouse position). Parameters ---------- title : str, optional The title of the plot. Set to 'TimeMoc' by default. ...
347,287
def from_instance_count(cls, instance_count_arg, entrypoint="*"): try: if instance_count_arg is None: return cls(None) if isinstance(instance_count_arg, basestring) or isinstance(instance_count_arg, int): return cls({entrypoint: {"clusterSpec": {"...
Returns a SystemRequirementsDict that can be passed as a "systemRequirements" input to job/new or run/ API calls. The instance_count_arg should be either a: * string or int eg. "6" or 8 * dictionary, eg. {"main": 4, "other_function": 2}
347,288
def retrieve_records(self, timeperiod, include_running, include_processed, include_noop, include_failed, include_disabled): resp = dict() try: query = unit_of_work_dao.QUERY_GET_FREERUN_SINCE(timeperiod, include_running, ...
method looks for suitable UOW records and returns them as a dict
347,289
def timestamp(self): if self.conf.time_source == CTIME: return os.path.getctime(self.path) return email.utils.mktime_tz(email.utils.parsedate_tz( self.message.get()))
Compute the normalized canonical timestamp of the mail.
347,290
def get_gen_slice(ctx=Bubble(), iterable=[], amount=-1, index=-1): ctx.gbc.say(, stuff=iterable, verbosity=10) i = -1 if amount > 0: if index < 0: index = 0 else: for item in iterable: i += 1 item[buts()] = i ctx.gbc.say( %...
very crude way of slicing a generator
347,291
def check_dimensions(self, dataset): results = [] required_ctx = TestCtx(BaseCheck.HIGH, ) message = message += s a single station, it must have dimensions (time, z). x and y dimensions must be scalar or have dimensions (station). time must be a coordinate variable with dimens...
Checks that the feature types of this dataset are consistent with a timeseries-profile-orthogonal dataset. :param netCDF4.Dataset dataset: An open netCDF dataset
347,292
def _read_msg(self): def _recv_socket(nbytes): try: buf = self.socket.recv(nbytes) except IOError as err: raise ...
read message from server
347,293
def predict(self, dataset, output_type=): m = self.__proxy__[] target = self.__proxy__[] f = _BOW_FEATURE_EXTRACTOR return m.predict(f(dataset, target), output_type=output_type)
Return predictions for ``dataset``, using the trained model. Parameters ---------- dataset : SFrame dataset of new observations. Must include columns with the same names as the features used for model training, but does not require a target column. Additional...
347,294
def view_package_info(self, package: str=) -> str: output, _ = self._execute( , self.device_sn, , , , package) return output
View package detail information.
347,295
def update_dict_recursive(editable_dict: dict, editing_dict: dict) -> None: for k, v in editing_dict.items(): if isinstance(v, collections.Mapping): update_dict_recursive(editable_dict.get(k, {}), v) else: editable_dict[k] = v
Updates dict recursively You need to use this function to update dictionary if depth of editing_dict is more then 1 Args: editable_dict: dictionary, that will be edited editing_dict: dictionary, that contains edits Returns: None
347,296
def _log_phi(z): if z * z < 0.0492: coef = -z / SQRT2PI val = functools.reduce(lambda acc, c: coef * (c + acc), CS, 0) res = -2 * val - log(2) dres = exp(-(z * z) / 2 - res) / SQRT2PI elif z < -11.3137: num = functools.reduce( l...
Stable computation of the log of the Normal CDF and its derivative.
347,297
def _validate(self): try: out = self._run_tf() except: raise Exception(%s version\ % (self.tf_path, self.tf_path)) res = re.search(r, out) if res is None: logger.error( ...
Confirm that we can run terraform (by calling its version action) and then validate the configuration.
347,298
def update_surge(api_client, surge_multiplier): try: update_surge = api_client.update_sandbox_product( SURGE_PRODUCT_ID, surge_multiplier=surge_multiplier, ) except (ClientError, ServerError) as error: fail_print(error) else: success_print(updat...
Use an UberRidesClient to update surge and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. surge_mutliplier (float) The surge multiple for a sandbox product. A multiplier greater than or equal to 2.0 ...
347,299
def mboxes(self): archives = [] if os.path.isfile(self.dirpath): try: archives.append(MBoxArchive(self.dirpath)) except OSError as e: logger.warning("Ignoring %s mbox due to: %s", self.dirpath, str(e)) else: for root, ...
Get the mboxes managed by this mailing list. Returns the archives sorted by name. :returns: a list of `.MBoxArchive` objects