Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
16,900
def getfile(self, project_id, file_path, ref): data = {: file_path, : ref} request = requests.get( .format(self.projects_url, project_id), headers=self.headers, data=data, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) if request.status_code == 2...
Allows you to receive information about file in repository like name, size, content. Note that file content is Base64 encoded. :param project_id: project_id :param file_path: Full path to file. Ex. lib/class.rb :param ref: The name of branch, tag or commit :return:
16,901
def getUserAuthorizations(self, login, user): self.send_getUserAuthorizations(login, user) return self.recv_getUserAuthorizations()
Parameters: - login - user
16,902
def execute(options): package_name = options[] source_directory = options[] if options[] is True: upstream = True else: upstream = False sub_tasks = {: options[], : options[], : options[]} if sub_tasks == {: False, : False, : False}: sub_tasks = {: True, ...
execute the tool with given options.
16,903
def apply_grad_zmat_tensor(grad_C, construction_table, cart_dist): if (construction_table.index != cart_dist.index).any(): message = "construction_table and cart_dist must use the same index" raise ValueError(message) X_dist = cart_dist.loc[:, [, , ]].values.T C_dist = np.tensordot(grad...
Apply the gradient for transformation to Zmatrix space onto cart_dist. Args: grad_C (:class:`numpy.ndarray`): A ``(3, n, n, 3)`` array. The mathematical details of the index layout is explained in :meth:`~chemcoord.Cartesian.get_grad_zmat()`. construction_table (pandas.DataF...
16,904
def load_csv_data(resource_name): data_bytes = pkgutil.get_data(, .format(resource_name)) if data_bytes is None: raise ValueError("No data resource found with name {}".format(resource_name)) else: data = data_bytes.decode() reader = csv.reader(data.splitlines()) nex...
Loads first column of specified CSV file from package data.
16,905
def encode_dataset_coordinates(dataset): non_dim_coord_names = set(dataset.coords) - set(dataset.dims) return _encode_coordinates(dataset._variables, dataset.attrs, non_dim_coord_names=non_dim_coord_names)
Encode coordinates on the given dataset object into variable specific and global attributes. When possible, this is done according to CF conventions. Parameters ---------- dataset : Dataset Object to encode. Returns ------- variables : dict attrs : dict
16,906
def partition_read( self, session, table, key_set, transaction=None, index=None, columns=None, partition_options=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ...
Creates a set of partition tokens that can be used to execute a read operation in parallel. Each of the returned partition tokens can be used by ``StreamingRead`` to specify a subset of the read result to read. The same session and read-only transaction must be used by the PartitionReadR...
16,907
def write(self): writer = csv.writer(self.file) for f, b in zip(self.gb.result["forward"], self.gb.result["backward"]): f = f._asdict() b = b._asdict() if not self.check_same(f, b): raise AssertionError() args_info = ", ".join(["...
Write result to the file. The output file is specified by ``file``.
16,908
def get_knownGene_hg19(self): if self._knownGene_hg19 is None: self._knownGene_hg19 = self._load_knownGene(self._get_path_knownGene_hg19()) return self._knownGene_hg19
Get UCSC knownGene table for Build 37. Returns ------- pandas.DataFrame knownGene table if loading was successful, else None
16,909
def Stichlmair_dry(Vg, rhog, mug, voidage, specific_area, C1, C2, C3, H=1.): r dp = 6*(1-voidage)/specific_area Re = Vg*rhog*dp/mug f0 = C1/Re + C2/Re**0.5 + C3 return 3/4.*f0*(1-voidage)/voidage**4.65*rhog*H/dp*Vg**2
r'''Calculates dry pressure drop across a packed column, using the Stichlmair [1]_ correlation. Uses three regressed constants for each type of packing, and voidage and specific area. Pressure drop is given by: .. math:: \Delta P_{dry} = \frac{3}{4} f_0 \frac{1-\epsilon}{\epsilon^{4.65}} ...
16,910
def send_message(self, subject=None, text=None, markdown=None, message_dict=None): message = FiestaMessage(self.api, self, subject, text, markdown, message_dict) return message.send()
Helper function to send a message to a group
16,911
def getTraceCombosByIds(self, trace_ids, adjust): self.send_getTraceCombosByIds(trace_ids, adjust) return self.recv_getTraceCombosByIds()
Not content with just one of traces, summaries or timelines? Want it all? This is the method for you. Parameters: - trace_ids - adjust
16,912
def _make_annulus_path(patch_inner, patch_outer): import matplotlib.path as mpath path_inner = patch_inner.get_path() transform_inner = patch_inner.get_transform() path_inner = transform_inner.transform_path(path_inner) path_outer = patch_outer.get_path() tran...
Defines a matplotlib annulus path from two patches. This preserves the cubic Bezier curves (CURVE4) of the aperture paths. # This is borrowed from photutils aperture.
16,913
def cli(env, package_keyname, keyword, category): table = formatting.Table(COLUMNS) manager = ordering.OrderingManager(env.client) _filter = {: {}} if keyword: _filter[][] = {: % keyword} if category: _filter[][] = {: {: % category}} items = manager.list_items(package_ke...
List package items used for ordering. The item keyNames listed can be used with `slcli order place` to specify the items that are being ordered in the package. .. Note:: Items with a numbered category, like disk0 or gpu0, can be included multiple times in an order to match how many of the ...
16,914
def absent(name, user, enc=, comment=, source=, options=None, config=, fingerprint_hash_type=None): s home directory, defaults to ".ssh/authorized_keys". Token expansion %u and %h for username and home path supported. ...
Verifies that the specified SSH key is absent name The SSH key to manage user The user who owns the SSH authorized keys file to modify enc Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa or ssh-dss comment The comment to be placed with t...
16,915
def load_dic28(): dataset_path = _load() X = _load_csv(dataset_path, ) y = X.pop().values graph1 = nx.Graph(nx.read_gml(os.path.join(dataset_path, ))) graph2 = nx.Graph(nx.read_gml(os.path.join(dataset_path, ))) graph = graph1.copy() graph.add_nodes_from(graph2.nodes(data=True)) ...
DIC28 Dataset from Pajek. This network represents connections among English words in a dictionary. It was generated from Knuth's dictionary. Two words are connected by an edge if we can reach one from the other by - changing a single character (e. g., work - word) - adding / removing a single chara...
16,916
def mouse(table, day=None): where = (("day", day),) if day else () events = db.fetch(table, where=where, order="day") for e in events: e["dt"] = datetime.datetime.fromtimestamp(e["stamp"]) stats, positions, events = stats_mouse(events, table) days, input = db.fetch("counts", order="day", ...
Handler for showing mouse statistics for specified type and day.
16,917
def set_domain_workgroup(workgroup): minion-id if six.PY2: workgroup = _to_unicode(workgroup) with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return Tru...
Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL
16,918
def values(self): "Returns all values this object can return via keys." return tuple(set(self.new.values()).union(self.old.values()))
Returns all values this object can return via keys.
16,919
def get_task_instances(self, state=None, session=None): from airflow.models.taskinstance import TaskInstance tis = session.query(TaskInstance).filter( TaskInstance.dag_id == self.dag_id, TaskInstance.execution_date == self.execution_date, ) if state: ...
Returns the task instances for this dag run
16,920
def write_bel_namespace(self, file: TextIO, use_names: bool = False) -> None: if not self.is_populated(): self.populate() if use_names and not self.has_names: raise ValueError values = ( self._get_namespace_name_to_encoding(desc=) if use...
Write as a BEL namespace file.
16,921
def _clear_screen(): if platform.system() == "Windows": tmp = os.system() else: tmp = os.system() return True
http://stackoverflow.com/questions/18937058/python-clear-screen-in-shell
16,922
def create_prefetch(self, addresses): with self._lock: for add in addresses: self._state[add] = _ContextFuture(address=add, wait_for_tree=True)
Create futures needed before starting the process of reading the address's value from the merkle tree. Args: addresses (list of str): addresses in the txn's inputs that aren't in any base context (or any in the chain).
16,923
def get_float_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False) -> Optional[float]: return get_float_raw(get_string_relative( strings, prefix1, delta, pre...
Fetches a float parameter via :func:`get_string_relative`.
16,924
async def send_message(self, message, *, end=False): if not self._send_request_done: await self.send_request() if end and self._end_done: raise ProtocolError() with self._wrapper: message, = await self._dispatch.send_message(message) awa...
Coroutine to send message to the server. If client sends UNARY request, then you should call this coroutine only once. If client sends STREAM request, then you can call this coroutine as many times as you need. .. warning:: It is important to finally end stream from the client-side ...
16,925
def get_candidate_config(self, merge=False, formal=False): command = "show configuration" if merge: command += " merge" if formal: command += " formal" response = self._execute_config_show(command) match = re.search(".*(!! IOS XR Configuration.*)...
Retrieve the configuration loaded as candidate config in your configuration session. :param merge: Merge candidate config with running config to return the complete configuration including all changed :param formal: Return configuration in IOS-XR formal config format
16,926
def assert_raises_errno(exception, errno, msg_fmt="{msg}"): def check_errno(exc): if errno != exc.errno: msg = "wrong errno: {!r} != {!r}".format(errno, exc.errno) fail( msg_fmt.format( msg=msg, exc_type=exception, ...
Fail unless an exception with a specific errno is raised with the context. >>> with assert_raises_errno(OSError, 42): ... raise OSError(42, "OS Error") ... >>> with assert_raises_errno(OSError, 44): ... raise OSError(17, "OS Error") ... Traceback (most recent call last): ...
16,927
def typevalue(self, key, value): def listconvert(value): try: return ast.literal_eval(value) except (SyntaxError, ValueError): if...
Given a parameter identified by ``key`` and an untyped string, convert that string to the type that our version of key has.
16,928
def inform(self, reading): try: self._inform_callback(self._sensor, reading) except Exception: log.exception( .format(reading, self._sensor.name, self._sensor.type))
Inform strategy creator of the sensor status.
16,929
def files_read(self, path, offset=0, count=None, **kwargs): opts = {"offset": offset} if count is not None: opts["count"] = count kwargs.setdefault("opts", opts) args = (path,) return self._client.request(, args, **kwargs)
Reads a file stored in the MFS. .. code-block:: python >>> c.files_read("/bla/file") b'hi' Parameters ---------- path : str Filepath within the MFS offset : int Byte offset at which to begin reading at count : int ...
16,930
def compare(testsuite, gold, select=): from delphin.mrs import simplemrs, compare as mrs_compare if not isinstance(testsuite, itsdb.TestSuite): if isinstance(testsuite, itsdb.ItsdbProfile): testsuite = testsuite.root testsuite = itsdb.TestSuite(testsuite) if not isinstance(...
Compare two [incr tsdb()] profiles. Args: testsuite (str, TestSuite): path to the test [incr tsdb()] testsuite or a :class:`TestSuite` object gold (str, TestSuite): path to the gold [incr tsdb()] testsuite or a :class:`TestSuite` object select: TSQL query to select (...
16,931
def find_path(name, path=None, exact=False): path = os.environ.get(, os.defpath) if path is None else path dpaths = path.split(os.pathsep) if isinstance(path, six.string_types) else path candidates = (join(dpath, name) for dpath in dpaths) if exact: if WIN32: pathext = [] + os...
Search for a file or directory on your local filesystem by name (file must be in a directory specified in a PATH environment variable) Args: fname (PathLike or str): file name to match. If exact is False this may be a glob pattern path (str or Iterable[PathLike]): list of directori...
16,932
def lrange(self, key, start, stop): redis_list = self._get_list(key, ) start, stop = self._translate_range(len(redis_list), start, stop) return redis_list[start:stop + 1]
Emulate lrange.
16,933
def make_exttrig_file(cp, ifos, sci_seg, out_dir): xmldoc = ligolw.Document() xmldoc.appendChild(ligolw.LIGO_LW()) tbl = lsctables.New(lsctables.ExtTriggersTable) cols = tbl.validcolumns xmldoc.childNodes[-1].appendChild(tbl) row = tbl.appendRow() setattr(row, "event_ra", flo...
Make an ExtTrig xml file containing information on the external trigger Parameters ---------- cp : pycbc.workflow.configuration.WorkflowConfigParser object The parsed configuration options of a pycbc.workflow.core.Workflow. ifos : str String containing the analysis interferometer IDs. sci...
16,934
def to_google(self, type, label, issuer, counter=None): warnings.warn(, DeprecationWarning) return self.to_uri(type, label, issuer, counter)
Generate the otpauth protocal string for Google Authenticator. .. deprecated:: 0.2.0 Use :func:`to_uri` instead.
16,935
def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\ null_grad_thresh=20., null_grad_val = 1./5.): bestnr = self.get_new_snr(index=index, nhigh=nhigh, column="chisq") if len(self.get_ifos()) < 3: return bestnr if self.snr > null_grad_thresh: ...
Return the BestNR statistic for this row.
16,936
def as_bel(self) -> str: return .format( str(self[IDENTIFIER]), .join(.format(self[x]) for x in PMOD_ORDER[2:] if x in self) )
Return this protein modification variant as a BEL string.
16,937
def numSegments(self, cell=None): if cell is not None: return len(self._cells[cell]._segments) return self._nextFlatIdx - len(self._freeFlatIdxs)
Returns the number of segments. :param cell: (int) Optional parameter to get the number of segments on a cell. :returns: (int) Number of segments on all cells if cell is not specified, or on a specific specified cell
16,938
def patch_namespaced_custom_object(self, group, version, namespace, plural, name, body, **kwargs): kwargs[] = True if kwargs.get(): return self.patch_namespaced_custom_object_with_http_info(group, version, namespace, plural, name, body, **kwargs) else: (data) = s...
patch the specified namespace scoped custom object This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_custom_object(group, version, namespace, plural, name, body, async_req=True) >>> ...
16,939
def _delete_reminders_from_list( self, listName): self.log.info() applescript = % locals() cmd = "\n".join(["osascript << EOT", applescript, "EOT"]) p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True) stdout, stderr = p.communicate() i...
* delete reminders from list* **Key Arguments:** - ``listName`` -- the name of the reminders list
16,940
def get_image(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.image_count): component_position, image_info = QRTPacket._get_exact( RTImage, data, component_pos...
Get image.
16,941
def render(self, rect, data): size = self.get_minimum_size(data) extra_width = rect.w - size.x extra_height = rect.h - size.y if self.scaling_col is None or not 0 <= self.scaling_col < self.cols: width_per_col = extra_width / float(self.cols) ...
Draws the cells in grid.
16,942
def password_option(*param_decls, **attrs): def decorator(f): attrs.setdefault(, True) attrs.setdefault(, True) attrs.setdefault(, True) return option(*(param_decls or (,)), **attrs)(f) return decorator
Shortcut for password prompts. This is equivalent to decorating a function with :func:`option` with the following parameters:: @click.command() @click.option('--password', prompt=True, confirmation_prompt=True, hide_input=True) def changeadmin(password): ...
16,943
def _zip_files(files, root): zip_data = StringIO() with ZipFile(zip_data, , ZIP_DEFLATED) as zip_file: for fname in files: zip_file.write(os.path.join(root, fname), fname) for zip_entry in zip_file.filelist: perms = (zip_entry.external_attr & ZIP_P...
Generates a ZIP file in-memory from a list of files. Files will be stored in the archive with relative names, and have their UNIX permissions forced to 755 or 644 (depending on whether they are user-executable in the source filesystem). Args: files (list[str]): file names to add to the archive...
16,944
def key_binding(self, keydef, mode=): def register(fun): fun.mpv_key_bindings = getattr(fun, , []) + [keydef] def unregister_all(): for keydef in fun.mpv_key_bindings: self.unregister_key_binding(keydef) fun.unregister_mpv_key_bind...
Function decorator to register a low-level key binding. The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key up" or ``'D'`` for "key down". The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the litera...
16,945
def send(self, message, *args, **kwargs): self._messages.put((message, args, kwargs), False)
Sends provided message to all listeners. Message is only added to queue and will be processed on next tick. :param Message message: Message to send.
16,946
def get_resource_url(self): name = self.__class__.resource_name url = self.__class__.rest_base_url() return "%s/%s" % (url, name)
Get resource complete url
16,947
def start(self, listen_ip=LISTEN_IP, listen_port=0): coro = self.loop.create_datagram_endpoint( lambda: self, local_addr=(listen_ip, listen_port)) self.task = self.loop.create_task(coro) return self.task
Start discovery task.
16,948
def argmin(self): return tuple(centres[index] for centres, index in zip(self.centres(), numpy.unravel_index(self.array.argmin(), self.array.shape)))
Return the co-ordinates of the bin centre containing the minimum value. Same as numpy.argmin(), converting the indexes to bin co-ordinates.
16,949
def __fetch_crate_owner_user(self, crate_id): raw_owner_user = self.client.crate_attribute(crate_id, ) owner_user = json.loads(raw_owner_user) return owner_user
Get crate user owners
16,950
def create_from_string(self, string, context=EMPTY_CONTEXT, *args, **kwargs): if not PY2 and not isinstance(string, bytes): raise TypeError("string should be an instance of bytes in Python 3") io = StringIO(string) instance = self.create_from_stream(io, context, *args, **kw...
Deserializes a new instance from a string. This is a convenience method that creates a StringIO object and calls create_instance_from_stream().
16,951
def execute_cql_query(self, query, compression): self._seqid += 1 d = self._reqs[self._seqid] = defer.Deferred() self.send_execute_cql_query(query, compression) return d
Executes a CQL (Cassandra Query Language) statement and returns a CqlResult containing the results. Parameters: - query - compression
16,952
def _DeserializeAttributeContainer(self, container_type, serialized_data): if not serialized_data: return None if self._serializers_profiler: self._serializers_profiler.StartTiming(container_type) try: serialized_string = serialized_data.decode() except UnicodeDecodeError as exc...
Deserializes an attribute container. Args: container_type (str): attribute container type. serialized_data (bytes): serialized attribute container data. Returns: AttributeContainer: attribute container or None. Raises: IOError: if the serialized data cannot be decoded. OSErr...
16,953
def label_from_lists(self, train_labels:Iterator, valid_labels:Iterator, label_cls:Callable=None, **kwargs)->: "Use the labels in `train_labels` and `valid_labels` to label the data. `label_cls` will overwrite the default." label_cls = self.train.get_label_cls(train_labels, label_cls) self.train...
Use the labels in `train_labels` and `valid_labels` to label the data. `label_cls` will overwrite the default.
16,954
def stack(recs, fields=None): if fields is None: fields = list(set.intersection( *[set(rec.dtype.names) for rec in recs])) if set(fields) == set(recs[0].dtype.names): fields = list(recs[0].dtype.names) return np.hstack([rec[fields] for rec in recs])
Stack common fields in multiple record arrays (concatenate them). Parameters ---------- recs : list List of NumPy record arrays fields : list of strings, optional (default=None) The list of fields to include in the stacked array. If None, then include the fields in common to all...
16,955
def computeISI(spikeTrains): zeroCount = 0 isi = [] cells = 0 for i in range(np.shape(spikeTrains)[0]): if cells > 0 and cells % 250 == 0: print str(cells) + " cells processed" for j in range(np.shape(spikeTrains)[1]): if spikeTrains[i][j] == 0: zeroCount += 1 elif zeroCount...
Estimates the inter-spike interval from a spike train matrix. @param spikeTrains (array) matrix of spike trains @return isi (array) matrix with the inter-spike interval obtained from the spike train. Each entry in this matrix represents the number of time-steps in-between 2 spikes as the algo...
16,956
def button_clicked(self, button): if button is self.idx_ok: chans = self.get_channels() group = self.one_grp cycle = self.get_cycles() stage = self.idx_stage.selectedItems() params = {k: v.get_value() for k, v in self.index.items()} ...
Action when button was clicked. Parameters ---------- button : instance of QPushButton which button was pressed
16,957
def telegram(): if not exists(, msg=): run() run() run() with warn_only(): run() run() else: print() run(, msg="\nCreate executable :")
Install Telegram desktop client for linux (x64). More infos: https://telegram.org https://desktop.telegram.org/
16,958
def connect_text(instance, prop, widget): def update_prop(): val = widget.text() setattr(instance, prop, val) def update_widget(val): if hasattr(widget, ): widget.blockSignals(True) widget.setText(val) widget.blockSignals(False) widg...
Connect a string callback property with a Qt widget containing text. 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 should impl...
16,959
def do_WhoIsRequest(self, apdu): if _debug: WhoIsIAmServices._debug("do_WhoIsRequest %r", apdu) if not self.localDevice: if _debug: WhoIsIAmServices._debug(" - no local device") return low_limit = apdu.deviceInstanceRangeLowLimit hi...
Respond to a Who-Is request.
16,960
def get_admin_url(obj, page=None): if obj is None: return None if page is None: page = "change" if page not in ADMIN_ALL_PAGES: raise ValueError("Invalid page name . Available pages are: {}.".format(page, ADMIN_ALL_PAGES)) app_label = obj.__class__._meta.app_label obje...
Return the URL to admin pages for this object.
16,961
async def start(self, remoteParameters): assert self._state == State.NEW assert len(remoteParameters.fingerprints) if self.transport.role == : self._role = lib.SSL_set_accept_state(self.ssl) else: self._role = lib.SSL_set_connec...
Start DTLS transport negotiation with the parameters of the remote DTLS transport. :param: remoteParameters: An :class:`RTCDtlsParameters`.
16,962
def qteImportModule(self, fileName: str): path, name = os.path.split(fileName) name, ext = os.path.splitext(name) if path == : path = sys.path else: path = [path] try: fp, pathname, desc = imp.find...
Import ``fileName`` at run-time. If ``fileName`` has no path prefix then it must be in the standard Python module path. Relative path names are possible. |Args| * ``fileName`` (**str**): file name (with full path) of module to import. |Returns| * **module**...
16,963
def unindent(self): cursor = self.textCursor() if not cursor.hasSelection(): cursor.movePosition(QTextCursor.StartOfBlock) line = foundations.strings.to_string(self.document().findBlockByNumber(cursor.blockNumber()).text()) indent_marker = re.match(r"({0})"....
Unindents the document text under cursor. :return: Method success. :rtype: bool
16,964
async def request_resource(self, type: Type[T_Resource], name: str = ) -> T_Resource: value = self.get_resource(type, name) if value is not None: return value signals = [ctx.resource_added for ctx in self.context_chain] await wait_event( ...
Look up a resource in the chain of contexts. This is like :meth:`get_resource` except that if the resource is not already available, it will wait for one to become available. :param type: type of the requested resource :param name: name of the requested resource :return: the re...
16,965
def _run_module_as_main(mod_name, alter_argv=True): try: if alter_argv or mod_name != "__main__": mod_name, loader, code, fname = _get_module_details(mod_name) else: mod_name, loader, code, fname = _get_main_module_details() except ImportError as exc: ...
Runs the designated module in the __main__ namespace Note that the executed module will have full access to the __main__ namespace. If this is not desirable, the run_module() function should be used to run the module code in a fresh namespace. At the very least, these variables in __main__...
16,966
def delete(path, dryrun=False, recursive=True, verbose=None, print_exists=True, ignore_errors=True): if verbose is None: verbose = VERBOSE if not QUIET: verbose = 1 if verbose > 0: print( % path) exists_flag = exists(path) link_flag = islink(path) ...
Removes a file, directory, or symlink
16,967
def retrieveVals(self): ntpinfo = NTPinfo() stats = ntpinfo.getPeerStats() if stats: if self.hasGraph(): self.setGraphVal(, , stats.get()) if self.hasGraph(): self.setGraphVal(, , ...
Retrieve values for graphs.
16,968
def Serialize(self, val, info): self._Serialize(val, info, self.defaultNS)
Serialize an object
16,969
def is_compatible(self): for pattern in OPTIONS[]: if fnmatch(self.package.lower(), pattern): return True return False
Check if package name is matched by compatible_patterns
16,970
def SetAuth(self, style, user=None, password=None): self.auth_style, self.auth_user, self.auth_pass = \ style, user, password return self
Change auth style, return object to user.
16,971
def get_storage_conn(storage_account=None, storage_key=None, opts=None): if opts is None: opts = {} if not storage_account: storage_account = opts.get(, None) if not storage_key: storage_key = opts.get(, None) return azure.storage.BlobService(storage_account, storage_key)
.. versionadded:: 2015.8.0 Return a storage_conn object for the storage account
16,972
def absdir(path): if not os.path.isabs(path): path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(), path))) if path is None or not os.path.isdir(path): return None return path
Return absolute, normalized path to directory, if it exists; None otherwise.
16,973
def get_update_object(self, form): pk = form.cleaned_data[] queryset = self.get_queryset() try: obj = queryset.get(pk=pk) except queryset.model.DoesNotExist: obj = None return obj
Retrieves the target object based on the update form's ``pk`` and the table's queryset.
16,974
def cached_property(prop): def cache_wrapper(self): if not hasattr(self, "_cache"): self._cache = {} if prop.__name__ not in self._cache: return_value = prop(self) if isgenerator(return_value): return_value = tuple(return_value) se...
A replacement for the property decorator that will only compute the attribute's value on the first call and serve a cached copy from then on.
16,975
def run_cmd(cmd, out=os.path.devnull, err=os.path.devnull): logger.debug(.join(cmd)) with open(out, ) as hout: proc = subprocess.Popen(cmd, stdout=hout, stderr=subprocess.PIPE) err_msg = proc.communicate()[1].decode() with open(err, ) as herr: herr.write(str(err_msg)) msg =...
Runs an external command :param list cmd: Command to run. :param str out: Output file :param str err: Error file :raises: RuntimeError
16,976
def dynacRepresentation(self): details = [ self.energyDefnFlag.val, self.energy.val, self.phase.val, self.x.val, self.y.val, self.radius.val, ] return [, [details]]
Return the Pynac representation of this Set4DAperture instance.
16,977
def _make_datablock(self): section_ids = sorted(self.sections) id_to_insert_id = {} row_count = 0 for section_id in section_ids: row_count += len(self.sections[section_id].points) id_to_insert_id[section_id] = row_count - 1 dat...
Make a data_block and sections list as required by DataWrapper
16,978
async def create_turn_endpoint(protocol_factory, server_addr, username, password, lifetime=600, ssl=False, transport=): loop = asyncio.get_event_loop() if transport == : _, inner_protocol = await loop.create_connection( lambda: TurnClientTcpProtocol(server...
Create datagram connection relayed over TURN.
16,979
def copyMakeBorder(src, top, bot, left, right, border_type=cv2.BORDER_CONSTANT, value=0): hdl = NDArrayHandle() check_call(_LIB.MXCVcopyMakeBorder(src.handle, ctypes.c_int(top), ctypes.c_int(bot), ctypes.c_int(left), ctypes.c_int(right), ...
Pad image border Wrapper for cv2.copyMakeBorder that uses mx.nd.NDArray Parameters ---------- src : NDArray Image in (width, height, channels). Others are the same with cv2.copyMakeBorder Returns ------- img : NDArray padded image
16,980
def _set_cdn_defaults(self): if self._cdn_enabled is FAULT: self._cdn_enabled = False self._cdn_uri = None self._cdn_ttl = DEFAULT_CDN_TTL self._cdn_ssl_uri = None self._cdn_streaming_uri = None self._cdn_ios_uri = None self._cdn_log_retention...
Sets all the CDN-related attributes to default values.
16,981
def get_epithet_index(): _dict = {} for k, v in AUTHOR_EPITHET.items(): _dict[k] = set(v) return _dict
Return dict of epithets (key) to a set of all author ids of that epithet (value).
16,982
def map_seqprop_resnums_to_seqprop_resnums(self, resnums, seqprop1, seqprop2): resnums = ssbio.utils.force_list(resnums) alignment = self._get_seqprop_to_seqprop_alignment(seqprop1=seqprop1, seqprop2=seqprop2) mapped = ssbio.protein.sequence.utils.alignment.map_resnum_a_to_resnum_b(re...
Map a residue number in any SeqProp to another SeqProp using the pairwise alignment information. Args: resnums (int, list): Residue numbers in seqprop1 seqprop1 (SeqProp): SeqProp object the resnums match to seqprop2 (SeqProp): SeqProp object you want to map the resnums to ...
16,983
def create_java_executor(self, dist=None): dist = dist or self.dist if self.execution_strategy == self.NAILGUN: classpath = os.pathsep.join(self.tool_classpath()) return NailgunExecutor(self._identity, self._executor_workdir, classpath, ...
Create java executor that uses this task's ng daemon, if allowed. Call only in execute() or later. TODO: Enforce this.
16,984
def register_text_type(content_type, default_encoding, dumper, loader): content_type = headers.parse_content_type(content_type) content_type.parameters.clear() key = str(content_type) _content_types[key] = content_type handler = _content_handlers.setdefault(key, _ContentHandler(key)) handl...
Register handling for a text-based content type. :param str content_type: content type to register the hooks for :param str default_encoding: encoding to use if none is present in the request :param dumper: called to decode a string into a dictionary. Calling convention: ``dumper(obj_dict)....
16,985
def MAPGenoToTrans(parsedGTF,feature): GenTransMap=parsedGTF[parsedGTF["feature"]==feature] def getExonsPositions(df): start=int(df["start"]) stop=int(df["end"]) strand=df["strand"] r=range(start,stop+1) if strand=="-": r.sort(reverse=True) r=[ st...
Gets all positions of all bases in an exon :param df: a Pandas dataframe with 'start','end', and 'strand' information for each entry. df must contain 'seqname','feature','start','end','strand','frame','gene_id', 'transcript_id','exon_id','exon_number'] :param feature: feature up...
16,986
def count(self, filter=None, session=None, **kwargs): warnings.warn("count is deprecated. Use estimated_document_count or " "count_documents instead. Please note that $where must " "be replaced by $expr, $near must be replaced by " "$geo...
**DEPRECATED** - Get the number of documents in this collection. The :meth:`count` method is deprecated and **not** supported in a transaction. Please use :meth:`count_documents` or :meth:`estimated_document_count` instead. All optional count parameters should be passed as keyword argu...
16,987
def solve(self, b_any, b, check_finite=True, p=None): if self.schur_solver is None and self.A_any_solver is None: assert ( (b is None) or (b.shape[0]==0) ) and ( (b_any is None) or (b_any.shape[0]==0) ), "shape missmatch" return b, b_any elif self.schu...
solve A \ b
16,988
def visit(self, node): for child in node: yield child for subchild in self.visit(child): yield subchild
Returns a generator that walks all children recursively.
16,989
def setup_size(self, width, height): self._iconw = max(0, width - 7) self._iconh = max(0, height - 6) self.update_all_buttons()
Set the width and height for one cell in the tooltip This is inderectly acomplished by setting the iconsizes for the buttons. :param width: the width of one cell, min. is 7 -> icon width = 0 :type width: int :param height: the height of one cell, min. is 6 -> icon height = 0 :t...
16,990
def writelines(self, lines, fmt): if isinstance(fmt, basestring): fmt = [fmt] * len(lines) for f, line in zip(fmt, lines): self.writeline(f, line, self.endian)
Write `lines` with given `format`.
16,991
def resolve_variable(provided_variable, blueprint_name): value = None if provided_variable: if not provided_variable.resolved: raise UnresolvedVariable(blueprint_name, provided_variable) value = provided_variable.value return value
Resolve a provided variable value against the variable definition. This acts as a subset of resolve_variable logic in the base module, leaving out everything that doesn't apply to CFN parameters. Args: provided_variable (:class:`stacker.variables.Variable`): The variable value provided...
16,992
def xpathCompareValues(self, inf, strict): ret = libxml2mod.xmlXPathCompareValues(self._o, inf, strict) return ret
Implement the compare operation on XPath objects: @arg1 < @arg2 (1, 1, ... @arg1 <= @arg2 (1, 0, ... @arg1 > @arg2 (0, 1, ... @arg1 >= @arg2 (0, 0, ... When neither object to be compared is a node-set and the operator is <=, <, >=, >, then the objects are compared by ...
16,993
def get_runtime_vars(varset, experiment, token): ?words=at the thing&color=red&globalname=globalvalue url = if experiment in varset: variables = dict() if token in varset[experiment]: for k,v in varset[experiment][token].items(): variables[k] = v ...
get_runtime_vars will return the urlparsed string of one or more runtime variables. If None are present, None is returned. Parameters ========== varset: the variable set, a dictionary lookup with exp_id, token, vars experiment: the exp_id to look up token: the participant id...
16,994
def password_reset_email_handler(notification): base_subject = _().format(domain=notification.site.domain) subject = getattr(settings, , base_subject) notification.email_subject = subject email_handler(notification, password_reset_email_context)
Password reset email handler.
16,995
def _make_result(cls, values, now, timezone): date = None time = None if Component.MONTH in values: year = cls._year_from_2digits(values.get(Component.YEAR, now.year), now.year) month = values[Component.MONTH] day = values.get(Component.DAY, 1) ...
Makes a date or datetime or time object from a map of component values :param values: the component values :param now: the current now :param timezone: the current timezone :return: the date, datetime, time or none if values are invalid
16,996
def parse_string(xml): string = "" dom = XML(xml) for sentence in dom(XML_SENTENCE): _anchors.clear() _attachments.clear() language = sentence.get(XML_LANGUAGE, "en") format = sentence.get(XML_TOKEN, [WORD, POS, CHUNK, PNP, ...
Returns a slash-formatted string from the given XML representation. The return value is a TokenString (for MBSP) or TaggedString (for Pattern).
16,997
def activations(self): activation = lib.EnvGetNextActivation(self._env, ffi.NULL) while activation != ffi.NULL: yield Activation(self._env, activation) activation = lib.EnvGetNextActivation(self._env, activation)
Iterate over the Activations in the Agenda.
16,998
def set_own_module(self, path): log = self._params.get(, self._discard) self._name = path self.module_add(event_target(self, , key=path, log=log), path)
This is provided so the calling process can arrange for processing to be stopped and a LegionReset exception raised when any part of the program's own module tree changes.
16,999
def show(self): self.iren.Initialize() self.ren_win.SetSize(800, 800) self.ren_win.SetWindowName(self.title) self.ren_win.Render() self.iren.Start()
Display the visualizer.