Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
348,700
def _embedding_metric_mds(matrix, dimensions=3): mds = sklearn.manifold.MDS(n_components=dimensions, dissimilarity=, metric=True) mds.fit(matrix) return mds.embedding_
Private method to calculate MMDS embedding :param dimensions: (int) :return: coordinate matrix (np.array)
348,701
def find_package(name: str) -> Tuple[Optional[Path], Path]: module = name.split(".")[0] loader = pkgutil.get_loader(module) if name == "__main__" or loader is None: package_path = Path.cwd() else: if hasattr(loader, ): filename = loader.get_filename(module) els...
Finds packages install prefix (or None) and it's containing Folder
348,702
def get_user_profile(self, auth_secret): result = {pytwis_constants.ERROR_KEY: None} loggedin, userid = self._is_loggedin(auth_secret) if not loggedin: result[pytwis_constants.ERROR_KEY] = \ pytwis_constants.ERROR_NOT_LOGGED_IN return (F...
Get the profile (i.e., username, password, etc.) of a user. Parameters ---------- auth_secret: str The authentication secret of the logged-in user. Returns ------- bool True if the logout is successful, False otherwise. result ...
348,703
def loaddfits(fitsname, coordtype=, loadtype=, starttime=None, endtime=None, pixelids=None, scantypes=None, mode=0, **kwargs): if mode not in [0, 1, 2]: raise KeyError(mode) logger.info() logger.info(.format(coordtype, starttime, endtime, mode, loadtype)) findR ...
Load a decode array from a DFITS file. Args: fitsname (str): Name of DFITS file. coordtype (str): Coordinate type included into a decode array. 'azel': Azimuth / elevation. 'radec': Right ascension / declination. loadtype (str): Data unit of xarray. 'Tsig...
348,704
def get_update_clause_from_dict(dictionary, datetime_format=): items = [] CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format) for k,v in dictionary.iteritems(): item = .format(k=k, v=v) items.append(item) clause = .join(item for item ...
Builds the update values clause of an update statement based on the dictionary representation of an instance
348,705
def getargs(): parser = argparse.ArgumentParser( description=) parser.add_argument("path", type=chkpath, nargs=, default=".", help="A valid path.") return parser.parse_args()
Return a list of valid arguments.
348,706
def tree_diff_assert(a, b, n=5, sort=False): a = dump(a) b = dump(b) if not sort: a = vformat(a).split("\n") b = vformat(b).split("\n") else: a = vformat(recursive_sort(a)).split("\n") b = vformat(recursive_sort(b)).split("\n") msg = "\n".join(difflib.unified_di...
User tree_diff() to assert a equals b. Dump any data-structure or object, traverse it depth-first and apply a unified diff, to display the result. :param a: data_structure a :param b: data_structure b :param n: lines of context :type n: int :...
348,707
def _rebuild_indicator(self): indicator = {:np.array([]), :np.array([]), :np.array([])} for term in range(self.n_terms): L = self.A[term].shape[0] K = self.F[term].shape[1] _update = {: (term+1)*np.ones((K,L)).T.rave...
update the indicator
348,708
def meth_delete(args): message = "WARNING: this will delete workflow \n\t{0}/{1}:{2}".format( args.namespace, args.method, args.snapshot_id) if not args.yes and not _confirm_prompt(message): return r = fapi.delete_repository_method(args.namespace, args.metho...
Remove (redact) a method from the method repository
348,709
def regular_to_pix(self): return mapper_util.voronoi_regular_to_pix_from_grids_and_geometry(regular_grid=self.grid_stack.regular, regular_to_nearest_pix=self.grid_stack.pix.regular_to_nearest_pix, pixel_centres=self.geometry.pixel_centres, pixel_neighbors=self.geometry.pix...
The 1D index mappings between the regular pixels and Voronoi pixelization pixels.
348,710
def _writePrediction(self, result): self.__predictionCache.append(result) if self._isBestModel: self.__flushPredictionCache()
Writes the results of one iteration of a model. The results are written to this ModelRunner's in-memory cache unless this model is the "best model" for the job. If this model is the "best model", the predictions are written out to a permanent store via a prediction output stream instance Parameters: ...
348,711
def connect_value(instance, prop, widget, value_range=None, log=False): if log: if value_range is None: raise ValueError("log option can only be set if value_range is given") else: value_range = math.log10(value_range[0]), math.log10(value_range[1]) def update_prop...
Connect a numerical callback property with a Qt widget representing a value. Parameters ---------- instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This sho...
348,712
def dropDataProducts(self, *pathnames): trash = QTreeWidget(None) updated = False for path in pathnames: item = self.dpitems.get(path) if item and not item._dp.archived: self.takeTopLevelItem(self.indexOfTopLevelItem(item)) trash.a...
Drops (that is, deletes) new (i.e. non-archived) DP items matching the given pathnames.
348,713
def _make_dataset(cls, coords): class Slice(cls._SliceType): extra_coords = coords Slice.__name__ = % ( cls.__name__, .join( % item for item in coords.items()), ) return Slice
Construct a new dataset given the coordinates.
348,714
def refunds_get(self, **kwargs): request = TOPRequest() for k, v in kwargs.iteritems(): if k not in (, , , , , ) and v==None: continue request[k] = v self.create(self.execute(request), fields=[, ], models={:NotifyRefund}) return self.notify_refunds
taobao.increment.refunds.get 获取退款变更通知信息 开通主动通知业务的APP可以通过该接口获取用户的退款变更通知信息 建议在获取增量消息的时间间隔是:半个小时
348,715
def getTextualNode(self, textId, subreference=None, prevnext=False, metadata=False): if subreference: textId = "{}:{}".format(textId, subreference) if prevnext or metadata: return self.getPassagePlus(urn=textId) else: return self.getPassage(urn=text...
Retrieve a text node from the API :param textId: CtsTextMetadata Identifier :param subreference: CapitainsCtsPassage Reference :param prevnext: Retrieve graph representing previous and next passage :param metadata: Retrieve metadata about the passage and the text :return: GetPas...
348,716
def stop(self): logger.debug() self._closing = True self.stop_consuming() self._connection.ioloop.start() logger.debug()
Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again, becuase this method is invoked when ...
348,717
def progress_stats(self, id): schema = ProgressSchema() resp = self.service.get(self.base+str(id)+, params={: }) return self.service.decode(schema, resp)
Compute progress stats for a result. :param id: Result ID as an int. :return: :class:`results.Progress <results.Progress>` object :rtype: results.Progress
348,718
def home_timeline(self, delegate, params={}, extra_args=None): return self.__get(, delegate, params, txml.Statuses, extra_args=extra_args)
Get updates from friends. Calls the delgate once for each status object received.
348,719
def invalidate_m2m_cache(sender, instance, model, **kwargs): logger.debug(.format(sender)) update_model_cache(instance._meta.db_table) update_model_cache(model._meta.db_table)
Signal receiver for models to invalidate model cache for many-to-many relationship. Parameters ~~~~~~~~~~ sender The model class instance The instance whose many-to-many relation is updated. model The class of the objects that are added to, removed from or cleared from the r...
348,720
def isrot(m, ntol, dtol): m = stypes.toDoubleMatrix(m) ntol = ctypes.c_double(ntol) dtol = ctypes.c_double(dtol) return bool(libspice.isrot_c(m, ntol, dtol))
Indicate whether a 3x3 matrix is a rotation matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrot_c.html :param m: A matrix to be tested. :type m: 3x3-Element Array of floats :param ntol: Tolerance for the norms of the columns of m. :type ntol: float :param dtol: ...
348,721
def get_callable_attr(self, attr_name): if not hasattr(self.doubled_obj, attr_name): return None func = getattr(self.doubled_obj, attr_name) if not is_callable(func): return None attr = Attribute( func, , self.double...
Used to double methods added to an object after creation :param str attr_name: the name of the original attribute to return :return: Attribute or None. :rtype: func
348,722
def filename(self, exists=os.path.exists, cython_suffix_re=CYTHON_SUFFIX_RE): filename = self.frame.f_globals.get(, ) if filename is None: filename = if filename.endswith((, )): filename = filename[:-1] elif filename.endswith(): filename =...
A string with absolute path to file. :type: str
348,723
def get_row_services(self, row): bsc = getToolByName(self, ) services = set() for val in row.get(, []): brains = bsc(portal_type=, getKeyword=val) if not brains: brains = bsc(portal_type=, title=val) if not brains: brai...
Return a list of services which are referenced in Analyses. values may be UID, Title or Keyword.
348,724
def on_trial_add(self, trial_runner, trial): cur_bracket = self._state["bracket"] cur_band = self._hyperbands[self._state["band_idx"]] if cur_bracket is None or cur_bracket.filled(): retry = True while retry: if self._cur_band_fi...
Adds new trial. On a new trial add, if current bracket is not filled, add to current bracket. Else, if current band is not filled, create new bracket, add to current bracket. Else, create new iteration, create new bracket, add to bracket.
348,725
def cudaPointerGetAttributes(ptr): attributes = cudaPointerAttributes() status = \ _libcudart.cudaPointerGetAttributes(ctypes.byref(attributes), ptr) cudaCheckStatus(status) return attributes.memoryType, attributes.device
Get memory pointer attributes. Returns attributes of the specified pointer. Parameters ---------- ptr : ctypes pointer Memory pointer to examine. Returns ------- memory_type : int Memory type; 1 indicates host memory, 2 indicates device memory. device : int ...
348,726
def _read_kw(ctx: ReaderContext) -> keyword.Keyword: start = ctx.reader.advance() assert start == ":" ns, name = _read_namespaced(ctx) if "." in name: raise SyntaxError("Found in keyword name") return keyword.keyword(name, ns=ns)
Return a keyword from the input stream.
348,727
def _harmonize_subset_types(set_, subset_tuples): if is_tuple(set_): return subset_tuples else: subset_class = set_.__class__ if is_set(set_) else tuple return imap(subset_class, subset_tuples)
Possibly convert an iterable of tuples with subsets of given "set", to an iterable of :class:`set` objects if original "set" was so too.
348,728
def create_excel_workbook(data, result_info_key, identifier_keys): workbook = analytics_data_excel.get_excel_workbook(data, result_info_key, identifier_keys) adjust_column_width_workbook(workbook) return workbook
Calls the analytics_data_excel module to create the Workbook
348,729
def nvmlDeviceGetPowerManagementLimitConstraints(handle): r c_minLimit = c_uint() c_maxLimit = c_uint() fn = _nvmlGetFunctionPointer("nvmlDeviceGetPowerManagementLimitConstraints") ret = fn(handle, byref(c_minLimit), byref(c_maxLimit)) _nvmlCheckReturn(ret) return [c_minLimit.value, c_maxLim...
r""" /** * Retrieves information about possible values of power management limits on this device. * * For Kepler &tm; or newer fully supported devices. * * @param device The identifier of the target device * @param minLimit Refe...
348,730
def read_plink(file_prefix, verbose=True): r from dask.array import concatenate file_prefixes = sorted(glob(file_prefix)) if len(file_prefixes) == 0: file_prefixes = [file_prefix.replace("*", "")] file_prefixes = sorted(_clean_prefixes(file_prefixes)) fn = [] for fp in file_prefix...
r"""Read PLINK files into Pandas data frames. Parameters ---------- file_prefix : str Path prefix to the set of PLINK files. It supports loading many BED files at once using globstrings wildcard. verbose : bool ``True`` for progress information; ``False`` otherwise. Returns...
348,731
def get(self, floating_ip_id): fip = self.client.show_floatingip(floating_ip_id).get() self._set_instance_info(fip) return FloatingIp(fip)
Fetches the floating IP. :returns: FloatingIp object corresponding to floating_ip_id
348,732
def get_metadata(self): if self.path_or_name is None: raise ValueError("You cannot explore the metadata of an intermediate query." "You can get metadata only after a load_from_local or load_from_remote") if self.location == : return self.__ge...
Returns the metadata related to the current GMQLDataset. This function can be used only when a local dataset is loaded using the :meth:`~gmql.dataset.loaders.Loader.load_from_path` and no other operation has been called on the GMQLDataset. The metadata are returned in the form of a Pandas Dataf...
348,733
def parse_args_and_kwargs(self, cmdline): args = [] kwargs = {} if len(cmdline) > 1: for item in cmdline[1:]: if in item: (key, value) = item.split(, 1) kwargs[key] = value else: ...
cmdline: list returns tuple of: args (list), kwargs (dict)
348,734
def ReadString(self): length = self.ReadUInt8() return self.unpack(str(length) + , length)
Read a string from the stream. Returns: str:
348,735
def freeze(self): self.__dict__[] = True for child in self._children.values(): child.freeze()
Causes the ConfigTree to become read only. This is useful for loading and then freezing configurations that should not be modified at runtime.
348,736
def detect_python2(source, pathname): RTs.setup_detect_python2() try: tree = RTs._rt_py2_detect.refactor_string(source, pathname) except ParseError as e: if e.msg != or e.value != : raise tree = RTs._rtp.refactor_string(source, pathname) if source != str(tree)[...
Returns a bool indicating whether we think the code is Py2
348,737
def get_xlmhg_stat(v, X, L, tol=DEFAULT_TOL): assert isinstance(v, np.ndarray) and v.ndim == 1 and \ np.issubdtype(v.dtype, np.integer) assert isinstance(X, int) assert isinstance(L, int) assert isinstance(tol, float) N = v.size if not N > 0: raise ValueError() if no...
Calculate the XL-mHG test statistic using recurrence relations. Parameters ---------- v: np.ndarray with dtype=np.uint8 The ranked list. X: int The XL-mHG ``X`` parameter. L: int The XL-mHG ``L`` parameter. tol: float, optional The tolerance used for comparin...
348,738
def get_sidecar_container(self, volume_mounts): return get_sidecar_container( job_container_name=self.job_container_name, sidecar_container_name=self.sidecar_container_name, sidecar_docker_image=self.sidecar_docker_image, sidecar_docker_image_pull_policy=...
Pod sidecar container for task logs.
348,739
def get_property(self, index, doctype, name): return self.indices[index][doctype].properties[name]
Returns a property of a given type :return a mapped property
348,740
def true_ces(subsystem, previous_state, next_state): network = subsystem.network nodes = subsystem.node_indices state = subsystem.state _events = events(network, previous_state, state, next_state, nodes) if not _events: log.info("Finished calculating, no echo events.") return ...
Set of all sets of elements that have true causes and true effects. .. note:: Since the true |CauseEffectStructure| is always about the full system, the background conditions don't matter and the subsystem should be conditioned on the current state.
348,741
def plotting_class(cls, obj): if isinstance(obj, AdjointLayout) or obj is AdjointLayout: obj = Layout if isinstance(obj, type): element_type = obj else: element_type = obj.type if isinstance(obj, HoloMap) else type(obj) try: plotc...
Given an object or Element class, return the suitable plotting class needed to render it with the current renderer.
348,742
def _time_to_gps(time): time = time.utc date = time.datetime micro = date.microsecond if isinstance(date, datetime.datetime) else 0 return LIGOTimeGPS(int(time.gps), int(micro*1e3))
Convert a `Time` into `LIGOTimeGPS`. This method uses `datetime.datetime` underneath, which restricts to microsecond precision by design. This should probably be fixed... Parameters ---------- time : `~astropy.time.Time` formatted `Time` object to convert Returns ------- gps :...
348,743
def _ParseLogLine(self, parser_mediator, structure): if not self._xchat_year: return time_elements_tuple = self._GetTimeElementsTuple(structure) try: date_time = dfdatetime_time_elements.TimeElements( time_elements_tuple=time_elements_tuple) date_time.is_local_time = True ...
Parses a log line. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file.
348,744
def bbox2path(xmin, xmax, ymin, ymax): b = Line(xmin + 1j*ymin, xmax + 1j*ymin) t = Line(xmin + 1j*ymax, xmax + 1j*ymax) r = Line(xmax + 1j*ymin, xmax + 1j*ymax) l = Line(xmin + 1j*ymin, xmin + 1j*ymax) return Path(b, r, t.reversed(), l.reversed())
Converts a bounding box 4-tuple to a Path object.
348,745
def examples(): sci = InterLexClient( api_key = os.environ.get(), base_url = , ) entity = { : , : , : , : , : { : , }, : [ { : }, { : ...
Examples of how to use. Default are that some functions are commented out in order to not cause harm to existing metadata within the database.
348,746
def chartDF(symbol, timeframe=, date=None, token=, version=): c = chart(symbol, timeframe, date, token, version) df = pd.DataFrame(c) _toDatetime(df) if timeframe is not None and timeframe != : _reindex(df, ) else: if not df.empty: df.set_index([, ], inplace=True) ...
Historical price/volume data, daily and intraday https://iexcloud.io/docs/api/#historical-prices Data Schedule 1d: -9:30-4pm ET Mon-Fri on regular market trading days -9:30-1pm ET on early close trading days All others: -Prior trading day available after 4am ET Tue-Sat Args: ...
348,747
def parse_config_input_output(args=sys.argv): parser = argparse.ArgumentParser( description=) parser.add_argument( , help=, metavar=, type=extant_file) parser.add_argument( , help=, metavar=, type=extant_dir) parser.add_argument( , ...
Parse the args using the config_file, input_dir, output_dir pattern Args: args: sys.argv Returns: The populated namespace object from parser.parse_args(). Raises: TBD
348,748
def copy(self): model = self._model self._model = None for i in self._metabolites: i._model = None for i in self._genes: i._model = None new_reaction = deepcopy(self) self._model = model for i in self._me...
Copy a reaction The referenced metabolites and genes are also copied.
348,749
def downloads(request): all_metadata = sorted(db.metadata.find(), key=lambda x: x[]) return render(request, , {: all_metadata})
Context: - all_metadata Templates: - billy/web/public/downloads.html
348,750
def cli(ctx): cmd = click.prompt() desc = click.prompt() alias = click.prompt(, default=) utils.save_command(cmd, desc, alias) utils.log(ctx, .format(cmd, desc))
Saves a new command
348,751
def do_shell(self, argv): import subprocess argv = argv[1:] if not argv: argv = os.environ[self.shell_variable] try: p = subprocess.Popen(argv, shell=(sys.platform==)) except EnvironmentError as ...
\ shell [COMMANDLINE] Execute COMMANDLINE in a subshell. 'sh' and '!' are synonyms.
348,752
def execute_commands(self, mapping, *args, **kwargs): def is_script_command(command): return isinstance(command[0], Script) def check_script_load_result(script, result): if script.sha != result: raise AssertionError( .format( ...
Concurrently executes a sequence of commands on a Redis cluster that are associated with a routing key, returning a new mapping where values are a list of results that correspond to the command in the same position. For example:: >>> cluster.execute_commands({ ... 'foo...
348,753
def fail(self): if self.failed is True: raise AttributeError("Cannot fail {} - it has already failed.".format(self)) else: self.failed = True self.time_of_death = timenow() self.network.calculate_full() for v in self.vectors(): ...
Fail a node, setting its status to "failed". Also fails all vectors that connect to or from the node. You cannot fail a node that has already failed, but you can fail a dead node. Set node.failed to True and :attr:`~dallinger.models.Node.time_of_death` to now. Instruct all not-...
348,754
def add_edge(self, src, dst): if src not in self.physical_qubits: self.add_physical_qubit(src) if dst not in self.physical_qubits: self.add_physical_qubit(dst) self.graph.add_edge(src, dst) self._dist_matrix = None
Add directed edge to coupling graph. src (int): source physical qubit dst (int): destination physical qubit
348,755
def get_nested_value(field_path, data): field_names = parse_field_path(field_path) nested_data = data for index, field_name in enumerate(field_names): if isinstance(nested_data, collections_abc.Mapping): if field_name in nested_data: nested_data = nested_data[field_...
Get a (potentially nested) value from a dictionary. If the data is nested, for example: .. code-block:: python >>> data { 'top1': { 'middle2': { 'bottom3': 20, 'bottom4': 22, }, 'middle5': True, ...
348,756
def _load_image(cls, rkey): v = cls._stock[rkey] img = None itype = v[] if itype in (, ): img = tk.PhotoImage(format=v[], data=v[]) elif itype == : img = v[] else: img = tk.PhotoImage(file=v[]) cls._cached[rkey] = img ...
Load image from file or return the cached instance.
348,757
def disable(identifier, children_only=False): DISABLED_TYPES.disable(identifier=identifier, children_only=children_only)
Disable an include type :param identifier: module or name of the include type :param children_only: disable the include type only for child processes, not the current process The ``identifier`` can be specified in multiple ways to disable an include type. See :py:meth:`~.DisabledIncludeTypes.disable` ...
348,758
def Architecture_var(cls, v, serializerVars, extraTypes, extraTypes_serialized, ctx, childCtx): t = v._dtype if isinstance(t, HArray) and v.defVal.vldMask: if v.drivers: raise SerializerException("Verilog does not support RAMs" ...
:return: list of extra discovered processes
348,759
def subdevicenames(self) -> Tuple[str, ...]: self: NetCDFVariableBase return tuple(self.sequences.keys())
A |tuple| containing the device names.
348,760
def read(url, **args): info, data = url.path.split() info = data_re.search(info).groupdict() mediatype = info.setdefault(, ) if in mediatype: mimetype, params = mediatype.split(, 1) params = [p.split() for p in params.split()] params = dict((k.strip(), v.strip()) for k, v i...
Loads an object from a data URI.
348,761
def to_tables(cols): tables = OrderedDict() for col in cols: tname = col["table_name"] if tname not in tables: tables[tname] = OrderedDict() tables[tname][col["column_name"]] = col return tables
Builds and returns a Dictionary whose keys are table names and values are OrderedDicts whose keys are column names and values are the col objects from which the definition is derived.
348,762
def unfreeze(name): if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = [, , name] subprocess.check_call(cmd)
unfreezes the container
348,763
def save_default_values(dsp, path): import dill with open(path, ) as f: dill.dump(dsp.default_values, f)
Write Dispatcher default values in Python pickle format. Pickles are a serialized byte stream of a Python object. This format will preserve Python objects used as nodes or edges. :param dsp: A dispatcher that identifies the model adopted. :type dsp: schedula.Dispatcher :param path: ...
348,764
def parse_insert_metrics(fn): with open(fn) as f: lines = [x.strip().split() for x in f.readlines()] index = lines[6] vals = lines[7] for i in range(len(index) - len(vals)): vals.append(np.nan) for i, v in enumerate(vals): if type(v) == str: try: ...
Parse the output from Picard's CollectInsertSizeMetrics and return as pandas Series. Parameters ---------- filename : str of filename or file handle Filename of the Picard output you want to parse. Returns ------- metrics : pandas.Series Insert size metrics. hist : pan...
348,765
def run(self): has_npm = npm_installation_check() if has_npm: run_npm_install() else: print("Warning: npm not installed using prebuilded js files!", file=sys.stderr) for js in JS_FILES: downloaded_js_name = os.path.join(TOP_D...
Download npm packages required by package.json and extract required files from them
348,766
def cholesky(A, ordering_method=, return_type=RETURN_P_L, use_long=False): = L L logger.debug(.format(A, ordering_method, return_type, use_long)) return_types = (RETURN_L, RETURN_L_D, RETURN_P_L, RETURN_P_L_D) if ordering_method not in CHOLMOD_ORDERING_METHODS: raise ValueError(.format(or...
P A P' = L L'
348,767
def _handle_bad_rest_arguments(self, controller, remainder, request): argspec = self._get_args_for_controller(controller) fixed_args = len(argspec) - len( request.pecan.get(, []) ) if len(remainder) < fixed_args: abo...
Ensure that the argspec for a discovered controller actually matched the positional arguments in the request path. If not, raise a webob.exc.HTTPBadRequest.
348,768
def import_(self, data): return self.__import(json.loads(data, **self.kwargs))
Read JSON from `data`.
348,769
def get_temp_dir(keep=False): dname = tempfile.mkdtemp(prefix="scapy") if not keep: conf.temp_files.append(dname) return dname
Creates a temporary file, and returns its name. :param keep: If False (default), the directory will be recursively deleted when Scapy exits. :return: A full path to a temporary directory.
348,770
def getpcmd(pid): if os.name == "nt": cmd = % (pid, ) with os.popen(cmd, ) as p: lines = [line for line in p.readlines() if line.strip("\r\n ") != ""] if lines: _, val = lines return val elif sys.platform == "darwin": ...
Returns command of process. :param pid:
348,771
def create(self, repo_user, repo_name, issue_number, body): return self.api.makeRequest( [, repo_user, repo_name, , issue_number, ], method=, post=dict(body=body))
PATCH /repos/:owner/:repo/issues/:number/comments :param issue_number: The issue's (or pull request's) number :param body: The body of this comment
348,772
def parallel(collection, method, processes=None, args=None, **kwargs): if processes is None: processes = min(mp.cpu_count(), 20) print "Running parallel process on " + str(processes) + " cores. :-)" pool = mp.Pool(processes=processes) PROC = [] tic = time.time() for main...
Processes a collection in parallel. Parameters ---------- collection : list i.e. list of Record objects method : method to call on each Record processes : int number of processes to run on [defaults to number of cores on machine] batch_size : int lenght of each batch [de...
348,773
def _process_model_dict(self, d): del d[] del d[] del d[] if d[] == self.default_model_expr: del d[] if YTRANSFORM_MAPPING[d[]] == self.default_ytransform: del d[] d["name"] = yamlio.to_scalar_safe(d["name"]) return d
Remove redundant items from a model's configuration dict. Parameters ---------- d : dict Modified in place. Returns ------- dict Modified `d`.
348,774
def _drives_list(self): drives_list = [] for member in self.drives: drives_list.append(sys_drives.Drive( self._conn, member.get(), self.redfish_version)) return drives_list
Gets the list of drives :return a list of drives.
348,775
def separate(word, extract_shadda=False): stack1 = stack.Stack(word) stack1.items.reverse() letters = stack.Stack() marks = stack.Stack() vowels = HARAKAT last1 = stack1.pop() marks.pop() marks.push(last1) elif last1 == SHADDA: ...
separate the letters from the vowels, in arabic word, if a letter hasn't a haraka, the not definited haraka is attributed. return ( letters, vowels) @param word: the input word @type word: unicode @param extract_shadda: extract shadda as seperate text @type extract_shadda: Boolean @return:...
348,776
def canonicalize(self, path): if os.path.isabs(path): out = os.path.normpath(path) else: out = os.path.normpath( + path) if sys.platform == : out = out.replace(, ) return out
Return the canonical form of a path on the server. For example, if the server's home folder is C{/home/foo}, the path C{"../betty"} would be canonicalized to C{"/home/betty"}. Note the obvious security issues: if you're serving files only from a specific folder, you probably don't want...
348,777
def validate_property_directives(directives): for directive_name in six.iterkeys(directives): if directive_name in VERTEX_ONLY_DIRECTIVES: raise GraphQLCompilationError( u.format(directive_name))
Validate the directives that appear at a property field.
348,778
def resolve_aliases(data_type): if not is_alias(data_type): return data_type resolved = resolve_aliases(data_type.data_type) data_type.data_type = resolved return resolved
Resolve all chained / nested aliases. This will recursively point nested aliases to their resolved data type (first non-alias in the chain). Note: This differs from unwrap_alias which simply identifies/returns the resolved data type. Args: data_type (DataType): The target DataType/Alias to res...
348,779
def print_version (out=stdout): print(configuration.App, _("released"), configuration.ReleaseDate, file=out) print(configuration.Copyright, file=out)
Print the program version (output defaults to stdout).
348,780
def _process_image_id(self): try: image_info = self.image_id.strip().split() self.image_publisher = image_info[0] self.image_offer = image_info[1] self.image_sku = image_info[2] self.image_version = image_info[3] except Exception: ...
Split image id into component values. Example: SUSE:SLES:12-SP3:2018.01.04 Publisher:Offer:Sku:Version Raises: If image_id is not a valid format.
348,781
def verification_resource(self, verification_id, audio=False): params = {} if audio: params["audio"] = True response = self._get(url.verifications_id.format(id=verification_id), params=params) self._check_response(response, 200) return self._create_response(...
Get Verification Resource. Uses GET to /verifications/<verification_id> interface. :Args: * *verification_id*: (str) Verification ID * *audio*: (boolean) If True, audio data associated with verification will be returned. :Returns: (dict) Verification data as shown `here <https:...
348,782
def _check_data_flow_ports(self, data_flow): from_state_id = data_flow.from_state to_state_id = data_flow.to_state from_data_port_id = data_flow.from_key to_data_port_id = data_flow.to_key from_data_port = self.get_data_port(from_state_id, from_data_port_id) ...
Checks the validity of the ports of a data flow Checks whether the ports of a data flow are existing and whether it is allowed to connect these ports. :param rafcon.core.data_flow.DataFlow data_flow: The data flow to be checked :return bool validity, str message: validity is True, when the dat...
348,783
def clear_all(tgt=None, tgt_type=): return _clear_cache(tgt, tgt_type, clear_pillar_flag=True, clear_grains_flag=True, clear_mine_flag=True)
.. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Clear the cached pillar, grains, and mine data of the targeted minions CLI Example: .. code-block:: bash salt-run cache.clear_all
348,784
def black(cls, string, auto=False): return cls.colorize(, string, auto=auto)
Color-code entire string. :param str string: String to colorize. :param bool auto: Enable auto-color (dark/light terminal). :return: Class instance for colorized string. :rtype: Color
348,785
def getAvgBySweep(abf,feature,T0=None,T1=None): if T1 is None: T1=abf.sweepLength if T0 is None: T0=0 data = [np.empty((0))]*abf.sweeps for AP in cm.dictFlat(cm.matrixToDicts(abf.APs)): if T0<AP[]<T1: val=AP[feature] data[int(AP[])]=np.concatenate((da...
return average of a feature divided by sweep.
348,786
def subtags(subtags): result = [] if not isinstance(subtags, list): subtags = [subtags] for subtag in subtags: for type in tags.types(subtag): result.append(Subtag(subtag, type)) return result
Get a list of existing :class:`language_tags.Subtag.Subtag` objects given the input subtag(s). :param subtags: string subtag or list of string subtags. :return: a list of existing :class:`language_tags.Subtag.Subtag` objects. The return list can be empty.
348,787
def send_single_file(self, sender, receiver, media_id): return self.send_file(sender, , receiver, media_id)
发送单聊文件消息 :param sender: 发送人 :param receiver: 接收人成员 ID :param media_id: 文件id,可以调用上传素材文件接口获取, 文件须大于4字节 :return: 返回的 JSON 数据包
348,788
def price_insert_filter(price_dict): if not isinstance(price_dict, dict): raise TypeError("dict_list is not a list. Please try again") required = ["period", "exchange", "open", "close", "high", "low", "volumefrom", "volumeto"] pkeys = price_dict.keys() for r in required: if r not i...
Price has a set of requirements: - period -> [minute, hour, day] - exchange - open - close - high - low - volumefrom - volumeto Ensure that we have all of them for inserts. Will
348,789
def optimize(self): self.check_session() result = self.session.optimize() if self.autosession: self.commit() return result
Optimize index for faster by-document-id queries.
348,790
def parse_definition(self, class_): start = self.line self.consume(tk.NAME) name = self.current.value self.log.debug("parsing %s ", class_.__name__, name) self.stream.move() if self.current.kind == tk.OP and self.current.value == : parenthesis_level =...
Parse a definition and return its value in a `class_` object.
348,791
def list_files(self, prefix, flat=False): layer_path = self.get_path_to_file("") path = os.path.join(layer_path, prefix) for blob in self._bucket.list_blobs(prefix=path): filename = blob.name.replace(layer_path, ) if not flat and filename[-1] != : yield filename elif f...
List the files in the layer with the given prefix. flat means only generate one level of a directory, while non-flat means generate all file paths with that prefix.
348,792
def find_data_objects(classname=None, state=None, visibility=None, name=None, name_mode=, properties=None, typename=None, tag=None, tags=None, link=None, project=None, folder=None, recurse=None, modified_after=None, modified_before=...
:param classname: Class with which to restrict the search, i.e. one of "record", "file", "applet", "workflow" :type classname: string :param state: State of the object ("open", "closing", "closed", "any") :type state: string :param visibility: Visibility of the object ("hidden", "visible...
348,793
def allreduce_ring_single_shard(xs, devices, reduction_fn_string="SUM"): n = len(xs) binary_reduction = mtf.binary_reduction_fn(reduction_fn_string) assert len(devices) == n, "devices must be a list of length len(xs)" if n == 1: return xs result = [None] * n if n % 2 == 0: left_center = n // 2 - ...
Compute the reduction of all Tensors and put the result everywhere. Performance-optimized for a ring of devices. Args: xs: a list of n tf.Tensors devices: a list of strings reduction_fn_string: "SUM" or "MAX" Returns: a list of n Tensors Raises: ValueError: if devices is not a list of n s...
348,794
def on(self, message, namespace=None): namespace = namespace or def decorator(handler): def _handler(sid, *args): return self._handle_event(handler, message, namespace, sid, *args) if self.server: ...
Decorator to register a SocketIO event handler. This decorator must be applied to SocketIO event handlers. Example:: @socketio.on('my event', namespace='/chat') def handle_my_custom_event(json): print('received json: ' + str(json)) :param message: The name of t...
348,795
def _accumulate_sufficient_statistics(self, stats, X, framelogprob, posteriors, fwdlattice, bwdlattice): stats[] += 1 if in self.params: stats[] += posteriors[0] if in self.params: n_samples, n_components = framelogprob...
Updates sufficient statistics from a given sample. Parameters ---------- stats : dict Sufficient statistics as returned by :meth:`~base._BaseHMM._initialize_sufficient_statistics`. X : array, shape (n_samples, n_features) Sample sequence. fr...
348,796
def _points_within_distance(self, pnt1, pnt2): if self._get_distance(pnt1, pnt2) <= self.distance: return True return False
Returns true if lat/lon points are within given distance in metres.
348,797
def cmd(send, msg, _): if not msg: msg = textutils.gen_word() send(textutils.gen_slogan(msg))
Gets a slogan. Syntax: {command} [text]
348,798
def unregister_file(self, file_node, raise_exception=False): if raise_exception: if not file_node in self.list_file_nodes(): raise foundations.exceptions.ProgrammingError("{0} | file isn{0}FileNode'.".format(file_node)) parent = file_node.parent row = fil...
Unregisters given :class:`umbra.components.factory.script_editor.nodes.FileNode` class Node from the Model. :param file_node: FileNode to unregister. :type file_node: FileNode :param raise_exception: Raise the exception. :type raise_exception: bool :return: FileNode. :rt...
348,799
def run_process(self, analysis, action_name, message=): if action_name == : analysis.on_connect(self.executable, self.zmq_publish) while not analysis.zmq_handshake: yield tornado.gen.sleep(0.1) log.debug(.format(action_name)) analysis.zmq_send({: actio...
Executes an process in the analysis with the given message. It also handles the start and stop signals in case a process_id is given.