content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def extract_modified_bs_sequence(sax_sequence): """ This functions extracts the modified Behaviour Subsequence (BS) sequence list, which is the original sax word sequence where every consecutive pairs of sax words are equal are fused into the same sax word. :param sax_sequence: list of original sax wor...
3a26278a478789032d35f994902440db3f879c9d
653,610
def build_ols_query(ontology_uri: str) -> str: """Build a url to query OLS for a given ontology uri.""" return "https://www.ebi.ac.uk/ols/api/terms?iri={}".format(ontology_uri)
160611dba7a3a543deec482c16d89da466f0d6cc
653,611
from bs4 import BeautifulSoup def generate_table_data(html_output): """Generate an ASCII table based on the HTML provided.""" soup = BeautifulSoup(html_output, 'html.parser') table_data = [ ['Parameter', 'Value'] ] for table in soup.select('table.specs'): rows = table.find_all("t...
09ecdd5f12c60b8ccadab8ee8cd44b494dea5773
653,614
def extract_resource_info_from_hls_rpt(rpt): """Extract the resource info from the HLS rpt. Parameters ---------- rpt: HLS report in XML format """ res = {"BRAM18K": 0, "DSP": 0, "URAM": 0, "FF": 0, "LUT": 0} root = rpt for est in root.iter("AreaEstimates"): for child in...
cfe46f325c4d871de5ff549af068011f1832b68d
653,615
import re def transform_col_in_line(line, col_transformations): """Given a line in a table definition, transform any column names for which a transformation is defined in `col_transformations`. """ col_patterns = [ "^\s*`([a-zA-Z0-9_]+)`.*,$", # fields "^\s*PRIMARY KEY \(`([a-zA-Z0-9...
833f48181561868d1b88309f99b52250ef8443ba
653,616
import socket import argparse def validate_address_port(address, port): """ Validate IP address and port """ try: socket.inet_aton(address) except socket.error: raise argparse.ArgumentTypeError( "%s is not a valid IP address" % address) if (port < 0) or (port > 65...
fb10fbec21407e02376f2609f6fe1ec68b862b02
653,617
def find_nested_vars(curr_dict, nested_key=None, var_list=[]): """ Returns a list of tuples with the nested key and var that needs to be replaced by parent Args: curr_dict (dict): dictionary (can be nested) nested_key (str): used for keeping track of nested keys for easy replaces later on ...
76f8857bf5a17e51f773ff6878b8ac807d4f9d47
653,618
def factors_list(n): """Return a list containing all the numbers that divide `n` evenly, except for the number itself. Make sure the list is in ascending order. >>> factors_list(6) [1, 2, 3] >>> factors_list(8) [1, 2, 4] >>> factors_list(28) [1, 2, 4, 7, 14] """ all_factors ...
1d2dd96f62399c714f5b61be12aaad2ea891b5ea
653,619
def struct_calcsize(formatstring): """ <Purpose> Given a formatstring, indicates the correct packed string size. <Arguments> formatstring: The format string (See the python docs). Caveat, if integer, etc. types are used they *must* contain an endianness character <...
87fc2f6811857609120cadd7ab3973a3981a4359
653,621
from bs4 import BeautifulSoup def create_soup(url): """ Create soup object from url """ try: html_report_part1 = open(url,'r') soup = BeautifulSoup( html_report_part1, "html.parser") return soup except Exception as e: print("[ERROR] Error occurred in requesting html...
29d9a23c9edde02484c2eee7adef77372ccaa00f
653,622
def to_list(dataseq): """Converts a ``ctypes`` array to a list.""" return list(dataseq)
3a4a7ce1a8e987a7c3ae69e6b0e8b32a077cd6f3
653,623
def write(content, path): """ Write string to utf-8 pure text file """ with open(path, "wb") as f: return f.write(content.encode("utf-8"))
22205d076479ddde192573450b6cf7b74a6be231
653,624
def _append_if_error(errors, sentence_id, test, explanation, token=None): """ If a test fails, append an error/warning dictionary to errors. Args: errors: a list of errors sentence_id: ID of the sentence this applies to test: boolean from a checked expression explanation: us...
78476118ddb073aefc86c4e926b66b9f91e252ec
653,625
def get_url_path(url): """Return a list of all actual elements of a url, safely ignoring double-slashes (//) """ return filter(lambda x: x != '', url.split('/'))
90f7558f974253f326732d6b4536ad2b3b107748
653,626
def __check_if_required_data_are_missing(data, error_line): """ Check if required data for this dataset are missing. Rules checked in this function: - Check if the invoice's number isn't missing. - Check if the invoice's date isn't missing. - Check if the invoice's client number isn't m...
a5248596dce024972bf5b461de4a65cd15a3afcd
653,627
def landmarks_json(name, infos="", normalized="NOT"): """Return a json object for the landmarks saving. Param: name, string. Name of the dataset. Param: infos, string. Some information on the set. Param: normalized, string. Tell If the points were normalized & which way. """ return { ...
5b0914935221231c1295eb2a8637fecb6fff25d6
653,628
def textblock(text, indent=0): """ Indent textblock by specified number of spaces. .. code-block:: pycon >>> block = 'one\ntwo' >>> print(textblock(block)) one two >>> print(textblock(block), 4) one two """ if indent: return ('\n' + ' ' * indent).join(...
0364b199b7934f8ec79ffe3d93693a0076706cd3
653,629
def desnake(text): """Turns underscores into spaces""" return text.strip().replace("_", " ")
fb3f5aa34a5630beffb93b8f14f9f0ca3bc96d7e
653,630
def code_to_symbol(code): """ 生成symbol代码标志 :param code: 数字 :return: str,股票代码 """ if isinstance(code, int): code = str(code) if len(str(code)) != 6 : return '%s.SZ'%((6-len(code)) * '0' + code) else: return '%s.SH'%code if code[:1] in ['5', '6', '9'] else '%s....
592d972e147e7854e0a9057db51ed6a7c677fa8c
653,631
def g2N(T): """ Converting gram to Newton """ return [0.00980665 * i for i in T]
648ff44af335d762fa083e1ba1bb62f1474f60a4
653,632
from typing import Dict from typing import Any def get_syntax(selected: Dict[str, Any], cmd: str) -> str: """Returns the syntax for a given command Parameters ---------- selected : Dict[str, Any] The command object cmd : str The command that was attempted Returns --------...
4de2bf50dc3b12a7f20ebbf3e6d8cf8ba1c75d2f
653,633
def _handleResponse(results, assure_address=True): """Process the results from a Google Maps API callself. Heuristically (by visual inspection), approximate addresses tend to resolve better to buildings than geographic centers. So if we are willing to relax address constraints, then filter on that typ...
e5bfc79f2799ef59c3a2213c0a894c31466f9cbf
653,634
import os import json def prepare_for_word2vec(save_file): """ 拆分成sentence_file 和user_dict 用于训练词向量 :param save_file: :return: sentence_file, user_dict """ sentence_file = os.path.join(os.path.dirname(save_file), "sentence_file.txt") user_dict = os.path.join(os.path.dirname(save_file), "use...
dd20112b0b29417c51d470e4647caa24f0165491
653,635
def predict_model_gen(session, style_dataset, sample_count): """Create a generator function that emits style images. Args: session: tf.Session, the session that contains subgraph to load the traning dataset style_dataset: tf.data.Dataset that contains training style images. sample_count: int, num...
a781a4f625a961e725ef108d5a8a49799da6ad23
653,636
def _get_remaining_columns( columns, metadata, nrows, ncols, col_limits, families, weights, family_counts, random_state, ): """Sample all remaining columns for the current individual. If ``col_limits`` has a tuple upper limit then sample all remaining columns for the indi...
e07077703bd01b7789a5249166b48ff714dc8e53
653,637
import stat import os def Isdir(path): """ Return whether the supplied path represents a directory """ return stat.S_ISDIR(os.stat(path)[0])
aac4a8dd8b10959f11f83bceccb510699304671c
653,638
def binary_search(array, elem, first, last): """ Search for an element in an array using binary search :param array: array to look for element :param elem: the lement to look for :param first: the index of the first position in the array :param last: the index of the last position in the array ...
8af4b1cc35dac36f7176c039c37318bf7b54b6e6
653,639
def string_time_from_ms(time_in_ms: int, hours: bool = False) -> str: """ Convert timestamp in millisecond in a string with the format mm:ss.xxx If hours is true the format will be hh:mm:ss.xx """ # if no time time_in_ms is equal to the maximum value of a 32bit int if time_in_ms == 2147483647 o...
aabcaf1e5e2038f28fb529ee1f83539c8e47b161
653,640
def format_timedelta(timedelta): """Formats a timedelta object to a string by throwing off the microsecond part from the standard timedelta string representation. """ whole_repr = str(timedelta) + '.' return whole_repr[:whole_repr.find('.')]
8c71eb5dc7fbbed65eaece1e84351c805011e9d0
653,641
from typing import List import math def calculate_raster_coordinate(longitude: float, latitude: float, origin: List[int], pixel: List[int]): """ From a given longitude and latitude, calculate the raster coordinate corresponding to the top left point of the grid surrounding the given geographic coordinate. ...
7a9f809121afd375fec3628f69a4d830d9f7674a
653,643
def escape(string): """Escape strings to be SQL safe""" if '"' in string: raise Exception("Can't escape identifier {} because it contains a backtick" .format(string)) return '"{}"'.format(string)
054b3b2908d10f82be41bfaa2e587d4e800dea84
653,644
def load_imagenet1k_label_darknet(): """ Function to read the ImageNet label file. Used for testing the pre-trained model. dataset (str): name of data set. 'imagenet', 'cifar' """ imagenet_label_dict = {} file_path = '../data/imageNetLabel.txt' with open(file_path, 'r') as ...
f90dbbd5104707404f8565ad0b7d4b81a5d16d35
653,646
def decode_fourcc(cc): """ Turns the float into a four letter codec string. Taken from here: https://stackoverflow.com/a/49138893/4698227 :param cc: the codec as float :type cc: float :return: the codec string :rtype: str """ return "".join([chr((int(cc) >> 8 * i) & 0xFF) for i i...
306d373f8a1666bf5be3232a0f61f0ecbe0f7136
653,647
def _region_to_coords(region): """Split GATK region specification (chr1:1-10) into a tuple of chrom, start, end """ chrom, coords = region.split(":") start, end = coords.split("-") return (chrom, int(start), int(end))
5ffb2c0c12541ffe31e648b043b18301969e09a8
653,648
def _doc_from_base(base_doc): """ """ return base_doc.__doc__.replace( 'Abstract', 'CUBA LIF' ).replace( 'neuron parameter', 'CUBA LIF neuron parameter' ).replace( 'This should never be instantiated on its own.', 'The block is 8 bit quantization ready.' )
72e3ae88559c8a2fc34746e131ca5f4957ef2e16
653,650
def edges_iter(G,nbunch=None): """Return iterator over edges adjacent to nodes in nbunch. Return all edges if nbunch is unspecified or nbunch=None. For digraphs, edges=out_edges """ return G.edges_iter(nbunch)
147c2b1e105453fdabf96a2849b738b5d49b8065
653,651
def compute_gradient(y, tx, w): """Compute the gradient.""" e = y - (tx).dot(w) N = len(e) gradient = -1 / N * (tx.T).dot(e) return gradient
acd990f510ac4efbee980bed55535d0837a68aa9
653,652
def compress_amount(n): """\ Compress 64-bit integer values, preferring a smaller size for whole numbers (base-10), so as to achieve run-length encoding gains on real- world data. The basic algorithm: * If the amount is 0, return 0 * Divide the amount (in base units) evenly by the larges...
e2ea91ebe137edd03c7433d0c49189eb89ed0b62
653,653
def scale_image(image, scale): """ This function... :param image: :param scale: :return: """ return image * scale
5bc429f9cd8ae7a0fcbcc6fd057eba9bf8309884
653,654
import re def get_dotted_table(table_lines): """Get table data. Args: table_lines(list): list of table rows Returns: list[list]: table_list - list of lists with row names and values """ table_list = [] for line in table_lines: if "...." in line: table_l...
8ae802d361a9afb36ba9d07f793670d94864e02e
653,655
import copy def get_topic_node_kwargs_data(node_data): """ Returns all keywords data other than source_id, title, and license. """ node_data = copy.deepcopy(node_data) del node_data['source_id'] del node_data['title'] # the following attributes will appear in `to_dict` method, but we don't...
650dc01acbae9deb14bfba9cd02304f1e984b40f
653,656
def get_input(prompt="", choices=None): """Waits for user to give answer from choices :param choices: List of choices to verify answer against :param prompt: Prompt to pass to input :rtype: String (lowercase) """ while True: answer = input(prompt).lower() if not isinstance(choic...
ad54b39741692868ab17c78950cfd874f26c5372
653,657
def cmd_exists(cmds_list, cmd): """Check if given command is in list of available commands @param cmds_list: see L{RTorrent._rpc_methods} @type cmds_list: list @param cmd: name of command to be checked @type cmd: str @return: bool """ return(cmd in cmds_list)
66988e710c83f6d3b31baa7fc373eb1b4077e1ff
653,658
import argparse def parse_argument(args): """parse user arguments""" parser = argparse.ArgumentParser(description="Execution Information") # Add arguments parser.add_argument( "--mode", dest="mode", type=str, default="train", choices=["train", "validation", "te...
b33fcb7247036382794d6c6e83ff46a0c3812731
653,659
def valid_binary(): """ magic=0xA1B2C3D4 version=2, type=price, size=16 """ return bytes([212, 195, 178, 161, 2, 0, 0, 0, 3, 0, 0, 0, 16, 0, 0, 0])
b5a94730aa037a62dbe5648ceadf813995d605f0
653,660
def transform_string(string): """Transform the string, which can contains the escape sequences and replace them for the relevant printable chars Arguments: string(string): string to transformation Return: string: the string without escape sequences """ i = 0 while i < len...
36bd9fcdb28579c196797d77369079bbee32c7a7
653,661
def map_quadrant(d): """ Map to the first and forth quadrant only. ... not sure, let's disable this mapping for now. """ return d if 90 < d <= 180: d2 = d - 180 elif d < -90: d2 = d + 180 else: d2 = d return d2
5b0e355292aa930673c24686458a47594d263f5d
653,662
def _ConditionHelpText(intro): """Get the help text for --condition.""" help_text = """ {intro} *expression*::: (Required) Expression of the condition which evaluates to True or False. This uses a subset of Common Expression Language syntax. *title*::: (Required) Title for the expression, i.e. a short string desc...
3899206fc5bb60c6dec9bc0fc58dcce80cb0799b
653,663
def configsection(config, section): """ gets the list of keys in a section Input: - config - section Output: - list of keys in the section """ try: ret = config.options(section) except: ret = [] return ret
6850cc0478242364f98864190daaa34704c39569
653,664
def _py2vim_scalar(value, null, true, false): """Return the given Python scalar translated to a Vim value. None, True, and False are returned as the (Vim) sentinel values 'null', 'true', and 'false', respectively; anything else is returned untouched. """ if value is None: return null if...
3fff2543663b695d39e1c56bd728ee4f3a47b0d4
653,666
def Y_i(i,A,X): """ Calculate band `i` of the coordinate rotation described in equation 8 of Lyzenga 1978. Parameters ---------- i : int The band number of `Y` to calculate. A : np.array The coordinate system rotation parameters calculated by the method `Aij` and des...
c0b62a5bb36ecfc86db12e4cb35a03d425e8d524
653,667
def degree_max_repetition(recpat_bag:list): """ Computes the degree of maximal repetition from a bag of recurring patterns -- a list of ngram tuples. """ return max([len(recpat) for recpat in recpat_bag])
dc5f20123eb56957284a69487b80e37abecdcd87
653,668
def pathfinder_auxiliary(row, col, M): """ Find the maximum path from the longest path's location @param row The row index in the matrix of where to find the longest path @param col The column index in the matrix of where to find the longest path to @param M The Matrix,...
9c1d590176489d63badc876e24b2fd09a7cd7c58
653,669
import os def ensure_path(folder_path): """ Make sure given folder path exists and return given path. Raises an exception if path does not exists, cannot be created or is not a folder. """ if not os.path.exists(folder_path): os.makedirs(folder_path, exist_ok=True) if not os.path.isdir(...
e21d193077f672ed27a157f2a3ccc770f8955bed
653,670
def a2hex(s): """Converts strin to hex representation: ff:00:ff:00 ...""" return ':'.join(x.encode('hex') for x in s)
3e151ab45675950f58d877364c4151ece19ec1a5
653,671
def get_global_sge_script(pythonPathsList, binPathsList, customEnvironment={}): """This is a wrapper script for running commands on an SGE cluster so that all the python modules and commands are pathed properly""" custEnvString = "" for key, value in list(customEnvironment.items()): custEnvString +...
284261c4dddae970b80a9ba12aeb0ff6525543e2
653,673
def near_field_shift(foclenwat, patlenwat, acovelwat, acovelmet): """ :param foclenwat: Fw = focal length in water :param patlenwat: Xw = path length in water :param acovelwat: Cw = acoustic velocity in water :param acovelmet: Cm = acoustic velocity in metal :return: Fv = new (virtual) focal len...
2ce21ad217bea4b3e50b0ae2d545acfec3d7e0f7
653,674
import torch def parse_hex(s): """ Hex to tuple """ s = s.lstrip('#') if len(s) == 3: s = s[0] + s[0] + s[1] + s[1] + s[2] + s[2] rgb = tuple(int(s[i:i+2], 16) for i in (0, 2, 4)) # sRGB to RGB # return torch.pow(torch.tensor([rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0]...
94a6fcc1fb1c3b8ae26307ae31de5dc1c0fc5d75
653,675
def is_valid_cog(cog): """Validates course over ground Arguments --------- cog : float Course over ground Returns ------- True if course over ground is greater than zero and less than 360 degrees """ return cog >= 0 and cog < 360
a2aadeb235aa6ab69e3ad6673288703fbce049dc
653,676
def IsGlobalTargetGrpcProxiesRef(target_grpc_proxy_ref): """Returns True if the target gRPC proxy reference is global.""" return target_grpc_proxy_ref.Collection() == 'compute.targetGrpcProxies'
20ea7d0baf818a2435506a7e0a23f7c1a0921f36
653,677
import sys def leitura(): """Lê um arquivo e o transforma em uma lista de dicionários. O arquivo de entrada deve seguir o formado: <usuário>:x:<UID>:<GID>:<Nome do usuário>:<home>:<shell>  Desta maneira transformando o arquivo de texto em uma lista com o usuário, UID e Nome do usuário de maneira ...
b5bcada377f4ca9dfc2b3043f5aaddeaaceb9081
653,678
import time import argparse def parse_time_arg(s): """ Parse a time stamp in the "year-month-day hour-minute" format. """ try: return time.strptime(s, "%Y-%m-%d %H:%M") except ValueError as e: raise argparse.ArgumentTypeError(e)
cbf60ff980286a23fbf09113f0f6bfbd800a17d6
653,679
def divide(num, den): """ Divide num by den in a template, returns 'NaN' if denominator is 0. """ return (float(num) / float(den)) if float(den)!=0 else 'NaN'
1c5d8c797a4d2492657f25d8c72b9d060a56db51
653,680
def _get_all_objects(objs): """ Helper function to get all objects of a 'Network' along with their corresponding ``contained_objects``. Parameters ---------- objs : Iterable List or set of objects Returns ------- all_objects : set A set of all Network's objects and ...
df555ffb632bfef1e8aa70fae5588bc311ef5faa
653,681
def is_empty(df): """Tests if a pd.DataFrame is empty or not""" return len(df.index) == 0
fd204f0824a70cbd0388d02cbaffa49514403ee8
653,683
def gen_names_for_range(N,prefix='',start=1): """generates a range of IDS with leading zeros so sorting will be ok""" n_leading_zeros= len(str(N)) format_int=prefix+'{:0'+str(n_leading_zeros)+'d}' return [format_int.format(i) for i in range(start,N+start)]
f146550e3c5a2ffc051a8edf8d364657a7677d8f
653,684
def cap_text(text): """ Input a String Output the capitalized String """ return text.title()
bff9a135ab71025ae1670a57a3a139c8d03a029d
653,685
import os def splitfilename(filename): """ splits file name into parent directory, name and extension """ path, filename = os.path.split(filename) name, ext = os.path.splitext(filename) return path, name, ext
30f99dbdf2bacd28f4d54c5cfc72e3e2bf67fe46
653,686
def correctDrumLoop(drumLoop, timeOfDance): """ makes the background drum loop for the entirety of the dance :param drumLoop: an AudioSegment of the selected background drum loop :return: an AduioSegment of the selected background drum loop, corrected in its time lenght """ timeOfDanceSeconds = ...
735e9e76f224981d67fa0f291ae47b8a8815a54f
653,687
def is_launch_test_mark_valid(item): """ Return `True` if the item is a launch test. If not, a warning and a skip mark will be added to the item. """ kwargs = item.get_closest_marker('launch').kwargs return 'fixture' in kwargs and kwargs['fixture'] is not None
3ca5e959948c8f17c3edab119d8d76e2298170d1
653,688
import requests def checkCurrentVersion(): """ ugly! """ global __version__ link = "https://raw.githubusercontent.com/amerand/PMOIRED/master/pmoired/__init__.py" f = requests.get(link, verify=False, timeout=10) lines = f.text.split('\n') lines = list(filter(lambda x: x.replace(' ', '')...
6aea27f3de28d6fcc77101e7d6d0780a2a932d66
653,689
def helper_split(split_string : str, easy : bool = True): """ A helper method to universalize the splitting logic used in multiple blocks and adapters. Please use this wherever a verb needs content to be chopped at | , or ~! >>> helper_split("this, should|work") ["this, shou...
4fcebbcd115e56b975ba6298cbfc46a5443dfc9c
653,690
import ast def convert_struct(str_struct=None): """convert the string argument to it's proper type Args: str_struct (str, optional): string to be evaluated. Defaults to None. Returns: string struct as it's actuat evaluated type """ return ast.literal_eval(str_struct) if str_struc...
854563babbfe86818c3c04d27f2ea95298ae4815
653,692
def bytes2human(n: int) -> str: """Convert `n` bytes into a human readable string. >>> bytes2human(10000) '9.8K' >>> bytes2human(100001221) '95.4M' """ # http://code.activestate.com/recipes/578019 symbols = ("K", "M", "G", "T", "P", "E", "Z", "Y") prefix = {} for i, s in enumera...
6929ad5c3fb865a32e733ba6c0d9fdfed0493efc
653,693
def frequency_count(text_data): """ count the frequency of each word in data :param text_data: list[string] :return: freq_cnt => {word -> freq} """ text_data = list(map(lambda x: x.split(), text_data)) # generate the vocabulary total_word_list = [] for line in text_data: tota...
3bfd7998e1017497257bf2b920108b3b873e1891
653,694
import torch def extend_batch(batch, dataloader, batch_size): """ If the batch size is less than batch_size, extends it with data from the dataloader until it reaches the required size. Here batch is a tensor. Returns the extended batch. """ while batch.shape[0] != batch_size: data...
cbc87d52116c0b4075c3fee3abe7d528d32be56d
653,695
import logging import sys def default_logger(): """A logger used to output seed information to nosetests logs.""" logger = logging.getLogger(__name__) # getLogger() lookups will return the same logger, but only add the handler once. if not len(logger.handlers): handler = logging.StreamHandler(...
0b0ce339787216054a7a0aed8c569f7d63b2f35d
653,696
def queue_to_list(queue): """Convert a Queue to a list.""" result = [] while queue.qsize() != 0: result.append(queue.get()) return result
ef40ef32373b81689925dd145842b44033c107e5
653,697
def get_duration(oid_list, oid): """ 获得视频时长 """ return oid_list[oid][1]
39e3c2e86622d3e69996cf4938507c4633c16043
653,698
import os import hashlib def samefile(sourcefile, destfile): """ """ if not os.path.exists(destfile): return False if not os.path.exists(sourcefile): return False inhash = hashlib.md5() inhash.update(open(sourcefile).read().encode('utf-8')) outhash = hashlib.md5() out...
f30de86b72afd136d031be1e688e2aeb04f2256a
653,699
def get_value(json, attr): """Get the value from the json.""" if attr in json: return json[attr][0] return ""
df795daca80a4499b58270cd1a5b48ae3e73d5ac
653,702
def run_async(coro): """Execute a coroutine until it's done.""" values = [] result = None while True: try: values.append(coro.send(None)) except StopIteration as ex: result = ex.args[0] if ex.args else None break return values, result
f77d62546958dde04c34d788b89ef0a1f7d11e25
653,703
def get_core_genomes(groupsDict, catDict, number, duplicates): """ Gets core genome for each category """ coreDict = {} allDict = {} # holds genes present in category, but not shared in all for cat in catDict: coreDict[cat] = set() allDict[cat] = set() for group in groupsDict: ...
a2a4edfa93f8714cbc1b9d2bd72cbcf27e6f9960
653,704
def to_pdb_line(atom_id, atom_type, amino_type, chain_ID, residue_id, coords): """Puts all the required info into a .pdb format """ x, y, z = coords insertion = "$" if type(residue_id) is str: if residue_id[-1].isalpha(): insertion = residue_id[-1] residue_id = int(re...
c7b4a465ba32b7a6294ba020055ad99b06457802
653,706
def taxonomy(resp_json, return_obj, options): """Extract specific data on taxa from the subquery.""" for rec in resp_json: data = dict() data.update(db='sead') # Determine the taxon rank and fill in the appropriate fields if "species" in rec: ...
c0bf677450b48fd24c6bc104b3a95b8130d04aad
653,707
def get_log_prob_unigram(masked_token_ids, token_ids, mask_idx, lm): """ Given a sequence of token ids, with one masked token, return the log probability of the masked token. """ model = lm["model"] tokenizer = lm["tokenizer"] log_softmax = lm["log_softmax"] mask_token = lm["mask_token"...
d68dbf996966584c16bbf8ebc13c5c4af079c270
653,708
def num_region_obs(count_arr, lon_idxs, lat_idxs): """ Given lon/lat indices and array of GOSAT counts, determine number of observations in the region as defined by the indices. Parameters: count_arr (np arr) : array of counts (Mx72x46), M num months lon_idxs (np arr) : array of longit...
2ca841b003e81637e87f497b628ecea805092fed
653,709
def get_uid_from_action_name(action_name, uid_string=None): """ Extract id from action name by splitting at "__", because this marks the start of id in action name. If uid string is in action name, remove it :param action_name: full action name of processor (e.g. "{action_type}_{aName}_{id}[uid_string}]...
01f28bf98ecc390bda02e1a2736c32192abbacf9
653,711
def add_bubble(fig, **kwargs): """Creates shape ontop of the figure""" return fig.add_shape( type="circle", line_color="white", fillcolor="pink", opacity=0.6, xref='paper', yref='paper', x0=0.5, y0=0.6)
6fc2e6ed0cec79d1976be0af44e504ffef262711
653,712
def metaclass_name_for_class(classname): """Return the name of the C++ metaclass for the given class.""" if '::' in classname: return None return classname + '::MetaClass'
dda8195475b34aa6dc51f4ce5b4dbe0bd01398ea
653,713
def CountScores(outfile, t1, t2, graph, separator="|", cds1={}, cds2={}, options={}): """count scores between t1 and t2 in graph. return lists of scores between t1 and within clusters and the number of not found vertices and links """ between_scores ...
6e641b9a76f91d56b4e4a584e6a7fbb6a617877b
653,714
from pathlib import Path def file_exists( path, exception=ValueError, emsg="`path` is not a file or does not exist", ): """ Assert if file exist. Parameters ---------- path : str or pathlib.Path The file path. exception : Exception The Exceptio...
a9b8c3f633ea9e0ffc906064042ade2a4aa0a1e2
653,715
def _deserialize(response_entity_type): """ Auto-deserializes the response from any decorated client method call that has a 'format' key in it's 'params' dictionary argument, where 'format' value is either 'json' or 'xml'. Deserializes the response into response_entity_type domain object respo...
4282214874a419b8710876492bf2b48d85071dc0
653,716
def make_insert(mycursor, loc, start_date, due_date, size, url, price, lat, lon, maanden): """ Insert data into database table of mysql """ call = "INSERT INTO kamernet (loc, start_date, due_date, size, url, price, lat, lon, tijd)" call += " VALUES ('{}','{}','{}',{},'{}','{}', {}, {}, {});".format(...
d9f7277dc5b2268656793a96a22872aaba822e46
653,717
import os def iodir(datadir): """IO data directory.""" return os.path.join(datadir, 'io')
5008f9ab43c9a56229913a01ebf49db8ab2c570e
653,718
import base64 def b64e(b): """Base64 encode some bytes. Uses the url-safe - and _ characters, and doesn't pad with = characters.""" return base64.urlsafe_b64encode(b).rstrip(b"=")
3c2ce4e5658d2b3ec1f0b0c46464f5baaffbe20c
653,719
import torch def tensor_abs(inputs): """Apply abs function.""" return torch.abs(inputs)
f7c5e0c0a4fa35ade7bae98ceb7236a1f7ccce45
653,720
from typing import Dict from typing import Any def parse_camera_id(metadata: Dict[str, Any]): """ Determine the camera the photograph was taken with from its EXIF data. :param metadata: EXIF data to find the camera from. :returns: The camera id, if it could be determined. If not, returns ``'Unknown'``. """ f...
1468bac8b6e69d73a021c09c97730e9ae3d25f61
653,722
import optparse import sys def options_parse(): """ Command line option parser for spherically_project.py """ parser = optparse.OptionParser(version='$Id: rewrite_mc_surface,v 1.1 2020/06/23 15:42:08 henschell $', usage='Function to load and resafe surface under a gi...
c0ac24f62a1af8073c2eb46af654a2e8c1f575c8
653,723
def key2freq(n: int) -> float: """ Gives the frequency for a given piano key. Args: n: The piano key index Returns: The Frequency """ return 440 * 2 ** ((n - 49) / 12)
aab19e8d4fe592249daef7302895af200ab11486
653,724