Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
338,600
def weighted_moving_average(data, period): catch_errors.check_for_period_error(data, period) k = (period * (period + 1)) / 2.0 wmas = [] for idx in range(0, len(data)-period+1): product = [data[idx + period_idx] * (period_idx + 1) for period_idx in range(0, period)] wma = sum(produ...
Weighted Moving Average. Formula: (P1 + 2 P2 + 3 P3 + ... + n Pn) / K where K = (1+2+...+n) = n(n+1)/2 and Pn is the most recent price
338,601
def correct_rytov_sc_input(radius_sc, sphere_index_sc, medium_index, radius_sampling): params = get_params(radius_sampling) na = params["na"] nb = params["nb"] prefac = medium_index / (2 * na) sm = 2 * na - nb - 1 rt = nb**2 - 4 * n...
Inverse correction of refractive index and radius for Rytov This method returns the inverse of :func:`correct_rytov_output`. Parameters ---------- radius_sc: float Systematically corrected radius of the sphere [m] sphere_index_sc: float Systematically corrected refractive index of ...
338,602
def map_subcommands(self, func): def crawl(cmd): for sc in cmd.subcommands.values(): yield from crawl(sc) yield cmd return map(func, crawl(self.root_command))
Run `func` against all the subcommands attached to our root command.
338,603
def perm_check(function, perm_check_func=_perm_check_func, raise_exception=False): def real_decorator(func): def wrapped(request, db, col, cmd, *args, **kwargs): bPermPass = perm_check_func(request, db, col, cmd) if perm_check_func else True if raise_exception and (not bPermPass...
perm_check_func: the auth func with parameter db,col,cmd raise_exception: True: raise http 403 exception if permission check failed, otherwise return a JSON
338,604
def requiredUnlessTable(col_name, arg, dm, df, con=None): table_name = arg if col_name in df.columns: return None elif not con: return None elif table_name in con.tables: return None else: return "{} column is required unless table {} is present".format(col_name,...
Col_name must be present in df unless arg (table_name) is present in contribution
338,605
def log10(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_log10, (BigFloat._implicit_convert(x),), context, )
Return the base-ten logarithm of x.
338,606
def regroup(target, expression): if not target: return return [ {: key, : list(val)} for key, val in groupby(obj_list, lambda v, f=expression.resolve: f(v, True)) ]
Regroups a list of alike objects by a common attribute. This complex tag is best illustrated by use of an example: say that ``people`` is a list of ``Person`` objects that have ``first_name``, ``last_name``, and ``gender`` attributes, and you'd like to display a list that looks like: * Male: ...
338,607
def get_categorical_features_to_sampling(examples, top_k): observed_features = collections.defaultdict(list) for example in examples: for feature_name in get_categorical_feature_names(example): original_feature = parse_original_feature_from_example( example, feature_name) observed_fea...
Returns categorical features and a sampling of their most-common values. The results of this slow function are used by the visualization repeatedly, so the results are cached. Args: examples: Examples to read to get feature samples. top_k: Max number of samples to return per feature. Returns: A d...
338,608
def decimal_str_to_int(decimal_string): int_string = decimal_string.replace(, ) int_string = int_string.lstrip() return int(int_string)
Helper to decimal currency string into integers (cents). WARNING: DO NOT TRY TO DO THIS BY CONVERSION AND MULTIPLICATION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param string The amount in currency with full stop decimal separator @return integer The amount in cents
338,609
def get_all_package_releases(self, package_name: str) -> Iterable[Tuple[str, str]]: validate_package_name(package_name) self._validate_set_registry() release_ids = self.registry._get_all_release_ids(package_name) for release_id in release_ids: _, version, manifest_ur...
Returns a tuple of release data (version, manifest_ur) for every release of the given package name available on the current registry.
338,610
def _representable(value: Any) -> bool: return not inspect.isclass(value) and not inspect.isfunction(value) and not inspect.ismethod(value) and not \ inspect.ismodule(value) and not inspect.isbuiltin(value)
Check whether we want to represent the value in the error message on contract breach. We do not want to represent classes, methods, modules and functions. :param value: value related to an AST node :return: True if we want to represent it in the violation error
338,611
def transfer_syntax(UID=None, description=None): transfer_syntax = { "1.2.840.10008.1.2": "Implicit VR Endian: Default Transfer Syntax for DICOM", "1.2.840.10008.1.2.1": "Explicit VR Little Endian", "1.2.840.10008.1.2.1.99": "Deflated Explicit VR Big Endian", "1.2.840.10008.1.2....
Transfer Syntax UID <-> Description lookup. :param UID: Transfer Syntax UID, returns description :param description: Take the description of a transfer syntax and return its UID
338,612
def element_info_as_json_with_filter(name, _filter): if name and _filter: element = fetch_meta_by_name(name, filter_context=_filter) if element.json: return element.json
Top level json meta data (href, name, type) for element :param str name: name of element :param str _filter: filter of entry point :return: list dict with metadata, otherwise None
338,613
def split_by_base_count(infile, outfiles_prefix, max_bases, max_seqs=None): seq_reader = sequences.file_reader(infile) base_count = 0 file_count = 1 seq_count = 0 fout = None if max_seqs is None: max_seqs = float() for seq in seq_reader: if base_count == 0: ...
Splits a fasta/q file into separate files, file size determined by number of bases. Puts <= max_bases in each split file The exception is a single sequence >=max_bases is put in its own file. This does not split sequences.
338,614
def min_conflicts(csp, max_steps=100000): csp.current = current = {} for var in csp.vars: val = min_conflicts_value(csp, var, current) csp.assign(var, val, current) for i in range(max_steps): conflicted = csp.conflicted_vars(current) if not conflicted: ...
Solve a CSP by stochastic hillclimbing on the number of conflicts.
338,615
def emit(self, action, payload, level=Level.INSTANT): if level == self.Level.INSTANT: return self.emit_instantly(action, payload) elif level == self.Level.CONTEXTUAL: return self.emit_contextually(action, payload) elif level == self.Level.DELAY: retur...
Emit action.
338,616
def index_to_rawjson(ix): if isinstance(ix, N1qlIndex): ix = ix.raw return _to_json(ix)
:param ix: dict or IndexInfo object :return: serialized JSON
338,617
def get_scope(self, project_path, source, lineno, filename, continous=True): return self._call(, project_path, source, lineno, filename, continous=continous)
Return scope name at cursor position For example:: class Foo: def foo(self): pass | def bar(self): pass get_scope return Foo.foo if continuous is True and Foo otherwise. :param project_pat...
338,618
def calc_temperature_stats(self): self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone) self.temp.mean_course = melodist.util.calculate_mean_daily_course_by_month(self.data.temp, normalize=True)
Calculates statistics in order to derive diurnal patterns of temperature
338,619
def clearcal(vis, weightonly=False): tb = util.tools.table() cb = util.tools.calibrater() cb.setvi(old=True, quiet=False) cb.open(b(vis)) if needinit: cb.initcalset() cb.close()
Fill the imaging and calibration columns (``MODEL_DATA``, ``CORRECTED_DATA``, ``IMAGING_WEIGHT``) of each measurement set with default values, creating the columns if necessary. vis (string) Path to the input measurement set weightonly (boolean) If true, just create the ``IMAGING_WEIGHT`` c...
338,620
def explained_variance(ypred,y): assert y.ndim == 1 and ypred.ndim == 1 vary = np.var(y) return np.nan if vary==0 else 1 - np.var(y-ypred)/vary
Computes fraction of variance that ypred explains about y. Returns 1 - Var[y-ypred] / Var[y] interpretation: ev=0 => might as well have predicted zero ev=1 => perfect prediction ev<0 => worse than just predicting zero
338,621
def word_error_rate(ref: Sequence[T], hyp: Sequence[T]) -> float: if len(ref) == 0: raise EmptyReferenceException( "Cannot calculating word error rate against a length 0 "\ "reference sequence.") distance = min_edit_distance(ref, hyp) return 100 * float(distance) / len...
Calculate the word error rate of a sequence against a reference. Args: ref: The gold-standard reference sequence hyp: The hypothesis to be evaluated against the reference. Returns: The word error rate of the supplied hypothesis with respect to the reference string. Raises:...
338,622
def acceptAlias(decoratedFunction): def wrapper(self, *args, **kwargs): SubAssert(isinstance(self, AliasBase)) if len(args) > 0: key = args[0] if args[0] in self._aliases.keys(): key = self._aliases[args[0]] return decoratedFunction(self, key...
This function should be used as a decorator. Each class method that is decorated will be able to accept alias or original names as a first function positional parameter.
338,623
def to_xdr_object(self): try: source_account = [account_xdr_object(self.source)] except StellarAddressInvalidError: source_account = [] return Xdr.types.Operation(source_account, self.body)
Creates an XDR Operation object that represents this :class:`Operation`.
338,624
def _complete_transaction(cleanup_only, recursive, max_attempts, run_count, cmd_ret_list): cmd = [] if cleanup_only: cmd.append() cmd_ret_list.append(__salt__[]( cmd, output_loglevel=, python_shell=False )) if (cmd_ret_list[-1][] == salt.defaults.exitcodes.EX_...
.. versionadded:: Fluorine Called from ``complete_transaction`` to protect the arguments used for tail recursion, ``run_count`` and ``cmd_ret_list``.
338,625
def make_variable_handler(dec_f, sized_values, min_size, non_minimal_data_handler): sized_values = list(sized_values) def f(script, pc, verify_minimal_data=False): size, pc = dec_f(script, pc) data = bytes_as_hex(script[pc:pc+size]) if len(data) < size: return pc+1, Non...
Create a handler for a data opcode that returns literal data of a variable size that's fetched and decoded by the function dec_f.
338,626
def generate(schema_file, all_options): schema = load_schema_file(open(schema_file, )) config_parser = generate_config_parser(schema, include_all=all_options) config_parser.write(sys.stdout)
Generates a template configuration file from a confirm schema.
338,627
def load_asdf(asdf_obj, data_key=, wcs_key=, header_key=): asdf_keys = asdf_obj.keys() if wcs_key in asdf_keys: wcs = asdf_obj[wcs_key] else: wcs = None if header_key in asdf_keys: ahdr = asdf_obj[header_key] else: ahdr = {} if data_key in asdf_keys: ...
Load from an ASDF object. Parameters ---------- asdf_obj : obj ASDF or ASDF-in-FITS object. data_key, wcs_key, header_key : str Key values to specify where to find data, WCS, and header in ASDF. Returns ------- data : ndarray or `None` Image data, if found....
338,628
def execute(self, env, args): tasks = env.task.get_list_info() if not tasks: env.io.write("No tasks found.") else: if args.verbose: _print_tasks(env, tasks, mark_active=True) else: if env.task.active: ...
Lists all valid tasks. `env` Runtime ``Environment`` instance. `args` Arguments object from arg parser.
338,629
def standard_deviation_difference(data, ground_truth, mask=None, normalized=False, force_lower_is_better=True): r if not hasattr(data, ): data = odl.vector(data) space = data.space ground_truth = space.element(ground_truth) ...
r"""Return absolute diff in std between ``data`` and ``ground_truth``. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tensor`, an unweighted tensor space will be assumed. ground_truth : `array-like` Reference to which `...
338,630
def _config_stress(self): self.stress_exe = None stress_installed = False self.stress_exe = which() if self.stress_exe: stress_installed = True else: self.stress_exe = which() if self.stress_exe: stress_install...
Configures the possible stress processes and modes
338,631
def update_record(cls, fqdn, name, type, value, ttl, content): data = { "rrset_name": name, "rrset_type": type, "rrset_values": value, } if ttl: data[] = int(ttl) meta = cls.get_fqdn_info(fqdn) if content: url =...
Update all records for a domain.
338,632
def execute_task(self, task, workflow_id, data=None): start_time = datetime.utcnow() store_doc = DataStore(**self.app.user_options[].data_store, auto_connect=True).get(workflow_id) store_loc = .format(task.dag_name, task.name) def handle_callback(message, event_type, exc...
Celery task that runs a single task on a worker. Args: self (Task): Reference to itself, the celery task object. task (BaseTask): Reference to the task object that performs the work in its run() method. workflow_id (string): The unique ID of the workflow run that st...
338,633
def verify_data_signature(self, signature_url, data_url, data): req = requests.get(signature_url) if req.status_code is 200: tm = int(time.time()) datestamp = datetime.utcfromtimestamp(tm).isoformat() sigfile = "repo-{0}-tmp.sig".format(datestamp) ...
Verify data against it's remote signature :type signature_url: str :param signature_url: remote path to signature for data_url :type data_url: str :param data_url: url from which data was fetched :type data: str :param data: content of remote file at file_url
338,634
def save(filename, obj, overwrite=False, create_directories=False): if isinstance(filename, six.string_types): filename = os.path.expanduser(filename) if not overwrite and os.path.exists(filename): raise ValueError( % filename) if create_directories: dname = os.p...
pimms.save(filename, obj) attempts to pickle the given object obj in the filename (or stream, if given). An error is raised when this cannot be accomplished; the first argument is always returned; though if the argument is a filename, it may be a differet string that refers to the same file. The ...
338,635
def substr(self, name, start, end=-1): with self.pipe as pipe: f = Future() res = pipe.substr(self.redis_key(name), start=start, end=end) def cb(): f.set(self.valueparse.decode(res.result)) pipe.on_execute(cb) return f
Return a substring of the string at key ``name``. ``start`` and ``end`` are 0-based integers specifying the portion of the string to return. :param name: str the name of the redis key :param start: int :param end: int :return: Future()
338,636
def parse_file(defn, preprocess=True): if pycparser is None: raise ImportError("Please install pycparser in order to parse C definitions") defn = .join(x for x in defn.split() if _include_re.match(x) is None) if preprocess: defn = do_preprocess(defn) preamble, ignoreme = make_pre...
Parse a series of C definitions, returns a tuple of two type mappings, one for variable definitions and one for type definitions.
338,637
def applyUserPars_steps(configObj, input_dict, step=): step_kws = {: , : } stepname = getSectionName(configObj,step) finalParDict = configObj[stepname].copy() del finalParDict[step_kws[step]] user_pars = {} for kw in finalParDict: if kw in input_dict: user_pars[kw] = input_dic...
Apply logic to turn on use of user-specified output WCS if user provides any parameter on command-line regardless of how final_wcs was set.
338,638
def get_sunrise_time(self, timeformat=): if self._sunrise_time is None: return None return timeformatutils.timeformat(self._sunrise_time, timeformat)
Returns the GMT time of sunrise :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time or '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` :type timeformat: str :returns: an int or a str or None :ra...
338,639
def grad_and_aux(fun, x): vjp, (ans, aux) = _make_vjp(lambda x: atuple(fun(x)), x) return vjp((vspace(ans).ones(), vspace(aux).zeros())), aux
Builds a function that returns the gradient of the first output and the (unmodified) second output of a function that returns two outputs.
338,640
def json_post(methodname, rtype, key): return compose( reusable, map_return(registry(rtype), itemgetter(key)), basic_interaction, map_yield(partial(_json_as_post, methodname)), oneyield, )
decorator factory for json POST queries
338,641
def compile_rcc(rccfile): print "Compileing: %s" % rccfile rccfilename = os.path.basename(rccfile) outname = rccfilename.rsplit(os.path.extsep, 1)[0] + "_rc.py" path = os.path.dirname(jukeboxcore.gui.resources.__file__) outputpath = os.path.join(path, outname) print "Outputfile: %s" % ...
Compile the given Qt resource file. The compiled file will be in the jukeboxcore.gui.resources package and ends with _rc.py :param rccfile: filepath to the rccfile :type rccfile: str :returns: None :rtype: Nonen :raises: None
338,642
def amazon_elb_trace_id(): amazon_request_id = request.headers.get(, ) trace_id_params = dict(x.split() if in x else (x, None) for x in amazon_request_id.split()) if in trace_id_params: return trace_id_params[] if in trace_id_params: return trace_id_params[] return None
Get the amazon ELB trace id from current Flask request context :return: The found Trace-ID or None if not found :rtype: str | None
338,643
def controlParameters(self, module, status): if self.use_legacy_protocol : return .format(self.moduleParameters(module), status) else: return .format(self.moduleParameters(module), status)
Returns control parameters as XML. :type module: str :type status: str :param module: The module number/ID :param status: The state to set (i.e. true (on) or false (off)) :return XML string to join with payload
338,644
def count(self, metric_name=): metric = self.table.count().name(metric_name) return self.table.aggregate([metric], by=self.by, having=self._having)
Convenience function for computing the group sizes (number of rows per group) given a grouped table. Parameters ---------- metric_name : string, default 'count' Name to use for the row count metric Returns ------- aggregated : TableExpr The a...
338,645
def setWhitespaceChars( self, chars ): self.skipWhitespace = True self.whiteChars = chars self.copyDefaultWhiteChars = False return self
Overrides the default whitespace chars
338,646
def upload_scan(self, application_id, file_path): return self._request( , + str(application_id) + , files={: open(file_path, )} )
Uploads and processes a scan file. :param application_id: Application identifier. :param file_path: Path to the scan file to be uploaded.
338,647
def fetch_next(self, query=None, **kwargs): if query: self.query = query hash_ = self._hash if hash_ in self._data: for result in self._data[hash_]: yield result if self.scraper.current_item is not self: self._move_here() ...
Generator to yield data one row at a time. Yields a Result, not the entire ResultSet. The containing ResultSet can be accessed through `Result.resultset`, but be careful not to manipulate the ResultSet until it is populated (when this generator is empty), or you may see unexpected result...
338,648
def get_bool(self, key, default=None): u return self.get_converted( key, ConversionTypeEnum.BOOL, default=default)
u""" Возвращает значение, приведенное к булеву
338,649
def _container_factory(self, **options): ac_dict = options.get("ac_dict", False) _dicts = [x for x in (options.get(o) for o in self.dict_options()) if x] if self.dict_options() and ac_dict and callable(ac_dict): return ac_dict if _dicts and calla...
The order of prirorities are ac_dict, backend specific dict class option, ac_ordered. :param options: Keyword options may contain 'ac_ordered'. :return: Factory (class or function) to make an container.
338,650
def childAtPath(self, path): if self.__root is None: return None if path[0] == : path = path[1:] path = path.split(,1) if self.getChild(path[0]) is None: return None if len(path) > 1: return self.__root.childAtPath(path[1])...
Get a child at I{path} where I{path} is a (/) separated list of element names that are expected to be children. @param path: A (/) separated list of element names. @type path: basestring @return: The leaf node at the end of I{path} @rtype: L{Element}
338,651
def betting_market_rules_update( self, rules_id, names, descriptions, account=None, **kwargs ): assert isinstance(names, list) assert isinstance(descriptions, list) if not account: if "default_account" in self.config: account = self.config["defaul...
Update betting market rules :param str rules_id: Id of the betting market rules to update :param list names: Internationalized names, e.g. ``[['de', 'Foo'], ['en', 'bar']]`` :param list descriptions: Internationalized descriptions, e.g. ``[['de', 'Foo...
338,652
def remove(self, force=False, timeout=-1): return self.delete(force=force, timeout=timeout)
Removes the rackserver with the specified URI. Note: This operation is only supported on appliances that support rack-mounted servers. Args: force (bool): If set to true, the operation completes despite any problems with network connectivity or errors on the ...
338,653
def colors(self, n=10, d=0.035): s = sum([w for clr, rng, w in self.ranges]) colors = colorlist() for i in _range(n): r = random() for clr, rng, weight in self.ranges: if weight / s >= r: break r -= weight / s colors.ap...
Returns a number of random colors from the theme.
338,654
def delete(cls, id): client = cls._new_api_client() return client.make_request(cls, , url_params={: id})
Destroy a Union object
338,655
def list_algorithms(self, page_size=None): params = {} if page_size is not None: params[] = page_size return pagination.Iterator( client=self._client, path=.format(self._instance), params=params, response_class=mdb_pb2.ListAl...
Lists the algorithms visible to this client. Algorithms are returned in lexicographical order. :rtype: :class:`.Algorithm` iterator
338,656
def fill_data_brok_from(self, data, brok_type): cls = self.__class__ for prop, entry in list(cls.properties.items()): if brok_type in entry.fill_brok: data[prop] = self.get_property_value_for_brok(prop, cls.properties) if hasat...
Add properties to 'data' parameter with properties of this object when 'brok_type' parameter is defined in fill_brok of these properties :param data: object to fill :type data: object :param brok_type: name of brok_type :type brok_type: var :return: None
338,657
def find_rt_coefficients_tot_intens(self, depth0=None): j_O, alpha_O, j_X, alpha_X = self.find_rt_coefficients(depth0=depth0) j_I = j_O + j_X alpha_I = 0.5 * (alpha_O + alpha_X) return (j_I, alpha_I)
Figure out total-intensity emission and absorption coefficients for the current parameters. **Argument** *depth0* (default None) A first guess to use for a good integration depth, in cm. If None, the most recent value is used. **Return value** A tuple ``(j...
338,658
def render(file): fp = file.open() content = fp.read() fp.close() notebook = nbformat.reads(content.decode(), as_version=4) html_exporter = HTMLExporter() html_exporter.template_file = (body, resources) = html_exporter.from_notebook_node(notebook) return body, resources
Generate the result HTML.
338,659
def user_organizations(self, user_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/organizations api_path = "/api/v2/users/{user_id}/organizations.json" api_path = api_path.format(user_id=user_id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/organizations#list-organizations
338,660
def process_fidelity(channel1, channel2, require_cptp=True): is_cptp1 = None is_cptp2 = None if isinstance(channel1, (list, np.ndarray)): channel1 = Operator(channel1) if require_cptp: is_cptp1 = channel1.is_unitary() if isinstance(channel2, (list, np.ndar...
Return the process fidelity between two quantum channels. This is given by F_p(E1, E2) = Tr[S2^dagger.S1])/dim^2 where S1 and S2 are the SuperOp matrices for channels E1 and E2, and dim is the dimension of the input output statespace. Args: channel1 (QuantumChannel or matrix): a quan...
338,661
def related_items_changed(self, instance, related_manager): assigned = related_manager.select_related("keyword") keywords = " ".join([str(a.keyword) for a in assigned]) string_field_name = list(self.fields.keys())[0] % \ self.related_field_name if get...
Stores the keywords as a single string for searching.
338,662
def verify_connectivity(config): logger.debug("Verifying Connectivity") ic = InsightsConnection(config) try: branch_info = ic.get_branch_info() except requests.ConnectionError as e: logger.debug(e) logger.debug("Failed to connect to satellite") return False excep...
Verify connectivity to satellite server
338,663
def get_count(self, request, notifications, mark_as_read=False): return Response({: notifications.filter(is_read=False).count()})
return count of unread notification
338,664
def interpolate_lat_lon(points, t, max_dt=1): if (t <= points[0][0]) or (t >= points[-1][0]): if t <= points[0][0]: dt = abs((points[0][0] - t).total_seconds()) else: dt = (t - points[-1][0]).total_seconds() if dt > max_dt: raise ValueError( ...
Return interpolated lat, lon and compass bearing for time t. Points is a list of tuples (time, lat, lon, elevation), t a datetime object.
338,665
def SaveData(self, raw_data): if self.filename is None: raise IOError("Unknown filename") logging.info("Writing back configuration to file %s", self.filename) try: os.makedirs(os.path.dirname(self.filename)) except (IOError, OSError): pass try: mode ...
Store the raw data as our configuration.
338,666
def get_query(self, query_params=None): if query_params is None: query_params = {} query = query_params[] = self.site_id if self.api_token is not None: query_params[] = self.api_token for key, value in query_params.iteritems(): if isi...
Return a query string
338,667
def preprocess(from_idx, to_idx, _params): source_exts = src_path = _params[] tgt_path = _params[] face_predictor_path = succ = set() fail = set() for idx in range(from_idx, to_idx): s_id = + str(idx) + source_path = src_path + + s_id target_path = tgt_path...
Preprocess: Convert a video into the mouth images
338,668
def marker(self): if not self._marker: assert markers, self._marker = markers.Marker(self.raw) return self._marker
Return environment marker.
338,669
def login(self, **kwargs): c_user = kwargs.pop(, env.get()) c_pass = kwargs.pop(, env.get()) c_mail = kwargs.pop(, env.get()) c_registry = kwargs.pop(, env.get()) c_insecure = kwargs.pop(, env.get()) if super(DockerFabricClient, self).login(c_user, password=c_pas...
Identical to :meth:`dockermap.client.base.DockerClientWrapper.login` with two enhancements: * additional logging; * login parameters can be passed through ``kwargs``, or set as default using the following ``env`` variables: * ``env.docker_registry_user`` (kwarg: ``username``), ...
338,670
def get_dependencies(pefile): hasher = hashlib.sha1(os.path.normpath(pefile).encode()) cachefile = hasher.hexdigest() + + os.path.basename(pefile) + cachefile = os.path.join(CACHE_DIR, cachefile) if nr.path.compare_timestamp(pefile, cachefile): continue result.append(dep) return ...
Uses Dependency Walker to get a list of dependencies for the specified PE file (a Windows executable or dynamic link library).
338,671
def get_doc_comments(text): r def make_pair(match): comment = match.group() try: end = text.find(, match.end(0)) + 1 if not in comment: next_line = next(split_delimited(, , text[end:])) else: next_line = text[end:text.find(, en...
r""" Return a list of all documentation comments in the file text. Each comment is a pair, with the first element being the comment text and the second element being the line after it, which may be needed to guess function & arguments. >>> get_doc_comments(read_file('examples/module.js'))[0][0][:4...
338,672
def chosen_probabs(probab_observations, actions): B, T = actions.shape assert (B, T + 1) == probab_observations.shape[:2] return probab_observations[np.arange(B)[:, None], np.arange(T), actions]
Picks out the probabilities of the actions along batch and time-steps. Args: probab_observations: ndarray of shape `[B, T+1, A]`, where probab_observations[b, t, i] contains the log-probability of action = i at the t^th time-step in the b^th trajectory. actions: ndarray of shape `[B, T]`, with ea...
338,673
def get(self, id): with rconnect() as conn: if id is None: raise ValueError if isinstance(id, uuid.UUID): id = str(id) if type(id) != str and type(id) != unicode: raise ValueError try: que...
Get a single instance by pk id. :param id: The UUID of the instance you want to retrieve.
338,674
def compand(self, attack=0.2, decay=1, soft_knee=2.0, threshold=-20, db_from=-20.0, db_to=-20.0): self.command.append() self.command.append(str(attack) + + str(decay)) self.command.append(str(soft_knee) + + str(threshold) + + str(db_from) + + str(db_to)) return self
compand takes 6 parameters: attack (seconds), decay (seconds), soft_knee (ex. 6 results in 6:1 compression ratio), threshold (a negative value in dB), the level below which the signal will NOT be companded (a negative value in dB), the level above which the signal will ...
338,675
def drange(start: Decimal, stop: Decimal, num: int): delta = stop - start step = delta / (num - 1) yield from (start + step * Decimal(tick) for tick in range(0, num))
A simplified version of numpy.linspace with default options
338,676
def _download_and_parse_dataset(tmp_dir, train): file_path = generator_utils.maybe_download(tmp_dir, _SNLI_ZIP, _SNLI_URL) zip_ref = zipfile.ZipFile(file_path, ) zip_ref.extractall(tmp_dir) zip_ref.close() file_name = if train else dataset_file_path = os.path.join(tmp_dir, _SNLI_DATA_PATH % file_name)...
Downloads and prepairs the dataset to be parsed by the data_generator.
338,677
def _timestamp_query_param_from_json(value, field): if _not_null(value, field): value = value.replace(" ", "T", 1) value = value.replace("Z", "") value = value.replace("+00:00", "") if "." in value: return datetime.da...
Coerce 'value' to a datetime, if set or not nullable. Args: value (str): The timestamp. field (.SchemaField): The field corresponding to the value. Returns: Optional[datetime.datetime]: The parsed datetime object from ``value`` if the ``field`` is not null (otherwise it is ...
338,678
def f_get_default(self, name, default=None, fast_access=True, with_links=True, shortcuts=True, max_depth=None, auto_load=False): try: return self.f_get(name, fast_access=fast_access, shortcuts=shortcuts, max_depth=max_depth...
Similar to `f_get`, but returns the default value if `name` is not found in the trajectory. This function uses the `f_get` method and will return the default value in case `f_get` raises an AttributeError or a DataNotInStorageError. Other errors are not handled. In contrast to ...
338,679
def cluster_health_for_indices(self, index=None, params={}, **kwargs): params[] = result = self.cluster_health(index, params, **kwargs) return self._process_cluster_health_info(result)
Return a list of cluster health of specified indices(default all), the first element is a dictionary represent a global information of the cluster such as "cluster_name", "number_of_nodes"... the second element represent a indices information list that each element is a dictionary for one index ...
338,680
def do_POST(self): self.do_initial_operations() payload = self.coap_uri.get_payload() if payload is None: logger.error("BAD POST REQUEST") self.send_error(BAD_REQUEST) return coap_response = self.client.post(self.coap_uri.pat...
Perform a POST request
338,681
def on_select_fit(self, event): fit_val = self.fit_box.GetValue() if self.s not in self.pmag_results_data[] or not self.pmag_results_data[][self.s] or fit_val == : self.clear_boxes() self.current_fit = None self.fit_box.SetStringSelection() self.t...
Picks out the fit selected in the fit combobox and sets it to the current fit of the GUI then calls the select function of the fit to set the GUI's bounds boxes and alter other such parameters Parameters ---------- event : the wx.ComboBoxEvent that triggers this function ...
338,682
def setup(sphinx): from flask import has_app_context from invenio_base.factory import create_app PACKAGES = [, , , ] if not has_app_context(): app = create_app(PACKAGES=PACKAGES) ctx = app.test_request_context() ctx.push()
Setup Sphinx object.
338,683
def apwp(data, print_results=False): pole_lat, pole_lon = bc02(data) ExpDec, ExpInc = vgp_di(pole_lat, pole_lon, data[1], data[2]) paleo_lat = magnetic_lat(ExpInc) if print_results: print() print( % (data[3], paleo_lat, ExpDec, ExpInc, pole_lat, po...
calculates expected pole positions and directions for given plate, location and age Parameters _________ data : [plate,lat,lon,age] plate : [NA, SA, AF, IN, EU, AU, ANT, GL] NA : North America SA : South America AF : Africa IN :...
338,684
def enable_log(level=logging.DEBUG): logger = logging.getLogger(__name__) logger.setLevel(level) if not logger.handlers: logger.info() logger.addHandler(logging.StreamHandler(sys.stdout))
Enable console logging. This is a utils method for try run with storops. :param level: log level, default to DEBUG
338,685
def iter_children(graph, node: BaseEntity) -> Iterable[BaseEntity]: return ( node for node, _, d in graph.in_edges(node, data=True) if d[RELATION] == IS_A )
Iterate over children of the node.
338,686
def setitem(self, startindex, fs): return self.setslice_with_length(startindex, startindex+1, fs, len(self))
Shim for easily converting old __setitem__ calls
338,687
def get_chain_details_by_pfam(self, pdb_id, chain = None): pfam_api = self.get_pfam_api() if chain: pfam_accs = pfam_api.get_pfam_accession_numbers_from_pdb_chain(pdb_id, chain) if pfam_accs: pfam_accs = {chain : pfam_accs} else: pfam_...
Returns a dict pdb_id -> chain(s) -> chain and SCOPe details. This returns Pfam-level information for a PDB chain i.e. no details on the protein, species, or domain will be returned. If there are SCOPe entries for the associated Pfam accession numbers which agree then this function returns ...
338,688
def tamper_dir(inputpath, *args, **kwargs): silent = kwargs.get(, False) if in kwargs: del kwargs[] filescount = 0 for _ in tqdm(recwalk(inputpath), desc=, disable=silent): filescount += 1 files_tampered = 0 tamper_count = 0 total_size = 0 for dirname, filepath in tqdm(re...
Randomly tamper the files content in a directory tree, recursively
338,689
def region_to_apply(self): if (self.request.region_full or (self.request.region_pct and self.request.region_xywh == (0, 0, 100, 100))): return(None, None, None, None) if (self.width <= 0 or self.height <= 0): raise IIIFError(cod...
Return the x,y,w,h parameters to extract given image width and height. Assume image width and height are available in self.width and self.height, and self.request is IIIFRequest object Expected use: (x,y,w,h) = self.region_to_apply() if (x is None): # full ima...
338,690
def comma_join(fields, oxford=True): def fmt(field): return "" % field if not fields: return "nothing" elif len(fields) == 1: return fmt(fields[0]) elif len(fields) == 2: return " and ".join([fmt(f) for f in fields]) else: result = ", ".join([fmt(f) for...
Join together words.
338,691
def remote_root(self): return os.path.relpath(self.address.spec_path, self.target_base)
The remote package root prefix portion of the the full `import_path`
338,692
def parse_firefox (url_data): filename = url_data.get_os_filename() for url, name in firefox.parse_bookmark_file(filename): url_data.add_url(url, name=name)
Parse a Firefox3 bookmark file.
338,693
def pauli_sum(*elements: Pauli) -> Pauli: terms = [] key = itemgetter(0) for term, grp in groupby(heapq.merge(*elements, key=key), key=key): coeff = sum(g[1] for g in grp) if not isclose(coeff, 0.0): terms.append((term, coeff)) return Pauli(tuple(terms))
Return the sum of elements of the Pauli algebra
338,694
def delete_project(project_id): try: res = _pybossa_req(, , project_id) if type(res).__name__ == : return True else: return res except: raise
Delete a Project with id = project_id. :param project_id: PYBOSSA Project ID :type project_id: integer :returns: True -- the response status code
338,695
def stdin_channel(self): if self._stdin_channel is None: self._stdin_channel = self.stdin_channel_class(self.context, self.session, (self.ip, self.stdin_port)) return self._...
Get the REP socket channel object to handle stdin (raw_input).
338,696
def dice_coeff(im1, im2, val=1): if isinstance(im1, basestring) and isinstance(im2, basestring) \ and os.path.isfile(im1) and os.path.basename(im1).endswith((, )) \ and os.path.isfile(im2) and os.path.basename(im2).endswith((, )): imn1 = imio.getnii(im1, output=) imn2 = imio.getnii(im2...
Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>. Input images can be given as: 1. paths to NIfTI image files or as 2. Numpy arrays. The ROI value can be given as: 1. a single integer representing one ROI out of many in the parcellation...
338,697
def __getOrganizations(self, web): orgsElements = web.find_all("a", {"class": "avatar-group-item"}) self.organizations = len(orgsElements)
Scrap the number of organizations from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node.
338,698
def get_identifier(identifier, module_globals, module_name): if isinstance(identifier, six.string_types): fn = module_globals.get(identifier) if fn is None: raise ValueError(.format(module_name, identifier)) return fn elif callable(identifier): return identifier ...
Helper utility to retrieve the callable function associated with a string identifier. Args: identifier: The identifier. Could be a string or function. module_globals: The global objects of the module. module_name: The module name Returns: The callable associated with the identi...
338,699
def webIDToStoreID(key, webid): if len(webid) != 16: return None try: int(webid, 16) except TypeError: return None except ValueError: return None l = list(webid) for nybbleid in range(7, -1, -1): a, b = _swapat(key, nybbleid) _swap(l, b, a) ...
Takes a webid (a 16-character str suitable for including in URLs) and a key (an int, a private key for decoding it) and produces a storeID.