content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import copy
import collections
def get_db_data(relation_data, unprefixed):
"""Organize database requests into a collections.OrderedDict
:param relation_data: shared-db relation data
:type relation_data: dict
:param unprefixed: Prefix to use for requests without a prefix. This should
... | 0e2a30624f35f49119ae9bd275153d5e9fdf7503 | 53,600 |
def KleinBottle():
"""
A minimal triangulation of the Klein bottle, as presented for example
in Davide Cervone's thesis [Cer1994]_.
EXAMPLES::
sage: simplicial_complexes.KleinBottle()
Minimal triangulation of the Klein bottle
"""
return UniqueSimplicialComplex([[2, 3, 7], [1, 2... | 37f00c16500b7cefe5f9c645d8a0d0aa986ab487 | 53,601 |
def speech_to_text(file_name, model_id):
"""Use Watson Speech to Text to convert audio file to text."""
# create Watson Speech to Text client
stt = SpeechToTextV1(iam_apikey=keys.speech_to_text_key)
# open the audio file
with open(file_name, 'rb') as audio_file:
# pass the file to Watson ... | d3e214e97c4d530a78ac9d2353ea38b3c70f5fdf | 53,602 |
def auth_connection(connection) -> openeo.Connection:
"""Connection fixture to a backend of given version with some image collections."""
connection.authenticate_basic(TEST_USER, TEST_PASSWORD)
return connection | 77638e524d014ddcdd75b6d3e40233b1175101f1 | 53,603 |
def convert(tree,fileName=None):
"""
Converts input files to be compatible with merge request #412, where we switch from custom
XML pathing to standard XPATH nomenclature.
@ In, tree, xml.etree.ElementTree.ElementTree object, the contents of a RAVEN input file
@ In, fileName, the name for the raven in... | 841f491370dc07d77f9af5428d78486136220ce9 | 53,604 |
import logging
def merge_object_masks(list_masks, thr_overlap=0.7):
""" merge several mask into one multi-class segmentation
:param [ndarray] list_masks:
:param float thr_overlap:
:return ndarray:
>>> m1 = np.zeros((5, 6), dtype=int)
>>> m1[:4, :4] = 1
>>> m2 = np.zeros((5, 6), dtype=int... | d67ae35083ea0ed126c0871d44449c72cda040b7 | 53,605 |
def s3_lazy_put(filename, assume_immutable=False):
"""Put file to s3 only if out of sync."""
key = BUCKET.get_key(filename)
if key is None:
key = BUCKET.new_key(filename)
print 'uploading', filename
key.set_contents_from_filename(filename)
return key
elif assume_immutable... | b92c42194776d6f45e600716fb547109d5f87927 | 53,606 |
def moments(Xax, data, vheight=True, estimator=np.mean, negamp=None,
veryverbose=False, nsigcut=None, noise_estimate=None, **kwargs):
"""
Returns the gaussian parameters of a 1D distribution by calculating its
moments. Depending on the input parameters, will only output a subset of
the abo... | 63daf8eef8e2e24d97b8440ab81aa8aa21860002 | 53,607 |
def preprocess_adj(adj):
"""Preprocessing of adjacency matrix for simple GCN model"""
return normalize_adj(adj + sps.eye(adj.shape[0])).astype(np.float32) | fad916c7247ea1057450a78b17a2c8556719e35a | 53,608 |
from apysc._callable import callable_util
from apysc._event import handler_circular_calling_util as circ_util
from apysc._validation.variable_name_validation import \
def get_handler_name(
*, handler: _Handler, instance: Any) -> str:
"""
Get a handler name.
Parameters
----------
handler :... | 3b3051f2a79b4ecdcf7f5b5b362fdc6b3f2cf6ea | 53,609 |
def do_lookup(get_locations_func):
"""
Generic method which gets the locations in [(lat,lng),(lat,lng),...] format by calling get_locations_func
and returns an answer ready to go to the client.
:return:
"""
try:
locations = get_locations_func()
return {'results': [get_elevation(... | cd04851722836e37a5112428be26fa2f31ece1de | 53,610 |
def get_parameter_for_dev_mode(dev_mode_setting):
"""Return parameter for whether the test should be running on dev_mode.
Args:
dev_mode_setting: bool. Whether the test is running on dev_mode.
Returns:
str. A string for the testing mode command line parameter.
"""
return '--params.... | 502d8b070d441508c8c2e90700cdb807423d1e13 | 53,611 |
import re
def load_MDU(mdu):
"""parse MDU and store parameter key/values in dictionary
:function: TODO
:returns: TODO
"""
params = {}
key_value = re.compile("(.*)=(.*)#.*")
with open(mdu, "r") as f:
lines = f.readlines()
for line in lines:
match = key_value... | 0d693a6b4cb91b65dcb68324daec6835802e305d | 53,612 |
def get_username(prompt: str) -> str:
"""Prompt the user for a username"""
username = input(prompt)
return username | c6d6119ba9b2b1ec9408501afb04b513aa9b4965 | 53,613 |
import os
import pickle
def load_tracking_params(base, ext, names = None, init_fname = None):
"""Loads parameters from file
If file doesn't exist, returns empty dictionary
Parameters
--------------
base : str
relative path to file
ext : str
file extension, must be eit... | 1aa0f6020bc02a56f02a65de8efef7f84f2ca790 | 53,614 |
def preprocess(x, y, nb_classes=10, clip_values=None):
"""Scales `x` to [0, 1] and converts `y` to class categorical confidences.
:param x: Data instances.
:type x: `np.ndarray`
:param y: Labels.
:type y: `np.ndarray`
:param nb_classes: Number of classes in dataset.
:type nb_classes: `int`
... | ed3abcec3cede4f97d1693f67653d3c57b7e5413 | 53,615 |
def mkatas(u_t, v_t, wap, t_t, ttt, g_w, p_l, lat, nlat, ntp, nlev):
"""Compute the stat.-trans. eddy APE conversions from u, v, wap and t.
Arguments:
- u_t: a 3D zonal velocity field;
- v_t: a 3D meridional velocity field;
- wap: a 3D vertical velocity field;
- t_t: a 3D temperature field;
... | 5656377647c143124c0c85d3b920393e2640cbed | 53,616 |
def fourier_model(cn, Nfreqs):
"""
Calculate a 1D (complex) Fourier series model from a set of complex coefficients.
Parameters
----------
coeffs : array_like
Array of complex Fourier coefficients, ordered from (-n, n), where n is
the highest harmonic mode in the model.
Nfreqs ... | 77c5dcad9535ab1e673bde66446081f23c329377 | 53,617 |
def remove_low_information_features(feature_matrix, features=None):
"""Select features that have at least 2 unique values and that are not all null
Args:
feature_matrix (:class:`pd.DataFrame`): DataFrame whose columns are feature names and rows are instances
features (list[:class:`f... | 0377b2b87d04ddaa89e332ed72c12a05b4a1c3e6 | 53,618 |
def latlt2cart(lat,lt,hemisphere):
"""
Latitude and local time to cartesian for a top-down dialplot
"""
r,theta = latlt2polar(lat,lt,hemisphere)
return r*cos(theta),r*sin(theta) | e295fd58fb57069229cb20a15d02b8a2d591d1d1 | 53,619 |
import hashlib
def md5_password(password, salt):
"""获取原始密码+salt的md5值
"""
trans_str = password + salt
md = hashlib.md5()
md.update(trans_str.encode('utf-8'))
return md.hexdigest() | cbb4306bfa1e11957a56d5ace5d810ac421f5d83 | 53,620 |
import math
def build_belief(belief_type: Belief, num_agents=NUM_AGENTS, **kwargs):
"""Evenly distributes the agents beliefs into subgroups.
"""
if belief_type is Belief.MILD:
middle = math.ceil(num_agents / 2)
return [0.2 + 0.2 * i / middle if i < middle else 0.6 + 0.2 * (i - middle)... | e83ca205cf528e3ed1400892077172dd195c9389 | 53,621 |
import warnings
def find_time_delay(s1, s2, datarate=1, resolution: bool=False):
"""
Finds the time shift or delay between two signals
If s1 is advanced to s2, then the delay is positive.
Parameters
----------
s1: array-like
s2: array-like
datarate: int, optional
Input data sa... | bea029b20de51434a66623f08a90203db12fe5a0 | 53,622 |
def create(workout_type, user_id):
"""Creates a workout object of the specified type."""
workout = None
if workout_type == Keys.WORKOUT_TYPE_EVENT:
workout = Event.Event(user_id)
elif workout_type == Keys.WORKOUT_TYPE_REST:
workout = Rest.Rest(user_id)
else:
workout = Workout... | 552457989abd845087411642895371aa272003d9 | 53,623 |
def clean_dfg_based_on_noise_thresh(dfg, activities, noise_threshold, parameters=None):
"""
Clean Directly-Follows graph based on noise threshold
Parameters
----------
dfg
Directly-Follows graph
activities
Activities in the DFG graph
noise_threshold
Noise threshold
... | 91e250dee69ae46fdbe410c64c533b13b07aa439 | 53,624 |
def post_form(lti):
# pylint: disable=unused-argument,
"""
Access route with 'initial' request.
:param lti: `lti` object
:return: string "hi"
"""
return "hi" | 1715ede499f78025730c936d9a167c5e6cc1caa6 | 53,625 |
def cached_accessor(func_or_att):
"""Decorated function checks in-memory cache and disc cache for att first"""
if callable(func_or_att): #allows decorator to be called without arguments
att = func_or_att.__name__
return cached_accessor(func_or_att.__name__)(func_or_att)
att = func_or_att
... | d63b216b76038081378be22678337c9ae4420ccc | 53,626 |
import os
import glob
def function_parts(subdir='./'):
"""
Parse the gsw m-files in a given subdirectory.
Returns a list of parts: function base name, arguments,
inputs, and the help lines with a section index dictionary.
"""
d = os.path.join(mfiledir, subdir)
mfilelist = glob.glob(os.pa... | 1ad86315dee160469c422c1c71f49c28760eb0a5 | 53,627 |
import os
def make_graph():
"""Convert the data to a BEL graph."""
if not os.path.exists(DATA_PATH):
download_data()
df = extract_data()
return _make_graph(df) | 61e23b489cf8a37420e0464d46bf34dea7383e41 | 53,628 |
from typing import List
def find_valid_background_scan_segments(
N2_CVs, maximum_scanrate=0.011, scan_length=1950, segment_key="Segment #"
) -> List[int]:
"""checks if the data possibly contains a N2 background scan"""
# finder_warning = None
if not isinstance(N2_CVs, pd.DataFrame):
# option... | 90921f2c5db3f2621eb1058002029c7f8f0c42a6 | 53,629 |
import collections
def api_root(request, format=None):
"""
GET:
Display all available urls.
Since some urls have specific permissions, you might not be able to access
them all.
"""
apis = PUBLIC_APIS(request, format)
if request.user.is_staff:
apis += PROTECTED_APIS(request, fo... | 16e8b671f57dbf7859216055ecba95960e29a176 | 53,630 |
from typing import Tuple
import requests
import time
def get_gas_from_etherscan(key: str,
verbose: bool = False) -> Tuple[int, int, int]:
"""
Fetch gas from Etherscan API
"""
r = requests.get('https://api.etherscan.io/api',
params={'module': 'gastracker'... | b61df980f33ff1471017a6531805c229712708d9 | 53,631 |
def bit(value, position, length=1):
"""
Return bit of number value at position
Position starts from 0 (LSB)
:param value:
:param position:
:param length:
:return:
"""
binary = bin(value)[2:]
size = len(binary) - 1
if position > size:
return 0
else:
return ... | f639eae3d3f260b5b0d29ddd6a3ad99c89267704 | 53,632 |
from operator import mod
def sidereal_lunar_longitude(tee):
"""Return sidereal lunar longitude at moment, tee."""
return mod(lunar_longitude(tee) - precession(tee) + SIDEREAL_START, 360) | 9e3406527da1ffbc3cb4223f30cf92a4a703b3e0 | 53,633 |
def create_view_event_from_tensor_basic_info(tensors_info):
"""
Create view event reply according to tensor names.
Args:
tensors_info (list[TensorBasicInfo]): The list of TensorBasicInfo. Each element has keys:
`full_name`, `node_type`, `iter`.
Returns:
EventReply, the even... | f288fe55942dd55d513e807419401d00f22ae7a5 | 53,634 |
def diff_template(page, label=None):
"""
Return a Template:Diff2 string for the given Page.
"""
if label is None:
label = page.title()
return f"{{{{Diff2|{page.latest_revision_id}|{label}}}}}" | 48cca6ad78ce2e0f2e1ce4902d56734fccf45030 | 53,635 |
def is_builtin(func):
"""Return true if the function is a DGL builtin function."""
return isinstance(func, fn.BuiltinFunction) | 2cdd395672f7e72a42be80c718f5b389d261befe | 53,636 |
import warnings
def compute_sun_angle(
position,
pose,
utc_datetime,
sensor_orientation,
):
""" compute the sun angle using pysolar functions"""
altitude = 0
azimuth = 0
with warnings.catch_warnings(): # Ignore pysolar leap seconds offset warning
warnings.simplefilter("ignore")... | 34df23edf3818b53fc3b501173a116d38ae8e108 | 53,637 |
def find_tuple_with_max_ncp(base, T, key, T_max_vals, T_min_vals):
"""
Scan through the whole table T, and find the i-th tuple that maximizes NCP(base, i).
Parameters
----------
:param base: list of int
Tuple to compare T's tuples against
:param key: T
the table
:param... | 0f48f01dc5a7ccf2f78c4f7e0f614a8ca6f765eb | 53,638 |
import re
def make_dataset_name(name):
"""Dataset name contains "letters, numbers, -, _" only, any other content will be replaced with "-"
"""
def may_replace(c):
if re.match("\w", c) is None:
if c == '-':
return c
else:
return "_"
e... | bf97474ffcb0c5e0354c724ca4defea1b04f8939 | 53,639 |
def averageOfNumbers():
""" averageOfNumbers
Outputs the average of a series of numbers entered by the user.
returns:
The average of the numbers input by the user.
"""
numbers = []
amount_of_numbers = input("How many numbers do you wish to input? ")
for x in range(1, int(amount... | 3403bf775f0675e0f54dc18f5146e37989fc0ce2 | 53,640 |
import csv
import tqdm
def process_covid_ctset_data(covid_ctset_meta_csv, covid_ctset_dir, output_dir):
"""Processes slices for all patients in the given COVID-CTSet CSV file"""
filenames = []
classes = []
with open(covid_ctset_meta_csv, 'r') as f:
reader = list(csv.DictReader(f, delimiter=','... | 4fd588f01667e0e91ae222f1b13684722d77c6ce | 53,641 |
import sys
def validate(xmlfile=None, type='request'):
"""
:type xmlfile: str
"""
if type not in ['request', 'response', 'cixml']:
print('Invalid xml document type')
sys.exit()
else:
schema = xmlschema.XMLSchema('{}{}.xsd'.format(SCHEMAS_FOLDER, type))
return schem... | 5b89096b1414a22b75baa3a09df09cd6c7e2dfa2 | 53,642 |
import time
def pinsage_sample(graph,
nodes,
samples,
top_k=10,
proba=0.5,
norm_bais=1.0,
ignore_edges=set()):
"""Implement of graphsage sample.
Reference paper: .
Args:
graph: A pgl... | 7884479e95b91c5396745a805525aa0eee224445 | 53,643 |
import sys
def nbytes(obj, pprint=False):
""" return the number of bytes of the object, which includes size of nested
structures
Parameters
----------
obj: object
object to find the size of
pprint: bool, optional (default=False)
if set, returns the result after calling pretty... | 072ae3f0f614b2ba1fb02a8ed5acae95e6348097 | 53,644 |
import math
def calc_entropy(data, base=2):
"""
Calculate the entropy of data. Using documentation from
scipy.stats.entropy as the basis for this code
(https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html).
:param data: Measure the entropy of this object
:return: Calcu... | 72a9d111120415471c7d54e11c862ce8ebde4a55 | 53,645 |
import functools
def singledispatch_method(func):
"""Singledispatch on second argument, i.e. the one that isn't `self`."""
dispatcher = functools.singledispatch(func)
def wrapper(*args, **kw):
return dispatcher.dispatch(args[1].__class__)(*args, **kw)
wrapper.register = dispatcher.register
... | 5f1afbcba1d97420bc4b29ff983e19acd1159d3b | 53,646 |
def set_slops_from_read_orientation(slop, tpl_reads_orientation, cipos, ciend, buffer=0): # TODO: from Hardcoded to Dynamic Variable for buffer if requested
"""
set the slop boundaries according to the svtype and the reads orientation fro that svtype
:param slop: minimum slop value
:param tpl_reads_ori... | 4bd213c722c6503cc60cab3b5e05d30ee84b38dd | 53,647 |
import functools
def authenticate_user_registration(some_function):
""" Decorator for functions (pages) that require a user to provide identification. Returns
403 (forbidden) or 401 (depending on beiwe-api-version) if the identifying info (username,
password, device ID) are invalid.
In any function wr... | 293a8441e652e15b60529c2d6a8aa5fa0766ce57 | 53,648 |
def getValidPaths(author_collabs, year):
"""
selects the neighbours with valid paths
returns a list where each result is a tuple of author name, collaborations < year
"""
valid_neighbours = list()
for n in author_collabs:
valid_collabs = list()
for c in author_collabs[n]:
... | b9cc56b3bee490296afb9448c6082eb0206a74e7 | 53,649 |
from typing import Optional
from typing import Dict
from typing import Any
from typing import Tuple
def plot_image(
image: ArrayLike,
imshow_kwargs: Optional[Dict] = None,
text_kwargs: Optional[Dict] = None,
**kwargs: Any,
) -> Tuple[plt.Figure, plt.Axes]:
"""
Plots given image.
Parameter... | 45f38f5ee579bb74b35f8ec6f9e9ca1daa164b74 | 53,650 |
def get_same_pinyin(char):
"""
取同音字
:param char:
:return:
"""
return same_pinyin.get(char, set()) | f53d9c61313dbd4b5263733a287065bfd8b78cb9 | 53,651 |
def get_chart_params(title, output, show_legend=False):
"""Parse output type and output options and return related chart
parameters. For example: returns filename if output_type is file
or server it output_type is server
Args:
title (str): the title of your plot.
output (str): selected ... | 6e120ba54ce690c3f75e3ee1def0ea804f06bfb5 | 53,652 |
def preprocess(img, net_input_height_size=368, stride=8,
pad_value=(0, 0, 0), img_mean=(128, 128, 128), img_scale=1/256):
"""
Args:
img:
Returns:
"""
height, width, _ = img.shape
scale = net_input_height_size / height
scaled_img = cv2.resize(img, (0, 0), fx=scale,... | d2c363b8101990a5069a359ac33ebf32a91fdbed | 53,653 |
def compute_DVARS(func_img, mean_img=None, mask=None, apply_mask=False):
"""Computes the DVARS for a given fMRI image."""
if mean_img is None:
mean_img = np.mean(func_img, axis=3)
if apply_mask:
if mask is None:
mask = mask_image(mean_img)
mean_img[np.logical_not(mask)]... | 7736cdfe6fd2ed243f262d0d2dbf3c661729bac4 | 53,654 |
def count_unplayed_cards(r, progress):
"""Returns the number of cards which are not yet played, including cards
which are unplayable because all those cards (or cards of a value below it)
are already discarded"""
n = 0
for suit in r.suits:
n += 5 - progress[suit]
return n | 445b1b3d07aff4c2010fc482cb7f5b55a8250bac | 53,655 |
def index(request):
"""View function for home page of site."""
# Render the HTML template index.html with the data in the context variable.
return render(
request,
'index.html',
context = {},
) | c76567019712cc77dbe41c34d179ed82959b952d | 53,656 |
def find_start_time(arr, reps=1):
"""! A function to find when simulations reaches a steady state with
respect to array, arr.
@param arr: Array to find steady state in
@param reps: repetitions of recursion
@return: st Start time, the index of time array when the simulation
first reaches a the s... | 11951c82ddbcd33130cfcd224e7511e8600bbe7e | 53,657 |
def execute_sql(sql, model=Award, fetcher=fetchall_fetcher, read_only=True):
"""
Executes a sql query against a database.
sql - Can be either a sql string statement or a psycopg2 Composable
object (Identifier, Literal, SQL, etc).
model - A Django model that represents a ... | b57db28bcccc49045e1b0e3bd91da175a4a00cf5 | 53,658 |
import torch
def calc_region(bbox, ratio, featmap_size=None):
"""Calculate a proportional bbox region.
The bbox center are fixed and the new h' and w' is h * ratio and w * ratio.
Args:
bbox (Tensor): Bboxes to calculate regions, shape (n, 4)
ratio (float): Ratio of the output region.
... | eaea91d60f34ab146cb48ff905eac8a0b5d21d7c | 53,659 |
def toFENhash(fen):
""" Removes the two last parts of the FEN notation
"""
return ' '.join(fen.split(" ")[:-2]) | bc2575ce35f8d2678753369d2b3a4d050388891f | 53,660 |
def remap_lads(lad_name):
"""Some LADs of MSOA census data do not match
the LAD geographies of the LAD population data
"""
if lad_name == 'E06000048':
lad_mapped = 'E06000057' #Northumberland
elif lad_name == 'E08000020':
lad_mapped = 'E08000037'
elif lad_name == 'E07000097':
... | 46e13886a4541fcd5a47870d845db717373084cc | 53,661 |
def generate_dummy_ip():
"""
makes a random ip address as a string
"""
return str(randint(0,255)) + "." + str(randint(0,255)) + "." + str(randint(0,255)) + "." + str(randint(0,255)) | fa893e110c4fbf0313a96d78b31dd27c29b9fc35 | 53,662 |
import os
import sys
def _upload_and_get_command(boto3_factory, args, job_s3_folder, job_name, config, log):
"""
Get command by parsing args and config.
The function will also perform an s3 upload, if needed.
:param boto3_factory: initialized Boto3ClientFactory object
:param args: input arguments... | d2164f377aeb005998ed8ef1d228cf9713716c8b | 53,663 |
from typing import Union
import os
def get_cached(path: str, category: str=None) -> Union[str, dict, list]:
"""Get contents of a file.
The file contents are cached in memory, and all subsequent calls
to `get_cached()` with identical `path` & `category` arguments
return cached contents rather than rea... | 6b9e6d1859fb6ac622759e56a647026a29e405fd | 53,664 |
def get_paying_proxy_contract(w3: Web3, address=None):
"""
Get Paying Proxy Contract. This should be used just for contract creation/changing master_copy
If you want to call Safe methods you should use `get_safe_contract` with the Proxy address,
so you can access every method of the Safe
:param w3: ... | 1e3264d551e3b0604dc5f5c5f79c15412fc82fe8 | 53,665 |
import regex
def search_motif_positions_debug(sequence, motif):
"""
Search a sequence for a given motif (as regex),
and return position as list. Return False if the motif
is absent from the sequence.
"""
print("Found motifs: %s" % regex.findall(r"%s" % motif, sequence))
positions = [m.start(... | 826c0938c87096492c1a6386a3eb6e155dbe0c25 | 53,666 |
def validate(detector, val_data, metric):
"""Test on validation dataset."""
metric.reset()
for img, label in val_data:
# scores, bboxes = detector.detect(img)
scores, bboxes = detector.ms_detect(img)
metric.update(bboxes, scores, label)
return metric.get() | 7b9f3a5405ea40eba37765d7fbc5b204203c96de | 53,667 |
def calculate_EcefPoints(lats, longs):
"""
Construct a numpy array of EcefPoints from 2 arrays containing
Latitudes and Longitudes.
Note: lats and longs must be of equal lengths.
Parameters
----------
lats: float array
An array of Latitudes in [degrees].
longs: float array
... | daa1497b0d14773386d519cd8b33bca2e2e122fd | 53,668 |
def compute_flow_map(u, v, gran=8):
"""
Plot optical flow map
"""
flow_map = np.zeros(u.shape)
for y in range(flow_map.shape[0]):
for x in range(flow_map.shape[1]):
if y % gran == 0 and x % gran == 0:
dx = 2 * int(u[y, x])
dy = 2 * int(v[y, x])
... | 3c74a87158e59980c0e807f24f4cbf3be80e8954 | 53,669 |
def brand_usage(number_of_brand_purchasers, total_purchasers):
"""Returns the percentage of brand usage for a period.
Args:
number_of_brand_purchasers (int): Total number of unique purchasers of a brand in a period.
total_purchasers (int): Total unique purchasers in a period.
Returns:
... | cc7478c4810876ea0a335e639a861dc9175028af | 53,670 |
def sim_walks(num_steps, num_trials, d_class):
"""Assumes num_steps an int >= 0, num_trials an int > 0,
d_class a subclass of Drunk
Simulates num_trials walks of num_steps steps each.
Returns a list of the final distances for each trial"""
Homer = d_class()
origin = Location(0, 0)
... | fffa42653f1b6e84eea10fac5cba6b6390129288 | 53,671 |
import os
def colormaps_path():
"""Returns the path to user-defined colormaps"""
return os.path.join(user_path(), "colormaps") | 63294eb26dc764c1b0d7c7dcf392d21ec92c4964 | 53,672 |
def _construct_request_parameters(args: dict, keys: list, params={}):
"""A helper function to add the keys arguments to the dict parameters"""
parameters = {}
if params is not None:
for p in params:
parameters[p] = params[p]
for (arg_field, filter_field) in keys:
value = ar... | a268ddf8612014a4a4012eab8cfae50d1437be1e | 53,673 |
from typing import Optional
def __run_query_table(context, client, sql: String) -> Optional[DataFrame]:
"""
Execute an SQL
:param context: execution context
:param sql: the SQL select query to execute
:return: panda DataFrame or None
:rtype: panda.DataFrame
"""
df = None
close_dow... | ff4f342d0b620d0d2a9b03b12164e39b84e18fb2 | 53,674 |
import six
import uuid
def add_parts_json(ibs, annot_uuid_list, part_bbox_list, part_theta_list, **kwargs):
"""
REST:
Method: POST
URL: /api/part/json/
Ignore:
sudo pip install boto
Args:
annot_uuid_list (list of str) : list of annot UUIDs to be used in IBEIS IA
... | 7b158f6cade44f2610d7b97b1425b6eeeb999170 | 53,675 |
def single_re_sub_empty_test():
"""A function without arguments, needed for timeit.
NB: uses global variable text to solve the argument problem"""
return single_re_sub_empty(text, repl_chars) | a5921a88012f9ebccdaac0baa5de4a166c8f0e79 | 53,676 |
import sys
def A_STAR(global_map, start, end, Type = '8c',e = 1, heuristic = 'eu' ):
"""
Implements A* Algorithm for the Given Grid Map
Arguments:
global_map - np.array()
start - start location [x,y]
end - end location [x,y]
Type - Type of Neibhours ('8c' or '4c')
e - Heurestic Factor
... | 684ecde2c6a0f270c291e85b5c3097dee11d4da9 | 53,677 |
def create_templates(filename):
"""Create templates with the service."""
data_to_use = _load_json(filename)
service = current_records_marc21.templates_service
templates = []
for data in data_to_use:
template = service.create(data=data["values"], name=data["name"])
templates.append(t... | ab788770dd6c58b156bf84dee7f1bdfe86ec8130 | 53,678 |
def coherence_limit(nQ=2, T1_list=None, T2_list=None,
gatelen=0.1):
"""
The error per gate (1-average_gate_fidelity) given by the T1,T2 limit.
Args:
nQ: number of qubits (1 and 2 supported).
T1_list: list of T1's (Q1,...,Qn).
T2_list: list of T2's (as measured, ... | 5860ecfbc883fc74acdb838d975b9de2fdba2158 | 53,679 |
from typing import Sequence
import warnings
def connection_from_list_slice(
list_slice: Sequence,
args: ConnectionArguments = None,
connection_type: ConnectionConstructor = Connection,
edge_type: EdgeConstructor = Edge,
pageinfo_type: PageInfoConstructor = PageInfo,
slice_start=0,
list_len... | f318dab2e5fa7b422813a3f61ba92c95c01bba1e | 53,680 |
def logp_model(residuals, params_nodes, Pk, Variance, distribution_parameters):
"""returns -2log p of residuals"""
Pk_double = np.concatenate((Pk, Pk))
return 2*np.sum(np.square(params_nodes) / Pk_double) + negative_2loglikelihood(residuals, Variance, distribution_parameters) | 0ecaed2b7a06747ca27cb4d4b67855bed29a0837 | 53,681 |
def _loadParamFromFile(config, section, paramName):
"""
read param from file
validate it
and load to to global conf dict
"""
# Get paramName from answer file
value = config.get(section, paramName)
# Validate param value using its validation func
param = controller.getParamByName(pa... | a656e32b1273bab63708fd91acdbcaec9dc97fa4 | 53,682 |
def nonConv(wSpace, pts, val= -100, vis= False, img_name= 'img'):
"""This function takes in list of convex shapes with there points list for each shape
and the union of these shapes will give us the desired nonConvex shape"""
convPts = []
ctr=0
for conv in pts:
ctr+=1
wSpace1 = convPolygon(wSpace, conv, vis=... | f545e2a7ab87e1833cf8d41e3734054852ee9ad5 | 53,683 |
import os
def restart_run(db) -> list:
"""When restarting a hash run, identify which files need to be skipped from the
database
Args:
db (TinyDB database): A TinyDB database objects containing filepaths and hashes
of the search so far
"""
logger.info("Restarting hashing proces... | 04fc0e3874aef2a9ee45cadda6ed4a9a9db58662 | 53,684 |
from typing import Dict
from typing import List
from typing import Tuple
def votes_per_month(values: Dict[str, List[str] | Tuple[str]]) -> Dict[str, Dict[str, int]]:
"""
:param values: a dictionary formatted like: {month: list of votes}
:returns: dictionary every person for every month
"""
all_per... | acff0d2aaff68b12430c7d28f7f7f7b0f08aaa3c | 53,685 |
import array
def CalculationElement(curr_doc, elementlist):
"""
:param elementlist: list of all elements
:return:
all_functions: [[functions of elements 1][functions of element 2]...[functions of element n]]
--> order of functions: N, u, Q, M, w, phi
x: Symbol to plot over
... | 0b351ecf8c82cd0bd2750711eb41e2e9d1e97e8d | 53,686 |
def adjacency2digraph(
adj_matrix: np.ndarray,
similar_this_dgraph: nx.DiGraph = None) -> nx.DiGraph:
"""Converts the adjacency matrix to directed graph.
If similar_this_graph is given, then the final directed graph has the same
node labeling as the given graph has.
Using dgraph2adjacen... | b82a08bd669a4d5c6629713c2a869250356b8bd1 | 53,687 |
def move_cursor(move):
"""Return move value for cursor."""
return {
'left': -1,
'right': 1,
}[move] | 333c3b6b0a8b3e936250f47b16019420da2a3670 | 53,688 |
def accuracy(output, target):
"""Computes the precision@k for the specified values of k"""
topk = (1,4)
maxk = max(topk)
batch_size = target.size(0)
# 上位何件のデータを参照するかターゲットデータのラベル数を参照
label_count = np.count_nonzero(target == 1, axis = 1)
# one-hot配列からクラス番号を取得
class_index_array, class_num... | b33a612ff6ae883eabe6e0f15d1e2ddffc4ff79a | 53,689 |
def unsubscribe_from_basket_action(newsletter):
"""Unsubscribe from Basket action."""
def unsubscribe_from_basket(modeladmin, request, queryset):
"""Unsubscribe from Basket."""
ts = [(mozillians.users.tasks.unsubscribe_from_basket_task
.subtask(args=[userprofile.user.email, userp... | 8514a17decf1c47dd3718da781c03b880e2aae3e | 53,690 |
from typing import Tuple
from typing import Dict
from typing import List
import os
import shutil
def pgi_params() -> Tuple[Dict[str, str], List[str]]:
"""
Nvidia PGI compilers
pgc++ is not available on Windows at this time
"""
compilers = {'FC': 'pgfortran',
'CC': 'pgcc'}
i... | ce525a88cac123183715983c0e2d6ad01de7184d | 53,691 |
def find_possible_pt2262_device(device_id):
"""Look for the device which id matches the given device_id parameter."""
for dev_id, device in RFX_DEVICES.items():
if hasattr(device, 'is_lighting4') and len(dev_id) == len(device_id):
size = None
for i, (char1, char2) in enumerate(zi... | 037e3bf24811ba545ebe1b8327056239fca2f59c | 53,692 |
import math
def gcd(*nums):
"""
Find the greatest common divisor (GCD) of a list of numbers.
Args:
*nums (tuple[int]): The input numbers.
Returns:
gcd_val (int): The value of the greatest common divisor (GCD).
Examples:
>>> gcd(12, 24, 18)
6
>>> gcd(12, 2... | ea3b2f55ab1db530a2c0e5d472c053b9e538f3e0 | 53,693 |
def create_app(debug=True, base_url="/api/v1/data"):
"""Create main Flask app if this module is the entrypoint, e.g. python3 -m data.api"""
app = Flask(__name__)
app.debug = debug
configure_app(app, base_url=base_url)
return app | baf3e17a4fb01ee4188064c95b120449c091633f | 53,694 |
def exposure_compensation(img,
illuminant_lux, # ambient illumination strength in lux
luminance_target=300, # will compensate for this luminance, in cd/m2
luminance_display=300, # the luminance of the display cd/m2
... | d6a0d740a0578fcf7860c5bff98a719b4e9ed8f2 | 53,695 |
from typing import Union
import os
def get_generate_dicom_seg_cmd(
resampled_aseg: Union[str, bytes, os.PathLike],
aseg_dicom_seg_metadata: Union[str, bytes, os.PathLike],
t1_dicom_file: Union[str, bytes, os.PathLike],
aseg_dicom_seg_output: Union[str, bytes, os.PathLike],
) -> str:
"""Generate th... | 6e5160bbbdb55a5b0ac25b4babe294c3abbeb987 | 53,696 |
from typing import Callable
from pathlib import Path
from typing import Tuple
from typing import Type
def template_and_parser(
template_file: Callable[[str, str], Path]
) -> Callable[[str, str], Tuple[Path, Type[AbstractParser]]]:
"""
Retrieve the parser and test template for a particular
supported fi... | ae24f243a88aa109f42494caef13f79188b21410 | 53,697 |
def sum_2(strg):
"""Sums last 3 digits"""
sum = 0
for i in strg[3:]:
sum += int(i)
if sum == 0:
sum = 1
return sum | 0b49ae9eb3f390b855d43030a5a163f594e78652 | 53,698 |
def URLs(integration: bool):
"""
summary: return URLs dict (funName:url)
arguments: (integration: bool [test type])
"""
URLs = {
"get_access_token": "/token",
"GetMe": "/users/me/",
"ListUsers": "/users",
"GetAdmins": "/users/admins",
"CreateUser": "/user",
... | 6a89eaa5ff2b0280fa82b15182edbef6dfd06154 | 53,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.