content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def valid_pairs(pairs, chain): """ Determine if the chain contains any invalid pairs (e.g. ETH_XMR) """ for primary, secondary in zip(chain[:-1], chain[1:]): if not (primary, secondary) in pairs and \ not (secondary, primary) in pairs: return False return True
c9e36d0490893e1b1a6cd8c3fb0b14b382d69515
4,214
from typing import Any def fqname_for(obj: Any) -> str: """ Returns the fully qualified name of ``obj``. Parameters ---------- obj The class we are interested in. Returns ------- str The fully qualified name of ``obj``. """ if "<locals>" in obj.__qualname__: ...
6d4e5db255715c999d1bb40533f3dbe03b948b07
4,215
def symbol_size(values): """ Rescale given values to reasonable symbol sizes in the plot. """ max_size = 50.0 min_size = 5.0 # Rescale max. slope = (max_size - min_size)/(values.max() - values.min()) return slope*(values - values.max()) + max_size
a33f77ee8eeff8d0e63035c5c408a0788b661886
4,216
def import_by_name(name): """ 动态导入 """ tmp = name.split(".") module_name = ".".join(tmp[0:-1]) obj_name = tmp[-1] module = __import__(module_name, globals(), locals(), [obj_name]) return getattr(module, obj_name)
714ca90704d99a8eafc8db08a5f3df8e17bc6da4
4,217
def hexColorToInt(rgb): """Convert rgb color string to STK integer color code.""" r = int(rgb[0:2],16) g = int(rgb[2:4],16) b = int(rgb[4:6],16) color = format(b, '02X') + format(g, '02X') + format(r, '02X') return int(color,16)
59b8815d647b9ca3e90092bb6ee7a0ca19dd46c2
4,218
def insert_at_index(rootllist, newllist, index): """ Insert newllist in the llist following rootllist such that newllist is at the provided index in the resulting llist""" # At start if index == 0: newllist.child = rootllist return newllist # Walk through the list curllist = rootllist for i in ran...
767cde29fbc711373c37dd3674655fb1bdf3fedf
4,219
def priority(n=0): """ Sets the priority of the plugin. Higher values indicate a higher priority. This should be used as a decorator. Returns a decorator function. :param n: priority (higher values = higher priority) :type n: int :rtype: function """ def wrapper(cls): cls...
58ab19fd88e9e293676943857a0fa04bf16f0e93
4,221
def sanitize_option(option): """ Format the given string by stripping the trailing parentheses eg. Auckland City (123) -> Auckland City :param option: String to be formatted :return: Substring without the trailing parentheses """ return ' '.join(option.split(' ')[:-1]).strip()
ece0a78599e428ae8826b82d7d00ffc39495d27f
4,222
def node_values_for_tests(): """Creates a list of possible node values for parameters Returns: List[Any]: possible node values """ return [1, 3, 5, 7, "hello"]
b919efc5e59a5827b3b27e4f0a4cd070ceb9a5a4
4,223
import six def get_from_module(identifier, module_params, module_name, instantiate=False, kwargs=None): """The function is stolen from keras.utils.generic_utils. """ if isinstance(identifier, six.string_types): res = module_params.get(identifier) if not res: ...
406a1da5843feb8556bbd1802426b57e7a33b20d
4,225
def get_equations(points): """ Calculate affine equations of inputted points Input : 1 points : list of list ex : [[[x1, y1], [x2, y2]], [[xx1, yy1], [xx2, yy2]]] for 2 identified elements Contains coordinates of separation lines i.e. [[[start poin...
4eea43aee8b5f9c63793daae0b28e3c8b4ce0929
4,226
def Temple_Loc(player, num): """temple location function""" player.coins -= num player.score += num player.donation += num # player = temple_bonus_check(player) for acheivements return (player)
dced7b9f23f63c0c51787291ab12701bd7021152
4,227
import pickle def from_pickle(input_path): """Read from pickle file.""" with open(input_path, 'rb') as f: unpickler = pickle.Unpickler(f) return unpickler.load()
4e537fcde38e612e22004007122130c545246afb
4,229
def get_only_metrics(results): """Turn dictionary of results into a list of metrics""" metrics_names = ["test/f1", "test/precision", "test/recall", "test/loss"] metrics = [results[name] for name in metrics_names] return metrics
1b0e5bb8771fdc44dcd22ff9cdb174f77205eadd
4,230
def pkcs7_unpad(data): """ Remove the padding bytes that were added at point of encryption. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209 """ if isinstance(data, str): return data[0:-ord(data[-1])] else: ...
4b43b80220e195aa51c129b6cbe1f216a94360cd
4,233
def minus (s): """ заменить последний минус на равенство """ q = s.rsplit ('-', 1) return q[0] + '=' + q[1]
8d4ae538d866a930603b71ccdba0b18145af9988
4,234
def _chk_y_path(tile): """ Check to make sure tile is among left most possible tiles """ if tile[0] == 0: return True return False
cf733c778b647654652ae5c651c7586c8c3567b8
4,235
import re def alphanum_key(string): """Return a comparable tuple with extracted number segments. Adapted from: http://stackoverflow.com/a/2669120/176978 """ convert = lambda text: int(text) if text.isdigit() else text return [convert(segment) for segment in re.split('([0-9]+)', string)]
0e5e3f1d6aa43d393e1fb970f64e5910e7dc53fc
4,236
import copy def update_cfg(base_cfg, update_cfg): """used for mmcv.Config or other dict-like configs.""" res_cfg = copy.deepcopy(base_cfg) res_cfg.update(update_cfg) return res_cfg
c03dcfa7ac6d2f5c6745f69028f7cdb2ebe35eec
4,237
import subprocess def get_sub_bibliography(year, by_year, bibfile): """Get HTML bibliography for the given year""" entries = ','.join(['@' + x for x in by_year[year]]) input = '---\n' \ f'bibliography: {bibfile}\n' \ f'nocite: "{entries}"\n...\n' \ f'# {year}' out...
7c990c0a1e463f1db0fdc9a522f7c224f5969f7f
4,238
def GetDepthFromIndicesMapping(list_indices): """ GetDepthFromIndicesMapping ========================== Gives the depth of the nested list from the index mapping @param list_indices: a nested list representing the indexes of the nested lists by depth @return: depth """ retur...
c2318b3c6a398289c2cbf012af4c562d3d8bc2da
4,240
from typing import Dict def generate_person(results: Dict): """ Create a dictionary from sql that queried a person :param results: :return: """ person = None if len(results) > 0: person = { "id": results[0], "name": results[1].decode("utf-8"), ...
21c2f2c8fa43c43eabf06785203556ccae708d45
4,241
def paliindrome_sentence(sentence: str) -> bool: """ `int` """ string = '' for char in sentence: if char.isalnum(): string += char return string[::-1].casefold() == string.casefold()
4559f9f823f748f137bbe1eb96070dba8e7d867d
4,242
def get_default_pool_set(): """Return the names of supported pooling operators Returns: a tuple of pooling operator names """ output = ['sum', 'correlation1', 'correlation2', 'maximum'] return output
32d28fdb80ecdacab8494251edd87b566128fd79
4,243
import os def excel_file2(): """Test data for custom data column required fields.""" return os.path.join('test', 'data', 'NADataErrors_2018-05-19_v1.0.xlsx')
84a6ae00e88b8035f92b9c4c8702a63a0631ec0f
4,244
import numpy as np def rate_multipressure(qD, delta_p, B, mu, perm, h): """Calculate Rate as Sum of Constant Flowing Pressures""" return ((.007082 * perm * h) / (B * mu)) * (np.sum(qD * delta_p))
a8621613abb63bb6f15c71ab3ba02d65ab160e6b
4,246
def is_leap_year(year): """ Is the current year a leap year? Args: y (int): The year you wish to check. Returns: bool: Whether the year is a leap year (True) or not (False). """ if year % 4 == 0 and (year % 100 > 0 or year % 400 == 0): return True return False
16e4c83adc9d42dae2396186f980755b33af9188
4,248
def pandoc_command(event, verbose=True): #@+<< pandoc command docstring >> #@+node:ekr.20191006153547.1: *4* << pandoc command docstring >> """ The pandoc command writes all @pandoc nodes in the selected tree to the files given in each @pandoc node. If no @pandoc nodes are found, the command loo...
972cd1e683b70c175e6b1710b9efb875932d8359
4,249
def random_majority_link_clf(): """ for link classification we do not select labels from a fixed distribution but instead we set labels to the number of possible segments in a sample. I.e. we only predict a random link out of all the possible link paths in a sample. """ def clf(labels, k:int...
f53f2fee85914e25d5e407808dcfbee623b0782a
4,250
def weight_point_in_circle( point: tuple, center: tuple, radius: int, corner_threshold: float = 1.5 ): """ Function to decide whether a certain grid coordinate should be a full, half or empty tile. Arguments: point (tuple): x, y of the point to be tested ...
db0da5e101184975385fb07e7b22c5e8a6d4fd47
4,251
import os def disk_usage(path): """returns disk usage for a path""" total = os.path.getsize(path) if os.path.isdir(path): for filename in os.listdir(path): child_path = os.path.join(path, filename) total += disk_usage(child_path) print(f"{total:<10} {path}") return ...
0c4901f94d562d7def81afcef4ffa27fe48c106c
4,252
def get_arrival_times(inter_times): """Convert interevent times to arrival times.""" return inter_times.cumsum()
7197fc6315d3eaca118ca419f23aed7c0d7cd064
4,254
def contains_vendored_imports(python_path): """ Returns True if ``python_path`` seems to contain vendored imports from botocore. """ # We're using a very rough heuristic here: if the source code contains # strings that look like a vendored import, we'll flag. # # Because Python is dynamic, t...
90ed6939d7f43cac29eb66c3e27e911b9cc62532
4,255
def filter_uniq(item): """Web app, feed template, creates unique item id""" detail = item['item'] args = (item['code'], item['path'], str(detail['from']), str(detail['to'])) return ':'.join(args)
914fa4e3fcdf6bc7e6a30b46c8f33eecd08adcf1
4,256
def atoi(s, base=None): # real signature unknown; restored from __doc__ """ atoi(s [,base]) -> int Return the integer represented by the string s in the given base, which defaults to 10. The string s must consist of one or more digits, possibly preceded by a sign. If base is 0, it is chos...
420c9a68c1fe829a665eaba830df757114a81b47
4,257
def precip_units(units): """ Return a standardized name for precip units. """ kgm2s = ['kg/m2/s', '(kg/m^2)/s', 'kg/m^2/s', 'kg m^-2 s^-1', 'kg/(m^2 s)', 'kg m-2 s-1'] mmday = ['mm/day', 'mm day^-1'] if units.lower() in kgm2s: return 'kg m^-2 s^-1' elif units.lower() in...
e5f94c3dd41b68d2e7b6b7aa1905fd5508a12fab
4,258
def calcul_acc(labels, preds): """ a private function for calculating accuracy Args: labels (Object): actual labels preds (Object): predict labels Returns: None """ return sum(1 for x, y in zip(labels, preds) if x == y) / len(lab...
3dc22c8707c181dda50e2a37f2cd822b2a31590d
4,259
def get_preprocessor(examples, tokenize_fn, pad_ids): """ Input: examples: [List[str]] input texts tokenize_fn: [function] encodes text into IDs Output: tf input features """ def generator(): for example in examples: tokens = tokenize_fn(example) yield pad...
0b2fb2217e04183fee027faedd163a8f8a048e9a
4,260
def read_user(msg): """Read user input. :param msg: A message to prompt :type msg: ``str`` :return: ``True`` if user gives 'y' otherwhise False. :rtype: ``bool`` """ user_input = input("{msg} y/n?: ".format(msg=msg)) return user_input == 'y'
662e95002130a6511e6e9a5d6ea85805f6b8f0f5
4,261
import requests def get_tenants(zuul_url): """ Fetch list of tenant names """ is_witelabel = requests.get( "%s/info" % zuul_url).json().get('tenant', None) is not None if is_witelabel: raise RuntimeError("Need multitenant api") return [ tenant["name"] for tenant in requ...
97944d2de2a8dfc2dd50dbea46a135a184e7aa37
4,262
def get_accuracy(pred, target): """gets accuracy either by single prediction against target or comparing their codes """ if len(pred.size()) > 1: pred = pred.max(1)[1] #pred, target = pred.flatten(), target.flatten() accuracy = round(float((pred == target).sum())/float(pred.numel()) * 100, 3...
f30e57602e4a06b0a0e3cd131bf992cf8f9b514e
4,263
import numpy def ifourier_transform(F,dt,n): """ See Also ------- fourier_transform """ irfft = numpy.fft.irfft shift = numpy.fft.fftshift return (1.0/dt)*shift(irfft(F,n=n))
d068cdbbe95f58d4210d2e799dfaee878fb9bf98
4,264
import argparse def parse_arguments(): """ Function to parse command line arguements from the user Returns ------- opts : dict command line arguements from the user """ info = 'Divides pdb info files for parallelization' parser = argparse.ArgumentParser(description=info) ...
8bdc260c1dcb779c7b30927651e26c05a9c0d5f5
4,265
def stringify_parsed_email(parsed): """ Convert a parsed email tuple into a single email string """ if len(parsed) == 2: return f"{parsed[0]} <{parsed[1]}>" return parsed[0]
6552987fe6a06fdbb6bd49e5d17d5aadaae3c832
4,267
def base_to_str( base ): """Converts 0,1,2,3 to A,C,G,T""" if 0 == base: return 'A' if 1 == base: return 'C' if 2 == base: return 'G' if 3 == base: return 'T' raise RuntimeError( 'Bad base: %d' % base )
f1c98b7c24fae91c1f809abe47929d724c886168
4,268
import argparse def parse_args(args): """ function parse_args takes arguments from CLI and return them parsed for later use. :param list args : pass arguments from sys cmd line or directly :return dict: parsed arguments """ parser = argparse.ArgumentParser() required = parser.add_argument...
e3783dc173696b5758d8fc90bc810841e043be0a
4,269
def dictmask(data, mask, missing_keep=False): """dictmask masks dictionary data based on mask""" if not isinstance(data, dict): raise ValueError("First argument with data should be dictionary") if not isinstance(mask, dict): raise ValueError("Second argument with mask should be dictionary")...
d18f6effb4367628ba85095024189d0f6694dd52
4,270
def _format_warning(message, category, filename, lineno, line=None): """ Replacement for warnings.formatwarning that disables the echoing of the 'line' parameter. """ return "{}:{}: {}: {}\n".format(filename, lineno, category.__name__, message)
8267150c5890759d2f2190ccf4b7436ea8f55204
4,272
def wordify_open(p, word_chars): """Prepend the word start markers.""" return r"(?<![{0}]){1}".format(word_chars, p)
8b267aaca897d6435a84f22064f644727ca6e83c
4,274
def user_info(context, **kwargs): """ Отображает информацию о текущем авторизованом пользователе, либо ссылки на авторизацию и регистрацию Пример использования:: {% user_info %} :param context: контекст :param kwargs: html атрибуты оборачивающего тега :return: """ request = co...
20321056fd5fdf8f51e79fb66d335272e85ada0d
4,275
def is_array_of(obj, classinfo): """ Check if obj is a list of classinfo or a tuple of classinfo or a set of classinfo :param obj: an object :param classinfo: type of class (or subclass). See isinstance() build in function for more info :return: flag: True or False """ flag = False if is...
5fecce974b5424cff7d5e6a4a9f9bd1482e10e85
4,276
from textwrap import dedent def make_check_stderr_message(stderr, line, reason): """ Create an exception message to use inside check_stderr(). """ return dedent("""\ {reason}: Caused by line: {line!r} Complete stderr: {stderr} """).format(stderr=stderr, line=line, reason=reason)
a6510e8036ab27e6386e6bc8e6c33727849282c0
4,277
def stripped_spaces_around(converter): """Make converter that strippes leading and trailing spaces. ``converter`` is called to further convert non-``None`` values. """ def stripped_text_converter(value): if value is None: return None return converter(value.strip()) ret...
b92f38d3eb8d191f615488bbd11503bae56ef6de
4,278
def list_in_list(a, l): """Checks if a list is in a list and returns its index if it is (otherwise returns -1). Parameters ---------- a : list() List to search for. l : list() List to search through. """ return next((i for i, elem in enumerate(l) if elem == a), -1)
494d9a880bcd2084a0f50e292102dc8845cbbb16
4,280
def sent_to_idx(sent, word2idx, sequence_len): """ convert sentence to index array """ unknown_id = word2idx.get("UNKNOWN", 0) sent2idx = [word2idx.get(word, unknown_id) for word in sent.split("_")[:sequence_len]] return sent2idx
ffaa65741d8c24e02d5dfbec4ce84c03058ebeb8
4,281
def list_data(args, data): """List all servers and files associated with this project.""" if len(data["remotes"]) > 0: print("Servers:") for server in data["remotes"]: if server["name"] == server["location"]: print(server["user"] + "@" + server["location"]) ...
6a005b6e605d81985fca85ca54fd9b29b28128f5
4,282
def anchor_inside_flags(flat_anchors, valid_flags, img_shape, allowed_border=0, device='cuda'): """Anchor inside flags. :param flat_anchors: flat anchors :param valid_flags: valid flags :param img_shape: image meta info :param allowed_border: if allow border :return: ins...
500fe39f51cbf52bd3417b14e7ab7dcb4ec2f9cc
4,283
import sys def parseExonBounds(start, end, n, sizes, offsets): """ Parse the last 2 columns of a BED12 file and return a list of tuples with (exon start, exon end) entries. If the line is malformed, issue a warning and return (start, end) """ offsets = offsets.strip(",").split(",") sizes ...
8252fea73d80dc0a78cd28fb05e63eb687fb1f27
4,284
def _GenerateGstorageLink(c, p, b): """Generate Google storage link given channel, platform, and build.""" return 'gs://chromeos-releases/%s-channel/%s/%s/' % (c, p, b)
e5e4a0eb9e27b0f2d74b28289c8f02dc0454f438
4,285
def _has_desired_permit(permits, acategory, astatus): """ return True if permits has one whose category_code and status_code match with the given ones """ if permits is None: return False for permit in permits: if permit.category_code == acategory and\ permit.status_co...
4cac23303e2b80e855e800a7d55b7826fabd9992
4,287
def computeHashCheck(ringInputString, ringSize): """Calculate the knot hash check. Args: ringInputString (str): The list of ints to be hashed as a comma-separated list. ringSize (int): The size of the ring to be \"knotted\". Returns: int: Value of the hash check. """ ringI...
75dce4aacdd4ae03fa34532471a21a43a81fbd13
4,289
def compute_dl_target(location): """ When the location is empty, set the location path to /usr/sys/inst.images return: return code : 0 - OK 1 - if error dl_target value or msg in case of error """ if not location or not location.strip(): loc = "...
419b9fcad59ca12b54ad981a9f3b265620a22ab1
4,292
import re def find_classes(text): """ find line that contains a top-level open brace then look for class { in that line """ nest_level = 0 brace_re = re.compile("[\{\}]") classname_re = "[\w\<\>\:]+" class_re = re.compile( "(?:class|struct)\s*(\w+)\s*(?:\:\s*public\s*" ...
126bc091a809e152c3d447ffdd103c764bc6c9ac
4,293
def get_input(request) -> str: """Get the input song from the request form.""" return request.form.get('input')
de237dc0ad3ce2fa6312dc6ba0ea9fe1c2bdbeb3
4,294
from typing import Hashable import math def _unit_circle_positions(item_counts: dict[Hashable, tuple[int, int]], radius=0.45, center_x=0.5, center_y=0.5) -> dict[Hashable, tuple[float, float]]: """ computes equally spaced points on a circle based on the radius and center positions ...
66f60f5b90f7825f2abfdd2484375c9558786250
4,295
def replace_na(str_value: str, ch: str = "0") -> str: """replaces \"0\" with na, specifically designed for category list, may not work for others need Args: str_value (str): category list ch (str, optional): Replacemet char. Defaults to "0". Returns: str: clean cotegory name ""...
d8e6dfe6806c7a008163ba92c62e7b2b18633538
4,296
def d1_to_q1(A, b, mapper, cnt, M): """ Constraints for d1 to q1 """ for key in mapper['ck'].keys(): for i in range(M): for j in range(i, M): # hermetian constraints if i != j: A[cnt, mapper['ck'][key](i, j)] += 0.5 ...
1ee9ec17f4464ef280aa22780d6034309941954e
4,297
import os def relative_of(base_path: str, relative_path: str) -> str: """Given a base file and path relative to it, get full path of it""" return os.path.normpath(os.path.join(os.path.dirname(base_path), relative_path))
b35e580ff2afc4cf196f6e53eedd5f4383579c6e
4,299
def get_gs_distortion(dict_energies: dict): """Calculates energy difference between Unperturbed structure and most favourable distortion. Returns energy drop of the ground-state relative to Unperturbed (in eV) and the BDM distortion that lead to ground-state. Args: dict_energies (dict): ...
2f23103ccac8e801cb6c2c4aff1fb4fc08341e78
4,300
import sys def get_pcap_bytes(pcap_file): """Get the raw bytes of a pcap file or stdin.""" if pcap_file == "-": pcap_bytes = sys.stdin.buffer.read() else: with open(pcap_file, "rb") as f: pcap_bytes = f.read() return pcap_bytes
51abbefeb918016edef6f8f40c7c40cb973e2fc0
4,305
import subprocess def run(s, output_cmd=True, stdout=False): """Runs a subprocess.""" if output_cmd: print(f"Running: {s}") p_out = subprocess.run( s, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=False ) if stdout: return p_out.stdout.decode("utf-8")...
efcfe30a536789a69662642d2b2da1afc04ebe57
4,306
from types import ModuleType import sys def _create_module(module_name): """ex. mod = _create_module('tenjin.util')""" mod = ModuleType(module_name.split('.')[-1]) sys.modules[module_name] = mod return mod
bfc1092bce61f7716a42ceeccc0604ced3696cdd
4,307
def sortKSUID(ksuidList): """ sorts a list of ksuids by their date (recent in the front) """ return sorted(ksuidList, key=lambda x: x.getTimestamp(), reverse=False)
0476bc0ef19f8730488041ac33598ba7471f96e7
4,308
from typing import Counter def get_vocabulary(list_): """ Computes the vocabulary for the provided list of sentences :param list_: a list of sentences (strings) :return: a dictionary with key, val = word, count and a sorted list, by count, of all the words """ all_the_words = [] for tex...
d6c357a5768c2c784c7dfe97743d34795b2695c0
4,310
import math def split(value, precision=1): """ Split `value` into value and "exponent-of-10", where "exponent-of-10" is a multiple of 3. This corresponds to SI prefixes. Returns tuple, where the second value is the "exponent-of-10" and the first value is `value` divided by the "exponent-of-10". ...
776ded073807773b755dcd7ab20c47d1f33ca1e1
4,312
def transitive_closure(graph): """ Compute the transitive closure of the graph :param graph: a graph (list of directed pairs) :return: the transitive closure of the graph """ closure = set(graph) while True: new_relations = set((x, w) for x, y in closure for q, w in closure if q == y...
3bb6567033cf920ccced7565e75f8f789c55c37d
4,314
def get_logo_color(): """Return color of logo used in application main menu. RGB format (0-255, 0-255, 0-255). Orange applied. """ return (255, 128, 0)
a6eee63d816a44af31893830ac641d6c0b1b9ba1
4,315
from numpy import sqrt def vel_gradient(**kwargs): """ Calculates velocity gradient across surface object in supersonic flow (from stagnation point) based upon either of two input variable sets. First method: vel_gradient(R_n = Object radius (or equivalent radius, for shapes that a...
8ee3ef490c113551e9200743e52378a8206a3666
4,316
def compute_agg_tiv(tiv_df, agg_key, bi_tiv_col, loc_num): """ compute the agg tiv depending on the agg_key""" agg_tiv_df = (tiv_df.drop_duplicates(agg_key + [loc_num], keep='first')[list(set(agg_key + ['tiv', 'tiv_sum', bi_tiv_col]))] .groupby(agg_key, observed=True).sum().reset_index()) if 'is_...
246ea2d61230f3e3bfe365fdf8fdbedbda98f25b
4,317
def replacelast(string, old, new, count = 1): """Replace the last occurances of a string""" return new.join(string.rsplit(old,count))
6af2cd56cc43e92b0d398e8aad4e25f0c6c34ddd
4,320
def load_secret(name, default=None): """Check for and load a secret value mounted by Docker in /run/secrets.""" try: with open(f"/run/secrets/{name}") as f: return f.read().strip() except Exception: return default
1aac980ad6bc039964ef9290827eb5c6d1b1455f
4,321
def len_adecuada(palabra, desde, hasta): """ (str, int, int) -> str Valida si la longitud de la palabra está en el rango deseado >>> len_adecuada('hola', 0, 100) 'La longitud de hola, está entre 0 y 100' >>> len_adecuada('hola', 1, 2) 'La longitud de hola, no está entre 1 y 2' :para...
df217a0159cd04c76f5eb12ca42e651ee62fcd99
4,322
import re def convert_as_number(symbol: str) -> float: """ handle cases: ' ' or '' -> 0 '10.95%' -> 10.95 '$404,691,250' -> 404691250 '$8105.52' -> 8105.52 :param symbol: string :return: float """ result = symbol.strip() if...
cea1d6e894fa380ecf6968d5cb0ef1ce21b73fac
4,323
def smiles_dict(): """Store SMILES for compounds used in test cases here.""" smiles = { "ATP": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)OP(=O)(O)OP(=O)(O)O)[C" + "@@H](O)[C@H]1O", "ADP": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)OP(=O)(O)O)[C@@H](O)[C" + "@H]1O", "meh": "CCC(=O)C(=O)O...
080373bdfb250f57e20e0e2b89702ac07c430f69
4,324
import operator def most_recent_assembly(assembly_list): """Based on assembly summaries find the one submitted the most recently""" if assembly_list: return sorted(assembly_list, key=operator.itemgetter('submissiondate'))[-1]
1d7ecf3a1fa862e421295dda0ba3d89863f33b0f
4,327
def _get_individual_id(individual) -> str: """ Returns a unique identifier as string for the given individual. :param individual: The individual to get the ID for. :return: A string representing the ID. """ if hasattr(individual, "identifier") and (isinstance(individual.identifier, list) and ...
e606d5eef7bfbcd0d76113c20f450be3c1e6b2ab
4,329
def ConvertToMeaningfulConstant(pset): """ Gets the flux constant, and quotes it above some energy minimum Emin """ # Units: IF TOBS were in yr, it would be smaller, and raw const greater. # also converts per Mpcs into per Gpc3 units=1e9*365.25 const = (10**pset[7])*units # to cubic Gpc an...
e393f66e72c3a43e91e9975f270ac7dcf577ad3e
4,330
def hw_uint(value): """return HW of 16-bit unsigned integer in two's complement""" bitcount = bin(value).count("1") return bitcount
9a9c6017d3d6da34c4e9132a0c89b267aa263ace
4,331
def evenly_divides(x, y): """Returns if [x] evenly divides [y].""" return int(y / x) == y / x
dbf8236454e88805e71aabf58d9b7ebd2b2a6393
4,333
import collections def order_items(records): """Orders records by ASC SHA256""" return collections.OrderedDict(sorted(records.items(), key=lambda t: t[0]))
a9117282974fcea8d0d99821ea6293df82889b30
4,334
def convert_group_by(response, field): """ Convert to key, doc_count dictionary """ if not response.hits.hits: return [] r = response.hits.hits[0]._source.to_dict() stats = r.get(field) result = [{"key": key, "doc_count": count} for key, count in stats.items()] result_sorted = so...
888321f300d88bd6f150a4bfda9420e920bab510
4,335
def compOverValueTwoSets(setA={1, 2, 3, 4}, setB={3, 4, 5, 6}): """ task 0.5.9 comprehension whose value is the intersection of setA and setB without using the '&' operator """ return {x for x in (setA | setB) if x in setA and x in setB}
2b222d6c171e0170ace64995dd64c352f03aa99b
4,336
def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str """ if len(strs) > 0: common = strs[0] for str in strs[1:]: while not str.startswith(common): common = common[:-1] return common else: return ''
a860d46df8dbaeaab90bb3bc69abb68484216b5b
4,338
def insert(shape, axis=-1): """Shape -> shape with one axis inserted""" return shape[:axis] + (1,) + shape[axis:]
8c786df81b76cfa5dae78b51d16b2ee302263c53
4,339
def is_numpy_convertable(v): """ Return whether a value is meaningfully convertable to a numpy array via 'numpy.array' """ return hasattr(v, "__array__") or hasattr(v, "__array_interface__")
163da2cf50e2172e1fc39ae8afd7c4417b02a852
4,341
from datetime import datetime def get_fake_datetime(now: datetime): """Generate monkey patch class for `datetime.datetime`, whose now() and utcnow() always returns given value.""" class FakeDatetime: """Fake datetime.datetime class.""" @classmethod def now(cls): """Return...
f268640c6459f4eb88fd9fbe72acf8c9d806d3bc
4,342
import os def get_processing_info(data_path, actual_names, labels): """ Iterates over the downloaded data and checks which one is in our database Returns: files_to_process: List of file paths to videos labs_to_process: list of same length with corresponding labels """ files_to_proc...
0e2ed514159bd230d9315d1b668ce8a59d36b545
4,343
def compress_pub_key(pub_key: bytes) -> bytes: """Convert uncompressed to compressed public key.""" if pub_key[-1] & 1: return b"\x03" + pub_key[1:33] return b"\x02" + pub_key[1:33]
05824112c6e28c36171c956910810fc1d133c865
4,346
def _(text): """Normalize white space.""" return ' '.join(text.strip().split())
f99f02a2fe84d3b214164e881d7891d4bfa0571d
4,347
import os def get_tmp_directory_path(): """Get the path to the tmp dir. Creates the tmp dir if it doesn't already exists in this file's dir. :return: str -- abs path to the tmp dir """ tmp_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tmp...
b480578e6ae7a1840e8bf4acce36a63253a33d80
4,348