content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def split_person_name(name):
"""
A helper function. Split a person name into a first name and a last name.
Example.
>>> split_person_name("Filip Oliver Klimoszek")
("Filip Oliver", "Klimoszek")
>>> split_person_name("Klimoszek")
("", "Klimoszek")
"""
parts = name.split(" ")
return " ".join(parts[:-1... | 86b7c7cec1e7772437f41f11437834cfa34051c7 | 3,631,300 |
def readFile(file):
"""Reads file and returns lines from file.
Args:
string: file name
Returns:
list: lines from file
"""
fin = open(file)
lines = fin.readlines()
fin.close()
return lines | 52c62e6c97caad053cd6619935d8d3674cc3b8cb | 3,631,301 |
def vec_rotate_left(x):
"""Circular left shift the contents of the vector
Args:
x (jax.numpy.ndarray): A line vector.
Returns:
jax.numpy.ndarray: Left rotated x.
"""
return jnp.roll(x, -1) | 58bc95e73ba45829c588c07682f1b04f9f2b6f30 | 3,631,302 |
def play_game(my_play='PUT',game_id='PUT'):
"""Submit a play to a game. Return results of the game."""
# If no my_play then something is wrong
# If no game_id and no match_id then create a new game and play it
# If game_id then play that game
# If match_id and no game_id then .. idk .. tea?
# Pu... | 50bd11a8f89f68ca981eecc96c6c225cd84fd1c7 | 3,631,303 |
def get_inputs(seq_len):
"""Get input layers.
See: https://arxiv.org/pdf/1810.04805.pdf
:param seq_len: Length of the sequence or None.
"""
names = ['Token', 'Segment', 'Masked']
return [keras.layers.Input(
batch_shape=(1, seq_len,),
name='Input-%s' % name,
) for name in name... | 585d6bae73b7b9f4fc6e9dcafd85ee0e4be88b44 | 3,631,304 |
import base64
def get_credentials(args):
"""Read credentials from args"""
# cmdline credentials override those stored in config file
if args.api_key or args.api_secret:
if not args.api_key or not args.api_secret:
raise AuthError(
(
"Both --key and --... | f4f69b20e5ea2fe58a8ee22920c7faeea8738aae | 3,631,305 |
import logging
def GetRange(spreadsheet_id, sheet_name, range_in_sheet):
"""Gets the given range in the given spreadsheet.
Args:
spreadsheet_id: The id from Google Sheets, like
https://docs.google.com/spreadsheets/d/<THIS PART>/
sheet_name: The name of the sheet to get, from the bottom tab.
ran... | 08eaa5f761679622b6561c7ed56d41ef725c940e | 3,631,306 |
def format_price(raw_price):
"""Formats the price to account for bestbuy's raw price format
Args:
raw_price(string): Bestbuy's price format (ex: $5999 is $59.99)
Returns:
string: The formatted price
"""
formatted_price = raw_price[:len(raw_price) - 2] + "." + raw_price[len(raw_pric... | a3b0adc94421334c3f1c4fe947329d329e68990e | 3,631,307 |
import os
def get_directory(directory=None):
"""Get directory to work with."""
# Set variable fdir = current directory, if user didn't specify another dir
if not directory:
fdir = os.getcwd()
# Set variable fdir = directory chosen by the user, if a dir is specified
else:
fdir = os.... | 9b83f5502cea6ff908b7528c2ae480d9072ccd79 | 3,631,308 |
def access_app(app_label, *permissions):
"""
Returns a scope that represents access for the given
permissions to the given app.
"""
return _make_grant(
(
app_label,
),
permissions,
) | ef9ad2827cd38d70760618c7f3af8ab645a3b22f | 3,631,309 |
def mock_device_with_capabilities(monkeypatch):
"""A function to create a mock device with non-empty observables"""
with monkeypatch.context() as m:
m.setattr(Device, '__abstractmethods__', frozenset())
m.setattr(Device, '_capabilities', mock_device_capabilities)
def get_device(wires=1)... | d21e319645ce4ae59db1cea9c38c1e5bc8bf967f | 3,631,310 |
def replicated_data(index):
"""Whether data[index] is a replicated data item"""
return index % 2 == 0 | 26223e305d94be6e092980c0eb578e138cfa2840 | 3,631,311 |
def create_source_list(uris_list):
"""
Create a source_list object
Adds list of uris to soure_list object.
@arg uris_list List of list of GCS uris
@returns A source_list object
@example
uris_list = [["gs://my-bucket/my-image-1.tif"], ["gs://my-bucket/my-image-2.tif"]]
print(create_s... | cd5ca853d1c388d5be0c5591a64eff4120af5b3e | 3,631,312 |
def sigmoid_rampup(current, rampup_length):
""" Exponential rampup from https://arxiv.org/abs/1610.02242 .
"""
if rampup_length == 0:
return 1.0
else:
current = np.clip(current, 0.0, rampup_length)
phase = 1.0 - current / rampup_length
return float(np.exp(-5.0 * phase * ... | a003cb14073b14789e221197d42f818ee29b863b | 3,631,313 |
def photos_restaurants():
"""returns photos"""
return render_template('photos.html') | f0404e9cd0cd97018f64f415612180828afaef1d | 3,631,314 |
def encode(obj, outtype='json', raise_error=False):
""" encode objects, via encoder plugins, to new types
Parameters
----------
outtype: str
use encoder method to_<outtype> to encode
raise_error : bool
if True, raise ValueError if no suitable plugin found
Examples
--------
... | 7408fc616c7b1c99a47a33b55bf9c0cabcd1cf70 | 3,631,315 |
def minorify_scale(scale):
"""Turns a major scale into a minor scale"""
return rotate(scale, 5) | a0f2e5d7307095eb6c6b426a32c7958082d1eff9 | 3,631,316 |
def _get_dtype_maps():
""" Get dictionaries to map numpy data types to ITK types and the
other way around.
"""
# Define pairs
tmp = [ (np.float32, 'MET_FLOAT'), (np.float64, 'MET_DOUBLE'),
(np.uint8, 'MET_UCHAR'), (np.int8, 'MET_CHAR'),
(np.uint16, 'MET_USHORT'), (... | a5816325737a97054764b0b266353053cf83b025 | 3,631,317 |
def get_user_roles_common(user):
"""Return the users role as saved in the db."""
return user.role | cf25f029325e545f5d7685e6ac19e0e09105d65a | 3,631,318 |
def getlist(self, option: str, fallback: list=None, *, raw: bool=False, vars: dict=None) -> list:
"""
Converts a SectionProxy cvs option to a list
:param option: the option to get
:param fallback: default value, if option does not exist
:param raw: True to disable interpolation
:param vars: addi... | b451c48bfaa0dc1cf51f6ffd52866a9d5c1ad761 | 3,631,319 |
def _schedule_spatial_pack(cfg, s, output, conv, data_vec, kernel_vec):
"""schedule the spatial packing for conv2d"""
data = s[data_vec].op.input_tensors[0]
max_unroll = 16
vec_size = [1, 2, 4, 8, 16]
# get tunable parameters (they are defined in compute)
BC, TC, VC = cfg["tile_co"].size
BH... | 91f3cb0b442b1b35fbdcb532b0d229b05a56b09f | 3,631,320 |
from .spectral import TemplateSpectralModel
from .spatial import ConstantSpatialModel
def create_fermi_isotropic_diffuse_model(filename, **kwargs):
"""Read Fermi isotropic diffuse model.
See `LAT Background models <https://fermi.gsfc.nasa.gov/ssc/data/access/lat/BackgroundModels.html>`_
Parameters
-... | 6233fa84e2234722587c17289522e61e8fcc453b | 3,631,321 |
def get_auto_sync(admin_id):
"""Method to return status of the auto synchronization statement.
Args:
admin_id (str): Root privileges flag.
"""
return r_synchronizer.is_sync_auto() | 897a30c35eb115e359dae844a81155bfa3b93b12 | 3,631,322 |
def create_inchi_groups(ctfile):
"""Organize `InChI` into groups based on their identical `InChI` string and similar coupling type.
:param ctfile: `SDfile` instance.
:type ctfile: :class:`~ctfile.ctfile.SDfile`
:return: Dictionary of related `InChI` groups.
:rtype: :rtype: :py:class:`dict`
"""
... | 819239eac4298be1de63510faf67e282ee20bb91 | 3,631,323 |
def qmax_statistics(sample_q, sample, uncertainty, qmax, qmin, qmaxinst,
relative_max_uncertainty,):
"""
"""
#TODO: Include background statistics in this?
if qmax is 'statistics':
old_settings = np.seterr(divide='ignore')
uncertainty_percent_array = uncertainty ... | 99c905d15b5fa651c5c0d893835881d0e2d7dadc | 3,631,324 |
def loocvRF(data, idcolumn, outcomevar, dropcols=[], numestimators=1000, fs=0.02):
"""
Main loocv RF function that calls other functions to do RF feature selection, training, and testing.
Args:
data (pandas DataFrame): This is a dataframe containing each participant's features and outcome... | 3681923d34334e16490586e143cb29dd9b426461 | 3,631,325 |
from typing import Union
def sqla_session(x: Union['db_url', 'engine']):
"""
Do a pile of sane defaults to get a sqla session. Example usage:
db = sqla_session(...)
df = pd.read_sql(sql=..., con=db.bind)
"""
# Resolve args
if isinstance(x, str):
db_url = x
if '/' ... | 4a7b6fa07d360a884d60982083a4a70a7699dd1c | 3,631,326 |
def box_iou(box1, box2, order='xyxy'):
"""Compute the intersection over union of two set of boxes.
The default box order is (xmin, ymin, xmax, ymax).
Args:
box1: (tf.tensor) bounding boxes, sized [A, 4].
box2: (tf.tensor) bounding boxes, sized [B, 4].
order: (str) box order, either 'xyxy'... | 03b40728a52cc4b825e2e9473ce5ada6dfa07d2e | 3,631,327 |
def get_bmi_category(df):
"""
This function adds the BMI category and Health risk based on the BMI value
:param df: input dataframe with BMI values
:return: Dataframe with BMI category and Health risk derived from their respective BMI values
"""
return df.withColumn('BMI Category', F.when(df.BM... | 85574ae7e1b9887b86aa06881e6950d30e2e2aea | 3,631,328 |
import os
import shutil
def setup(projectdir='.', resourcedir='mm'):
"""Initialise a default modelmanager project in the current directory."""
resourcedir = osp.join(projectdir, resourcedir)
settings_path = osp.join(resourcedir, SettingsManager.settings_file_name)
print('Initialising a new modelmanag... | 284317ed6a9c177a4489847220f4c40a4b4b4dff | 3,631,329 |
def create_mm_sim(molecule):
"""Create vacuum simulation system"""
platform = Platform.getPlatformByName('CPU')
properties={}
properties["Threads"]="2"
integrator = LangevinIntegrator(temperature, collision_rate, stepsize)
topology = molecule.to_topology()
system = forcefield.create_openmm... | 7023320e9344bf9601844917692f36650ee57376 | 3,631,330 |
def team_event_awards(team_key: TeamKey, event_key: EventKey) -> Response:
"""
Returns a list of awards for a team at an event.
"""
track_call_after_response("team/event/awards", f"{team_key}/{event_key}")
awards = TeamEventAwardsQuery(team_key=team_key, event_key=event_key).fetch_dict(
Api... | 942f6576bec422a84d9d1ad220b38a050ff4b466 | 3,631,331 |
def version_match(ms_version, mi_version):
"""Judge if the version of Mindinsight and Mindspore is matched."""
if not ms_version:
ms_version = MS_VERSION
# the debugger version in MS 1.4.xxx is still 1.3.xxx
if mi_version.startswith('1.4.') and ms_version.startswith('1.3.'):
return True
... | 68d74482eb693794cedcf3e89063f97cab85110a | 3,631,332 |
def add_to_tfrecord(coco, img_id, img_dir, coder, writer, is_train):
"""
Add each "single person" in this image.
coco - coco API
Returns:
The number of people added.
"""
# Get annotation id for this guy
# Cat ids is [1] for human..
ann_id = coco.getAnnIds(imgIds=img_id, catIds=[1]... | 2bed504df8c65633b69ad520596cf65bced29d12 | 3,631,333 |
def partial_es(Y_idx, X_idx, pred, data_in, epsilon=0.0001):
"""
The analysis on the single-variable dependency in the neural network.
The exact partial-related calculation may be highly time consuming, and so the estimated calculation can be used in the bad case.
Args:
Y_idx: index of Y to acce... | 12186469b27bebea4735372e2b45f463bbfbaff1 | 3,631,334 |
def process_source_text(
source_text: str,
endpoint_config: submanager.models.config.FullEndpointConfig,
) -> str:
"""Perform text processing operations on the source text."""
source_text = submanager.sync.utils.replace_patterns(
source_text,
endpoint_config.replace_patterns,
)
s... | 318a66717008a57c0a975359092a925d55dfe44a | 3,631,335 |
def angle(v1, v2, deg=False):
"""
Angle between two N dimmensional vectors.
:param v1: vector 1.
:param v2: vector 2.
:param deg: if True angle is in Degrees, else radians.
:return: angle in radians.
Example::
>>> angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
... | 0d85cc76085468401fcb805d0df5a83862791d49 | 3,631,336 |
def random_pure_actions(nums_actions, random_state=None):
"""
Return a tuple of random pure actions (integers).
Parameters
----------
nums_actions : tuple(int)
Tuple of the numbers of actions, one for each player.
random_state : int or np.random.RandomState, optional
Random see... | 300c77583d60e0fa5d5be240ae1beb8c4555db22 | 3,631,337 |
import os
def get_my_process():
"""get process object of current process
Returns:
[psutil.Process] -- process object
"""
return get_process_object(os.getpid()) | 0c519d1d2b2d19c81413f80f7bc070824890c9ff | 3,631,338 |
import pandas
import numpy
def prepare_and_store_dataframe(test_df: pandas.DataFrame, current_datetime: str, prediction: numpy.ndarray,
eval_identity: str, df_output_dir: str):
"""Prepares a dataframe that includes the testing data (timestamp, value), the detected anomalies and the... | a2aa5d9ffb9ec495abb96ddebc820dd351392b1a | 3,631,339 |
def read_terrace_centrelines(DataDirectory, shapefile_name):
"""
This function reads in a shapefile of terrace centrelines
using shapely and fiona
Args:
DataDirectory (str): the data directory
shapefile_name (str): the name of the shapefile
Returns: shapely polygons with terraces
... | bd527dc9c890f3e0efd7076803ce1288f2643062 | 3,631,340 |
def isfloat(s):
"""
Checks whether the string ``s`` represents a float.
:param s: the candidate string to test
:type s: ``str``
:return: True if s is the string representation of a number
:rtype: ``bool``
"""
try:
x = float(s)
return True
except:
r... | 2233d0a06b9ff0be74f76ef2fce31c816f68584c | 3,631,341 |
import aiohttp
async def _fetch_team_info(team_id=None):
"""Get general team information"""
url = f"{BASE_URL}teams/{team_id}"
async with aiohttp.ClientSession() as session:
data = await _fetch_data(session, url)
team_info = data['teams'][0]
return team_info | b846b71cf65d2179c59f108c3c0e27ff4eb25149 | 3,631,342 |
def numeric(typ):
"""Check whether `typ` is a numeric type"""
return typ.tcon in (Bool, Int, Float, Complex) | b03a2042072a084e8482e5782ffc074512bf52e2 | 3,631,343 |
def quadtree_point_in_polygon(
poly_quad_pairs,
quadtree,
point_indices,
points_x,
points_y,
poly_offsets,
ring_offsets,
poly_points_x,
poly_points_y,
):
""" Test whether the specified points are inside any of the specified
polygons.
Uses the table of (polygon, quadrant)... | 898e8d4da600da559605146a451093c0452ce6cc | 3,631,344 |
from typing import Dict
def obtain_treasury_maturities(treasuries: Dict) -> pd.DataFrame:
"""Obtain treasury maturity options [Source: EconDB]
Parameters
----------
treasuries: dict
A dictionary containing the options structured {instrument : {maturities: {abbreviation : name}}}
Returns
... | 02dfc478be14cf63938b43420c61b359baf06ab3 | 3,631,345 |
def graph(gra):
""" write a molecular graph to a string
"""
gra_str = automol.graph.string(gra)
return gra_str | 635ee0fcad2aa1b5d2542c9d89a492692efbcf0a | 3,631,346 |
def diag(v, k=0):
"""
Extract a diagonal or construct a diagonal array.
See syntax here: https://numpy.org/doc/stable/reference/generated/numpy.diag.html
"""
if not is_casadi_type(v):
return _onp.diag(v, k=k)
else:
if k != 0:
raise NotImplementedError(
... | 983ff1bd5c753d40b44f8fe38dadab9febfccffa | 3,631,347 |
def which_set(connections_list_of_dics):
"""
"""
set_of_derivations=get_set_of_derivations(connections_list_of_dics)
list_of_derivations=[]
list_of_derivations.append("all")
list_of_derivations.append("each")
for this_deriv in list(set_of_derivations):
list_of_derivations.append(this_deriv)
list_of_... | d4b93396a9966d532c4a46acb88467d8cbe00914 | 3,631,348 |
def ensure_derived_space(func):
"""
Decorator for Surface functions that require ImageSpace arguments.
Internally, Surface objecs store information indexed to a minimal
enclosing voxel grid (referred to as the self.index_grid) based on
some arbitrary ImageSpace. When interacting with other ImageS... | 3f293d0833fd7079a49eaf5ce2de53c76d238da8 | 3,631,349 |
def available_datasets():
"""
Returns the list of available datasets.
"""
return sorted(_datasets.keys()) | 77b1d451f89f76486d36a03008634fc1b5728150 | 3,631,350 |
def readable_date(input_date):
"""helper method to make a date object more readable
:param input_date: a date object
:return: more readable string representation of a date
"""
return "{} {}, {}".format(month_name[input_date.month], str(input_date.day), str(input_date.year)) | a22649298ef2fd488257091bfdf82a11f8de1846 | 3,631,351 |
def get_unicode_from_response(response):
"""Return the requested content back in unicode.
This will first attempt to retrieve the encoding from the response
headers. If that fails, it will use
:func:`requests_toolbelt.utils.deprecated.get_encodings_from_content`
to determine encodings from HTML ele... | 3b7b9ced468e3a26cd7c322b6c0a6c0552215e7b | 3,631,352 |
def stack_layers(inputs, net_layers, kernel_initializer='glorot_uniform'):
"""Builds the architecture of the network by applying each layer specified in net_layers to inputs.
Args:
inputs: a dict containing input_types and input_placeholders for each key
and value pair, respecively.
net_layers: a li... | a010ec3e1c02978c28c2df2f947f1360ccb35deb | 3,631,353 |
def instance_gpu() -> str:
"""
Returns the GPU for the Colab instance.
:return: The GPU model
"""
devices = device_lib.list_local_devices()
gpu = [x.physical_device_desc for x in devices if x.device_type == "GPU"][0]
return gpu.split(",")[1].split(":")[1].strip() | 37af910eb3bac5b089f28ee73fb9040b686b516e | 3,631,354 |
def _get_expected_samples(A_s, b_s, mu_0, sample_shape) -> np.ndarray:
"""
Given an initial `mu_0`, calculate the expected samples from an almost-deterministic
`StateSpaceModel`.
"""
*batch_shape, transitions, state_dim = b_s.shape
means_list = [mu_0]
for i in range(transitions):
mea... | 46a88611ae0a04851474fbbe5605a523e3e42a6a | 3,631,355 |
import ast
def local_vars(fn: ast.AST):
"""Returns a set of all function local variables."""
return set(_locals_impl(fn)) | c51290884099957063be9bc0814dca13ceb7566e | 3,631,356 |
def swap(size: int, target0: int, target1: int) -> Matrix:
"""
Construct swap gate which swaps two states
:param int size: total number of qubits in circuit
:param int target0: The first target bit to swap
:param int target1: The second target bit to swap
returns:
Matrix: Matrix repres... | a34d15c5b74ad49b01b6dfe894f640982c88d4fe | 3,631,357 |
def get_ELS_file_name(dt, remove_extension=False):
"""
>>> get_ELS_file_name('28-06-2004/22:00')
'ELS_200418018_V01.DAT'
>>> get_ELS_file_name('28-06-2004/09:00')
'ELS_200418006_V01.DAT'
>>> get_ELS_file_name('29-06-2004/09:00')
'ELS_200418106_V01.DAT'
>>> get_ELS_file_name('29-06-2005/0... | f6a9f0dfff3501379f94e55e3fecdf2033400db2 | 3,631,358 |
def percentage_to_float(x):
"""Convert a string representation of a percentage to float.
>>> percentage_to_float('55%')
0.55
Args:
x: String representation of a percentage
Returns:
float: Percentage in decimal form
"""
return float(x.strip('%')) / 100 | 6c1aeac99278963d3dd207d515e72b6e1e79f09f | 3,631,359 |
def _naics_code_to_name(naics_val: str) -> str:
"""Converts NAICS codes to their industry using the _NAICS_MAP.
Args:
naics_val: A NAICS string literal to process.
Expected syntax of naics_val - NAICS/{codes}
'-' can be used to denote range of codes that may or may not belong
... | 96e5f7d951c81337ee3d431f765a98c6d12f737f | 3,631,360 |
import copy
def threshold_distribution(distribution, target_bin=128):
"""
Return the best threshold value.
Ref: https://github.com//apache/incubator-mxnet/blob/master/python/mxnet/contrib/quantization.py
Args:
distribution: list, activations has been processed by histogram and normalize,size ... | 8831842d2d09d73cefedeb3c954911e770a55f49 | 3,631,361 |
from typing import Optional
import re
def get_pragma_spec(source: str) -> Optional[NpmSpec]:
"""
Extracts pragma information from Solidity source code.
Args:
source: Solidity source code
Returns: NpmSpec object or None, if no valid pragma is found
"""
pragma_match = next(re.finditer(r"... | 8a5af024c1105a52140b2bfefb583b67568964d5 | 3,631,362 |
def delete_form(context, *args, **kwargs):
"""Тег формы удаления объекта.
"""
action = (args[0] if len(args) > 0
else kwargs.get('action'))
if action is None:
raise TemplateSyntaxError(
"delete_form template tag "
"requires at least one argument: "
... | c99736384eb149869bc4110e90427fe21beaecc7 | 3,631,363 |
def _ligandscout_xml_tree(pharmacophore):
""" Get an xml element tree necesary to create a ligandscout pharmacophore.
Parameters
----------
pharmacophore : openpharmacophore.Pharmacophore
Pharmacophore object that will be saved to a file.
Returns
-------
... | c9e8b09a103917ceb6242dd74de4c93198cf841d | 3,631,364 |
def get_form(line):
"""
gets the form of the word,
can use instead of getLemma
TODO: pick a function naming convention and stick with it
"""
if line == "":
return ""
s = line.split("\t")
return s[0] | b16e1d38d45833dd75863232deab362a4d4fb58a | 3,631,365 |
import time
import requests
def request_get_content(url: str, n_retry: int = 3) -> bytes:
"""Retrieve the binary content at url.
Retry on connection errors.
"""
t0 = time.time()
for i in range(1, n_retry + 1):
try:
r = _session().get(url)
r.raise_for_status()
... | 6fc3882243b4d23f7311ab9d7b5a1bf946a801d7 | 3,631,366 |
def _escape_special_chars(content):
"""No longer used."""
content = content.replace("\N{RIGHT-TO-LEFT OVERRIDE}", "")
if len(content) > 300: # https://github.com/discordapp/discord-api-docs/issues/1241
content = content[:300] + content[300:].replace('@', '@ ')
return content | 816fc3ba15150c3e254a17d1a021d1ddee11e49f | 3,631,367 |
def gather(results_dir):
"""Move all of the files and directories from the present working directory
into results_dir.
If results_dir doesn't exist, create it.
Delete any symbolic links so that the present working directory is empty.
:param results_dir: Path of the directory into which to store t... | 375154347ea57147d236c4fbf1da01791e654684 | 3,631,368 |
def system_dynamics(t, x, params,):
"""
Parameters
----------
x0 : State vector
t : Current time step
params : Simulation parameters
Returns
-------
dx : State vector dynamics for time step integration
"""
# Extract state variables and parameters
# Python star... | 1d9ef4f2ff304f14f961620af3ec646a3a6ad1b3 | 3,631,369 |
def key():
"""Connection key"""
return ConnectionKey('localhost', 80, False, None, None, None, None) | 4af1cc0619db168f9e9110095accab1836031bd4 | 3,631,370 |
import ipdb
def _check_deviation(indexesv,
xdatav,
ydatav,
yarray_,
ii,
start_,
end_,
mbf,
dev_thresh,
no_data,
... | 541acff0c88b3912e185989348d4c81fa4275507 | 3,631,371 |
def crop_boxes_inv(cropped_boxes, crop_shape):
"""
Inverse operation of crop_boxes
"""
crop_x1 = crop_shape[0]
crop_y1 = crop_shape[1]
raw_boxes = np.zeros_like(cropped_boxes)
raw_boxes[:, 0::4] = cropped_boxes[:, 0::4] + crop_x1
raw_boxes[:, 1::4] = cropped_boxes[:, 1::4] + crop_y1
... | 309eba1ddde6a9474bab132b5f2deaae75b772e4 | 3,631,372 |
from typing import OrderedDict
import inspect
def build_paramDict(cur_func):
"""
This function iterates through all inputs of a function,
and saves the default argument names and values into a dictionary.
If any of the default arguments are functions themselves, then recursively (depth-first) ad... | b62daf5ffe7b9211d898d26dc754875459dbe1ba | 3,631,373 |
def auto_gen_message(open, fill, close):
"""
Produces the auto-generated warning header with language-spcific syntax
open - str - The language-specific opening of the comment
fill - str - The values to fill the background with
close - str - The language-specific closing of the commen... | e72ff3760ea78efb969f5c457caca726e070a387 | 3,631,374 |
def neighbor(matrix, taxa=None, distances=True):
"""
Function clusters data according to the Neighbor-Joining algorithm \
(:evobib:`Saitou1987`).
"""
clusters = dict([(i, [i]) for i in range(len(taxa))])
formatter = "({0}:{2:.4f},{1}:{3:.4f})" if distances else "({0},{1})"
taxa = check_langu... | 8bd655082cb6c5e1b9ba7efdda5241ea0943782c | 3,631,375 |
def mixed_type_frame():
"""
Fixture for DataFrame of float/int/string columns with RangeIndex
Columns are ['a', 'b', 'c', 'float32', 'int32'].
"""
return DataFrame({'a': 1., 'b': 2, 'c': 'foo',
'float32': np.array([1.] * 10, dtype='float32'),
'int32': np.... | 7a07b77413839104b687e095b8805a205f3b14fc | 3,631,376 |
def dar_state():
"""Get DAR state
"""
return jsonify(state=dar.state) | df188f3f9c37e011f820453740f9758adf2dabb9 | 3,631,377 |
def has_prefix(sub_s):
"""
:param sub_s: the list which includes the permutations of string's alphabet
:return: if the permutations of string's alphabet not exists in dictionary
"""
global d
for word in d:
if d[word].startswith(sub_s):
return True
return False | 07c4636e1e85029c8cc5e5d8450ceae1a6511846 | 3,631,378 |
def MaskStringWithIPs(string):
"""Mask all private IP addresses listed in a string."""
ips = ExtractIPsFromString(string)
for ip in ips:
use_bits = IsPrivateIP(ip)
if use_bits:
masked_ip = MaskIPBits(ip, use_bits)
string = string.replace(ip, masked_ip)
return string | b90f194cd038c1979b38ac57c8e30326a19ca4b8 | 3,631,379 |
def DiagGaussian_UnifBins(mean, stdd, bin_min, bin_max, coding_prec, n_bins, rebalanced=True):
"""
Codec for data from a diagonal Gaussian with uniform bins.
rebalanced=True will ensure no zero frequencies, but is slower.
"""
if rebalanced:
bins = np.linspace(bin_min, bin_max, n_bins)
... | d54464e8a4bf2e5f93ee228b19b9de92e00dfafd | 3,631,380 |
def GetUserFansCount(user_url: str) -> int:
"""获取用户粉丝数
Args:
user_url (str): 用户个人主页 Url
Returns:
int: 用户粉丝数
"""
AssertUserUrl(user_url)
AssertUserStatusNormal(user_url)
json_obj = GetUserJsonDataApi(user_url)
result = json_obj["followers_count"]
return result | 057a732bff7ae74896b598022d57754e034a02af | 3,631,381 |
from typing import Counter
def majority_vote(labels):
"""assumes labels sorted by distance ASC"""
vote_counts = Counter(labels)
winner, winner_count = vote_counts.most_common(1)[0]
num_winners = len([count
for count in vote_counts.values()
if count... | f56aede57a08ee4d9190e3b69daa48a7946fcb99 | 3,631,382 |
from typing import Union
from typing import Literal
def primitive_vertices_sphere(
radius: Floating = 0.5,
segments: Integer = 8,
intermediate: Boolean = False,
origin: ArrayLike = np.array([0, 0, 0]),
axis: Union[Literal["+z", "+x", "+y", "yz", "xz", "xy"], str] = "+z",
) -> NDArray:
"""
... | 4519d0629273eeb4391fb0fa49ba552c139acb98 | 3,631,383 |
def VtuDiff(vtu1, vtu2, filename = None):
"""
Generate a vtu with fields generated by taking the difference between the field
values in the two supplied vtus. Fields that are not common between the two vtus
are neglected. If probe is True, the fields of vtu2 are projected onto the cell
points of vtu1. Otherwi... | 5b3ce93ae70b32e112f66332bfeb101d3804b772 | 3,631,384 |
def senv(key, default=NoDefault, required=False, settings=None, _altered_defaults=None, _defaults=None):
"""
return the value for key by checking the following sources:
- the environment
- the settings dictionary
if the key is in _defaults but not in _altered_defaults, don't consider the val... | 7d73117e6b9a47bcf0266e82d86b98a3662c37cf | 3,631,385 |
def average_balance_observer(validator_type):
""" A function factory that returns an observer function"""
def obs_func(state):
validators = state["network"].validators
validator = validators[0]
head = br.specs.get_head(validator.store)
current_state = validator.store.block_states... | f771f306d7cc3653e73fbb915ed7938ec35bcbeb | 3,631,386 |
def get_channel_members_names(channel):
"""Returns a list of all members of a channel. If the member has a nickname, the nickname is used instead of their name, otherwise their name is used"""
names = []
for member in channel.members:
if member.nick is None:
names.append(member.name)
... | 955ea4013841fe8aac52f0474a65e221795db571 | 3,631,387 |
import os
import time
import math
def _build( ):
"""
Build the project.
This step handles:
Checking library dependencies.
Checking which files need to be built.
And spawning a build thread for each one that does.
"""
if _guiModule:
_guiModule.run()
built = False
global _building
_building = True
for ... | 67ef0546f5f08cef03006545885c3b865bc6e387 | 3,631,388 |
def getRaCfg(name, default):
""" Gets a config attribute, if not set, return the default. """
if 'raCfg' in config:
if name in config['raCfg'] and isinstance(config['raCfg'][name], bool):
return config['raCfg'][name]
return default | 9ea0498568f86948ac2a111622cbae7a2535c24a | 3,631,389 |
import typing
def quat_mean(quaternions: typing.Sequence[typing.Union[typing.Sequence, np.ndarray]]) -> np.ndarray:
"""
Find the mean of a bunch of quaternions
Fails in some pathological cases where the quats are widely distributed.
:param quaternions:
:return:
"""
if len(quaternions) <= ... | cc95cdb2be8db53701e5e97c5200cdcf67ab6be9 | 3,631,390 |
def get_element_dict(propname='mass_number'):
""" Obtain dictionary of elements ordered by a property.
"""
prop_dict = {k:getattr(elements[k], propname) for k in elements.keys()}
elems = list(elements.keys())
props = list(prop_dict.values())
# Sort the element list by the masses
srtse... | 9902bb1f96618a2d8e4d328711cbacdc68c8a2e3 | 3,631,391 |
def get_match_history(start_at_match_id=None, player_name=None, hero_id=None,
skill=0, date_min=None, date_max=None, account_id=None,
league_id=None, matches_requested=None, game_mode=None,
min_players=None, tournament_games_only=None,
... | ad89ec7b54e03cddbbe966cc8b2701e6002e8a7e | 3,631,392 |
from alert.models import AddDropPeriod
def get_add_drop_period(semester):
"""
Returns the AddDropPeriod object corresponding to the given semester. Throws the same
errors and behaves the same way as AddDropPeriod.objects.get(semester=semester) but runs faster.
This function uses caching to speed up ad... | b2e18e73d2d01e064866fb95c5d425e615a5c7da | 3,631,393 |
from solarforecastarbiter.io.fetch import nwp as fetch_nwp
def run_nwp(forecast, model, run_time, issue_time):
"""
Calculate benchmark irradiance and power forecasts for a Forecast or
ProbabilisticForecast.
Forecasts may be run operationally or retrospectively. For
operational forecasts, *run_tim... | bcff6b763b5391e074f262b96848e3caa216bfa1 | 3,631,394 |
def get_path_filename(handle):
""" cleans path, combines it"""
path = config['path'].strip('/').strip()
return path + '/' + handle + config['extension'] | 01b4a60fdf28327849e2ae63633b1f42c4b09dc8 | 3,631,395 |
def get_user_subscription_steps(signature=None):
"""ユーザー申込みのステップ数
:return:
"""
url_pattern = 'format:user_subscription_step%s'
url_kwargs = {'signature': signature}
step_list = create_steps(
[
('①', '申込み基本情報'),
('②', '申込者分類選択'),
('③', '申込者情報入力'),
... | ba0a3e2b50de225d94e10abe5bdaadf51e95b636 | 3,631,396 |
def approx(g, nodes):
"""
Computes the approximation of g over the nodes for Simpson's method
"""
factor = g(nodes[2] - nodes[0]) / _real(6)
_sum = g(nodes[0]) + _real(4) * g(nodes[1]) + g(nodes[2])
return factor * _sum | b8d41129c251f436aad2d93c166fde744ba4128d | 3,631,397 |
import os
def _get_db_path():
"""
Return the path to the database file. If the environment variable NATURE_RECORDER_DB is set, this will be used
as the path to the SQLite database file. If not, then the default "development" database file, in the
applications data folder, is used.
:return: The p... | 86029a8d661fc8e81efebf94933820930cfa1c97 | 3,631,398 |
def get_fmtfldsdict(prtfmt):
"""Return the fieldnames in the formatter text."""
# Example prtfmt: "{NS} {study_cnt:2} {fdr_bh:5.3e} L{level:02} D{depth:02} {GO} {name}\n"
return {v:v for v in get_fmtflds(prtfmt)} | 12fbdf364f907783b13babc9ba7f3d8b618b32e5 | 3,631,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.