content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import re def validate_date(date): """Validate date format. :param date: The date that will be entered into the database. :type date: str :return: True if the date format is well formed with valid characters, false if not. :rtype: bool """ result = None date_format = "([0-9]{4}-[0-9]{...
c9bf560c6e25246e8713f93b4a85ac87a7693337
591,580
def green_channel(input_image): """ Split input_image channels and return only the green channel :param input_image: image :type input_image: numpy.ndarray :return: image with only the green channel :rtype: numpy.ndarray """ return input_image[:, :, 1]
47fd11ae7a68285fd59e539556b0efb856566c3f
458,972
import requests from bs4 import BeautifulSoup def get_next_page_doc_url_set(author_name,page_num,unit_name): """ this function support the function: def get_doc_url_set(author_name,unit_name): get urls of specified page. Args: author_name: author's name page_num: specified pag...
f70770a51be83277b2ce3d9233c089a6a73396a6
554,020
import math def pretty_duration(d): """Formats a time duration Formats a time duration in a human readable format Arguments: d {float} -- Duration in seconds Returns: str -- formated duration """ if d < 1: return "<1s" s = '' days = math.fl...
6aa50f86aa2a5df8487bc99f3df8a67f5d71177f
564,973
def permute_axes(array, input_axes, output_axes): """ Transpose the array with input_axes axis order to match output_axes axis order. Assumes that array has all the dimensions in output_axes, just in different orders, and drops/adds dims to the input axis order. Arguments: array (ndarray): ...
6e9ddd84862dd79204bdc36a2ebf2fa25545911e
543,752
def convert_to_hex(rgba_color): """ Convert an RGBa reference to HEX :param rgba_color: RGBa color :return: HEX color """ red = int(rgba_color.red * 255) green = int(rgba_color.green * 255) blue = int(rgba_color.blue * 255) return '0x{r:02x}{g:02x}{b:02x}'.format(r=red, g=green, b=bl...
05f5ff9bb11c3d63a5d789c4e3ceae8ee4ef3659
253,267
def px2mm(pixels, resolution=1600, precision=2): """Convert scanned pixels to millimeters. Arguments: pixels: measurement in pixels. resolution: image resolution in pixels/inch. precision: number of significant digits for rounding. Returns: The converted measurement. ""...
7a35d6d9bc049273b092a5bd4ea5e4d608b7cace
597,813
from typing import Iterable from typing import Tuple from typing import Counter def filter_mutation_set_by_position(mutation_sets: Iterable[Tuple[Tuple[int, int], ...]], limit: int = 10): """Return a filtered mutation set, where each position is used a maximum of `limit` times.""" filtered_mutation_sets = [] po...
7120a40e0e21ea3d03fcd4a9618c3791724eaec2
222,815
def quantum_state_preparation_qiskit(circuit, parameters, n = 2): """ Parameters ---------- circuit: qiskit circuit parameters: n*2 array each row contains rx and ry parameters Returns ------- qiskit circuit """ q = circuit.qregs for i in r...
5443d7a4c29c6ab003f71e345d5a07925f538c21
19,973
def is_keyword(text): """Check whether text is likely to be a keyword.""" return len(text.strip()) < 4 and text.isalpha()
a971dc2040e6847a9dbe7230a3effb7b3e6b6ed1
134,281
import re def get_values(line): """ Returns the portion of an INSERT statement containing values """ capture = re.match(r'^INSERT\s+INTO\s+`?(.*?)`?\s*(\(.*?\))?\s*VALUES\s*(\(.*?$)', line) if capture is None: return None return capture.groups()[2]
2cb8b902d58bc7409415e875d1f32d690ebc8549
283,203
from datetime import datetime import pytz def ns_to_datetime(ns): """ Converts nanoseconds to a datetime object (UTC) Parameters ---------- ns : int nanoseconds since epoch Returns ------- nanoseconds since epoch as a datetime object : datetime """ dt = datetime.utcf...
8e70e06b01add515147e267c2490b552567afb09
646,667
def excel_column_to_column_index(excel_column: str) -> int: """Takes an excel column like 'A' and converts to column index""" return ord(excel_column.upper()) - 64
76c67c576bdf5236204022980305887ac3aa6f60
495,802
def format_helptext(value): """Handle formatting for HELPTEXT field. Apply formatting only for token with value otherwise supply with newline""" if not value: return "\n" return "\t {}\n".format(value)
426fa6ee036c5a8376645d6455c1681b1200e174
60,812
import re def format_text_time_zone(text): """Returns text after removing blank spaces inside time zone text. Parameters ---------- text : str the text to be formatted. Returns ------- str a string formatted to match time zone (ex. UTC+2). """ text = re.sub(r'\s*\...
9902e9b27142ca0d5984165fdddf70164aa57048
112,308
import math def distance(p1, p2): """ Calculates the distance between two points. :param p1, p2: points :return: distance between points """ p1x, p1y = p1 p2x, p2y = p2 return math.sqrt((p1x - p2x) ** 2 + (p2y - p2y) ** 2)
13cc6d2c2007441478fec8f4b17f08113cbdc2e6
609,113
def linearization(X, Jfun, P): """Transform a covariance matrix via linearization Arguments: X: the point to linearize about, (n,) numpy array Jfun: function which takes the state and returns the (n x n) Jacobian of the function, f, which we want to transform the covariance by. It ...
c24c4d0815842cc70ac31f0ba9f505bc0d743036
23,097
def sourceJoin(nick, ident, host): """sourceJoin(nick, ident, host) -> str Join a source previously split by sourceSplit and join it back together inserting the ! and @ appropiately. """ return "%s!%s@%s" % (nick, ident, host)
9aaed0b756c9425425018f63abeb3d119e270415
200,614
def getUniqueByID(seq): """Very fast function to remove duplicates from a list while preserving order Based on sort f8() by Dave Kirby benchmarked at https://www.peterbe.com/plog/uniqifiers-benchmark Requires Python>=2.7 (requires set()) """ # Order preserving seen = set() return [x fo...
fec0964de14a6cbf70b50816a68335c27243d56e
323,749
import base64 def auth_for_user(user): """ Formats the base64 string based on a user """ return base64.standard_b64encode( "{}:{}".format(user.username, user.password).encode() )
2c0b92747f57e8a527407fd8adf7570338a06a7a
394,435
def hasQueryMatch(qList, tweetJSON): """Returns true if a tweet containing any keyword in QUERY_KEYWORDS is found""" return any(keyword in tweetJSON['text'] for keyword in qList)
b0ff979b8c54f09450749ef134c7b9deabe7a231
628,722
def _agg_data(data_strs): """ Auxiliary function that aggregates data of a job to a single byte string """ ranges = [] pos = 0 for datum in data_strs: datum_len = len(datum) ranges.append((pos, pos+datum_len-1)) pos += datum_len return b"".join(data_strs), ranges
b752a9a466ed6eaf5a9c37ff05f532641f296237
426,664
def GetExcelStyleColumnLabel(ColNum): """Return Excel style column label for a colum number. Arguments: ColNum (int): Column number Returns: str : Excel style column label. """ Letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ColLabelList = [] while ColNum: ColNum, ...
bc2fd2214e812ba592758bbd779714ba7cadb530
483,669
from typing import Callable def override_input(inputs: list[str]) -> Callable[[str], str]: """ Returns a new input() function that accepts a string and repeatedly pops strings from the front the provided list and returns them as calls to input(). """ def _input(prompt: str) -> str: """ ...
c7db23b19361dd72cc6519a6f52537ed719341f5
409,892
def f(N): """ 1/(N^2 -1) """ # tmp = np.dtype(np.float32) # 单精度 tmp = 1/(pow(N,2) - 1) return tmp
9cee33913b2044eca704eeee5b4edacdeb25102c
526,665
from typing import Optional def plot_number_formatter(val: float, _: Optional[float], precision: int = 3) -> str: """ Format numbers in the plot. Parameters ---------- val : float The value. _ : [None | float] The position (needed as input from FuncFormatter). precision : ...
ffc66a14f6003c038dedc4b44d0e4b94e956f265
555,041
def get_force_datakeeper(self, symbol_list, is_multi=False): """ Generate DataKeepers to store by default results from force module Parameters ---------- self: VarLoad A VarLoad object symbol_list : list List of the existing datakeeper (to avoid duplicate) is_multi : bool ...
1321948d15f07914de30dab648d643121d94d491
622,795
def calc_mean_std(feat, eps=1e-5): """ Calculate channel-wise mean and standard deviation for the input features and preserve the dimensions Args: feat: the latent feature of shape [B, C, H, W] eps: a small value to prevent calculation error of variance Returns: Channel-wise mean an...
0c564490787a210a0b9947781905dcf16b9d655d
158,811
def reset_dupe_index(df, ind_name): """ Reset index and rename duplicate index column Parameters: df (pandas DataFrame): DataFrame to reset index ind_name (str): Name of column to reset Returns: df (pandas DataFrame): DataFrame with reset duplicate index """ df.rename({ind_name: ind_name+'_back'}, inplace...
213de79ad7108f759d2bcdf1bfb9eb9d8f193c19
96,256
import re def question2(records): """Combien de noms de régions mentionnées dans ce fichier comportent un nombre de lettres supérieur ou égal à 10 (espaces et tirets non compris) ? """ # On déduplique les noms noms = set(r.region for r in records) # On les nettoie. # Attention, ceci est un...
11d4656c89d898d675261a29231b6ac1df7f9555
306,627
def product(val1, val2, val3): """Returns the product of the three input values """ product = val1 * val2 * val3 return product
7c9ee354eb0c132f7c875031058aa4f8f957ae9a
255,945
import bz2 def make_bz2(tar_file, destination): """ Takes a tar_file and destination. Compressess the tar file and creates a .tar.bz2 """ tar_contents = open(tar_file, 'rb') bz2file = bz2.BZ2File(destination + '.tar.bz2', 'wb') bz2file.writelines(tar_contents) bz2file.close() tar_c...
62704974ef5831559425d93bb8e3c6cbbb1e3e4b
498,594
def find_first_entry(line, elements, start=0, not_found_value=-1): """ Find the index of the earliest position inside the `line` of any of the strings in `elements`, starting from `start`. If none are found, return `not_found_value`. """ first_entry=len(line) for e in elements: pos=...
171f0f1cbbc9fbaa3d65faacec7e6eca673eb378
83,311
import base64 import gzip import json def extract_log_events(event): """Decode and decompress log data.""" log_data = event['awslogs']['data'] compressed_data = base64.b64decode(log_data) decompressed_data = gzip.decompress(compressed_data) json_data = json.loads(decompressed_data) log_stream ...
f26196feb6a5e42f5177fe093f69486c4a531f16
379,477
def generate_link(word, link): """ Return a str like a markdown link :return: str (example: [python](https://en.wikipedia.org/wiki/Python_(programming_language))) """ return f'[{word}]({link})'
290ece2e7a947c721adf255b018164428dbb09f2
424,642
def __get_station(seedid): """Station name from seed id""" st = seedid.rsplit('.', 2)[0] if st.startswith('.'): st = st[1:] return st
ab0795ce4b252a25c9eb1ba96d7b2f595ab48774
482,142
from typing import Union from typing import Type from typing import Any import inspect from typing import Sequence def is_sequence(item: Union[object, Type[Any]]) -> bool: """Returns if 'item' is a sequence and is NOT a str type.""" if not inspect.isclass(item): item = item.__class__ return ( ...
4aa68c2870c1c974e5e5e358a2428b5806408351
518,873
def _tr_xml_to_json_extension(xml_filename): """ _tr_xml_to_json_extension Translates example.xml to example.json (just the filename) """ if '.xml' in xml_filename: return xml_filename.replace('.xml', '.json') else: return xml_filename + '.json'
2a90c24f8a49d26ba0109af73de903cb3540550d
571,846
def get_centers(bins): """Return the center of the provided bins. Example: >>> get_centers(bins=np.array([0.0, 1.0, 2.0])) array([0.5, 1.5]) """ bins = bins.astype(float) return (bins[:-1] + bins[1:]) / 2
4f5b3454e1ef718302c7e5ea204954d498ca9e10
702,265
from typing import Iterable from typing import Hashable def any_in(x: Iterable[Hashable], y: Iterable[Hashable]) -> bool: """ Check if any elements in `x` is in `y`. Returns `True` if `x` is empty. Defined to improve readability. Examples: >>> any_in([1, 2, 2, 1, 2], [1, 2, 3]) True ...
9be46812d36c21668a0776a4e55d523af169814e
557,260
import re def _agg_removing_duplicates(agg_elem): """Aggregate while removing the duplicates. Aggregate the labels or alt labels together as a single element can have several Wikidata entities that need to be merged. Args: agg_elem (list of string): elem to aggregate Returns: st...
f0b17d9acdd97452a728ed990f8150a72cbbe0f8
685,980
import codecs def splinter_screenshot_getter_html(splinter_screenshot_encoding): """Screenshot getter function: html.""" def getter(browser, path): with codecs.open(path, "w", encoding=splinter_screenshot_encoding) as fd: fd.write(browser.html) return getter
dfc2018f65cff5a89b6fa488252544b9a368b501
185,428
def normalize_prefix(path): """Add trailing slash to prefix if it is not present >>> normalize_prefix("somepath") 'somepath/' >>> normalize_prefix("somepath/") 'somepath/' """ if path is None or path is '' or path is '/': return None elif path.endswith('/'): return path ...
6b9d921cf04e55e51b1919eee7cd5a6f1642d7e8
509,032
import hashlib def hash_file(readable_file): """ Returns SHA256 hash of readable file-like object """ buf = readable_file.read(4096) hasher = hashlib.sha256() while buf: hasher.update(buf) buf = readable_file.read(4096) return hasher.hexdigest()
5b878c81a81a7a35318e83cf4b532917aabbe917
330,929
import inspect def _first_param_empty(signature): """Check whether the first argument to this call is empty, ie. no with a default value""" try: first = next((signature.parameters.items()).__iter__()) return first[1].default == inspect._empty except StopIteration: return True
052db9e7db8ceaf78af58a378f0ebd3f7994bab8
71,401
def get_words(wlist): """ Extract words from a file. @param wlist String name of file to read @return list List of all possible answer words (strings) """ with open(wlist, "r", encoding="UTF-8") as f_file: ostr = f_file.read() return ostr.split()
1975f1e58c6b4dbcff212fd4a979133cf96d8d37
448,515
def extract_params(params): """ Extracts the values of a set of parameters, recursing into nested dictionaries. """ values = [] if isinstance(params, dict): for key, value in params.items(): values.extend(extract_params(value)) elif isinstance(params, list): for value...
9c1fd2f0ba0b98d807fc1c6d8b435dce6ac8f3e5
362,362
def scale_to(x, from_max, to_min, to_max): """Scale a value from range [0, from_max] to range [to_min, to_max].""" return x / from_max * (to_max - to_min) + to_min
e48e1f6556ee39fbdbba3cf2aa62e4efbcefba1c
651,793
from typing import Dict def loss_dict() -> Dict[str, float]: """ Initialize loss dictionary for network sub-tasks """ # Add z in front of each key name so they appear on the bottom (and together) in tensorboard d = {'z_normals_loss': 0.0, 'z_scene_loss': 0.0, 'z_depth_loss': 0.0, 'z_conf_loss': 0.0, ...
f8b5c2c3fb4dad0431cce29583e928d1ed1b772e
413,427
def coord(x, y, unit=1): """ Converts pdf spacing co-ordinates to metric. """ x, y = x * unit, y * unit return x, y
23bae6aef93de37c045f3a6eae8460ffed32c105
182,634
def X(val): """ Compact way to write a leaf node """ return val, []
88b3d62cec471d2614ff7c220de0dc20e0c74930
284,356
from warnings import warn def find_torder(dic, shape): """ Find the torder from the procpar dictionary. If propar dictionary is incomplete a UserWarning is issued and 'r' is returned. Parameters ---------- dic : dict Dictionary of parameters in the procpar file. shaoe : tuple...
ad50702de4cea2fe25618f59893c55dddead036b
306,504
def fn_name(fn): """Return str name of a function or method.""" s = str(fn) if s.startswith('<function'): return 'fn:' + fn.__name__ else: return ':'.join(s.split()[1:3])
67ed11485b1f8edfa517a84aafae56031edc01f8
427,198
import ipaddress def is_valid_ipv4_address(address): """Check if the given ipv4 address is valid""" invalid_list = ['0.0.0.0','255.255.255.255'] try: ip = ipaddress.IPv4Address(address) if (ip.is_reserved) or (ip.is_multicast) or (ip.is_loopback) or (address in invalid_list): r...
ec7d8450f3f9aaad0248474fecc22f220d227cb8
403,769
import sympy import six import random def _split_factors(integer): """Randomly factors integer into product of two integers.""" assert integer.is_Integer if integer == 0: return [1, 0] # Gives dict of form {factor: multiplicity} factors = sympy.factorint(integer) left = sympy.Integer(1) right = symp...
5a0adbc43296c325ee01b2043e5096c9702ce562
635,070
def add_segment_final_space(segments): """ >>> segments = ['Hi there!', 'Here... ', 'My name is Peter. '] >>> add_segment_final_space(segments) ['Hi there! ', 'Here... ', 'My name is Peter.'] """ r = [] for segment in segments[:-1]: r.append(segment.rstrip()+' ') r.append(segment...
6593cbd325cac7a102ec21a7bfc16e22e74dc31f
665,780
import torch def pad(seq_batch, pad_token=0, min_len=None): """Pads a list[list[Object]] so that each inner list is the same length. Args: seq_batch (list[list[Object]]): batch of sequences to pad. pad_token (Object): object to pad sequences with. min_len (int | None): all sequences padded to at leas...
636604ded73b37353dc825589751180f8af96a11
408,103
def find_freq(wvec, freq_val): """ Helper function returns the nearest index to the frequency point (freq_val) """ return min(range(len(wvec)), key=lambda i: abs(wvec[i]-freq_val))
262605d4b641c36470a2985a0008e4ea0d79d4cf
624,221
def utc_to_esmf(utc): """ Converts a UTC datetime into ESMF format. :param utc: python UTC datetime :return: a string in ESMF format """ return "%04d-%02d-%02d_%02d:%02d:%02d" % (utc.year, utc.month, utc.day, utc.hour, utc.minute, utc.second)
e9bd2b37895c6578a6c03ff3ac59a6cd209612d5
341,043
def getlinktags(link): """ Return tags for a link (list) """ linktags = link.get('tags') if linktags is None: linktags = list() else: linktags = linktags.split(',') return linktags
cd44f493a43e4c7d53b4a6c6f7faff80582904f2
535,480
def _NormalizeArgd(rawDict): """ Normalize the argument dictionary. All parameters start with '#' will be checked whether it is not None(client did not pass it). After checking a new dictionary will be generated and returned. :param rawDict: a dict, contains request args with required attribute flag...
b2778285370429c2a1e02b2bdde923fdb6828d9d
561,338
import math def choose_grid_size(train_inputs, ratio=1.0, kronecker_structure=True): """ Given some training inputs, determine a good grid size for KISS-GP. :param x: the input data :type x: torch.Tensor (... x n x d) :param ratio: Amount of grid points per data point (default: 1.) :type rati...
1d3e30a6b7b419a1e2fcdc245830aa00d1ba493d
11,411
def available(func): """A decorator to indicate that a method on the adapter will be exposed to the database wrapper, and will be available at parse and run time. """ func._is_available_ = True return func
a0c886bccb9bbbdacfe23c5659929b8be68c004e
698,352
import re def camel_case_to_underscore(name): """Converts camel case names to underscore lower case.""" return re.sub( '([a-z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), name)
2bf5ec8ab0825f007d5d852f126843e7119ad0be
552,283
def count_keys(num_qubits): """ Return ordered count keys. """ return [bin(j)[2:].zfill(num_qubits) for j in range(2 ** num_qubits)]
dd5a5c5b5de39894ca113f24d15b1056ac68aff6
465,716
def _get_best_joint_indexes(max_span_length, logits, n_best_size): """Gets the n-best start and end indices from flat logits.""" indices = sorted(range(len(logits)), key=logits.__getitem__, reverse=True) indices = indices[:n_best_size] starts = [x // max_span_length for x in indices] offsets = [x % max_span_l...
0e6fe7a0401c84424eec10f087cb9d7edb53090c
222,930
def parse_attestation(attestation): """ Given a bytes of the attestation report of length 688, return a dict of each field of the report """ assert(len(attestation) == 752) parsed_report = {} parsed_report['nonce'] = attestation[:32] parsed_report['attest_pk'] = attestation[32:...
5098acaef93f538822f31d5231a4e6f5e8fecc81
221,575
def get_keytable_path(opendkim_conf): """Returns the path to the KeyTable file from the OpenDKIM config. """ param = 'KeyTable' with open(opendkim_conf, 'r') as f: for line in f: if line.startswith(param): return line.replace(param, '').strip() msg = "Could not ...
cc40686d6dd9440747dff76ea0ceaafc0c3357ad
642,842
import errno def ps_zombies_list(pids): """ Given a list of PIDs, return which are zombies :param pids: iterable list of numeric PIDs :return: set of PIDs which are zombies """ zombies = set() for pid in pids: try: with open("/proc/%d/stat" % pid) as statf: ...
151c5e946923ef1fa9150dfc3df92a9d5c4e5b90
407,596
def GetBgpRoutingMode(network): """Returns the BGP routing mode of the input network.""" return network.get('routingConfig', {}).get('routingMode')
ae682acd55a74897dcd896ea52b8d146639bcf6a
493,152
def parse_volume_bindings(volumes): """ Parse volumes into a dict. :param volumes: list of strings :return: dict """ def parse_volume(v): if ':' in v: parts = v.split(':') if len(parts) > 2: hp, cp, ro = parts[0], parts[1], parts[2] ...
34a72defb428e109ac400b6ff31681dd6e16a9c5
660,483
from pathlib import Path def check_directory(dir_path: str): """create git instance Args: dir_path (str): fullpath of git root directory Raises: FileExistsError: dir_path does not exist FileExistsError: dir_path does not have .git directory Returns: strin...
fd27fbf11d93e5c03080b19e321938c256e5b9a0
396,451
import math def cosine_similarity(v1, v2): """ compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||) """ sumxx, sumxy, sumyy = 0, 0, 0 for i in range(len(v1)): x = v1[i] y = v2[i] sumxx += x*x sumyy += y*y sumxy += x*y return 1.0 - sumxy / ...
ab5eb9782d74546663c59a844eecd39ef01a0a97
479,288
def get_manifest_out_of_files(files): """ Parses `files` for a file that ends with `androidmanifest.xml`. :param Set[str] files: list of paths to files as absolute paths :return: manifest string if in `files`, else None """ for file_name in files: if file_name.lower().endswith("androidma...
6e9e209920a7bc1a810679ab3d20eb7e2a2048ef
614,140
def get_module_task_instance_id(task_instances): """ Return the first task instance that is a module node. """ for id in task_instances: if task_instances[id] == 'module_node': return id return None
0423f87090d9b71f5a83d07f8719ccb870f4d275
288,368
from typing import Callable def search(low: int, high: int, test: Callable[[int], bool]) -> int: """Binary search: [low..high) is the range to search; function "test" takes a single value from that interval and returns a truth value. The function must be ascending: (test(x) and y >= x) => test(y). Ret...
047ee9fbb21461d02299f7d8a27dd37d29757717
76,181
import posixpath def decode_single_feature_from_dict( feature_k, feature, tfexample_dict): """Decode the given feature from the tfexample_dict. Args: feature_k (str): Feature key in the tfexample_dict feature (FeatureConnector): Connector object to use to decode the field tfexample_dict (...
e61120e6889c66c57813146845a3b15620ab5f33
473,461
def minSegment(self,*args,**kwargs): """ Get segment min length """ return self._np(isNorm=False,isSegment=True)
881bd0fc7f5ec45f30e16cd00f838636f6e3a645
176,487
def is_sim_meas(op1: str, op2: str) -> bool: """Returns True if op1 and op2 can be simultaneously measured. Args: op1: Pauli string on n qubits. op2: Pauli string on n qubits. Examples: is_sim_meas("IZI", "XIX") -> True is_sim_meas("XZ", "XX") -> False ...
03484aed2c5d4a9181056ff376b8252eab69327c
238,485
def binary_boundary(t, d): """ Return the last <t integer that is a multiple of 2^d >>> binary_boundary(11, 4) 0 >>> binary_boundary(11, 3) 8 >>> binary_boundary(11, 2) 8 >>> binary_boundary(11, 1) 10 >>> binary_boundary(15, 4) 0 >>> binary_boundary(16, 4) ...
b4c3f1a183166fa113cad5634fe58c6ebfe06776
154,296
def collatz(n): """ The Collatz sequence generating function: f(n) = (1/2)n if n is even, or 3n + 1 if n is odd """ return int(n / 2) if n % 2 == 0 else 3*n + 1
58b68c63f17c72a1097a49456be5135ed85c48b4
592,781
def printBond(bond): """Generate bond line Parameters ---------- bond : Bond Object Bond Object Returns ------- bondLine : str Bond line data """ R0 = 0.1*bond.R0 K0 = bond.K0*836.80 return '<Bond class1=\"%s\" class2=\"%s\" length=\"%0.6f\" k=\"%0.6f\"/>\...
813b5d67eaa9119efc74bf018e647486faa0074b
626,219
import hashlib def hash256(string): """ Create a hash from a string """ grinder = hashlib.sha256() grinder.update(string.encode()) return grinder.hexdigest()
7409e5053a3ee61f534ec05edfffaf63bd6ca3e6
656,348
def _get_tag_name_from_entries(media_entries, tag_slug): """ Get a tag name from the first entry by looking it up via its slug. """ # ... this is slightly hacky looking :\ tag_name = tag_slug for entry in media_entries: for tag in entry.tags: if tag['slug'] == tag_slug: ...
0906c849f632a0f17c0e5128cd13baf0f3d3264a
595,753
def request_add_host(request, address): """ If the request has no headers field, or request['headers'] does not have a Host field, then add address to Host. :param request: a dict(request key, request name) of http request :param address: a string represents a domain name :return: request after add...
0ae2eb267e5042b3a662fb8f8b6bb4ec03c56b37
630,340
import struct def _pad_float32(pos: int) -> int: """ Helper method to pad to the next page boundary from a given position. Parameters ---------- pos : int Current offset Returns ------- padding : int Required padding in bytes. """ float_size = struct.calcsize(...
29d6258ea15139b20f613b81fef389987f4581b0
295,366
def derivative_tanh(tanh_output): """ Compute derivative of Tanh function """ return 1 - tanh_output**2
8343d3bdb1b3385bd257f4ed7891b3414deec080
314,221
import requests def can_connect_to_wiktionary() -> bool: """Check whether WAN connection to Wiktionary is available.""" try: requests.get("https://en.wiktionary.org/wiki/linguistics") except (requests.ConnectionError, requests.ConnectTimeout): return False else: return True
61030a79f58f694f62693f02f35255e65a1e1390
211,059
def time_calc(ttime): """Calculate time elapsed in (hours, mins, secs) :param float ttime: Amount of time elapsed :return: int, int, float """ # create local copy tt = ttime # if not divisible by 60 (minutes), check for hours, mins, secs if divmod(tt, 60)[0] >= 1: h_t = divmo...
efcc768c0c45b846c4328ed2eef20a510d02d919
322,810
def to_hgvs(variants, reference=None, only_substitutions=True, sequence_prefix=False, sort=True): """An allele representation of a list of variants in HGVS [1]_. Parameters ---------- variants : list A list of variants. reference : str or None, optional The reference sequence. ...
f97014d556c4f99ddb4f759113f0ddc8975db3f7
410,618
def split_identifier(identifier): """Splits string at _ or between lower case and uppercase letters.""" prev_split = 0 parts = [] if '_' in identifier: parts = [s.lower() for s in identifier.split('_')] else: for i in range(len(identifier) - 1): if identifier[i + 1].isup...
820486a85e17756f49fb4b18be995f0d4d2a1e92
553,940
def kyc_token(chain, team_multisig, initial_supply): """Create the token contract.""" args = ["KYC token", "KYC", initial_supply, 18, True] # Owner set tx = { "from": team_multisig } contract, hash = chain.provider.deploy_contract('CrowdsaleToken', deploy_args=args, deploy_transaction=tx...
75f505d063b24a943adf4b7692a49ee17feffde4
296,340
import torch def quat_conjugate(a: torch.Tensor) -> torch.Tensor: """Computes the conjugate of a quaternion. Args: a: quaternion to compute conjugate of, shape (N, 4) Returns: Conjugated `a`, shape (N, 4) """ shape = a.shape a = a.reshape(-1, 4) return torch.cat((-a[:, :3...
530eb2a8d8b9b87de2bfcaeb48729704908131cc
14,132
def get_seq(query_filepath): """ Get a sequence from a single-entry FASTA file. """ f = open(query_filepath,'r') lines = f.readlines() lines = [row.strip() for row in lines] # restituisce una copia della stringa con i caratteri iniziali e finali rimossi per le righe in fila lines = [row.repl...
fd77760a389e192d60ecc592e1a3ca8fa1c9b17e
618,876
def parse_colon_delimited_options(option_args): """Parses a key value from a string. Args: option_args: Key value string delimited by a color, ex: ("key:value") Returns: Return an array with the key as the first element and value as the second Raises: ValueError: If the key value option is ...
7d083298ed9c35853b352fe545d9e15a69089694
544,410
def GetLabel(plist): """Plists have a label.""" return plist['Label']
b6692b603c72e829fe819e22dc219905f6db151f
646,196
def output(output_name, product_index=0): """Return a selector function for a specified output of a product. :param output_name: the name of the output to select :param product_index: which product's outputs to look in """ return lambda facility: facility.products[product_index].outputs[output_name...
d038db0650352c6d94a9e794c31e56afce1c13ea
341,532
def to_money(money_value: float) -> str: """Returns the float as a string formatted like money.""" return '{:,.2f}'.format(money_value)
054251804e5d918ce81a949c705e91e7a26c70b2
255,085
def linecoef(p1, p2): """ Coefficients A, B, C of line equation (Ax + By = C) from the two endpoints p1, p2 of the line Input: p1, p2 the two points (x, y) of the line segment Output: Coefficients of the line equation """ # ref: https://stackoverflow.com/questions/20677795/ # how-...
03fac6db5b9b425e03421f963008876aff854a51
318,290
def _find_direct_matches(list_for_matching, list_to_be_matched_to): """ Find all 100% matches between the values of the two iterables Parameters ---------- list_for_matching : list, set iterable containing the keys list_to_be_matched_to : list, set iterable containing the values...
c333a6f719a768bdfc1f4b615b22c48dd7b34e73
438,997