content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def pressure_to_eta(del_p, wavenumber, device_d, water_d):
"""Convert the non-hydrostatic pressure to height above device_d=0."""
return del_p / _coefficient(wavenumber, device_d, water_d) | 26718e66164d236ae8d8f7b5bd1618b4a36ccefd | 3,602,600 |
def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[],init_weight=True):
"""Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights
Parameters:
net (network) -- the network to be initialized
init_type (str) -- the name of an... | b8d5e6185b247cc96b2774479aa065c7a5211b70 | 3,602,601 |
def confirm_pw(username, pw, pw_hash):
"""Verify a password for a given user."""
salt = pw_hash.split(',')[0]
return make_pw_hash(username, pw, salt) == pw_hash | a479b45499701ccdd82d596eef99cb6f0c063bc2 | 3,602,602 |
def documents_create(bucket_name, documents, session=None):
"""Create a set of documents and associated bucket.
If no changes are detected, a new revision will not be created. This
allows services to periodically re-register their schemas without
creating unnecessary revisions.
:param bucket_name:... | 1a906d39988d829528af6ab3f5f0ecb6d7f39a40 | 3,602,603 |
def run_bandit(params, means, variances, experiment):
"""
Performs the bandit->environment->attacker interaction for a number of trials.
Arguments:
params (Python dict): holds parameter values of interest (see main.py)
means (np.ndarray (n_arms,)): mean of the reward distribution assoc... | 293dae01227319f7924b21bd837bd10708cff85b | 3,602,604 |
def predicted_effects_for_variant(
variant,
transcript_id_whitelist=None,
only_coding_transcripts=False,
only_coding_effects=False,
require_mutant_protein_sequence=False):
"""
For a given variant, return its set of predicted effects. Optionally
filter to transcripts w... | 69ea8e1b078d0e0bac9759d744f64b823009f26a | 3,602,605 |
from typing import Tuple
def __coord_on_finish(
piece_number: int, player_number: int, piece_progress=0
) -> Tuple[int, int]:
"""Piece number is irrelevant
>>> __coord_on_finish(1, 0, 57)
(9, 3)
>>> __coord_on_finish(1, 0, 61)
(9, 7)
>>> __coord_on_finish(1, 1, 57)
(3, 9)
>>> _... | 41dac0a68d63fe738726c2a97bddaa236a536766 | 3,602,606 |
def _extract_spots_outside_foci(cell_cyt_mask, spots_out_foci):
"""
Extract spots detected outside foci, in a specific cell.
Parameters
----------
cell_cyt_mask : np.ndarray, bool
Binary mask of the cell with shape (y, x).
spots_out_foci : np.ndarray, np.int64
Coordinate of the ... | d4e06d9ad14ced3b8984b71c32d9d3b1e0cebaae | 3,602,607 |
def augment(im, augment_str):
"""Augments image (used for training)."""
if augment_str:
im = Image.fromarray((im * 255).astype(np.uint8))
im = make_augment(augment_str)(im)
im = np.asarray(im).astype(np.float32) / 255
return im | c35d72fc97a56ac11f31862fc7bb16bebb3a9b9e | 3,602,608 |
def aoc_string(data):
"""Read AOC string."""
length = unpack('<h', data)
return data.read(length) | a765759b94cb5cf693956d95abc07c70c839e077 | 3,602,609 |
import os
def read_markdown(*path):
"""folder_path,...,file_name"""
try:
path_com = os.path.join(*path)
if os.path.isfile(path_com):
with open(path_com, 'r', encoding='utf-8') as file:
content = file.read()
print(path_com, 'read.')
return co... | 6c0fd2e4b09e9a30c00de632e758034f01334b45 | 3,602,610 |
import dateutil
def parse_date(date_string):
"""Parse a timestamp
If it doesn't have a timezone, assume utc
Returned datetime object will always be timezone-aware
"""
dt = dateutil.parser.parse(date_string)
if not dt.tzinfo:
# assume naive timestamps are UTC
dt = dt.replace(t... | fe858fef9e454afa3352849733e9282e14be18b6 | 3,602,611 |
from re import T
def nzseel2():
"""
RESTful CRUD controller
"""
tablename = "%s_%s" % (module, resourcename)
table = db[tablename]
# Pre-populate Inspector ID
table.person_id.default = s3_logged_in_person()
# Subheadings in forms:
s3db.configure(tablename,
deletable... | e67223a2216d47b28f3175339a9ec160cf836e80 | 3,602,612 |
def End_Net(input_x, phase_depth, keep_prob):
"""
Define Aggregation Network
"""
weights, summaries = End_Net_weights_init()
layer8 = conv2d_batchnorm_init(input_x, weights[0], name="conv_9", phase= phase_depth, stride=[1,2,2,1])
layer9 = conv2d_batchnorm_init(layer8, weights[1], name="conv_1... | 06036b2d05a841e43a9970be7033ee1537671606 | 3,602,613 |
import base64
def decrypt(cipher_text, working_key):
"""
Method decrypt cc-avenue response.
:param cipher_text: encrypted data
:param working_key: working data
:return: list
"""
cipher_text = base64.b64decode(cipher_text)
iv = cipher_text[:AES.block_size]
cipher = AES.new(bytes(wo... | 8786af7539378c069690513fc665bb5d84b830ef | 3,602,614 |
from datetime import datetime
def get_start():
"""
Helper function to retrieve the start of the time period from which to gather stock data
"""
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
day = weekdays[datetime.today().weekday()]
now = datetime.today()
if day in... | d79886240011a0e7c56cf9c11c93fb8569ef57a1 | 3,602,615 |
import io
def get_custom_stopwords(stop_words_file):
"""
创建停用词list,
:param stop_words_file: 停用词文件
:return:
"""
with io.open(stop_words_file, encoding='utf-8')as f:
stopwords = f.read()
stopwords_list = stopwords.split('\n')
custom_stopwords_list = [i for i in stopwords_list]
... | d2e25e44815b6769688493a96852cc537d1127bf | 3,602,616 |
from typing import Union
def _hex(v: Union[LayerFieldsContainer, LayerField]) -> int:
"""parse the layer field as a hex string"""
# split v into octets and reverse the order
assert not isinstance(v, LayerFieldsContainer) or len(v.fields) == 1
return int(v.get_default_value(), 16) | 00e1dd102085866a44ed092fadf59e03d10eb0ba | 3,602,617 |
def read_bytes(vw, va):
"""
read up to MAX_BYTES_FEATURE_SIZE from the given address.
raises:
envi.SegmentationViolation: if the given address is not valid.
"""
segm = vw.getSegment(va)
if not segm:
raise envi.SegmentationViolation()
segm_end = segm[0] + segm[1]
try:
... | e2a94adff54cd97c7d36f661a3cd14bd18182ccb | 3,602,618 |
def extract_image_number(filename: str, from_file: bool) -> int:
"""
finds the number of the image from the original images of LITIV 2014 dataset.
:param filename: name of the image file.
:param from_file: filename is read from a ground-truth file or not.
:return: number.
"""
number = filena... | e55431beffb02959907106a01596310812ba7363 | 3,602,619 |
def subarraySum(nums, k):
"""
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
"""
count = 0
s = 0
for i in range(len(nums)):
s += nums[i]
if s % k == 0:
count += 1
return count | 6bbad5ec5511f8563fc951aa916f76a6297946ba | 3,602,620 |
def traffic_sign_detection_noisy(img_in):
"""Finds all traffic signs in a synthetic noisy image.
The image may contain at least one of the following:
- traffic_light
- no_entry
- stop
- warning
- yield
- construction
Use these names for your output.
See the instructions docume... | 50a5430fbe793a6bc863c92378c44522822ce7a3 | 3,602,621 |
import re
def extract_methods_text(article_content, par_range=4, max_words_in_heading=8, re_to_match=RE_BIOMED_METHODS_TEXT, verbose=False):
"""
Methods section detection function for raw-text content, which returns both the headings
found and the text content identified. Because we don't have much struct... | f91227c8c0fbf1538b2d1188417b565d33b81ce8 | 3,602,622 |
def get_planet_variables(mc, theta, verbose=False):
"""
Derived parameters from the Common Models are listed
:param mc:
:return:
"""
try:
n_samplings, n_pams = np.shape(theta)
except:
n_samplings = 1
stellar_values = get_stellar_parameters(mc, theta)
planet_variabl... | 573a84f22734508d22d9887155fc28604fe2079a | 3,602,623 |
def beam_rigidity(**kwargs):
"""Beam rigidity."""
# TODO: cleanup this function (and siriuspy Normalizer)
electron_rest_energy_eV = _c.electron_rest_energy * _u.joule_2_eV
electron_rest_energy_GeV = electron_rest_energy_eV * _u.eV_2_GeV
# checks arguments and make necessary conversions
if len(k... | c85dbc80385449e76bfd0a7efaf51266aeb533e8 | 3,602,624 |
def get_container_by_container_id(container_id):
"""
lookup task id based on matching container id
:param container_id: str. container_id is a unique string generated by the docker daemon
for each instance of a container
:return: str. task id
"""
if len(container_id) <= 12:
query = '... | 8e53a998e917ed6929bcee7116ebdc0f3297bddd | 3,602,625 |
def calculate_arc_length(x1, x2, origin):
"""
Calculate the arc length between points x1 and x2.
:param x1, x2: points coordinates.
:return: arc length
"""
r1 = vector.addVectors([x1, origin], [1, -1])
r2 = vector.addVectors([x2, origin], [1, -1])
radius = vector.magnitude(r1)
angle ... | cef209b2b1556700416131e56230bd37196ac956 | 3,602,626 |
def find(data,fwhm=4,thresh=4000) :
""" Star finding using DAOStarfinder
"""
daofind = DAOStarFinder(fwhm=fwhm,threshold=thresh)
sources=daofind(data)
sources.rename_column['xcentroid','x']
sources.rename_column['ycentroid','y']
return sources | befde70505c3567e86d1b33cdb22bacfab19129b | 3,602,627 |
import functools
from datetime import datetime
def cache(ttl=CACHE_DEFAULT_TTL):
""" TTL Cache Decorator
Parameters
----------
ttl: datetime.timedelta
Time-To-Live
Returns
-------
function
Wrapped Function
"""
def wrap(func):
cached = {}
@functool... | f2fbbeb4368ee629b4be4383d7ad80a49c03577f | 3,602,628 |
def make_ro_state(f):
"""
Build a read-only State instance and pass to `f` as the `state` kwarg if the `state` kwarg is None.
Function `f` should have have at least two kwargs, `user` and `state`.
"""
@wraps(f)
def state_check(self, *args, **kwargs):
state = kwargs.pop('state', None)
... | 4df20a8c81eed81b47fd10c92379ec8d58d0ec8a | 3,602,629 |
def get_changes_by_project(changes):
"""
Break changes into a dict of dicts keyed by project
"""
changes_by_project = defaultdict(dict)
for change in changes:
changes_by_project[change.project][change.long_id] = change
return changes_by_project | 76923ce721df8d68fc96ff63cf49a9aac3b0dce4 | 3,602,630 |
from typing import Any
from typing import Callable
from io import StringIO
def yaml_dumps(value: Any, get_yaml_obj: Callable[[], YAML] = get_yaml) -> str:
"""Converts the object to yaml.
:param value: the object to convert.
:param get_yaml_obj: A function such as :func:`get_yaml` that will be called
... | b12390989fc4c64722c38c8931f90906c8261991 | 3,602,631 |
def aaa_check_compute_auth_token(cookie, in_token, in_user):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("AaaCheckComputeAuthToken")
method.cookie = cookie
method.in_token = in_token
method.in_user = in_user
xml_request = method.to_xml(option=WriteXmlOption.DIRTY)
re... | 8e837e873ef4ca76f53f91e7ce92de79be568b3f | 3,602,632 |
def page_size(request, page_size):
""" Changes page size in user preferences"""
try:
u, created = User.objects.get_or_create(user=request.user.id)
u.pagesize = page_size
u.save()
return HttpResponse('saved pagesize %s' % page_size)
except Exception, inst:
return H... | 0e5bf12142d678481829ea3136d20a559db7c366 | 3,602,633 |
def fail_on_npm_install():
"""
Used to simulate an error when executing "npm install"
"""
return 1 | ea0b2b14487acf8b9833e84374de469a1b22b61a | 3,602,634 |
def calculateNetIncome(gross, state):
"""
Calculate the net income after federal and state tax
:param gross: Gross Income
:param state: State Name
:return: Net Income
"""
state_tax = {'LA': 10, 'SA': 0, 'NY': 9}
# Calculate net income after federal tax
net = gross - (gross * .10)
... | 915528d8bfd15c18003eaeb8f6b3f1e8ad5565a0 | 3,602,635 |
def calc_se3_torch_batch(poses_src, poses_tgt):
"""Bx3x4."""
# B = poses_src.shape[0]
se3_src2tgt_batch = se3_mul_torch_batch(poses_tgt, se3_inverse_torch_batch(poses_src))
return se3_src2tgt_batch | d5f2ce006ac08e8c92c463c3631a76e7574fd4c0 | 3,602,636 |
from typing import Union
def _rescale_proba(p: Union[float, pd.Series],
min: float,
max: float) -> Union[float, pd.Series]:
"""Performs min-max-scaling on a probability value"""
return np.abs((p - min) / (max - min)) | caacf603c5a02af15fd6bd640c79f3d3379d46b0 | 3,602,637 |
def build_tree(train: list, max_depth: int, min_size: int) -> dict:
"""
Build a decision tree
:param train: dataset used to build the tree
:param max_depth: of the desired tree
:param min_size: of the terminal nodes
:return:
"""
class_values = list(set(row[-1] for row in dataset))
ro... | 0a6170795677d41e0080aaff80c5758049789341 | 3,602,638 |
def field_size(field_label):
"""
Helper function to determine the size of a binary
table field
Parameters
----------
field_label : PVLModule
The field label
Returns
-------
int :
The size of the one entry in bytes
"""
data_sizes = {
'Intege... | afaff70bc18d4d9d023fb7c89d45560f1a691bcf | 3,602,639 |
def definite_range():
"""Create test fixture for Definite Range."""
return DefiniteRange(min=22, max=33) | 0296dd02adc5e890a0d6a020b1772ad0df91c76f | 3,602,640 |
import os
import csv
def _get_vocab_freqs():
"""Returns vocab frequencies.
Returns:
List of integers, length=FLAGS.vocab_size.
Raises:
ValueError: if the length of the frequency file is not equal to the vocab
size, or if the file is not found.
"""
path = FLAGS.vocab_freq_path or os.path.join... | f0491ba4556f97e8914ecdfd286795ac975cbc78 | 3,602,641 |
def WaitForOperation(resources, service, operation, collection, resource_ref,
message):
"""Waits for the operation to finish.
Args:
resources: The resource parser.
service: apitools.base.py.base_api.BaseApiService, the service representing
the target of the operation.
operati... | 90de3bc3c6d49be10aee94af6eb55fcb6cc738aa | 3,602,642 |
def ask(question,reply_y,reply_n,engine=ENGINE_DEFAULT):
"""
"""
say(msg,engine)
uinp = getch()
logger.debug("answer was : {}".format(uinp))
if uinp in ['y','Y','j','J']:
if reply_y:
say(reply_y,engine)
return 0
else:
if reply_n:
say(reply_... | 8e33c7ee4078829e1fa13732cf89de3d12c2915c | 3,602,643 |
def ListInstancesDNS(region, instances=None, node_types=[], states=[], names=[]):
"""Return a list of DNS names for instances matching the arguments.
If instance IDs are specified and one or more is not found, an EC2ResponseError exception is thrown.
"""
return [i.public_dns_name for i in ListInstances(region, ... | 20337bcbb97ca1a3602ec34276b1fb96b2e07747 | 3,602,644 |
def _calc_trans_distor(X: np.ndarray, labels: np.ndarray, Y: float) -> float:
""" Calculate transformed distortion function for the jump method """
_, means, _ = calc_stat_per_batch(X, labels)
distor = (((X - means.T[labels,:]) ** 2).sum() / X.shape[0] / X.shape[1])
trans_distor = distor ** (-Y)
re... | bcbc697833eb65c48abf9ba2e324c493a323c17a | 3,602,645 |
def _changes_available(isdsAppliance):
"""
Check for pending changes on the appliance
:param isdsAppliance:
:return:
"""
# changes = isdsAppliance.invoke_get("Get pending changes",
# "/pending_changes")
# logger.debug("Pending changes on applia... | 6add04f43540d489c87299a051ebdde10ed25e40 | 3,602,646 |
import argparse
def parse_args():
"""Parse commandline arguments into a dict."""
parser = argparse.ArgumentParser()
parser.add_argument('--output_dir', default='output')
parser.add_argument('--training_path', default=TRAINING_PATH)
parser.add_argument('--target_path', default=TARGET_PATH)
pars... | 93a41fc59732e32f796e179384180514d2b1bcc8 | 3,602,647 |
def bencode(thing):
"""
bencodes the given object, returning a bytes object
containing the bencoded data.
Allowed object types are:
- list (list)
- dictionary (dict)
- integer (int)
- string (str)
- bytes object (bytes)
Note that all strings will be converted to byte objects du... | e1c08941a37ce19873e50c33c682ecefbd24073c | 3,602,648 |
def slowSort(array):
"""Sort an array the slow (but certain) way"""
cpy = np.copy(array)
ind = np.arange(0, len(array))
for i in xrange(len(cpy)):
for j in xrange(len(cpy)):
if cpy[i] > cpy[j] and i < j:
# Swap the copy array values
tmp = cpy[i]
... | b110f6aa797c5ab64309a1e982de561445377f33 | 3,602,649 |
def GetBankElementSummary(bank_element):
""" Summarizes the bank element
params: bank_element = value of the object of type bank_element_t
returns: String with summary of the type.
"""
format_str = "{0: <#020x} {1: <16s} {2: <16d} {3: <16d}"
if bank_element.be_type == 0:
out_strin... | b14b9a9cb7744bc02958573bc22009fe075e893e | 3,602,650 |
def test_input(ctx):
"""
To get custom user input!
input: Yes/No
If yes
it stores value in user_input of context
"""
if ctx.get("user_input"):
print("We got: ", ctx.get("user_input"))
return
val = input("Say yes: ")
if val == "yes":
ctx["user_input"] = val
return RepeatStatement() | 28250a05ede180b7d8948a50d6ded526270b1b4f | 3,602,651 |
def _reference_before_setitem(self, key, value):
# type: (Object, str, Any) -> Tuple[str, Any]
"""
This hook allows for the use of any arbitrary attribute, as specified in
the `patternProperties` for this object in the OpenAPI schema
"""
if key != "$ref":
_add_property(self, key)
ret... | 38f5ff3bc96cddac89d3dea6008c9df63835d587 | 3,602,652 |
from typing import List
def _input_fn(file_pattern: List[Text],
data_accessor: tfx.components.DataAccessor,
tf_transform_output: tft.TFTransformOutput,
batch_size: int = 200) -> tf.data.Dataset:
"""Generates features and label for tuning/training.
Args:
file_pattern:... | 8afcf39ff01f8b9b3c643b4b4adccaf1c3586f4f | 3,602,653 |
def leading_by(agents, player):
"""Determine difference between player's score and closest opponent."""
scores = [a.score() for a in agents]
player_score = scores[player]
scores.sort()
if player_score == scores[-1]:
return player_score - scores[-2]
else:
return player_score - sco... | e97aa0a1109bb2ba5f276f34030ea1f93022046f | 3,602,654 |
import torch
def smiles2graph(mol):
"""
Converts SMILES string or rdkit's mol object to graph Data object without remove salt
:input: SMILES string (str)
:return: graph object
"""
if isinstance(mol, Chem.rdchem.Mol):
pass
else:
mol = Chem.MolFromSmiles(mol)
# atoms
... | 2547a07ca8f3beec6681b15c87666197fd58181a | 3,602,655 |
import os
async def reload_models(model_dict: dict, response: Response):
"""load_latest_models - endpoint for updating the transformer model
Args:
model_dict: dict; {"sentence": "bert...", "qexp": "bert...", "transformer": "bert..."}
Response: Response class; for status codes(apart of fastapi ... | b937db7f90b1a6950efe43631a1749e50a9b0236 | 3,602,656 |
def is_valid(t: float):
"""
Returns a `bool` indicating if the given value for a t
parameter is valid.
A t parameter is valid if in the [0, 1] range.
:param t: `float` t parameter value
:return: `bool` is the t value valid?
"""
return False if t < MIN or t > MAX else True | 6e3ee60136ead77a9bc4ff6b84e3986f5b0532b3 | 3,602,657 |
def get_bid2sid(offsets, stc_lens):
"""
:param offsets: list of 1 tensor, offsets by doc
:param stc_lens: list of 1 list, stc length
:return: bid2sid: dict of int, blank id 2 stc id, both start from 0
"""
bid2sid, acc_len = dict(), 0
sid = 0
for bid, offset in enumerate(offsets[0]):
... | a5a96d3ea6c7fcb17a97df706799fe0716ae659b | 3,602,658 |
import random
def generate_easy_alphanumeric_string():
"""
Generates an "easy" alphanumeric (lower case) string of length 8 without the 0 (zero)
character. This is a design decision, because users will have to type in the "easy"
string on mobile devices, so we have made this a string that is easy to t... | 76c1b5e51344f726dffcd2800b31349427268f22 | 3,602,659 |
def create_abbreviations(metagraph):
"""Creates abbreviations for node and edge kinds."""
kind_to_abbrev = find_abbrevs(metagraph.node_dict.keys())
kind_to_abbrev = {kind: abbrev.upper() for kind, abbrev in kind_to_abbrev.items()}
edge_set_to_keys = dict()
for edge in list(metagraph.edge_dict.keys(... | 98eb8c0e158b592990a4850263a93be08d41f3a4 | 3,602,660 |
import logging
import glob
import os
def get_psf_wings(instrument, detector, filtername, pupilname, wavefront_error, wavefront_error_group,
library_path):
"""Locate the file containing PSF wing image and read them in. The
idea is that there will only be one file for a given detector/filter/
... | d56ba6d2532dbeccf336527d0aaafe6372b9d2ee | 3,602,661 |
def mk_seealso(
function_name: str,
role: str = "func",
prefix: str = "\n\n",
module_location: str = ".",
) -> str:
"""
Returns a sphinx `seealso` pointing to a function.
Intended to be used for building custom fitting model docstrings.
.. admonition:: Usage example for a custom fittin... | 0165599829e8edd3f75adcda9402069066a0381a | 3,602,662 |
import torch
def get_accuracy(prototypes, embeddings, targets):
"""Compute the accuracy of the prototypical network on the test/query points.
Parameters
----------
prototypes : `torch.FloatTensor` instance
A tensor containing the prototypes for each class. This tensor has shape
`(met... | f196820e28258a24ed84a10b4829f3be6a0d68d8 | 3,602,663 |
def take_step(obj, step):
""" Takes a step towards a target obj """
temp_obj = getattr_or_get(obj, step)
if 'id' in step:
# if the step is an ID, we need to get the object represented by that id
model_str = step.split('_')[0].lower().capitalize()
if model_str != 'User':
... | 4366977af518df512c433c057bb3d675a3b8d6c9 | 3,602,664 |
def mock_xibo_api(mocker):
"""Return a mock XiboApi."""
return mocker.MagicMock() | 8c2ad1566ad716d9fb4dd680a624e59f89950a0a | 3,602,665 |
def get_corpus_archive_name(cycle: int) -> str:
"""Returns a corpus archive name given a cycle."""
return 'corpus-archive-%04d.tar.gz' % cycle | 3068ce88bd85f2c21819da697a2b1147f547c509 | 3,602,666 |
def _fn_tanh_ ( self , b = 1 ) :
""" Hyperbolic tangent function: f = tan(ab)
>>> f =
>>> a = f.tanh ( )
>>> a = f.tanh ( b )
>>> a = tanh ( f )
"""
return _fn_make_fun_ ( self ,
b ,
Ostap.Mor... | d64cab6625f9a50e2e568a5cb275e7b11d4b6b32 | 3,602,667 |
from typing import Iterable
def mpp_transformer(origin, origin_mpp, aim_mpp):
"""transform numbers according to mpp
:param origin: original numbers
:param origin_mpp: original mpp
:param aim_mpp: aim mpp
:return: transed numbers
"""
if isinstance(origin, Iterable):
transed = []
... | 64955bbc22821990e1087622b23ba46e90ab86bd | 3,602,668 |
def solve(input_grid):
"""
Here we have solve function that takes the input grid.
Every even steps we move the cells around to swap the
digits on the currently processed grid
"""
_output_grid = to_output_array(input_grid)
_, n_cols = get_shape_of_array(input_grid)
for i in range(n_cols)... | 65867f0a80314aab328180d7d070f4b0c61a3d3c | 3,602,669 |
def rank_equality(y_true, y_pred, groups):
"""Compute the rank equality error between two rankings.
Parameters
----------
y_true : array-like of shape = (n_samples)
Ground truth (correct) target values.
y_pred : array-like of shape = (n_samples)
Estimated target values.
groups... | a599e82dd1ea795dce6513b36f0fc24d379f1a8a | 3,602,670 |
def distributionCorrection(df, channel):
"""
Resample file pairs in a dataframe.
df: pd.DataFrame
channel: str
Column name of the values for resampling.
Returns:
estimated_true_positives: pd.DataFrame
To Do:
Make a more generic function, or at least pull... | 56488b5d12119c62b6f36e20f7158d57f937fff1 | 3,602,671 |
from typing import Optional
def get_cluster(arn: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetClusterResult:
"""
Resource Type definition for AWS::MSK::Cluster
"""
__args__ = dict()
__args__['arn'] = arn
if opts is None:
opts = pulum... | 888bac8b40daa72a7b27532bdc94de6f38b156d4 | 3,602,672 |
def one_step(site, DOY, herb_class, available_forage, prop_legume,
supp_available, supp, intake=None, force_supp=None):
"""One step of the forage model, with one herbivore type, if available
forage does not change."""
row = []
herb_class.calc_distance_walked(site.S, herb_class.stocking_den... | f924f6f2cc2c5bd9175254677c7ef973030edbb1 | 3,602,673 |
def array_replace(space, w_arr, args_w):
""" Replaces elements from passed arrays into the first array """
for i, w_arr in enumerate(args_w):
if w_arr.tp != space.tp_array:
space.ec.warn("array_replace_recursive(): Argument #%d "
"should be an array" % (i+1))
... | bab04d17733a12418b248e6f72e9dc053b263ac7 | 3,602,674 |
def upsample(inputs, out_shape, data_format):
"""
Upsamples to `out_shape` using nearest neighbor interpolation.
"""
if data_format == 'channel_first':
inputs = tf.transpose(inputs, [0, 2, 3, 1])
new_height = out_shape[3]
new_width = out_shape[2]
else:
new_height ... | 0916d0e1b2033690c4d38a80842795c3d7ca44b8 | 3,602,675 |
from typing import List
from typing import Tuple
def _build_visualization_data(ordering: List[Tuple[str, Node]]) -> List:
"""
Function which generates the required data structure for creating the .dot file
output of the pipeline. Creates a nested list structure which indicates when
a subgraph/cluste... | a52340dc74072a7b7856750d5b2bb1c3a394bfe7 | 3,602,676 |
from typing import Iterable
from typing import List
def _setup_config_sources(spec: YapconfSpec, cli_vars: Iterable[str]) -> List[str]:
"""Sets the sources for configuration loading
Args:
spec: Yapconf specification
cli_vars: Command line arguments
Returns:
List of configuration ... | 8f193cc03750707f330b542e3d168399ac75b07d | 3,602,677 |
def get_transform(_split):
"""Frames train(test) transformation."""
if "test" in _split or "val" in _split:
transform_fn = transforms.Compose([
transforms.Resize(cfg.TEST.IM_SIZE, interpolation=BICUBIC),
transforms.CenterCrop(cfg.TRAIN.IM_SIZE),
transforms.Normalize(... | 7433f23a2e6f4cad1be4b89ce61ee7f58e51b508 | 3,602,678 |
def _chase_up(start_time, interval):
"""Utility function to check if there are missed intervals.
:param start_time: A time object representing the starting time.
:param interval: An integer specifying the time interval in seconds.
:returns: Number of seconds to sleep before next round.
"""
end_... | cf04c16e48ba05a6d7d68841298ef1a8e5976fa6 | 3,602,679 |
def create_queries(cson_content):
"""Create the queries from the CSON configuration file
Args:
cson_content: The CSON configuration file content.
Returns:
The CSON configuration file content with key instead of description for the queries.
Raises:
ValueError: The CSON if malfo... | 628a704e16d2ccace2aa5cb487a3f28ae63043dc | 3,602,680 |
import re
def extract_airlines_from_flight_text(flight_text):
"""
:param flight_text: Raw flight text string, e.g.,
"3:45 PM – 8:15 PM+1\nUnited\n13h 30m\nSFO–PVG\nNonstop\n$4,823",
"12:51 PM – 4:50 PM+1\nDelta\nChina Southern\n12h 59m\nSEA–PVG\nNonstop\n$4,197",
"2:10 AM – 1:25 PM+1\... | 188f040c15e62f4eace72cb90ef74825c4b803fc | 3,602,681 |
import os
def get_theme():
"""Return absolute path of the JSON file for the current theme"""
# Name of current theme
defaults = ObjCClass("NSUserDefaults").standardUserDefaults()
name = str(defaults.objectForKey_("ThemeName"))
# Theme is user-created
if name.startswith("User:"):
home ... | a26c5c73d1bfb843b189b82d7c5aca7353193031 | 3,602,682 |
def find_centroid_of_flux(image, mask=None):
"""Find center of flux in an image
function giving the tuple of the position of weighted average of
the flux in a square image
indentical result as calculateCentroid from drp_stella.images
@input image poststamp image for which to find center
@in... | bc6f03c0fee7fb5cfeebb62b8a1b5646f58b8a40 | 3,602,683 |
import copy
import time
def sim_mabs_norm(algo_list: list, locs: list, scales: list, num_sims: int, horizon: int, algo_name: list,
batch: bool =False, batch_size: int =0) -> list:
"""Run simulations Multi-Armed Bandit Algorithms on rewards given by Gaussian distributions.
:param algo_list: ... | 1491ae1fd4baf7e335c24cc4974fae412ee5c440 | 3,602,684 |
def ts_to_list(ts): # Completed
"""
Helper function used to convert a pandas time
series object back to a python list object.
"""
if isinstance(ts, pd.core.series.Series):
ts = ts.values.tolist()
return ts | ea0955bb05f5a9f4b30a8571419a2b02d640d4c3 | 3,602,685 |
def get_inputs(inputs, mask=None):
"""Extract and normalize the arrays from inputs"""
gmax = inputs[0][:,:,1].max()
o = inputs[0][:,:,0]/gmax
n = inputs[1][:,:,0]/gmax
return o,n | 329dfce70d65dec8d5f177239b7f88c977519867 | 3,602,686 |
import torch
def _bbox_pre_decode(points: torch.Tensor, bbox_pred: torch.Tensor,
stride: torch.Tensor):
"""compute real bboxes."""
points = points[..., :2]
bbox_pos_center = torch.cat([points, points], dim=-1)
bboxes = bbox_pred * stride + bbox_pos_center
return bboxes | 27aec66f69c31e1147dc544808f4ce10954b1272 | 3,602,687 |
def return_data():
"""Return the images data
Params:
None
Returns:
(array): containing data informations of image
"""
path_csv = '20200416_2'
figures = []
dict_results = daily_average(path_csv)
figures.append(dict_results['figure'])
figures.append(weekly_percentage(... | 2a167aa8e4262b006e3c83e881166a867d90eebc | 3,602,688 |
import os
def get_cache_dir():
"""Get the cache directory."""
if CACHE_DIRECTORY_KEY in _config:
return _config[CACHE_DIRECTORY_KEY]
return os.path.join(get_state_dir(), CACHE_DIRECTORY) | 2e9012c2532ca1ba3a409a74d5a60b58dccc7bc5 | 3,602,689 |
def formatTime(t):
"""Check if hour, minute, second variable has format hh, mm or ss if not change format.
:param t: string time hh, mm or ss
:return: string time in correct format eg. hh=02 instead of hh=2
"""
if len(t) < 2:
t = "0" + t
return t | 8011fc25a001964af1f1e0b0cb4e54f7d7aec721 | 3,602,690 |
def song_value(songtitle, artist, chart):
""" Returns the value of a song in a chart
Run through one billboard chart objekt and return the "value" of the song
with the specified title and artist in this chart.
If the song is not on the chart 0 is returend.
... | 637b5a83938729e1ecf131804c12f38f7aba6247 | 3,602,691 |
def extract_patches(path, numPatchesPerImage, patchSize):
"""
:param path: path to a RGB fundus image
:param numPatchesPerImage: number of patches to extract per image
:param patchSize: patch is nxn size
:return: patches: matrix with an image patch in each row
"""
img = load(path)
img ... | f6d1b111bde5c5cc695ff79d7a4cccec82f225bf | 3,602,692 |
def integrate(values, ax_val, index, Nper, is_aper, is_phys, is_mean=False):
"""Returns the integral of values along given axis
Parameters
----------
values: ndarray
array to integrate
ax_val: ndarray
axis values
index: int
index of axis along which to derivate
Nper:... | ac213f3f78ef32908055bfcc931cc3359234f6a4 | 3,602,693 |
def processImage(path, regions, ftypes, fiducials, outparams, fmtdict):
"""Processes a single image and returns a feature vector, or raises an Exception"""
fc = FeatureComputer(mstr=regions, fstr=ftypes)
fvec = fc.compute(path, fiducials=fiducials, outparams=outparams, fmtdict=fmtdict)
return fvec | 801fe0c4742e606866ac5aff6e02eb59cb956e33 | 3,602,694 |
def _create_connection(network, ip_address, mac_address, ip_allocation_mode,
primary_interface=False, nic_order=0):
"""
repack fields to dict
"""
return {'network': network,
'ip_address': ip_address,
'mac_address': mac_address,
'ip_allocatio... | da2c38d853ab9ba458031265e6ca6d33f2a54185 | 3,602,695 |
def rf_tile_stats(tile_col):
"""Compute the Tile-wise floating point statistics"""
return _apply_column_function('rf_tile_stats', tile_col) | 96fab4598cb001fae06c9f14cc748802b2b63309 | 3,602,696 |
def resize(x: np.ndarray, factor: float=2)-> np.ndarray:
"""
resizes an image by the factor. If factor
< 1, reduces the size, >1 increases the size
This doesn't perform interpolation
Parameters
-------------
x: np.ndarray
an image as an array
factor: float
the resize fa... | 723c0f338ba07f6b62f8e51a6f6d3fcb45e923db | 3,602,697 |
def _cluster_quality_sumsquares(data, clusters):
"""Within-clusters sum of squares
"""
min_distance = np.min(_cluster_quality_distance(data, clusters), axis=1)
return np.sum(min_distance**2) | 04f7156550133896551c20a1b6ad8805d9952c9b | 3,602,698 |
def remove_signature(message):
"""Remove the 3 Letter signature and the '/' found at the beginning of a valid message"""
return message[1:] | a802dc5abfea09e05fad51936dd76e17719900e7 | 3,602,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.