content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def fexists(sftp, path): """os.path.exists for paramiko's SCP object """ try: sftp.stat(path) except IOError: return False else: return True
3cff765bbc8cc3f5ed3a3165473961ebfc04ec94
28,038
import random def random_guesser_v1(passage): """Takes in a string and returns a dictionary with 6 keys for the binary values representing features of the string, and another six keys representing the scores of those features. Note: for the scores, 0 represents no score, while -1 represents '...
b2759839fcdd59d36aa2bf6643750970affc77a1
28,042
def most_similar(train, test, distances): """ get the most similar program name Parameters ---------- train: list a list of string containing names of training programs test: list a list containing names of test progra...
324722574bbbdbda61e7e4bc65669c2ce9674630
28,045
def decimal_hours(timeobject, rise_or_set: str) -> float: """ Parameters ---------- timeobject : datetime object Sunrise or -set time rise_or_set: string 'sunrise' or 'sunset' specifiying which of the two timeobject is Returns ------- float time of timeobject in d...
44fe260abf8751cb78cf6e484dbf223d05233713
28,046
def sqrt(pop): """ Returns square root of length of list :param pop: List :return: Square root of size of list """ return len(pop) ** 0.5
877ae17cbe2cdd3a5f5b2cb03fc8d0b7af48c916
28,052
import re def is_hex_color(color: str) -> bool: """ Checks if a given color string is a valid hex color :param color: :return: """ match = re.search(r"^#(?:[0-9a-fA-F]{3}){1,2}$", color) if not match: return False return True
a86632883ccc05bc393b1b310c0fdf2eff559e55
28,057
import logging def get_logger(name): """ Retrieves a logger. :param name: The name of the logger :returns: The requested logger :rtype: logging.getLogger instance """ log = logging.getLogger(name) log.setLevel(logging.ERROR) return log
45d36a78d1a076123a93b3460774056685befc1e
28,058
def get_cls_db(db_name): """ Get benchmark dataset for classification """ if db_name.lower() == 'cls_davis': return './dataset/classification/DAVIS' elif db_name.lower() == 'cls_biosnap': return './dataset/classification/BIOSNAP/full_data' elif db_name.lower() == 'cls_bindingdb':...
89cf36b94299e4a4e1b2a4880ae1e891e37e77ac
28,061
import pathlib def get_file_size(file_path): """ Returns file size """ file = pathlib.Path(file_path) return file.stat().st_size
aa90923cd117b2b96a76c8d29d6218e3a577d5df
28,069
import math def deRuiter_radius(src1, src2): """Calculates the De Ruiter radius for two sources""" # The errors are the square root of the quadratic sum of # the systematic and fitted errors. src1_ew_uncertainty = math.sqrt(src1.ew_sys_err**2 + src1.error_radius**2) / 3600. src1_ns_uncertainty = ...
55c7f174b61c249427f09cec3c885c049f1d38dc
28,075
def fix_data(text): """Add BOS and EOS markers to sentence.""" if "<s>" in text and "</s>" in text: # This hopes that the text has been correct pre-processed return text sentences = text.split("\n") # Removing any blank sentences data sentences = ["<s> " + s + " </s>" for s in senten...
b502784e9e8fa8875030730595dcaaae66e2f31b
28,083
import base64 def b64_encode(value: bytes) -> bytes: """ URL safe base 64 encoding of a value :param value: bytes :return: bytes """ return base64.urlsafe_b64encode(value).strip(b"=")
40a7dfbec7ec390a71cdacc5ab54ce8e2a092754
28,084
def comment_scalar(a_dict, key): """Comment out a scalar in a ConfigObj object. Convert an entry into a comment, sticking it at the beginning of the section. Returns: 0 if nothing was done. 1 if the ConfigObj object was changed. """ # If the key is not in the list of scalars there is...
f2121caa4e58ec88527ae128a0ac9669efa066d7
28,089
from datetime import datetime def xml2date(s): """Convert XML time string to python datetime object""" return datetime.strptime(s[:22]+s[23:], '%Y-%m-%dT%H:%M:%S%z')
762480533d8e64544b4b4c4c67093098dcfebb56
28,091
def atom2dict(atom, dictionary=None): """Get a dictionary of one of a structure's :class:`diffpy.structure.Structure.atoms` content. Only values necessary to initialize an atom object are returned. Parameters ---------- atom : diffpy.structure.Structure.atom Atom in a structure. di...
6873c64bd39d211a43f302375d6a6c76e3bd0b7e
28,103
def get_connectivity(input_nodes): """Create a description of the connections of each node in the graph. Recurrent connections (i.e. connections of a node with itself) are excluded. Args: input_nodes (:obj:`list` of :obj:`Node`): the input operations of the model. Returns: ...
ea14ff70f4c821744079219a2ec3ee50acc0483b
28,104
def get_message_with_context(msg: str, context: str) -> str: """ Concatenates an error message with a context. If context is empty string, will only return the error message. :param msg: the message :param context: the context of the message :return: the message with context """ if len(...
8d625b297ba4510fdef3476138bafd1e210fcaa6
28,105
def unique(list1, list2): """Get the unique items that are in the first list but not in the second list. NOTE: unique(l1,l2) is not always equal to unique(l2,l1) Args: list1 (list): A list of elements. list2 (list): A list of elements. Returns: list: A list with th...
9e870319287ef7296cb5f54dc1089dc676ecc553
28,109
def get_classes(module, superclass=None): """ Return a list of new-style classes defined in *module*, excluding _private and __magic__ names, and optionally filtering only those inheriting from *superclass*. Note that both arguments are actual modules, not names. This method only returns classe...
9b31c7179a29b148e8e7503fa8bc06282e1248b4
28,112
from hashlib import md5 as _md5 def get_filesize_and_checksum(filename): """Opens the file with the passed filename and calculates its size and md5 hash Args: filename (str): filename to calculate size and checksum for Returns: tuple (int,str): size of data and its ...
b8e1c0dc6bcb9785d2c6f47dbebe6ccedf18b1af
28,113
def exception_str(exc): """Call this to get the exception string associated with the given exception or tuple of the form (exc, traceback) or (exc_class, exc, traceback). """ if isinstance(exc, tuple) and len(exc) == 3: return str(exc[1]) return str(exc)
eb3729cc49a5e346fbd9c064f2fe0fc4ef4bd2c2
28,129
def xidz(numerator, denominator, value_if_denom_is_zero): """ Implements Vensim's XIDZ function. This function executes a division, robust to denominator being zero. In the case of zero denominator, the final argument is returned. Parameters ---------- numerator: float denominator: floa...
45782f957c56a0f91528d6d945c5d7887fd68e95
28,131
def mock_exists(file_map, fn): """ mock os.path.exists() """ return (fn in file_map)
f68741c4bd4da3e5f4d32dce1ef9c249495c8f5a
28,132
def linear_function(x,m,b): """ Get the y value of a linear function given the x value. Args: m (float): the slope b (float): the intercept Returns: The expected y value from a linear function at some specified x value. """ return m*x + b
929882eb3f3e4b0767458c63ed17ca67fc6ab17f
28,133
def pp_timestamp(t): """ Get a friendly timestamp represented as a string. """ if t is None: return '' h, m, s = int(t / 3600), int(t / 60 % 60), t % 60 return "%02d:%02d:%05.2f" % (h, m, s)
d1766cabcff9f09c145d98536900e9a82e734f63
28,139
def remove_hook_words(text, hook_words): """ removes hook words from text with one next word for text = "a b c d e f" and hook_words = ['b', 'e'] returns "a d" (without b, e and next words) """ words = text.split() answer = [] k = 0 while k < len(words): if words[k] in...
aaa1706fe7d9322d900ef346f3189824d06f8df2
28,142
def is_u2f_enabled(user): """ Determine if a user has U2F enabled """ return user.u2f_keys.all().exists()
39b3b93e03eee230fc978ad5ec64ba4965b2d809
28,149
def extend_feature_columns(feature_columns): """ Use to define additional feature columns, such as bucketized_column and crossed_column Default behaviour is to return the original feature_column list as is Args: feature_columns: [tf.feature_column] - list of base feature_columns to be extended ...
11d0c77331745719d445f7926f041e2fe1c70903
28,150
def clean_data(players): """Sanitize the list of player data.""" cleaned_players = [] for player in players: cleaned_player = {} for key, value in player.items(): cleaned_value = value if key == "height": cleaned_value = int(value[0:2]) ...
88836eb154ff1a3cb32c567634adf813ac234de6
28,153
import shutil def exe_exists(exe): """ Returns the full path if executable exists and is the path. None otherwise """ return shutil.which(exe)
38bed97a3d195e6adc8e0dba936d213828f15e2f
28,156
def confusion_stats(set_true, set_test): """ Count the true positives, false positives and false negatives in a test set with respect to a "true" set. True negatives are not counted. """ true_pos = len(set_true.intersection(set_test)) false_pos = len(set_test.difference(set_true)) false...
401b216b1317f16a424830e71b48f1d21d603956
28,159
def category_parents(category): """ Get list parents of category :param category: Object category, product. e.g <8c8fff64-8886-4688-9a90-24f0d2d918f9> :return: Dict | List | List categories and sub-categories. e.g. [ { "id": "c0136516-ff72-441a-9835-1ecb37357c41", ...
84616c76fb4179eb2f91600699e1f07d0de9b15f
28,162
from typing import Iterable from typing import Dict from typing import Any from typing import List import collections def _list_dict_to_dict_list(samples: Iterable[Dict[Any, Any]]) -> Dict[Any, List[Any]]: """Convert a list of dictionaries to a dictionary of lists. Args: samples: a list of dictionari...
a5bd1dea71306f5e8151f6dfcc94b96f328b6d76
28,165
def count_rule_conditions(rule_string: str) -> int: """ Counts the number of conditions in a rule string. Parameters ---------- rule_string : str The standard Iguanas string representation of the rule. Returns ------- int Number of conditions in the rule. """ n_...
4dc8bc3fdc7ee4d4302101a39b7849bcd7dff6e8
28,166
def check_length_of_shape_or_intercept_names(name_list, num_alts, constrained_param, list_title): """ Ensures that the length of the parameter names matches the number of pa...
d83ed7d6989c7e3ccdbbb256eaa72759a7f242d3
28,167
def get_token_object(auth): """ Retrieve the object or instance from a token creation. Used for knox support. :param auth: The instance or tuple returned by the token's .create() :type auth tuple | rest_framework.authtoken.models.Token :return: The instance or object of the token :rtype: r...
3651951e413f3fd44f159ed6070542d54f2923b2
28,169
def format_interconnector_loss_demand_coefficient(LOSSFACTORMODEL): """Re-formats the AEMO MSS table LOSSFACTORMODEL to be compatible with the Spot market class. Examples -------- >>> LOSSFACTORMODEL = pd.DataFrame({ ... 'INTERCONNECTORID': ['X', 'X', 'X', 'Y', 'Y'], ... 'REGIONID': ['A', 'B',...
a7a87543eedb33248f6532ec234d47b7fe5455b3
28,170
from datetime import datetime def to_time_string(value): """ gets the time string representation of input datetime with utc offset. for example: `23:40:15` :param datetime | time value: input object to be converted. :rtype: str """ time = value if isinstance(value, datetime): ...
b81ffff8b4ab626e0094bcfeb0bf6916de89d344
28,172
def u(string: str) -> bytes: """Shortcut to encode string to bytes.""" return string.encode('utf8')
3310da2d9f24be94c0426128ac19db2481dd2c2d
28,173
def dictToTuple(heading, d): """Convert dict into an ordered tuple of values, ordered by the heading""" return tuple([d[attr] for attr in heading])
1a76201da4e5348a4c4ba9607992ad41a1c87163
28,179
def twoballs_filename(data_dir, num_examples, num_feat, num_noise_feat, frac_flip): """Generate filename to save data and permutations""" data_filename = data_dir + '/twoballs_n=%d_%d:%d_rcn=%1.1f.csv'\ % (num_examples, num_feat, num_noise_feat, frac_flip) perm_filename = data_dir + '/twoballs_n=%d_...
8b965192527088017ca5544894c1257e22222caf
28,182
def getcompanyrow(values): """ :param values: :return: list of values representing a row in the company table """ companyrow = [] companyrow.append(values['_COMPANYNUMBER_']) companyrow.append(values['_COMPANYNAME_']) companyrow.append(values['_WEBADDRESS_']) companyrow.append(valu...
ea7b96c13797cf9aeeaa6da4d25e9144e2fc4524
28,184
def _get_deconv_pad_outpad(deconv_kernel): """Get padding and out padding for deconv layers.""" if deconv_kernel == 4: padding = 1 output_padding = 0 elif deconv_kernel == 3: padding = 1 output_padding = 1 elif deconv_kernel == 2: padding = 0 output_paddin...
3c4a161e2d67bdb81d7e60a5e65ce232a4b0d038
28,186
import requests import shutil def download_file(url): """ Download file at given URL. - url: url of file to be downloaded - return: downloaded file name """ filename = url.split('/')[-1] r = requests.get(url, stream=True) with open(filename, 'wb') as f: shutil.copyfileobj(...
b153f84f6f04299e460e19b9703d2ebd30804144
28,187
def recip_to_duration(recip): """Convert a humdrum recip string to a wholenote duration. """ # Breves are indicated by zero. if recip[0] == '0': duration = 2 else: duration = float(recip.rstrip('.')) ** -1 dots = recip.count('.') return (2 * duration) - duration*(2.0 ** (-1...
200e86809488ab90df2e9dc0dde8bf7260804bc8
28,192
import random def weighted_sampler(pop_dict, k=1): """randomly sample a dictionary's keys based on weights stored as values example: m = {'a':3, 'b':2, 'c':5} samps = weighted_sampler(m, k=1000) #samps should be a ~ 300, b ~ 200, and c ~ 500 >>> samps.count('a') 304 >>> s...
421cd16931a4b6695c8800cbc140aa86b9ce413a
28,196
def points_to_vector(point1, point2): """ Return vector from point1 to point2 """ return point2 - point1
b8333afc6ecf6dbc8e1a9571b64d195ba896a73e
28,198
import torch def vector_to_index(vector, all_zeros=-1): """ Converts a binary vector to a list of indices corresponding to the locations where the vector was one. """ l = len(vector) integers = torch.Tensor([i+1 for i in range(l)]) # i+1 so that the zeroth element and the zeros vector below don't ...
ba052dc3ed81e188249ad5e0192d864675412807
28,201
def enforce_use_of_all_cpus(model): """For sklearn models which have an `n_jobs` attribute, set to -1. This will force all cores on the machine to be used. Args: model : sklearn model A trainable sklearn model Returns: model : sklearn model Model 'as is' wit...
6fb7878700ffc2fea960432ed76f6d1d90638a32
28,203
from contextlib import redirect_stdout import io def capture_stdout(func, *args, **kwargs): """Capture standard output to a string buffer""" stdout_string = io.StringIO() with redirect_stdout(stdout_string): func(*args, **kwargs) return stdout_string.getvalue()
4b9f4ed54644a28850d0f68e2dda1f484fa9644c
28,205
import torch def l2_dist_close_reward_fn(achieved_goal, goal, threshold=.05): """Giving -1/0 reward based on how close the achieved state is to the goal state. Args: achieved_goal (Tensor): achieved state, of shape ``[batch_size, batch_length, ...]`` goal (Tensor): goal state, of shape ``[bat...
ca65cb272f13a6caa5f88c75d4129bf15dc3c22d
28,208
def update_kvk(kvk): """ Function to update outdated KvK-numbers :param kvk: the orginal KvK-number :return: the updated KvK-number, if it was updated """ # Make sure KvK-number is a string kvk = str(kvk) # Add zero to beginning of outdated KvK-number and return it if len(kvk) == 7...
61b1d490de866786330a698e0370a360856c14a9
28,209
from typing import Union def check_positive_int(input_int: Union[str, int]) -> int: """Check if `input_int` is a positive integer. If it is, return it as an `int`. Raise `TypeError` otherwise """ input_int = int(input_int) if input_int <= 0: raise ValueError(f"A positive integer is expecte...
686b062a3df929541a708fca0df10d3ae5a09088
28,210
def has_perm(user, perm): """Return True if the user has the given permission, false otherwise.""" return user.has_perm(perm)
01f3395f45c5ef0274b4b68fc557fa5f8e7b9466
28,211
def format_date_string(date_str): """ :param date_str: expects the format Thu Feb 28 14:51:59 +0000 2019 :return: a dictionary containing day,month,hour,min """ # month_val represents the month value month_val = { 'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':...
dd77f0b87c84c0e1be57fa40c1b6bc2fdda0ad75
28,215
def get_oidc_auth(token=None): """ returns HTTP headers containing OIDC bearer token """ return {'Authorization': token}
a951cfdf83c5a0def3128ce409ced5db4fa8d3b6
28,218
def bytes_from_hex(hexcode): """ Given a valid string of whitespace-delimited hexadecimal numbers, returns those hex numbers translated into byte string form. """ return ''.join(chr(int(code, 16)) for code in hexcode.split())
fbb800f0ea7f1327b42965fab48b740fad251027
28,225
def validate_split_durations(train_dur, val_dur, test_dur, dataset_dur): """helper function to validate durations specified for splits, so other functions can do the actual splitting. First the functions checks for invalid conditions: + If train_dur, val_dur, and test_dur are all None, a ValueError...
351bcd963d68e70d434ce7939cc4d01359285d1f
28,229
from pathlib import Path from typing import Any import csv def load_csv(path: Path) -> Any: """Load data from csv file.""" with open(path, newline='') as csvfile: reader = csv.DictReader(csvfile) items = list(reader) return items
3a6d071f34bf239fb9de5c9eaabcaf6e71021373
28,233
def train_valid_split(x_train, y_train, split_index=45000): """Split the original training data into a new training dataset and a validation dataset. Args: x_train: An array of shape [50000, 3072]. y_train: An array of shape [50000,]. split_index: An integer. Returns: x_train_new: An array of shape [split...
fd8eb959fd67c5a5cdfca0399e8b4fae1ff654d8
28,241
import struct def structparse_ip_header_info(bytes_string: bytes): """Takes a given bytes string of a packet and returns information found in the IP header such as the IP Version, IP Header Length, and if IP Options are present. Examples: >>> from scapy.all import *\n >>> icmp_pcap = rdpcap('...
af8be564ec68d8ecc7f91d8483309a6312f42263
28,247
def get_config(cfg): """ Sets the hypermeters (architecture) for ISONet using the config file Args: cfg: A YACS config object. """ config_params = { "net_params": { "use_dirac": cfg.ISON.DIRAC_INIT, "use_dropout": cfg.ISON.DROPOUT, "dropout_rate":...
ea871170b7d70efde0601bbce340b3960227a459
28,254
def num2vhdl_slv(num, width=4): """ Creates a VHDL slv (standard_logic_vector) string from a number. The width in bytes can be specified. Examples: num2vhdl_slv(10, width=1) => x"0A" num2vhdl_slv(0x10, width=2) => x"0010" """ return ('x"%0' + str(width * 2) +...
a9fb6ce594bdb8756d073ae268cb03dccda7592e
28,256
import jinja2 def ps_filter(val): """Jinja2 filter function 'ps' escapes for use in a PowerShell commandline""" if isinstance(val, jinja2.Undefined): return "[undefined]" escaped = [] for char in str(val): if char in "`$#'\"": char = "`" + char elif char == '\0': ...
495cd87bfc930089aaa5f4f9b282d20b4883bfb5
28,257
import operator def multiply_round(n_data: int, cfg: dict): """ Given a configuration {split: percentage}, return a configuration {split: n} such that the sum of all is equal to n_data """ print(cfg) s_total = sum(cfg.values()) sizes = {name: int(s * n_data / s_total) for name, s in cfg.it...
6727de1f6f9bc70aa9d5bb3b53ccf73381e4a86d
28,259
from typing import List def get_combinations(candidates: List[int], target: int) -> List[List[int]]: """Returns a list of lists representing each possible set of drops. This function (and its recursive helper function) was adapted from https://wlcoding.blogspot.com/2015/03/combination-sum-i-ii.html. ...
9d68f3b69c23697d924e40d4471296223871165a
28,260
import json def simple_aimfree_assembly_state() -> dict: """ Fixture for creating the assembly system DT object for tests from a JSON file. - Complexity: simple """ with open('tests/assets/simple/aimfree_assembly_state.json') as assembly_file: aimfree_assembly_state = json.load(as...
a1cdd6e85a90d39604214d2d49a52cedbbc4b165
28,262
def implicit_valence(a): """ Implicit valence of atom """ return a.GetImplicitValence()
88b0e7682e8d142d7f0e10caa37fe67bbe4fa2e2
28,270
def joint_card(c1,c2): """Given two cardinalities, combine them.""" return '{' + ('1' if c1[1] == c2[1] == '1' else '0') + ':' + ('1' if c1[3] == c2[3] == '1' else 'M') + '}'
f9df53869d68cd7c48916ede0396787caeebadaf
28,274
def _is_hierachy_searchable(child_id: str) -> bool: """ If the suffix of a child_id is numeric, the whole hierarchy is searchable to the leaf nodes. If the suffix of a child_id is alphabetic, the whole hierarchy is not searchable. """ pieces_of_child_id_list = child_id.split('.') suffix = pieces_of_...
13146128fc8ab050323a23f07133676caeb83aaf
28,275
import re def make_job_def_name(image_name: str, job_def_suffix: str = "-jd") -> str: """ Autogenerate a job definition name from an image name. """ # Trim registry and tag from image_name. if "amazonaws.com" in image_name: image_name = image_name.split("/", 1)[1].split(":")[0].replace("/"...
e81e86e8df750434a1a9310d99256733ea0f8619
28,276
import itertools def generate_grid_search_trials(flat_params, nb_trials): """ Standard grid search. Takes the product of `flat_params` to generate the search space. :param params: The hyperparameters options to search. :param nb_trials: Returns the first `nb_trials` from the combinations ...
d35072aa26fa62b60add89f36b4343ee4e93567b
28,279
def convert_string_list(string_list): """ Converts a list of strings (e.g. ["3", "5", "6"]) to a list of integers. In: list of strings Out: list of integers """ int_list = [] for string in string_list: int_list.append(int(string)) return int_list
b75ba67c142796af13186bc4d7f67e3061a1d829
28,282
import csv def read_csv(file_name): """ Read csv file :param file_name: <file_path/file_name>.csv :return: list of lists which contains each row of the csv file """ with open(file_name, 'r') as f: data = [list(line) for line in csv.reader(f)][2:] return data
01f9aadc0bce949aa630ab050e480da24c53cc40
28,286
def get_names_from_lines(lines, frac_len, type_function): """Take list of lines read from a file, keep the first fract_len elements, remove the end of line character at the end of each element and convert it to the type definded by function. """ return [type_function(line[:-1]) for line in lines[:fr...
c9b42ef1388c0cd09b3d7d5e6a7381411438200e
28,288
def execroi(img, roi): """ Args: img(np.array): 2 dimensions roi(2-tuple(2-tuple)) Returns: np.array: cropped image """ return img[roi[0][0] : roi[0][1], roi[1][0] : roi[1][1]]
4c59dd52186888b2b1c43007a00301a43237dcb3
28,292
def selected_features_to_constraints(feats, even_not_validated=False): """ Convert a set of selected features to constraints. Only the features that are validated are translated into constraints, otherwise all are translated when `even_not_validated` is set. :return: str """ res = "" f...
e029c26b0e53874b4076c9a4d9065a558736f565
28,293
def iso_string_to_sql_utcdatetime_mysql(x: str) -> str: """ Provides MySQL SQL to convert an ISO-8601-format string (with punctuation) to a ``DATETIME`` in UTC. The argument ``x`` is the SQL expression to be converted (such as a column name). """ return ( f"CONVERT_TZ(STR_TO_DATE(LEFT({x...
1117b228c77f187b5884aeb014f2fb80309ea93a
28,294
def compute_rmsd(frame, ref): """Compute RMSD between a reference and a frame""" return ref.rmsd(frame)
b189453a409d02279851bd492a95757d1d25bccc
28,297
def iou_score(SR, GT): """Computes the IOU score""" smooth = 1e-8 SR = (SR > 0.5).float() inter = SR * GT union = SR + GT return inter.sum() / (union.sum() + smooth)
05627c3b5c62422318a2968bab0a5cfe4430b3b6
28,298
def docstring_parameter(**kwargs): """ Decorates a function to update the docstring with a variable. This allows the use of (global) variables in docstrings. Example: @docstring_parameter(config_file=CONFIG_FILE) myfunc(): \"\"\" The config file is {config_file} \"\"\" Args: ...
c69505037948f120a7c29ee500f2327001e8b80d
28,299
def arg_to_dict(arg): """Convert an argument that can be None, list/tuple or dict to dict Example:: >>> arg_to_dict(None) [] >>> arg_to_dict(['a', 'b']) {'a':{},'b':{}} >>> arg_to_dict({'a':{'only': 'id'}, 'b':{'only': 'id'}}) {'a':{'only':'id'},'b':{'only':'id'...
adc75f811d02770b34be2552445b192e33401e76
28,302
def enum(**named_values): """ Create an enum with the following values. :param named_values: :return: enum :rtype: Enum """ return type('Enum', (), named_values)
794007a79e43c3ff4af2f70efa3817c224e42bd7
28,310
def fib_1_recursive(n): """ Solution: Brute force recursive solution. Complexity: Description: Number of computations can be represented as a binary tree has height of n. Time: O(2^n) """ if n < 0: raise ValueError('input must be a positive whole number') if n in [0, 1]: return n return fib_1_recursi...
beb4a726075fed152da34706394ac1bd7ef29f17
28,311
def crop_center(img,cropx,cropy,cropz): """ Crops out the center of a 3D volume """ x,y,z = img.shape startx = x//2-(cropx//2) starty = y//2-(cropy//2) startz = z//2-(cropz//2) return img[startx:startx+cropx,starty:starty+cropy,startz:startz+cropz]
a003fb7fdbcee5e6d4a8547a2f50fa82181bdf37
28,314
def get_text(spec): """Reads the contents of the given file""" with open(spec) as fh: return fh.read()
21766304777d483af403375678389519ca1bcfe1
28,315
def _sum_edge_attr(G, node, attr, method='edges', filter_key=None, split_on='-', include_filter_flags=None, exclude_filter_flags=None): """accumulate attributes for one node_id in network G Parameters ---------- G : networkx.Graph or networkx.MultiGraph a graph network to sum...
270f0afb943b6c6828a6cc8a22452ee5eabbcfb8
28,320
def get_column_indexes(column_name_items): """ This function returns the indexes for the columns of interest from the CSV file. :param column_name_items: List of column names :type column_name_items: list :return: Column index for 'TRUTH.TOTAL', 'QUERY.TP', 'QUERY.FP', 'TRUTH.FN', 'METRIC.Precisio...
51c38d048db6530bc502dfb64e95384ee096428a
28,324
def is_sorted(t): """Predicate, true if t is sorted in ascending order. t: list """ # sorted(t) will return a sorted version of t, without changing t. # == will compare the two lists to see if their value is the same # The is operator would fail here, even if the lists look identical # i.e. ...
3c346a349cd0d870c5cef549a574674ea566ae6c
28,326
import typing def get_param_query(sql: str, params: dict) -> typing.Tuple[str, tuple]: """ Re-does a SQL query so that it uses asyncpg's special query format. :param sql: The SQL statement to use. :param params: The dict of parameters to use. :return: A two-item tuple of (new_query, arguments) ...
44d2316f346ec53354d7ebeb69387c093ab3089b
28,327
def csv_list(value): """ Convert a comma separated string into a list Parameters ---------- value : str The string object to convert to a list Returns ------- list A list based on splitting the string on the ',' character """ if value: result = [] ...
d65e004eb6696e7418e4f5f65a6271562c462cab
28,328
def find_section_id(sections, id): """ Find the section with a given id """ for idx, section in enumerate(sections): try: if section['id'] == id: return idx except KeyError: continue return None
5ee29faea5a0966873966fc85ecfe1f89b08ecbb
28,330
import typing def voiced_variants(base_phone) -> typing.Set[str]: """ Generate variants of voiced IPA phones Parameters ---------- base_phone: str Voiced IPA phone Returns ------- set[str] Set of base_phone plus variants """ return {base_phone + d for d in [""...
99111f1fcbfabb27a22efb75121d9f71cf76b64b
28,333
def clean_string(s: str, extra_chars: str = ""): """Method to replace various chars with an underscore and remove leading and trailing whitespace Parameters ---------- s : str string to clean extra_chars : str, optional additional characrters to be replaced by an underscore Ret...
7f93f1fea075bb09ba3b150a6ff768d0a266093c
28,335
from typing import Counter def count_characters_two( string ): """ Counts using collections.Count """ counter = Counter(string) return counter
d2c3b5eef156507f2b7b8b9a3b3b5a1a54a0a766
28,336
import torch def unique_2d(*X): """Get the unique combinations of inputs X. Parameters ---------- X : array-like of type=int and shape=(n_samples, n_features) Input events for which to get unique combinations Returns ------- *X_unique : np.array of sha...
8a4580c9dbbc8118f1f43d723874ccd26c4eb1ec
28,337
import torch def run_single(model: torch.nn.Module, *args) -> torch.Tensor: """ Runs a single element (no batch dimension) through a PyTorch model """ return model(*[a.unsqueeze(0) for a in args]).squeeze(0)
f0c74c90a403086cf1f0057a3ee4f8d785668e26
28,340
import hashlib def hash_file(file_path: str) -> str: """ return sha1 hash of the file """ with open(file_path, "r") as content_file: hash_object = hashlib.sha1(content_file.read().encode("utf-8")) return hash_object.hexdigest()
fb71d4610a3b081b5b69e49c721fa3a0da61e859
28,345
import torch def tensor(x): """Construct a PyTorch tensor of data type `torch.float64`. Args: x (object): Object to construct array from. Returns: tensor: PyTorch array of data type `torch.float64`. """ return torch.tensor(x, dtype=torch.float64)
2734d09e8c3a563dda48f7954029f3f857b3aff3
28,359
def _first_or_none(array): """ Pick first item from `array`, or return `None`, if there is none. """ if not array: return None return array[0]
e8430cf316e12b530471f50f26d4f34376d31ce2
28,363