content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def convert_shelves(element): """Get the names of all the shelves that hold this book.""" # The shelves for a review are returned in the following format: # # <shelves> # <shelf name="read" exclusive="true"/> # <shelf name="fiction" exclusive="false" review_shelf_id="1234"/> # ...
0afb1c0c0f7ff51847584c88d47ded20acfaa3e4
663,749
def poly(x1, x2, degree=3, gamma=1., r=0.): """ polynomial kernel function Parameters ------------ x1 : numpy array, (..., n) the first input feature vector x2 : numpy array, (..., n) the second input feature vector degree : positive double, default: 3 degree of ...
681306c6b6e55019d0103f981a8e478ddf14d4c0
663,750
def element_with_unique_name(self,name): """Returns the element with unique_name This mehtod extends the powerfactor.Application class. It returns the element with the given unique_name. Args: name: The unique name of the element e.g. 'Netz\\Last.ElmLod' Returns: A powerfactory.Da...
7513eded489913fbddbc1083df9fd017f5f2b94d
663,751
def _step_to_value(step, num_steps, values): """Map step in performance to desired control signal value.""" num_segments = len(values) index = min(step * num_segments // num_steps, num_segments - 1) return values[index]
af5c4731827ceca84b56917812d43ff9da44a42d
663,754
import functools def qutip_callback(func, **kwargs): """Convert `func` into the correct form of a QuTiP time-dependent control QuTiP requires that "callback" functions that are used to express time-dependent controls take a parameter `t` and `args`. This function takes a function `func` that takes `t...
8d20a3fc75bd673a3b5576e2d147162d13ca19ba
663,755
def isNum(s) -> bool: """ Checks if its a number >>> isNum("1") True >>> isNum("-1.2") True >>> isNum("1/2") True >>> isNum("3.9/2") True >>> isNum("3.9/2.8") True >>> isNum("jazz hands///...") False """ if "/" in str(s): s = s.replace("/", "", 1) ...
ee16745f54346b7629e6dcd775690b634270d3bd
663,762
def frames_to_ms(frames: int, fps: float) -> int: """ Convert frame-based duration to milliseconds. Arguments: frames: Number of frames (should be int). fps: Framerate (must be a positive number, eg. 23.976). Returns: Number of milliseconds (rounded to int). ...
04a9c37cc2b6514b432fa773c2215a716e418209
663,771
def mapLists(first, second): """ Make a dictionary from two lists with elements of the first as the keys and second as values. If there are more elements in the first list, they are assigned None values and if there are more in the second list, they're dropped. """ index = 0 dict = {} # Read through every index ...
928b31e0cf636389124f8ba6b4910b9a51539204
663,774
def format_schema_tf(schema): """Format schema for an Athena table for terraform. Args: schema (dict): Equivalent Athena schema used for generating create table statement Returns: formatted_schema (list(tuple)) """ # Construct the main Athena Schema formated_schema = [] for...
ba808b145c16f2b13419f7dcdd0c55901da4ec8f
663,776
def add_entities(kb, desc_dict, nlp): """ Adds company entities to KB :param kb: the empty Knowledge Base :param desc_dict: dict with KvK-numbers and SBI-code descriptions of companies :param nlp: the nlp object to retrieve vector of SBI-code description :return: the KB with companies entities ...
58d1d700fb6caca6be159f99ee4a4ee619fd5ec0
663,778
import json def output_json(output): """Return JSON formated string.""" return json.dumps(output, sort_keys=True, indent=2)
32424662588c0353409b47f6a4dac6d9df6ad55b
663,780
import json def handle_event(ext, body): """Handle an event from the queue. :param ext: The extension that's handling this event. :param body: The body of the event. :return: The result of the handler. """ payload = json.loads(body) return ext.obj.event(author_id=payload['author_id'] or N...
36b193d7c04545b284311cf3ad0c55f2f3633c3c
663,781
def title_case(inp_str): """ Transforms the input string to start each word from capital letter Parameters ---------- inp : string string to be changed Returns ------- result : string a string were each word starts from the capital letter """ if isinstance(inp_str, str): ...
82e4da51b818073af84bc4534ca5b604e990cf0d
663,782
def batch_split(batch_size, max_num): """Split into equal parts of {batch_size} as well as the tail""" if batch_size > max_num: print("Fix the batch size to maximum number.") batch_size = max_num max_range = list(range(max_num)) num_splits = max_num // batch_size num_splits = ( ...
5a94908adfba9ba3e0c82598c3be2b739ec99f2c
663,783
def seq_matches(seq1, seq2): """ Return True if two sequences of numbers match with a tolerance of 0.001 """ if len(seq1) != len(seq2): return False for i in range(len(seq1)): if abs(seq1[i] - seq2[i]) > 1e-3: return False return True
977cc2194380dcd89d2e75f3491691e50da25a12
663,790
def is_far_from_group(pt, lst_pts, d2): """ Tells if a point is far from a group of points, distance greater than d2 (distance squared) :param pt: point of interest :param lst_pts: list of points :param d2: minimum distance squarred :return: True If the point is far from all others. """ ...
6836792aa32c47833a9839a85306e7d249c6a160
663,791
import torch def get_board_tensor(board_str, black_moves): """ function to move from FEN representation to 12x8x8 tensor Note: The rows and cols in the tensor correspond to ranks and files in the same order, i.e. first row is Rank 1, first col is File A. Also, the color to move next occupi...
bf19b91e4d7d952c6f3a958607436522ca1db872
663,792
import re def unsub_emails(unsub_list, email_list): """ Takes the list of plex user email address and filters out the members of the unsubscribe list. """ excludes = re.split(r",|,\s", unsub_list) email_list = list(set(email_list)^set(excludes)) return email_list
5acdc6472fad2b75244234c646612d2b0f38c727
663,793
import re def slice_marc_shorthand(string: str) -> tuple: """ Splits a string and gives a tuple of two elements containing the Main Number and the subfield of a marc shorthand Calls a regex check to make sure the format is corret :param str string: a string describing a marc shorthand, should look lik...
a80e762fe0c9a6cb3111bb491d9215f75c282c5f
663,794
import socket def createTestSocket(test, addressFamily, socketType): """ Create a socket for the duration of the given test. @param test: the test to add cleanup to. @param addressFamily: an C{AF_*} constant @param socketType: a C{SOCK_*} constant. @return: a socket object. """ skt...
3b8e9d63e29151adb1bd2d2c4e48d07cb1bd4e6a
663,796
from pathlib import Path def get_texture_type(image_path): """ Gets the PBR texture type from the filename. :param image_path: Path to the image from which to extract pbr type :return: """ filename = Path(image_path) texture_type = filename.stem.split('_')[-1] return texture_type
efe68b7e213200c5cfc40cf10ba2ea4c2b7903dc
663,799
def keyGen(attributes, data): """ Traverses the data and returns the key generated based on the given attributes. **Parameters**: attributes : list A list of attributes which define the key. data : dict The data for which the key has to be generated for. **Retur...
2fee66f6fef0266cbcea7c2d66c67a45d53d21ae
663,800
def ancestors(node): """Return a list of ancestors, starting with the direct parent and ending with the top-level (root) parent.""" result = [] parent = node.getParent() while parent is not None: result.append(parent) parent = parent.getParent() return result
2a5ad411ce0f36bc94d5b8437da0ccbc033de5cf
663,803
def calcMitGuideScore(hitSum): """ Sguide defined on http://crispr.mit.edu/about Input is the sum of all off-target hit scores. Returns the specificity of the guide. """ score = 100 / (100+hitSum) score = int(round(score*100)) return score
8c9a40c506e6c6e6bf780b088005542a29e8c328
663,807
def timeout(timeout): """ Condition to be used on Timers. True after the given amount of time has elapsed since this decorator became active. """ def inner(timer, *args, **kwargs): return timer >= timeout return inner
d6cafdbdd94c100f73a927bdb0b31c9d787bc595
663,808
def check_resource_deleted(error_message): """Create a callable to verify that a resource is deleted. To be used with the :meth:`run` function. The callable will raise an :class:`AssertionError` if the chosen resource is shown as existing in the response given to the callable Args: error_m...
73071ec4be55117461b1dd9a57da2ba875bc28ac
663,809
def getCurvesListWithDifferentCurveName(originalCurveList, origCurve, newCurve): """ Takes in list of curves, curve name to be replaced, and curve name to replace with. Returns a list with the orginal and new curve names switched in the given curve list """ plentifulCurves_wDEPTH = originalCurveLis...
7e0f4af1d54e416b6b95e0ee30b82876a80320a1
663,812
from typing import Counter def number_of_contacts(records, direction=None, more=0): """ The number of contacts the user interacted with. Parameters ---------- direction : str, optional Filters the records by their direction: ``None`` for all records, ``'in'`` for incoming, and ``'...
06fb9e0ecce538a590eee4e204fd08fb5b187439
663,813
def format_summary(a): """a is a vector of (median, min, max, std).""" return "{0:<6.3g} {3:<6.3g} ({1:.3g} - {2:.3g})".format(*a)
3fdc96d9f704007dc745e2c470233fa7b51c8730
663,817
def get_available_directions(character: dict, columns: int, rows: int) -> list: """ Get the list of available directions. :param character: a dictionary :param columns: an integer :param rows: an integer :precondition: character must be a dictionary :precondition: columns >= 0 :precondi...
eec1f32edec917996138c8d5d6428819920b27d8
663,818
import binascii def crc32(string: str) -> str: """Return the standard CRC32 checksum as a hexidecimal string.""" return "%08X" % binascii.crc32(string.encode())
6cc3f534bddf02066f638f86e2404496efb345b3
663,819
def get_slots(intent_request): """ Fetch all the slots and their values from the current intent. """ return intent_request["currentIntent"]["slots"]
b8f140ea3c9473ff7507046f42ceaa770946a2b7
663,822
def rossler(x, y, z, a=0.2, b=0.2, c=5.7): """Compute next point in Rossler attractor.""" x_dot = -y - z y_dot = x + a*y z_dot = b + z*(x-c) return x_dot, y_dot, z_dot
82b9c71f264dee7d832c3f70f4155a8fb2117c19
663,823
def find_cntrs(boxes): """Get the centers of the list of boxes in the input. Parameters ---------- boxes : list The list of the boxes where each box is [x,y,width,height] where x,y is the coordinates of the top-left point Returns ------- list Centers of each...
accd05af1a4e9fdb05ea8a644c6933a69a45f9a7
663,827
def _is_bazel_external_file(f): """Returns True if the given file is a Bazel external file.""" return f.path.startswith('external/')
ed843d2937efc92ed84132686b8135476ba96b73
663,828
def get_formatted_name(first, middle, last): """Generate a neatly formatted full name""" full_name=f"{first} {middle} {last}" return full_name.title() """this version works for people with middle name but breaks for people with only first and last names"""
75291005b2ad0650e2e1aa4c828dfd2411e01f9b
663,829
import re from typing import OrderedDict def get_example_sections(example): """Parses a multipart example and returns them in a dictionary by type. Types will be by language to highlight, except the special "__doc__" section. The default section is "html". """ parts = re.split(r'<!-- (.*) -->', ...
a28ede469e82755528013a3b1cc08a56ed024577
663,834
import csv import operator def read_training_history(path, ordering=None): """Read training history from the specified CSV file. Args: path (str): Path to CSV file. ordering (str): Column name to order the entries with respect to or ``None`` if the entries should remain unordered....
7fb53ada411e08ff3723231311a639cb895d8cd6
663,836
def diff(a, b): """ Takes the difference of two numbers Arguments --------- a : int, float b : int, float Returns ------- d : float difference between a and b """ return a - b
c6b30403da67f1f1a27efc59243b5b5c46f90f20
663,839
def _cert_type_from_kwargs(**kwargs): """Return cert type string from kwargs values""" for k in ('admin', 'creator', 'initiator', 'platform'): try: if k in kwargs['user_type'] and kwargs['user_type'][k]: return k except LookupError: if k in kwargs and kwa...
c4f055eee201dcacd5590afb5b4f9f65edca3c9f
663,842
def readPhraseIndexFromFiles (filenames): """Takes a list of files; reads phrases from them, with one phrase per line, ignoring blank lines and lines starting with '#'. Returns a map from words to the list of phrases they are the first word of.""" phraseIndex = dict() for filename in filenames: ...
c2968c8d7613c501c7c6bd37ead7017ded57be09
663,845
def campaign_news_item_save_doc_template_values(url_root): """ Show documentation about campaignNewsItemSave """ required_query_parameter_list = [ { 'name': 'voter_device_id', 'value': 'string', # boolean, integer, long, string 'description': ...
4a44bf91bf2398aa69e20c767e9fe73ee939af29
663,847
def first_plus_last(num: int) -> int: """Sum first and last digits of an integer.""" as_string = str(num) return int(as_string[0]) + int(as_string[-1])
b9140d7c4a46d10d928d465445aa10953e458379
663,850
def extract_name(row): """ Helper function for comparing datasets, this extracts the name from the db name Args: row: row in the dataframe representing the db model Returns: name extracted from agency_name or np.nan """ return row['agency_name'][:row['agency_name']....
84d525d008cf35e4ee0b1347caf0909a67cad1e3
663,852
from typing import Dict def __construct_robot_message_subject(serial_number: str, uuid: str) -> Dict[str, str]: """Generates a robot subject for a plate event message. Arguments: serial_number {str} -- The robot serial number. uuid {str} -- The robot uuid. Returns: {Dict[str, str...
94c08e3b32608a62b7504b43f2faeac141ead6c6
663,854
def cap_text(text): """capitalize() upper cases the first letter of a string.""" return text.capitalize()
89266c34ee581ec31152fc480762a13df61b10c6
663,857
import re def get_level(line, indent) : """ Return the level of indentation of a given line """ level = 0 while line.startswith(indent) : line = line[len(indent):] level += 1 if re.match(r"^(\s+)", line) : raise Exception("Syntax Error") return level
3fbaf5f2c142af988d3ba341bcfa9d8a43c584d8
663,861
def construct_fasta_entry(host_id, sequence, description=None, wrap=None): """Returns a FASTA-formatted entry for the sequence. Parameters ---------- host_id : int Host ID of target host sequence : iterable If sequence is a list of single characters, the list will be joined ...
9cdb3118057b72e3b0e742540260d1bb2b72b61f
663,862
def get_triangular(n: int) -> int: """Get `n`-th triangular number Args: n: Index of triangular number Examples: >>> print(get_triangular(10)) 55 """ return n * (n + 1) // 2
e1151418e3328eb358a592af187240f6a2a09989
663,865
def sort_bl(p): """Sort a tuple that starts with a pair of antennas, and may have stuff after.""" if p[1] >= p[0]: return p return (p[1], p[0]) + p[2:]
d30582c7d05fd5ab151d3adf24c122f1199ad5a0
663,866
def round_down(x, n): # type: (int, int) -> int """Round down `x` to nearest `n`.""" return x // n * n
b60c94ddae5a852d5d0c750e574de151f045648c
663,867
import torch def normalize(tensor, min=None, max=None): """ Normalize the tensor values between [0-1] Parameters ---------- tensor : Tensor the input tensor min : int or float (optional) the value to be considered zero. If None, min(tensor) will be used instead (default is Non...
46f413ffc1aacde12ab6f8d95bba105fc58f86d3
663,868
import random import math def GetSample(gan_params): """Get one sample for each range specified in gan_params.""" ret = {} for param_name, param_info in sorted(gan_params.items()): if param_info.is_discrete: v = random.choice(param_info.range) else: assert isinstance(param_info.default, floa...
b623b6fdae3c17d3cad38bea70439fbb3fc4f71b
663,871
def tag_filter(tag_list, base_df): """Search with tags. Args: base_df (DataFrame): Search target. tag_list (list): List of search tag. Returns: (DataFrame): Searched DataFrame. """ result_df = base_df for tag in tag_list: mask = result_df["tag"].apply(lambda x:...
fe6a9f075d859167d3ec160b96c7f839db394154
663,872
import json def decode_predictions(preds, top=5): """Decode the prediction of an ImageNet model. # Arguments preds: Numpy tensor encoding a batch of predictions. top: integer, how many top-guesses to return. # Returns A list of lists of top class prediction tuples `(class...
0478877a61a7d5f36eae93e4e6590c2b0668a8ef
663,875
def get_num(x): """Grab all integers from string. Arguments: *x* (string) -- string containing integers Returns: *integer* -- created from string """ return int(''.join(ele for ele in x if ele.isdigit()))
102c07a64f18fa10696903c41ab9d661caccc9de
663,876
def reverse_complement(seq): """Return reverse complement of a dna sequence.""" bases_dict = { 'A': 'T', 'a': 't', 'C': 'G', 'g': 'c', 'G': 'C', 'c': 'g', 'T': 'A', 't': 'a'} return "".join([bases_dict[base] for base in reversed(seq)])
f64c2b5a003d6a36a1a615657efc4b1cbbf3c709
663,877
from typing import Set def config_files() -> Set[str]: """ Return a set of the names of all the PyTorch mypy config files. """ return { 'mypy.ini', 'mypy-strict.ini', }
a3073c3292fe0abbdf424c0661fba62375e508a8
663,879
import pipes def tokens_to_string(tokens): """ Build string from tokens with proper quoting. :param tokens: list of string tokens :return: space-separated string of tokens """ return ' '.join(map(pipes.quote, tokens))
aac25e891e8bc39bd18f159fdcd19a466d82f9f1
663,881
def unique_dot_keys(experiment_keys): """ Return the first run of each dot, given all experiments. """ result = list() for key in sorted(experiment_keys): if key[:2] not in map(lambda x: x[:2], result): result.append(key) return(result)
53ddc58e43eb628d49c1347937f1932345658f26
663,882
def _checkFileEndingGeneric(file_: str, ending: str) -> bool: """ generic function that checks if file_ ends with param 'ending' """ return file_.endswith(ending)
412716c9f8250076944881f82b6ede860dba7e38
663,883
def reformate_path(path): """On certain editors (e.g. Spyder on Windows) a copy-paste of the path from the explorer includes a 'file:///' attribute before the real path. This function removes this extra piece Args: path: original path Returns: Reformatted path """ _path = path....
a488402957e233454749a55b92a0f4ce0526ebe9
663,884
def initial_fixation_duration(interest_area, fixation_sequence): """ Given an interest area and fixation sequence, return the duration of the initial fixation on that interest area. """ for fixation in fixation_sequence.iter_without_discards(): if fixation in interest_area: retur...
3fef15047500b8be8175a28d838feb10cd571f80
663,886
def none_are_none(*args) -> bool: """ Return True if no args are None. """ return not any([arg is None for arg in args])
0264cf2abd4bb0fbcc4aff8f6f4a1c44512d844b
663,890
def get_word_lengths(s): """ Returns a list of integers representing the word lengths in string s. """ return [len(w) for w in s.split()]
54d6a646ddc27606cb9dd8324a614e5e7df00857
663,893
def doc_brief(brief): """format brief for doc-string""" return " {0}\n".format(brief)
24576b056014fe0712489361d61ae8409b1f09f2
663,894
def broadcast_rank(source, target): """Broadcasts source to match target's rank following Numpy semantics.""" return source.reshape((1,) * (target.ndim - source.ndim) + source.shape)
f4cf5a1e899599db06e5807fc17c08d1f68e2bd4
663,895
def longest_substring_with_k_distinct(s, k): """Find the length of the longest substr with less than or equal to k distinct characters. Time: O(n) Space: O(k) >>> longest_substring_with_k_distinct("araaci", 2) 4 >>> longest_substring_with_k_distinct("araaci", 1) 2 >>> longest_subs...
341e73fad56cfa9a22176c54baa6a3140ed96bb1
663,897
def sec2hms(seconds): """ return seconds as (hh,mm,ss)""" hr = int(seconds) mn = int((seconds*3600 - hr*3600)/60) sec = seconds*3600 - hr*3600 - mn*60 return [hr, mn, sec]
38cb365cd49d69c81e331c3ecfef41e4907400c0
663,905
from typing import Dict from typing import List import csv def read_temp_csv_data(filepath_temp: str) -> Dict[str, Dict[int, List[float]]]: """Return a mapping from the state to a mapping of the year to yearly data in the format [average temperature, precipitation, wildfire counts]. Currently, the values...
4342eb9b1ed392cd8ee94dfa400a194948fef3a4
663,909
def replay_args(parser, show_all_task_softmax=True): """This is a helper function of function :func:`parse_cmd_arguments` to add an argument group for options regarding Generative Replay. Args: parser (argparse.ArgumentParser): The argument parser to which the group should be added. ...
ecc69b700a0221a9be7400d203f6dab2a7745bdd
663,911
def get_trait_names(clinvar_json: dict) -> list: """ Given a dictionary for a ClinVar record parse the strings for the trait name of each trait in the record, prioritising trait names which are specified as being "Preferred". Return a list of there strings. :param clinvar_json: A dict object contai...
4728b182dc9fc5bfea9db440d279774f16f4eddd
663,912
def init_label_dict(num_classes): """ init label dict. this dict will be used to save TP,FP,FN :param num_classes: :return: label_dict: a dict. {label_index:(0,0,0)} """ label_dict={} for i in range(num_classes): label_dict[i]=(0,0,0) return label_dict
7681e02aecadfc05a81599a0f6cb0f95a92c7a62
663,915
def convert_string_AE2BE(string, AE_to_BE): """convert a text from American English to British English Parameters ---------- string: str text to convert Returns ------- str new text in British English """ string_new = " ".join([AE_to_BE[w] if w in AE_to_BE.keys() e...
b032b007ad59ef653733e01b3c7b43de5d2a956a
663,916
def order_dict(_dict: dict, reverse: bool=True) -> dict: """ Takes a dictionary and returns it ordered. :param _dict: :class:`dict` :param reverse: :class:`bool` :return: :class:`dict` """ temp_dict = {} unordered_list = [(k, v) for k, v in _dict.items()] ordered_list = sorted(unor...
5e32efefff3f70e86eec21470cc179ff95707897
663,917
import re def replace_string( text, old_string, new_string ): """ Check that `old_string` is in `text`, and replace it by `new_string` (`old_string` and `new_string` use regex syntax) """ # Check that the target line is present if re.findall(old_string, text) == []: raise RuntimeError(...
93811fe03ac720baab12b3bd0733a8b05cf6b3a0
663,918
def list_api_vs(client, resource_group_name, service_name): """Lists a collection of API Version Sets in the specified service instance.""" return client.api_version_set.list_by_service(resource_group_name, service_name)
c12a895195a0122afa53649c2cb351e118916a62
663,919
def startswith(text, starts): """Simple wrapper for str.startswith""" if isinstance(text, str): return text.startswith(starts) return False
3bfc1637fdc3fc4e2fdc40badafbecbc140991b1
663,921
def compare_acl(acl1, acl2): """ Compares two ACLs by comparing the role, action and allow setting for every ACE. :param acl1: First ACL :type acl1: dict with role, action as key and allow as value :param acl2: Second ACL :type acl2: dict with role, action as key and allow as value :return:...
4e38bb1a0dabe58401898a804bc5d3054861df97
663,923
def _reference_expect_copies(chrom, ploidy, is_sample_female, is_reference_male): """Determine the number copies of a chromosome expected and in reference. For sex chromosomes, these values may not be the same ploidy as the autosomes. The "reference" number is the chromosome's ploidy in the CNVkit refe...
115ab67a370bc640d39470be419053f4322b4f50
663,924
import math def score_feature_vector(feature_vector, probs, cnt_bins, restrict_features): """ For a feature vector, computes its log transformed likelihood ratio with respect to the model. That is, every feature value in the feature vector is evaluated and log of the likelihood ratio is added to the t...
d09078afef15dfc35470a73eb10e4a445cc8e781
663,931
def removekey(d, key): """This functions returns a copy of a dictionnary with a removed key Parameters: d (dict): dictionnary key: the key that must be deleted Returns: copy of dictionnary d without the key """ r = dict(d) del r[key] return r
45eeb1e56a38e065aeb2dba58acc098152ea0425
663,932
def get_dataset_info(dataset_type): """define dataset_name and its dataroot""" root = '' if dataset_type == 'LEVIR_CD': root = 'path-to-LEVIR_CD-dataroot' # add more dataset ... else: raise TypeError("not define the %s" % dataset_type) return root
d9fea426ba8b3277d774e1dee7fef3c132a3f5c3
663,936
def get_default(dct, key, default=None, fn=None): """Get a value from a dict and transform if not the default.""" value = dct.get(key, default) if fn is not None and value != default: return fn(value) return value
d65f2c578d3de4e2e917c32b342b580fbdfff817
663,937
import re def get_class_name(a_string): """Convert a name string to format: ThisIsAnUnusualName. Take a space delimited string, return a class name such as ThisIsAnUnusualName Here we use this function for instance name. Thus it allows to start with a number """ joint_name = a_string.title().repla...
f1f0e146cdd2f35029eef0ed3b2e944c89082f1f
663,939
def _get_num_contracts(contracts_list, param_name): """ Return the number of simple/default contracts. Simple contracts are the ones which raise a RuntimeError with message 'Argument `*[argument_name]*` is not valid' """ msg = "Argument `*[argument_name]*` is not valid" return sum( ...
4ef03e50d2d4c6fd1881c94dacd8e9db166d7d8a
663,940
def get_duplicate_indices(words): """Given a list of words, loop through the words and check for each word if it occurs more than once. If so return the index of its first ocurrence. For example in the following list 'is' and 'it' occurr more than once, and they are at indices 0 and 1 so you would ...
0ea94957d5ff8ae9cd7488ea9b4adcf33020ec2c
663,941
import time def utc_offset(time_struct=None): """ Returns the time offset from UTC accounting for DST Keyword Arguments: time_struct {time.struct_time} -- the struct time for which to return the UTC offset. If Non...
f7b52f3fd292ac773d107f8143ffc7ab8be57499
663,944
import requests from bs4 import BeautifulSoup def getBoxscoreURLsFromPlayer(playerId): """ Put in a player id and get all boxscores for that player. - can be updated to specify after which date. """ r = requests.get('https://www.pro-football-reference.com/players/'+ playerId[0] + '/' + p...
7c083e65f292211fe3389d78206e9a2ec6c309fc
663,946
def read_wien2k_G_vectors(filename): """ Read the Wien2K G-vectors and return the vectors - G1 - G2 - G3 In Wien2K the G-vectors are stored in a file with the extension .outputkgen, and are listed under G1 G2 G3 so we need to be looking for lines that start with that content. ...
4a8388a11cb992520c946b2b5b7468824767e9ba
663,947
def add2(matrix1,matrix2): """ Add corresponding numbers in 2D matrix """ combined = [] for row1,row2 in zip(matrix1,matrix2): tmp = [sum(column) for column in zip(row1,row2)] combined.append(tmp) return combined # Alternativley: # nest the list comprehension for a one line ...
53660ae20171d2b91f9ad472bd4572b4c8bf991a
663,948
def nomalize_image(image): """Nomalize image from [0,255] to "[-1, 1]""" image = image / 255.0 image = 2 * (image - 0.5) return image
eb07880036567cdaa44b78531face24dd697745d
663,952
def wavelength(frequency, speed=343.2): """Calculate the wavelength l of frequency f given the speed (of sound)""" l = speed/frequency return l
6e72b642bdb2f6426c4527d413a551d2d82a3ca6
663,954
import uuid def unique_dataset_name(prefix: str = "selenium-dataset"): """ Return a universally-unique dataset name """ return f'{prefix}-{uuid.uuid4().hex[:8]}'
a048d843dc12d5193f068a4a793e3b8fe188d108
663,955
def make_ignore_f(start_line): """Make an ignore function that ignores bad gg lines""" def ignore(line): """Return false if line is bad""" return not line or ['',''] == line or [start_line,''] == line return ignore
d81dee049adeca826c26126bca27fd92f4876afe
663,956
import json def pj(jdb): """Dumps pretty JSON""" return json.dumps(jdb,sort_keys=True,indent=4)
7235ef14a5a55cee58a5cde72bc65b4b56c66755
663,958
def _to_number(val): """ Convert to a numeric data type, but only if possible (do not throw error). >>> _to_number('5.4') 5.4 >>> _to_number(5.4) 5.4 >>> _to_number('-6') -6 >>> _to_number('R2D2') 'R2D2' """ try: if val.is_integer(): # passed as int in float for...
e848f9832778bf6463889b20894681947a0716ba
663,962
import hashlib def md5(text): """Returns the md5 hash of a string.""" hash = hashlib.md5() hash.update(text) return hash.hexdigest()
91a583ed19bfd36b80e157d30e62c9ce7cf50a44
663,963
def divides(d: int, n: int) -> bool: """Return whether d divides n.""" if d == 0: return n == 0 else: return n % d == 0
ad575e50364976c29443b4306bdb0daa375ad7b1
663,966
def get_raw_field_descr_from_header(file_handler): """ Get the raw field descriptors of the GNSS Logger log. These field descriptors will be later used to identify the data. This method advances the file pointer past the line where the raw fields are described """ for line in file_handler:...
eb85ec44fe781fcaffbe0a942ca750a82c599d75
663,967