content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
import requests
import sys
def get_data_path_or_download(dataset, data_root):
"""Finds a dataset locally and downloads if needed.
Args:
dataset (str): dataset name. For instance 'camouflage_n=100000_2020-Oct-19.h5py'.
See https://github.com/ElementAI/synbols-resources/tree/maste... | 195ce4a3b9849649a3993c1c89e2e3743e19bbcf | 671,932 |
def get_aliases(cur, cp):
"""get all aliases of a codepoint"""
cur.execute("SELECT alias FROM codepoint_alias WHERE cp = %s", (cp,))
return map(lambda s: s['alias'], cur.fetchall()) | bd1e541a4d7b4f56955cd98b496c290a562c3ef6 | 671,933 |
def select_matching_record(dataframe, linked_row, matching_col):
"""Return dataframe row based on matching column name"""
return dataframe[
dataframe[matching_col] == linked_row[matching_col]
].compute() | 09ff9ec683d1199e8736d8cb8c673b514ba4609f | 671,934 |
import six
def column_info(df):
"""Returns a list of columns and their datatypes
Args:
df (`pandas.DataFrame`): The dataframe to get info for
Returns:
:type:`list` of :type:`dict`: A list of dicts containing column ids and their
Dtypes
"""
column_info = []
for co... | ea1652133b976d529e6440cdcb2f397c1b3109bc | 671,936 |
def other_features(sent, i):
"""
Get token features (not related to embeddings) for a word.
:param sent:List of lists, each word in the sentence has a list of different elements (token, pos, lemma, etc).
:param i: Which word we are getting features for.
:return:A dict of use_embeddings features for... | 6c4d7a376a1ccdab184bb070f4ff0e563bf4950b | 671,937 |
import requests
import tempfile
import gzip
def get_cif(code, mmol_number, outfile=None):
"""
Parameters
----------
code : str
PDB code.
mmol_number : int
mmol number (biological assembly number) of file to download. Numbers from PDBe.
If None, defaults to the preferred bio... | b76ff7bfddaf64df862cff1773cdf82deee99ea1 | 671,938 |
def row_to_dictionary(row_obj, exclude_None=True):
"""Convert a row to a Python dictionary that is easier to work with"""
if "cursor_description" in dir(row_obj):
column_names = [desc[0] for desc in row_obj.cursor_description]
row_dict = {}
for i in range(len(column_names)):
... | 2bc887a751537efe984ae62ffb19fedbdd6b0536 | 671,939 |
from typing import Sequence
import os
def read_file(path_segments: Sequence[str]) -> str:
"""Read a file from the package.
Params:
path_segments: a list of strings to join to make the path.
"""
here = os.path.abspath(os.path.dirname(__file__))
file_path = os.path.join(here, *path_segments... | 16e088a141262e5f36f6604125bcdf79fdbe2b93 | 671,940 |
import re
def read_data_table(filename: "str") -> "dict":
"""
Reads in a CSV file containing columnwise data for various elements, and returns a dictionary containing the data.
Lines beginning with "#" are ignored
:param filename: A valid filename for a csv file
:type filename: str
:return: A... | 44a8407153867016ec8b7f62505da11a8ebcffee | 671,941 |
def last_column_type(column_types):
"""Return the max order in the order types."""
return max([v['order'] for v in column_types.values()], default=0) | 98ff619ae143e6e62efc2baa01f1e6b50081db50 | 671,943 |
def le16(data, start=0):
"""
Read value from byte array as a long integer
:param bytearray data: Array of bytes to read from
:param int start: Offset to start reading at
:return int: An integer, read from the first two bytes at the offset.
"""
raw = bytearray(data)
return raw[start] ... | 2e085120a9dc129dfdf8b03ce2490ad1e4fbf5ea | 671,944 |
import os
import json
def init_extra_data(config, data):
"""Initialize extra data."""
# If --update is set and output file exists, read previous data
if config.update and os.path.exists(config.outfile):
with open(config.outfile) as f:
return json.load(f)
# Otherwise create an empty... | 50e0bf12d6f565948f8896a87258060c204f5bfc | 671,945 |
def reverseStringRecursive(a_string):
"""assumes a_string is a string
returns a string, the reverse of a_string"""
# base case
if len(a_string) <= 1:
return a_string
# recursive case
else:
return a_string[-1] + reverseStringRecursive(a_string[:-1]) | f5dc8d235671b8b2ba3816007c381a2deb072a3e | 671,946 |
def get_menulist(yamlobj, root=False):
"""
This function parses objects returned by get_menucontent() and prepares
input for draw_menu().
:param yamlobj: Python object ( nested list / dicts ).
:param root: True only if parsing YAML hierarchy from top.
:return: menu_ids - list of IDs, menu_title... | 62df876bd319852722d212b8e9ee132c539edf76 | 671,947 |
import re
def svgparselength(lengthstr):
"""
Parse an SVG length string into a float and a units
string, if any.
:param lengthstr: SVG length string.
:return: Number and units pair.
:rtype: tuple(float, str|None)
"""
integer_re_str = r'[+-]?[0-9]+'
number... | 483b6431981f0d13f8c1d4987a3dfb5cbf67b923 | 671,948 |
import re
import os
import fnmatch
def to_node_name(node_data):
"""Creates a node name given an input object, does a bit of silly type selecting and name rearranging. This matches for 75%
of the cases. There are a lot of user defined nodes without a clear path to generate a name. For instance the DataTableGra... | 3fef8cb33f2911488392fb21ec6da913bf9a09e3 | 671,949 |
from typing import OrderedDict
def get_candidates(results, num_results=None):
"""Return ordered tuples of candidates and their results.
:param num_results: Enforce a particular number of results, default None.
:param results: The results to get candidates from.
:returns: A list of tuples of candidat... | ee8acbf6f33e5fe3f63b71de65cfb93133ea2462 | 671,950 |
def _parse_preamble(path):
"""
Parse preamble at path.
"""
with open(path, "r") as f:
preamble = f.read().split('\n')
return preamble | f551f29e015854079abd112406b5629971570a41 | 671,951 |
def apply_(mask: str, value: str) -> int:
"""Apply binmask to value."""
bin_value = "{0:b}".format(int(value)).zfill(36)
return int("".join([m if m != "X" else b for m, b in zip(mask, bin_value)]), 2) | 45692b12a30d2ece592566988b51dcfcba703ff9 | 671,952 |
import typing
import math
def shanks(y: int, a: int, mod: int) -> typing.Union[int, None]:
"""Вычисляет x для выражения y = a ** x % mod"""
if y >= mod:
raise ValueError("y не может быть больше или равным mod")
m = k = math.ceil(math.sqrt(mod))
seq1 = {pow(a, j, mod) * y % mod: j for j in rang... | 73e909e5a58ec312549e7ddea74f45bb8e0e67d1 | 671,954 |
import random
import time
def random_id(length = 8):
""" Generates a random alphanumeric id string.
"""
tlength = int(length / 2)
rlength = int(length / 2) + int(length % 2)
chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',... | 42fc34e854c0ebcab5f19ae0ccd20edd1da1be9a | 671,955 |
import requests
from bs4 import BeautifulSoup
def get_soup(url):
"""Given a url, returns a BeautifulSoup object of that page's html"""
web_page = requests.get(url)
return BeautifulSoup(web_page.text, "html.parser") | eedabb426d409f63f0eaf71105f1f329ad7ee1e5 | 671,956 |
def index_to_position(index, strides):
"""
Converts a multidimensional tensor `index` into a single-dimensional position in
storage based on strides.
Args:
index (array-like): index tuple of ints
strides (array-like): tensor strides
Return:
int : position in storage
"""
... | 87999cabc9c465a5a787988a90ad29fdf07e3804 | 671,957 |
from typing import List
from typing import Union
def ls_strip_elements(ls_elements: List[str], chars: Union[None, str] = None) -> List[str]:
"""
>>> ls_strip_elements([' a','bbb',' '])
['a', 'bbb', '']
>>> ls_strip_elements([])
[]
"""
if (not ls_elements) or (ls_elements is None):
... | 830691f26e934d025b96e0d1c3d89d0bb634ed4d | 671,958 |
def _arith_seq_summa(qty: int, first: float, step: float) -> float:
"""Сумма элементов арифметической прогрессии."""
return qty * (first + (qty - 1) * step / 2) | 680f80f264591527d83baad8b6bf56131c7bbbc6 | 671,959 |
def create_intersected_loops_row(loop_coords, loop_id_1, loop_id_2):
"""
Create intersected loops row.
"""
row = [
loop_coords[loop_id_1]['chrom'],
loop_coords[loop_id_1]['start'],
loop_coords[loop_id_1]['end'],
loop_id_1,
'0',
'+',
loop_coords[loo... | 5c7b677d437c4da52bde799196134b57853383a1 | 671,960 |
from typing import Optional
def get_scheduler_state(code: int) -> Optional[str]:
"""Translate an schduler state code to a human-readable state.
Official mapping is available
`here <https://github.com/BOINC/boinc/blob/master/py/Boinc/boinc_db.py>`.
Args:
code:
The code of scheduler stat... | 36ae5e82ddb2cee058101e286bd1e04eedcc8956 | 671,962 |
def perform_cipher(one, two, positive):
"""Shifts elements of one by values of characters of two in positional order, with sign determined by positive."""
if len(one) > len(two):
raise ValueError("Length of object to be ciphered must be less than or equal to length of key.")
final = ""
for i in range(0, len(one))... | 2baaa31e0c837c5d735260366f1e3ff9f12a2ee5 | 671,963 |
def _clean_join(content):
"""
Joins a list of values together and cleans (removes newlines)
:param content: A str or list of str to process
:return: The joined/cleaned str
"""
if not isinstance(content, str):
content = ''.join(content) if content else ''
return content.replace('\n', ... | 6f47fe51b1fced76fe45b91ed5a83368090062ea | 671,964 |
from typing import Any
def py_is_none(x: Any) -> bool:
"""Check if x is None."""
return x is None | de9ea258cbefdf4547194c559b70aeebb19e8a2d | 671,966 |
def format_odometer(raw: list) -> dict:
"""Formats odometer information from a list to a dict."""
instruments: dict = {}
for instrument in raw:
instruments[instrument["type"]] = instrument["value"]
if "unit" in instrument:
instruments[instrument["type"] + "_unit"] = instrument["u... | 06f75f5682dcbd7c36ce112bfb0e24279376c91c | 671,967 |
def try_parse_ticket_ids(title):
"""Get ticket id from PR title.
Assumptions:
- ticket id or special prefix before PR title
- no whitespace before ticket id
- whitespace between ticket id and PR title
Transformations (for the worst case):
"ggrc-1234/1235: Do something" -> ["GGRC-1234", "GGRC-123... | 080350d8af1d070a18c461bb95fdf5e2680064ea | 671,968 |
def convert_from_digits(digits, base):
"""
calculates the sum of the numbers in the list by evaluating their base
:param digits: digits to convert
:param base: the base to convert the number to
:return: an integer
:rtype: int
"""
return sum(num * base**indx for indx, num in enumerate(rev... | a934ebbbab9e2754764593289eb9b6e3ab9c3907 | 671,969 |
import io
def get_input(file_loc="./input.txt"):
"""Docstring."""
with io.open(file_loc) as fh:
puzzle_input = fh.read().splitlines()
return puzzle_input | 1b6055c53acd09bf6b3d4fbd7909969933907764 | 671,970 |
def check_label(predicted_cui, golden_cui):
"""
Some composite annotation didn't consider orders
So, set label '1' if any cui is matched within composite cui (or single cui)
Otherwise, set label '0'
"""
return int(
len(set(predicted_cui.split("|")).intersection(set(golden_cui.split("|"))... | 65e1a5650155490637375dd4107815db28edc27e | 671,971 |
def get_song_id(url):
""" 从 url 中截取歌曲的 id """
song_id = url.split('=')[1]
return song_id | bfafb5c8b992a0c85502c4e0de1abcf88e04bd62 | 671,972 |
def get_taxnode(t, val):
"""
:param t:
:param val:
:return:
"""
name_value = val.strip().title().replace("'S", "'s")
# Title case capitalizes "'s"..geesh.
tx = "{}.{}".format(t.lower(), name_value)
return tx | b0f07eeb01c049dd6872a8464a23c540f4cad3f7 | 671,973 |
import json
def string_to_dict(value):
"""str to dict, replace '' with None"""
if not value:
return None
values = json.loads(value)
for key in values:
if values[key] == "":
values[key] = None
return values | d9d11241f32dd2d3cddbd89c604da60c3e9a18b7 | 671,974 |
import os
import argparse
def cli_load_arguments(config_file= None):
"""
Load CLI input, load config.toml , overwrite config.toml by CLI Input
"""
if config_file is None :
cur_path = os.path.dirname(os.path.realpath(__file__))
config_file = os.path.join(cur_path, "template/models_conf... | 2dbf0eae27b6541a0f1aa8cade6fe592c1a58c20 | 671,975 |
import numpy
def cov(m):
"""
Returns an estimate of the covariance matrix associated with the data m.
m is a dxn matrix where d is the number of dimensions and n is the number of points
"""
if (m.__class__ != numpy.matrix):
raise AssertionError
num_el = m.shape[1]
mean = m.mean(1)
#msu... | 98a962d63e838d54c4c544064cfc66b557f14187 | 671,977 |
def make_readable(res):
"""
Eliminates the namespace from each element in the results of a
SPARQL query.
"""
return [[uri.split("#")[-1] for uri in row] for row in res] | 877568d3d0e0a10d01b68d8cce2b71f08b56ecc2 | 671,978 |
from datetime import datetime
def strf_timestamp(timestamp, form):
"""
Helper function to safely create string date time from a timestamp value
:return: string - date time in the specified form
"""
try:
return datetime.utcfromtimestamp(timestamp).strftime(form)
except Exception: # py... | 0d9866c6bf73f084d723acb7e2a7b820c34a1105 | 671,979 |
import csv
def close_history(args):
"""close the history file and print the best record in the history file"""
args.hist_file.close()
args.hist_file = open(args.results_dir+'/history.csv', 'r', newline='')
reader = csv.DictReader(args.hist_file)
best_epoch = 0
best = {}
for epoch, record i... | ec033b6feb34343d15287a1df6f4056304187379 | 671,980 |
from typing import List
def op(input: List[int]) -> List[int]:
"""Run the input as an OP Code Program"""
pos = 0
while True:
opcode = input[pos]
# ABORT
if opcode == 99:
return input
# ADD
elif opcode == 1:
r1 = input[pos + 1]
... | 0d234984890f6d9364f693f63ff6587749164ba7 | 671,981 |
def get_latest_event_onset(dfs):
"""
input:
dfs (dict): a dict of pandas dataframes of the data.
Returns:
(list): a list of tuples of participant_id, and latest event onset date.
"""
# num levels might be more than one.
df=dfs['survey'].copy()
if 'ili' in df.columns... | 55e6104fb58d69692237a754617923cf263291dc | 671,982 |
def extractPrimitivePack(a, indices, use_tangents):
"""
Packs indices, that the first one starts with 0. Current indices can have gaps.
"""
attributes = {
'POSITION' : [],
'NORMAL' : []
}
if use_tangents:
attributes['TANGENT'] = []
result_primitive = {
'mat... | a8ceeb4344d7d6521473cc465025e0cf44ce235c | 671,983 |
def FindSimple_TwoLaneMergeDiverge(Row):
"""
Parameters
----------
Row : TYPE
Row of freeval segmentation database
Would need some information about the previous ramp. To avoid double counting Close M/D
Returns
-------
The type of ramp : 2 Lane, close M/D or None.
"""
... | 42e81e63b985e712bb0dcc36b236face4664af87 | 671,984 |
def load_federated_extensions(federated_extensions: dict) -> list:
"""Load the list of extensions"""
extensions = []
for name, data in federated_extensions.items():
build_info = data["quetz"]["_build"]
build_info["name"] = name
extensions.append(build_info)
return extensions | 76d80affc48e6e7a3dfe43b21dc19225b974791e | 671,985 |
import argparse
import os
def get_arg_parser() -> argparse.ArgumentParser:
"""Prepares the command line argument parser
Return:
Returns the argument parser instance
"""
def dir_type(dir_path: str) -> str:
"""Checks if the path is a folder
Parameters:
dir_path: path ... | f784780cb905d5c7306d9a41cae2c42cceb05e17 | 671,987 |
def svm_read_problem(data_file_name, num_features, return_scipy=False):
"""
svm_read_problem(data_file_name, return_scipy=False) -> [y, x], y: list, x: list of dictionary
svm_read_problem(data_file_name, return_scipy=True) -> [y, x], y: ndarray, x: csr_matrix
Read LIBSVM-format data from data_file_nam... | baa8e8794420a27b1813c64463952429d4fc46f1 | 671,988 |
def reduce_by_ident(retain_data, reduce_data, idents, cutoff=0.3):
"""
Remove the proteins from a list of ids which are sequence similar to the ids in another list of ids.
Args:
retain_data: List of ids which should be retained.
reduce_data: List of ids which should be reduced according to ... | f50f13e792e14194c696bf8b0ac5e3bc071a3e1d | 671,989 |
import os
import mimetypes
def guess_mimetype(filename: str) -> str:
"""Guesses the mimetype of a file based on the given ``filename``.
.. code-block:: python
>>> guess_mimetype('example.txt')
'text/plain'
>>> guess_mimetype('/foo/bar/example')
'application/octet-stream'
Parameters
----------
filen... | bfed2ecb585c0b694c1310b7b5e9e8e5b435aee4 | 671,990 |
import hashlib
def get_hash(dict_obj):
"""
Return hash of a dict of strings
"""
rec = []
for k, v in dict_obj.items():
if isinstance(v, str):
rec.append(k + ":" + v)
elif isinstance(v, list):
rec.append(k + "".join(v))
# Update, use sorted so the origin... | 36ffeb0ba74cf8efebcdc38d400ad2d940588c0f | 671,991 |
def prepare_point_field_data(res):
"""Prepare point field data.
:param res:
:return:
"""
lat_lon = res[0]['geometry']['location']
geo_location = "POINT ({} {})".format(
lat_lon['lat'],
lat_lon['lng']
)
return geo_location | 2de48cd7cdac38d5bc20ded1b745c6e8951f6151 | 671,992 |
def dup_factions(factions, num_winners):
"""Expand a list of factions by a factor of num_winners into a list of candidates
>>> dup_factions(['A', 'B'], 3)
['A1', 'A2', 'A3', 'B1', 'B2', 'B3']
"""
return [f'{f}{n}' for f in factions for n in range(1, num_winners+1)] | 7b691a7d8bf163ac55b4c75fba2864c4df72e81c | 671,993 |
from typing import List
from typing import Tuple
from typing import Optional
def _get_homos_lumos(
moenergies: List[List[float]], homo_indices: List[int]
) -> Tuple[List[float], Optional[List[float]], Optional[List[float]]]:
"""
Calculate the HOMO, LUMO, and HOMO-LUMO gap energies in eV.
Parameters
... | 356be753670b3d2503fae8db8f0ba363baab2316 | 671,994 |
def is_oneliner(txt) -> bool:
"""Checks if the given string contains no newlines."""
assert isinstance(txt, str)
return len(txt.splitlines()) == 1 | cd612c5818b9458e7a048907cdcc9aba32f41973 | 671,995 |
import pathlib
import pkg_resources
def get_requirements(source):
"""Get the requirements from the given ``source``
Parameters
----------
source: str
The filename containing the requirements
"""
with pathlib.Path(source).open() as requirements_txt:
install_requires = [
... | 68aab8795c42348b88853ea3bf9376c290c45df9 | 671,996 |
def intersect_slices(slice_1, slice_2):
"""
Finds intersection of n-dim slices slice_1 and slice_2.
Arguments:
- slice_1, slice_2: tuple or list of slices (one element for each dimension)
Returns
- slice: tuple containing intersecting slices (one element for each dimension)
"""
re... | 08261cb70cea67e7c4086ad95eb45f9904e62240 | 671,997 |
def agestr2years(age_str: str) -> int:
"""Convert an Age String into a int where the age unit is
in years. Expected formats are: nnnD, nnnW, nnnM, nnnY.
Notes
-----
The return value may not yield precise results as the following
assumptions are made: there are 365 days in a year, there are 52
... | 76a3b579aed95de608e529e2a8009f897763ecaa | 671,998 |
def format_label(fld, skip_last=False):
"""return a label consisting of subfields in a Field, properly formatted"""
subfields = fld.get_subfields('a','b','n','d','c')
if len(subfields) > 0:
if skip_last:
subfields = subfields[:-1]
return ' '.join(subfields)
else:
return None | fc4d6517b78b5b9f4077642609bb99564c7dec50 | 671,999 |
import copy
import numpy
import math
def InfodBV(float_array_input):
"""Prints the average sum as decibel whereas 1.0 is 0dB.
Parameters
----------
float_array_input : float
The audio data.
Returns
-------
dBV : float
Average power in dB.
"""
count = 0
added_... | 467207ed0d4fe021af16f6707f2c51fc9b468003 | 672,001 |
import random
def Choice(*args):
"""Can be used to sample random parameter values."""
return random.choice(args) | cd339bc771a7a2d7f317a19f684368d2d7c07f6e | 672,002 |
def to_intpmf(values, counts, simplify=True):
""" Convert an integer probability mass function to a stochastic expression. """
if len(counts) != len(values):
raise ValueError("Mismatching number of values and counts.")
if len(values) == 0:
raise ValueError("Cannot construct distribution fro... | 8b360e6256410efabbcbee90bf441b8e2d084458 | 672,003 |
def _extract_chart_params(token, width=150, height=150):
""" Check if width/height were included as first chart param (eg. 250x300) """
pieces = token.contents.split()
args = pieces[1:]
if ':' not in args[0] and 'x' in args[0]:
width, height = args[0].split('x')
width = int(width)
... | cfe2c41736dff7cbfb03bae4e1164297bf52d7c7 | 672,004 |
def buildn(s):
"""
>>> buildn(4)
4
>>> buildn(10)
19
>>> buildn(20)
299
>>> buildn(21)
399
"""
n, d = 0, 0
while s > 9:
n = 10 * n + 9
s -= 9
d += 1
if s != 0:
if n != 0:
n = s * (10 ** d) + n
else:
n = s... | 8cc9deb10b62ab7bcfda28900aff4f0227eef4be | 672,005 |
import subprocess
def create_subprocess(cmd, check_retcode=True):
"""Runs a command in a subprocess and checks for any errors.
Creates a subprocess via a call to ``subprocess.Popen`` with the argument ``shell=True``, and pipes
stdout and stderr.
Args:
cmd: `str`. The command to execute.
... | d05199a095a45850697c9008c46c939b0015c745 | 672,006 |
def use_config_replace_args(args, config):
"""
Update the running config to the args
"""
for key, value in config.items():
if key != "data_path":
setattr(args, key, value)
return args | 6b1a8788ae22334b634a056a251d76f43da5fd54 | 672,007 |
def load_textblock_support(context):
"""Prints out CSS and HTML code needed for text block administration to work"""
return context | 61d2aa1a6e3cdb1a3070bb271e4bd3ea087a25fb | 672,008 |
import os
def list_files(images_path):
"""
returns a list of names (with extension, without full path) of all files
in folder path
"""
imageFiles = []
for name in os.listdir(images_path):
if os.path.isfile(os.path.join(images_path, name)):
imageFiles.append(name)
return... | 0cdb138dbced99e03688d1f615b2731e909dba2e | 672,009 |
def isPathExcluded(curPath,excludePath):
""" Returns True if excludePath is part of parameter curPath, otherwise False. """
try:
curPath.relative_to(excludePath)
return True
except ValueError:
return False | d888302bc1a8976bed4e9d2d9dc6d12929fe968f | 672,010 |
from typing import List
def head_commit_query(user: str, repo: str, branches: List[str]) -> str:
"""
Fetch the head commit for a list of branches
"""
def branch_part(branch: str, num: int) -> str:
return f"""
r{num}: repository(name: "{repo}", owner: "{user}") {{
ref(quali... | b8dd69fef321fe882d046e9be7399abafc1386ce | 672,011 |
def holling_type_0(X,idx_A,coefficient):
""" linear response with respect to *destination/predator* compartment
For examples see:
`Examples <https://gist.github.com/465b/cce390f58d64d70613a593c8038d4dc6>`_
Parameters
----------
X : np.array
containing the current state of the conta... | 354b3a8b041bec0c287764daf0dcd919f76531d8 | 672,012 |
import sys
def normalized_bitscore(m8file):
"""
Parse a rapsearch m8 file and calculate the normalized bit score for each entry
:param m8file:
:return: a hash of subject id->normalized bit score
"""
nbs = {}
with open(m8file, 'r') as f:
for l in f:
if l.startswith("#")... | 00cff6681c11abc79eb0f751c431505a06465875 | 672,013 |
def custom_scaler(train_x, scaler):
"""
Scales data by simply dividing. No subtraction takes place.
Parameters:
train_x: The data. Shape=(m,n)
scaler: The scaling vector. Shape= (m,)
Returns:
train_x: Inplace scaling happens.
"""
train_x=train_x/scaler
return train_x | 5ec00e8800f7098d4772f1cff45e9fd13945449b | 672,014 |
def combine_programmers_info(infos):
"""."""
all_info = {'names': []}
for info in infos:
names = info.get('names', [])
for name in names:
if name not in all_info['names']:
all_info['names'].append(name)
name_info = info.get(name, {})
if nam... | 1231a0fbb5791997fa02903387d59afcd22a335d | 672,015 |
def build_condition_pairs(conditions):
""" Return the list of parameter pairs in a form of strings
Inputs
------
conditions : dict
dictionary with arguments
Outputs
-------
condition_pairs : list of str
parameter pairs in strings
"""
condition_pairs = []
for key in conditions.keys():
... | b7b30b569eb230f8f3da32f40c75f70fd29b4fba | 672,016 |
def parse_intf_status(lines):
"""
@summary: Parse the output of command "show interface description".
@param lines: The output lines of command "show interface description".
@return: Return a dictionary like:
{
"Ethernet0": {
"oper": "up",
"admin": "up... | dfc4590f0659fea16daac31e01c9beeae98d590f | 672,017 |
def distanc(*args):
"""Calcs squared euclidean distance between two points represented by n dimensional vector
:param tuple args: points to calc distance from
:return: euclidean distance of points in *args
"""
if len(args) == 1:
raise Exception('Not enough input arguments (expected two)')
... | c1e52723970c243876e89a9dbdb91c5d5580a49d | 672,018 |
def count_items(column_list):
"""
Conta a ocorrência de valores em uma coluna de uma lista
Argumentos:
column_list: A lista de valores de uma coluna.
Retorna:
Retorna os tipos de valor possíveis e a quantidade deles, nesta ordem.
"""
item_types = []
count_items = []
for... | e59df5c5c25417444fe88cf89a0c0832e836df5e | 672,019 |
def r_int_asr( f , a , b , tol , w , fa , fb , m , cluster=False , sfreq=-1.0 ):
""" Recursive implementation of adaptive Simpson's rule for a callable function
test log:
"""
# NOTE: even fewer function calls needed if we pass down fa, fb, fm, and m
if m is None : m = ( a + b ) / 2.0 # midpoint
ml = (... | 5feb9448f641b38c5bc98c7fcdf84fcd417ffe0a | 672,022 |
import re
def version_from_file(version_filename):
"""
From OSP 13 on the version release and build numbers are reported in a
file: /etc/rhosp-release.
It reports the OSP version and the upstream release name
"""
version_pattern = "Red Hat OpenStack Platform release ([\d.]+) \((.*)\)"
ver... | 543ba456ac4ff744307886242b63591ff439c32a | 672,023 |
def main(request, response):
"""Send a response with the Origin-Agent-Cluster header given in the "header"
query parameter, or no header if that is not provided. Other query
parameters (only their presence/absence matters) are "send-loaded-message"
and "redirect-first", which modify the behavior a bit.
... | b7bb527cae06d900dd57af0d510e355aca1676d1 | 672,024 |
import json
import base64
def transform(event, context):
"""Sample Firehose transform."""
output = []
print(json.dumps(event, indent=4))
if "body" in event:
# We are calling this from the REST API
event = event["body"]
for record in event["records"]:
payload = base64.b64de... | 77c0e5e57c6838d6f2c58e44f5d2737d6b1eed8a | 672,025 |
def remove_improbable_entities(results, cutoff=3):
"""Remove improbable entities. E.g. if less than 3 characters (dm, eq, tx)"""
# Should remove links from Amazon, which give amazon undue credit.
new_results = []
for r in results:
if len(r[0]) >= cutoff:
new_results.append(r)
re... | 24ae486fa219f283d14d47af4202d9acac68e556 | 672,026 |
def min_fountain(a,N):
"""
Count minimum number of fountains to be activated to cover the entire garden
There is a one-dimensional garden of length N. In each position of the N length garden, a fountain has been installed.
Given an array a[]such that a[i] describes the coverage limit of ith fountain. A... | 6003a41dcc2757e4daac3b5271437205bad0d049 | 672,027 |
from typing import Dict
def role_playing_hubs() -> Dict[str, str]:
"""Build role playing hubs definition."""
return {"h_customer_role_playing": "h_customer"} | 6aff38d2704ae960874bf3c7449ce97acddec79c | 672,028 |
def _is_nested_type(field_type: type) -> bool:
"""Determine whether a typing class is nested (e.g. Union[str, int])."""
return type(field_type._subs_tree()) is tuple | 09bcda59ae59ca243baa45f5b7ba02ae87d5cbba | 672,029 |
def _lookup_option_cost(tier_dict, premium):
"""
Returns the per share option commission for a given premium.
"""
if tier_dict is None:
return 0.0
for (min_val, max_val) in tier_dict:
if min_val <= premium < max_val:
return tier_dict[(min_val, max_val)]
raise Exceptio... | d741824edf427f0124eb0ab2f63f3150a5ad3577 | 672,030 |
def sanitizePath(path, failIfEmptyString=True):
"""
converts all backslashes to forward slashes and adds a slash at
the end of the given string, if not already present
@param path the path that should be sanitized
@return returns the sanitized path
"""
if path == '' or path is None:
... | 1bb41564e278370a3e98de3a5e6452bf8f2acc4b | 672,032 |
import sys
def is_frozen_as_exe() -> bool:
"""Check if script is frozen as an exe using PyInstaller.
Eli (12/20/19) cannot figure out how to mock sys, so this is not
unit tested.
"""
return hasattr(sys, "_MEIPASS") | f7929c7dd55d6c5a076a531186f70742a6172fb1 | 672,033 |
def calc_formation_enthalpy(ergs_react,erg_prod,coeffs):
"""
Calculate the formation enthalpy using energies and coefficients of reactants,
and energy of product.
"""
if len(ergs_react) != len(coeffs):
raise ValueError('len(ergs_react) != len(coeffs)')
dH = erg_prod
for i in range(le... | 8e3b3573a145b2d5d1ba24ece2e2c4a8279bafbc | 672,034 |
def fill_names(vals, spws, default='spw'):
"""Create name base
"""
if len(vals)==0:
base = default
else:
base = vals[0]
return ['%s%s' % (base, spw[0]) for spw in spws] | 48d55ac16827f31452a010b6545ff58ddacd3de3 | 672,035 |
def format_all_sides(value):
"""Convert a single value (padding or border) to a dict
with keys 'top', 'bottom', 'left' and 'right'"""
all = {}
for pos in ('top', 'bottom', 'left', 'right'):
all[pos] = value
return all | 33a86122b2cbe24be79c4cc25b43cba59f781792 | 672,036 |
def remember_umbrella(weather_arg: str) -> bool:
"""Remember umbrella
Checks current weather data text from :meth:`get_weather` for keywords indicating rain.
Args:
weather_arg: String containing current weather text of specified city.
Returns:
True if any of the rain keywords are foun... | a912b75f1e4a32c7088120e09843609a08fe20f3 | 672,037 |
import colorsys
def color_RGB_to_hsv(iR: float, iG: float, iB: float) -> tuple[float, float, float]:
"""Convert an rgb color to its hsv representation.
Hue is scaled 0-360
Sat is scaled 0-100
Val is scaled 0-100
"""
fHSV = colorsys.rgb_to_hsv(iR / 255.0, iG / 255.0, iB / 255.0)
return rou... | 87e0a45cae0c9577bd2a51689422dd49dec79e01 | 672,038 |
def cube(x):
"""
Return the cube of number.
>>> cube(2)
8
>>> cube(-2)
-8
"""
return x ** 3 | a9775e6ea404852e62b687ea6e64df2a0c23af61 | 672,039 |
def make_bool(s):
""" Convert string to bool """
return True if s.lower() == 'true' else False | d9c0d0d0a7e14cb5f520aacd11717de7b4a4ef94 | 672,040 |
import numpy
def ppndf(p):
"""Returns the Deviate Scale equivalent of a false rejection/acceptance ratio
The algorithm that calculates the deviate scale is based on function
``ppndf()`` from the NIST package DETware version 2.1, freely available on
the internet. Please consult it for more details. By... | ec4d784043a7a16c770eadb512cc531b2b27d160 | 672,041 |
def dict_item(d, k):
"""Returns the given key from a dictionary."""
return d[k] | 57ba01362a9051c97f12e166e1f9c33e03a70615 | 672,042 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.