content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def batch_process_image_to_spots(dax_filename, sel_channels,
save_filename,
data_type, region_ids,
ref_filename,
load_file_lock=None,
warp_image=True, ... | 5,348,500 |
def upload(target='local'):
""" Release to a given pypi server ('local' by default). """
sysmsg("Uploading to pypi server \033[33m{}".format(target))
local('python setup.py sdist register -r "{}"'.format(target))
local('python setup.py sdist upload -r "{}"'.format(target)) | 5,348,501 |
def timer(jarvis, s):
"""
Set a timer
R Reset
SPACE Pause
Q Quit
Usages:
timer 10
timer 1h5m30s
"""
k = s.split(' ', 1)
if k[0] == '':
jarvis.say("Please specify duration")
return
timer_cmd = "python -m termdown " + k[0]
system(timer_c... | 5,348,502 |
def inner_xml(xml_text):
"""
Get the inner xml of an element.
>>> inner_xml('<div>This is some <i><b>really</b> silly</i> text!</div>')
u'This is some <i><b>really</b> silly</i> text!'
"""
return unicode(INNER_XML_RE.match(xml_text).groupdict()['body']) | 5,348,503 |
def store_tags():
"""Routing: Stores the (updated) tag data for the image."""
data = {
"id": request.form.get("id"),
"tag": request.form.get('tags'),
"SHOWN": 0
}
loader.store(data)
next_image = loader.next_data()
if next_image is None:
return redirect("/finished... | 5,348,504 |
def getAssets(public_key: str) -> list:
"""
Get all the balances an account has.
"""
balances = server.accounts().account_id(public_key).call()['balances']
balances_to_return = [ {"asset_code": elem.get("asset_code"), "issuer": elem.get("asset_issuer"), "balance": elem.get("balance")} for elem in ba... | 5,348,505 |
def parse_pattern(format_string, env, wrapper=lambda x, y: y):
""" Parse the format_string and return prepared data according to the env.
Pick each field found in the format_string from the env(ironment), apply
the wrapper on each data and return a mapping between field-to-replace and
values for each.
... | 5,348,506 |
def test_minimize_score_with_worsened_symptom(integration_db):
"""
Minimize ingredients contained in Recipe[0] are:
saury fish: 10 (ref. 10)
cabbage: 200 (ref. 30|200 )
fish: 30 (ref: 20 )
this time the formula would be:
saury-fish (ignored) - (60 * 1.5) - (30 * 1.5)
"""
fro... | 5,348,507 |
def u1_series_summation(xarg, a, kmax):
"""
5.3.2 ROUTINE - U1 Series Summation
PLATE 5-10 (p32)
:param xarg:
:param a:
:param kmax:
:return: u1
"""
du1 = 0.25*xarg
u1 = du1
f7 = -a*du1**2
k = 3
while k < kmax:
du1 = f7*du1 / (k*(k-1))
... | 5,348,508 |
def mask_iou(masks_a, masks_b, iscrowd=False):
"""
Computes the pariwise mask IoU between two sets of masks of size [a, h, w] and [b, h, w].
The output is of size [a, b].
Wait I thought this was "box_utils", why am I putting this in here?
"""
masks_a = masks_a.view(masks_a.size(0), -1)
mas... | 5,348,509 |
def async_worker_handler(event: Dict[str, Any], _: Any):
"""Process the tickets"""
_logger.info(event)
job_id = event.get('job_id')
try:
db_table.get(job_id)
tickets = inventory_parser.from_tsv(storage.get(job_id))
total_value = sum([ticket.value for ticket in tickets])
d... | 5,348,510 |
def normalized_grid_coords(height, width, aspect=True, device="cuda"):
"""Return the normalized [-1, 1] grid coordinates given height and width.
Args:
height (int) : height of the grid.
width (int) : width of the grid.
aspect (bool) : if True, use the aspect ratio to scale the coordinat... | 5,348,511 |
def test_copy_object_modified_since(log_entry):
"""Test copy_object() with modified since condition."""
# Get a unique bucket_name and object_name
bucket_name = _gen_bucket_name()
object_name = "{0}".format(uuid4())
object_source = object_name + "-source"
object_copy = object_name + "-copy"
... | 5,348,512 |
def _verify_env_variables():
"""
Verifies that required env variable(s) exist and valid.
:return: None
"""
if os.getenv('remote_repo_path') is None and os.getenv('local_repo_path') is None:
complain('One of: remote_repo_path or local_repo_path is required. Aborting.')
if os.getenv('acti... | 5,348,513 |
def ray_map(task: Task, *item_lists: Iterable[List[Any]], log_dir: Optional[Path] = None) -> List[Any]:
"""
Initialize ray, align item lists and map each item of a list of arguments to a callable and executes in parallel.
:param task: callable to be run
:param item_lists: items to be parallelized
:p... | 5,348,514 |
def consensus_kmeans(data=None,
k=0,
linkage='average',
nensemble=100,
kmin=None,
kmax=None):
"""Perform clustering based on an ensemble of k-means partitions.
Parameters
----------
data : array
... | 5,348,515 |
def save_api_dataset(process_df, raw_df, path, query_type, param_class,
data_period):
"""Save processed datasets at regular monthly intervals.
Args:
process_df (pandas DataFrame):
An SDFS formatted dataset for query data returned by the API
service.
... | 5,348,516 |
def to_cftime(date, calendar="gregorian"):
"""Convert datetime object to cftime object.
Parameters
----------
date : datetime object
Datetime object.
calendar : str
Calendar of the cftime object.
Returns
-------
cftime : cftime object
Cftime ojbect.
"""
... | 5,348,517 |
def _test_cross_zernikes(testj=4, nterms=10, npix=500):
"""Verify the functions are orthogonal, by taking the
integrals of a given Zernike times N other ones.
Parameters :
--------------
testj : int
Index of the Zernike polynomial to test against the others
nterms : int
Test tha... | 5,348,518 |
def poly_to_mask(mask_shape, vertices):
"""Converts a polygon to a boolean mask with `True` for points
lying inside the shape. Uses the bounding box of the vertices to reduce
computation time.
Parameters
----------
mask_shape : np.ndarray | tuple
1x2 array of shape of mask to be generat... | 5,348,519 |
def get_nn_edges(
basis_vectors,
extent,
site_offsets,
pbc,
distance_atol,
order,
):
"""For :code:`order == k`, generates all edges between up to :math:`k`-nearest
neighbor sites (measured by their Euclidean distance). Edges are colored by length
with colors between 0 and `order - 1`... | 5,348,520 |
def expand(vevent, default_tz, href=''):
"""
:param vevent: vevent to be expanded
:type vevent: icalendar.cal.Event
:param default_tz: the default timezone used when we (icalendar)
don't understand the embedded timezone
:type default_tz: pytz.timezone
:param href: the hre... | 5,348,521 |
def fsapi(session, stream, env, args):
"""Handle FS API requests.
Args:
string of the form <imsi>|<True if for dest_imsi (default is False)>
Subscriber State can be:
active (unblocked), -active (blocked),first_expired (validity expired)
"""
args = args.split('|')
imsi = args[0]
d... | 5,348,522 |
def setup_transition_list():
"""
Creates and returns a list of Transition() objects to represent state
transitions for a biased random walk, in which the rate of downward
motion is greater than the rate in the other three directions.
Parameters
----------
(none)
Returns
---... | 5,348,523 |
def unit_vector(data, axis=None, out=None):
"""Return ndarray normalized by length, i.e. eucledian norm, along axis.
>>> v0 = numpy.random.random(3)
>>> v1 = unit_vector(v0)
>>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0))
True
>>> v0 = numpy.random.rand(5, 4, 3)
>>> v1 = unit_vector(v0, a... | 5,348,524 |
def negative_f1_score(probs, labels):
"""
Computes the f1 score between output and labels for k classes.
args:
probs (tensor) (size, k)
labels (tensor) (size, 1)
"""
probs = torch.nn.functional.softmax(probs, dim=1)
probs = probs.numpy()
labels = labels.numpy()
... | 5,348,525 |
def validate_dataset_path(value):
"""Validates the path for input dataset"""
try:
storage_type = get_storage_type(value)
if storage_type == 'local':
dataset_path = Path(value)
if not dataset_path.is_dir():
raise Exception("Directory doesn't exist")
exc... | 5,348,526 |
def search_usb_devices_facets():
"""Facet USB Devices"""
data = {"terms": {"fields": ["status"]}}
usb_url = USB_DEVICES_FACETS.format(HOSTNAME, ORG_KEY)
return requests.post(usb_url, json=data, headers=HEADERS) | 5,348,527 |
def __casestudy_gen(
ctx: click.Context, project: str, override: bool, version: int,
ignore_blocked: bool, merge_stage: tp.Optional[str], new_stage: bool,
update: bool
) -> None:
"""Generate or extend a CaseStudy Sub commands can be chained to for example
sample revisions but also add the latest."""... | 5,348,528 |
def test_coord_init_representation():
"""
Spherical or Cartesian represenation input coordinates.
"""
coord = SphericalRepresentation(lon=8 * u.deg, lat=5 * u.deg, distance=1 * u.kpc)
sc = SkyCoord(coord, frame='icrs')
assert allclose(sc.ra, coord.lon)
assert allclose(sc.dec, coord.lat)
... | 5,348,529 |
def chunked(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i+n] | 5,348,530 |
def debug(*args):
""" Handy for figuring out what's going on in a template. Usage: {% debug "print" some_var "stuff" %}. """
print(*args) | 5,348,531 |
def pack4(v):
"""
Takes a 32 bit integer and returns a 4 byte string representing the
number in little endian.
"""
assert 0 <= v <= 0xffffffff
# The < is for little endian, the I is for a 4 byte unsigned int.
# See https://docs.python.org/2/library/struct.html for more info.
return struc... | 5,348,532 |
def index():
"""
"""
category = Category.get_categories()
pitch = Pitch.get_all_pitches()
title = "Welcome to Pitch Hub"
return render_template('index.html', title = title, category = category, pitch =pitch) | 5,348,533 |
def maximum_sum_increasing_subsequence(numbers, size):
"""
Given an array of n positive integers. Write a program to find the sum of
maximum sum subsequence of the given array such that the integers in the
subsequence are sorted in increasing order.
"""
results = [numbers[i] for i in range(size... | 5,348,534 |
def lstsqb(a, b):
"""
Return least-squares solution to a = bx.
Similar to MATLAB / operator for rectangular matrices.
If b is invertible then the solution is la.solve(a, b).T
"""
return la.lstsq(b.T, a.T, rcond=None)[0].T | 5,348,535 |
def test_subset_4D_data_all_argument_permutations(load_esgf_test_data, tmpdir):
"""Tests clisops subset function with:
- no args (collection only)
- time only
- level only
- bbox only
- time + level
- time + bbox
- level + bbox
- time + level + bbox
On completion:
- Check th... | 5,348,536 |
def multivariateGaussian(X, mu, sigma2):
"""
多元高斯分布
:param X:
:param mu:
:param sigma2:
:return:
"""
k = len(mu)
if sigma2.shape[0] > 1:
sigma2 = np.diag(sigma2)
X = X - mu
argu = (2 * np.pi) ** (-k / 2) * np.linalg.det(sigma2) ** (-0.5)
p = argu * np.exp(-0.5 * n... | 5,348,537 |
def test_open_notebook_in_non_ascii_dir(notebook, qtbot, tmpdir):
"""Test that a notebook can be opened from a non-ascii directory."""
# Move the test file to non-ascii directory
test_notebook = osp.join(LOCATION, 'test.ipynb')
test_notebook_non_ascii = osp.join(str(tmpdir), u'äöüß', 'test.ipynb')
o... | 5,348,538 |
def get_day(input):
"""
Convert input to a datetime object and extract the Day part
"""
if isinstance(input, str):
input = parse_iso(input)
if isinstance(input, (datetime.date, datetime.datetime)):
return input.day
return None | 5,348,539 |
def run():
"""Create Conan promote instance and run
Collect user arguments as
"""
promote = ConanPromote()
promote.run(sys.argv[1:]) | 5,348,540 |
def update_organization(instance, language):
"""
Update Elasticsearch indices when an organization was modified and published:
- update the organization document in the Elasticsearch organizations index for the
organization and its direct parent (because the parent ID may change from Parent to Leaf),
... | 5,348,541 |
def read_ds(tier, pos_source=None):
"""
Like read_pt above, given a DS tier, return the DepTree object
:param tier:
:type tier: RGTier
"""
# First, assert that the type we're looking at is correct.
assert tier.type == DS_TIER_TYPE
# --1) Root the tree.
root = DepTree.root()
#... | 5,348,542 |
def get_local_ontology_from_file(ontology_file):
""" return ontology class from a local OWL file """
return ow.get_ontology("file://" + ontology_file).load() | 5,348,543 |
def get_wolframalpha_imagetag(searchterm):
""" Used to get the first image tag from the Wolfram Alpha API. The return value is a dictionary
with keys that can go directly into html.
Takes in:
searchterm: the term to search with in the Wolfram Alpha API
"""
base_url = 'http://api.wolframa... | 5,348,544 |
def get_synset_definitions(word):
"""Return all possible definitions for synsets in a word synset ring.
:param word (str): The word to lookup.
:rtype definitions (list): The synset definitions list.
"""
definitions = []
synsets = get_word_synsets(word)
for _synset in synsets:
defini... | 5,348,545 |
def test_edit_write_with_modifications_two_colision():
""" two modifications with same position """
reader = StringIO("{}")
writer = StringIO()
mods = Modifications()
mods.add(0,2, "XX")
mods.add(0,2, "YY")
write_with_modifications(reader, mods, writer)
writer.seek(0)
ret = writer.r... | 5,348,546 |
def getResourceDefUsingSession(url, session, resourceName, sensitiveOptions=False):
"""
get the resource definition - given a resource name (and catalog url)
catalog url should stop at port (e.g. not have ldmadmin, ldmcatalog etc...
or have v2 anywhere
since we are using v1 api's
returns rc=200... | 5,348,547 |
def _merge_sse(sum1, sum2):
"""Merge the partial SSE."""
sum_count = sum1 + sum2
return sum_count | 5,348,548 |
def earliest_deadline_first(evs, iface):
""" Sort EVs by departure time in increasing order.
Args:
evs (List[EV]): List of EVs to be sorted.
iface (Interface): Interface object. (not used in this case)
Returns:
List[EV]: List of EVs sorted by departure time in increasing order.
... | 5,348,549 |
def auto_load(filename):
"""Load any supported raw battery cycler file to the correct Datapath automatically.
Matches raw file patterns to the correct datapath and returns the datapath object.
Example:
auto_load("2017-05-09_test-TC-contact_CH33.csv")
>>> <ArbinDatapath object>
au... | 5,348,550 |
def set_stream_color(stream, disabled):
"""
Remember what our original streams were so that we
can colorize them separately, which colorama doesn't
seem to natively support.
"""
original_stdout = sys.stdout
original_stderr = sys.stderr
init(strip=disabled)
if stream != original_std... | 5,348,551 |
def show_scatter_plot(selected_species_df: pd.DataFrame):
"""
根据选择的某个类别的两个特征画出散点图
"""
st.subheader("Scatter plot")
feature_x = st.selectbox("Which feature on x?", selected_species_df.columns[0:4])
feature_y = st.selectbox("Which feature on y?", selected_species_df.columns[0:4])
fig = px.scat... | 5,348,552 |
def print_param_list(param_list, result, decimal_place=2, unit=''):
"""
Return a result string with parameter data appended. The input `param_list` is a list of a tuple
(param_value, param_name), where `param_value` is a float and `param_name` is a string. If `param_value`
is None, it writes 'N/A'.
... | 5,348,553 |
def test_comments_should_never_be_moved_between_imports_issue_1427():
"""isort should never move comments to different import statement.
See: https://github.com/PyCQA/isort/issues/1427
"""
assert isort.check_code(
"""from package import CONSTANT
from package import * # noqa
""",
... | 5,348,554 |
def get_veh_id(gb_data):
"""
Mapping function for vehicle id
"""
veh_ref = gb_data['Vehicle_Reference']
acc_id = get_acc_id_from_data(gb_data)
veh_id = common.get_gb_veh_id(acc_id, int(veh_ref))
return veh_id | 5,348,555 |
def linreg_qr_gramschmidt_unencrypted(clientMap, coordinator, encryLv=3, colTrunc=False):
"""
Compute vertical federated linear regression using QR.
QR decomposition is computed by means of Numpy/Scipy builtin algorithm and Gram-Schmidt method.
Parameters
----------
clientMap : List
The... | 5,348,556 |
def register_classes():
"""Register these classes with the `LinkFactory` """
AnalyzeExtension.register_class()
AnalyzeExtension_SG.register_class() | 5,348,557 |
def has_soa_perm(user_level, obj, ctnr, action):
"""
Permissions for SOAs
SOAs are global, related to domains and reverse domains
"""
return {
'cyder_admin': True, #?
'ctnr_admin': action == 'view',
'user': action == 'view',
'guest': action == 'view',
}.get(user_l... | 5,348,558 |
def _move(file, folder, new_name, rel, renamer):
"""Simply rename a file (full path) in a directory (folder)."""
os.rename(file, os.path.join(folder, new_name))
renamer.names[new_name] = rel | 5,348,559 |
def Count_Tiles(colour_pattern,palette):
"""Count the number of tiles used in each shape and colour.
A report is printed to the console.
"""
mask = np.isnan(colour_pattern[8][0])
shapes_used = np.floor(colour_pattern[8][0][~mask])
colours_used = colour_pattern[8][2][~mask]
... | 5,348,560 |
def GetMaxImageMemory():
""" """
pass | 5,348,561 |
def parse_test(project, path):
"""Compares the dynamic graph to the parsed one."""
inputs, outputs, built_by, graph = parse_graph(project.graph)
fuzzed = sorted([f for f in inputs - outputs if project.filter_in(f)])
count = len(fuzzed)
root = project.buildPath
G = defaultdict(list)
with open(path, 'r'... | 5,348,562 |
def upload_artifact(args: Any, file_path: str, org_id: Any = None) -> Dict[str, Any]:
"""
Upload artifact using Pyxis API
Args:
args (Any): CLI arguments
file_path (str): Path to a artifact file
org_id (Any): organization ID - optional
Returns:
Dict[str, Any]: Pyxis res... | 5,348,563 |
def balance_command(chat, message, args):
"""Show your token balance"""
try:
# push txn
asyncio.get_event_loop().run_until_complete(balance(chat.id, chat))
except EosRpcException as e:
e = str(e).replace("\'", "\"")
code_idx = e.find('code')
code_val = int(e[code_idx+7:(code_idx+14)])
# print(... | 5,348,564 |
def show_absolute(signal, kind, unshuffled=False, unshuffle=False, map_backward=None, vmin=-4, vmax=4):
"""
Plot the absolute values of the given signal matrix.
Parameters
----------
signal : numpy.ndarray, shape=(n_samples, n_features)
True signal matrix.
kind : str, values=('Bias', 'S... | 5,348,565 |
def main(base_dir,
out_dir,
use_interpenetration=True,
n_betas=10,
flength=5000.,
pix_thsh=25.,
use_neutral=False,
viz=True):
"""Set up paths to image and joint data, saves results.
:param base_dir: folder containing LSP images and data
:param o... | 5,348,566 |
def check_skyscrapers(input_path: str) -> bool:
"""
Main function to check the status of skyscraper game board.
Return True if the board status is compliant with the rules,
False otherwise.
"""
board = read_input(input_path)
return check_not_finished_board(board) and check_uniqueness_in_rows... | 5,348,567 |
def test_invalid_tri():
"""Invalid triangle yields false"""
check50.run("./is_valid_tri").stdin("4").stdin("2").stdin("7").stdout("false\n", "false\n").exit(0) | 5,348,568 |
def test_pidfile_is_absolute_path():
"""Test that the pidfile is converted to an absolute path."""
pidfile = "~/test.pid"
user = getpass.getuser()
m = simple.SimplePidManager(pidfile=pidfile)
assert "~" not in m.pidfile
assert m.pidfile == "{0}/test.pid".format(os.path.expanduser("~"))
asser... | 5,348,569 |
async def get_station(station: avwx.Station, token: Optional[Token]) -> dict:
"""Log and returns station data as dict"""
await app.station.add(station.lookup_code, "station")
return await station_data_for(station, token=token) or {} | 5,348,570 |
def add_check_numerics_ops():
"""Connect a `check_numerics` to every floating point tensor.
`check_numerics` operations themselves are added for each `half`, `float`,
or `double` tensor in the graph. For all ops in the graph, the
`check_numerics` op for all of its (`half`, `float`, or `double`) inputs
is gua... | 5,348,571 |
def get_text(part):
"""Gmailの本文をdecode"""
if not part['filename'] and \
part['body']['size'] > 0 and \
'data' in part['body'].keys():
content_type = header(part['headers'], 'Content-Type')
encode_type = header(part['headers'], 'Content-Transfer-Encoding')
data = decod... | 5,348,572 |
def clear():
"""
Clear PlaceOrder screen variables and assign new values.
"""
global price_thread1, price_thread2, price_thread3, price_thread4,\
lsize_thread1, lsize_thread2, lsize_thread3, lsize_thread4
ls.set(-1)
cp.set(-1)
st1.set(0)
st2.set(0)
st3.set(0)
st4.set(0)
... | 5,348,573 |
def serve_forever(host, port):
"""
Start mail services.
:param host: Host
:param port: Port
"""
print("Starting mail-in/out on {}:{}".format(host, port))
inbox.serve(address=host, port=port) | 5,348,574 |
def test_create_run_action_with_missing_id(
decoy: Decoy,
run_store: RunStore,
unique_id: str,
current_time: datetime,
client: TestClient,
) -> None:
"""It should 404 if the run ID does not exist."""
not_found_error = RunNotFoundError(run_id="run-id")
decoy.when(run_store.get(run_id="ru... | 5,348,575 |
def run(ex: "interactivity.Execution"):
"""Specify the target function(s) and/or layer(s) to target."""
selection: "definitions.Selection" = ex.shell.selection
is_exact = ex.args.get("exact", False)
functions = ex.args.get("functions", False)
layers = ex.args.get("layers", False)
both = not func... | 5,348,576 |
def main():
"""Shows basic usage of the Apps Script API.
Creates a Apps Script API service object and uses it to call an
Apps Script function to print out a list of folders in the user's root
directory.
"""
SCRIPT_ID = 'ENTER_YOUR_SCRIPT_ID_HERE'
# Authorize and create a service object.
... | 5,348,577 |
def get_mixture_mse_accuracy(output_dim, num_mixes):
"""Construct an MSE accuracy function for the MDN layer
that takes one sample and compares to the true value."""
# Construct a loss function with the right number of mixtures and outputs
def mse_func(y_true, y_pred):
# Reshape inputs in case t... | 5,348,578 |
def ByName(breakdown_metric_name):
"""Return a BreakdownMetric class by name."""
breakdown_mapping = {
'distance': ByDistance,
'num_points': ByNumPoints,
'rotation': ByRotation,
'difficulty': ByDifficulty
}
if breakdown_metric_name not in breakdown_mapping:
raise ValueError('Invalid ... | 5,348,579 |
def test_ap_wpa_psk_ext_eapol(dev, apdev):
"""WPA2-PSK AP using external EAPOL supplicant"""
(bssid,ssid,hapd,snonce,pmk,addr,wpae) = eapol_test(apdev[0], dev[0],
wpa2=False)
msg = recv_eapol(hapd)
anonce = msg['rsn_key_nonce']
logger.info("Re... | 5,348,580 |
def deserialize_structure(serialized_structure, dtype=np.int32):
"""Converts a string to a structure.
Args:
serialized_structure: A structure produced by `serialize_structure`.
dtype: The data type of the output numpy array.
Returns:
A numpy array with `dtype`.
"""
return np.asarray(
[toke... | 5,348,581 |
def get_all_text_elements(dataset_name: str) -> List[TextElement]:
"""
get all the text elements of the given dataset
:param dataset_name:
"""
return data_access.get_all_text_elements(dataset_name=dataset_name) | 5,348,582 |
def form_x(form_file,*args):
"""
same as above, except assumes all tags in the form are number, and uses the additional arguments in *args to fill out those tag values.
:param form_file: file which we use for replacements
:param *args: optional arguments which contain the form entries for the file in question, by n... | 5,348,583 |
def init():
"""Manage IAM users."""
formatter = cli.make_formatter('aws_user')
@click.group()
def user():
"""Manage IAM users."""
pass
@user.command()
@click.option('--create',
is_flag=True,
default=False,
help='Create if i... | 5,348,584 |
def fix_units(dims):
"""Fill in missing units."""
default = [d.get("units") for d in dims][-1]
for dim in dims:
dim["units"] = dim.get("units", default)
return dims | 5,348,585 |
def annotate_movement(raw, pos, rotation_velocity_limit=None,
translation_velocity_limit=None,
mean_distance_limit=None, use_dev_head_trans='average'):
"""Detect segments with movement.
Detects segments periods further from rotation_velocity_limit,
translation_ve... | 5,348,586 |
def set_weight_send_next(request, responder):
"""
When the user provides their weight, save the answer and move to the next question.
"""
process_answer_with_entity(request, responder, pd.Q_WEIGHT) | 5,348,587 |
def run_in_executor(
func: F,
executor: ThreadPoolExecutor = None,
args: Any = (),
kwargs: Any = MappingProxyType({}),
) -> Future:
"""将耗时函数加入到线程池 ."""
loop = get_event_loop()
# noinspection PyTypeChecker
return loop.run_in_executor( # type: ignore
executor, context_partial(func... | 5,348,588 |
def validate_params(canvas_size, border_width):
"""validate_params(canvas_size, border_width) -> None
Assert that canvas and border size are both non-negative ints,
canvas size is not zero, and canvas size is larger than border"""
assert_is_int('size', canvas_size)
assert_is_int('border', border_width)
if canva... | 5,348,589 |
def reset_slave(server):
"""Function: reset_slave
Description: Clear replication configuration in a slave.
Arguments:
(input) server -> Server instance.
"""
# Semantic change in MySQL 8.0.22
slave = "replica" if server.version >= (8, 0, 22) else "slave"
server.cmd_sql("reset ... | 5,348,590 |
def find_entry_with_minimal_scale_at_prime(self, p):
"""
Finds the entry of the quadratic form with minimal scale at the
prime p, preferring diagonal entries in case of a tie. (I.e. If
we write the quadratic form as a symmetric matrix M, then this
entry M[i,j] has the minimal valuation at the prim... | 5,348,591 |
def _gcs_get(url: str, temp_filename: str) -> None:
"""Pull a file directly from GCS."""
blob = _get_gcs_blob(url)
blob.download_to_filename(temp_filename) | 5,348,592 |
def from_arrow(array, highlevel=True, behavior=None):
"""
Args:
array (`pyarrow.Array`, `pyarrow.ChunkedArray`, `pyarrow.RecordBatch`,
or `pyarrow.Table`): Apache Arrow array to convert into an
Awkward Array.
highlevel (bool): If True, return an #ak.Array; otherwise, retu... | 5,348,593 |
def _basis_search(equiv_lib, source_basis, target_basis, heuristic):
"""Search for a set of transformations from source_basis to target_basis.
Args:
equiv_lib (EquivalenceLibrary): Source of valid translations
source_basis (Set[Tuple[gate_name: str, gate_num_qubits: int]]): Starting basis.
... | 5,348,594 |
def Get_EstimatedRedshifts( scenario={} ):
""" obtain estimated source redshifts written to npy file """
return np.genfromtxt( FilenameEstimatedRedshift( scenario ), dtype=None, delimiter=',', names=True, encoding='UTF-8') | 5,348,595 |
def request_init(c, options, server, request, task):
"""`RequestManager` callback to initialise URL of the connection."""
print server + urllib.quote(request)
c.setopt(pycurl.URL, server + urllib.quote(request)) | 5,348,596 |
def get_national_museums(db_connection, export_to_csv, export_path):
"""
Get national museum data from DB
"""
df = pd.read_sql('select * from optourism.state_national_museum_visits', con=db_connection)
if export_to_csv:
df.to_csv(f"{export_path}_nationalmuseums_raw.csv", index=False)
... | 5,348,597 |
def new_database(uri):
"""Drop the database at ``uri`` and create a brand new one."""
destroy_database(uri)
create_database(uri) | 5,348,598 |
def hrm_configure_pr_group_membership():
"""
Configures the labels and CRUD Strings of pr_group_membership
"""
T = current.T
s3db = current.s3db
settings = current.deployment_settings
request = current.request
function = request.function
table = s3db.pr_group_membership
if ... | 5,348,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.