Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
352,100 | def sender(address, use_queue=True, **kwds):
return QueuedSender(address, **kwds) if use_queue else Sender(address) | :param str address: a pair (ip_address, port) to pass to socket.connect
:param bool use_queue: if True, run the connection in a different thread
with a queue |
352,101 | def screen_cv2(self):
hwnd = win32gui.GetDesktopWindow()
left, top, right, bottom = self.rect
width, height = right-left, bottom-top
win32gui.BitBlt(self._hdcmem, 0, 0, width, height,
self._hdcwin, left, top, win32con.SRCCOPY)
... | cv2 Image of current window screen |
352,102 | def generate_html_report(base_path, asset_id):
jenv = Environment(loader=PackageLoader(, ))
s = Session()
asset = s.query(AssetList).filter_by(id=asset_id).first()
if not asset:
print % asset_id
return
filename = os.path.join(base_path, % (
asset.name,
dat... | Generates the HTML report and dumps it into the specified filename |
352,103 | def kill(self, dwExitCode = 0):
hProcess = self.get_handle(win32.PROCESS_TERMINATE)
win32.TerminateProcess(hProcess, dwExitCode) | Terminates the execution of the process.
@raise WindowsError: On error an exception is raised. |
352,104 | def is_date(property_name, *, format=None, present_optional=False, message=None):
def check(val):
if val is None:
return present_optional
else:
is_date, _ = util.try_parse_date(val)
return is_date
return Validation(check, property_name, message) | Returns a Validation that checks a value as a date. |
352,105 | def _es_text(settings, text_formating = {}):
s = {k: settings[k] for k in (ConsoleWidget.SETTING_FLAG_PLAIN,)}
s.update(text_formating)
return s | Extract text formating related subset of widget settings. |
352,106 | def _get_doubles_target(module, class_name, path):
try:
doubles_target = getattr(module, class_name)
if isinstance(doubles_target, ObjectDouble):
return doubles_target._doubles_target
if not isclass(doubles_target):
raise VerifyingDoubleImportError(
... | Validate and return the class to be doubled.
:param module module: The module that contains the class that will be doubled.
:param str class_name: The name of the class that will be doubled.
:param str path: The full path to the class that will be doubled.
:return: The class that will be doubled.
:... |
352,107 | def refresh_authorization(self):
response = self.request_handler.post(
endpoint=,
omit_api_version=True,
data={
: ,
: self.auth.client_id,
: self.auth.client_secret,
: self.auth.refresh_token,
... | Refreshes the authorization tokens.
:return: Dictionary containing auth tokens, expiration info, and response status.
:rtype: ``dict`` |
352,108 | def find_roots( disconnected, index, shared ):
log.warn( , len(disconnected), len(index))
natural_roots = [x for x in disconnected if x.get() and not x.get()]
log.warn( ,len(natural_roots))
for natural_root in natural_roots:
recurse_module(
natural_root, index, shared
)... | Find appropriate "root" objects from which to recurse the hierarchies
Will generate a synthetic root for anything which doesn't have any parents... |
352,109 | def get_messages(self, resource_group, name):
instance_view = self._get_instance_view(resource_group, name)
return [event.message for event in instance_view.events] | Get the messages of a container group
:param resource_group: the name of the resource group
:type resource_group: str
:param name: the name of the container group
:type name: str
:return: A list of the event messages
:rtype: list[str] |
352,110 | def try_ntime(max_try, func, *args, **kwargs):
if max_try < 1:
raise ValueError
for i in range(max_try):
try:
return func(*args, **kwargs)
except Exception as e:
last_exception = e
raise last_exception | Try execute a function n times, until no exception raised or tried
``max_try`` times.
**中文文档**
反复尝试执行一个函数若干次。直到成功为止或是重复尝试 ``max_try`` 次。期间
只要有一次成功, 就正常返回。如果一次都没有成功, 则行为跟最后一次执行了
``func(*args, **kwargs)`` 一样。 |
352,111 | def dump_stream(self, iterator, stream):
def init_stream_yield_batches():
should_write_start_length = True
for series in iterator:
batch = self._create_batch(series)
if should_write_start_length:
write_int(SpecialLengths.START... | Override because Pandas UDFs require a START_ARROW_STREAM before the Arrow stream is sent.
This should be sent after creating the first record batch so in case of an error, it can
be sent back to the JVM before the Arrow stream starts. |
352,112 | def jaccard(self, other):
if other.seed != self.seed:
raise ValueError("Cannot compute Jaccard given MinHash with\
different seeds")
if len(self) != len(other):
raise ValueError("Cannot compute Jaccard given MinHash with\
different... | Estimate the `Jaccard similarity`_ (resemblance) between the sets
represented by this MinHash and the other.
Args:
other (datasketch.MinHash): The other MinHash.
Returns:
float: The Jaccard similarity, which is between 0.0 and 1.0. |
352,113 | def distant_total_damped_rated_level(
octave_frequencies,
distance,
temp,
relhum,
reference_distance=1.0):
damping_distance = distance - reference_distance
sums = 0.0
for band in OCTAVE_BANDS.keys():
if band not in octave_frequencies:
... | Calculates the damped, A-rated total sound pressure level
in a given distance, temperature and relative humidity
from octave frequency sound pressure levels in a reference distance |
352,114 | def terminal_states(data, vkey=, groupby=None, groups=None, self_transitions=False, basis=None,
weight_diffusion=0, scale_diffusion=1, eps=1e-3, copy=False):
adata = data.copy() if copy else data
logg.info(, r=True)
strings_to_categoricals(adata)
groupby = if groupby is None ... | Computes terminal states (root and end points).
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
vkey: `str` (default: `'velocity'`)
Name of velocity estimates to be used.
self_transitions: `bool` (default: `False`)
Allow transitions from one node t... |
352,115 | def get_system_uptime_output_show_system_uptime_minutes(self, **kwargs):
config = ET.Element("config")
get_system_uptime = ET.Element("get_system_uptime")
config = get_system_uptime
output = ET.SubElement(get_system_uptime, "output")
show_system_uptime = ET.SubElement(ou... | Auto Generated Code |
352,116 | def do_work_on(self, repo):
self.abort_on_nonexisting_repo(repo, )
self.network.active_repo = repo | Make repo the active one.
Commands working on a repo will use it as default for repo parameter. |
352,117 | def move_tab(self, index_from, index_to):
filename = self.filenames.pop(index_from)
editor = self.editors.pop(index_from)
self.filenames.insert(index_to, filename)
self.editors.insert(index_to, editor) | Move tab.
(tabs themselves have already been moved by the history.tabwidget) |
352,118 | def verify_checksum(self, data, checksum, filename):
calculated_checksum = hashlib.sha256(data).hexdigest()
logger.debug("calculated checksum {0} for {1}".format(calculated_checksum,
filename))
if calculated_checksum != check... | Verify sha256 checksum vs calculated checksum
:type data: str
:param data: data used to calculate checksum
:type checksum: str
:param checksum: expected checksum of data
:type filename: str
:param checksum: original filename |
352,119 | def from_spec(spec, kwargs=None):
memory = util.get_object(
obj=spec,
predefined_objects=tensorforce.core.memories.memories,
kwargs=kwargs
)
assert isinstance(memory, Memory)
return memory | Creates a memory from a specification dict. |
352,120 | def uniqualize(l,**kwargs):
if( in kwargs):
mode = kwargs[]
else:
mode =
pt = copy.deepcopy(l)
seqs =[]
freq = {}
for i in range(0,pt.__len__()):
v = pt[i]
if(v in freq):
freq[v] = freq[v] + 1
else:
freq[v] = 0
seq... | from elist.elist import *
l = [1, 2, 2]
new = uniqualize(l)
new
id(l)
id(new)
####
l = [1, 2, 2]
rslt = uniqualize(l,mode="original")
rslt
id(l)
id(rslt) |
352,121 | def get_argument(
self,
name: str,
default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT,
strip: bool = True,
) -> Optional[str]:
return self._get_argument(name, default, self.request.arguments, strip) | Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be
required, and we raise a `MissingArgumentError` if it is missing.
If the argument appears in the request more than once, we return the
last value.
This method se... |
352,122 | def format_help(self):
if self._subparsers:
for action in self._subparsers._actions:
if isinstance(action, LazySubParsersAction):
for parser_name, parser in action._name_parser_map.iteritems():
action._setup_subparser(parser_name, ... | Sets up all sub-parsers when help is requested. |
352,123 | def _append_svg(self, svg, before_prompt=False):
self._append_custom(self._insert_svg, svg, before_prompt) | Append raw SVG data to the widget. |
352,124 | def get_or_create(cls, *props, **kwargs):
lazy = kwargs.get(, False)
relationship = kwargs.get()
get_or_create_params = [{"create": cls.deflate(p, skip_empty=True)} for p in props]
query, params = cls._build_merge_query(get_or_create_params, relationship=relationship, ... | Call to MERGE with parameters map. A new instance will be created and saved if does not already exists,
this is an atomic operation.
Parameters must contain all required properties, any non required properties with defaults will be generated.
Note that the post_create hook isn't called after ge... |
352,125 | def collect(self, file=sys.stderr):
cur = gcstats()
Ncur = len(cur)
if self.stats is not None and file is not None:
prev = self.stats
Nprev = self.ntypes
if Ncur != Nprev:
print("
Scur, Sprev, first = set(cur), set(prev... | Collect stats and print results to file
:param file: A writable file-like object |
352,126 | def tonal_distance(pianoroll_1, pianoroll_2, beat_resolution, r1=1.0, r2=1.0,
r3=0.5):
_validate_pianoroll(pianoroll_1)
_validate_pianoroll(pianoroll_2)
assert len(pianoroll_1) == len(pianoroll_2), (
"Input pianorolls must have the same length.")
def _tonal_matrix(r1, r2... | Return the tonal distance [1] between the two input pianorolls.
[1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting
harmonic change in musical audio. In Proc. ACM Workshop on Audio and
Music Computing Multimedia, 2006. |
352,127 | def _is_compatible_with(self, other):
title = self._compare_title(other)
suffix = self._compare_suffix(other)
return title and suffix | Return True if names are not incompatible.
This checks that the gender of titles and compatibility of suffixes |
352,128 | def get_args():
parser = argparse.ArgumentParser(
description=)
parser.add_argument(,
,
type=int,
help=,
required=True
)
parser.add_argument(,
,
... | Parse command line arguments. |
352,129 | def _get_metadata_path_for_display(self, name):
try:
return path | Return the path to the given metadata file, if available. |
352,130 | def groupify(function):
@wraps(function)
def wrapper(paths, *args, **kwargs):
groups = {}
for path in paths:
key = function(path, *args, **kwargs)
if key is not None:
groups.setdefault(key, set()).add(path)
return groups
return wrappe... | Decorator to convert a function which takes a single value and returns
a key into one which takes a list of values and returns a dict of key-group
mappings.
:param function: A function which takes a value and returns a hash key.
:type function: ``function(value) -> key``
:rtype:
.. parsed-... |
352,131 | def _render(self):
if hasattr(self, ):
if hasattr(self, ):
self.render_trigger.emit()
elif not self._first_time:
self.render() | redraws render window if the render window exists |
352,132 | def process_views(self):
output = {}
logger.debug("Processing %d view(s)...", len(self.views))
for view_name, view in iteritems(self.views):
try:
output = deep_merge_dict(
output,
view.process(
s... | Processes the loaded views to generate the required output data. |
352,133 | def stringify(self):
hexcode = "
for x in self.value:
part = hex(x)[2:]
if len(part) < 2: part = "0" + part
hexcode += part
return hexcode | Returns the color value in hexcode format.
eg. ``'#ff1056'`` |
352,134 | def get_goid2color_pval(self):
go2color = {}
self.set_goid2color_pval(go2color)
color_dflt = self.alpha2col[1.000]
for goid in self.go2res:
if goid not in go2color:
go2color[goid] = color_dflt
return go2color | Return a go2color dict containing GO colors determined by P-value. |
352,135 | def timeline_home(self, max_id=None, min_id=None, since_id=None, limit=None):
return self.timeline(, max_id=max_id, min_id=min_id,
since_id=since_id, limit=limit) | Fetch the logged-in users home timeline (i.e. followed users and self).
Returns a list of `toot dicts`_. |
352,136 | def frombed(args):
from jcvi.formats.fasta import Fasta
from jcvi.formats.bed import Bed
from jcvi.utils.cbook import fill
p = OptionParser(frombed.__doc__)
opts, args = p.parse_args(args)
if len(args) != 3:
sys.exit(not p.print_help())
bedfile, contigfasta, readfasta = args
... | %prog frombed bedfile contigfasta readfasta
Convert read placement to contig format. This is useful before running BAMBUS. |
352,137 | async def _async_forward(async_chunks: collections.AsyncIterable,
out: Optional[Union[TeeCapture, IO[str]]]
) -> Optional[str]:
capture = isinstance(out, TeeCapture)
out_pipe = out.out_pipe if isinstance(out, TeeCapture) else out
chunks = [] if capture... | Prints/captures output from the given asynchronous iterable.
Args:
async_chunks: An asynchronous source of bytes or str.
out: Where to put the chunks.
Returns:
The complete captured output, or else None if the out argument wasn't a
TeeCapture instance. |
352,138 | def period(self, unit, size = 1):
assert unit in (DAY, MONTH, YEAR), .format(unit, type(unit))
assert isinstance(size, int) and size >= 1, .format(size, type(size))
return Period((unit, self, size)) | Create a new period starting at instant.
>>> instant(2014).period('month')
Period(('month', Instant((2014, 1, 1)), 1))
>>> instant('2014-2').period('year', 2)
Period(('year', Instant((2014, 2, 1)), 2))
>>> instant('2014-2-3').period('day', size = 2)
Period(('day', Instan... |
352,139 | def middle_bollinger_band(data, period, std=2.0):
catch_errors.check_for_period_error(data, period)
period = int(period)
mid_bb = sma(data, period)
return mid_bb | Middle Bollinger Band.
Formula:
m_bb = sma() |
352,140 | def closure_for_targets(cls, target_roots, exclude_scopes=None, include_scopes=None,
bfs=None, postorder=None, respect_intransitive=False):
target_roots = list(target_roots)
if not target_roots:
return OrderedSet()
build_graph = target_roots[0]._build_graph
address... | Computes the closure of the given targets respecting the given input scopes.
:API: public
:param list target_roots: The list of Targets to start from. These targets will always be
included in the closure, regardless of scope settings.
:param Scope exclude_scopes: If present and non-empty, only depen... |
352,141 | def download(self, uuid, url, forced_file_name=None,
progress_bar=True, chunk_size=256,
directory=None, overwrite=False):
self.last_req_time = None
url = self.get_full_url(url)
self.log.debug("download url : " + url)
request = urllib2.R... | download a file from LinShare using its rest api.
This method could throw exceptions like urllib2.HTTPError. |
352,142 | def _findlinestarts(code_object):
byte_increments = [c for c in code_object.co_lnotab[0::2]]
line_increments = [c for c in code_object.co_lnotab[1::2]]
lineno = code_object.co_firstlineno
addr = 0
for byte_incr, line_incr in zip(byte_increments, line_i... | Find the offsets in a byte code which are the start of source lines.
Generate pairs (offset, lineno) as described in Python/compile.c.
This is a modified version of dis.findlinestarts. This version allows
multiple "line starts" with the same line number. (The dis version
conditions its... |
352,143 | def __validate_args(task_id, backend, category, backend_args):
if not task_id or task_id.strip() == "":
msg = "Missing task_id for task"
raise ValueError(msg)
if not backend or backend.strip() == "":
msg = "Missing backend for task " % task_id
r... | Check that the task arguments received are valid |
352,144 | def probably_wkt(text):
valid = False
valid_types = set([
, , , ,
, , ,
])
matched = re.match(r, text.strip())
if matched:
valid = matched.group(1).upper() in valid_types
return valid | Quick check to determine if the provided text looks like WKT |
352,145 | def _compute_heating_rates(self):
self._compute_flux()
self.heating_rate[] = -self._flux
self.heating_rate[][..., -1, np.newaxis] = self._flux | Compute energy flux convergences to get heating rates in :math:`W/m^2`. |
352,146 | async def delete(self):
await self._handler.delete(
fabric_id=self.fabric.id, vid=self._orig_data[]) | Delete this VLAN. |
352,147 | def handle_error_event(self, act, detail, exc=SocketError):
del self.tokens[act]
self.scheduler.active.append((
CoroutineException(exc, exc(detail)),
act.coro
)) | Handle an errored event. Calls the scheduler to schedule the associated
coroutine. |
352,148 | def _loader(self, tags):
class ConfigLoader(SafeLoader):
pass
ConfigLoader.add_multi_constructor("", lambda loader, prefix, node: TaggedValue(node.value, node.tag, *tags))
return ConfigLoader | Create a yaml Loader. |
352,149 | def ratio(self):
return 2.0 * self.matches() / (len(self.seq1) + len(self.seq2)) | Ratio of matches to the average sequence length. |
352,150 | def optimize(self, x0, target):
x = x0
for _ in range(self.maxiter):
delta = np.linalg.solve(self.h(x, target), -self.g(x, target))
x = x + delta
if np.linalg.norm(delta) < self.tol:
break
return x | Calculate an optimum argument of an objective function. |
352,151 | def euclidean_distances(a, b, squared=False, to_numpy=True):
a, b = to_gpu(a, b)
a2 = np.sum(np.square(a), 1)
b2 = np.sum(np.square(b), 1)
c = -2 * np.dot(a, b.T)
c += a2[:, None]
c += b2[None, :]
if not squared:
np.sqrt(c, out=c)
if to_numpy:
return to_np(c)
... | Compute the pairwise euclidean distance between matrices a and b.
If the input matrix are in numpy format, they will be uploaded to the
GPU first which can incur significant time overhead.
Parameters
----------
a : np.ndarray (n, f)
first matrix
b : np.ndarray (m, f)
second mat... |
352,152 | def geometryType(self):
if self._geomType is None:
if self.geometry is not None:
self._geomType = self.geometry.type
else:
self._geomType = "Table"
return self._geomType | returns the feature's geometry type |
352,153 | def _ReadStructureFamilyDataTypeDefinition(
self, definitions_registry, definition_values, definition_name,
is_member=False):
if is_member:
error_message =
raise errors.DefinitionReaderError(definition_name, error_message)
definition_object = self._ReadLayoutDataTypeDefinition(
... | Reads a structure family data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
definition_name (str): name of the definition.
is_member (Optional[bool]): True if the... |
352,154 | def set_name(self, name, overwrite=False, increment=True):
exists = os.path.exists(os.path.join(self._path, self.increment_name(name, 0)))
warning = "Filename and path already exists, refusing to set filename without overwrite=True or increment=True"
assert not (exis... | Sets the name of the file to be saved.
@params
name - the name to the file
increment - whether or not to increment the filename if there is an existing file ie test.txt => test1.txt
overwrite - whether or not to overwrite existing local file, renders increment redundant |
352,155 | def login(self, username=None, password=None):
if (username is None) and (password is None):
auth_token = self.__login_guest()
elif (username is not None) and (password is not None):
auth_token, fullName = self.__login_credentials(username, password)
self.log... | Before doing any remote operation, the user has to login to the GMQL serivice.
This can be done in the two following ways:
* Guest mode: the user has no credentials and uses the system only as a temporary guest
* Authenticated mode: the users has credentials and a stable remote account
... |
352,156 | def _uploadStream(self, jobStoreFileID, container, checkForModification=False, encrypted=None):
if checkForModification:
try:
expectedVersion = container.get_blob_properties(blob_name=str(jobStoreFileID)).properties.etag
except AzureMissingResourceHttpError:
... | :param encrypted: True to enforce encryption (will raise exception unless key is set),
False to prevent encryption or None to encrypt if key is set. |
352,157 | def extant_file(file):
if not os.path.exists(file):
raise argparse.ArgumentTypeError("{0} does not exist".format(file))
return file | 'Type' for argparse - checks that file exists but does not open. |
352,158 | def Gr(L: float, Ts: float, Tf: float, beta: float, nu: float, g: float):
return g * beta * (Ts - Tf) * L**3.0 / nu**2.0 | Calculate the Grashof number.
:param L: [m] heat transfer surface characteristic length.
:param Ts: [K] heat transfer surface temperature.
:param Tf: [K] bulk fluid temperature.
:param beta: [1/K] fluid coefficient of thermal expansion.
:param nu: [m2/s] fluid kinematic viscosity.
:returns: fl... |
352,159 | def _generate_edges(self, edge_prob):
self.E, self.parent = [], {}
for i in range(self.m):
if random() < edge_prob and i > 0:
p_i = choice(i)
self.E.append((p_i, i))
self.parent[i] = p_i | Generate a random tree-structured dependency graph based on a
specified edge probability.
Also create helper data struct mapping child -> parent. |
352,160 | def Vmg_STP(self):
rnitrogen
return self.VolumeGasMixture(T=298.15, P=101325, zs=self.zs, ws=self.ws) | r'''Gas-phase molar volume of the mixture at 298.15 K and 101.325 kPa,
and the current composition in units of [m^3/mol].
Examples
--------
>>> Mixture(['nitrogen'], ws=[1]).Vmg_STP
0.02445443688838904 |
352,161 | def set_col_name(self, index, name):
javabridge.call(self.jobject, "setColName", "(ILjava/lang/String;)V", index, name) | Sets the column name.
:param index: the 0-based row index
:type index: int
:param name: the name of the column
:type name: str |
352,162 | def extend(self, other):
def extend_trans(pipe):
values = list(other.__iter__(pipe)) if use_redis else other
for v in values:
self._append_helper(v, pipe)
if self._same_redis(other, RedisCollection):
use_redis = True
self._transac... | Extend the right side of the the collection by appending values from
the iterable *other*. |
352,163 | def basic_addresses_write(self, cycles, last_op_address, address, word):
log.critical("%04x| write $%04x to $%04x", last_op_address, word, address)
return word | 0113 0019 TXTTAB RMB 2 *PV BEGINNING OF BASIC PROGRAM
0114 001B VARTAB RMB 2 *PV START OF VARIABLES
0115 001D ARYTAB RMB 2 *PV START OF ARRAYS
0116 001F ARYEND RMB 2 *PV END OF ARRAYS (+1)
0117 0021 FRETOP RMB 2 *PV START OF STRING STORAGE (TOP OF FREE RAM)
0118 0023 STRTAB RMB 2... |
352,164 | def remove_user(name, profile=):
client = _get_client(profile)
organization = client.get_organization(
_get_config_value(profile, )
)
try:
git_user = client.get_user(name)
except UnknownObjectException:
log.exception("Resource not found")
return False
if o... | Remove a Github user by name.
name
The user for which to obtain information.
profile
The name of the profile configuration to use. Defaults to ``github``.
CLI Example:
.. code-block:: bash
salt myminion github.remove_user github-handle |
352,165 | def filter_aliases(alias_table):
for alias in alias_table.sections():
if alias_table.has_option(alias, ):
yield (alias.split()[0], remove_pos_arg_placeholders(alias_table.get(alias, ))) | Filter aliases that does not have a command field in the configuration file.
Args:
alias_table: The alias table.
Yield:
A tuple with [0] being the first word of the alias and
[1] being the command that the alias points to. |
352,166 | def local_temp_dir():
path = tempfile.mkdtemp()
yield path
shutil.rmtree(path, ignore_errors=True) | Creates a local temporary directory. The directory is removed when no longer needed. Failure to do
so will be ignored.
:return: Path to the temporary directory.
:rtype: unicode |
352,167 | def mcmc(self, n_burn, n_run, walkerRatio, sigma_scale=1, threadCount=1, init_samples=None, re_use_samples=True):
param_class = self._param_class
mcmc_class = Sampler(likelihoodModule=self.likelihoodModule)
mean_start = param_class.kwargs2args(self._lens_temp, self._source_tem... | MCMC routine
:param n_burn: number of burn in iterations (will not be saved)
:param n_run: number of MCMC iterations that are saved
:param walkerRatio: ratio of walkers/number of free parameters
:param sigma_scale: scaling of the initial parameter spread relative to the width in the ini... |
352,168 | def _android_get_installed_platform_tools_version(self):
platform_tools_dir = os.path.join(
self.android_sdk_dir,
)
if not os.path.exists(platform_tools_dir):
return None
data_file = os.path.join(platform_tools_dir, )
if not os.path.exists(... | Crudely parse out the installed platform-tools version |
352,169 | def alt_fn(self, i, pre_dl=None, post_dl=None):
self.delay(pre_dl)
self.k.press_key(self.k.alt_key)
self.k.tap_key(self.k.function_keys[i])
self.k.release_key(self.k.alt_key)
self.delay(post_dl) | Press Alt + Fn1 ~ 12 once.
**中文文档**
按下 Alt + Fn1 ~ 12 组合键。 |
352,170 | def setIcon(self, icon):
if icon:
self._icon = QIcon(icon)
else:
self._icon = None | Sets the icon for this item to the inputed icon.
:param icon | <str> || <QIcon> || None |
352,171 | def chart_plot(self, ax=None, cmap=,
xlabel=, ylabel=, grid_on=True, colorbar=True):
from matplotlib.mlab import griddata
from numpy import linspace, meshgrid
import matplotlib.pyplot as plt
x = self.dropna().N
y = self.dropna().Z
z = sel... | Plot a nuclear chart with (N,Z) as axis and the values
of the Table as a color scale
Parameters
----------
ax: optional matplotlib axes
defaults to current axes
cmap: a matplotlib colormap
default: 'RdBu'
xlabel: string representing the la... |
352,172 | def ancestors(self):
ret = []
workunit = self
while workunit is not None:
ret.append(workunit)
workunit = workunit.parent
return ret | Returns a list consisting of this workunit and those enclosing it, up to the root.
:API: public |
352,173 | def isfile(self, str_path):
b_isFile = False
if self.isdir(str_path):
b_isFile = False
else:
str_parentDir = .join(str_path.split()[0:-1])
str_fileName = str_path.split()[-1]
if self.... | A convenience function, returns bool if <str_path> is
a "file" in the tree space |
352,174 | def output_interval_histogram(self,
histogram,
start_time_stamp_sec=0,
end_time_stamp_sec=0,
max_value_unit_ratio=1000000.0):
s max
value when reporting on it.
... | Output an interval histogram, with the given timestamp and a
configurable maxValueUnitRatio.
(note that the specified timestamp will be used, and the timestamp in
the actual histogram will be ignored).
The max value reported with the interval line will be scaled by the
given max_... |
352,175 | def hostname_text(self):
if self._hostname_text is None:
self.chain.connection.log("Collecting hostname information")
self._hostname_text = self.driver.get_hostname_text()
if self._hostname_text:
self.chain.connection.log("Hostname info collected")
... | Return hostname text and collect if not collected. |
352,176 | def uri(self):
"Fedora URI for this object (``info:fedora/foo:
use_pid = self.pid
if callable(use_pid):
use_pid = self.DUMMY_PID
return + use_pid | Fedora URI for this object (``info:fedora/foo:###`` form of object pid) |
352,177 | def extract_code(lines, node, lstrip="", ljoin="\n", strip=""):
first_line, first_col = node.first_line - 1, node.first_col
last_line, last_col = node.last_line - 1, node.last_col
if first_line == last_line:
return lines[first_line][first_col:last_col].strip(strip)
result = []
res... | Get corresponding text in the code
Arguments:
lines -- code splitted by linebreak
node -- PyPosAST enhanced node
Keyword Arguments:
lstrip -- During extraction, strip lines with this arg (default="")
ljoin -- During extraction, join lines with this arg (default="\n")
strip -- After extra... |
352,178 | def SetExtractionConfiguration(self, configuration):
self._hasher_file_size_limit = configuration.hasher_file_size_limit
self._SetHashers(configuration.hasher_names_string)
self._process_archives = configuration.process_archives
self._process_compressed_streams = configuration.process_compressed_st... | Sets the extraction configuration settings.
Args:
configuration (ExtractionConfiguration): extraction configuration. |
352,179 | def get_module_names(path_dir, exclude=None):
if exclude is None: exclude = _default_exclude
"Search a given `path_dir` and return all the modules contained inside except those in `exclude`"
files = sorted(path_dir.glob(), key=lambda x: (x.is_dir(), x.name), reverse=True)
res = [f]
for f in files:
... | Search a given `path_dir` and return all the modules contained inside except those in `exclude` |
352,180 | def calc_bowa_v1(self):
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
sta = self.sequences.states.fastaccess
aid = self.sequences.aides.fastaccess
for k in range(con.nhru):
if con.lnk[k] in (VERS, WASSER, FLUSS, SEE):
sta.bowa[k] = 0.
... | Update soil moisture and correct fluxes if necessary.
Required control parameters:
|NHRU|
|Lnk|
Required flux sequence:
|WaDa|
Updated state sequence:
|BoWa|
Required (and eventually corrected) flux sequences:
|EvB|
|QBB|
|QIB1|
|QIB2|
|QDB|
... |
352,181 | def process_subprotocol(
self, headers: Headers, available_subprotocols: Optional[Sequence[Subprotocol]]
) -> Optional[Subprotocol]:
subprotocol: Optional[Subprotocol] = None
header_values = headers.get_all("Sec-WebSocket-Protocol")
if header_values and available_subprotoc... | Handle the Sec-WebSocket-Protocol HTTP request header.
Return Sec-WebSocket-Protocol HTTP response header, which is the same
as the selected subprotocol. |
352,182 | def downstream_index_dinf(dinfdir_value, i, j):
down_dirs = DinfUtil.dinf_downslope_direction(dinfdir_value)
down_coors = []
for dir_code in down_dirs:
row, col = D8Util.downstream_index(dir_code, i, j)
down_coors.append([row, col])
return down_coors | find downslope coordinate for Dinf of TauDEM
Args:
dinfdir_value: dinf direction value
i: current row
j: current col
Returns:
downstream (row, col)s |
352,183 | def get_default_database(self, default=None, codec_options=None,
read_preference=None, write_concern=None, read_concern=None):
if self.__default_database_name is None and default is None:
raise ConfigurationError(
)
return database.Database(
... | Get the database named in the MongoDB connection URI.
>>> uri = 'mongodb://host/my_database'
>>> client = MongoClient(uri)
>>> db = client.get_default_database()
>>> assert db.name == 'my_database'
>>> db = client.get_database()
>>> assert db.name == 'my_database'
... |
352,184 | def implementation_std(vals_std, vals_std_u, bs_std, bs_std_u, **kwargs):
r
nsim = kwargs.pop(, 1000000)
random_seed = kwargs.pop(, 0)
if kwargs:
raise TypeError(.format(kwargs))
imp_var = (vals_std ** 2) - (bs_std ** 2)
imp_std = np.sqrt(np.abs(imp_var)) * np.sign(imp_var... | r"""Estimates varaition of results due to implementation-specific
effects. See 'nestcheck: diagnostic tests for nested sampling calculations'
(Higson et al. 2019) for more details.
Uncertainties on the output are calculated numerically using the fact
that (from central limit theorem) our uncertainties ... |
352,185 | def populate(self, fields=None, **fields_kwargs):
pop_fields = {}
fields = self.make_dict(fields, fields_kwargs)
for k in self.schema.fields.keys():
pop_fields[k] = fields.get(k, None)
self._populate(pop_fields) | take the passed in fields, combine them with missing fields that should
be there and then run all those through appropriate methods to hydrate this
orm.
The method replaces cls.hydrate() since it was becoming hard to understand
what was going on with all these methods that did things ju... |
352,186 | def print_result(
result: Result,
host: Optional[str] = None,
vars: List[str] = None,
failed: bool = False,
severity_level: int = logging.INFO,
) -> None:
LOCK.acquire()
try:
_print_result(result, host, vars, failed, severity_level)
finally:
LOCK.release() | Prints the :obj:`nornir.core.task.Result` from a previous task to screen
Arguments:
result: from a previous task
host: # TODO
vars: Which attributes you want to print
failed: if ``True`` assume the task failed
severity_level: Print only errors with this severity level or hig... |
352,187 | def binaryTree_depthFirstNumbers(binaryTree, labelTree=True, dontStopAtID=True):
traversalIDs = {}
def traverse(binaryTree, mid=0, leafNo=0):
if binaryTree.internal and (dontStopAtID or binaryTree.iD is None):
midStart = mid
j, leafNo = traverse(binaryTree.left, mid, leafNo)... | get mid-order depth first tree numbers |
352,188 | def execute(self):
if not self.commands or self._parser is None:
raise NotImplementedError(
"No commands registered with this program!"
)
args = self.parser.parse_args()
try:
handle_default_args(arg... | Entry point to the execution of the program. |
352,189 | def abort(self, exception=exc.ConnectError):
log.warning("Aborting connection to %s:%s", self.host, self.port)
def abort_pending(f):
exc_info = sys.exc_info()
log.debug(.format(f))
if False and any(exc_info):
f.set_exc_info(exc_i... | Aborts a connection and puts all pending futures into an error state.
If ``sys.exc_info()`` is set (i.e. this is being called in an exception
handler) then pending futures will have that exc info set. Otherwise
the given ``exception`` parameter is used (defaults to
``ConnectError``). |
352,190 | def runSearchIndividuals(self, request):
return self.runSearchRequest(
request, protocol.SearchIndividualsRequest,
protocol.SearchIndividualsResponse,
self.individualsGenerator) | Runs the specified search SearchIndividualsRequest. |
352,191 | def clear( self ):
self.uiQueryTXT.setText()
self.uiQueryTREE.clear()
self.uiGroupingTXT.setText()
self.uiSortingTXT.setText() | Clears the information for this edit. |
352,192 | def create(self, client=None):
client = self._require_client(client)
data = {"projectId": self.project_id, "name": self.name, "labels": self.labels}
resp = client._connection.api_request(
method="POST", path="/projects", data=data
)
self.set_properties_from_... | API call: create the project via a ``POST`` request.
See
https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/create
:type client: :class:`google.cloud.resource_manager.client.Client` or
:data:`NoneType <types.NoneType>`
:param client: the cl... |
352,193 | def get_python():
if sys.platform == :
python = path.join(VE_ROOT, , )
else:
python = path.join(VE_ROOT, , )
return python | Determine the path to the virtualenv python |
352,194 | def get_plane_equation(p0, p1, p2, reference):
p0_xyz = get_xyz_from_ll(p0, reference)
p1_xyz = get_xyz_from_ll(p1, reference)
p2_xyz = get_xyz_from_ll(p2, reference)
p0 = np.array(p0_xyz)
p1 = np.array(p1_xyz)
p2 = np.array(p2_xyz)
u = p1 - p0
v = p2 - p0
normal = np.c... | Define the equation of target fault plane passing through 3 given points
which includes two points on the fault trace and one point on the
fault plane but away from the fault trace. Note: in order to remain the
consistency of the fault normal vector direction definition, the order
of the three given poi... |
352,195 | def _read_select_poll(poll):
npipes = len(NonBlockingStreamReader._streams)
for stream_descr in NonBlockingStreamReader._streams:
if not stream_descr.has_error:
poll.register(stream_descr.stream,
select.POLLIN | select.POLLERR | select.P... | Read PIPEs using select.poll() method
Available on Linux and some Unixes |
352,196 | def five_resect(dna, n_bases):
end of top strand.
:param dna: Sequence to resect.
:type dna: coral.DNA
:param n_bases: Number of bases cut back.
:type n_bases: int
:returns: DNA sequence resected at the 5
new_instance = dna.copy()
if n_bases >= len(dna):
new_instance.top.seq = ... | Remove bases from 5' end of top strand.
:param dna: Sequence to resect.
:type dna: coral.DNA
:param n_bases: Number of bases cut back.
:type n_bases: int
:returns: DNA sequence resected at the 5' end by n_bases.
:rtype: coral.DNA |
352,197 | def version_tuple(version):
if isinstance(version, str):
return tuple(int(x) for x in version.split())
elif isinstance(version, tuple):
return version
else:
raise ValueError("Invalid version: %s" % version) | Convert a version string or tuple to a tuple.
Should be returned in the form: (major, minor, release). |
352,198 | def xarray_derivative_wrap(func):
@functools.wraps(func)
def wrapper(f, **kwargs):
if in kwargs or in kwargs:
return preprocess_xarray(func)(f, **kwargs)
elif isinstance(f, xr.DataArray):
axis = f.metpy.find_axis_name(kwargs.get(, 0))
... | Decorate the derivative functions to make them work nicely with DataArrays.
This will automatically determine if the coordinates can be pulled directly from the
DataArray, or if a call to lat_lon_grid_deltas is needed. |
352,199 | def parse(cls, config_data: dict, sampleinfo_data: dict, sacct_jobs: List[dict],
jobs: int) -> dict:
analysis_types = [sample[] for sample in config_data[]]
run_data = {
: config_data[],
: config_data[],
: config_data[],
: sampleinfo... | Parse information about a run. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.