content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def getn_hidden_area(*args):
"""getn_hidden_area(int n) -> hidden_area_t"""
return _idaapi.getn_hidden_area(*args) | 3265d4258ce6717e8ca23bd10754e1b1648d4217 | 3,640,067 |
def cdist(X: DNDarray, Y: DNDarray = None, quadratic_expansion: bool = False) -> DNDarray:
"""
Calculate Euclidian distance between two DNDarrays:
.. math:: d(x,y) = \\sqrt{(|x-y|^2)}
Returns 2D DNDarray of size :math: `m \\times n`
Parameters
----------
X : DNDarray
2D array of s... | 14a2368ff0717ff04e0477699ff13d20f359ba0d | 3,640,068 |
def popcount_u8(x: np.ndarray):
"""Return the total bit count of a uint8 array"""
if x.dtype != np.uint8:
raise ValueError("input dtype must be uint8")
count = 0
# for each item look-up the number of bits in the LUT
for elem in x.flat:
count += u8_count_lut[elem]
return count | e85c07b3df7dcd993c0f1cc7f9dbecd97e8be317 | 3,640,069 |
from scipy import stats
def split_errorRC(tr, t1, t2, q, Emat, maxdt, ddt, dphi):
"""
Calculates error bars based on a F-test and
a given confidence interval q.
Note
----
This version uses a Fisher transformation for
correlation-type misfit.
Parameters
----------
tr : :clas... | 3155031382c881a15a8a300d6656cae1fc0fee64 | 3,640,070 |
import copy
def filter_parts(settings):
"""
Remove grouped components and glyphs that have been deleted or split.
"""
parts = []
temp = copy.copy(settings['glyphs'])
for glyph in settings['glyphs']:
name = glyph['class_name']
if name.startswith("_split") or name.startswith("_gr... | f8d6a59eeeb314619fd4c332e2594dee3543ee9c | 3,640,071 |
def kernel_zz(Y, X, Z):
"""
Kernel zz for second derivative of the potential generated by a sphere
"""
radius = np.sqrt(Y ** 2 + X ** 2 + Z ** 2)
r2 = radius*radius
r5 = r2*r2*radius
kernel = (3*Z**2 - r2)/r5
return kernel | 14f36fe23531994cd40c74d26b91477d266ca21c | 3,640,072 |
def getAccentedVocal(vocal, acc_type="g"):
"""
It returns given vocal with grave or acute accent
"""
vocals = {'a': {'g': u'\xe0', 'a': u'\xe1'},
'e': {'g': u'\xe8', 'a': u'\xe9'},
'i': {'g': u'\xec', 'a': u'\xed'},
'o': {'g': u'\xf2', 'a': u'\xf3'},
... | cfec276dac32e6ff092eee4f1fc84b412c5c915c | 3,640,073 |
def env_initialize(env, train_mode=True, brain_idx=0, idx=0, verbose=False):
""" Setup environment and return info """
# get the default brain
brain_name = env.brain_names[brain_idx]
brain = env.brains[brain_name]
# reset the environment
env_info = env.reset(train_mode=train_mode)[brain_na... | 3c951a77009cca8c876c36965ec33781dd2c08dd | 3,640,074 |
def lorentzianfit(x, y, parent=None, name=None):
"""Compute Lorentzian fit
Returns (yfit, params), where yfit is the fitted curve and params are
the fitting parameters"""
dx = np.max(x) - np.min(x)
dy = np.max(y) - np.min(y)
sigma = dx * 0.1
amp = fit.LorentzianModel.get_amp_from_amplitude(... | cd221c3483ee7f54ac49baaeaf617ef8ec2b7fa7 | 3,640,075 |
def tf_quat(T):
""" Return quaternion from 4x4 homogeneous transform """
assert T.shape == (4, 4)
return rot2quat(tf_rot(T)) | 7fb2a7b136201ec0e6a92faf2cc030830df46fa5 | 3,640,076 |
def solve2(lines):
"""Solve the problem."""
result = 0
for group in parse_answers2(lines):
result += len(group)
return result | 5990b61e713733ba855937b8191b8a8a4f503873 | 3,640,077 |
def get_contract_type(timestamp: int, due_timestamp: int) -> str:
"""Get the contract_type
Input the timestamp and due_timestamp. Return which contract_type is.
Args:
timestamp: The target timestamp, you want to know.
due_timestamp: The due timestamp of the contract.
Returns:
... | 3b3a084f786c82a5fc1b2a7a051e9005b3df5f0a | 3,640,078 |
from typing import Any
from typing import Optional
from typing import Union
from typing import Type
from typing import Tuple
from typing import Sequence
from typing import cast
def is_sequence_of(obj: Any,
types: Optional[Union[Type[object],
Tuple[Type[objec... | 3762454785563c7787451efad143547f97ae8994 | 3,640,079 |
def _parse_tree_height(sent):
"""
Gets the height of the parse tree for a sentence.
"""
children = list(sent._.children)
if not children:
return 0
else:
return max(_parse_tree_height(child) for child in children) + 1 | d6de5c1078701eeeb370c917478d93e7653d7f4f | 3,640,081 |
def pandas_loss_p_g_i_t(c_m, lgd, ead, new):
""" Distribution of losses at time t.
long format (N_MC, G, K, T)."""
mat_4D = loss_g_i_t(c_m, lgd, ead, new)
names = ['paths', 'group_ID', 'credit_rating_rank', 'time_steps']
index = pds.MultiIndex.from_product([range(s)for s in mat_4D.shape], names=... | 65e9db48eab0a40596b205a7304bd225eb5c93d0 | 3,640,082 |
def find_available_pacs(pacs, pac_to_unstuck=None, pac_to_super=None, pac_to_normal=None):
"""
Finds the available pacs that are not assigned
"""
available_pacs = pacs['mine']
if pac_to_unstuck is not None:
available_pacs = [x for x in available_pacs if x['id'] not in pac_to_unstuck.keys()... | 4b6674fd87db2127d5fffa781431ccc9a9ff775a | 3,640,084 |
async def login_for_access_token(
form_data: OAuth2PasswordRequestForm = Depends(),
):
"""
Log in to your account using oauth2 authorization.
In response we get an jwt authorization token
which is used for granting access to data
"""
is_auth, scope = await authenticate_authority(
for... | 441326317f0f13275ad33e369efe419a605ac4eb | 3,640,085 |
def get_plain_expressions(s):
"""Return a list of plain, non-nested shell expressions found in the shell
string s. These are shell expressions that do not further contain a nested
expression and can therefore be resolved indenpendently.
For example::
>>> get_plain_expressions("${_pyname%${_pyname#?... | a3b0f6812ffe361e291b28c4273ca7cc975eb1e7 | 3,640,086 |
def create_indices(dims):
"""Create lists of indices"""
return [range(1,dim+1) for dim in dims] | 1a83b59eb1ca2b24b9db3c9eec05db7335938cae | 3,640,087 |
def observed_property(property_name, default, cast=None):
"""Default must be immutable."""
hidden_property_name = "_" + property_name
if cast is None:
if cast is False:
cast = lambda x: x
else:
cast = type(default)
def getter(self):
try:
return... | 7358557b221b5d4fa18fbd29cd02b47823cfdfe0 | 3,640,088 |
from typing import Callable
from io import StringIO
def query_helper(
source: S3Ref, query: str, dest: S3Ref = None, transform: Callable = None
) -> StringIO:
"""
query_helper runs the given s3_select query on the given object.
- The results are saved in a in memory file (StringIO) and returned.
... | 3670734c76f615fe6deb3dfed8305cfc1740b124 | 3,640,089 |
def indicator_selector(row, indicator, begin, end):
"""Return Tons of biomass loss."""
dasy = {}
if indicator == 4:
return row[2]['value']
for i in range(len(row)):
if row[i]['indicator_id'] == indicator and row[i]['year'] >= int(begin) and row[i]['year'] <= int(end):
dasy[s... | 329411837633f4e28bea4b2b261b6f4149b92fb1 | 3,640,090 |
import math
def xy_from_range_bearing(range: float, bearing: float) -> map_funcs.Point:
"""Given a range in metres and a bearing from the camera this returns the x, y position in metres relative to the runway
start."""
theta_deg = bearing - google_earth.RUNWAY_HEADING_DEG
x = CAMERA_POSITION_XY.x + ra... | a2575437b52003660d83b241da13f10687fa4241 | 3,640,091 |
def flask_get_modules():
"""Return the list of all modules
---
tags:
- Modules
responses:
200:
description: A list of modules
"""
db_list = db.session.query(Module).all()
return jsonify(db_list) | 21352458773143f785658488e34f9e486c7f818d | 3,640,092 |
def create_user(username, password):
"""Registra um novo usuario caso nao esteja cadastrado"""
if User.query.filter_by(username=username).first():
raise RuntimeError(f'{username} ja esta cadastrado')
user = User(username=username, password=generate_password_hash(password))
db.session.add(user)
... | 1a50d31b764cce10d0db78141041deafc15f7c40 | 3,640,093 |
import numpy
def _get_mesh_colour_scheme():
"""Returns colour scheme for MESH (maximum estimated size of hail).
:return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.
:return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.
"""
colour_list = [
[152,... | 4301822297d069a6cc289e72b5bf388ffae01cf4 | 3,640,094 |
def _manually_create_user(username, pw):
"""
Create an *active* user, its server directory, and return its userdata dictionary.
:param username: str
:param pw: str
:return: dict
"""
enc_pass = server._encrypt_password(pw)
# Create user directory with default structure (use the server fun... | 21d523ae29121697e63460302d8027499b4d896d | 3,640,097 |
def update_geoscale(df, to_scale):
"""
Updates df['Location'] based on specified to_scale
:param df: df, requires Location column
:param to_scale: str, target geoscale
:return: df, with 5 digit fips
"""
# code for when the "Location" is a FIPS based system
if to_scale == 'state':
... | e62083f176cd749a88b2e73774e70140c6c5b9ac | 3,640,098 |
import json
def translate(text, from_lang="auto", to_lang="zh-CN"):
"""translate text, return the result as json"""
url = 'https://translate.googleapis.com/translate_a/single?'
params = []
params.append('client=gtx')
params.append('sl=' + from_lang)
params.append('tl=' + to_lang)
params.a... | 944a5a90f60d8e54c402100e512bbce2bbb407c5 | 3,640,099 |
def backproject_to_plane(cam, img_pt, plane):
"""Back an image point to a specified world plane"""
# map to normalized image coordinates
npt = np.matrix(npl.solve(cam[0], np.array(list(img_pt)+[1.0])))
M = cam[1].transpose()
n = np.matrix(plane[:3]).flatten()
d = plane.flat[3]
Mt = M * cam[2... | 47ae45103460db5a5447900dda10783c8f92362e | 3,640,100 |
from datetime import datetime
def format_cell(cell, datetime_fmt=None):
"""Format a cell."""
if datetime_fmt and isinstance(cell, datetime):
return cell.strftime(datetime_fmt)
return cell | 8d3fb41bb3d7d3f3b341482e2d050d32092118bf | 3,640,101 |
def optimize(gradients, optim, global_step, summaries, global_norm=None, global_norm_clipped=None, appendix=''):
"""Modified from sugartensor"""
# Add Summary
if summaries is None:
summaries = ["loss", "learning_rate"]
# if "gradient_norm" in summaries:
# if global_norm is None:
# ... | 4887d45d5b9eb5a96008daeab5d11c97afed27fd | 3,640,102 |
def _get_desired_asg_capacity(region, stack_name):
"""Retrieve the desired capacity of the autoscaling group for a specific cluster."""
asg_conn = boto3.client("autoscaling", region_name=region)
tags = asg_conn.describe_tags(Filters=[{"Name": "value", "Values": [stack_name]}])
asg_name = tags.get("Tags"... | cdcec8493333a001fe3883b0c815da521c571f7a | 3,640,103 |
def _default_geo_type_precision():
""" default digits after decimal for geo types """
return 4 | eef082c8a8b38f4ede7bfb5d631b2679041b650c | 3,640,104 |
import scipy
def load_movietimes(filepath_timestamps, filepath_daq):
"""Load daq and cam time stamps, create muxer"""
df = pd.read_csv(filepath_timestamps)
# DAQ time stamps
with h5py.File(filepath_daq, 'r') as f:
daq_stamps = f['systemtime'][:]
daq_sampleinterval = f['samplenumber'][... | 4d54f7378f3d189a5bea4c14f68d5556958ba4f3 | 3,640,105 |
def is_valid_hotkey(hotkey: str) -> bool:
"""Returns True if hotkey string is valid."""
mode_opts = ["press", "click", "wheel"]
btn_opts = [b.name for b in Button]
wheel_opts = ["up", "down"]
hotkeylist = hotkey[2:].split("_")
if len(hotkeylist) == 0 or len(hotkeylist) % 2 != 0:
return ... | 2fb47b3f77b4cb3da2b70340b6ed96bd03c0bd14 | 3,640,106 |
def find_range_with_sum(values : list[int], target : int) -> tuple[int, int]:
"""Given a list of positive integers, find a range which sums to a target
value."""
i = j = acc = 0
while j < len(values):
if acc == target:
return i, j
elif acc < target:
acc += values... | d54f185c98c03f985724a29471ecb1e301c14df5 | 3,640,107 |
def output_AR1(outfile, fmri_image, clobber=False):
"""
Create an output file of the AR1 parameter from the OLS pass of
fmristat.
Parameters
----------
outfile :
fmri_image : ``FmriImageList`` or 4D image
object such that ``object[0]`` has attributes ``coordmap`` and ``shape``
cl... | b805e73992a51045378d5e8f86ccf780d049002b | 3,640,108 |
def feature_bit_number(current):
"""Fuzz bit number field of a feature name table header extension."""
constraints = UINT8_V
return selector(current, constraints) | 4a2103f399765aec9d84c8152922db3801e4a718 | 3,640,109 |
def render_page(context, slot, payload): # pylint: disable=R0201,W0613
""" Base template slot """
chapter = request.args.get('chapter', '')
module = request.args.get('module', '')
page = request.args.get('page', '')
try:
if page:
return render_template(f"{chapter.lower()}/{modul... | 69e5a837d90084b4c215ff75fb08a47aab1cff97 | 3,640,110 |
def add_stripe_customer_if_not_existing(f):
"""
Decorator which creates user as a customer if not already existing before making a request to the Stripe API
"""
@wraps(f)
def wrapper(user: DjangoUserProtocol, *args, **kwargs):
user = create_customer(user)
return f(user, *args, **kwar... | 676e9fad5de545a2627d52942917a49af3c6539d | 3,640,111 |
def noisify_patternnet_asymmetric(y_train, noise, random_state=None):
""" mistakes in labelling the land cover classes in PatternNet dataset
cemetery -> christmas_tree_fram
harbor <--> ferry terminal
Den.Res --> costal home
overpass <--> intersection
park.space --> park.lot
runway_mark --> p... | ef37d5c39081cba489076956c0cd948a93ba0387 | 3,640,114 |
def group_superset_counts(pred, label):
"""
Return TP if all label spans appear within pred spans
:param pred, label: A group, represeted as a dict
:return: A Counts namedtuple with TP, FP and FN counts
"""
if (pred["label"] != label["label"]):
return Counts(0, 1, 1)
for label_span i... | 8fddd5cfdb0050e97ec60d37e4d939b40cf5d891 | 3,640,115 |
def other():
""" Queries all of the logged in user's Campaigns
and plugs them into the campaigns template """
entities = db.session.query(Entity)
entities = [e.to_dict() for e in entities]
return render_template('other.html', entities=entities) | 7c7613f919bf5eecc223cf90715e9bd2ae6eb130 | 3,640,116 |
def rel_angle(vec_set1, vec_set2):
"""
Calculate the relative angle between two vector sets
Args:
vec_set1(array[array]): an array of two vectors
vec_set2(array[array]): second array of two vectors
"""
return vec_angle(vec_set2[0], vec_set2[1]) / vec_angle(vec_set1[0], vec_set1[1]) ... | af89a10e26968f53200294919d8b72b532aa3522 | 3,640,117 |
def check_position_axes(chgcar1: CHGCAR, chgcar2: CHGCAR) -> bool:
"""Check the cell vectors and atom positions are same in two CHGCAR.
Parameters
-----------
chgcar1, chgcar2: vaspy.CHGCAR
Returns
-------
bool
"""
cell1 = chgcar1.poscar.cell_vecs
cell2 = chgcar2.poscar.cell_v... | 29eabfd72a664c77d55164953b6819f3eabd72f1 | 3,640,118 |
def path_shortest(graph, start):
""" Pythonic minheap implementation of dijkstra's algorithm """
# Initialize all distances to infinity but the start one.
distances = {node: float('infinity') for node in graph}
distances[start] = 0
paths = [(0, start)]
while paths:
current_distance, cu... | 32fe7df3fb02c3a0c3882f5cc5135417c5193985 | 3,640,119 |
import urllib
import json
def request(url, *args, **kwargs):
"""Requests a single JSON resource from the Wynncraft API.
:param url: The URL of the resource to fetch
:type url: :class:`str`
:param args: Positional arguments to pass to the URL
:param kwargs: Keyword arguments (:class:`str`) to pass... | 66f23e5a15b44b5c9bc0777c717154749d25987e | 3,640,120 |
def destagger(var, stagger_dim, meta=False):
"""Return the variable on the unstaggered grid.
This function destaggers the variable by taking the average of the
values located on either side of the grid box.
Args:
var (:class:`xarray.DataArray` or :class:`numpy.ndarray`): A variable
... | 89bb08618fa8890001f72a43da06ee8b15b328be | 3,640,121 |
def create_blueprint(request_manager: RequestManager, cache: Cache,
dataset_factory: DatasetFactory):
"""
Creates an instance of the blueprint.
"""
blueprint = Blueprint('metadata', __name__, url_prefix='/metadata')
@cache.memoize()
def _get_method_types_per_approach():
... | 32693a6286e4ffb15e4820dbd7ad5fdbe6632e95 | 3,640,123 |
def sides(function_ast, parameters, function_callback):
"""
Given an ast, parses both sides of an expression.
sides(b != c) => None
"""
left = side(function_ast['leftExpression'], parameters, function_callback)
right = side(function_ast['rightExpression'], parameters, function_callback)
... | 9ed00100122f821340a0db37e77bfcf786eacdf9 | 3,640,124 |
def print_url(host, port, datasets):
"""
Prints a list of available dataset URLs, if any. Otherwise, prints a
generic URL.
"""
def url(path = None):
return colored(
"blue",
"http://{host}:{port}/{path}".format(
host = host,
port = por... | 37d58dce1672f60d72936d6e1b9644fdd5ab689f | 3,640,125 |
def get_default_sample_path_random(data_path):
"""Return path to sample with default parameters as suffix"""
extra_suffix = get_default_extra_suffix(related_docs=False)
return get_default_sample_path(data_path, sample_suffix=extra_suffix) | 54220840dc6ef1831859a60058506e7503effcb7 | 3,640,126 |
def VectorShadersAddMaterialDesc(builder, materialDesc):
"""This method is deprecated. Please switch to AddMaterialDesc."""
return AddMaterialDesc(builder, materialDesc) | 0aaec1d3e14536a65c9cb876075d12348176096c | 3,640,127 |
import math
def phase_randomize(D, random_state=0):
"""Randomly shift signal phases
For each timecourse (from each voxel and each subject), computes its DFT
and then randomly shifts the phase of each frequency before inverting
back into the time domain. This yields timecourses with the same power
... | d8f3230acdf8b3df98995adaadc92f41497a27ea | 3,640,128 |
def monospaced(text):
"""
Convert all contiguous whitespace into single space and strip leading and
trailing spaces.
Parameters
----------
text : str
Text to be re-spaced
Returns
-------
str
Copy of input string with all contiguous white space replaced with
... | 51f07908dde10ef67bd70b5eb65e03ee832c3755 | 3,640,129 |
def molecule_block(*args, **kwargs):
"""
Generates the TRIPOS Mol2 block for a given molecule, returned as a string
"""
mol = Molecule(*args, **kwargs)
block = mol.molecule_block() + mol.atom_block() + mol.bond_block() + '\n'
return block | 79ebf821e105666fb81396197fa0f218b2cf3e48 | 3,640,130 |
def setup_test_env(settings_key='default'):
"""Allows easier integration testing by creating RPC and HTTP clients
:param settings_key: Desired server to use
:return: Tuple of RPC client, HTTP client, and thrift module
"""
return RpcClient(handler), HttpClient(), load_module(settings_key) | 827a71692dd2eb9946db34289dcf48d5b5d4415b | 3,640,131 |
from typing import List
from typing import Tuple
def calculateCentroid(
pointCloud : List[Tuple[float, float, float]]
) -> Tuple[float, float, float]:
"""Calculate centroid of point cloud.
Arguments
--------------------------------------------------------------------------
pointCloud (flo... | 0e8d6d578a0a983fe1e68bff22c5cc613503ee76 | 3,640,132 |
def get_num_uniq_users(csv_file, userid_col):
"""
A Helper function to help get the number of unique users
:param csv_file: path to CSV file
:param userid_col: Column for user ID
:return:
"""
# Read the CSV file using pandas
df = pd.read_csv(csv_file)
# Use the nunique() method to g... | ade25596bb308414c80e1aea87d412bd5a340288 | 3,640,134 |
from zooniverse_web.models import Survey, QuestionResponse, Response, QuestionOption
from zooniverse_web.utility.survey import generate_new_survey
def administration(request):
"""Administration actions ((re)train acton predictor for a new survey)
Parameters
----------
request:
POST request
... | 7d5a08450c9058f6fd33a13fc4cf6b714bc7e657 | 3,640,136 |
from typing import Counter
def checkout(skus):
"""
Calculate the total amount for the checkout based on the SKUs entered in
:param skus: string, each char is an item
:return: int, total amount of the cart, including special offers
"""
total = 0
counter = Counter(skus)
# got through t... | ad00a9c3e3cd4f34cfd7b5b306d3863decc0751b | 3,640,137 |
def func_tradeg(filename, hdulist=None, whichhdu=None):
"""Return the fits header value TELRA in degrees.
"""
hdulist2 = None
if hdulist is None:
hdulist2 = fits.open(filename, 'readonly')
else:
hdulist2 = hdulist
telra = fitsutils.get_hdr_value(hdulist2, 'TELRA')
if hdulis... | 4e6751d2eb0ac9e6264f768e932cbd42c2fc2c4e | 3,640,138 |
def column_indexes(column_names, row_header):
"""項目位置の取得
Args:
column_names (str): column name
row_header (dict): row header info.
Returns:
[type]: [description]
"""
column_indexes = {}
for idx in column_names:
column_indexes[idx] = row_header.index(column_names... | 4205e31e91cd64f833abd9ad87a02d91eebc8c61 | 3,640,139 |
import logging
import pickle
def dmx_psrs(caplog):
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
caplog.set_level(logging.CRITICAL)
psrs = []
for p in psr_names:
with open(datadir+'/{0}_ng9yr_dmx_DE436_epsr.pkl'.format(p), 'rb') as fin:
... | 6bbb5df017374f207d7c9338a737212f5c7e5b23 | 3,640,140 |
def fit_stats(act_map, param, func=KentFunc):
"""Generate fitting statistics from scipy's curve fitting"""
phi_grid, theta_grid = meshgrid(phi_arr, theta_arr)
Xin = np.array([theta_grid.flatten(), phi_grid.flatten()]).T
fval = act_map.flatten()
fpred = func(Xin, *param) # KentFunc
res = fval - ... | 97e4223daf3e140f1a091491f18012840b8c006a | 3,640,141 |
def conv2d_for_hpool_valid_width_wrapper(inputs,filters,strides,padding,**kwargs):
"""
Wraps tf.layers.conv2d to allow valid convolution across signal width and
'same' convolution across signal height when padding is set to "valid_time"
Arguments:
inputs (TF Tensor): Tensor input.
filters (TF... | 9b4438c687232245e645ea5714e7ad7899ecd98b | 3,640,142 |
import copy
def resample_cells(tree, params, current_node = 'root', inplace = False):
"""
Runs a new simulation of the cell evolution on a fixed tree
"""
if not inplace:
tree = copy.deepcopy(tree)
for child in tree.successors(current_node):
initial_cell = tree.nodes[current_node][... | 10cde9abdf3a6271aa20276c3e193b1c93ca7908 | 3,640,143 |
def get_sql_query(table_name:str) -> str:
"""Fetch SQL query file for generation of dim or fact table(s)"""
f = open(f'./models/sql/{table_name}.sql')
f_sql_query = f.read()
f.close()
return f_sql_query | fc3308eae51b7d10667a50a0f4ee4e295bfea8d0 | 3,640,144 |
def _map_args(call_node, function):
"""Maps AST call nodes to the actual function's arguments.
Args:
call_node: ast.Call
function: Callable[..., Any], the actual function matching call_node
Returns:
Dict[Text, ast.AST], mapping each of the function's argument names to
the respective AST node.
"... | b19befded386e6081be9858c7eb31ffd45c96ef3 | 3,640,145 |
def sub_bases( motif ):
"""
Return all possible specifications of a motif with degenerate bases.
"""
subs = {"W":"[AT]", \
"S":"[CG]", \
"M":"[AC]", \
"K":"[GT]", \
"R":"[AG]", \
"Y":"[CT]", \
"B":"[CGT]", \
"D":"[AGT]", \
"H":"[ACT]", \
"V":"[ACG]", \
"N":"[ACGTN]"}
for symbol,... | 10ff2ea1959aba103f1956398afb5f1d8801edd7 | 3,640,146 |
import logging
def parse(input_file_path):
"""
Parse input file
:param input_file_path: input file path
:return: Image list
"""
verticals, horizontals = 0, 0
logging.info("parsing %s", input_file_path)
with open(input_file_path, 'r') as input_file:
nb = int(input_file.readline(... | ecd4fd066d1128f385da59965a93e59c038052bd | 3,640,147 |
def char(ctx, number):
"""
Returns the character specified by a number
"""
return chr(conversions.to_integer(number, ctx)) | 5c5254978055f690b6801479b180ff39b31e2248 | 3,640,148 |
import re
import logging
async def get_character_name(gear_url, message):
"""
It is *sometimes* the case that discord users don't update their username
to be their character name (eg for alts).
This method renders the gear_url in an HTML session and parses the page
to attempt to find the charact... | cdd18e0123f226d2c59d41bbf39e0dfc02188d73 | 3,640,149 |
import pandas
def get_treant_df(tags, path='.'):
"""Get treants as a Pandas DataFrame
Args:
tags: treant tags to identify the treants
path: the path to search for treants
Returns:
a Pandas DataFrame with the treant name, tags and categories
>>> from click.testing import CliRunner
... | a5972646e27ffd88d18f1c0d212a2ae081ebe4f1 | 3,640,150 |
def gather_keypoints(keypoints_1, keypoints_2, matches):
"""
Gather matched keypoints in a (n x 4) array,
where each row correspond to a pair of matching
keypoints' coordinates in two images.
"""
res = []
for m in matches:
idx_1 = m.queryIdx
idx_2 = m.trainIdx
pt... | 5abef87c570493b57e81dcddc2732ed541aa6a08 | 3,640,151 |
async def stop():
""" Stop any playing audio. """
Sound.stop()
return Sound.get_state() | 3c7ea7aae3e8dd7e3b33ddd9beed0ce2182800bc | 3,640,152 |
def is_numeric(X, compress=True):
"""
Determine whether input is numeric array
Parameters
----------
X: Numpy array
compress: Boolean
Returns
-------
V: Numpy Boolean array if compress is False, otherwise Boolean Value
"""
def is_float(val):
try:
float(v... | ad28657f51680cd193671a6a8a8da6a91390dc15 | 3,640,153 |
def figure_ellipse_fitting(img, seg, ellipses, centers, crits, fig_size=9):
""" show figure with result of the ellipse fitting
:param ndarray img:
:param ndarray seg:
:param [(int, int, int, int, float)] ellipses:
:param [(int, int)] centers:
:param [float] crits:
:param float fig_size:
... | de6b58a01a64c3123f5aad4dfb6935c6c19a041c | 3,640,154 |
def fmt_bytesize(num: float, suffix: str = "B") -> str:
"""Change a number of bytes in a human readable format.
Args:
num: number to format
suffix: (Default value = 'B')
Returns:
The value formatted in human readable format (e.g. KiB).
"""
for unit in ["", "Ki", "Mi", "Gi", "Ti",... | 09b36d229856004b6df108ab1ce4ef0a9c1e6289 | 3,640,155 |
def get_kpoint_mesh(structure: Structure, cutoff_length: float, force_odd: bool = True):
"""Calculate reciprocal-space sampling with real-space cut-off."""
reciprocal_lattice = structure.lattice.reciprocal_lattice_crystallographic
# Get reciprocal cell vector magnitudes
abc_recip = np.array(reciprocal_... | 0536b5e2c37b7ba98d240fc3099fad93d246f730 | 3,640,156 |
def resnet_v1_101(inputs,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
spatial_squeeze=True,
reuse=None,
scope='resnet_v1_101', **kwargs):
"""ResNet-101 model of... | 138289084d48edd9d9c1096bd790b1479d902ec1 | 3,640,157 |
def is_package_authorized(package_name):
"""
get user information if it is authorized user in the package config
Returns:
[JSON string]: [user information session]
"""
authorized_users = get_package_admins(package_name)
user_info = get_user_info()
user_dict = j.data.serializers.json... | 59b89ebb9c8579d61a18a194e7f5f4bd41d738b6 | 3,640,158 |
def submit_search_query(query_string, query_limit, query_offset,
class_resource):
"""
Submit a search query request to the RETS API
"""
search_result = class_resource.search(
query='%s' % query_string, limit=query_limit, offset=query_offset)
return search_result | f8c30c86f7ff7c33fc96b26b1491ddaa48710fbc | 3,640,159 |
def one_hot_encode(df):
"""
desc : one hot encodes categorical cols
args:
df (pd.DataFrame) : stroke dataframe
returns:
df (pd.DataFrame) : stroke dataframe with one_hot_encoded columns
"""
# extract categorical columns
stroke_data = df.copy()
cat_cols = stroke_data.... | 6895dfbc4bb57d5e8d9a5552e2ac7fcb94e07434 | 3,640,160 |
def assert_increasing(a):
"""Utility function for enforcing ascending values.
This function's handle can be supplied as :py:kwarg:`post_method` to a
:py:func:`processed_proprty <pyproprop>` to enforce values within a
:py:type:`ndarray <numpy>` are in ascending order. This is useful for
enforcing ti... | f1ded37b40686cf400da23f567880e73180a78fe | 3,640,161 |
def copy_to_device(device,
remote_path,
local_path='harddisk:',
server=None,
protocol='http',
vrf=None,
timeout=300,
compact=False,
use_kstack=False,
... | 762ef928656473458e0fee8dc47c1a581103ed0e | 3,640,162 |
def decode_replay_header(contents):
"""Decodes and return the replay header from the contents byte string."""
decoder = VersionedDecoder(contents, protocol.typeinfos)
return decoder.instance(protocol.replay_header_typeid) | 1fcee7900a5c0c310e67afe31a154b8310da7089 | 3,640,164 |
def _generate_indexed(array: IndexedArray) -> str:
"""Generate an indexed Bash array."""
return (
"("
+ " ".join(
f"[{index}]={_generate_string(value)}"
for index, value in enumerate(array)
if value is not None
)
+ ")"
) | 2443b3c6be74684360c395995b3d16d4ebecf1d8 | 3,640,165 |
from datetime import datetime
def up_date(dte, r_quant, str_unit, bln_post_colon):
""" Adjust a date in the light of a (quantity, unit) tuple,
taking account of any recent colon
"""
if str_unit == 'w':
dte += timedelta(weeks=r_quant)
elif str_unit == 'd':
dte += timedelta(... | 684b09e5d37bf0d3445262b886c73188d35425ef | 3,640,166 |
from typing import MutableMapping
def read_options() -> Options:
"""
read command line arguments and options
Returns:
option class(Options)
Raises:
NotInspectableError: the file or the directory does not exists.
"""
args: MutableMapping = docopt(__doc__)
schema = Schema({... | 25cd3c29f6e206fd97334f7a48d267680a9e553c | 3,640,167 |
def test_generator_single_input_2():
"""
Feature: Test single str input
Description: input str
Expectation: success
"""
def generator_str():
for i in range(64):
yield chr(ord('a') + i)
class RandomAccessDatasetInner:
def __init__(self):
self.__data =... | d251279c0740b52c9d32c2ae572f6dbdf32f36ea | 3,640,168 |
def SLINK(Dataset, d):
"""function to execute SLINK algo
Args:
Dataset(List) :- list of data points, who are also lists
d(int) :- dimension of data points
Returns:
res(Iterables) :- list of triples sorted by the second element,
first element is index of poin... | d10a3f8cb3e6d81649bebd4a45f5be79d206f1be | 3,640,169 |
def static_file(path='index.html'):
"""static_file"""
return app.send_static_file(path) | 5c3f2d423d029a8e7bb8db5fbe3c557f7a6aa9c3 | 3,640,170 |
def lazy_property(function):
""" Decorator to make a lazily executed property """
attribute = '_' + function.__name__
@property
@wraps(function)
def wrapper(self):
if not hasattr(self, attribute):
setattr(self, attribute, function(self))
return getattr(self, attribute)
... | db1d62eb66a018bc166b67fe9c2e25d671261f77 | 3,640,171 |
from pathlib import Path
def basename(fname):
"""
Return file name without path.
Examples
--------
>>> fname = '../test/data/FSI.txt.zip'
>>> print('{}, {}, {}'.format(*basename(fname)))
../test/data, FSI.txt, .zip
"""
if not isinstance(fname, path_type):
fname = Path(fna... | 55cd53ec71e4e914493129e40fa216ddcdbe8083 | 3,640,172 |
def validate_lockstring(lockstring):
"""
Validate so lockstring is on a valid form.
Args:
lockstring (str): Lockstring to validate.
Returns:
is_valid (bool): If the lockstring is valid or not.
error (str or None): A string describing the error, or None
if no error w... | 0feb67597e31667013ab182159c8433ae4a80346 | 3,640,173 |
from typing import Iterable
def decode_geohash_collection(geohashes: Iterable[str]):
"""
Return collection of geohashes decoded into location coordinates.
Parameters
----------
geohashes: Iterable[str]
Collection of geohashes to be decoded
Returns
-------
Iterable[Tuple[float... | 2e673c852c7ac2775fd29b32243bdc8b1aa83d77 | 3,640,174 |
def renormalize_sparse(A: sp.spmatrix) -> sp.spmatrix:
"""Get (D**-0.5) * A * (D ** -0.5), where D is the diagonalized row sum."""
A = sp.coo_matrix(A)
A.eliminate_zeros()
rowsum = np.array(A.sum(1))
assert np.all(rowsum >= 0)
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
d_inv_sqrt[np.isinf... | 33122bcf018dba842f04e044cf9e799860a56042 | 3,640,175 |
def _fetch(
self,
targets=None,
jobs=None,
remote=None,
all_branches=False,
show_checksums=False,
with_deps=False,
all_tags=False,
recursive=False,
):
"""Download data items from a cloud and imported repositories
Returns:
int: number of successfully downloaded files
... | 18238bb1c4c5bd0772757013173e26645d5cdf5a | 3,640,178 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.