content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from datetime import datetime
def _read_housekeeping(fname):
"""Reads housekeeping file (fname; csv-format) returns a pandas data frame instance."""
print('reading %s'%fname)
try:
df = pd.read_csv(fname, error_bad_lines=False)
except ValueError:
return False
# data = df.values
# ... | b41a492f497a9a3220d52968d2a94466c7973673 | 31,300 |
import math
def get_line_equation(segment_point0, segment_point1):
"""
Ax + By + C = 0
:param segment_point0: Point
:param segment_point1:
:return: A, B, C
"""
x0, y0 = segment_point0.px, segment_point0.py
x1, y1 = segment_point1.px, segment_point1.py
a, b, c = y1 - y0, x0 - x1, x... | 9e0b35f2cac4c7a5835755878fd8aa5d32735699 | 31,301 |
def keep_lesser_x0_y0_zbt0_pair_in_dict(p, p1, p2):
"""Defines x0, y0, and zbt0 based on the group associated with the
lowest x0. Thus the new constants represent the point at the left-most
end of the combined plot.
:param p: plot to combine p1 and p2 into
:param p1: 1st plot to combine
:param p... | 4dc7c008e86606b4257980f59b12fc6a183e060f | 31,302 |
from typing import List
from typing import Dict
from typing import Optional
def build_csv_from_cellset_dict(
row_dimensions: List[str],
column_dimensions: List[str],
raw_cellset_as_dict: Dict,
top: Optional[int] = None,
line_separator: str = "\r\n",
value_separator: str... | b6f40a97f14da3c37d63b6bfd545dc95fa61240e | 31,303 |
def get_stages_from_api(**kwargs):
"""
This is the API method, called by the appConfig.instantiate method
"""
resp = utils.request(utils.RETRIEVE, 'stages', kwargs)
return utils.parse(resp) | 03e6ae52b0e3e18bd107b5bf0069ccaa6c01b322 | 31,304 |
import numpy
import numba
def fill_str_array(data, size, push_back=True):
"""
Fill StringArrayType array with given values to reach the size
"""
string_array_size = len(data)
nan_array_size = size - string_array_size
num_chars = sdc.str_arr_ext.num_total_chars(data)
result_data = sdc.str... | 5dc586a7334bdae73145574fa9afb2f939f1808e | 31,305 |
def _visible_fields(user_profile, user, configuration=None):
"""
Return what fields should be visible based on user's preferences
:param user_profile: User profile object
:param user: User object
:param configuration: A visibility configuration dictionary.
:return: whitelist List of fields to b... | 43e9b0f03ebee891681a6c3cf7892c5dab36e5f0 | 31,306 |
def open_dataframe():
"""
Function to open the dataframe if it exists, or create a new one if it does not
:return: Dataframe
"""
print("Checking for presence of data file......")
try:
datafile = './data/data.csv'
dataframe = pd.read_csv(datafile)
print("File found.... loa... | 8f6bbed1e57df7a1567863c4ecd3bc4656901727 | 31,307 |
import logging
def parse_manifest_v3(manif, manifest_info, opts):
"""
parse IIIF V3 manifest for annotations
"""
annotation_info = manifest_info['annotations']
canvas_ids = set()
annolist_idx = 0
if manif.get('type', None) != 'Manifest':
raise ValueError("Manifest not of type ... | 6596af85090cb6f1b9908f6b6e34c0b02b216fae | 31,308 |
import fnmatch
def zipglob(sfiles, namelist, path):
"""Returns a subset of filtered namelist"""
files = []
# cycle the sfiles
for sfile in sfiles:
# we will create a list of existing files in the zip filtering them
# by the sfile filename
sfile.zfiles = fnmatch.filter(namelist,... | 818e9a7598ba0827616061bbfed80e345d1e22a5 | 31,309 |
def to_string(result: ValidationResult, name_col_width: int) -> str:
"""Format a validation result for printing."""
name = state_name(result.state)
if result.failed:
msg = ", ".join(result.error_details.strip().split("\n"))
return f"❌ {name} {msg}"
elif result.state.reward is None:
... | 263e327e053e6aee06a936b24eaabc2dd9ef028a | 31,310 |
def two_sum_v1(array, target):
"""
For each element, find the complementary value and check if this second value is in the list.
Complexity: O(n²)
"""
for indice, value in enumerate(array):
second_value = target - value
# Complexity of in is O(n). https://stackoverflow.com/questions/... | 0dcc3b4a10ac4c04cabd4ab09a9e71f739455f55 | 31,311 |
def worker_numric_avg(fleet, value, env="mpi"):
"""R
"""
return worker_numric_sum(fleet, value, env) / fleet.worker_num() | 9906fb0c35b718a9da6c8d6d0e0a5a85da5cf28d | 31,312 |
from typing import List
from typing import Tuple
from typing import Dict
def build_graph(
nodes: List[Tuple[str, Dict]], edges: List[Tuple[str, str, Dict]]
) -> nx.DiGraph:
"""Builds the graph using networkx
Arguments
---------
nodes : list
A list of node tuples
edges : list
A... | 0d0bbbfa96ddd5c170a2ec7e9fb06b964b997dd3 | 31,313 |
def table_exists_sql(any_schema=False):
"""SQL to check for existence of a table. Note that for temp tables, any_schema should be set to True."""
if not any_schema:
schema_filter_sql = sql.SQL('AND schemaname = current_schema()')
else:
schema_filter_sql = sql.SQL('')
return sql.SQL("""S... | 2ea073d26705f218d2929c7a419ef61a05c4cced | 31,314 |
def _process_json(data):
"""
return a list of GradPetition objects.
"""
requests = []
for item in data:
petition = GradPetition()
petition.description = item.get('description')
petition.submit_date = datetime_from_string(item.get('submitDate'))
if 'decisionDate' in it... | 5d381b896cd237b7780f1c048ef3e8fc6dd8bb9a | 31,315 |
def PaddingMask(pad=0):
"""Returns a layer that maps integer sequences to padding masks.
The layer expects as input a batch of integer sequences. The layer output is
an N-D array that marks for each sequence position whether the integer (e.g.,
a token ID) in that position represents padding -- value ``pad`` --... | 146f4bb6b518b38c007a42ed78c7e0d344070dee | 31,316 |
import yaml
def python_packages():
"""
Reads input.yml and returns a list of python
related packages
"""
with open(r"tests/input.yml") as file:
inputs = yaml.load(file, Loader=yaml.FullLoader)
return inputs["python_packages"] | 91889c21b1553f9b09c451913e658b458c4502d0 | 31,317 |
import asyncio
def create_tcp_visonic_connection(address, port, protocol=VisonicProtocol, command_queue = None, event_callback=None, disconnect_callback=None, loop=None, excludes=None):
"""Create Visonic manager class, returns tcp transport coroutine."""
# use default protocol if not specified
protocol =... | 0db9e05db4035caf828d61c91799d3658c61b6e0 | 31,318 |
def metric_wind_dict_to_beaufort(d):
"""
Converts all the wind values in a dict from meters/sec
to the corresponding Beaufort scale level (which is not an exact number but rather
represents a range of wind speeds - see: https://en.wikipedia.org/wiki/Beaufort_scale).
Conversion table: https://www.win... | b26ddb5e9c0423612a9c7086030fd77bbfa371ad | 31,319 |
def add_favorite_clubs():
"""
POST endpoint that adds favorite club(s) for student user. Ordering is preserved
based on *when* they favorited.
"""
user = get_current_user()
json = g.clean_json
new_fav_clubs_query = NewOfficerUser.objects \
.filter(confirmed=True) \
.filter(... | 1288e3d579dca54d25883fed4241b6fa1206f7f0 | 31,320 |
def death_rate_60():
"""
Real Name: b'death rate 60'
Original Eqn: b'Critical Cases 60*fraction of death 60/duration of treatment 60'
Units: b'person/Day'
Limits: (None, None)
Type: component
b''
"""
return critical_cases_60() * fraction_of_death_60() / duration_of_treatment_60() | 223990d67fcde9731080e58c7f5ca6ee208c17ff | 31,321 |
from datetime import datetime
def cast_vote(uid, target_type, pcid, value):
""" Casts a vote in a post.
`uid` is the id of the user casting the vote
`target_type` is either `post` or `comment`
`pcid` is either the pid or cid of the post/comment
`value` is either `up` or `down`
"""
... | 702622b91612c1b9636c16786c76c1c711cf7520 | 31,322 |
def convert_file(ifn: str, ofn: str, opts: Namespace) -> bool:
"""
Convert ifn to ofn
:param ifn: Name of file to convert
:param ofn: Target file to convert to
:param opts: Parameters
:return: True if conversion is successful
"""
if ifn not in opts.converted_files:
out_json = to... | 963a3bdc4b5fa48295230e183ee99fd4b3f79b22 | 31,323 |
def target_validation(target_name, action):
"""
Given a Target name and an action, determine if the target_name is a valid
target in target.json and if the target supports the action.
Parameters
----------
target_name : str
Name of the Target.
action : str
Type of action the... | c2f8015856f154c16fbcae29f3ed931c3a4d8f73 | 31,324 |
import hashlib
def _writechecksummanifest(fn: str, prefixlen: int, bac: dict) -> tuple[str, int, int]:
"""Write an AIP "checksum manifest".
This writes an AIP "checksum manifest" to the given ``fn`` PDS filename, stripping ``prefixlen``
characters off paths, and using information from the ``bac``. Retur... | ac5b960e0afae10a15ffccdb5fbc3e6743ad085f | 31,325 |
def bartletts_formula(acf_array, n):
"""
Computes the Standard Error of an acf with Bartlet's formula
Read more at: https://en.wikipedia.org/wiki/Correlogram
:param acf_array: (array) Containing autocorrelation factors
:param n: (int) Length of original time series sequence.
"""
# The first ... | d207695a59d1b1c968f2e3877edbee3ce97f1604 | 31,326 |
def AddEnum(idx, name, flag):
"""
Add a new enum type
@param idx: serial number of the new enum.
If another enum with the same serial number
exists, then all enums with serial
numbers >= the specified idx get their
serial numbers incremented (in other words,
... | 1b5a713380c1b79e1bc26e1300e36adbcc7ceb8e | 31,327 |
from typing import Optional
from typing import Tuple
from typing import Union
def get_turbine_shadow_polygons(blade_length: float,
blade_angle: Optional[float],
azi_ang: float,
elv_ang: float,
... | c3d568d60325a8309a3305b871943b55f8959f41 | 31,328 |
def str_igrep(S, strs):
"""Returns a list of the indices of the strings wherein the substring S
is found."""
return [i for (i,s) in enumerate(strs) if s.find(S) >= 0]
#return [i for (s,i) in zip(strs,xrange(len(strs))) if s.find(S) >= 0] | bae8afdb7d0da4eb8384c06e9f0c9bc3f6a31242 | 31,329 |
def random_laplace(shape, loc=0.0, scale=1.0, dtype=tf.float32, seed=None):
"""
Helper function to sample from the Laplace distribution, which is not
included in core TensorFlow.
"""
z1 = random_exponential(shape, loc, dtype=dtype, seed=seed)
z2 = random_exponential(shape, scale, dtype=dtype, seed=seed)
r... | 77c2df0bacfcf2ec07f137def93e2a9429d968ca | 31,330 |
import math
def resample_image(img_in, width_in, height_in, width_out, interpolation_method="bilinear"):
"""
Resample (i.e., interpolate) an image to new dimensions
:return resampled image, new height
"""
img_out = []
scale = float(width_out) / float(width_in)
scale_inv = 1.0 / scale
# print "Resampling sca... | 4d9759c02749cab30244326d3da7cf7c6c48fe46 | 31,331 |
def identify_missing(df=None, na_values=['n/a', 'na', '--', '?']):
"""Detect missing values.
Identify the common missing characters such as 'n/a', 'na', '--'
and '?' as missing. User can also customize the characters to be
identified as missing.
Parameters
----------
df : DataFrame
R... | b7b7fe20309463cd6f9044cb85459084910d23a4 | 31,332 |
def categorize():
"""API de categorização utilizando o modelo Perceptron()"""
# Load input
body = request.json
# Error handling
if not "products" in body:
return { "error": "json field 'products' does not exist"}, 400
products = body["products"]
if type(products) != list:
... | b155b1a88c62124d64559414bee5a07a325e1279 | 31,333 |
def _TryJobSvnRepo(builder_type):
"""Returns an SVN repo to use for try jobs based on the builder type."""
if builder_type == fetch_build.PERF_BUILDER:
return PERF_SVN_REPO_URL
if builder_type == fetch_build.FULL_BUILDER:
return FULL_SVN_REPO_URL
if builder_type == fetch_build.ANDROID_CHROME_PERF_BUILDE... | 9d3a71ee10735499a0f677c88f5b2dc2c8e24e5c | 31,334 |
def find_wr5bis_common2(i, n, norm, solution_init, common2b_init):
"""
Find the point when for the scalar product of the solution
equals the scalar product of a guess with 2 consecutive bits in common.
Fct_common2b(w) = fct_solution(w), for which w in [w0_3 , w0_4]
with 0 =< w0_3 < w0_4 < 1 ?
fct_solution(w) =... | 2678f1ad355f1bc96aaf1be96945af2b21727d97 | 31,335 |
import yaml
import re
def yml_remove_releaseNote_record(file_path, current_server_version):
"""
locate and remove release notes from a yaml file.
:param file_path: path of the file
:param current_server_version: current server GA version
:return: True if file was changed, otherwise False.
"""
... | 48a6f68642a094dd07a0daa13a78d11991a2aa5c | 31,336 |
from typing import Union
def calculate_z_score(
data: Union[MultimodalData, UnimodalData, anndata.AnnData],
n_bins: int = 50,
) -> np.array:
"""Calculate the standardized z scores of the count matrix.
Parameters
-----------
data: ``MultimodalData``, ``UnimodalData``, or ``anndata.AnnData`` ob... | df510bea5d475690ee234c1f92c6a9cb5bfab308 | 31,337 |
def encode(*args, **kwargs):
"""
A helper function to encode an element.
@param args: The python data to be encoded.
@kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}.
@return: A L{util.BufferedByteStream} object that contains the data.
"""
encoding = kwargs.pop('encoding', DEFAU... | 41fd8c725643826a9e74dfdd59607f5bc6eda5c3 | 31,338 |
from typing import Tuple
def fenergy_symmetric_bar(
work_ab: ArrayLike,
work_bc: ArrayLike,
uncertainty_method: str = "BAR",
) -> Tuple[float, float]:
"""BAR for symmetric periodic protocols.
Args:
work_ab: Measurements of work from first half of protocol.
work_bc: Measurements of... | 569f694cd9a2ea58ef929230e5eb4fc399229e57 | 31,339 |
def format_resolution(resolution):
"""For debugging, convert resolution dict from resolve_citations() to
just the matched_text() of each cite, like
{'1 U.S. 1': ['1 U.S. 1', '1 U.S., at 2']}.
"""
return {
k.citation.matched_text(): [i.matched_text() for i in v]
for k, v in resolu... | ff4d327c2e747c5d3221bcd38bf4f93b2b30b17b | 31,340 |
def mod_arr_fit(ktp_dct, mess_path,
fit_type='single', fit_method='dsarrfit',
t_ref=1.0, a_conv_factor=1.0, inp_param_dct=None):
"""
Routine for a single reaction:
(1) Grab high-pressure and pressure-dependent rate constants
from a MESS output file
(2)... | aacb366b2b826b8ffaaae620ee531ce7cb7e0339 | 31,341 |
from typing import Union
from typing import Sequence
from typing import List
def _choose_image_ids(selected: Union[None, int, Sequence[int]],
available: List[int]) -> List[int]:
"""Choose which image ids to load from disk."""
# Load all.
if selected is None:
return available
# Load... | 2f12c0f840ec4daede35ac3f65e745ad8681c19a | 31,342 |
import mite as m2
import M2kinter as m2
def _open_file(name, mode):
"""
Opens a file in the specified mode. If the mite or M2kinter module
is available the path given is not absolute, the writepath or
datapath (depending on the specified mode) is searched first.
"""
if not name:
raise ... | 4aee4a2a54e5f9bd1ba72810b72deb50d0f69d54 | 31,343 |
def canonical_message_builder(content, fmt):
"""Builds the canonical message to be verified.
Sorts the fields as a requirement from AWS
Args:
content (dict): Parsed body of the response
fmt (list): List of the fields that need to go into the message
Returns (str):
canonical mes... | 41a5e61cea00348c43675e373acb3cdcb311a762 | 31,344 |
import random
def get_random_image(shape):
"""
Expects something like shape=(480,640,3)
:param shape: tuple of shape for numpy array,
for example from my_array.shape
:type shape: tuple of ints
:return random_image:
:rtype: np.ndarray
"""
if random.random() < 0.5:
r... | 6ac0a627ce6f125b269584cb0694c6b26bb5e23d | 31,345 |
import torch
def evaluate(model, val_loader, device):
"""
model: CNN networks
val_loader: a Dataloader object with validation data
device: evaluate on cpu or gpu device
return classification accuracy of the model on val dataset
"""
# evaluate the model
model.eval()
# context-manage... | f5b738117a2c73d666718acaeff83f8856294db9 | 31,346 |
def estimateInharmonicity(inputFile = '../../sounds/piano.wav', t1=0.1, t2=0.5, window='hamming',
M=2048, N=2048, H=128, f0et=5.0, t=-90, minf0=130, maxf0=180, nH = 10):
"""
Function to estimate the extent of inharmonicity present in a sound
Input:
inputFile (string): wa... | f3d8d78b3e565b69e72f435b5afdef7a6f6a28fd | 31,347 |
import attr
def _get_default_secret(var, default):
"""
Get default or raise MissingSecretError.
"""
if isinstance(default, attr.Factory):
return attr.NOTHING
elif isinstance(default, Raise):
raise MissingSecretError(var)
return default | debece74ea410589a0330dac9aaf2e57796c2001 | 31,348 |
import copy
def merge_similar_bounds(json_data: dict, file_names: list, bounds_list: list) -> dict:
"""Finds keys in a dictionary where there bounds are similar and merges them.
Parameters
----------
json_data : dict
Dictionary data from which the data informations were extracted from.
fi... | 314d6501e887d7a52d2aed054583188be992c1ed | 31,349 |
import base64
def is_base64(s):
"""Return True if input string is base64, false otherwise."""
s = s.strip("'\"")
try:
if isinstance(s, str):
sb_bytes = bytes(s, 'ascii')
elif isinstance(s, bytes):
sb_bytes = s
else:
raise ValueError("Argument mus... | 6ce7bc4ddc79d5d50acce35f7995033ffb7d364a | 31,350 |
def get_coco(opt, coco_path):
"""Get coco dataset."""
train_dataset = CenterMultiPoseDataset(opt, split = 'train') # custom dataset
val_dataset = CenterMultiPoseDataset(opt, split = 'val') # custom dataset
opt.val_interval = 10
return train_dataset, val_dataset | c78e07bff16053ce1c4c9a8246750f938159f3b6 | 31,351 |
def _get_output_columns(nodes, context):
"""Get the output columns for a list of SqlNodes.
Args:
nodes: List[SqlNode], the nodes to get output columns from.
context: CompilationContext, global compilation state and metadata.
Returns:
List[Column], list of SqlAlchemy Columns to outp... | 9c8c45311ca03892eaf4e82bbb592af6137eb0a6 | 31,352 |
from typing import final
def notif(message):
"""
docstring
"""
#message= mess.text
#print(message)
#print(type(message))
query= str(message).split(',')
#print(query)
if(len(query)==2):
#print(eval(query[1]))
list_str= final.ajio_care.find_stock(eval(query[0]),eval(q... | 5791165d8ac9fe582090de2f6a4831f2da3039ee | 31,353 |
import optparse
import sys
def parse_args():
"""
Parses command line arguments
"""
parser = optparse.OptionParser(
version=nodeenv_version,
usage="%prog [OPTIONS] ENV_DIR")
parser.add_option('-n', '--node', dest='node',
metavar='NODE_VER', default=get_last_stable_node_ver... | c7bb1121d8cfd71732823b2e2043287af734e5bb | 31,354 |
def float32(x):
"""Returns a 32-bit floating point representation of the input.
Only defined for basic scalar types."""
return np.float32(x) | a63d595a1d9a1949183a8303b0258779082278c7 | 31,355 |
from pathlib import Path
def collect_test_names():
""" "
Finds all test names in `TEST_DATA_DIR` which have are valid, i.e.
which have both a C file and associated gcc AST json
"""
test_data_dir_path = Path(TEST_DATA_DIR)
c_files = test_data_dir_path.glob("*.c")
ast_files = test_data_dir_p... | c34609264f460c66d8ea85a456901e0f1daca84f | 31,356 |
def read_from_file(filename):
"""Read from a file located at `filename` and return the corresponding graph object."""
file = open(filename, "r")
lines = file.readlines()
file.close()
# Check if it is a graph or digraph
graph_or_digraph_str = lines[0].strip() if len(lines) > 0 else None
if ... | 86879facbef971541fabe95ef9430480931ef986 | 31,357 |
from quaternion.calculus import spline_definite_integral as sdi
def inner_product(t, abar, b, axis=None, apply_conjugate=False):
"""Perform a time-domain complex inner product between two waveforms <a, b>.
This is implemented using spline interpolation, calling
quaternion.calculus.spline_definite_integra... | c675ee377a73e0858ad078bce47b5e41120b8d0b | 31,358 |
from typing import List
def build_datamodel(good_pbks: List[str], is_supply: bool) -> DataModel:
"""
Build a data model for supply and demand (i.e. for offered or requested goods).
:param good_pbks: the list of good public keys
:param is_supply: Boolean indicating whether it is a supply or demand dat... | 35b450039e6401a80fc03c61e771eb433bfab693 | 31,359 |
def tryReduceOr(sig, val):
"""
Return sig and val reduced by | operator or None
if it is not possible to statically reduce expression
"""
m = sig._dtype.all_mask()
if not val.vldMask:
return val
if val._isFullVld():
v = val.val
if v == m:
return val
... | 4be6cb3ebf3792859745ed474151e0b748f4d479 | 31,360 |
def get_mod_from_id(mod_id, mod_list):
"""
Returns the mod for given mod or None if it isn't found.
Parameters
----------
mod_id : str
The mod identifier to look for
mod_list : list[DatRecord]
List of mods to search in (or dat file)
Returns
-------
DatRecord or Non... | 1fac309e4dfadea6da34946eb695f77cbbd61f92 | 31,361 |
def resize(image):
"""
Resize the image to the input shape used by the network model
"""
return cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) | 315b43be9fc33740466fb6671119fbc97a2c853a | 31,362 |
def exp_f(name):
""""Similar to E but trains to full 3001 epochs"""
print("e82 but with seq length 2000 and 5 appliances and learning rate 0.01 and train and validation on all 5 houses")
source = RealApplianceSource(
filename='/data/dk3810/ukdale.h5',
appliances=[
['fridge freeze... | fceb234feb9848e6a2618e4f5433345265d1b839 | 31,363 |
def indices_2_one_hot(indices, n):
"""
Converts a list of indices into one hot codification
:param indices: list of indices
:param n: integer. Size of the vocabulary
:return: numpy array with shape (len(indices), n)
"""
one_hot = np.zeros((len(indices), n), dtype=np.int8)
for i in range... | c74864bf23cbd56dbc9de12f250570b9df9cdf8c | 31,364 |
from typing import Set
def extract_tables(query: str) -> Set[Table]:
"""
Helper function to extract tables referenced in a query.
"""
return ParsedQuery(query).tables | cb48448b09f9aac90a85ca2bd7011f32fcbe6e6f | 31,365 |
def master_operation(matrix):
"""
Split the initial matrix into tasks and distribute them among slave operations
"""
workers = MPI.COMM_WORLD.Get_size()
accumulator = []
task_queue = []
if not matrix[0][0]:
task_queue.append([(0, 0)])
while True:
sent_workers = []
... | c936abd299cd0181138f4f4c87a5cf306be06c7a | 31,366 |
def _weight_mean_color(graph, src, dst, n):
"""Callback to handle merging nodes by recomputing mean color.
The method expects that the mean color of `dst` is already computed.
Parameters
----------
graph : RAG
The graph under consideration.
src, dst : int
The vertices in `graph... | 13fe474363578f704dfe8e16be725628a6e3ca5f | 31,367 |
def predict(model, pTestSet, pModelParams, pNoConvertBack):
"""
Function to predict test set
Attributes:
model -- model to use
testSet -- testSet to be predicted
conversion -- conversion function used when training the model
"""
#copy the test set, before invalidated rows and... | 4d6aa09bc1223732d73ea7f37aed2ccc28e879b3 | 31,368 |
def poisson_log_likelihood(x, log_rate):
"""Compute the log likelihood under Poisson distribution.
log poisson(k, r) = log(r^k * e^(-r) / k!)
= k log(r) - r - log k!
log poisson(k, r=exp(l)) = k * l - exp(l) - lgamma(k + 1)
Args:
x: binned spike count data.
log_rate: The (log... | dc797090efceb4266a90e89125fb5a9acc5b2da7 | 31,369 |
import math
def distance(point1, point2):
""" Return the distance between two points."""
dx = point1[0] - point2[0]
dy = point1[1] - point2[1]
return math.sqrt(dx * dx + dy * dy) | 7605d98e33989de91c49a5acf702609272cf5a68 | 31,370 |
import os
import json
def get_filesystem_perf_results(result_dir, pred_type='classification'):
"""
Retrieve model metadata and performance metrics stored in the filesystem from a hyperparameter search run.
"""
model_uuid_list = []
model_type_list = []
max_epochs_list = []
learning_rate_lis... | 625f34a877b07d4a8d75e59e316d6ec5169d2e41 | 31,371 |
import math
def order_of_magnitude(value):
"""
Returns the order of magnitude of the most significant digit of the
specified number. A value of zero signifies the ones digit, as would be
the case in [Number]*10^[Order].
:param value:
:return:
"""
x = abs(float(value))
offset = 0 ... | 53a4b1be76199864fee69d4333049fb1f2371e46 | 31,372 |
def compute_discounted_R(R, discount_rate=1):
"""Returns discounted rewards
Args:
R (1-D array): a list of `reward` at each time step
discount_rate (float): Will discount the future value by this rate
Returns:
discounted_r (1-D array): same shape as input `R`
but the valu... | 50a18277e749faa73c725217824091a71d00f991 | 31,373 |
def setup_dom_for_char(character, create_dompc=True, create_assets=True,
region=None, srank=None, family=None, liege_domain=None,
create_domain=True, create_liege=True, create_vassals=True,
num_vassals=2):
"""
Creates both a PlayerOrNpc instan... | 3c806c560e0691440bc7d7399467eecb563745f0 | 31,374 |
def cumulative_sum(t):
"""
Return a new list where the ith element is the sum of all elements up to that
position in the list. Ex: [1, 2, 3] returns [1, 3, 6]
"""
res = [t[0]]
for i in range(1, len(t)):
res.append(res[-1] + t[i])
return res | 14b2ef722f72e239d05737a7bb7b3a6b3e15305f | 31,375 |
def WIS(x, q, x_q, norm=False, log=False, smooth=False):
"""
Parameters
----------
:
TODO
:
TODO
Returns
-------
:
TODO
"""
# todo sort q and x_q based on q
K = len(q) // 2
alps = np.array([1 - q[-i - 1] + q[i] for i in range(K)])
Fs = np.arra... | b3b9b2157d05dd1329a0051862789826d8b0e1a7 | 31,376 |
from typing import Tuple
def update_documents_in_collection(resource) -> Tuple[Response, int]:
"""Endpoint for updating multiple documents."""
try:
collection_name = services.check_resource_name(resource)
request_args = request.args.copy()
filters = ["_projection", "_sort", "_limit",... | 743b7bf3c3d2be765da181b5fbceef3309f91b48 | 31,377 |
def generate_prior_data(Pi, a_prior, b_prior):
"""Return column data sources needed to generate prior distribution."""
# Prior probability distribution
n = 1000
x = np.linspace(0, 1, n)
dist = beta(a_prior, b_prior)
p = dist.pdf(x)
# Arrays for the area under the curve patch
xs = np.hs... | 1bce66203f0b3ad6ab74fb346a81ec15ff2b7d63 | 31,378 |
def InteractionFingerprintAtomic(ligand, protein, strict=True):
"""Interaction fingerprint accomplished by converting the molecular
interaction of ligand-protein into bit array according to
the residue of choice and the interaction. For every residue
(One row = one residue) there are eight bits which re... | ecdfc34e5c6cb5c5ca3fcf008629b1d3face158c | 31,379 |
from typing import Union
def add_subject_conditions(
data: pd.DataFrame, condition_list: Union[SubjectConditionDict, SubjectConditionDataFrame]
) -> pd.DataFrame:
"""Add subject conditions to dataframe.
This function expects a dataframe with data from multiple subjects and information on which subject
... | 7475af9b13685604678b4d566e9b2daa4f6f82ef | 31,380 |
def chinese_remainder(n1: int, r1: int, n2: int, r2: int) -> int:
"""
>>> chinese_remainder(5,1,7,3)
31
penjelasan : 31 adalah nomor yang paling kecil
ketika dibagi dengan 5 kita dapat hasil bagi 1
ketika dibagi dengan 7 kita dapat hasil bagi 3
"""
(x, y) = extended_euclid(n1, n2)
m... | e98882790c9c4bdd1e23f1d9b49d7a30ddaf7e81 | 31,381 |
def likelihood(angle, displacement, ln_variance, z, s, debug=False):
"""
Returns theano function from the angle, displacement, ln_variance2 theano.scalars
"""
variance = tt.exp(ln_variance)
# gradient = tt.tan(angle)
v = tt.stacklists([[-np.sin(angle)], [np.cos(angle)]])
delta = tt.dot(v.T,... | 3ddac8592c6f95e79ad8350cbc4b42b9d5a7b83a | 31,382 |
from typing import Iterable
def query_factorize_industry_df(factorize_arr, market=None):
"""
使用match_industries_factorize可以查询到行业所对应的factorize序列,
使用factorize序列即组成需要查询的行业组合,返回行业组合pd.DataFrame对象
eg: 从美股所有行业中找到中国企业的行业
input:ABuIndustries.match_industries_factorize('中国', market=EMarketTargetType.E_... | 7060336e59b54d87f061a6163367b22c056edb6a | 31,383 |
import yaml
def rbac_assign_roles(email, roles, tenant=None):
"""assign a list of roles to email"""
tstr = " -tenant=%s " % (tenant) if tenant else ""
roles = ",".join(roles)
rc = run_command("%s user-role -op assign -user-email %s -roles %s %s" % (
g_araalictl_path, email, roles,... | 27bc4835052fd3e6c5e2660ab47c12b49ff426ef | 31,384 |
def haversine_np(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
Reference:
https://stackoverflow.com/a/29546836/7657658
https://gist.github.com/mazzma12/6dbcc71ab3b579c08d66a968ff509901
"""
lon1, la... | ace51c2e9e93a42270f669d4b8d48ce87ff660d6 | 31,385 |
import typing
import os
def basename_wo_ext(
path: typing.Union[str, bytes],
*,
ext: str = None
) -> str:
"""File basename without file extension.
Args:
path: file or directory name
ext: explicit extension to be removed
Returns:
basename of directory or fi... | 40992c6906811cc5c448dbecdb7806ddedc68f36 | 31,386 |
import re
def extract_current_step(current_status_string):
""" Attempts to extract the current step numeric identifier from the given status string. Returns the step
number or None if none.
"""
# Older format: `Step 12 :`
# Newer format: `Step 4/13 :`
step_increment = re.search(r"Step ([0-9]+)... | 8bbee5b13140394e3e04021eccd43d2b4c3b4c14 | 31,387 |
import warnings
def unique1d(ar1, return_index=False, return_inverse=False):
"""
Find the unique elements of an array.
Parameters
----------
ar1 : array_like
This array will be flattened if it is not already 1-D.
return_index : bool, optional
If True, also return the indices a... | 8ac57d97079d60215dc96fd33d1f176129445662 | 31,388 |
def login_required(func):
"""
Decorator check required login and active user
:param func:
:return:
"""
@wraps(func)
def decorated_view(*args, **kwargs):
if current_app.login_manager._login_disabled:
return func(*args, **kwargs)
elif not current_user.is... | 894d162a8fd50c0e4fba810c0f575865994ba00e | 31,389 |
def prepare_statement(template, values):
"""Correctly escape things and keep as unicode.
pyscopg2 has a default encoding of `latin-1`: https://github.com/psycopg/psycopg2/issues/331"""
new_values = []
for value in values:
adapted = adapt(value)
adapted.encoding = 'utf-8'
new_val... | 68af78444da86cdf73f74f84f5c7f0743b591e5c | 31,390 |
def addgroup(request):
"""Add group form."""
return render(
request,
'addgroup.htm',
context={},
) | dce8da2641b35bbdb1062463e9bc954b70c9d1d2 | 31,391 |
def cached_function_method_signature(ctx: MethodSigContext) -> CallableType:
"""Fixes the `_CachedFunction.__call__` signature to be correct.
It already has *almost* the correct signature, except:
1. the `self` argument needs to be marked as "bound";
2. any `cache_context` argument should be r... | 7b1b9893afe4f1e723eed7894b0adf9221c24d1d | 31,392 |
def load_valid_data_full():
"""
load validation data from disk
"""
hdf5_file_valid = h5py.File(HDF5_PATH_VALID, "r")
data_num_valid = hdf5_file_valid["valid_img"].shape[0]
images_valid = np.array(hdf5_file_valid["valid_img"][:]) # your test set features
labels_valid = np.array(hdf5_file_val... | bc586424e6fc2669107c7548220461a089bbad16 | 31,393 |
import json
def import_slab_structures(filename):
"""Read 2D water structures from file and return a dictionary of it.
Parameters
----------
filename : str
Filename of the file containing the bulk structures
Returns
-------
filedict : dict
Dictionary of the structures
... | d6ca4d5c7b5c264d55cd26f638dfb4ec34bce259 | 31,394 |
import re
def handle_email(text):
"""Summary
Args:
text (TYPE): Description
Returns:
TYPE: Description
"""
return re.sub(r'(\w+@\w+)', Replacement.EMAIL.value, text) | c96e3f5791394d5200c309e5ea1a285aae85a3df | 31,395 |
def LowerCustomDatatypes():
"""Lower custom datatypes.
See tvm::datatypes::Registry for more information on adding custom datatypes.
Returns
-------
fpass : tvm.ir.transform.Pass
The result pass
"""
return _ffi_api.LowerCustomDatatypes() | cb55a578a3daabf6e95a64bc95ba75643d2f14bd | 31,396 |
import typing
def apply_if_or_value(
maybe_value: typing.Optional[typing.Any],
operation: typing.Callable[[typing.Any], typing.Any],
fallback_value: typing.Any,
) -> typing.Any:
"""Attempt to apply operation to maybe_value, returning fallback_value if
maybe_value is None.
Almost a convenience... | fe67fbc1b71ed22fa3da516df82a72cb64e30f33 | 31,397 |
import torch
def make_pyg_dataset_from_dataframe(
df: pd.DataFrame, list_n: list, list_e: list, paired=False, mode: str = "all"
) -> list:
"""Take a Dataframe, a list of strings of node features, a list of strings of edge features
and return a List of PyG Data objects.
Parameters
----------
d... | 267787c7b527a92421fa7e83ca75bf2a8083ec2a | 31,398 |
def ucfirst(string: str):
"""Return the string with the first character in upper case."""
return _change_first_case(string, upper=True) | 4f52744dc62f4db7437451de3120691bbb184298 | 31,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.