Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
340,500 | def _load(self, element, commentchar):
for child in element:
if "id" in child.attrib:
tline = TemplateLine(child, self, commentchar)
self.order.append(tline.identifier)
self.lines[tline.identifier] = tline
else:
... | Loads all the child line elements from the XML group element. |
340,501 | def get_erc20_contract(w3: Web3, address=None):
return w3.eth.contract(address,
abi=ERC20_INTERFACE[],
bytecode=ERC20_INTERFACE[]) | Get ERC20 interface
:param w3: Web3 instance
:param address: address of the proxy contract
:return: ERC 20 contract |
340,502 | def _get_fitnesses(self,
problem,
population,
cache_encoded=True,
cache_solution=False,
pool=None):
fitnesses = [None] * len(population)
if cache_encode... | Get the fitness for every solution in a population.
Args:
problem: Problem; The problem that defines fitness.
population: list; List of potential solutions.
pool: None/multiprocessing.Pool; Pool of processes for parallel
decoding and evaluation. |
340,503 | def logoff_session(session_id):
**
try:
win32ts.WTSLogoffSession(win32ts.WTS_CURRENT_SERVER_HANDLE, session_id, True)
except PyWinError as error:
_LOG.error(, error)
return False
return True | Initiate the logoff of a session.
.. versionadded:: 2016.11.0
:param session_id: The numeric Id of the session.
:return: A boolean representing whether the logoff succeeded.
CLI Example:
.. code-block:: bash
salt '*' rdp.logoff_session session_id
salt '*' rdp.logoff_session 99 |
340,504 | def fetch(self, endpoint=None, page=1, key=None, filter=, **kwargs):
if not endpoint:
raise ValueError()
self._endpoint = endpoint
params = {
"pagesize": self.page_size,
"page": page,
"filter": filter
}
if self.key:
... | Returns the results of an API call.
This is the main work horse of the class. It builds the API query
string and sends the request to Stack Exchange. If there are multiple
pages of results, and we've configured `max_pages` to be greater than
1, it will automatically paginate through the... |
340,505 | def load_name(*names, load_order=DEFAULT_LOAD_ORDER, extension=, missing=Missing.silent):
def generate_sources():
for source, name in product(load_order, names):
if callable(source):
yield source(name, extension)
else:
... | Read a `.Configuration` instance by name, trying to read from files in
increasing significance. The default load order is `.system`, `.user`,
`.application`, `.environment`.
Multiple names are combined with multiple loaders using names as the 'inner
loop / selector', loading ``/etc/name1.yaml`` and ``/... |
340,506 | def console_get_default_foreground(con: tcod.console.Console) -> Color:
return Color._new_from_cdata(
lib.TCOD_console_get_default_foreground(_console(con))
) | Return this consoles default foreground color.
.. deprecated:: 8.5
Use :any:`Console.default_fg` instead. |
340,507 | def update(self, value, *args, **kwargs):
log.debug(.format(value=value, args=args, kwargs=kwargs))
self.on_update(value, *args, **kwargs) | Call this function to inform that an update is available.
This function does NOT call finish when value == maximum.
:param value: The current index/position of the action. (Should be, but must not be, in the range [min, max])
:param args: extra positional arguments to pass on
:param kwar... |
340,508 | def execute(self, capture_output=False, fail_fast=False, cmdline=None, lastcsums=None, **kwargs):
currcsums = self.csums()
scripts = self.get_scripts()
output = []
for script in scripts:
if not os.access(script, os.R_OK ^ os.X_OK) or re.match(".*~$", scrip... | Pass in the kwargs as --<name> <value> pairs.
:param capture_output: if True then return output of script in return dict. If False, only return code
:param fail_fast:if True then quit execution after first non-zero return code, else execute all
:returns list of (script, returncode, stdout) tuple... |
340,509 | def encrypt(self, key, data, mode, padding):
if hasattr(key, "private_bytes"):
_key = key.public_key()
else:
_key = key
try:
return _key.encrypt(data, padding.build())
except Exception:
error_message = "Encryption failed"
... | Encrypt data using the supplied values.
:param bytes key: Loaded encryption key
:param bytes data: Data to encrypt
:param JavaMode mode: Encryption mode to use (not used by :class:`JavaAsymmetricEncryptionAlgorithm`)
:param JavaPadding padding: Padding mode to use
:returns: Encr... |
340,510 | def _disable_encryption(self):
self.encrypt = self._disabled_encrypt
self.decrypt = self._disabled_decrypt | Enable encryption methods for ciphers that support them. |
340,511 | def validate(self, pA, pB):
if pA in pB.links or \
pB in pA.links:
raise Exception()
dA = pA.domains()
dB = pB.domains()
for d in dA:
if d in dB:
raise Exception( % d)
for d in dB:
if d in dA:
... | Validate that the two properties may be linked.
@param pA: Endpoint (A) to link.
@type pA: L{Endpoint}
@param pB: Endpoint (B) to link.
@type pB: L{Endpoint}
@return: self
@rtype: L{Link} |
340,512 | def set_stencil_op(self, sfail=, dpfail=, dppass=,
face=):
self.glir.command(, ,
face, sfail, dpfail, dppass) | Set front or back stencil test actions
Parameters
----------
sfail : str
Action to take when the stencil fails. Must be one of
'keep', 'zero', 'replace', 'incr', 'incr_wrap',
'decr', 'decr_wrap', or 'invert'.
dpfail : str
Action to tak... |
340,513 | def get_statement_model(self):
from chatterbot.conversation import Statement
statement = Statement
statement.storage = self
return statement | Return the class for the statement model. |
340,514 | def normalize_with_model(vector, model):
r
vector = numpy.array(vector, dtype=numpy.float)
minp, maxp, minv, maxv = model
if 1 == vector.ndim:
vector = vector[:, None]
for i in range(vector.shape[1]):
vector[:,i][vector[:,i] < minp[i]] = minp[i]
... | r"""
Normalize as with `normalize`, but not based on the data of the passed feature
vector, but rather on a learned model created with `normalize`. Thus formerly
unseen query data can be normalized according to the training data.
Parameters
----------
vector : sequence
A sequence of... |
340,515 | def _cl_int_plot_multi_top_losses(self, samples:int=3, figsize:Tuple[int,int]=(8,8), save_misclassified:bool=False):
"Show images in `top_losses` along with their prediction, actual, loss, and probability of predicted class in a multilabeled dataset."
if samples >20:
print("Max 20 samples")
retu... | Show images in `top_losses` along with their prediction, actual, loss, and probability of predicted class in a multilabeled dataset. |
340,516 | def range_return(request, items):
if ( in request.headers):
range = parse_range_header(request.headers[])
elif in request.headers:
range = parse_range_header(request.headers[])
else:
range = {
: 0,
: MAX_NUMBER_ITEMS - 1,
: MAX_NUMBER_ITEMS
... | Determine what range of objects to return.
Will check fot both `Range` and `X-Range` headers in the request and
set both `Content-Range` and 'X-Content-Range' headers.
:rtype: list |
340,517 | def stitch(images):
if type(images) != ImageCollection:
images = ImageCollection(images)
calc_translations_parallel(images)
_translation_warn(images)
yoffset, xoffset = images.median_translation()
if xoffset != yoffset:
warn( % (yoffset, xoffset))
y, x = imread(image... | Stitch regular spaced images.
Parameters
----------
images : ImageCollection or list of tuple(path, row, column)
Each image-tuple should contain path, row and column. Row 0,
column 0 is top left image.
Example:
>>> images = [('1.png', 0, 0), ('2.png', 0, 1)]
Returns
... |
340,518 | def contains(coll, k):
if isinstance(coll, IAssociative):
return coll.contains(k)
return k in coll | Return true if o contains the key k. |
340,519 | def GetServicePeriodsActiveEachDate(self, date_start, date_end):
date_it = date_start
one_day = datetime.timedelta(days=1)
date_service_period_list = []
while date_it < date_end:
periods_today = []
date_it_string = date_it.strftime("%Y%m%d")
for service in self.GetServicePeriodLis... | Return a list of tuples (date, [period1, period2, ...]).
For each date in the range [date_start, date_end) make list of each
ServicePeriod object which is active.
Args:
date_start: The first date in the list, a date object
date_end: The first date after the list, a date object
Returns:
... |
340,520 | def ClassHopperMutant(initial_object, class_returning_callable, copy=True):
from copy import copy as _copy
def class_mutator(obj):
obj.__class__ = class_returning_callable(obj)
return obj
if copy:
initial_object = _copy(initial_object)
return OnAccessMutant(initial_objec... | ClassHopper: a wrapper that reevaluates the class of the wrapped instance
on every access attempt.
It's like obj.__class__ = callable_returning_a_class(),
but magically happening before every manipulation with the object.
Usage: mutant.ClassHopper(initial_object, callable_returning_a_class) |
340,521 | def delete(self, *labels):
deletes = []
for label in labels:
k1, k2 = self._keys_from_label(label)
deletes.append(k1)
deletes.append(k2)
self.kvl.delete(self.TABLE, *deletes) | Delete `labels` from the store, which involves deleting two
records for each :class:`Label`.
:rtype: None
:raises: :exc:`KeyError` if any of the `labels` could not be found. |
340,522 | def close(self):
if self._initialized:
self.stop()
self.logged_in = False
return self.serial_h.close() | Send a terminate request and then disconnect from the serial device. |
340,523 | def _loads(self, string):
if not self.serialized:
return self._decode(string)
if string is not None:
try:
return self.serializer.loads(string)
except TypeError:
return self.serializer.loads(self._decode(string)... | If :prop:serialized is True, @string will be unserialized
using :prop:serializer |
340,524 | def reinforce_branches_overloading(network, crit_lines):
try:
standard_line_lv = network.equipment_data[].loc[
network.config[][]]
except KeyError:
print()
try:
standard_line_mv = network.equipment_data[].loc[
network.config[][]]
except KeyError... | Reinforce MV or LV grid due to overloading.
Parameters
----------
network : :class:`~.grid.network.Network`
crit_lines : :pandas:`pandas.DataFrame<dataframe>`
Dataframe containing over-loaded lines, their maximum relative
over-loading and the corresponding time step.
Index o... |
340,525 | def validate(self, value, model_instance):
if isinstance(value, six.string_types):
super(JSONField, self).validate(value, model_instance)
try:
json.loads(value)
except Exception as err:
raise ValidationError(str(err)) | Check value is a valid JSON string, raise ValidationError on
error. |
340,526 | def _get_enquire_mset(database, enquire, start_offset, end_offset, checkatleast=DEFAULT_CHECK_AT_LEAST):
try:
return enquire.get_mset(start_offset, end_offset, checkatleast)
except xapian.DatabaseModifiedError:
database.reopen()
return enquire.get_mset(start_... | A safer version of Xapian.enquire.get_mset
Simply wraps the Xapian version and catches any `Xapian.DatabaseModifiedError`,
attempting a `database.reopen` as needed.
Required arguments:
`database` -- The database to be read
`enquire` -- An instance of an Xapian.enquire o... |
340,527 | def match(self, key=None, year=None, event=None, type=, number=None, round=None, simple=False):
if key:
return Match(self._get( % (key, if simple else )))
else:
return Match(self._get(.format(year=year if not event[0].isdigit() else ,
... | Get data on a match.
You may either pass the match's key directly, or pass `year`, `event`, `type`, `match` (the match number), and `round` if applicable (playoffs only). The event year may be specified as part of the event key or specified in the `year` parameter.
:param key: Key of match to get data... |
340,528 | def export(self, passphrase=None, iter=2048, maciter=1):
passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
if self._cacerts is None:
cacerts = _ffi.NULL
else:
cacerts = _lib.sk_X509_new_null()
cacerts = _ffi.gc(cacerts, _lib.sk_X509_free... | Dump a PKCS12 object as a string.
For more information, see the :c:func:`PKCS12_create` man page.
:param passphrase: The passphrase used to encrypt the structure. Unlike
some other passphrase arguments, this *must* be a string, not a
callback.
:type passphrase: :py:data... |
340,529 | def eval_fitness(self, chromosome):
score = 0
number = self.translator.translate_gene(chromosome.genes[0])
for factor in self.factors:
if number % factor == 0:
score += 1
else:
score -= 1
if score == len(self.fa... | Convert a 1-gene chromosome into an integer and calculate its fitness
by checking it against each required factor.
return: fitness value |
340,530 | def batch_results(self, results):
logging.debug("batch_results() invoked")
queue = self.mgr.get_queue(self.qname_out)
for item in results:
queue.put(item, block=True)
logging.debug("batch_results() returning data") | Push a batch of output results to the Spark output RDD of ``TFCluster.inference()``.
Note: this currently expects a one-to-one mapping of input to output data, so the length of the ``results`` array should match the length of
the previously retrieved batch of input data.
Args:
:results: array of out... |
340,531 | def to_json(msg):
result = {}
result[herald.MESSAGE_HEADERS] = {}
if msg.headers is not None:
for key in msg.headers:
result[herald.MESSAGE_HEADERS][key] = msg.headers.get(key) or None
result[herald.MESSAGE_SUBJECT] = msg.subjec... | Returns a JSON string representation of this message |
340,532 | def _compute_radii(self):
radii = self._get_user_components()
if (radii is None):
centers = self.components_[]
n_centers = centers.shape[0]
max_dist = np.max(pairwise_distances(centers))
radii = np.ones(n_centers) * max_dist/s... | Generate RBF radii |
340,533 | def signers(self):
signerlist = libcrypto.CMS_get0_signers(self.ptr)
if signerlist is None:
raise CMSError("Cannot get signers")
return StackOfX509(ptr=signerlist, disposable=False) | Return list of signer's certificates |
340,534 | def in_64(library, session, space, offset, extended=False):
value_64 = ViUInt64()
if extended:
ret = library.viIn64Ex(session, space, offset, byref(value_64))
else:
ret = library.viIn64(session, space, offset, byref(value_64))
return value_64.value, ret | Reads in an 64-bit value from the specified memory space and offset.
Corresponds to viIn64* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Constants.*SPACE*)
:para... |
340,535 | def create_sas_token(key_name, shared_access_key, scope, expiry=timedelta(hours=1)):
shared_access_key = base64.b64encode(shared_access_key)
abs_expiry = int(time.time()) + expiry.seconds
return c_uamqp.create_sas_token(shared_access_key, scope, key_name, abs_expiry) | Create a SAS token.
:param key_name: The username/key name/policy name for the token.
:type key_name: bytes
:param shared_access_key: The shared access key to generate the token from.
:type shared_access_key: bytes
:param scope: The token permissions scope.
:type scope: bytes
:param expiry:... |
340,536 | def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=replace_inf,
remo... | Compute the median absolute error (MdAE) between the simulated and observed data.
.. image:: /pictures/MdAE.png
**Range** 0 ≤ MdAE < inf, closer to zero is better.
**Notes** Random errors (noise) do not cancel. It is the same as the mean absolute error (MAE), only it takes the
median rather than the ... |
340,537 | def get_queryset(self):
self.queryset = super(CustomFieldsMixin, self).get_queryset()
serializer_class = self.get_serializer_class()
if hasattr(serializer_class.Meta, ):
nested_fields = serializer_class.Meta.nested_fields
fields = serializer_class.Meta.fields
... | For reducing the query count the queryset is expanded with `prefetch_related` and `select_related` depending on the
specified fields and nested fields |
340,538 | def _ftp_nlst(self, dir_name):
assert compat.is_native(dir_name)
lines = []
def _add_line(status, line):
lines.append(line)
cmd = "NLST " + dir_name
self._ftp_retrlines_native(cmd, _add_line, self.encoding)
return lines | Variant of `self.ftp.nlst()` that supports encoding-fallback. |
340,539 | def CheckHashes(hash_ids):
return {
k: bool(v)
for k, v in data_store.REL_DB.ReadHashBlobReferences(hash_ids).items()
} | Checks if files with given hashes are present in the file store.
Args:
hash_ids: A list of SHA256HashID objects.
Returns:
A dict where SHA256HashID objects are keys. Corresponding values
may be False (if hash id is not present) or True if it is not present. |
340,540 | def remap_input_source(input, names):
def __init__(self, input, names):
ProxyInputSource.__init__(self, input)
assert isinstance(names, (list, tuple)), names
self._names = tuple(names)
def _setup(self, inputs):
self._all_placehdrs = [build_or_reuse_placeholder(v) for v in i... | When you have some :class:`InputSource` which doesn't match the inputs of
your tower function, use `RemapInputSource`.
It produces placeholders for all the inputs in your model,
except that the corresponding ones are replaced with the tensor produced
by the given :class:`InputSource`.
Args:
... |
340,541 | def create_for_module_vars(cls, scope_vars):
inst = cls()
if not inst._set_env_path_with_node_modules():
import warnings
msg = (
"Unable to locate the binary or runtime; default "
"module level functions will not work. Please either prov... | This was originally designed to be invoked at the module level
for packages that implement specific support, but this can be
used to create an instance that has the Node.js backed
executable be found via current directory's node_modules or
NODE_PATH. |
340,542 | def RegisterPlugin(cls, plugin_class):
name = getattr(
plugin_class, , plugin_class.__name__)
name = name.lower()
if name in cls._plugins:
raise KeyError(
.format(name))
preprocess_plugin = plugin_class()
cls._plugins[name] = preprocess_plugin
if isinstance(
... | Registers an preprocess plugin class.
Args:
plugin_class (type): preprocess plugin class.
Raises:
KeyError: if plugin class is already set for the corresponding name.
TypeError: if the source type of the plugin class is not supported. |
340,543 | def _kmeans(X, n_clusters, max_iter, n_trials, tol):
n_samples, n_features = X.shape[0], X.shape[1]
centers_best = np.empty(shape=(n_clusters,n_features), dtype=float)
labels_best = np.empty(shape=n_samples, dtype=int)
for i in range(n_trials):
centers, labels, sse_tot, sse_arr, n_iter =... | Run multiple trials of k-means clustering,
and outputt he best centers, and cluster labels |
340,544 | def pretty_format_args(*args, **kwargs):
args = list([repr(a) for a in args])
for key, value in kwargs.items():
args.append("%s=%s" % (key, repr(value)))
return "(%s)" % ", ".join([a for a in args]) | Take the args, and kwargs that are passed them and format in a
prototype style. |
340,545 | def members(name, ref):
cube = get_cube(name)
result = cube.members(ref, cuts=request.args.get(),
order=request.args.get(),
page=request.args.get(),
page_size=request.args.get())
result[] =
return jsonify(result) | List the members of a specific dimension or the distinct values of a
given attribute. |
340,546 | def parse(self, fh):
with fh:
try:
first_line = next(fh)
except StopIteration:
return
first_parsed = self.parse_line(first_line.rstrip())
fh_new = itertools.chain([first_line], fh)
if first_parsed.category == "v... | Generate tap.line.Line objects, given a file-like object `fh`.
`fh` may be any object that implements both the iterator and
context management protocol (i.e. it can be used in both a
"with" statement and a "for...in" statement.)
Trailing whitespace and newline characters will be automa... |
340,547 | def crypto_core_ed25519_add(p, q):
ensure(isinstance(p, bytes) and isinstance(q, bytes) and
len(p) == crypto_core_ed25519_BYTES and
len(q) == crypto_core_ed25519_BYTES,
.format(
),
raising=exc.TypeError)
r = ffi.new("unsigned char[]", crypto_core_ed25... | Add two points on the edwards25519 curve.
:param p: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
representing a point on the edwards25519 curve
:type p: bytes
:param q: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
representing a point on the edwards... |
340,548 | def generate_entropy(strength, internal_entropy, external_entropy):
if strength not in (128, 192, 256):
raise Exception("Invalid strength")
if not internal_entropy:
raise Exception("Internal entropy is not provided")
if len(internal_entropy) < 32:
raise Exception("Internal ent... | strength - length of produced seed. One of 128, 192, 256
random - binary stream of random data from external HRNG |
340,549 | def push(self, k):
if not self._first:
self._first = self._last = node = DLL.Node(k)
elif self._first.value == k:
return
else:
try:
self.delete(k)
except KeyError:
pass
... | Push k to the top of the list
>>> l = DLL()
>>> l.push(1)
>>> l
[1]
>>> l.push(2)
>>> l
[2, 1]
>>> l.push(3)
>>> l
[3, 2, 1] |
340,550 | def as_sql(self):
return .join( % name if self.attributes[name].sql_expression is None
else % (self.attributes[name].sql_expression, name)
for name in self.names) | represent heading as SQL field list |
340,551 | def add_average_summary(self, var, tag=None, decay=0.999, ignore_nan=True):
if not self.summary_collections:
return
with self.g.as_default():
if decay < 0.9 or decay >= 1.0:
raise ValueError( % decay)
avg_var = self.exponential_moving_average(var,
... | Add a summary with the moving average of var.
Adds a variable to keep track of the exponential moving average and adds an
update operation to the bookkeeper. The name of the variable is
'%s_average' % name prefixed with the current variable scope.
Args:
var: The variable for which a moving aver... |
340,552 | def check_aggregate(self, variable, components=None, exclude_on_fail=False,
multiplier=1, **kwargs):
df_components = self.aggregate(variable, components)
if df_components is None:
return
rows = self._apply_filters(variable=variable)... | Check whether a timeseries matches the aggregation of its components
Parameters
----------
variable: str
variable to be checked for matching aggregation of sub-categories
components: list of str, default None
list of variables, defaults to all sub-categories of `... |
340,553 | def reset_config_files():
print("*** Reset Spyder settings to defaults ***", file=STDERR)
for fname in SAVED_CONFIG_FILES:
cfg_fname = get_conf_path(fname)
if osp.isfile(cfg_fname) or osp.islink(cfg_fname):
os.remove(cfg_fname)
elif osp.isdir(cfg_fname):
... | Remove all config files |
340,554 | def field2read_only(self, field, **kwargs):
attributes = {}
if field.dump_only:
attributes["readOnly"] = True
return attributes | Return the dictionary of OpenAPI field attributes for a dump_only field.
:param Field field: A marshmallow field.
:rtype: dict |
340,555 | def project(self, coords):
geotransform = self.tuple
for x, y in coords:
geo_x = geotransform[0] + geotransform[1] * x + geotransform[2] * y
geo_y = geotransform[3] + geotransform[4] * x + geotransform[5] * y
geo_x += geotransform[1] / 2.0
... | Convert image pixel/line coordinates to georeferenced x/y, return a
generator of two-tuples.
Arguments:
coords -- input coordinates as iterable containing two-tuples/lists
such as ((0, 0), (10, 10)) |
340,556 | def JMS_to_FormFlavor_chrom(C, qq, parameters):
e = sqrt(4 * pi * parameters[])
gs = sqrt(4 * pi * parameters[])
if qq[0] in dflav.keys():
s = dflav[qq[0]]
b = dflav[qq[1]]
return {
+ qq : C[][s, b] / e,
+ qq : C[][s, b] / gs,
+ qq : C[][b... | From JMS to chromomagnetic FormFlavor basis for Class V.
qq should be of the form 'sb', 'ds', 'uu', mt (mu tau), em (e mu) etc. |
340,557 | def default_campaign(
campaign=None, expandcampvars=True, exclude_nodes=None, frozen=True
):
campaign = campaign or nameddict()
def _merger(_camp, _deft):
for key in _deft.keys():
if (
key in _camp
and isinstance(_camp[key], dict)
and... | Fill an existing campaign with default
values for optional keys
:param campaign: dictionary
:type campaign: str
:param exclude_nodes: node set to exclude from allocations
:type exclude_nodes: str
:param expandcampvars: should env variables be expanded? True by default
:type expandcampvars: ... |
340,558 | def get_frip(self, sample):
import pandas as pd
with open(sample.frip, "r") as handle:
content = handle.readlines()
reads_in_peaks = int(re.sub("\D", "", content[0]))
mapped_reads = sample["readCount"] - sample["unaligned"]
return pd.Series(reads_in_peaks / m... | Calculates the fraction of reads in peaks for a given sample.
:param pipelines.Sample sample: Sample object with "peaks" attribute. |
340,559 | def unlock_weixin_callback_example(url, req, resp, img, identify_image_callback):
unlock_url =
data = {
: time.time() * 1000,
: identify_image_callback(img)
}
headers = {
: ,
: ,
: url
}
r_unlock = req.post(unlock_url, data, headers=headers)
... | 手动打码解锁
Parameters
----------
url : str or unicode
验证码页面 之前的 url
req : requests.sessions.Session
requests.Session() 供调用解锁
resp : requests.models.Response
requests 访问页面返回的,已经跳转了
img : bytes
验证码图片二进制数据
identify_image_callback : callable
处理验证码函数,输入验证码二进制数... |
340,560 | def to_json_path(graph: BELGraph, path: str, **kwargs) -> None:
with open(os.path.expanduser(path), ) as f:
to_json_file(graph, file=f, **kwargs) | Write this graph to the given path as a Node-Link JSON. |
340,561 | def _fabtabular():
import csv
import sys
from pkg_resources import resource_filename
data = resource_filename(__package__, )
inverted = resource_filename(__package__, )
macro = resource_filename(__package__, )
part5 = resource_filename(__package__, )
part2 = resource_filename(__pac... | This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists. |
340,562 | def trace(self, app):
if app not in self._trace_cache:
process = subprocess.Popen(
"trace-deps.js {}".format(app), shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
env=self.env, universal_newlines=True, cwd=self._package_json_dir
... | Trace the dependencies for app.
A tracer-instance is shortlived, and re-tracing the same app should
yield the same results. Since tracing is an expensive process, cache
the result on the tracer instance. |
340,563 | def write_code(self, name, code):
file_path = self.gen_file_path(name)
with open(file_path,) as f:
f.write(code) | Writes code to a python file called 'name',
erasing the previous contents.
Files are created in a directory specified by gen_dir_name (see function gen_file_path)
File name is second argument of path |
340,564 | def execute(self):
for n in self.g.nodes():
self.g.node[n][] = [n]
all_communities = {}
for ego in tqdm.tqdm(nx.nodes(self.g), ncols=35, bar_format=):
ego_minus_ego = nx.ego_graph(self.g, ego, 1, False)
community_to_nodes = self.__overlapping_labe... | Execute Demon algorithm |
340,565 | def list_benchmarks(root, fp):
update_sys_path(root)
fp.write()
first = True
for benchmark in disc_benchmarks(root):
if not first:
fp.write()
clean = dict(
(k, v) for (k, v) in benchmark.__dict__.items()
if isinstance(v, (str, int, float, l... | List all of the discovered benchmarks to fp as JSON. |
340,566 | def main(self):
self.secret_finder()
self.parse_access_token()
self.get_session_token()
self.parse_session_token()
self.get_route()
self.download_profile()
self.find_loci()
self.download_loci() | Run the appropriate methods in the correct order |
340,567 | def process_args():
parser = argparse.ArgumentParser()
parser.add_argument(, type=str,
metavar=,
action=,
help=)
parser.add_argument(, type=str, metavar=,
... | Parse command-line arguments. |
340,568 | def list(self, networkipv4=None, ipv4=None):
uri =
if networkipv4:
uri += % networkipv4
if ipv4:
uri += % ipv4
return self.get(uri) | List all DHCPRelayIPv4.
:param: networkipv4: networkipv4 id - list all dhcprelay filtering by networkipv4 id
ipv4: ipv4 id - list all dhcprelay filtering by ipv4 id
:return: Following dictionary:
[
{
"networkipv4": <networkipv4_id>,
"id": <id>,
... |
340,569 | def validate(self, value, redis):
value = self.value_or_default(value)
self.validate_required(value)
if value is None:
return None
if type(value) == str:
try:
value = datetime.datetime.strptime(value, )
except ValueError:
... | Validates data obtained from a request in ISO 8061 and returns it in Datetime data type |
340,570 | def sku_update(self, product_id, properties, session, **kwargs):
request = TOPRequest()
request[] = product_id
request[] = properties
for k, v in kwargs.iteritems():
if k not in (, , , , ) and v==None: continue
request[k] = v
self.create(self.exec... | taobao.fenxiao.product.sku.update 产品sku编辑接口
产品SKU信息更新 |
340,571 | def list_accounts(self, id, max_id=None, min_id=None, since_id=None, limit=None):
id = self.__unpack_id(id)
if max_id != None:
max_id = self.__unpack_id(max_id)
if min_id != None:
min_id = self.__unpack_id(min_id)
if since_id !=... | Get the accounts that are on the given list. A `limit` of 0 can
be specified to get all accounts without pagination.
Returns a list of `user dicts`_. |
340,572 | def __verify_load(self, load, verify_keys):
if any(key not in load for key in verify_keys):
return False
if not in load:
log.error(
%s\%s\,
load[], inspect_stack()[],
)
return False
if not self.__verify_mi... | A utility function to perform common verification steps.
:param dict load: A payload received from a minion
:param list verify_keys: A list of strings that should be present in a
given load
:rtype: bool
:rtype: dict
:return: The original load (except for the token) if t... |
340,573 | def load_audio(path, with_path=True, recursive=True, ignore_failure=True, random_order=False):
from scipy.io import wavfile as _wavfile
all_wav_files = []
if _fnmatch(path, ):
all_wav_files.append(path)
elif recursive:
for (dir_path, _, file_names) in _os.walk(path):
... | Loads WAV file(s) from a path.
Parameters
----------
path : str
Path to WAV files to be loaded.
with_path : bool, optional
Indicates whether a path column is added to the returned SFrame.
recursive : bool, optional
Indicates whether ``load_audio`` should do a recursive dir... |
340,574 | def _check_if_ins_is_dup(self, start, insertion):
is_dup = False
variant_start = None
dup_candidate_start = start - len(insertion) - 1
dup_candidate = self._ref_seq[dup_candidate_start:dup_candidate_start + len(insertion)]
if insertion == dup_candidate:
... | Helper to identify an insertion as a duplicate
:param start: 1-based insertion start
:type start: int
:param insertion: sequence
:type insertion: str
:return (is duplicate, variant start)
:rtype (bool, int) |
340,575 | def mul(a, b):
if a is None:
if b is None:
return None
else:
return b
elif b is None:
return a
return a * b | Multiply two values, ignoring None |
340,576 | def _add_parsley_ns(cls, namespace_dict):
namespace_dict.update({
: cls.LOCAL_NAMESPACE,
: cls.LOCAL_NAMESPACE,
})
return namespace_dict | Extend XPath evaluation with Parsley extensions' namespace |
340,577 | async def _ask_queue_update(self):
try:
while True:
await asyncio.sleep(self._queue_update_timer)
if self._queue_update_last_attempt == 0 or self._queue_update_last_attempt > self._queue_update_last_attempt_max:
if self._queue_update_last_... | Send a ClientGetQueue message to the backend, if one is not already sent |
340,578 | def _on_auth(self, sock, authenticated):
def ack(eventname, error, data):
if error:
self.log.error(f)
else:
self.connect_channels(self.channels)
self.post_conn_cb()
sock.emitack("auth", self.creds, ack) | Message received from websocket |
340,579 | def clean_dict_keys(d):
new_d = {}
for (k, v) in d.iteritems():
new_d[str(k)] = v
return new_d | Convert all keys of the dict 'd' to (ascii-)strings.
:Raises: UnicodeEncodeError |
340,580 | def _is_ascii_encoding(encoding):
if encoding is None:
return False
try:
return codecs.lookup(encoding).name == "ascii"
except LookupError:
return False | Given an encoding this figures out if the encoding is actually ASCII (which
is something we don't actually want in most cases). This is necessary
because ASCII comes under many names such as ANSI_X3.4-1968. |
340,581 | def list_attached_team(context, id, sort, limit, where, verbose):
result = topic.list_teams(context, id=id, sort=sort, limit=limit,
where=where)
utils.format_output(result, context.format, verbose=verbose) | list_attached_team(context, id, sort, limit. where. verbose)
List teams attached to a topic.
>>> dcictl topic-list-team
:param string id: ID of the topic to list teams for [required]
:param string sort: Field to apply sort
:param integer limit: Max number of rows to return
:param string where... |
340,582 | def concat(self, operand, start=0, end=0, offset=0):
if not Gauged.map_concat(self.ptr, operand.ptr, start, end, offset):
raise MemoryError | Concat a map. You can also optionally slice the operand map
and apply an offset to each position before concatting |
340,583 | def read_cache(self):
if os.path.exists(self._cache_file):
self._cache = read_cache_file(self._cache_file)
else:
self._cache = {} | Reads the cached contents into memory. |
340,584 | def seconds2time(s):
hour, temp = divmod(s, 3600)
minute, temp = divmod(temp, 60)
temp, second = math.modf(temp)
return datetime.time(hour=int(hour), minute=int(minute), second=int(second),
microsecond=int(round(temp * 1e6))) | Inverse of time2seconds(). |
340,585 | def to_bqm(self, model):
linear = ((v, float(model.get_py_value(bias)))
for v, bias in self.linear.items())
quadratic = ((u, v, float(model.get_py_value(bias)))
for (u, v), bias in self.quadratic.items())
offset = float(model.get_py_value(self.offs... | Given a pysmt model, return a bqm.
Adds the values of the biases as determined by the SMT solver to a bqm.
Args:
model: A pysmt model.
Returns:
:obj:`dimod.BinaryQuadraticModel` |
340,586 | def largestNativeClique(self, max_chain_length=None):
def f(x):
return x.largestNativeClique(max_chain_length=max_chain_length)
objective = self._objective_bestscore
return self._translate(self._map_to_processors(f, objective)) | Returns the largest native clique embedding we can find on the
processor, with the shortest chainlength possible (for that clique
size). If possible, returns a uniform choice among all largest
cliques.
INPUTS:
max_chain_length (int): longest chain length to consider or ``No... |
340,587 | def readRaw8(self):
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(False)])
self._i2c_stop()
self._i2c_idle()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(True)])
self._i2c... | Read an 8-bit value on the bus (without register). |
340,588 | def _log(message):
print(time.strftime(, time.localtime()) + + str(message), flush=True) | Logs a message.
:param str message: The log message.
:rtype: None |
340,589 | def mount_for_path(path, client):
backend_data = client.list_secret_backends()[]
backends = [mnt for mnt in backend_data.keys()]
path_bits = path.split()
if len(path_bits) == 1:
vault_path = "%s/" % path
if vault_path in backends:
return vault_path[0:len(vault_path) - 1]... | Returns the mountpoint for this path |
340,590 | def __parse_stream(self, stream):
nline = 0
lines = stream.split()
for line in lines:
nline += 1
m = re.match(self.LINES_TO_IGNORE_REGEX, line, re.UNICODE)
if m:
continue
line = line.strip().strip()
... | Generic method to parse mailmap streams |
340,591 | def get(self, url, headers=None, params=None):
merged_headers = self._merge_headers(headers)
if "Accept" not in merged_headers:
merged_headers["Accept"] = MEDIA_TYPE_TAXII_V20
accept = merged_headers["Accept"]
resp = self.session.get(url, headers=merged_headers, p... | Perform an HTTP GET, using the saved requests.Session and auth info.
If "Accept" isn't one of the given headers, a default TAXII mime type is
used. Regardless, the response type is checked against the accept
header value, and an exception is raised if they don't match.
Args:
... |
340,592 | def hover(self):
def do_hover():
ActionChains(self.driver_wrapper.driver).move_to_element(self.element).perform()
return self.execute_and_handle_webelement_exceptions(do_hover, ) | Hovers the element |
340,593 | def parse_plain_scalar_indent(TokenClass):
def callback(lexer, match, context):
text = match.group()
if len(text) <= context.indent:
context.stack.pop()
context.stack.pop()
return
if text:
yield match.start(), TokenClass, text
... | Process indentation spaces in a plain scalar. |
340,594 | def reject(self, message=None):
with db.session.begin_nested():
if self.status != RequestStatus.PENDING:
raise InvalidRequestStateError(RequestStatus.PENDING)
self.status = RequestStatus.REJECTED
request_rejected.send(self, message=message) | Reject request. |
340,595 | def _add_url_rule_patch(blueprint_setup, rule, endpoint=None, view_func=None, **options):
if callable(rule):
rule = rule(blueprint_setup.url_prefix)
elif blueprint_setup.url_prefix:
rule = blueprint_setup.url_prefix + rule
options.setdefault(, blueprint_setup.sub... | Patch BlueprintSetupState.add_url_rule for delayed creation.
Method used for setup state instance corresponding to this Api
instance. Exists primarily to enable _make_url's function.
:param blueprint_setup: The BlueprintSetupState instance (self)
:param rule: A string or callable that... |
340,596 | def get_component(self, entity, component_type, missing=MISSING):
relation = self._get_relation(component_type)
if entity not in relation:
if missing is MISSING:
raise NoSuchComponentError()
else:
return missing
return relation[ent... | Get the component of type component_type associated with entity.
Long-hand for :func:`essence.Entity.get`.
:param entity: entity to query
:type entity: :class:`essence.Entity`
:param component_type: component to add to the entity
:type component_type: The :class:`type` of a :cl... |
340,597 | def parse_version_information(self, version_struct):
start_offset = self.get_offset_from_rva( version_struct.OffsetToData )
raw_data = self.__data__[ start_offset : start_offset+version_struct.Size ]
versioninfo_str... | Parse version information structure.
The date will be made available in three attributes of the PE object.
VS_VERSIONINFO will contain the first three fields of the main structure:
'Length', 'ValueLength', and 'Type'
VS_FIXEDFILEINFO will hold the re... |
340,598 | def new_prelu(self, name: str, input_layer_name: str=None):
input_layer = self.__network.get_layer(input_layer_name)
with tf.variable_scope(name):
channels_input = int(input_layer.get_shape()[-1])
alpha = self.__make_var(, shape=[channels_input])
output = tf... | Creates a new prelu layer with the given name and input.
:param name: name for this layer.
:param input_layer_name: name of the layer that serves as input for this one. |
340,599 | def push_framer(self, *args, **kwargs):
elem = self._interpret_framer(args, kwargs)
self._framers.append(elem) | Called by the client protocol to temporarily switch to a new
send framer, receive framer, or both. Can be called multiple
times. Each call to ``push_framer()`` must be paired with a
call to ``pop_framer()``, which restores to the previously set
framer.
When called with positio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.