content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import OrderedDict
def dict_from_lst(lst, ordered=False):
"""
Return a dictionary from a Geosoft `geosoft.gxapi.GXLST` instance.
:param lst: `geosoft.gxapi.GXLST` instance
:param ordered: True to return an OrderedDict
:returns: python dictionary from a Geosoft GXLST
... | 54c87468f6eb633fda64d1373dc7a8c621d7991b | 51,300 |
def parse_external_id(output, type=EXTERNAL_ID_TYPE_ANY):
"""
Attempt to parse the output of job submission commands for an external id.__doc__
>>> parse_external_id("12345.pbsmanager")
'12345.pbsmanager'
>>> parse_external_id('Submitted batch job 185')
'185'
>>> parse_external_id('Submitte... | 9af3c73ffbfeac3273251230fe220f381b402214 | 51,301 |
def ldns_pkt_set_ra(*args):
"""LDNS buffer."""
return _ldns.ldns_pkt_set_ra(*args) | 159dde50ee549980a2a92d21f5dce23327c4d6b3 | 51,302 |
def rehash(path, blocksize=1 << 20):
# type: (str, int) -> Tuple[str, str]
"""Return (encoded_digest, length) for path using hashlib.sha256()"""
h, length = hash_file(path, blocksize)
digest = 'sha256=' + urlsafe_b64encode(
h.digest()
).decode('latin1').rstrip('=')
# unicode/str python2 ... | 15c1f620d45cef116af6c221b326a208ab27acc4 | 51,303 |
import re
def CombineLogFiles(list_of_lists, logger):
"""Splices together multiple logcats from the same device.
Args:
list_of_lists: list of pairs (filename, list of timestamped lines)
logger: handler to log events
Returns:
list of lines with duplicates removed
"""
cur_device_log = ['']
for... | a749e34e63163c8493e0d4923e78367a6396327f | 51,304 |
from typing import Callable
from typing import Any
def step_decrease(f: Callable[[Any], Any], x, step=1e-2, step_multiplier=2, iteration_limit=100000000):
"""
Continues to increment x with x + step till f(x) returns a value that is bigger than the previous value
i.e
stop when f(x) > f(x+s)
step on... | 03b08e33ac6eaacc1e6939f9239058d90b9a6b04 | 51,305 |
def lcs_naive(first: str, index_f: int, second: str, index_s: int) -> int:
"""
Time Complexity: O(2^n)
"""
if index_f < 0 or index_s < 0:
return 0
if first[index_f] == second[index_s]:
return 1 + lcs_naive(first, index_f - 1, second, index_s - 1)
return max(
lcs_naive(f... | be2ef4013732d75ab14c69e8f93d38cc7f011e7c | 51,306 |
from typing import Dict
from pathlib import Path
from typing import Tuple
from typing import List
import os
import subprocess
def verify(signify: Dict[str, str], snapshot: Path,
filename: str="") -> Tuple[bool, List[str]]:
"""Verify the integrity of a given snapshot with signify.
signify -- a dict... | 785b476967f15203362ea99cea06d8e2d94b3522 | 51,307 |
from typing import List
def cf_explain(examples: List[Example], nmols: int = 3) -> List[Example]:
"""From given :obj:`Examples`, find best counterfactuals using :ref:`readme_link:counterfactual generation`
:param examples: Output from :func:`sample_space`
:param nmols: Desired number of molecules
"""... | ebaadd0d7d235bcece99257e6d0debd02f6bb79a | 51,308 |
def quantile(a, q, axis=None, out=None,
overwrite_input=False, interpolation='linear', keepdims=False):
"""
Compute the q-th quantile of the data along the specified axis.
..versionadded:: 1.15.0
Parameters
----------
a : array_like
Input array or object that can be convert... | 30af34a0806daf25370bb202aa2fe6dd6d2b5cb2 | 51,309 |
def build_classifier(img_shape, num_classes):
"""
Function: build_classifier
Input: img_shape: image shape, num_classes: the number of image classes
Output: CNN-based classifier model
"""
cinput = Input(shape=img_shape, name='classifier_input')
H = Conv2D(64, kernel_size=(5, 5), acti... | ead6fa1190bf8a2e79b2f2b354853072ca5a7513 | 51,310 |
def filter_pair_by_len(p, maxlen=c.MAX_LENGTH):
""" Filter out sentences if they are greater than maximum length.
"""
return len(p[0].split(" ")) < maxlen and len(p[1].split(" ")) < maxlen | 6e659746f193b3a420fd8189f324b166d4374b70 | 51,311 |
def run_model(params, rollout_size=50, num_steps=50):
"""Perform the training operation.
Parameters
----------
params : dict
flow-specific parameters (see flow/utils/registry.py)
rollout_size : int
length of a single rollout
num_steps : int
total number of training steps... | 86786ac27de7b4bd9a9ec75de745dfb45a00edf0 | 51,312 |
def func_lineno(func):
"""Get the line number of a function.
"""
try:
return func.compat_co_firstlineno
except AttributeError:
try:
if PYTHON_VERSION_MAJOR == 3:
return func.__code__.co_firstlineno
return func.func_code.co_firstlineno
excep... | 884f4fdfeeb22634d46f4f2651b0c5f93cb687e0 | 51,313 |
def calc_cl_metrics(acc_matrix):
"""
Calculate metrics based on an accuracy matrix of N train tasks on N test tasks
The lower triangular matrix is the BWT, the higher triangular matrix is the FWT
The metrics below are taking into account the accuracy of the model at every timestep / task
by dividin... | 4b1a1e12a6e2f06227f244ec8ba882ee634b135a | 51,314 |
def ElectricField(q, r0, x, y):
""" Return the electric field vector E=(Ex, Ey) due to charge q at r0.
"""
den = np.hypot(x - r0[0], y - r0[1]) ** 1.5
return q * (x - r0[0]) / den, q * (y - r0[1]) / den | 76aee7a4c8c0254eee8fc0c99793c86d501514fe | 51,315 |
import shelve
import contextlib
def readMirror(fileLocation):
"""Returns saved Model (mirror) from Pickled file at 'fileLocation'
Needed to transfer model from IPY to PY3
"""
#f = open(fileLocation,"rb")
with contextlib.closing(shelve.open(fileLocation, 'r')) as shelf:
mir = shelf['... | f6d6c56dbe99d544ccdc041f35e48e87883166c8 | 51,316 |
import json
import httpx
def get_api_es_client(session):
"""
Returns an Elasticsearch client for the catalogue cluster.
"""
secrets = session.client("secretsmanager")
credentials = json.loads(
secrets.get_secret_value(SecretId="elasticsearch/api_cleanup/credentials")[
"SecretS... | 5adcdb58a8eabe8d84834f730ab080a2f0b227c9 | 51,317 |
import os
import re
import inspect
def _longmess(*args, skip=0):
"""Message with stack backtrace"""
def ff(fn):
fn = os.path.relpath(fn)
if fn.startswith('./'):
return fn[2:]
return fn
def fa(a):
result = re.sub(r'^\(\*_args=(.*)\)$', r'\1',a).replace(',)', ')')
... | 502ff5f9541862c841d532d206cd6331e987eb4a | 51,318 |
def insertionsort(x, count = False):
"""
For each element e of x, move through the array until you come to a value
that is less than e, or the end of the array, then place e at the new location.
"""
assignments, conditionals = 0, 0
for i in range(1, len(x)):
element = x[i]
j = i... | 4a8ae9bda1dfee0cb41ae7544cb45d089e11f703 | 51,319 |
import logging
import sys
import os
import json
def install(enable=False, disable=False, status=None, prefix=None, path=None, verbose=False):
"""Installs the nb_conda_kernels configuration data.
Parameters
----------
enable: bool
Enable nb_conda_kernels; that is, make the changes to
t... | d68a0ff59ac2a65cf9459303b7eac3c653a5bbee | 51,320 |
def vm_impl_concatOffset(self):
"""Generate vm_impl function for ConcatOffset"""
def vm_impl(x):
out = vm.ConcatOffset(x) # out is tuple
return out
return vm_impl | 533041af510acf55c1337f6c2052053aa9669645 | 51,321 |
import requests
def get_assimilator_data(mode, assimilator, text, link):
"""
This function is used for get parsed web/local document from a Tika-service
mode: get metadata or content body
assimilator: api address of the text assimilator, running apache tika
text: piece of raw text
link: web ur... | 4af3970f8fd51e565c0d6bc5c2e92bf29eac98f5 | 51,322 |
def list_channel_messages_since_delta(session, *, deltaLink):
"""List channel messages for the team and channel
session = requests.Session() instance with Graph access token
deltaLink = the leftover delta you were given the last time you called list_channel_messages_since_time
we will p... | fc51b10d6cbd5207d150fa5579c3c367f77a09ba | 51,323 |
def get_default_title():
""" See description in Bootloader class below """
return __bootloader.get_default_title() | 13ca4ce0e74994f993830c20ca6b0bb920918998 | 51,324 |
def parse_config(app):
"""Process the Sphinx Gallery configuration"""
try:
plot_gallery = eval(app.builder.config.plot_gallery)
except TypeError:
plot_gallery = bool(app.builder.config.plot_gallery)
src_dir = app.builder.srcdir
abort_on_example_error = app.builder.config.abort_on_exa... | c90f17a7e6912fc94f9b97463db2ec570c9d0aab | 51,325 |
import json
def get_leader(cluster_name, role_type):
"""
:param cluster_name: 集群名称
:param role_type: 角色类型
:return: overlord or coordinator
"""
cluster = model_manager.get_cluster_obj_by_name_type(cluster_name, DRUID)
conn_info = json.loads(cluster.connection_info)
zk_addr = conn_info[Z... | 8d83f2f9625b92e4f1b355eaac5dd8e503155b7b | 51,326 |
from typing import Any
def _async_get_diagnostics(
hass: HomeAssistant,
entry: ConfigEntry,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
pv_entry: PowerviewEntryData = hass.data[DOMAIN][entry.entry_id]
shade_data = pv_entry.coordinator.data.get_all_raw_data()
hub_info = as... | fa6cd381a0b2a2578fa8aaa9276715deb70e8de9 | 51,327 |
import requests
import logging
def execute_dax_query(credential, dataset_id, daxQuery):
"""Execute DAX query"""
url = f"https://api.powerbi.com/v1.0/myorg/datasets/{dataset_id}/executeQueries"
try:
token = credential.get_token("https://analysis.windows.net/powerbi/api/.default").token
... | 9adcd81d0bcfc642b0c0336d351f5ad9b71aad7a | 51,328 |
def nosofsky_1986():
"""Category structure used in [1].
There are three category structures: dimensional, criss-cross,
interior-exterior, and diagonal.
References:
[1] Nosofsky, R. M. (1986). Attention, similarity, and the
identification-categorization relationship. Journal of
Expe... | 6a31e0fb7a53006bb735bc4024aa062c0f0f29c8 | 51,329 |
import time
def wait_for_tasks(session, tasks, timeout):
"""returns true if all tasks are no longer pending (ie success/failure/cancelled)
and false if a timeout occurs"""
finished = False
start = time.time ()
while not(finished) and ((time.time () - start) < timeout):
finished = True
... | 8a4652060621ce3a7f3890578dea307f7e9bc8b5 | 51,330 |
import requests
import json
def get_previous(pair, end, qty):
"""get the previous pairs
Arguments:
pair {string} -- the name of the pair eg. EOSUSD
end {int} -- time of the last records to request
qty {int} -- the number of records to request
Returns:
list -- qty prices b... | f09845b2ae75e7ae3f9eca1da26f2d88790a1478 | 51,331 |
import copy
def handle_multiple_variantcallers(data):
"""Split samples that potentially require multiple variant calling approaches.
"""
assert len(data) == 1
callers = get_variantcaller(data[0])
if isinstance(callers, basestring):
return [data]
elif not callers:
return []
... | 93ea4dff458ad2aa937e776fe45acfca3d91298e | 51,332 |
import yaml
import re
def guess_host_name():
""" Just a handy function for external use
"""
with open(join(package_path(), 'paths.yml')) as f:
loc_by_name = yaml.load(f, Loader=yaml.FullLoader)
for ld in loc_by_name.values():
if 'host_pattern' in ld:
if re.match(ld['host_pa... | 1d5d0503f4ac28d6bb96ad12469c19931065c082 | 51,333 |
import os
import tarfile
import glob
def prepare_gensim_archive(fn):
"""Unpacks a gensim archive file
:param fn: Filename of gensim archive file
:return: Filename of an on disk gensim model which can be loaded into memory with LdaModel.load()
"""
if fn.endswith('.tar') or fn.endswith('.bz2') or f... | 8ff95db3987e2250ee3ade920b52a31589cfef9c | 51,334 |
def main():
"""Runs the tests."""
defaults = {
'TEST_ID':
'MySimpleTest-' + KeystoreTestScenario.DEFAULT_TEST_ID
}
return citest.base.TestRunner.main(
default_binding_overrides=defaults,
test_case_list=[SynchronousKeystoreTest]) | d7c51db5bf56de8f5c923b9c968707bb7962a61a | 51,335 |
def get_maze(filename):
"""
Convenience function to get a grid from a file.
Takes the filename of the maze to load, loads the maze from the file,
and builds it into a grid. Then returns that grid.
Args:
filename: the file to load the maze from
Returns:
the grid representation ... | c9d0d3c3d7501afd4cd4a2fe178ad3f26877dfc3 | 51,336 |
def get_loss(name):
"""Returns loss_fn(outputs, ground_truths, **kwargs), where "outputs" are the model outputs.
Args:
name: The name of the loss function.
Returns:
loss_fn: A function that computes the loss between the inputs and the ground_truths
Raises:
ValueError: If Preprocessing `name` is n... | 33ef3a864ded30265cf3641ace5128c6271333cc | 51,337 |
def get_processed_invoices_df():
"""
this function will read the dataframe and create a text string for each row separated by new line '\n'
to match with resultant data for testing.
"""
process_invoices = spark.sql("select * from processedInvoiceTbl")
text = ""
for i in range(1, process_in... | e3ee7d2bc0880f1f8bd0fbd55338228814c01c2c | 51,338 |
def resistance(v='x', i='x', p='x', l='x', a='x', pw='x'):
"""
Calculate and return the value of resistance using given values of the params
How to Use:
Give arguments for v and i params,
or, give arguments for p,l and a params,
or, give arguments for pw and i params
or, giv... | d411cc6bb348e66d0f4eedab3a6ae7550a4cd4a7 | 51,339 |
async def edit_a_group(id: int, group: Group):
"""Updates the information stored about a group."""
updated_group = await Group.edit(id, group)
if not updated_group:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="group not found.")
return updated_group | e0e4d5faaf1cb9b071c899ab165c37cc6925bbfa | 51,340 |
from typing import AnyStr
from typing import Tuple
def derive_password(password: AnyStr) -> Tuple[bytes, bytes]:
"""
Args:
password: Password
Returns:
Encryption key, Mac key
"""
if isinstance(password, str):
password = password.encode()
tmp = PBKDF2HMAC(hashes.SHA25... | 8b3268006d556bcd97c936ce0390ab18ecb12939 | 51,341 |
import sys
def check_arguments(options, args, parser):
""" Checks if arguments passed to script are plausible.
Returns a ParseResult 6-tuple if successful. """
# Make sure args list may be valid
if len(sys.argv) < 6:
print >> sys.stderr, parser.get_usage()
sys.exit(1)
# Make s... | 8b136e9f521ad92f38f23d3abf07c2ad130cc1e4 | 51,342 |
def get_setting(varname):
""" Returns the value of a configuration variable. """
gl = globals()
if varname not in gl.keys():
raise ValueError("Unknown setting %s"%varname)
# Here, possibly add some code to raise exceptions if some
# parameter isn't set set properly, explaining on how to set... | ed5d831a7f96439dfe8439750c96062eae434f43 | 51,343 |
def get_lr(curr_epoch, hparams, iteration=None):
"""Returns the learning rate during training based on the current epoch."""
assert iteration is not None
batches_per_epoch = int(hparams.train_size / hparams.batch_size)
if 'svhn' in hparams.dataset and 'wrn' in hparams.model_name:
lr = step_lr(hp... | ebe5dc79bc03007dbffa8ee5c8d878d10cb5e690 | 51,344 |
def _timestamp_to_date_string(timestamp: pd.Timestamp):
"""Return a date-string (YYYY-MM-DD) from a pandas Timestamp."""
if timestamp.tzinfo:
timestamp = timestamp.tz_convert('UTC')
timestamp = timestamp.tz_localize(None)
date = pd.Timestamp.date(timestamp)
if pd.Timestamp(date) != timestamp... | c6b69be196cec2a0d3c9a7a246307227f6faba18 | 51,345 |
def beta_tcon(s_gkg,t_cels,p_dbar,tp_cels=None,chkvals=False,
chktol=_CHKTOL,tp_cels0=None,chkbnd=False,useext=False,
mathargs=None):
"""Calculate haline contraction wrt conservative temperature.
Calculate the haline contraction coefficient of seawater at constant
conservative temperature.
... | af4e6bb6903644ec7f25771240723b14429b1aaf | 51,346 |
def workspace_list_table_format(result):
"""Format workspace list as a table"""
table = []
for item in result:
table.append(workspace_show_table_format(item))
return table | b8af25ff21930bed92fec15e4f11323f3270a3b9 | 51,347 |
def get_items(wiki, only_undone=False) -> list:
""" all items page list """
items = []
for page in wiki.pages():
content: str = wiki.page_info(page["pageid"])["*"]
if content.startswith("{{面包屑|物品信息"):
if only_undone and content.find("{{施工中}}") == -1:
continue
... | 1637c04aa61f5efe882af6c7f1bed80c3cde3185 | 51,348 |
def cycle(n):
"""Return the cycle graph on n vertices."""
return circulant(n, [1]) | 25ea83b0c61fb653caca6e899dfade52304df8e7 | 51,349 |
from typing import Any
def _attempt_cast_as_float(value: Any) -> float:
"""
:param vale: a value
:return: the value as a float if casting is possible, otherwise return 1
"""
try:
return float(value)
except (ValueError, TypeError):
return 1.0 | 8616bf4d59a08f8e98d26231f7aa51d419d52550 | 51,350 |
from typing import Any
from typing import Dict
from typing import List
import json
def adjust_dict_property(property_value: Any, model_field: ModelField, depth: int):
"""Convert a dict property for the BigQuery schema"""
dict_value_type = ModelFieldUtils.get_dict_value_type(model_field=model_field)
# Scal... | 29df072365e0c0b216744f790b627c868dbcd81e | 51,351 |
import os
def put_exh_banner_api_v1(
exhibition_id=Route(str, rules=ObjectIdValid()),
banner_photo=File(rules=MaxFileCount(1))
):
"""전시회 배너 이미지 업로드"""
oid = ObjectId(exhibition_id)
exhibition = Exhibition(g.db).find_one(oid)
if exhibition['owner_id'] != g.user_id:
return forbidden("You... | e4a4c69a52d3f29592624884c73b1d2d1f203636 | 51,352 |
def show_permission(permission_id):
"""Get permission."""
data = _get_request_args()
return utils.make_json_response(
200,
permission_api.get_permission(permission_id, user=current_user, **data)
) | c1f06c1c055d09bc195323e2a66b74ae06dc9fd9 | 51,353 |
import gzip
def train_markov_gz(fn):
""" trains a Markov model on gzipped text data """
with gzip.open(fn, "rt", encoding="utf-8") as f:
text = f.read()
return markovify.Text(text, retain_original=False, state_size=3) | dfd6470cef3254f3521d62d81c96afc61b781418 | 51,354 |
import sqlite3
from typing import List
from typing import Any
from typing import Sequence
from typing import Optional
from typing import Type
from re import T
from typing import Tuple
def execute_sql_by_id(db: sqlite3.Connection, sql: str,
sql_values: List[Any], ids: Sequence[T2], return_type: Optional[Type[T... | beabdfaca28e78d9633b137ce98aceed64bdc9ae | 51,355 |
def get_angle_direction(v1, v2, axis):
"""
Return the direction of rotation to get v1 onto v2 about the provided axis.
"""
axes_dict = {'x':0, 'y':1, 'z':2, 'X':0, 'Y':1, 'Z':2}
if axis in axes_dict:
axis = axes_dict[axis]
v1, v2 = np.atleast_2d(v1, v2) # vectors will be (1,3) or (N,3... | 3dad8268f3437f629c970c892e30df59b1b5c30b | 51,356 |
from typing import Optional
import os
def init(name: str, environment: str, template: Optional[str] = None) -> None:
"""
Create the local structure for a new AWS DDK Python project.
NAME is the name of the project.
"""
# Use default Cookiecutter project template
if not template:
templ... | 650a84819e54a89a1377ee7ed301840eff50fc0e | 51,357 |
def _estimate_log_gaussian_prob(X, means, precisions_chol, covariance_type):
"""Estimate the log Gaussian probability.
Parameters
----------
X : array-like of shape (n_samples, n_features)
means : array-like of shape (n_components, n_features)
precisions_chol : array-like
Cholesky dec... | 1c5d5d4e16687b362ee01612fa9ab0c04efde85e | 51,358 |
def _build_draw_line(append):
"""Specialize a line plotting kernel for a given append/axis combination"""
@ngjit
def draw_line(x0i, y0i, x1i, y1i, i, plot_start, clipped, *aggs_and_cols):
"""Draw a line using Bresenham's algorithm
This method plots a line segment with integer coordinates on... | acd77b3259fc4c9efe9afbc6312f11737c14509d | 51,359 |
def getLastSensorAcquisitionTime(sensorId, sessionId):
"""
Get the last sensor acquisition timestamp.
URL Path:
- sensorId: sensor ID.
- sessionId: session ID.
HTTP Return Codes:
- 200 OK if success
Returns a json document with last acquisition timestamp. Format of ret... | 931c39f7f060a9448a6ff0c7cb57d9f0246313ec | 51,360 |
def zeros(shape):
"""
:param shape: tuple with the shape of the wanted output (filters_amount, depth, height, width)
:return: array (it's shape=param shape) with initialized values using 'zeros' initializer
"""
return np.zeros(shape=shape) | 034f61b27e23b829c8c8828f9d2e5fffad3e7055 | 51,361 |
def addr_generator(start_ip, port, count):
"""Generator a list of (ip, port).
"""
def tostr(ip):
return '.'.join([str(_) for _ in ip])
ip = [int(_) for _ in start_ip.split('.')]
addr_list = [(tostr(ip), port)]
for i in range(count-1):
ip[-1] += 1
addr_list.append((tostr(i... | 100288629f35d9108e0b364266242da0110dd8f7 | 51,362 |
def filter_threshold(delta_f, threshold_value):
""" Return indices of the data whose values are above the acceptable level """
return delta_f >= threshold_value | a0c34eba86a0fb4539174d75f2cde19994aaa8cf | 51,363 |
def handler(event, context) -> utils.Response:
"""lambda entry point."""
return handlers.SnsEventHandler(
name="twitter",
event=utils.LambdaEvent(event),
context=utils.LambdaContext(context),
action=post_status,
).response | 67b6b16b978bc229e44929d8fc0f1b18d86834d5 | 51,364 |
from functools import reduce
def vector_sum(vectors):
"""一系列向量相加"""
return reduce(vector_add, vectors) | a4ffe3cf55c1b9c75ea811e2d77a66fceeb256d8 | 51,365 |
import random
import time
def retry(func, *args, **kwargs):
"""Repeats a function until it completes successfully or fails too often.
Args:
func:
The function call to repeat.
args:
The arguments which are passed to the function.
kwargs:
Key-word arg... | cf6f7d3e434b54cf178b2867f7565f338e985968 | 51,366 |
import os
import sys
import json
def get_config():
"""获取config.json文件信息"""
if not os.path.isfile(config_path):
logger.warning(u'当前路径:%s 不存在配置文件config.json',
(os.path.split(os.path.realpath(__file__))[0] + os.sep))
sys.exit()
try:
with open(config_path) as f:
... | 648f2d9350ba5ba36a09ed39445abfd260bfae97 | 51,367 |
def build_model_columns():
"""
:param data = df_preprocess_noNA
Builds a set of wide and deep feature columns.
"""
# Continuous variable columns
speed = tf.feature_column.numeric_column('speed')
inv_speed = tf.feature_column.numeric_column('inv_speed')
ais_rem_time = tf.feature_column.numeric_column('ai... | 5f5df227c12948dd1e8cee34af485db42a7a23d4 | 51,368 |
def test_custom_timeout(monkeypatch, fake_response, aqhttp):
"""Timeout should override from the aqhttp.post method."""
class FakeRequest:
def __init__(self, status_code=200, url="myfakeurl.com", method="post"):
self.status_code = status_code
self.url = url
self.meth... | 6b03e8f6124557119ef8b30191ab6d35f3d3e002 | 51,369 |
def create_tags(dataframe, periods):
"""
Función para clasificar los registros de cierre como
subidas/bajadas fuertes, subidas/bajada, o matiene de
un día con respecto a otro.
Parámetros:
----------
df pd.DataFrame:
DataFrame que se quiere clasificar.
periods int:
... | 2431b8d52fac840bbebf55bd33aa18327f0b0a01 | 51,370 |
def encrypt(data, key):
"""RC4"""
S = list(range(256))
j = 0
out = []
for i in range(256):
j = (j + S[i] + key.encode()[i % len(key)]) % 256
S[i], S[j] = S[j], S[i]
i = j = 0
for char in data:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j]... | 6c2ced51fc2ad443ffbfee1435092b3c60207bdb | 51,371 |
from re import A
def crop_by_range(anim: Animation[A], start: float, finish: float) -> Animation[A]:
"""
Render a range of an animation.
`start` and `finish` should be floats from 0 to 1.
"""
if not (0 <= start < finish <= 1):
raise ValueError(
"Invalid range ({}, {}). Expected... | 40b90adecb659aad60b14387ec2978be67e36c0b | 51,372 |
def hist_match(cdf_org, cdf_tar):
"""
Build the lookup table described in step 3.
Arguments:
-----------
cdf_org: dict
The cumulative distribution function of orginal image.
cdf_tar: dict
The cumulative distribution function of target image.
Returns:
-----------
l... | a5a428aeed6bafcbb9d2d39c6068a2bd1717179b | 51,373 |
def run_one_step(dataframe, start_centers):
"""
Performs one iteration of K-Means.
This function takes a dataframe with dense feature vectors, a set of centroids, and returns
a new set of centroids along with the total distance of points to centroids.
This function calculates for each point the cl... | b3d3012b167ae8484ddfadd029d60442d12d9292 | 51,374 |
def report_options(func):
"""Common report options."""
func = all_option(func)
func = count_option(func)
func = length_option(func)
func = end_option(func)
func = start_option(func)
func = exclude_option(func)
func = include_option(func)
return func | 76506f9644695fb4dbd24d23ec5f868dd2ee3886 | 51,375 |
import random
def train_test_split_adjacenty(total_size, test_ratio, test_indexes):
"""
Parameters
----------
A: scipy.sparse.spmatrix
connected sparse unweighted adjacency matrix
test_indexes: list
tuple with (x, y, val) for each idx in test datasets
Returns
-------
t... | 9b826a234da30f253c0d433123a16f912843d658 | 51,376 |
import torch
def _chunk_slice(
t: torch.Tensor,
flat_start: int,
flat_end: int,
no_batch_dims: int,
):
"""
Equivalent to
t.reshape((-1,) + t.shape[no_batch_dims:])[flat_start:flat_end]
but without the need for the reshape call, which can be
memory-int... | f77f8ea76fbc382eeb8a512f0944b809087e3266 | 51,377 |
def dimshuffle(arr, pattern):
"""
Based on theano's dimshuffle function.
Permutes the axes of an array and inserts new singleton axes.
e.g. if x has shape (2,3), then dimshuffle(x, [1,0,'x']) has shape (3,2,1)
note that dimshuffle can not drop dimensions.
inputs
------
pattern: list... | 3134f33ac002171d18775b66d04577ad06103d72 | 51,378 |
import pytz
def utc_to_local(utc_dt, local_tz):
"""Accepts a datetime object in UTC time, and returns the same time, in the timezone that was also passed"""
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
return local_tz.normalize(local_dt) | 15ade0c4d1b732b4fd9ef5c2f7de0eb32a3c6936 | 51,379 |
def within_limits(cave: ArrayLike, coord: tuple[int, int]) -> bool:
"""Check whether a given coordinate is within the limits of the cave."""
return (
(0 <= coord[0])
& (coord[0] <= cave.shape[1] - 1)
& (0 <= coord[1])
& (coord[1] <= cave.shape[0] - 1)
) | f3ed4a65c5c1289a7bdc1707b7c7320e8c4e2231 | 51,380 |
import os
import sys
import codecs
def apps_get(section):
"""Get dictionary key-value pairs of app names and package names."""
"""获取apps.ini里的包名和app名称"""
acfg = NewSafeConfigParser()
acfgpath = os.path.join(sys.path[0], 'cfg','apps.ini')
if not os.path.isfile(acfgpath):
raise IOError('%s N... | 3f4b4f4de9441df58a0238a32881a5818dcb6f26 | 51,381 |
import os
def get_project_settings_map(ctx):
"""
Get the map of all project settings that were found in the root folder
Util function to load the <engine root>/<project name>/project.json file and cache it within the build context.
:param ctx:
:return:
"""
try:
return ctx.project_... | 317b27a23f1b3631a18ab6eef7eb3c97ae2bec3a | 51,382 |
def unpack_from(fmt, buf, offset=0):
"""
Unpack the buffer, containing packed C structure data, according to
fmt starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).
See struct.__doc__ for more on format strings.
"""
try:
o = _cache[fmt]
except KeyError:
o = _c... | a7f020cd7564f92d0c4d8f67a979e000a7c18724 | 51,383 |
def load_single_mat(mat_file_floder,n_clip=1,dataset="Avenue",vis=True):
"""
:param mat_file: mat file path
:return: anomaly boundary [num ,2]
"""
filename = '%s/%d_label.mat' % (mat_file_floder, n_clip)
data=sio.loadmat(filename)
volLabel=data["volLabel"]
n_bin = np.array([np.sum(vol... | 021dd4c8a0267b49bef187bbb57f6abe35b7d285 | 51,384 |
def _ScatterAddNdimShape(unused_op):
"""Shape function for ScatterAddNdim Op."""
return [] | 7c59fb40e177fea1bf1cd3970c364f4583fc37f9 | 51,385 |
def sanitize_name(original_name: str):
"""Sanitize name for output into compiler artifacts
Parameters
----------
original_name : str
Original name to sanitize
"""
return _backend.SanitizeName(original_name) | 6bc6ab6037c0925c07f5b59821a4356a673aa8c9 | 51,386 |
def parse(sql, category=None):
"""
Returns data structure for SQL statement.
@param category expected statement category if any, like "table"
@return ({..}, None), or (None, error)
"""
result, err = None, None
try:
result, err = Parser().parse(sql, category)
except... | 2381eef37d4102037920712bb665ca3b3dfbebd7 | 51,387 |
def store_to_flat_XML(model, vpath):
"""Store current LO document to vpath, as a ODF flat XML file"""
return store_to__by_extn(model, vpath, '.fodt') or \
store_to__by_extn(model, vpath, '.fods') or False | bdac5d13b0e57db39575fff91ce163e98e365c28 | 51,388 |
def eDFA(F: np.ndarray) -> np.ndarray:
"""
In the reference indicated below a measure of nonstationarity was added by
including a subsequent calculation of the extrema of the DFA. Denoted
:math:`dF_q^2(s)` the difference of the extrema at each segment, i.e.,
.. math::
dF_q^2(s) = \max[F_q^... | 7df59a38ad2b414efcfd0be16f67dbcf264df4c6 | 51,389 |
import time
import tqdm
import torch
from typing import OrderedDict
def train(loader, model, epoch, criterion, optimizer, threshold, class_weights=None, use_cuda=None):
"""
:param loader:
:param model:
:param epoch:
:param criterion:
:param optimizer:
:param threshold:
:param class_w... | 5cac64cc77d67ae6b4504f86c6cc101eda696105 | 51,390 |
def memoize(timeout=None, fast=False):
"""
Cache a function based on its arguments.
Args:
timeout: Time the result stays valid in the cache.
Returns:
The functions result.
"""
assert (not fast or (fast and timeout is not None)
), "You cannot set fast cache without a ... | dd290a19b675c25327668215e583b5b30f077a18 | 51,391 |
def get_appliance_bgp_neighbors(
self,
ne_id: str,
) -> dict:
"""Returns appliance BGP neighbor configuration
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - bgp
- GET
- /bgp/config/neighbor/{neId}
:param ... | f8e777f9e9fabbdb9610ce0bf5f0824b888a9e04 | 51,392 |
def pages_sub_menu(context, page, url='/'):
"""Get the root page of the given page and
render a nested list of all root's children pages.
Good for rendering a secondary menu.
:param page: the page where to start the menu from.
:param url: not used anymore.
"""
lang = context.get('lang', pag... | f718d6513da8f05683a7b85e2bebcdc359487616 | 51,393 |
def JsonToMessage(message_type, message):
"""Convert the given JSON to a message of type message_type."""
return _ProtoJsonApiTools.Get().decode_message(message_type, message) | b642c5160e6c06ff60daffedbb4d665b8005b711 | 51,394 |
import torch
def generate_angular_spectrum_kernel(shape, pixel_size, wavelength, \
numerical_aperture=None, flag_band_limited=True, \
dtype=torch.float32, device=torch.device('cuda')):
"""
Function that generates angular spectrum propa... | b07e54f087b8271ef27f88497717ed96ae3136a2 | 51,395 |
from typing import List
def getBarcodesFromSnap(fname: str) -> List[str]:
"""Read barcodes from a snap file
Attributes:
fname - a snap-format file
Return:
a dictionary contains all barcode in the snap file
"""
with h5py.File(fname, "r") as f:
barcodes: List[str] = [item.d... | 4fb9821e3184886688c795429742bf123aed49f8 | 51,396 |
def slicing_where(condition, full_input, true_branch, false_branch):
"""Split 'full_input' between 'true_branch' and 'false_branch' on 'condition'.
Args:
condition: A boolean Tensor with shape [B_1, ..., B_N].
full_input: A Tensor or nested tuple of Tensors of any dtype, each with
shape [B_1, ..., B_... | 8d1faf5c2b1b3f9ddc9e3a27529ef06de740551c | 51,397 |
def radiation_pressure_length_noise(
ff,
Pin,
finesse,
mass=2.92,
lam=1064e-9,
):
"""Radiation pressure length noise for a single optic in a cavity in units of m/rtHz.
Inputs:
-------
ff: float
audio frequency in Hz
Pin: float
cavity input power in watts
fines... | 1be70f39ac1739acf430ec9980a3ddbd645ff8aa | 51,398 |
def snic_distance_mod(pos_i, pos_j, col_i, col_j, si, mi):
"""
Computes the SNIC pixel distance
None of the components can be negative -> omitting the root does not change item order
:param pos_i: position of pixel i
:param pos_j: position of pixel j
:param col_i: color of pixel i
:param col... | 0d083e9f28bd36f0fc38e149371ad033b4bf54e5 | 51,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.