content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import json def jsonDecode(input): """ JSON decode. @param (str) input @return (mixed) """ try: return json.loads(input) except: pass
1200f71a2eab680ac41e4acddd6169f15359e4ee
673,639
def qualify(ns, name): """Makes a namespace-qualified name.""" return '{%s}%s' % (ns, name)
98cc677f4e149d2f515f844fa69e4164442241b1
673,640
import difflib def simple_merge(txt1, txt2): """Merges two texts""" differ = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK) diff = differ.compare(txt1.splitlines(1), txt2.splitlines(1)) content = "".join([l[2:] for l in diff]) return content
db353b9fd73a130b8fa6014968546345f66c2aec
673,641
def encoding_fmt(request): """ Fixture for all possible string formats of a UTF encoding. """ return request.param
53bc76ee4e5f4188cb5f6bce669d6ea3387a6bca
673,642
import math def sph2cart(theta, phi, r=1): """Converts spherical coords to cartesian""" x = r * math.sin(theta) * math.cos(phi) y = r * math.sin(theta) * math.sin(phi) z = r * math.cos(theta) vect = [x, y, z] return vect
cf793f0a81baefa80c96863d1b765fdd8d30b637
673,643
import base64 def convert_img_to_b64_string(img_path): """ Converts medical image to b64 string This function takes the image filepath as an input and outputs it as a b64 string. This string can be sent to the server and then the database. Args: img_path (str): the name of the file path contai...
b9d1e2077ae2e7f9c8e027a56c25e79d0262cb27
673,644
import random import math def randomLogGamma(beta,seed=None): """ Generate Log-Gamma variates p(x|beta) = exp(beta*x - x)/gamma(beta) RNG derived from G. Marsaglia and W. Tsang. A simple method for generating gamma variables. ACM Transactions on Mathematical Software, 26(3):363-372, 2000. See http...
3a1afeb59fbb2f6ad969e16de3ca1c58faa747c5
673,645
def _fmt_cmd_for_err(cmd): """ Join a git cmd, quoting individual segments first so that it's relatively easy to see if there were whitespace issues or not. """ return ' '.join(['"%s"' % seg for seg in cmd])
4b201ec9ba9f1f27df18913f1104bee4f98dcc49
673,647
def get_slices_by_indices(str, indices): """Given a string and a list of indices, this function returns a list of the substrings defined by those indices. For example, given the arguments:: str='antidisestablishmentarianism', indices=[4, 7, 16, 20, 25] this function returns the list:: ['...
e69bd33abfd3f9f423ed33c3b46841ad0ed1a30e
673,648
def cli(ctx, func="download", source="", dbkey="", ncbi_name="", ensembl_dbkey="", url_dbkey="", indexers=""): """Download and/or index a genome. Output: dict( status: 'ok', job: <job ID> ) If error: dict( status: 'error', error: <error message> ) """ return ctx.gi.ge...
2041a692e2ad81be9841f8cbfd41bd8a65b04c73
673,649
def _read_pid_file(filename): """ Reads a pid file and returns the contents. PID files have 1 or 2 lines; - first line is always the pid - optional second line is the port the server is listening on. :param filename: Path of PID to read :return: (pid, port): with the PID in the file and the p...
afccae64451ab50c0bb1e179095e4cac23730526
673,651
def col_variables(datatype): """This function provides a key for column names of the two most widely used battery data collection instruments, Arbin and MACCOR""" assert datatype == 'ARBIN' or datatype == 'MACCOR' if datatype == 'ARBIN': cycle_ind_col = 'Cycle_Index' data_point_col =...
004d851de05c2d0e07ced93a454b6c0377407f31
673,652
def get_languages(s): """ A function to obtain language settings via Accept-Language header. """ langs = [''.join(x.split(';')[:1]) for x in s] return langs
92b51de5791aa12ae54826b26f0f4e5cd8b0aea2
673,653
def make_contribs_dict(tsv_in, ignore=4, initials_col=None, sort_categories=False): """ Convert input author contributions .tsv to dict mapping contribution categories to author initials """ with open(tsv_in) as f: # Read first line of tsv_in to get contribution categories categs ...
ddc10afb32942055d0c03bcd2a9944b817009162
673,654
def build_dummy_module_def(group_name, fifo_type, module_in, PE_ids): """Build the definition of the dummy module Parameters ---------- group_name: str fifo_type: str module_in: int PE_ids: list """ dir_str = "out" if module_in == 0 else "in" index_str = ["idx", "idy", "idz"] ...
cb30e32aebc6796a8687f14e67eb5a50de20a080
673,655
def run(M=10, N=100, D=5, seed=42, maxiter=100, plot=True): """ Run deterministic annealing demo for 1-D Gaussian mixture. """ raise NotImplementedError("Black box variational inference not yet implemented, sorry") if seed is not None: np.random.seed(seed) # Generate data data = n...
3aafb6801c54cbe9f4f0f08ffadcf933d343ddf6
673,656
def uri_to_id(uri): """ Utility function to convert entity URIs into numeric identifiers. """ _, _, identity = uri.rpartition("/") return int(identity)
1578a3a6716e20cede81aeebf04a8da6455413d1
673,657
from typing import Dict from typing import Any from typing import Optional from typing import List def find_targets(scene: Dict[str, Any], num_targets: Optional[int] = None) -> List[Dict[str, Any]]: """Find 'target' objects in the scene. (IntPhys goals don't really have them, but they do have objects that may...
b1f05c75785586fcfb6a8e3f00168303ea58a1e4
673,658
def centimeter2feet(dist): """ Function that converts cm to ft. """ return dist / 30.48
f943b322760696d42d45e20da3565cb6e7c20ddb
673,659
def showreporoot(context, mapping): """String. The root directory of the current repository.""" repo = context.resource(mapping, 'repo') return repo.root
08b84afe2bdb79e3bafeeba408342345577ec796
673,660
import struct def char(c): """ Input: requires a size 1 string Output: 1 byte of the ascii encoded char """ return struct.pack('=c', c.encode('ascii'))
355303fdd2bbfbb77ec59e8adb14c6f01841fc90
673,661
import random def test_data(): """Return a pseudo-random string of length between 0 and 5120.""" length = random.randint(0, 5120) data = [chr(random.randint(0, 255)) for i in range(length)] return "".join(data)
739e4112666991b25dd5a62c8c8cb042fc9cefbc
673,662
import torch def covariance_z_mean(z_mean): """Computes the covariance of z_mean. Borrowed from https://github.com/google-research/disentanglement_lib/ Uses cov(z_mean) = E[z_mean*z_mean^T] - E[z_mean]E[z_mean]^T. Args: z_mean: Encoder mean, tensor of size [batch_size, num_latent]. Returns: ...
f9b82a6bb3c08c3ca59381c3f877cfbf0542aeb1
673,663
import socket def inet_to_str(inet): """Convert inet object to a string :param inet: inet network address :type inet: inet struct :return: str of printable/readable IP address """ try: return socket.inet_ntop(socket.AF_INET, inet) except ValueError: return socket.inet_nto...
313864b214fda7cccf2781fc049381ea998a93b2
673,664
import torch def get_idxs(results, test_targets, device): """ Args: results (tensor): predictions test_targets (tensor): Ground truth labels Returns: miss_index: index of misclassifier images hit_index: index of correctly classifier images """ miss_index = torch.where((results.argmax...
9c194b7b97c19ab5ff05412de7079bd16f5c2eb3
673,665
def genus_species(tokens): """ Input: Brassica oleracea Output: <taxon genus="Brassica" species="oleracea" sub-prefix="" sub-species=""><sp>Brassica</sp> <sp>oleracea</sp></taxon> """ (genus, species) = (tokens[0], tokens[1]) return f'''<taxon genus="{genus}" species="{species}" sub-prefix=...
1f492a28a254b07857428f4610f0c700e1f74833
673,666
def is_redirect(code): """Return that further action needs to be taken by the user agent in order to fulfill the request.""" return 300 <= code <= 399
3a02f5a6c7450222c0a4d5217097d4f76a0eff04
673,667
import torch def hotflip_attack(averaged_grad, embedding_matrix, increase_loss=False, num_candidates=1, filter=None): """Returns the top candidate replacements.""" with torch.no_grad(): gradient_dot_embedding_matrix = torch.ma...
24b7ab70c4b8b20be68291d9d9dfed1963228940
673,668
def calc_g_max(g_cur, g_max): """ Calculates g_max """ if g_cur > g_max: g_max = g_cur return g_max
6947c053032df30da406c186e0962ba5a4648bb7
673,670
def osc(last, type): """ R=[AG], Y=[CT], K=[GT], M=[AC], S=[GC], W=[AT], and the four-fold degenerate character N=[ATCG] """ if type == "r": if last == "a": return("g") if last == "g": return("a") return("a") if type == "y": if last == "c": return("t") if ...
e46371e9eab32c6f4ebb9f8c31cbb446ac23ea9f
673,672
def trailing_zeros(value: int) -> int: """Returns the number of trailing zeros in the binary representation of the given integer. """ num_zeros = 0 while value & 1 == 0: num_zeros += 1 value >>= 1 return num_zeros
bcb760be12e1b918647a017c04d5b46d87035510
673,673
def get_health_multiple(obj): """ get individual scores for 4 repo components. """ branch_count = 0 branch_age = 0 issues = 0 pull_requests = 0 denom = len(obj["repo"]) assert all(isinstance(obj[x], list) for x in obj) assert all(len(obj[x]) == denom for x in obj) for brc in ...
11c85252ddf694dba295d8dd6bd5e117e4d3fff7
673,674
def getAverageVectorForWords( word_list, model, np ): """Calculates average vector for the set of word. Parameters ---------- word_list : array Array of words in format [word1, word2, ...]. model : object Word2Vec model. np : object numpy library. Return...
5ee60efff539ec1b46728a7c16d1f5b4cf00db1b
673,675
def is_ethiopia_dataset(name): """Names with 'TR' at start or Ethiopia""" return name.upper().startswith('TR') or \ name.lower().find('ethiopia') > -1
81f9981a4389f9c9fe7a19f23f8a66541116b04d
673,676
import logging import sys def my_custom_logger(logger_name, log_file, level=logging.info): """ Method to return a custom logger with the given name and level """ logger = logging.getLogger(logger_name) logger.setLevel(level) format_string = '%(asctime)s %(message)s' datefmt_string ='%m/%d/...
69d0414db2164ee5ba65bf9978f66f473b3d614a
673,677
def format_dependencies(id_to_deps): """Format a dependency graph for printing""" msg = [] for name, deps in id_to_deps.items(): for parent in deps: msg.append("%s -> %s" % (name, parent)) if len(deps) == 0: msg.append('%s -> no deps' % name) return "\n".join(msg)
70f31b01365f2d1e6cabca5a9c277662c99eef8e
673,678
import win32file def get_usb_paths_windows(): """ Credit: https://stackoverflow.com/questions/4273252/detect-inserted-usb-on-windows https://mail.python.org/pipermail/python-win32/2006-December/005406.html """ path_list = None # [] drivebits = win32file.GetLogicalDrives() for d in range(1, 26): mask = 1 <<...
241eccb8edf4567b0e1f8b8ecffe69f99be5bbbe
673,679
from pathlib import Path def exhaustive_directory_search(root, filename): """Executes an exhaustive, recursive directory search of all downstream directories, finding directories which contain a file matching the provided file name query string. Parameters ---------- root : os.PathLike ...
cf6ded7ccce0af81190c1337dd511c44d45c3557
673,680
import math import struct def _bytes_to_int(b): """Convert bytes to hex integer""" len_diff = 4 - len(b) % 4 if len(b) % 4 > 0 else 0 b = len_diff * b'\x00' + b # We have to patch leading zeros for using struct.unpack bytes_num = int(math.floor(len(b) / 4)) ans = 0 items = struct.unpack('>' +...
67f44fc8a99068aed566ff03a897a23812654949
673,681
import inspect def get_commands(inputs: dict, module): """Processes the inputs and the given logic module Returns: The mapped functions on the module The command stacked from the inputs The outputs needed in the view""" functions = dict(inspect.getmembers(module, inspect.isfunction...
0f716ce6044238ff2625197e8251b7006c295464
673,682
def dot(v1,v2): """Dot product of two vectors""" n = len(v1) prod = 0 if n == len(v2): for i in range(n): prod += v1[i]*v2[i] return prod
569ad317cf8d875a0c0592a576c3987b02b54f95
673,683
def has_time_layer(layers): """Returns `True` if there is a time/torque layer in `layers. Returns `False` otherwise""" return any(layer.time for layer in layers if not layer.is_basemap)
0351fa97cab084b90e836f624a86baf8922861a1
673,684
def __plugin_cves(data, db): """ Get CVEs of a plugin :param data: PlecostDatabaseQuery object :type data: PlecostDatabaseQuery :return: results of query :rtype: str """ _plugin = data.parameter _query = ("SELECT DISTINCT(cve) " "FROM PLUGIN_VULNERABILITIES_CVE as PV...
c71425180fa114119b5016db6b1838124aebc32c
673,685
import secrets def generate_new_day_key(): """Returns a fresh random key""" return secrets.token_bytes(32)
872e291a49b088be24ec49caf7789df2bf5ec2c2
673,686
def is_storage(file, storage=None): """ Check if file is a local file or a storage file. Args: file (str or int): file path, URL or file descriptor. storage (str): Storage name. Returns: bool: return True if file is not local. """ if storage: return True eli...
2b4355e4efba38aef2ce5a5961e6013947b3cd94
673,687
def flatten(x): """flatten(sequence) -> list Return a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples:: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,No...
d435e06613671b1786dcc6de18804ff83d4fa808
673,688
import argparse def build_parser(argslist): """ _build_parser_ Set up command line parser for the selfupdate command """ parser = argparse.ArgumentParser( description=( 'git cirrus selfupdate command, ' 'used to update cirrus itself' ) ) parser...
2d45e2f26c8922a171d1c6ab1e5e71533e6df6cb
673,689
def get_strings_section(config, section): """ Get config file options from section containing strings. :param config: ConfigParser object. :param section: Name of the section to be read. """ options = config.options(section) section_dict = {} for option in options: secti...
65f5ce24464612c8eef8c19fc2253a98bcb026ec
673,691
from typing import Optional import os def get_write_path(original_path: str, write_dir_path: Optional[str], n_clusters: int, conducted_iterations: int) -> str: """ Returns: altered image file name being extended by n_clusters and conducted_iterations, prepended either by dir path original ...
886a7da65ee28346fb04dc1af23d2e37428cd98d
673,692
def minimum_distance(mp, ip, dp, i): """ Compares each element from the distance profile with the corresponding element from the matrix profile. Parameters ---------- mp: numpy.array Matrix profile. ip: numpy.array Index profile. ...
62cd66a15a3d3cf526c7eaca1f10fd5f56bde8f5
673,693
import torch def conj(self): """ Quaternion conjugate """ if len(self.shape) > 1: con = torch.cat([self.a, -self.b, -self.c, -self.d], 1) else: con = [self.a, -self.b, -self.c, -self.d] return self.__class__(con, False)
866c94b69e0376405b5287f869a8d2b8db30f10b
673,695
def convert_duration(milliseconds): """ Convert milliseconds to a timestamp Format: HH:MM:SS """ # it's easier to wrap your head around seconds seconds = milliseconds / 1000 hrs = seconds // 3600 mins = (seconds % 3600) // 60 s = (seconds % 3600) % 60 return "{:02}:{:02}:{:02}"...
dea6f0d09a0b53e193c1c0cfdf4f844f9da9bb65
673,696
def rivers_with_station(stations): """Returns a set containing all rivers which have a monitoring station. Params: Stations - List of all stations. \n. Returns: {River 1, River 2, ... } """ rivers = set() # set for station in stations: # iterate and add rivers to set r...
9422ecfade5fe19ce162911294abbd00e4444820
673,697
def place_mld_breakpoints(incompt_pos :list): """ Adds an MLD breakpoint in the middle of an incompatible interval. Parameters: incompt_pos (list): chop_list() output Output: list: indexes of MLD breakpoints in the sequence """ return [int(inter[0] + (inter[...
c194c879bc49ebda6bbaf8cadce44852b1ff73aa
673,698
def get_cnn_default_settings(kind): """Get default setting for mlp model.""" if kind == 'hidden_sizes': return [512] elif kind == 'activation': return 'relu' else: raise KeyError('unknown type: {}'.format(kind))
e7b11417e1df72c2551eefe521c50fe1912ee4aa
673,699
def random_variable_args(): """Provide arguments for each random variable.""" # Commented out tests are currently failing and will be fixed _random_variable_args = ( ("Bernoulli", {"probs": 0.5, "sample": 1.0}), ("Beta", {"concentration0": 1, "concentration1": 1}), ("Binomial", {"to...
70ae6a864f91a0f1ad7bcb79da15c3f89d190ff5
673,700
def list_drawings_from_document(client, did, wid): """List the drawings in a given workspace""" # Restrict to the application type for drawings res = client.list_elements(did, wid, element_type='APPLICATION') res_data = res.json() drawings = [] for element in res_data: if element['dataTy...
1d52169616688dbcde50761d89e7db17cde6a617
673,701
def read_order(order_file): """ Read the order of the API functions from a file. Comments can be put on lines starting with # """ fo = open(order_file, 'r') order = {} i = 0 for line in fo: line = line.strip() if not line.startswith('#'): order[line] = i ...
76d688fb780a3251a027f108127e7314e7c95b69
673,702
def crop_8x8(img): """Crop 8x8 of the input image.""" ori_h = img.shape[0] ori_w = img.shape[1] h = (ori_h // 32) * 32 w = (ori_w // 32) * 32 while h > ori_h - 16: h = h - 32 while w > ori_w - 16: w = w - 32 y = (ori_h - h) // 2 x = (ori_w - w) // 2 crop_img = img[y:y + h, x:x + w] retu...
d7e9d4b97d30bc1c12e7b81754769305402400a7
673,703
def add_spaces_to_fill(text, places): """Adds blank spaces to a string so that the length of the final string is given by 'places'. """ return text + (places-len(text))*" "
26b12e84b90fd331fdc8e1fd97d9680f050c9afe
673,704
from pathlib import Path def path(file): """Test asset path name resolution""" return Path(__file__).parent / 'assets' / file
42b3b83836fe3ec8fb9974f3b2884f8c4fb0f4e3
673,705
import math def update_global_state(global_params, aggregation_result, global_state): """ update global state object :global_params: global parameters object :aggregation_result: aggregation result :global_state: global state object to update :returns: global_state param """ def dist(...
e87aaef58771549bf5bea14acba9dd585905684f
673,706
import time def _invoke_timed_callback( reference_time, callback_lambda, callback_period): """Invoke callback if a certain amount of time has passed. This is a convenience function to standardize update callbacks from the module. Args: reference_time (float): time to base `callback_p...
44397d5c70d747966c83714a8ed17f9c3109de7c
673,707
def remove_entity_from_list(unique_list, i): """ Removes all instances of a particular entity from a list >>> remove_entity_from_list(['test', 'test', 'three'], 1) ['three'] """ return [x for x in unique_list if x != unique_list[i]]
ae66405b76842693ab629a8cd8ebc3d7ec145a24
673,708
import os import shutil def new_run_mkdir(directory, username, title): """Initialize directories for a new run. Clears out prior uploads with same title.""" os.makedirs(os.path.join(directory, username), exist_ok=True) try: shutil.rmtree(os.path.join(directory, username, title)) except OSError...
14bc8abe394184a8cef0086634ce590845948d23
673,709
def _tbl_str_width(num, widths): """Returns the width-argument for an html table cell using the width from the list of widths. Returns width="[some number]" or the empty-string if no width is specified for this num""" if num >= len(widths): return "" return ' width="%s"' % widths[num]
3d35c82033ae504eeac143f35653303f1425da60
673,710
import shutil def center_text(msg: str, *, pad: str = ' ') -> str: """Centers text horizontally for display within the current terminal, optionally padding both sides. :param msg: message to display in the center :param pad: if provided, the first character will be used to pad both sides of the message ...
3ead8c3bce298d779205bf0d6743ec6ac05c4d7a
673,711
def subscription_group(publisher_id): """ String ACL representation of subscriber permission. """ return 'subscription:{}'.format(publisher_id)
1ae8e3cc7aaf9085cac8809acc1af41855eb55bf
673,712
import typing def _parse_config_file(content: str) -> typing.Mapping[str, str]: """Parses an ini-style config file into a map. Each line is expected to be a key/value pair, using `=` as a delimiter. Lines without `=` are silently dropped. """ kv = {} for line in content.splitlines(): if not line or l...
b55a263aaeccb860d9212d35277df0db39893435
673,713
def get_same_padding_for_kernel_size(kernel_size): """ Returns the required padding for "same" style convolutions """ if kernel_size % 2 == 0: raise ValueError(f"Only odd sized kernels are supported, got {kernel_size}") return (kernel_size - 1) // 2
2c0c142d785ea1659f0bb03c22bfa1c972ae2e3d
673,714
import os def build_vistrails_cmd_line_file(path_to_vistrails, path_to_python, env_for_vistrails, filename, version, path_to_figures, pdf=False, wgraph=False, tree=False): """ build_vistrails_cmd_line_file(path...
52d04c39f82ddb76089b356b4f122adbfdc0d8c9
673,716
def _remove_output_cell(cell): """Remove the output of an ipymd cell.""" cell = cell.copy() if cell['cell_type'] == 'code': cell['output'] = None return cell
f4d19cc1c9d9b63988508d4dcc1f70ea68ef6716
673,717
def sum_loss(loss1, loss2): """ Keras only allows multiple losses if multiple outputs exists. Since only one output exists (because the trace loss is independent of the prediction output as no target exists), this loss allows to sum two other losses. """ def sum_loss_function(y_true, y_pred)...
9c2657c7f4a5707aa276694ae1289c7ee6156f64
673,718
from typing import Tuple from typing import Optional def _parse_hp_template(template_name) -> Tuple[str, Optional[int]]: """Parses a template name as specified by the user. Template can versionned: "my_template@v5" -> Returns (my_template, 5) or non versionned: "my_template" -> Returns (my_template, No...
2225eef7b2f21f5e5180b686261a1f413312b848
673,719
def construct_mapping(self, node, deep=False) -> dict: """ Custom function to override the YAML loader to ensure that keys are always strings. :param self: YAML safe loader :param node: YAML Node :param deep: Internal argument related to recursive construction :return: """ data = se...
7dfe372217e92921c4824d12055d9c19d86275af
673,720
def PyUnixTimeConv(some_DT_obj): """ func to convert DateTime Obj to Unix Epoch time, in SECONDS, hence rounding""" output_unix_time = some_DT_obj.timestamp() return round(output_unix_time)
657f6c34ee9cc9b98681ba2519e843466d1a01b6
673,721
def get_cigar_sheet(alignment): """ sift through alignment cigar string for single bp indels :param pysam.AlignedSegment: :return: cigar_sheets, # of single bp insertions, # of single bp deletions """ aln = alignment sheets = [] pairs = aln.aligned_pairs icount = 0 dcount = 0 al...
f2169f5b01683727f4c9e8a630029c228cf47ecc
673,722
import numpy as np def genTransMat(n): """ Generate transition matrix Arguments: n - dimension of transition matrix Return: transMat - an n*n transition matrix """ transMat = np.random.rand(n,n) #generate a square matrix consisting random numbers #Normalize transMat to be a tra...
fd31490b0643eeeb8c8455d64b953400dc45baac
673,723
import struct import socket def ip2long(ip): """Calculate the IP address as a long integer :param ip: IP address as a dotted-quad string :return: Long value of the IP address """ return struct.unpack('!L', socket.inet_aton(ip))[0]
22ef65c1b697e851af8b5ffbf1e296214d27ec09
673,724
import json def to_json(raw_data): """ Pretty-prints JSON data :param str raw_data: raw JSON data """ return json.dumps(raw_data, sort_keys=True, indent=4, separators=(',', ': '))
9faf1a31e2f906e8170226d81160a5523c201566
673,725
import aiohttp async def is_online() -> bool: """Function for checking if the api is online.""" try: async with aiohttp.ClientSession() as session: async with session.get('https://api.github.com') as response: if not response.status == 200: raise Excepti...
ef2d1da66bd989708d39684d8260e3154b2b429a
673,726
import re def get_sleep_awake_folder(s): """Get the if animal is sleeping from folder""" temp = re.split("_|\.|\ |\/", s.lower()) if "sleep" in temp or "sleeping" in temp: return 1 return 0
06c797da20273c3c316fda55db9be142a8a08ad9
673,728
def make_tuple(str_in): """ makes a tuple out of a string of the form "(a,b,c)" """ str_in = str_in.strip("()") l = str_in.split(",") return tuple(l)
d7ae58a3c618edbff3d2a83b72350d6ad32b1a3a
673,730
def rotate_ccw(str_array: list[str]) -> list[str]: """ Rotate a list of strings quarter-turn counter-clock-wise :param str_array: array as a list of strings :return: array rotated counter clock-wise """ zip_array = list(''.join(c) for c in zip(*str_array)) ccw_rot_array = zip_array[::-1] ...
a8bd4d70856c5c9c48d7b3778f14ceb0a2cbeb20
673,731
def get_object_name_from_schema(obj: object) -> str: """ Returns the name of an object based on type. This is used to return a userfriendly exception to the client on bulk update operations. """ obj_name = type(obj).__name__ to_remove = ["Base", "Create", "Update"] for item in to_remove:...
6e1d33f915ba6265bbea143b3e7c8b64fa06faab
673,732
def normalize_description(description): """ Normalizes a docstrings. Parameters ---------- description : `str` or `Any` The docstring to clear. Returns ------- cleared : `str` or `Any` The cleared docstring. If `docstring` was given as `None` or is detected as e...
4ece93902474f53ecce92cb3c902b0157beca733
673,733
import importlib def serialize(obj, only=tuple(), exclude=tuple()): """ Python object serializer :param obj: The object to parse into json string :return: A dictionary """ # Read from type name type_name = type(obj).__name__ try: # Convert string into actual class object ...
71911e4dc0d243ac71223588573c63a1474ba788
673,734
def htheta_function(x, theta_0, theta_1): """ Linear function that is to optimized """ return theta_0 + theta_1 * x
db1407e423c2ae251fbf6c655981de2b91684dea
673,735
def max_counts(ng1, ng2): """ Return a dicitonary of ngram counts such that each count is the greater of the two individual counts for each ngram in the input ngram count dictionaries /ng1/ and /ng2/. """ ret = ng1.copy() for k, v in ng2.items(): ret[k] = max(ret.get(k, 0), v) ...
d1c1b78353a1c07070b240b7806b753bd071a122
673,736
def turn(n): """Formula from WIkipedia. n could be numpy array of integers """ return (((n & -n) << 1) & n) != 0
b37e26fff265be114427fa1657e878eaa1b773a2
673,737
import torch def collate_fn(data): """批处理,填充同一batch中句子最大的长度""" x, spans, span_labels, relations, relation_labels, sequence_length = zip(*data) max_len = max(sequence_length) x = torch.stack( [torch.cat([item, torch.zeros(max_len - item.size(0), item.size(1))]) for item in x]) sequence_leng...
3cbf86ad7edd225243bfe973e771a56bed8bff06
673,739
import csv def csv_to_list(plants_csv_path, encode): """READ CSV TO LIST""" plants_list = [] with open(plants_csv_path, newline = "", encoding=encode) as f: reader = csv.reader(f) for row in reader: for i in row: parameters = i.split(';') plants_...
8f55499641f48d4c4e67c0cbc894c200d273d5d5
673,740
def ratio(x,y): """The ratio of 'x' to 'y'.""" return x/y
70b044627a75dd6fc583a84b87014bbade9b18c1
673,742
import operator def sequence_eq(sequence1, sequence2): """ Compares two sequences. Parameters ---------- sequence1 : sequence The first sequence. sequence2 : sequence The second sequence. Returns ------- bool `True` iff `sequence1` equals `sequence2`, othe...
3e6520602272873f471c808ad14c6d3a90d31972
673,743
import numpy import torch def subsequent_mask(size): """ Mask out subsequent positions. """ attn_shape = (1, size, size) mask = numpy.triu(numpy.ones(attn_shape), k=1).astype('uint8') return torch.from_numpy(mask) == 0
278b9c897fc8c8af8be331fdeacc48910307ade1
673,744
def strFromPositionRow(o): """Return string describing an order (for quick review when canceling orders). As always, 'averageCost' field is for some reason the cost-per-contract field while 'marketPrice' is the cost per share, so we manually convert it into the expected cost-per-share average cost for ...
316369d13847ce835d85536506a62b3658de98aa
673,745
def users_are_idiots(string): """ splits the input strings and removes any preceeding or trailing whitespaces. """ s = string.split(",") s = [i.strip() for i in s] return s
c540faab39725990d0c3e94c54354389574b6b93
673,746
import numpy def compute_vertex(origin_point, dh, tol=numpy.finfo(float).eps): """ Computes the bounding box of a rectangular polygon given its origin points and spacing dh. Args: origin_points: list of tuples, where tuple is (x, y) dh: spacing tol: used to eliminate overlapping p...
1be8350f38b452f2c1b4881088e1678233c23958
673,747
def hello(func): """make a func that print hello then execute a func Examples ------------- >>> def name(): ... print("Alice") ... >>> hello(name)() Hello Alice >>> @hello ... def name2(): ... print("Alice") ... >>> name2() Hello Alice """ ...
febf5699b6acb4f7d3ce829e81971da3e015c57c
673,748
import re def fix_tx_name(tx): """Remove the .[0-9] at the end of RefSeq IDs.""" if tx.startswith('NM'): return re.sub('\.[0-9]$', '', tx) else: return tx
68fae9ffd80b47da3d36ac919fa5a4ca2ad9a14f
673,750