content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def find_connected_nodes(graph, connection):
"""List nodes connected to specified node."""
return [node for node in graph if find_path(graph, node, connection)] | 058f86fb01e4e94160772bfdc8bbb330be4e9f8a | 3,598,800 |
import logging
def bacpypes_debugging(obj):
"""Function for attaching a debugging logger to a class or function."""
# create a logger for this object
logger = logging.getLogger(obj.__module__ + '.' + obj.__name__)
# make it available to instances
obj._logger = logger
obj._debug = logger.debug... | 8f653f4f8c829271fdd5507b1a97c4ba42b0640a | 3,598,801 |
def is_non_stop_flight(flight_id):
"""
_nonstop(x)
:entity_type flight_id
"""
processed_flight_id, entity_type = process_entity_string(flight_id, "flight_id")
sql = 'SELECT flight.flight_id FROM flight WHERE flight.stops = 0 AND flight.flight_id = %s' % (
processed_flight_id)
results... | 6a70058547952e6bfb21c805e90b2cb9d973db38 | 3,598,802 |
from glob import glob
from numpy import sort
import six
def _ensure_mfdataset_filenames(fname):
"""Checks if grib or nemsio data
Parameters
----------
fname : string or list of strings
Description of parameter `fname`.
Returns
-------
type
Description of returned object.
... | 1764cf93a766bfd646578bdc5d5cb83585072d4f | 3,598,803 |
def part2(puzzle, dist_limit=10000):
""" Solve part 2 """
coords = parse(puzzle)
def total_dist(p):
return sum(manhattan_dist(p, c) for c in coords)
def in_bounds(p):
return total_dist(p) < dist_limit
median = (lesser_median(p[0] for p in coords), lesser_median(p[1] for p in coord... | 71d1a44ff4135a236371a5e65da21d72825d8d37 | 3,598,804 |
def check_oplog(con, warning, critical, perf_data):
""" Checking the oplog time - the time of the log currntly saved in the oplog collection
defaults:
critical 4 hours
warning 24 hours
those can be changed as usual with -C and -W parameters"""
warning = warning or 24
critical = criti... | 7615347c96ce723b2208b95034b41e45d84f53d4 | 3,598,805 |
def get_meeting_aggregates(meeting_data):
"""
Aggregates the attendance counts and lines said for users across
a meeting category
"""
meeting_aggregate = {}
for meeting_name in meeting_data.keys():
meeting_users = {}
for meeting in meeting_data[meeting_name]:
for user... | b135016b05fc20ae0fa9dfc40d11cc51ffc7a8d0 | 3,598,806 |
import types
import itertools
import tqdm
def load_records(fp_in, slice_idxs=None, media_record_type=types.MediaRecord.SHA256, verbose=False):
"""Loads JSON or Pickle mapping data based on file extension
:param fp_in: (str) of serialized items
:param mapping: enum of ItemMappingType
:returns: (dict) of mapped... | be5f2e96525d391e3d8196d6220224daffb4b5fb | 3,598,807 |
def generate_regnet(w_a, w_0, w_m, d, q=8):
"""Generates per block ws from RegNet parameters."""
assert w_a >= 0 and w_0 > 0 and w_m > 1 and w_0 % q == 0
ws_cont = np.arange(d) * w_a + w_0
ks = np.round(np.log(ws_cont / w_0) / np.log(w_m))
ws = w_0 * np.power(w_m, ks)
ws = np.round(np.divide(ws,... | 2c4d6862c66ee202350f220a1c5949582e7fdc6a | 3,598,808 |
def subsample_epsdelta(eps,delta,prob):
"""
:param eps: privacy loss eps of the base mechanism
:param delta: privacy loss delta of the base mechanism
:param prob: subsampling probability
:return: Amplified eps and delta
This result applies to both subsampling with replacement and Poisson subsam... | 4a7e994ced04dc6de1fe1f9f1d910e75726be1c1 | 3,598,809 |
import os
import requests
import logging
import functools
def dl_files(base_url, release, database, out_dir, threads):
"""
List files from url and download all available
"""
# output directory
out_dir = os.path.join(out_dir, release, database)
if not os.path.isdir(out_dir):
os.makedirs... | 34509093a62c4cd5fbe8286700e7da09cba2559b | 3,598,810 |
def list_to_group_count(input_list):
"""
List to item occurrences count dictionary
"""
group_count = {}
for input_item in input_list:
if input_item in group_count:
group_count[input_item] = group_count[input_item] + 1
else:
group_count[input_item] = 1
ret... | bc6714d2d0b8872e29089eb0d142517c4ef63154 | 3,598,811 |
def get_tstat_limit(stats, fdr=0.01):
"""
Function to get tval_s0 at the specified FDR.
"""
t_limit = np.min(stats[stats.fdr<=fdr].t_cut)
return(t_limit) | 4f6a0b1a6a0e67116ccf0c24f84d18743d14f048 | 3,598,812 |
def single_term(points, i):
"""Return one term of an interpolated polynomial.
Arguments:
- points: a list of (float, float)
- i: an integer indexing a specific point
"""
theTerm = Polynomial([1.])
xi, yi = points[i]
for j, p in enumerate(points):
if j == i:
cont... | 5cf3ddf2a6ebb752c75570f5c944d7285b900806 | 3,598,813 |
def validate_graph(graph, shacl_path=None, format='nquads'):
"""Validate the current graph with a SHACL schema.
Uses default schema if not supplied.
"""
if shacl_path:
with open(shacl_path, 'r', encoding='utf-8') as f:
shacl = f.read()
else:
shacl = resource_string('renk... | 43eb258a5d2d08c86f23bcc13f103b9cc32c9d47 | 3,598,814 |
from typing import Tuple
def draw_text(
np_image: ImageType, pos: Tuple[int, int], text: str, color: Tuple[int, int, int], font_scale: float = 0.4
) -> ImageType:
"""
Draw text on an image.
:param np_image: image as np.ndarray
:param pos: x, y; the position of the text
:param text: text strin... | a1e9d852969729ec42375f5bba3537ba802cde8d | 3,598,815 |
from typing import Union
from typing import Tuple
def error_middleware(
*,
default_handler: Handler = default_error_handler,
config: Config = None,
ignore_exceptions: Union[ExceptionType, Tuple[ExceptionType, ...]] = None
) -> Middleware:
"""Middleware to handle exceptions in aiohttp applications.... | 09431c9e7552cf340b28298d8008bd3907fd02b2 | 3,598,816 |
def rk4(derivs, y0, t, *args, **kwargs):
"""
Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta.
This is a toy implementation which may be useful if you find
yourself stranded on a system w/o scipy. Otherwise use
:func:`scipy.integrate`.
Args:
derivs: the derivative of the s... | 2e7648747e702ae10d1644e606db08ea7e31899c | 3,598,817 |
def get_home_dir_path(filename):
"""Resolve a filename in the user's home dir"""
return abspath(join(expanduser('~'), filename)) | 3831874fc020a41ef1fb6af792a22ff93e33ea86 | 3,598,818 |
def merge_results(rates_array, weights_array):
""" Merges rates by weights.
Parameters
----------
rates_array : List[reaction_rates.ReactionRates]
The reaction rates for each substep.
weights_array : List[float]
The weights of each substep.
Returns
-------
r_bar : react... | e3a6c1972731ed1fda3177893ff637a9c2c66e9e | 3,598,819 |
def read_table(self, pointer="TABLE"):
""" Read a table. Will first attempt to parse it as generic CSV
and then fall back to parsin git based on the label format definition.
"""
if (self.filename.lower().endswith('.fits') or
self.filename.lower().endswith('.fit')):
try: # Is it a FI... | 578c2391c82738740c062c59087f27a282249563 | 3,598,820 |
def maior_numero_lista(lista_numeros, posicao_n):
"""
Determina o maior elemento de uma lista
recebendo a posição_n de um elemento da lista
e comparando com o resto
"""
if posicao_n == 0:
return lista_numeros[0]
maior_elemento = maior_numero_lista(lista_numeros, posicao... | 25ff12d0853972ada32b6d184e98fa6395ba18a7 | 3,598,821 |
def case_transfer_similar(cased_text: str, uncased_text: str) -> str:
"""Transfers the casing from one text to another - for similar (not matching)
text.
Use `difflib.SequenceMatcher` to identify the different type of changes
needed to turn `cased_text` into `uncased_text`.
- For inserted sections... | 2dbeeb24e01464f8dc7308979a38d8e80c6c51d6 | 3,598,822 |
def findDay(pageTitle, oldDay):
"""
Find day link from CFD template.
This function grabs the wiki source of a category page and attempts to
extract a link to the CFD per-day discussion page from the CFD template.
If the CFD template is not there, it will return the value of the second
parameter... | 9c0f62b7fc390bd1de2595dd280fd45ca38e606d | 3,598,823 |
def apply_to_audio(f, clip, *a, **k):
""" This decorator will apply the function f to the audio of
the clip created with f """
newclip = f(clip, *a, **k)
if hasattr(newclip, 'audio') and (newclip.audio != None):
newclip.audio = f(newclip.audio, *a, **k)
return newclip | 88cdc94e7c999b148b8e87e9f7715992d4598a9f | 3,598,824 |
def boot():
"""Add a boot config or boot configs
Examples:
.. code-block:: python
# add a config class
@kanon.boot()
class SiteConfig(object):
def config(self, options):
group = options.group("Service settings")
_ = group.define
... | a29ce2d83ba1317cee4ca227ec2d2ee6fba394b1 | 3,598,825 |
def get_ns_from_identifiers(identifiers_ns):
""""Return a namespace compatible with INDRA from an identifiers namespace.
For example, this function can be used to map 'uniprot' to 'UP'.
Parameters
----------
identifiers_ns : str
An identifiers.org standard namespace.
Returns
-----... | 033a0605037352ddcac8995c71a1a251435cc1ea | 3,598,826 |
def _subsystem_apply_dm(state, channel, mask):
"""
Applies a channel to every subsystem indicated by a mask, by
repeatedly applying the channel to each affected subsystem.
"""
# Initialize Output Matrix
rho_out = state
# checked affected subsystems print arange(len(state.dims[0]))[mask]
... | 8de0b25c0ee01d3163e9a2403b1abb4f72c04691 | 3,598,827 |
def make_mutable_url( data_id ):
"""
Local disk implementation of the make_mutable_url API call.
Given the ID of the data, generate a URL that
can be used to route reads and writes to the data.
Return a string.
"""
global MUTABLE_STORAGE_ROOT
# replace all /'s with \x2f's
data_i... | fdeacb0de3dcb8a34d6761b13b605f843db751c0 | 3,598,828 |
def sides(m):
"""Select the sides of a mobile."""
return branches(m) | e4471ee78184d9cc97aeba812a665135b3b2b533 | 3,598,829 |
from typing import Any
def affix(orig: Any, ch: str) -> str:
"""Ensure a given character is prepended to some original value."""
if isinstance(orig, (list, tuple,)):
orig = '.'.join(map(str, orig))
return '%s%s' % (ch, str(orig).lstrip(ch)) | f5f01b7fa0e82944646dc755cfa0770cec8c72c9 | 3,598,830 |
def get_pvalues(cluster_list, annotation, gene_population):
"""
Takes a liks of clusters and an annotation file and returns
a dataframe of p-values for each cluster and each annotation term
"""
n_clusters = len(cluster_list)
# ---------------------------- population size, M -----------------------... | 7173a3ac5c2ed633e5c24a838b62e141437335dc | 3,598,831 |
def compute_lab_volume(image):
"""
Compute the perceivable color volume in LAB space as a measure for the used colors (or color flatness)
Parameters
----------
image: the image to compute the LAB space volume for
Returns
-------
LABvolume = std(L)*std(a)*std(b)
"""
lab = rgb2la... | 303d378a7ecbbe75bb6b285462d3a39484d46517 | 3,598,832 |
import yaml
def get_project_id(dataset: str) -> str:
"""Returns the GCP project ID associated with the given dataset."""
with open(f'../stack/Pulumi.{dataset}.yaml', encoding='utf-8') as f:
return yaml.safe_load(f)['config']['gcp:project'] | d951e8d2a6c96df9aa2dc15499c36f93123f8038 | 3,598,833 |
def dense_nn(x):
"""
Network used to classify MNIST digits.
:param x: tensor with shape [batch_size, 784], input to the dense fully connected layer.
:return: [batch_size, 10], logits of dense fully connected.
"""
dense_1 = tf.nn.dropout(tf.nn.relu(dense(x, input_dim, n_l1, 'dense_1')), keep_prob... | 696eabfd1b93a269c8b63465653ab3fc18bc3b02 | 3,598,834 |
import typing
import os
def unarchive_from_file(path: typing.Union[str, bytes, os.PathLike]) -> typing.Any:
"""Unarchive the given file containing a single archived root value.
:raise ValueError: If the file doesn't contain exactly one root value.
"""
with Unarchiver.open(path) as unarchiver:
return unarchi... | 5c1b8d5a278d6f7cfbf4a1f7cbe0a07b4dc91771 | 3,598,835 |
def runge_kutta(t0, y0, h, n, f):
"""
This method computes the aproximation of a differential equation based in the Runge-Kutta computational method.
param t0 The initial point to start the numerical aproximation.
param y0 The initial value of the function in the aproximation.
param h The step length for aproxima... | 130ee650e34853a87cc72579233051ce744021cd | 3,598,836 |
import re
import argparse
def __validate_address(address):
""" If address looks like a valid e-mail address, return it. Otherwise
raise ArgumentTypeError.
Args:
address(string): email address to send to
.. document private functions
.. automethod:: _evaporate
"""
if re.match('^([^@\s]+)@((?:[-a-z0-9]+\... | ebc09945e737a7d1c7c85d34dd0bf1b01dcaa587 | 3,598,837 |
def score_state(num_answer, ans_one):
"""Takes in the player's answer, and ans_one
(explained in question);
checks if the player's choice is correct
"""
#assert num_answer in [1, 2]
if num_answer == 1:
if ans_one == True:
correct = True
else:
correct = Fa... | 123a0c5f40930fe5a6dc65220c39097a55120c19 | 3,598,838 |
from typing import List
from typing import Callable
def make_transformer(
nlp: Language,
name: str,
model: Model[List[Doc], FullTransformerBatch],
set_extra_annotations: Callable[[List[Doc], FullTransformerBatch], None],
max_batch_items: int,
):
"""Construct a Transformer component, which lets... | 978e31bb0cf672b4012e5dba03b67a03190747e2 | 3,598,839 |
def generate_AA_random_walks(APP_start, apk2idx, idx2apk, apk2node, node2apk, A, BP, p, q, length):
"""
Given a starting node, generate AA random walks that have max length of 'length'
"""
APP1 = apk2node[APP_start]
APP_idx = apk2idx[APP_start]
ser = pd.Series(A[APP_idx].toarray()[0])
API1 =... | a1e100e5f167fac3e1b9decfb130fe94e557b1cc | 3,598,840 |
def req_add_from_template(req_id):
"""
Add a Request from a Template
"""
fieldnames = ["type",
"priority",
"site_id",
"purpose",
"requester_id",
"comments",
]
db = current.db
s3db = c... | 3786f41d789c72cf61cf4a971850ea225ab08dc2 | 3,598,841 |
def law_of_orbits_perihelion(a: radius, e: eccentricity) -> radius:
"""Calculate aphelion from Kepler's Law or Orbits.
Where:
R = Displacement from major body to perihelion
a = Semimajor axis
e = eccentricity
"""
logger.trace(f"BASE FUNCTION: \"law_of_orbits_perihelion\" invoked.")
R: r... | 5c1278e6fc19214f844997439dbf0a56a62e056e | 3,598,842 |
def is_anagram_v3(s, t):
"""
NOTE: THIS SOLUTION DOES NOT WORK FOR ALL CASES
e.g: s = 'ac', t = 'bb', or aa vs bb
"""
val = 0
for i in range(len(s)):
val ^= ord(s[i])
print(f"val: {val}")
val ^= ord(s[i])
print(f"val: {val}")
return val == 0 | 121c4fd1841d6372fd5a03af3ae6f74e3dfb7b25 | 3,598,843 |
def register():
"""
{"username" : "user1", "password": "123qwe", "type"=0}
"""
data = request.json
username = data["username"]
password = data["password"]
type = int(data["type"])
user = User(username=username, password=password,type=type)
db.session.add(user)
try:
db.ses... | 3a50ecdae06a7ff02c706a33737b44ffd55a1a32 | 3,598,844 |
import os
def get_path(path='.'):
"""
:type path: str
:param path: relative path from this file
"""
return os.path.abspath(
os.path.join(
os.path.dirname(__file__),
path,
),
) | 76f3074421d3241e1cc8235587696ea0ee6edd77 | 3,598,845 |
import hmac
def verify_hmac_sha1(request):
"""Verify a HMAC-SHA1 signature."""
base_string = generate_signature_base_string(request)
sig = hmac_sha1_signature(
base_string, request.client_secret, request.token_secret)
return hmac.compare_digest(sig, request.signature) | 31b8c5843b4587d078d512e4f821e093e1b80543 | 3,598,846 |
from typing import Any
import sympy
import numpy
def vyxalify(value: Any) -> Any:
"""Takes a value and returns it as one of the four types we use here."""
if isinstance(value, sympy.core.numbers.Integer):
return int(value)
elif is_sympy(value):
return sympy.nsimplify(value.as_real_imag()[... | 86db306af2eeec8b49cff82af878240f156a0bb2 | 3,598,847 |
def low_frequency_turn_over_power_law(v, vc, a, c, beta, v0):
"""power law with low-frequency turn-over:
.. math::
S_v = c \\left( \\frac{v}{v0} \\right)^{a} \\exp\\left [ \\frac{a}{\\beta} \\left( \\frac{v}{vc} \\right)^{-\\beta} \\right ]
Parameters
----------
v : `list`
Frequenc... | d97e218f5ddfebac21dfe6eba73686aadda6457a | 3,598,848 |
import six
def OverrideProjectIdToProjectNumber(request):
"""Returns an updated `request` with the Cloud project number."""
resource, resource_name = GetResourceInfo(request)
project_id = DeriveProjectFromResource(resource)
project_number = ProjectIdToProjectNumber(project_id)
setattr(request, resource_name... | 595407ca014ad2152729bfb07aa27cc2f249dcaf | 3,598,849 |
def arg_name2cli_name(arg_name: str) -> str:
"""
Convert a snake_case argument into a --kabob-case argument.
"""
return "--" + arg_name.lower().replace("_", "-") | 541601ae07b09acdd2d33487517159cd3cbd6125 | 3,598,850 |
import json
def search_descriptor(request):
"""
Filters descriptors by name.
@todo could needs pagination
"""
filters = json.loads(request.GET['filters'])
page = int_arg(request.GET.get('page', 1))
descriptors = None
if filters['method'] == 'ieq' and 'name' in filters['fields']:
... | addf289fa5688c881d2c2a7cfdd88282cbae2123 | 3,598,851 |
from typing import Tuple
from typing import Any
def _basic_computation_tracincp_fast(
influence_instance: TracInCPFast,
inputs: Tuple[Any, ...],
targets: Tensor,
):
"""
For instances of TracInCPFast and children classes, computation of influence scores
or self influence scores repeatedly calls... | 4bf9df9d035b9d901a17a505399d3101c29d50ac | 3,598,852 |
def get_split_counts(df: pd.DataFrame):
"""Returns number of rows for each data split type given dataframe."""
assert constants.SPLIT_KEY in df.columns
return df[constants.SPLIT_KEY].value_counts().to_dict() | 470ca5cd0cbe247e0abc32ad4a002b9538520eae | 3,598,853 |
import requests
from datetime import datetime
def erc20_address_call(address):
"""API call to etherscan for an ethereum wallet
and returns the total positive count of remaining erc-20 coins
in the wallet"""
address = str(address)
url = "http://api.etherscan.io/api?module=account&action=t... | 0bebb4c96cd49b54c70b3f54605f230a97254647 | 3,598,854 |
def get_num_lines(input_src):
"""Count number of lines in file.
Args:
input_src: input file
Returns: number of lines
"""
# get number of lines
num_lines = 0
with open(input_src, "r", encoding="utf-8") as in_file:
try:
for line in in_file:
num_lin... | 4c1e9fdc1e67bb6e26a6c342d6c1a8ff077a26c4 | 3,598,855 |
import os
import torch
def load_checkpoint(path, model, optimizer, scheduler, verbose=None):
"""Loads intermediate state of the training procedure from file.
Parameters
----------
path : str
Path to saved parameters.
model : nn.Module
Pytorch model.
optimizer : Pytorch Optimiz... | 6ada8093fccbfe9645cbbc91d25a388e15218bd4 | 3,598,856 |
def _label_check(label_string: str, search_label: str):
""" Mask labels with Booleans that appear in row """
for label in label_string.split(' '):
if search_label == label:
return True
return False | 084d23321133dfcd9d8f819e8209165d1cac2c15 | 3,598,857 |
def lp(m, n):
""" Create a linear program with random equality constraints and
non-negative inequality constraints """
_x = np.maximum(0.0, np.random.randn(n))
# inequality constriants
A1 = -np.eye(n)
b1 = np.zeros(n)
# equality constraints
A2 = np.random.randn(m, n)
b2 = A2.dot(... | 892cd6abccfe70b58d274bd2fb0f74ac3e62f495 | 3,598,858 |
def get_strategies_properties():
"""
A function that returns a data frame with the strategies of the Axelrod
library and for each strategy it's property.
"""
axl_strategies = pd.DataFrame(
columns=[
"Name",
"Stochastic",
"Memory_depth",
"Make... | ab2f2a5d8c8f2c59e211d7a6bd8550fc80215ecf | 3,598,859 |
from scipy.optimize import minimize
from scipy.spatial.distance import pdist, squareform
def spring_layout(p, c0=0.2, c1=1.0):
"""Calculate points positions for Pharmacophore depiction using spring
layout.
Args:
p (Pharmacophore): model to depict
c0, c1 (float, optional): coefficients for s... | a3fc0bfd1451d63b28af0c2161a853469b471584 | 3,598,860 |
def flat_concat(xs):
""" From SpinningUp: Merges list of tensors into one (X,) tensor. """
return tf.concat([tf.reshape(x, (-1,)) for x in xs], axis=0) | 049756c1f929ab72264097c382b750602b1a61f1 | 3,598,861 |
import sys
def get_size(obj, seen=None) -> int:
"""Recursively finds size of objects
https://gist.githubusercontent.com/bosswissam/a369b7a31d9dcab46b4a034be7d263b2/raw/f99d210019c1fac6bb46d2da81dcdf5ef9932172/pysize.py"""
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id... | bbe8a1cbdbf170d1d93fe2168f44415fbd681fc3 | 3,598,862 |
import time
import PIL
def upscale_image(model, img):
"""Predict the result based on input image and restore the image as RGB."""
ycbcr = img.convert("YCbCr")
y, cb, cr = ycbcr.split()
y = img_to_array(y)
y = y.astype("float32") / 255.0
input = np.expand_dims(y, axis=0)
start = time.time... | f7be50cb2eff48e9727baa641d3b170ed69f4c1f | 3,598,863 |
def _create_instantiation_proposal(tran_prop_req, chain):
"""Create a chaincode instantiation proposal
This involves assembling the proposal with the data (chaincodeID,
chaincode invocation spec, etc.) and signing it using the private key
corresponding to the ECert to sign.
:param tran_prop_req: se... | f4ef3cbd057c58a0fdb5ca0adf08d22f151b3709 | 3,598,864 |
def flip_nested_dict(nested_dict):
"""Flip nested dictionary inside out."""
flipped = dict()
for key, subdict in nested_dict.items():
for k, v in subdict.items():
flipped[k] = flipped.get(k, dict())
flipped[k][key] = v
return flipped | c1ddbe48a158ed4a96db3b33deb2f423afd304fe | 3,598,865 |
def atr(df, window, high_col="High", low_col="Low", price_col="adj_close"):
"""Average True Range, measuring price volatility.
Parameters:
-----------
df : DataFrame
Input dataframe.
window : int
Length of rolling window for calculation of the ATR.
high_col : str
Column ... | afb6338e33a5c1ab4d4200f43429c3ff0cb9a7cc | 3,598,866 |
def queryConferences(self, request):
"""Query for conferences."""
conferences = Conference.query()
# return individual ConferenceForm object per Conference
return ConferenceForms(
items=[self._copyConferenceToForm(conf, "") \
for conf in conferences]
) | 933e601a8df63564228a015412169cb214bcd65d | 3,598,867 |
def get_users(client):
"""Return the db containing users metadata.
Parameters
----------
client --> pymongo.mongo_client.MongoClient class, MongoDB client
Returns
-------
metadatafs['fs'] --> pymongo.collection.Collection, reference to collection users
"""
#get the MongoDb ... | bd2f0b60781e27a23f015f7a7573821a0e2b8ef0 | 3,598,868 |
def read_raw_values(datasize, datastore, test):
"""read the raw data for a given test"""
in_file_name = str(datasize) + '/' + datastore + '_' + test + '.csv'
return [int(line.strip()) for line in open(in_file_name)] | 1d724b873ee0ccf50d2027df79a2d32472e7942a | 3,598,869 |
def nwi_add_color(fc):
"""Converts NWI vector dataset to image and add color to it.
Args:
fc (object): ee.FeatureCollection
Returns:
object: ee.Image
"""
emergent = ee.FeatureCollection(
fc.filter(ee.Filter.eq('WETLAND_TY', 'Freshwater Emergent Wetland')))
emergent = em... | 9e01958cb02c48b9bb45bb9d4b084dde443ab1ea | 3,598,870 |
import requests
import json
def get_exchange_balances(
asset: str, exchange: str, interval: str, since: int, until: int
) -> pd.DataFrame:
"""Returns the total amount of coins held on exchange addresses in units and percentage.
[Source: https://glassnode.com]
Parameters
----------
asset : str... | f2c94a9915429dfaf78f6b973f5cda848cca4b05 | 3,598,871 |
from datetime import datetime
async def calculate_maintenance_times():
"""
calculate_maintenance_times: Calculates the proper times for maintenance and
:return: - If there's maintenance, a list of the times as tuples as follows:
[
(JST_START_TIME, JST_END_TIME),
... | fec5e1f8746dc7e3c70cb057d9f7d211732a27ca | 3,598,872 |
def TrimMu(Stot, oldmu, thresh, norm=True):
""" Remove mu measurements below the threshold and adjust mu measurements
above the threshold to unity if we seek P(mu > thresh). """
trim = oldmu > thresh
if norm:
oldmu[:] = 0
oldmu[trim] = 1
else:
oldmu = oldmu[trim]
St... | 2a986599a6116b104b839d8b664f0caff57b1aee | 3,598,873 |
def getMultiData(channel, startTime, endTime):
""" getting multiple values - in progress, testing mode"""
channels = ["25m:guider:probe:exposureID", "25m:guider:probe:probeID",
"25m:guider:probe:flags"]
archiver.scan_archives()
data0, data1, data2 = archiver.get(channels, startTime, end... | 636388fa4341ee66b72f9da3b41ab5a32a21e8ab | 3,598,874 |
async def async_setup(hass: HomeAssistant, yaml_config: ConfigType) -> bool:
"""Activate the emulated_hue component."""
local_ip = await async_get_source_ip(hass)
config = Config(hass, yaml_config.get(DOMAIN, {}), local_ip)
await config.async_setup()
app = web.Application()
app["hass"] = hass
... | 6b0d929b201ede8527f3f4a56b1e93a2c7220599 | 3,598,875 |
def phase(x,period):
"""phase(x,period) returns the phase of location x with respect to the module with spacing period. The phase is between 0 and 1."""
return np.mod(x/float(period),1) | 2b0929d892abd0444a31274adb0f574e34e46014 | 3,598,876 |
def geo_rect(pnt1, pnt2):
"""Generate geo string (Rectangle) for mysql"""
_p1 = range(0, 2)
_p2 = range(0, 2)
_p1[0] = min(pnt1[0], pnt2[0])
_p1[1] = min(pnt1[1], pnt2[1])
_p2[0] = max(pnt1[0], pnt2[0])
_p2[1] = max(pnt1[1], pnt2[1])
return ' GeomFromText(\'Polygon(({0} {1}, {0} {3}, {2... | d47873a7dd1de36b229fb4e26c64a6647b2589b6 | 3,598,877 |
import numpy
def eval_h(x, lagrange, obj_factor, out):
"""Hessian of the Lagrangian
L = obj_factor * f + <lagrange, g>,
where <.,.> denotes the inner product.
"""
out[-1] = 0.0
out[:-2:2] = obj_factor * (2.0 + 400.0 * (3.0 * x[:-1] * x[:-1] - x[1:]))
out[:-4:2] -= lagrange * (2.0 + x[:-2])... | 5864ec66b160a98a75c62cdafc859a87e7e7795f | 3,598,878 |
def translate(speech):
"""
Translate the given speech
:param speech: the string text being given
:return: the returned string changed based on the language
"""
translator = Translator()
word = translator.translate(speech, dest='zh-cn')
print(word.text)
return word.text | 420356ce971807937fed7c9223ec0ef699c4ad6e | 3,598,879 |
def preprocess(dataframe):
"""Converts categorical features to numeric. Removes unused columns.
Args:
dataframe: Pandas dataframe with raw data
Returns:
Dataframe with preprocessed data
"""
dataframe = dataframe.drop(columns=UNUSED_COLUMNS)
# Convert integer valued (numeric) colum... | 7aaf7065d5486e995701513705bb80d463e6b5e0 | 3,598,880 |
def get_training_roidb(imdb):
"""Returns a roidb (Region of Interest database) for use in training."""
# if cfg.TRAIN.USE_FLIPPED:
# print 'Appending horizontally-flipped training examples...'
# imdb.append_flipped_images()
# print 'done'
print 'Preparing training data...'
if cf... | 6fdeb92c4f968155ecb0a3b26ee501103b9503c7 | 3,598,881 |
import collections
def mkparts(sequence, indices=None):
"""
Make some parts from sequence by indices
:param sequence: indexable object
:param indices: index list
:return: [seq_part1, seq_part2, ...]
"""
indices = indices or [1]
result_list = collections.deque()
start = 0
seq_le... | 710841ca3861a33382b6243579eec07f866eb965 | 3,598,882 |
def log_minor_tick_formatter(y: int, pos: float) -> str:
""" Provide reasonable minor tick formatting for a log y axis.
Provides ticks on the 2, 3, and 5 for every decade.
Args:
y: Tick value.
pos: Tick position.
Returns:
Formatted label.
"""
ret_val = ""
# The posi... | a378bd94ceab8698a45403544a728c6c29b402c9 | 3,598,883 |
def s_and_were_or_just_was(parameter):
"""a utility function for grammatical correctness [and DRY, i.e. Don`t Repeat Yourself]"""
return ("s were" if parameter != 1 else " was") | e4d1c03565e89b9b8ecba0137e1b0b9e3bcafa40 | 3,598,884 |
from typing import Union
from pathlib import Path
from typing import Any
from typing import TextIO
def fopen(filepath: Union[str, Path], *args: Any, **kwargs: Any) -> TextIO:
"""Open file.
Args:
filepath (Union[str, Path]): filepath
Returns:
TextIOWrapper: buffer text stream.
"""
... | fcf4ccf53c99a390ceaa9b27f86a7e3f4cff3af1 | 3,598,885 |
import html
def common_null_warning_html(text, alignment="center", top_margin=50):
"""
Get a null warning html block which can be used across all apps. Useful for
when no text is entered into a box, etc.
Args:
text (str): The null warning text.
alignment (str): Either "center" or "lef... | cf9d15b453778d9615da60a5f208c1fbc2a20f57 | 3,598,886 |
import sys
import os
def _terminal_supports_colors() -> bool:
"""
Returns True if the running system's terminal supports color, and False
otherwise.
"""
plat = sys.platform
supported_platform = plat != 'Pocket PC' and (plat != 'win32' or
'ANSIC... | 4397cc5c8cf0f57f0fbbd9f44deb9d26b24a3072 | 3,598,887 |
def calc_base_rate(data, training=True):
"""Calculates the base-rate for intelligent parameter initialization from the training data."""
suffix = 'train' if training else 'test'
in_key = suffix + '_time_in_seq'
out_key = suffix + '_time_out_seq'
valid_key = suffix + '_event_in_seq'
dts = (data[... | 372680ce7b66a1d370531ab8c3f9ee71f9a48cd9 | 3,598,888 |
def train_model(train_vectors, train_target, model_name):
"""
To train model based on passed data and model name
:param train_vectors: A vector of training data after applying operation of preprocess.py
:param train_target: Corresponding target variable for training data
:param model_name: name of m... | 341e8b08695110f8f6eab6d872e708a7dde6599d | 3,598,889 |
def getConnectionDetailsById(connectionServiceId):
"""
Get Details of a connection
TODO: need to add v2 call, this was missed in last api upgrade
Author:
David J. Stern
Date:
DEC 2017
Parameters:
connectionServiceId: (str): Vendor connection id to query
... | e8d93917f2d0c55a58d9bcfbabc873dd107e1158 | 3,598,890 |
def sql_update(sql):
""" Updates data in table """
string = ''
try:
conn = None
rows = 0
try:
# connect to the PostgreSQL database and create cursor
conn, cur = sql_login()
# execute the UPDATE statement
cur.execute(sql)
#... | 998d7e49d909251593071d1f2790affcfc77b80c | 3,598,891 |
import os
def main(loc):
"""
(str) -> int
Detect faces on all images in location
"""
for filename in os.listdir(loc):
img = cv2.imread(filename)
write_info(loc, filename, find_face(img))
return 0 | 28736bca27e6c1e9e3050d7d55fea337f51788e9 | 3,598,892 |
def sample_conditional(category):
"""Samples a drawing for the given category."""
def encode(session, eval_model, input_strokes, length):
strokes = to_big_strokes(input_strokes, length).tolist()
strokes.insert(0, [0, 0, 1, 0, 0])
seq_len = [len(input_strokes)]
return session.run(... | a069819ad248fd27a387a05b681be44de7ef98f7 | 3,598,893 |
def wikify(value):
"""Makes WikiWords"""
return replace_wikiwords(value) | a6f07a01eaf39cc0240f5bddde76f4e7d1153540 | 3,598,894 |
import os
import logging
import uuid
import pprint
import json
from typing import IO
def job_resource_create_and_setup_logs(job_root_dir, bg, task_opts, workflow_level_opts, ep_d):
"""
Create job resource dirs and setup log handlers
:type job_root_dir: str
:type bg: BindingsGraph
:type task_opts:... | 9489ba6647865ec43114864a8c077043d6852e3c | 3,598,895 |
def d_dz_mid(quantity):
"""Derivative applied to quantity at mid level"""
return_value = np.zeros(
[quantity.shape[0], quantity.shape[1]+1], dtype=quantity.dtype)
return_value[1:-1] = quantity[:, 1:] - quantity[:, :-1]
# in CLUBB it is assumed quantities are linear outside of their range at
... | 878482e4d704c97f27f9c0bb067f79f3ae186b3f | 3,598,896 |
def merge(line):
"""
Helper function that merges a single row or column in 2048
line: list like [8, 0, 16, 0, 16, 8]
returns: merged list [8, 32, 8, 0]
loop cur pos and index in list:
if two equal numbers seperated by 0s, double the previous index and replace number at current position with ... | ad43cd74f991490a2fd1ce18a68ae360534c9fd7 | 3,598,897 |
from datalad.utils import getargspec
def update_docstring_with_parameters(func, params, prefix=None, suffix=None,
add_args=None):
"""Generate a useful docstring from a parameter spec
Amends any existing docstring of a callable with a textual
description of its paramet... | 6b7786102803320ff63331843a31d6ae8a95e208 | 3,598,898 |
import signal
def signal_number_to_name(signum):
"""
Given an OS signal number, returns a signal name. If the signal
number is unknown, returns ``'UNKNOWN'``.
"""
# Since these numbers and names are platform specific, we use the
# builtin signal module and build a reverse mapping.
signal... | cc17db79f6e47b25e9ec5b9c33fb8d7bf7c0ad26 | 3,598,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.