content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_language(file_path):
"""Return the language a file is written in."""
if file_path.endswith(".py"):
return "python3"
elif file_path.endswith(".js"):
return "node"
elif file_path.endswith(".rb"):
return "ruby"
elif file_path.endswith(".go"):
return "go run"
elif file_path.endswith(".c") or file_... | 2f34390227932c7add58967dbe9bfc3834526b8e | 685,639 |
def make_iter_method(method_name, *model_names):
"""Make a page-concatenating iterator method from a find method
:param method_name: The name of the find method to decorate
:param model_names: The names of the possible models as they appear in the JSON response. The first found is used.
"""
def ite... | 67623ab63930a899a1e6ce91c80e49ec41779079 | 685,640 |
def get_vector11():
"""
Return the vector with ID 11.
"""
return [
0.6194425,
0.5000000,
0.3805575,
] | f45a1e4f7351c9455e67e98cbe6a40f15aee3440 | 685,641 |
def getGalaxyData(hd_gal, galaxy_SMHMR_mass, redshift_limit):
"""
Function to get relavant data for galaxies
"""
if isinstance(galaxy_SMHMR_mass, (int, float)):
downsample_gal = (hd_gal['galaxy_SMHMR_mass']>galaxy_SMHMR_mass) & (hd_gal['redshift_R']<redshift_limit)
else:
downsam... | 54eca309c270905e45bdf9de5553c73cf66e99be | 685,642 |
def parr_to_pdict(arr, measures_optimized):
"""Convert BO parameter tensor to parameter dict"""
if measures_optimized:
d = {
'p_stay_home': arr[0].tolist(),
}
return d
else:
d = {
'betas': {
'education': arr[0].tolist(),
... | 50623f2aae87a5326b4524f249bf28eb093aa7c0 | 685,643 |
def trapply_calib(trin):
"""Apply calibration values to data-points in a trace object"""
return trin.apply_calib() | cf19889be308fa8ad86a4a822202aa76185357e6 | 685,644 |
def make_my_controller_match():
"""Function to generate an ACL match for access to controllers specific to this device
Returns:
dict: A dictionary representing the my-controller match.
"""
return {'my-controller': []} | 27a76362b5a9abda456db71b423ea8152d798430 | 685,645 |
def all_names(command):
"""Return a list of all possible names in a command"""
return [command.name, *command.aliases] | 53460c0b93adf0c9ea80a67a2362c841e90da258 | 685,646 |
import string
def get_printable(text):
""" Return string if printable, else None
"""
try:
if all(c in string.printable for c in text):
return text
except TypeError:
if all(chr(c) in string.printable for c in text):
return text
return None | e6b14e2c59b1d90dfcfbdda82298c6a4624aee6c | 685,647 |
import array
import math
def get_entropy(data):
""" learn Entropy calculated across various sections & resources """
if len(data) == 0:
return 0.0
occurences = array.array('L', [0]*256)
for x in data:
occurences[x if isinstance(x, int) else ord(x)] += 1
entropy = 0
for x in occurences:
if x:
p_x = ... | e99f584a43291a6c6fa5c7bbc5adb3a6f0c453e6 | 685,648 |
import time
def is_noncomplex(obj):
"""Returns True if *obj* is a special (weird) class, that is complex than
primitive data types, but is not a full object. Including:
* :class:`~time.struct_time`
"""
if type(obj) is time.struct_time:
return True
return False | c5066e98af5556d331b64ff997d124f4e8110983 | 685,649 |
def split_index(index, n=8):
"""Split a conversions index, which is a list of tuples (file position,
number of lines, alignment position), one for each read, into `n`
approximately equal parts. This function is used to split the conversions
CSV for multiprocessing.
:param index: index
:type ind... | 61e783c1fe15fc12727f3fca4059735f6d7f78da | 685,650 |
from typing import Counter
import pickle
def build_dict(examples, filepath, max_words=50000):
"""
Build a dictionary for the words in `sentences` and a dictionary for the entities.
Only the max_words ones are kept and the remaining will be mapped to <UNK>.
"""
documents, questions, answers... | c9fd84f7c574249c6e9d250cd403de68594aa41e | 685,651 |
def get_value(input: int) -> str:
"""Given an int it return Fizz, Buzz or FizzBuzz if it is a multiple of 3, 5 or both"""
if input % 15 == 0:
return "FizzBuzz"
elif input % 3 == 0:
return "Fizz"
elif input % 5 == 0:
return "Buzz"
else:
return f"{input}" | 4121f16d70f3890e986ffee5a7e677e580f28120 | 685,652 |
import collections
import json
def diff_between_policies(old_policy, new_policy):
"""Returns the difference between two policies.
Args:
old_policy: Old policy
new_policy: New policy
"""
old_bindings = collections.defaultdict(set)
for b in old_policy["bindings"]:
if "condition" in b:
... | ec07a89e777b1b913afc0d2a8ba9c89529aa0d65 | 685,653 |
from datetime import datetime
import os
def iaga_fname(path, stn, date, cutoff_date=datetime(2007, 1, 1)):
"""
"""
if date >= cutoff_date.date():
ext = 'dmin.min'
else:
ext = 'd.min'
return os.path.join(path, '{stn}{date:%Y%m%d}{ext}'.format(stn=stn.lower(),
... | b355d805a196ae41aab1def08c5f6dad4059a05d | 685,655 |
import os
def scoop(source, target, offset, size):
""" copy a specified portion of a binary file """
truncated = False
try:
source_size = os.path.getsize(source)
except FileNotFoundError:
return 1, f'Invalid source: {source}'
if offset > source_size:
return 1, f"offset: {... | a3d9225195d5e16688666951426aed02508c6bbb | 685,656 |
import copy
def get_topic_with_children(prefix, children):
"""
Reuse the three-nodes sequence form sample_children to create a topic node.
Modify `node_id`s and `content_id`s to make sure nodes are different.
"""
topic = {
"title": "Topic " + prefix,
"node_id": prefix,
"con... | a6797e400d044f82700d0b4c25ca0886cde441a2 | 685,657 |
def camel_case_to_readable(text):
"""
'camelCase' -> 'Camel Case'
"""
if text == 'id':
return 'ID'
return ''.join(' ' + char if char.isupper() else char.strip() for char in text).strip().title() | f80b3fae61d9553bcdbee0930cc3b17168fd1b23 | 685,659 |
def check_box(grid, supp):
""" search box for unusable numbers and delete them"""
box_num = []
for x in range(9):
for y in range(9):
if grid[x][y] != 0:
box_num.append(grid[x][y])
for z in box_num:
for a in range(9):
supp[x][a][z] = 0
... | 1255ee80e767b8a19087b4d9a824aa8c0c944416 | 685,660 |
def split_smiles(smiles: str) -> list:
"""Splits a SMILES string into individual tokens.
This will split a SMILES string into tokens representing
individual parts of the SMILES string. Each individual token
will be one of the following,
- A single atom (including hydrogens or charge if specified)
... | a9e82d19375502a62155d952f230c583c50c059c | 685,661 |
def main(*, data_1, data_2):
"""entrypoint function for this component"""
# ***** DO NOT EDIT LINES ABOVE *****
# write your function code here.
common_index = data_1.index.intersection(data_2.index)
return {
"data_1_restricted": data_1.loc[common_index],
"data_2_restricted": data_... | 591dbabb178eaae46b3486ae3e00db115a7f29db | 685,663 |
def chi2fn_2outcome_wfreqs(N, p, f):
"""
Computes chi^2 for a 2-outcome measurement using frequency-weighting.
The chi-squared function for a 2-outcome measurement using
the observed frequency in the statistical weight.
Parameters
----------
N : float or numpy array
Number of sampl... | a9975542d26aa17f08e57730b4ad71c9e1dbb020 | 685,664 |
def get_wikidata_id(wikidata_uri):
"""
Returns Wikidata ID (e.g. "Q92212") given Wikidata entity URI, or None.
"""
wikidata_base_uri = "http://www.wikidata.org/entity/"
if wikidata_uri.startswith(wikidata_base_uri):
wikidata_id = wikidata_uri[len(wikidata_base_uri):]
else:
wikida... | 9b505dfb65a48ae4ca515483733f3f732aa88aac | 685,665 |
def get_feature_code(properties, yearsuffix):
"""
Get code from GeoJSON feature
"""
code = None
if 'code' in properties: code = properties['code']
elif ('lau1' + yearsuffix + 'cd') in properties: code = properties['lau1' + yearsuffix + 'cd']
return code | 1c068245e2551a2b35824c526a7b491538b387f0 | 685,666 |
def is_tank_asset(filepath, tk):
"""
Args:
filepath:
tk:
Returns:
"""
templ = tk.template_from_path(filepath)
return True if templ else False | 2a398ee66d2e9b70ef36e400ac569cd89c003bc6 | 685,667 |
def strid_to_opts(strid):
"""
Given model id as string, extract parameter dictionary.
Reverse of config_loader.opts2strid
:param strid:
:return:
"""
raise NotImplementedError
#Method not finished
parts = strid.split("_")
param_keys=",".split("thr,win,dim,neg,dim,size,eig,neg,d... | 643394fb7d0964942611be1eb07e2fabf15aab5d | 685,668 |
def convert_type(type_string):
"""Coverts the typing version of the type to the basic python type (list or
dict)
:param type_string:
:type type_string: str
:return: type
"""
if type_string.startswith('List'):
return list
elif type_string.startswith('Dict'):
return di... | e3c68cbf4fd1bae5ac9f438ab16b0b56a9b09eca | 685,669 |
def is_draw(state):
"""Returns True if no boxes are empty but nobody has won. If not returns False."""
for i in state:
for s in i:
if s == 0:
return False
return True | c34d0e04217069decc2af5189214a689e9770039 | 685,670 |
def key_check(line,keyword):
"""
For ARGS, checks if a line of the input file has a keyword on it
"""
if keyword in line:
return True ... | 9d0698d84648bab263b2b676ad2ef9838dce89bd | 685,671 |
def leiaInt(txt):
"""
Aceitando apenas que o usuário adicione um valor inteiro, caso não seja inserido um valor inteiro,
é soliciado novamente que o Usuário digite um número que não está na lista o menu é recarregado adicione um valor inteiro.
:param txt: Texto a ser exibido solicitando os dados do Usuá... | ea01b79b7e11ab1e7b4bcbc91341af8ef1f07199 | 685,672 |
def validate_vector(obj, throwerr=False):
"""
Given an object obj, check if it is a valid raw representation of a real
mathematical vector. An accepted object would:
1. be a Python list or Python tuple
2. be 2 or 3 items in length
:param obj: Test subject
:param throwerr: Raise an e... | dc223fe1541458d5b77d4cbf71284a06365cc2b5 | 685,673 |
def worldtidesinfo_unique_id(lat, long):
"""give a unique id for sensor"""
return "lat:{}_long:{}".format(lat, long) | 771ec01eb4bc45bdbfbf3ca58e09cf78889842d2 | 685,674 |
import math
def dist(x1, y1, x2, y2):
"""
Returns the euclidean distance.
Keyword arguments:
>>> x1: float value for X for first point (ft.)
>>> y1: float value for Y for first point (ft.)
>>> x2: float value for X for 2nd point (ft.)
>>> y2: float value for Y for 2nd point (ft.)
RETU... | 4e72efce9d04338f3729bfc4f854c795ca0aa44a | 685,675 |
def standardize_static(X_lst):
""" Standardize static features
"""
mean = X_lst[-1].mean(0)
std = X_lst[-1].std(0)
std[std == 0] = 1
X_lst[-1] = (X_lst[-1] - mean)/std
return(X_lst) | 24f7eb045fbeb33e8b35cde3f2100e9c38727a94 | 685,676 |
def handle_index(headers, resources={}):
"""Create an index of the subsections (with max depth of 2)"""
top_section = ""
index = []
last_level = -1
for id, level, title in headers:
if level > 3:
continue
if not top_section:
top_section = id
elif level... | 90afb1b6423c55a5d5b77955f450b4aab49abede | 685,677 |
import io
import os
def get_filetext(rootdir, filename):
""" Get the text of a local file """
with io.open(os.path.join(rootdir, filename), encoding='utf-8') as f:
return f.read() | 82f85d6ed7f9c7964d920e90d8d71db56c3e3e03 | 685,678 |
import inspect
def bokeh_no_input_update_function(update_function, doc):
"""return a function that adds a callback to the bokeh server queue."""
if inspect.iscoroutinefunction(update_function):
return lambda data: doc.add_next_tick_callback(update_function)
else:
async def async_update_fun... | 3ffc644e1d0be17c2881127678b703c6528c85d3 | 685,679 |
from typing import Callable
import inspect
def get_function_name(function: Callable) -> str:
"""Get the proper name of a function as string
Parameters
----------
function : Callable
function to get the name from
Returns
-------
name : str
"""
name = function.__module__ + ... | cd07a328dacf96de51738230b98f5db7f8ca2f7a | 685,680 |
def check_member_in_project(project, user):
"""
Check user whether or not in project.
"""
if user.is_staff:
return True
if user in project.members.all():
return True
return False | 2c55b3980bf84a2302f8ce64d938c332248d5540 | 685,681 |
def factor_n(n):
"""
Converts input n to the form 2^exp * mult + 1, where mult is the greatest odd
divisor of n - 1, and returns mult and exp.
"""
assert n >= 3 and n % 2 != 0, "n must be an odd integer > 2"
mult = n - 1
exp = 0
while mult % 2 == 0:
mult //= 2
exp += ... | ff5ef9da757934dfe98eff62a1614a4d9567b777 | 685,682 |
def get_sym(pair):
"""
reformats a tuple of (team, rival) so that the first element is smaller than the other
(by convention, this is how we represent a match without home-away status).
"""
if pair[0] > pair[1]:
return pair[1], pair[0]
else:
return pair | 7ab7edbfe2aebf3c76bf7182511a3a4896130278 | 685,683 |
def is_outgoing(reaction, scc):
""" bool: the reaction leads out of the passed scc. """
return not (set(reaction.products) <= scc) | 544ad3929597a783360161d9067d7c9fb92b5c56 | 685,684 |
def is_afs_path(path):
"""R
"""
if path.startswith("afs") or path.startswith("hdfs"):
return True
return False | e5129b085b90cd39b6aff19093d88d71bc0d05db | 685,685 |
def fromPoint3d( pt ):
"""Converts a Point3d to a tuple"""
if pt is None: return None
return (pt.x, pt.y, pt.z) | 834a73fb04c0d66932dc4897f7083ff88efc3dfd | 685,686 |
def is_valid_patch(xs,ys,patch_size,purple_mask,intensity_threshold,threshold=0.5):
"""Deprecated, computes whether patch is valid."""
print(xs,ys)
return (purple_mask[xs:xs+patch_size,ys:ys+patch_size]>=intensity_threshold).mean() > threshold | bfd3e26f336b9cdf71dd9fb861569c5832dde51b | 685,687 |
def get_rpkm_mean_filter(kl, min_rpkm_mean):
""" Mask kl to filter on the estimated means. """
m_min_rpkm_mean_1 = kl['mean_1'] > min_rpkm_mean
m_min_rpkm_mean_2 = kl['mean_2'] > min_rpkm_mean
m_min_rpkm_mean = m_min_rpkm_mean_1 & m_min_rpkm_mean_2
return m_min_rpkm_mean | 60e0ddc8f3205a5bb480ed3739cb6a1796748508 | 685,688 |
from datetime import datetime
def replace_date_format(date_string):
""" Return date in format without the year """
date = datetime.strptime(date_string, '%d.%m. | %H:%M')
return date | ed0e597015ef49231ce2681a0a8e44910c188484 | 685,689 |
import os
def eval_dp(filename, outfile, threads, points_file, model_name='ghhc', dataset_name='dataset'):
"""Evaluate dendrogram purity with shell script using xcluster DP code."""
os.system("sh bin/score_tree.sh {} {} {} {} {} > {}"
.format(filename, model_name, dataset_name, threads, points_... | 29837fa89d5a378c98b50757f57d2a31094ad759 | 685,691 |
import os as _os
import bz2 as _bz2
import tempfile as _tempfile
def compress(inputfile=None, outputfile=None, inputdata=None, compression_type="bz2"):
"""Compress either the passed filename or filedata using the
specified compression type. This will compress either to the
file called 'outputfile', or to ... | c030145a61e53de6d9720abc677fb596cc9a1643 | 685,692 |
import threading
def threadsafe_function(fcn):
"""decorator making sure that the decorated function is thread safe"""
lock = threading.RLock()
def new(*args, **kwargs):
"""Lock and call the decorated function
Unless kwargs['threadsafe'] == False
"""
threadsafe = kwargs... | 07ce73d55caed45cefe72bf9c7ace6d6de71d60e | 685,693 |
import argparse
def init_argparse() -> argparse.ArgumentParser:
"""Initialize an arguments parser, to parse the command line's arguments
Returns
-------
argparse.ArgumentParser
arguments parser to be used to process command line arguments
"""
parser = argparse.ArgumentParser(
... | 4147736d3fd8b8b95cf58a86a0a282f63d6d8d43 | 685,694 |
def acidity (NaOH_volume, NaOH_molarity, NaOH_fc, honey_solution_concentration, honey_solution_volume):
"""
Function to get acidity in honey - meq/kg
"""
mili_eq_NaOH = NaOH_volume * NaOH_molarity * NaOH_fc
grams_of_honey = (honey_solution_concentration * honey_solution_volume) / 100
acidity = (... | d8854838939569a8f74db33cec73c46d9f487200 | 685,695 |
import torch
def linear_to_exact_solve_shape(self, x, z_updated, W, b):
"""
Suitable reshape for the exact solve method.
"""
Z = torch.cat((W.t(),torch.unsqueeze(b,0).type_as(W)),0)
A = torch.cat((x, torch.ones(x.size(0),1).type_as(x)),1)
return A, z_updated, Z | 0fba7e6410aee90f92cb54c3585913f5b29282fc | 685,696 |
import os
def expand_restart_files(basename):
"""Returns expanded restart files based on basename"""
top = os.path.abspath(basename + '.top')
crds = os.path.abspath(basename + '.gro')
vels = '' # dummy file for cross-package interface
return top, crds, vels | 7759f6f06e8721ba69e3c92bdd63287e55a941df | 685,697 |
def construct_graph_from_nodes(parent_g, nodes, outputs, shapes, dtypes):
"""Construct Graph from nodes and outputs with specified shapes and dtypes."""
# pylint: disable=protected-access
g = parent_g.create_new_graph_with_same_config()
g.parent_graph = parent_g
nodes = set(nodes)
all_outputs = ... | e44b11ff78a648fd9825f5466c836aaa1121c1eb | 685,698 |
import io
import re
def extract_urls(fname, encoding="utf8"):
"""
extract URLs from a file and return the result in a list
"""
with io.open(fname, "rt", encoding=encoding) as f:
return re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', f.read()) | 90ad4f9e184e0a57034e9b0b7421989ec29e5e9e | 685,699 |
def parse_node_coverage(line):
# S s34 CGTGACT LN:i:7 SN:Z:1 SO:i:122101 SR:i:0 dc:f:0
# "nodeid","nodelen","chromo","pos","rrank",assemb
"""
Parse the gaf alignment
Input: line from gaf alignment
Output: tuple of nodeid, nodelen, start_chromo, start_pos, coverage
"""
l... | b8d2c5eaad33fdee0e9f004982ec9a27f2a40726 | 685,700 |
def atr_apply_nb(high_ts, low_ts, close_ts, window, ewm, adjust, tr, cache_dict):
"""Apply function for `vectorbt.indicators.basic.ATR`."""
h = hash((window, ewm))
return tr, cache_dict[h] | 5dfe393f0251d206c95131ebaad617947c362cb5 | 685,701 |
def fft_parameters(fft_para,source_params,locs,component,Nfft,data_t):
"""
Creates parameter dict for cross-correlations and header info to ASDF.
:type fft_para: python dictionary.
:param fft_para: useful parameters used for fft
:type source_params: `~np.ndarray`
:param source_params: max_mad,... | 6452c117d68316aaf27c535d165c10e428eab51f | 685,702 |
import re
def apply_formatting(locator, args):
"""Apply formatting to the locator
If there are no named fields in the locator this is just a simple
call to .format. However, some locators have named fields, and we
don't support named arguments to keep the syntax simple, so we
need to map position... | 795912b5378819fe2dc4d2bb9c4f59b33e4efd2f | 685,703 |
def direction_name(angle):
"""
Returns a name for a direction given in degrees.
Example: direction_name(0.0) returns "N"
direction_name(90.0) returns "E"
direction_name(152.0) returns "SSE".
"""
direction_names = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S",
... | 419a4d3fec9e977c84fad84bd6d09441f66e9ca9 | 685,704 |
def figure_to_html(figure, prefix=None, max_in_a_row=None, true_break_between_rows=False):
""" Turns filepaths to nice html-figures
Parameters
----------
figure: Union[List[str], str]
path or list of paths
prefix: Union[None, str]
if set, the length of this string will be clipped fr... | e939541455edac60cda1e680f1b74d3eddbb4265 | 685,706 |
def make_query(specific_table, offset):
"""
Generate a query to retrieve data from database.
:param specific_table: Name of table to retrieve data from.
:param offset: Optional offset to start from.
"""
query = 'select DISTINCT * from `{}`'.format(specific_table)
if isinstance(offset, int):... | e039ecb8fe340c51a80bc919bf368f0b4ceda508 | 685,707 |
def notification(
alert=None,
ios=None,
android=None,
amazon=None,
web=None,
wns=None,
actions=None,
interactive=None,
in_app=None,
open_platform=None,
sms=None,
email=None,
):
"""Create a notification payload.
:keyword alert: A simple text alert, applicable for ... | 1de5ece1569001cdefdffba8967bcfc7d1cee35c | 685,708 |
import random
def mutation(ind, fr_mut = 0.1):
"""
С заданной вероятностью изменяет случайный символ в последовательности
из 1 и 0 на противоположенный. При подаче пустой последовательности
выдаёт 00
"""
if random.random() < fr_mut:
if ind == '':
return '00'
else:
... | fee41c069addeb2a29299e3362d945e04f255d8a | 685,710 |
from typing import List
import random
def generate_artificial_reads(
genome: str, number_of_reads: int, read_length: int
) -> List[str]:
"""Generate a set of reads randomly from a genome"""
reads = []
for _ in range(number_of_reads):
start_position = random.randint(0, len(genome) - read_length... | 30ff2b25c141a548a4f8c1945725e3941f27ef6e | 685,711 |
import random
def start_food():
"""Creates random starting food from 5-10."""
food = random.randint(5,10)
return food | a44194ab1090d11c2c481e85d03e5cdb6adb335c | 685,712 |
def get_api_url(for_repository):
"""
Get the api url for GET request to obtain tags
:param for_repository:
:return:
"""
api_url = 'https://api.github.com/repos/{}/git/refs/tags'.format(for_repository)
return api_url | 00769ba24bf2af38c87d3c989463ee40b9bdb6be | 685,713 |
import platform
import os
import subprocess
def user_home(user):
""" Return user home path for all kind of users """
if platform.system().lower() == 'windows':
return os.getenv('HOME')
else:
return subprocess.check_output('echo ~' + user, shell=True).strip().decode('utf') | fbc339c4d404da82fdce4d60d54806f30ed712be | 685,714 |
def is_builtin_reducer(fn_reducer):
"""
Returns True if fn_reducer specifies the built-in reducer.
"""
return (fn_reducer == 'aggregate') | 0133273062d1661a7e60be1c11eb336825008ce6 | 685,715 |
def format_code(entry):
"""
Formats the viewing of code and errors
"""
code = ""
for line in entry.split('\n'):
code += "\n|G>>>|n %s" % line
return code.strip() | dfcc4482493333a91e0877a30dd04adc10edd00e | 685,716 |
def addmixconstraints256(model, config, var_x, current_round):
"""
Adds the mix layer. Note that this layer is only defined if there
are exactly two AES states.
"""
assert(config["aesstates"] == 2)
# Columnwise permutation
permutation = [0, 4, 1, 5,
2, 6, 3, 7]
state... | a2d203179bfddcccb3484862f4d71a6892132f6e | 685,717 |
def reverse_list(head):
"""
:type head: Node
:rtype: Node
"""
if not head and not head._next:
return head
prev = None
while head:
current = head
head = head._next
current._next = prev
prev = current
return prev | 02e4aa372199cc8ce8b5be479abc4d934430d6bb | 685,718 |
from typing import Union
def _is_dict(data: Union[dict, list]) -> bool:
"""
Checks whether provided data structure is a dictionary or not.
:param data: The data to check
:return: true if is dict, false otherwise
"""
if isinstance(data, dict):
return True
return False | 77ff0ac36c85700e0b9a32172ccd8f426419c848 | 685,719 |
def flatten(data):
"""Returns a flattened version of a list.
Courtesy of https://stackoverflow.com/a/12472564
Args:
data (`tuple` or `list`): Input data
Returns:
`list`
"""
if not data:
return data
if type(data[0]) in (list, tuple):
return list(flatten(dat... | f105493b23bdd08560e5a6a60bb59966a462f69a | 685,720 |
from typing import List
from typing import FrozenSet
def minimize_cutsets(cutsets: List[FrozenSet]):
""" Inefficient method used for testing. Assumes all in cutsets are valid but some are not minimal."""
cutsets.sort(key=lambda c: len(c))
results = set()
for c in cutsets:
minimal = True
... | fdb5e8447ac5fbe7c629c5ff1cba7013e7291a52 | 685,721 |
def detect_cycle(variable, substitutions):
"""check whether variable has been substituted before"""
# cycle detection
if not isinstance(variable, list) and variable in substitutions:
return True
elif tuple(variable) in substitutions:
return True
else:
has_cycle = False
... | 1ae00b9ea6ad85905bde4541908d807a4c92a3f0 | 685,723 |
def operation(scaled_embeddings, approach, dim = -1):
"""
defines the operation over the scaled embedding
"""
assert approach in ["sum-over", "max-pool", "mean-pool"]
if approach == "sum-over":
return scaled_embeddings.sum(dim)
elif approach == "max-pool":
... | cb675d6fbbd5346e855cca8e46c3a71ffd5ecf49 | 685,724 |
def clip(min, val, max):
"""
Returns `val` clipped to `min` and `max`.
"""
return min if val < min else max if val > max else val | b80e8e79e6ae8e0eea25e221c3bee13097da240c | 685,725 |
def solution():
"""
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
i, n = 2, 600851475143
while i * i <= n:
if n % i:
i += 1
else:
n //= i
return n | f024dc931293c8b4d9afdc468e39c5a3ebcfcce8 | 685,729 |
def unique(lst):
"""
Returns a list made up of the unique values found in lst. i.e., it
removes the redundant values in lst.
"""
lst = lst[:]
unique_lst = []
# Cycle through the list and add each value to the unique list only once.
for item in lst:
if unique_lst.count(item) <= ... | ea7da0316b397147b1f32f59e8bca14a2d861b47 | 685,730 |
def h_f(v):
""""humanize float"""
return "{:.1f}".format(v) | d8a7796330ed1e271697c92a8e6a6332b557f2e4 | 685,731 |
def reorder_commontracks_by_tag_connections(reconstruction, common_tracks, tag_graph):
"""Sort by number of connected tags to current reconstruction, then
by number of common tracks"""
# triplet that include number of tag connections
common_tracks_with_tags = []
# iterate through tracks, for each i... | 7a5dbd29413192676628bdd81fa423d8119f1bc2 | 685,732 |
import numpy
import time
import copy
def mutation(offspring_crossover):
"""
:param offspring_crossover: the population
:return: the new population with a gene of each individual mutated
"""
numpy.random.seed(seed=int(time.time()))
# define chromosomes limits
limits = [[-0.0008, 0.0008], [... | 89a9c9cdd7dfadb14e302cd02d5090a5566cf658 | 685,733 |
def _from_data_nist(data_raw):
"""Convert a NIST data format to an internal format."""
for point in data_raw:
point.pop('species_data')
return data_raw | 53160b26106587e2cfb2bd4a9cfd5201ed507418 | 685,734 |
def fetch(pars, fun):
"""
Fetch a parameter from a parameter set, computing it first if necessary.
"""
if not pars._has(fun.__name__):
fun(pars)
return pars._.__getattribute__(fun.__name__) | 8c8b16d083bb40d9a7200adb52dd5fc06593a75b | 685,735 |
from typing import List
def linear_search(arr: List[int], target: int) -> int:
"""
:param arr: Array of integers (may be sorted or unsorted)
:param target: integer we want to find
:return: position of the target in the array, -1 if not found
"""
for i in range(0, len(arr)):
if arr[i] =... | f6019243aa777d541ff1c1dfeccae6ba90b30590 | 685,736 |
import yaml
def load_local_paths(path):
"""
Load local paths .yaml file.
Parameters
==========
path : str
Path to .env file.
Returns
=======
local_paths : dict
Dictionary with environmental variables from .yaml file.
"""
with open(path, 'r') as f:
try... | 07923813202526eb1ecad4b636565458a6ed140c | 685,737 |
from pathlib import Path
import inspect
import sys
def _get_function_signature(func):
""" Get a unique signature for each function.
"""
try:
# NOTE: Unwrap function decorators because they add indirection to the actual function
# filename.
while hasattr(func, '__wrapped__'):
... | 9a9b0b2ea3439b4908369cd33ed969ac899132e2 | 685,738 |
def mass_from_column_name(mass):
"""Return the PVMassSpec mass 'M<x>' given the column name '<x>_amu' as string"""
return f"M{mass[:-4]}" | dc769442c3c276282f7e1ae76585677ef0b5bc10 | 685,739 |
def extract_content_text(xml_root):
"""
Returns all sections under a p node. After each identified p section, adds a
string interpretation of a paragraph break, i.e. two line-breaks.
:param xml_root: root of xml parse
:return: the content as a string
"""
xml_par_text = ''
for par in xml_... | 61b0fe4ba9a4748a0d0888569c4b4a58bbd0cf2c | 685,741 |
def gram_align_right(s, line_width: int = 20):
"""
Format for telegram, align right.
:param s: input text
:param int line_width: Width
:return: str
"""
return '`{}`'.format(str(s).rjust(line_width)) | 5b317c7145d9736dff5c7df167603f018d446f47 | 685,742 |
def recurse_fib(n):
""" F(n) = F(n - 1) + F(n - 2) """
if n < 2:
return n
else:
return recurse_fib(n - 1) + recurse_fib(n - 2) | 03e45b71e14d711e776233d39355f73e7b60c308 | 685,743 |
import torch
from typing import Tuple
def get_idxs_tuple(idxs: torch.Tensor
) -> Tuple[torch.Tensor, ...]:
"""
@param idxs - Shape (num indices, num dimensions that the indices index into).
@returns - A tuple, which can be directly used to index into a tensor, eg tensor[idxs_tuple].
... | b61318711c11d516295081276c11e0236a7c9520 | 685,744 |
def process_local_results(results, sensitive_species, number=10):
"""
Return a dictionary of processed results along with a formatted string
given results from local uncertainty analysis.
"""
processed_results = {}
for spc in sensitive_species:
total_var, reaction_u, thermo_u = results[s... | 7fc1c63df0d93bff37342c7ae65c8a9926412c71 | 685,745 |
def product(pmt1, pmt2):
""" the product of two permutations
"""
nelem = len(pmt1)
assert sorted(pmt1) == sorted(pmt2) == list(range(nelem))
prod = tuple(pmt2[i] for i in pmt1)
return prod | 3dfd288f921aa0de6b6ba4cc224a1c112a217068 | 685,746 |
from typing import Set
from typing import Dict
def make_indices_to_labels(labels: Set[str]) -> Dict[int, str]:
""" Creates a mapping from indices to labels. """
return {index: label for index, label in
enumerate(["pad"] + sorted(list(labels)))} | def903371ae37f33db1a0e4db064c4f9d68c9531 | 685,747 |
def _to_int(self) -> int:
"""Convert named tuples with _field_bits attribute to int."""
num = 0
for value, (_, shift) in zip(self, self._field_bits):
num |= (value << shift)
return num | 71dd0fd8997b2508a7c41002d9a86fe79500e4b5 | 685,748 |
def pstring(state, num):
"""Return a nice string give a state and its count.
Example:
>>> pstring(X(0,-1,1),4)
( 0, *, 1) : 4
"""
a,b,c = state
if b == -1:
b = " *"
return f"({a:2},{b:2},{c:2}) : {num:2}" | 3af8fe9b35d43dbca4f03b98c0f43721c6822203 | 685,749 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.