content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import subprocess import re def compiler_version(): """ Return the version of the installed solc. """ version_info = subprocess.check_output(['solc', '--version']) match = re.search(b'^Version: ([0-9a-z.-]+)/', version_info, re.MULTILINE) if match: return match.group(1)
951f3bf271740a49f5a381089e981587ebb1200f
18,122
def get_payer_channel(channelidentifiers_to_channels, transfer_pair): """ Returns the payer channel of a given transfer pair. """ payer_channel_identifier = transfer_pair.payer_transfer.balance_proof.channel_address assert payer_channel_identifier in channelidentifiers_to_channels payer_channel = channe...
42a0f99a65888dbe8b19d248f5d78d2b8b5f0fd1
18,123
def forward2reverse(dna): """Converts an oligonucleotide(k-mer) to its reverse complement sequence. All ambiguous bases are treated as Ns. """ translation_dict = {"A": "T", "T": "A", "C": "G", "G": "C", "N": "N", "K": "N", "M": "N", "R": "N", "Y": "N", "S": "N", ...
81d9e1eeebc2f446ada6e88be6f4332510a8e5e4
18,124
from typing import List import struct def pack_byte(data: List[int]): """ 打包短整数 """ return struct.pack(f"{len(data)}h", *data)
1f9951e0e1052528e4c6882fdd7fd94b9ac2c9a7
18,125
def fibonacci_two(n): """计算斐波那契数列2""" return n if n < 2 else fibonacci_two(n - 2) + fibonacci_two(n - 1)
b858b565b64f97138e4e2ddc976f3f17f573c0df
18,126
def count_rect_area(matrix): """ https://leetcode-cn.com/problems/maximal-square/solution/zui-da-zheng-fang-xing-by-leetcode-solution/ :param matrix: :return: """ if not matrix: return 0 n = len(matrix) m = len(matrix[0]) ans = [[0] * m for _ in range(n)] side=0 for i...
f476637354864823a3e3f8c0821f8a91012b5e2e
18,128
def norm(str): """Normalize string for checking""" return ' '.join(str.strip().split()).lower()
a2dacc1009acbc9615c9391458fac4a1793d154e
18,129
import inspect def iscoroutinefunction(obj): """ This is probably in the library elsewhere but returns bool based on if the function is a coro """ if inspect.iscoroutinefunction(obj): return True if hasattr(obj, '__call__') and inspect.iscoroutinefunction(obj.__call__): return True return ...
ccbb3216896990a197fe8059f6212c5bf8168a14
18,130
from typing import List import pathlib def parts_to_path(parts: List[str]) -> str: """Convert list of path parts into a path string e.g j.sals.fs.parts_to_path(["home","rafy"]) -> 'home/rafy' Args: parts (List[str]): path parts Returns: str: joined path parts """ pat...
71fcc68b91bbfa868fec8f0e70dbc8434417664f
18,131
import argparse def parse_arguments(args_to_parse): """ Parse CLI arguments """ descr = 'Apply pre-processing to generate the Swahili document classification dataset' parser = argparse.ArgumentParser(description=descr) general = parser.add_argument_group('General settings') general.add_argument('...
8d44a90ad58805b010ba4c662d48707e315de583
18,132
import json def my_json_dumps(data): """my_json_dumps JSON formatter Arguments: data {str} -- Data to JSON beautify Returns: str -- Data beautified """ return json.dumps(data, indent=2, sort_keys=True)
cc9b9424b79642d3dbd6eaec2dd685ecaed3b239
18,133
import random def _replace_mlm_tokens(tokens, candidate_pred_positions, num_mlm_preds, vocab): """Defined in :numref:`sec_bert-dataset`""" # 为遮蔽语言模型的输入创建新的词元副本,其中输入可能包含替换的“<mask>”或随机词元 mlm_input_tokens = [token for token in tokens] pred_positions_and_labels = [] # 打乱后用于在遮蔽语...
3bf7c4c1db7f577f7899d3a7156d6cfd97a192cd
18,134
import json from jinja2 import Template def request_body(fixtures, api_request, data): """Set request body.""" tpl = Template(data).render(**fixtures) body = api_request["kwargs"]["body"] = json.loads(tpl) return body
544d124fd8fb0c584575ed11b514c0eccb447d96
18,136
def get_preprocess_filenames(pipelines, vocab_file, dataset_file=None): """ Gets the appropriate vocabulary file path to load. Parameters ---------- pipelines : list List of preprocessing pipelines. vocab_file : str Path of vocabulary file. dataset_file : str, optional ...
727eda55b1e2de37d5fd00569c4efa849e27e1a9
18,137
def config_emptysection(config, section): """ Create empty configuration section. :param config: Configuration dictionary. :type config: configparser.ConfigParser :param section: Section of ini file to return. :type section: str """ if not config.has_section(section): config[se...
015dc3d549bae0b162c4dcf96545af3dd5c3d2fd
18,138
def _is_utf8(filepath): """ check if file is utf8 encoding """ with open(filepath, 'rb') as f: content = f.read() try: content_utf8 = content.decode('utf-8') except UnicodeDecodeError as e: return False return True
7e92aa296122368dd4aaa2af08b9d31ac0e674f9
18,140
import click def command_line_verbose_options(f): """ Decorator for specifying verbose and json output """ f = click.option( "--verbose", is_flag=True, default=False, help="Show all URLs and metadata.", )(f) f = click.option( "--json-output", is_...
7f9222a981e6c5a1322848c2ec080a559594b653
18,141
import os def _determine_files_dir(rd): """Determine the appropriate files directory for a recipe""" recipedir = rd.getVar('FILE_DIRNAME') for entry in rd.getVar('FILESPATH').split(':'): relpth = os.path.relpath(entry, recipedir) if not os.sep in relpth: # One (or zero) levels ...
40e2c0f92a24641bf2e2afed5f9ed637ce33898d
18,142
import math def get_cross_points(a, b, c, image_height): """ solve the quadratic equation x = ay^2 + by + c Parameters ---------- a: the first coefficient of quadratic equation b: the second coefficient of quadratic equation c: the third coefficient of quadratic equation image_height:...
d27c37195631083742c006f443e4d56e6bd21d64
18,143
def insert_nested_value(dictionary, path, value): """ Given a `dictionary`, walks the `path` (creating sub-dicts as needed) and inserts the `value` at the bottom. Modifies `dictionary`, and also returns `dictionary` as a convenience. For example: >>> insert_nested_value({}...
1d2c66f2d4e05b2553bd7feb616e1ddc7c24936e
18,147
def initialize_program(): """return a dict representation of a MILP program""" return { 'variables': {}, 'constants': {}, 'constraints': { 'A_eq': [], 'b_eq': [], 'A_lt': [], 'b_lt': [], }, 'cost_function': {}, }
b855dc0bd92e00e4afe58c8bb6b56b00f1495619
18,148
def tlvs_by_type(tlvs, tlv_type): """Return list of TLVs with matching type.""" return [tlv for tlv in tlvs if tlv.tlv_type == tlv_type]
5adda249aef14dc5523dc0a8ec84bbe599a266f7
18,149
import pickle def read_pickled_data(pickle_id): """ Loads pickled data based on ID string. Parameters ---------- filter_id : str An ID strong made of the month of the request and the a hash-value generated from the filter settings. Returns ------- data: list A l...
e7f851f968880087209abf89fb23523c2653b298
18,150
import os def walkdir(folder): """Walk through each files in a directory""" results = [] for dirpath, dirs, files in os.walk(folder): for filename in files: # yield os.path.abspath(os.path.join(dirpath, filename)) results.append(os.path.abspath(os.path.join(dirpath, filenam...
c16f020df646cba983e9cf773389a96b50d5cabf
18,151
def violations(norms,env): """ Returns a dict with key as object_id and value, as a list of all apossible violations of norm on that object """ assert "Obsolete function violations should not be used" and False from verify_action_4 import check_pro_or_per,check_per,check_obl violations={} my_dic...
2780103ff61eabef49f736d339014a4ac7dd1b64
18,153
import random def random_real(): """ Returns a random real +/- from [-90, 90] for testing. """ return random.uniform(-90, 90)
2b48df3e6ccb252a262f4b5eee063183cc60ce72
18,154
def GAMMA_ASSEMBLY(X_L, X_U, D, M): """ This function calculates the light absorption coefficient. Input: X_L | Lower limit design variables | Py list[D] X_U | Upper limit design variables | Py list[D] D | Problem dimension ...
32fcf3ce72e74a6d91419ce19f29859aa5fa3ac0
18,156
import torch def get_dihedral(pos, dihedral_index): """ Args: pos: (N, 3) dihedral: (4, A) """ n1, ctr1, ctr2, n2 = dihedral_index # (A, ) v_ctr = pos[ctr2] - pos[ctr1] # (A, 3) v1 = pos[n1] - pos[ctr1] v2 = pos[n2] - pos[ctr2] n1 = torch.cross(v_ctr, v1, dim=-1) # ...
2f9cc39bd7bea7a04860b7cc2f497d0910246b83
18,157
def extract_last_modified_user(gfile): """ Extractors for the gfile metadata https://developers.google.com/drive/v2/reference/files#resource-representations :param gfile: :return: """ if 'lastModifyingUser' not in gfile: return '' user = gfile['lastModifyingUser'] email = '' ...
39ecd81da5103219d98acd750c201b3ee1f1cd2b
18,158
def get_mode_count(df): """ Computes the mode and the count of the mode from an array. Args: df - data fram with ONE column Returns: df_mode - mode of the column df_mode_count - count for that mode """ # calculate the mode and its count from the input data fram (with one column) ...
8712b6a351c6afdb328e94a633652af86a1f4eba
18,159
import json def get_settings(settings_path): """ Opens the json-file with settings and loads and returns them """ with open(settings_path) as infile: settings = json.load(infile) return settings
a4e2cfc2c63ea2c3422f42c200d1d715338f0898
18,161
def decode_dict(d, *keys): """Decode all keys and values.""" decoded = {} for key in keys: if key in d: decoded[key.decode()] = d[key].decode() return decoded
59bfe8a63ef5cb64446b2c7823218b3dae533032
18,162
def to_list(*args): """ Input: args - variable number of integers represented as strings, e.g. to_list("15353", "025") Output: lst - a Python array of lists of strings, e.g. [[1,5,3,5,3],[0,2,5]] """ lst = [] for string in args: lst.append([int(digit) for digit in string...
9cf65eccc5ec42ee91c15b2485662716c85aacab
18,163
import requests def get_user_key(api_key: str, username: str, password: str) -> str: """Login the user and retruns his ``user_key`` This key can be cached since, it is only invalidated by the next (api) login. Arguments: api_key {str} -- the api_key of the application. username {str} --...
92dd0cedfd5364378d5381b0a64844e7f789f62d
18,164
import toml def readToml(filename): """Read a single TOML configuration file, or return an empty dict if it doesn't exist. """ try: with open(filename, encoding='utf-8') as fp: return toml.load(fp) except OSError: return {} except toml.TomlDecodeError as err: ...
b5d0761015cd1fbeb94bfb771a7ac30fb2c35d3d
18,165
def get_all_storage_units(req): """Return only the list of Storage Units from the request""" storage_units = [] for dist_grp in req.distribute_groups: storage_units += dist_grp.storage_units return storage_units
82b4403f8a63b309f35a08879f9585932272c3ff
18,166
def compute_gradient (X, Y, Theta): """ Computes the cost gradient X = m*n Y = m*1 Theta = n*1 gradient = (1/m) * X_transpose * (X*Theta - Y) """ (m, n) = X.shape return (1.0/m) * (X.T) * (X*Theta - Y)
6348e2099a8ae6e32f6150bcaf1124edadc1c798
18,167
def get_doc_id(element_tree): """ returns the document ID of a SaltXML document. :param tree: an ElementTree that represents a complete SaltXML document :type tree: ``lxml.etree._ElementTree`` """ id_element = element_tree.xpath('labels[@name="id"]')[0] return id_element.attrib['valueString...
64e3e2abda9a0182866cc34b2f510a6c6dffe05b
18,168
def cleanDotNodes(graph): """Remove unnecessary data from node list""" nodes = graph.get_node_list() tmp = [node for node in nodes if node.name.startswith('"')] for node in nodes: node.name = node.name.replace('"','') # There are some strange issues with what nodes are returned # across ...
b5861c60b6054f5e9701e2acc94cc6a8a0621fb8
18,169
def jwt_get_user_secret_key(user): """ 重写JWT的secret的生成 :param user: :return: """ return str(user.secret)
97bc4313e405657805ef4a82fb020baef04863d0
18,170
def convertMinuteDecimalToDregrees(toconvert): """ Convert minute decimal to degrees """ converted=[] for toc in toconvert: converted.append(float(toc)/60) return converted
7c9f839ccc80f1d2a660ffc51fd05e91304e6683
18,171
def marquage_ligne_a (matrix): """a- Retourne une liste d'index des lignes avec aucun zero encadre""" ligne_marque_a = list() for y, y_elt in enumerate(matrix): if 'E' not in y_elt: ligne_marque_a.append(y) return ligne_marque_a
da91effb7562f559008c8e72f2a87c4f701d094c
18,173
def cli(ctx, value): """Get a specific canned key Output: A dictionnary containing canned key description """ return ctx.gi.cannedkeys.show_key(value)
b13c15e104c9c129b2efcc158c34b79f623fbb50
18,174
def get_subtrees(tree_mem): """ break the tree membership information into which subtrees of a given size are present preparatory step for saving computational steps Parameters ---------- tree_mem : dictionary Contains the group information with the leaves as keys and the...
fdca6e8fb8c82b896748a2599ab5a25eac377108
18,175
from datetime import datetime def create_filename(): """I wanted a properly unique and readable date and time as the file name.""" global time_stamp time_stamp = (datetime.now().strftime(r'%d' + ('-') + '%b' + ('-') + '%Y' + ('-') + '%H' + ('.') ...
9d2706bc745fc636bffb98a862ec07d76d8714d5
18,176
def _deep_merge_dicts(defaults: dict, updates: dict) -> dict: """Merges two dicts recursively, with updates taking precendence. Note that this modifies defaults in place. """ for k, u in updates.items(): if k not in defaults: defaults[k] = u else: v = defaults[k]...
90ea8c5e81998a51005338c0d67cb6a07a4291f2
18,178
def thread_helper(extractor): """! @brief Supports multiprocess color extraction operations. @param extractor The Extractor object for which to run extraction process. @return The Extractor object. """ extractor.run() return extractor
e032f0eb81897eba39c0773cf0f7805f66e8f052
18,179
import shutil def test_cmtk_install() -> int: """ Tries to determine if CMTK is installed and whether individual binaries are directly accessible or are accessible via the cmtk script call :return: -1: No cmtk install detected, 0: Direct call, 1: call via cmtk script """ if shutil.which("warp"...
1be574fc3b5f9f7bd41056591e5681057ae0ebd4
18,180
def compute_image_shape(width: int, height: int, fmt: str) -> tuple: """Compute numpy array shape for a given image. The output image shape is 2-dim for grayscale, and 3-dim for color images: * ``shape = (height, width)`` for FITS images with one grayscale channel * ``shape = (height, width, 3)`` for ...
f154b3e97ef8f700517985a520104ed26b041a4a
18,181
def unpack_payload(func): """Decorator to run admin shell functions. Unpacks payload metadata and passess them as kwargs to the actual callback """ def wrapper(resource, event, trigger, payload): # Use only with MetadataEventPayload if payload: func(resource, event, tri...
dbb8fe5c89ef14a30c92e7df3c76af310db56ae4
18,182
def summarize_file(file_path): """Summarizes the provided file by some basic measurements. Returns: A tuple containing how many (bytes, words, lines it contains, and what is the maximum character count in one line). """ if file_path is None: return bytes_ = 0 words = 0...
63b56a976f00cf86fc384abdc304b97690f32554
18,183
def compute_products(of_adjacent_digits, in_number): """Compute the products of all N-sized groups of adjacent digits in a predefined number.""" # Convert said number to a string. numberToString = str(in_number) # Register the list of digit group products. products = [] # Build said groups. ...
56ef92514f2c24a707a3fd174d8bede0d0454ef9
18,184
import os def get_rapidtide_root(): """ Returns the path to the base rapidtide directory, terminated with separator. Based on function by Yaroslav Halchenko used in Neurosynth Python package. """ thisdir, thisfile = os.path.split(os.path.join(os.path.realpath(__file__))) return os.path.join(th...
2abfb4078e0fc37a3ce1b3772da129190cf15501
18,185
def romanToInt(s): """Calculates value of Roman numeral string Args: s (string): String of Roman numeral characters being analyzed Returns: int: integer value of Roman numeral string """ sum = 0 i = 0 while i < len(s): if s[i] == 'M': sum += 1000 elif s[i] == 'D': sum +=...
71e6fdb08c2d705dbd88764e5ee1441ee6397d14
18,186
import os def expanded_abspath(p): """Return absolute path with user ``~`` expanded for path `p`.""" return os.path.abspath(os.path.expanduser(p))
a8aa36f73499c960d2cdda99dea5ea9d584afc3e
18,187
def get_cart_location(env, screen_width): """ Returns the position of the middle of the cart :param env: :param screen_width: :return: """ world_width = env.x_threshold * 2 scale = screen_width / world_width return int(env.state[0] * scale + screen_width / 2.0)
2b245964e1ce8b70a7964766a13a14e7759e48bf
18,188
import os def find_cache_base_dir(cache_base_dir=None): """ Finds the base cache directory for caching operations Arguments --------- cache_base_dir: string, optional Defaults to None. If None, then the cache directory is searched in the environement variable 'SCATTERING_CACHE'. I...
3a581e578f7e37144314b3582c18ea966ca58f06
18,190
def is_happy(n): """ Determines whether the number n is a "happy number". Int -> Bool Notes: Uses str() to split digits (slower, less efficient) Uses a set to contain the sequence generated from n """ n_sequence = set() while n != 1: s = str(n) n = sum(pow(int(x),2) ...
30068b5e6e6f0a4aa1fbcb91fc062b663be5a0c1
18,191
def _get_ec2_range(column_name, min_value, max_value, quotes='"'): """ Return a clause to select where a column is equal to one or more values. """ if min_value and max_value: return('and %s>=%s and %s<=%s' % (column_name, '%s%s%s' % (quotes, min_value, quotes), column_name, '%s%s%s' % (quotes, ...
271dc11dbfd0149f2a44f31b580a677cef67bdd8
18,192
import numpy as np def estimate_order_of_convergence(x, y): """Computes an estimate of the order of convergence in the least-square sense. This assumes that the :math:`(x, y)` pair follows a law of the form .. math:: y = m x^p and estimates the constant :math:`m` and power :math:`p`. ""...
e1e1d72006d133f58e6ae1b204217b394ac57e19
18,194
import math def cosine_lr_scheduler( lr: float, n_warmup: int = 0, warmup_init_lr: float = -1, min_lr: float = 0.0, t_mult: float = 1.0, lr_period_updates: float = -1, lr_shrink: float = 0.1, max_update: int = -1, ): """Cosine annealing learning rate scheduler with warmup and step ...
7438511ad48cf30fa706e5c4fa4d234919a78234
18,196
from typing import Tuple def decomress_coords(coords_data: bytes) -> Tuple[int, int]: """Получение координат клетки из байтовых данных.""" cell_x, cell_y = coords_data # вычитание единицы происходит вследствие работы `compress_coords` return cell_x-1, cell_y-1
cb91d0dbc13076f50d9359867469ea293c227383
18,197
def bytestr_to_int(s: bytes) -> int: """converts bytes to integer""" i = 0 for char in s: i <<= 8 i |= char return i
c9a7fcd0ff347c8ac99bf812cfffd9a61dcfd785
18,199
def sanitize(string): """ Turns '-' into '_' for accumulo table names """ return string.replace('-', '_')
2a86fff76b6d504be7981877612c4b1965d61e4e
18,200
def handle_node_attribute(node, tag_name, attribute_name): """Return the contents of a tag based on his given name inside of a given node.""" element = node.getElementsByTagName(tag_name) attr = element.item(0).getAttribute(attribute_name) return attr
8bbde7ecf335ce37b1fc55e3472aa07af6b7806a
18,201
def select_trees(gdf, subplot): """ Args: gdf: a geopandas dataframe subplot: a shapely box Returns: selected_trees: pandas dataframe of trees """ selected_trees = gdf[gdf.intersects(subplot)] return selected_trees
e0c4acea2622c839fb4afe124aae0a33af012e0f
18,203
def getpoint(acad,point,inputstring="Click on Drawing to get point"): """ acad= acad object Inputstring=prompt optional """ return acad.doc.Utility.GetPoint(point,inputstring)
921de5fa8511d43b2a9bc33122d2ee7bd1025a57
18,205
def get_pending_registration_ip_set( ip_from_dns_set, ip_from_target_group_set ): """ # Get a set of IPs that are pending for registration: # Pending registration IPs that meet all the following conditions: # 1. IPs that are currently in the DNS # 2. Those IPs must have not been registered y...
0bc0c23093bf9881421c5ef2b1307b099ed10384
18,206
def echo(message): """ :param message: the message to echo :returns: the given message :raises: """ return message
d6193277965c15ce7d3768c5c92bc3dee9aeaa1e
18,207
def get_identical_attributes(features, exclude=None): """Return a dictionary of all key-value pairs that are identical for all |SegmentChains| in `features` Parameters ---------- features : list list of |SegmentChains| exclude : set attributes to exclude from identity criteria...
efe7e913c7bb5d4f69f50241a999fb85fdd72800
18,208
def redis_prime_logic__style_2_domain(redis_client, dbDomain, redis_timeouts): """ returns the certificate :param redis_client: :param dbDomain: A :class:`model.objects.Domain` :param redis_timeouts: REDIS KEY PREFIXES: d2: domain """ dbCertificateSigned = None if dbDomain...
aa293ece422a35051f68ee452c35ee4b2b3d98bb
18,212
def compute_avg_over_multiple_runs(number_episodes, number_runs, y_all_reward, y_all_cum_reward, y_all_timesteps): """ Compute average of reward and timesteps over multiple runs (different dates) """ y_final_reward = [] y_final_cum_reward = [] y_final_timesteps = [] for array_index in range(...
a991f1f71ada7852a6ed94d7764d8112c6015cd1
18,213
import sys import traceback def get_raising_file_and_line(tb=None): """Get the file and line number where an exception happened. :param tb: the traceback (uses the most recent exception if not given) :return: a tuple of the filename and line number :rtype: (str, int) .. deprecated:: 7.0 ...
2bb531572a58045fc57688c989e0c7003644fc36
18,214
def db36(s): """Convert a Redis base36 ID to an integer, stripping any prefix present beforehand.""" if s[:3] in 't1_t2_t3_t4_t5_': s = s[3:] return int(s, 36)
0946bb125b17afec7803adf3654af7250047f9d6
18,215
from typing import Optional import torch def _conj(z, out: Optional[torch.Tensor] = None) -> torch.Tensor: """Element-wise complex conjugate of a Tensor with complex entries described through their real and imaginary parts. can work in place in case out is z""" if out is None or out.shape != z.shape: ...
015e9fc6d44f079ec157d659cc68684bef1b9e87
18,216
def split_touched(files): """Splits files that are touched vs files that are read.""" tracked = [] touched = [] for f in files: if f.size: tracked.append(f) else: touched.append(f) return tracked, touched
574772b7cec285ca9463bbebeab90502933f35a4
18,218
def fromstringtolist(strlist, map_function=int): """ read list written as string map_function function to convert from string to suited element type """ if strlist in ("None", None): return None list_elems = strlist[1:-1].split(",") toreturn = [map_function(elem) for elem in list_...
23ec31783c66fdb05420a3e233102111a400a53f
18,219
import numpy def spectral_function(eig_p, eig_m, eigv_p, eigv_m, rdm, i, j, window, num_omega, mu=0.0, eta=0.05): """ """ om_min, om_max = window def a_omega(omega, rdm_i, eigs, eigv, diag=False): spec = 0.0 norm = 0.0 for nu in range(len(eigs)): ...
0fd1f4b41b18c9947d2b9e01246207a2ad2a16a5
18,220
import os import pathlib def parse_config_path(fpath): """ Parse a path in config files. (1) If the path does not contain '{CORE}' or '{DATA}', it is a non-default path, so return unchanged. (2) If the path contains '{CORE}', it is a default that is going into the platform package directory struc...
7b4121fbccfee17a9e6dc0c511bd80bc4276128a
18,221
def str_to_c_string(string): """Converts a Python bytes to a C++ string literal. >>> str_to_c_string(b'abc\x8c') '"abc\\\\x8c"' """ return repr(string).replace("'", '"').removeprefix('b')
5316e61282d3ce3a807764588904529291453a37
18,222
def iuo(z1,z2): """ intersection over union :param z1: polygon :param z2: polygon returns z1.intersection(z2) / z1.union(z2) """ assert z1.isvalid assert z2.isvalid return z1.intersection(z2) / z1.union(z2)
c7f682833a82c16fe0959fbed16980188b45dade
18,223
def round_and_clip_image(image): """ Given a dictionary, ensure that the values in the 'pixels' list are all integers in the range [0, 255]. All values should be converted to integers using Python's `round` function. Any locations with values higher than 255 in the input should have value 255 ...
2c50a431be17fb203ffcc1136e91e2ffa97a7337
18,224
def bokeh_args(app_path, args): """translate from forest to bokeh serve command""" opts = ["bokeh", "serve", app_path] if args.dev: opts += ["--dev"] if args.show: opts += ["--show"] if args.port: opts += ["--port", str(args.port)] if args.allow_websocket_origin: ...
c957528c9b00e8e2ebf2b041ba27b8d4d6a84f2a
18,225
import requests def getURLChain(targetURL): """For the given URL, return the chain of URLs following any redirects """ ok = False chain = [] try: r = requests.head(targetURL, allow_redirects=True) ok = r.status_code == requests.codes.ok # pylint: disable=no-member if ok: ...
ecdfab9aff08035e8f830d67ba1380782ae82e6d
18,226
def setDefaultAlgoParams(): """This module creates a default template of the algorithm parameters. Returns ------- algoParam : dict a dictionary with keys and values (default values are in bold): * **PROBLEM: 'binary'**,'regression' * **REG: 'elasticnet'**, 'group' * **...
a5973bd28d7d96936937919112d3f36db1b04cb4
18,227
def dict_get_path(data, path, default=None): """ Returns the value inside nested structure of data located at period delimited path When traversing a list, as long as that list is containing objects of type dict, items in that list will have their "name" and "type" values tested against the cur...
00cc29d35f23ebff77c8d66ac95c863b70240f17
18,229
def generate_deletes_of_word(word): """does not include the original word""" deletes = {} for i in range(len(word)): deletes[word[:i] + word[i + 1:]] = [word] return deletes
6526d1481dc319cabec4e2db34d97c2cf42b0856
18,230
def raises_keyerr(k, m): """ Determine whether a mapping is missing a particular key. This helper is useful for explicitly routing execution through __getitem__ rather than using the __contains__ implementation. :param object k: the key to check for status as missing :param Mapping m: the key-...
5244f18065f89c6a4c22e11a3b08b7e9628bd616
18,231
def struct(T): """ Identifies a pure-data class that may be passed to the API """ return T
7bfc4826c013b1e3208ed930f1926b8debcca1dd
18,233
def bold(content): """Corresponds to ``**content**`` in the markup. :param content: HTML that will go inside the tags. >>> 'i said be ' + bold('careful') 'i said be <b>careful</b>' """ return '<b>' + content + '</b>'
6ee44da053fe21932b7db5003fc1c40526fa9ec9
18,234
from typing import Union import os import sys def _get_constant(key: str) -> Union[str, list]: """ Returns a string value for a constant used elsewhere in the code. All constants are defined here. Args: key (str): Key for the constant. Returns: (str, list): The constant. """ ...
40c004a814b55a59e8814bb104a21f0d1c16db6b
18,235
def FUNCTION_TO_REGRESS_TEMPLATE(x, a, b, c): """ A simple function to perform regression on. Args: x: A list of integers. a,b,c: Coefficients """ return (x[0] * a/2) + pow(x[1], b) + c
46f53a3d2a7e6729f51439a355991103dcbc03c2
18,236
def replace_substring(text: str, replace_mapping_dict: dict): """Return a string replaced with the passed mapping dict Args: text (str): text with unreplaced string replace_mapping_dict (dict): mapping dict to replace text Returns: str: text with all the substrings replaces """...
12ca0addd4417813682100abe28462b88f58933e
18,237
import multiprocessing def cpu_count(): """ Return the number of CPUs. """ if multiprocessing is None: return 1 return multiprocessing.cpu_count()
6b0d6647216e6b7cf8e0bb2c5ada6e557ef45e80
18,239
def basefilename(context): """ Returns filename minus the extension """ return context.template_name.split('.')[0]
f077ffd509bce97d989a9cf6f68e1a0f379c6bab
18,240
import getpass import sys def prompt(prompt: str, secure: bool=False): """ Reads a line of input from the user params: prompt: input prompt secure: read with getpass returns: the string entered """ result = "" try: if secure: result = getpass.get...
0c0dab08e428912a8903da56c1c4c6f2544fad7a
18,241
from numpy.random import normal def noise(arr,mean,sigma): """ returns normal distributed noise array of shape x with mean and sigma. """ result = normal(mean,sigma,arr.shape) return result
54bfbd64cf5fb5920987327fa536381905aabbde
18,242
def is_core(protein, mutation, elaspic_core_data): """ Given protein and mutation, check if that protein.mutation is in elaspic_core_data. Parameters ---------- protein : <str> The UniProt/SWISSPROT protein name. E.g. "Q9UPU5". mutation : <str> The position of t...
51698e861f7c35e3a1d2e428ed71d178d470e3e1
18,243
def get_dropdown_value(soup, var_id): """Get the current value from a dropdown list. Use when you see a dropdown in this HTML format: <select id="var-id" name="var-name"> <option value="false"> -- Option#1 -- </option> ... <option value="true" selected="selected"> -- Option#2 -- </o...
d26ca8233b0cabb174a202800b063db810b902a1
18,244
def rgb2hex(r, g, b, normalized=False): """ Converts RGB to HEX color """ # Check if RGB triplett is normalized to unity if normalized: r, g, b = r * 255.0, g * 255.0, b * 255.0 return '#%02X%02X%02X' % (r, g, b)
f05fd63b90ee946e011565194f93f4015a8e2cf1
18,245