content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def pop_required_arg(arglist, previousArg) : """ Pop the first element off the list and return it. If the list is empty, raise an exception about a missing argument after the $previousArgument """ if not len(arglist) : raise Exception, "Missing required parameter after %s" % previousArg head = arglist[0...
ed35be7859326979dceb5843a07769e5a022a30b
56,157
def to_nested_tuples(item): """Converts lists and nested lists to tuples and nested tuples. Returned value should be hashable. """ if isinstance(item, list): return tuple([to_nested_tuples(i) for i in item]) else: return item
38bffdfca7e05cc22fdc663cdf75011336a9bf93
56,159
def parse_columns(columns): """ Extract relevant values from columns of the NCBI Assembly Report """ accession = columns[0] refseq_category = columns[4] # taxid = columns[5] # species_taxid = columns[6] # Helps with dog, for example organism_name = columns[7] assembly_level = columns[11]...
28712c8d2b4d16d2ff412ded2932bd55b720b78c
56,165
def infile_to_yaml(yaml_schema, infile_schema, infile_struct): """Transform elements in a SOG Fortran-ish infile data structure into those of a SOG YAML infile data structure. :arg yaml_schema: SOG YAML infile schema instance :type yaml_schema: :class:`YAML_Infile` instance :arg infile_schema: SOG...
b70ff33efd26ebe3bea4a9d549da211e1e40fedd
56,168
def find_first_of_filetype(content, filterfiltype, attr="name"): """Find the first of the file type.""" filename = "" for _filename in content: if isinstance(_filename, str): if _filename.endswith(f".{filterfiltype}"): filename = _filename break el...
950a48be91bd2d5bd017a94a788a28501d39e3ae
56,170
def getMObjectByMObjectHandle(handle): """ Retrieves an MObject from the given MObjectHandle. :type handle: om.MObjectHandle :rtype: om.MObject """ return handle.object()
71deab5a83723a67700ff4bea750d5705c0f7bef
56,171
import re def match_rule(target, rule): """ Match rule to a target. Parameters ---------- target : dict Dictionary containing [(key, value), ...]. Keys must be str, values must be str or None. rule : dict Dictionary containing [(key, match), ...], to be matched ...
4ed15a631a637eb98015ae01e6e34e4b02e7aa91
56,178
def get_novelty_smi(gen_smis, ref_smis, return_novelty=False,): """ Get novelty generated SMILES which are not exist in training dataset para gen_smis: generated SMILES, in list format para ref_smis: training SMILES, in list format para return_novelty: if return novelty MOLs, in canonical SMILES for...
3953ddeb8968d5562edaccf7a95aeb62866c3176
56,184
def GetManufacturerInfo(e): """Organize the manufacturer information of an EDID. Args: e: The edid.Edid object. Returns: A dictionary of manufacturer information. """ return { 'Manufacturer ID': e.manufacturer_id, 'ID Product Code': e.product_code, 'Serial number': e.serial_number,...
e2217e74db5aed0afe51650a799d8b993236bb8c
56,187
def get_people_count(group): """ Return the number of people in a group. """ # Separate people from the group. people = group.split("\n") if "" in people: people.remove("") # Return people count. return len(people)
f95f740da8118ec80b6e34f5c01cd6edac8e6c92
56,191
def gen_list_gt(lst, no): """Returns list with numbers greater than no.""" #syntax: [ item for item in lst if_condition ] return [ item for item in lst if item > no ]
2f4ffff19639f224c2e571f7af6e7abe9ce57ee2
56,192
def remove_vat(price, vat): """ Returns price exluding vat, and vat amount """ price_ex_vat = price / ((vat / 100) + 1) vat_paid = price - price_ex_vat return price_ex_vat, vat_paid
44612fdd3e169c3b76ca0bfa055709d53e15d1b6
56,194
def _ParseSelector(selector): """This function parses the selector flag.""" if not selector: return None, None selectors = selector.split(',') selector_map = {} for s in selectors: items = s.split('=') if len(items) != 2: return None, '--selector should have the format key1=value1,key2=value...
e5a199fcfe500936b70d94a32cc2e001050f75c7
56,195
import tempfile def write_temp_deploy(source_prototxt, batch_size): """ Modifies an existing prototxt by adding force_backward=True and setting the batch size to a specific value. A modified prototxt file is written as a temporary file. Inputs: - source_prototxt: Path to a deploy.prototxt that will be ...
2ff20107b026346d3cae9afb08dbb853c0562e55
56,197
def onlyNormalHours(data, normal_hours): """ This function takes in the data, and only spits out the data that falls under normal trading hours. Parameters ---------- data : DataFrame dataframe of the stock data. normal_hours : list list containing the opening hour and closing h...
29c7489ab2f80a661e1be5f708b61c4ea99267b4
56,199
def dequote(token): """ Return a token value stripped from quotes based on its token label. """ quote_style_by_token_label = { 'LITERAL-STRING-DOUBLE':'"', 'LITERAL-STRING-SINGLE': "'", } qs = quote_style_by_token_label.get(token.label) s = token.value if qs and s.startsw...
f214e27988fd3bfc516f8c4c67bf389c008498df
56,204
def delanguageTag(obj): """ Function to take a language-tagged list of dicts and return an untagged string. :param obj: list of language-tagged dict :type obj: list :returns: string """ if not isinstance(obj, list): return(obj) data = (obj if len(obj) else [{}])[-1] ret...
0bec893fe3fe02061147ff6fa4e8ed8878bd7378
56,207
def search_sorted(array, value): """ Searches the given sorted array for the given value using a binary search which should execute in O(log N). Parameters ---------- array : `numpy.ndarray` a 1D sorted numerical array value : float the numerical value to search for ...
6167ce64f6e1df1172a435cb9bc87150c917a8b4
56,209
def drop_duplicates(movies_df): """ Drop duplicate rows based on `imdb_id`. If `imdb_id` is not in the columns, create it from `imdb_link`. Additionally, drop any movies with an `imdb_id` of 0. Parameters ---------- movies_df : Pandas dataframe movie data Returns -------...
f498819bbc8ca5a652444220584ff2ed594f99e4
56,210
async def read_file(file) -> bytes: """Reads a given file.""" await file.seek(0) return await file.read()
5ed5b770e5f8a79fd72472a639600bbf31a6a25d
56,211
def seir_model(prev_soln, dx, population, virus): """ Solve the SEIR ODE :param prev_soln: previous ODE solution :param dx: timestep :param population: total population :param virus: Virus object :return: solution to ODE delta values """ s, e, i, r = prev_soln ds = - virus.beta ...
e21ff1ed04f2a6118e191a3fc89c2414f2508951
56,213
def ensure3d(arr): """Turns 2 arrays into 3d arrays with a len(1) 3rd dimension. Allows functions to be written for both grayscale and color images.""" if len(arr.shape) == 3: return arr elif len(arr.shape) == 2: return arr.reshape((arr.shape[0], arr.shape[1], 1))
ad070841bf401f8d3766441978956fdbf8acfe0a
56,215
def compare_log_to_resp(log, resp): """ Search the log list for the responses in the response list Search through the log list for the lines in the response list. The response list may contain substrings found in the log list lines. The response list lines must be found in the log list in the order the...
c03ba316cd9e31b3a590574d9aee3afe12a56f74
56,220
def validation_file_name(test_name): """Std name for a result snapshot.""" return test_name + '.snapshot~'
ab69f781ff9cb218b0400bb869ef61e4678d7c8d
56,225
def slug_provider(max_length): """ Provides the tested slug data :param max_length: maximum number of characters in the slug :return: list of tuples where the first tuple element is string value and the second tuple element is whether such a value is valid """ return [ ("", Fals...
99c31d7f14377de4067aa1e180266ad1499b22f4
56,229
def lr_scheduler(epoch, init_lr=0.001, lr_decay_epoch=7): """ Returns the current learning rate given the epoch. This decays the learning rate by a factor of 0.1 every lr_decay_epoch epochs. """ return init_lr * (0.1**(epoch // lr_decay_epoch))
aa51f2b1bc8cd1c85cb0221717d3c97fa73fab48
56,231
def GetNextNodeID(nodes, dist): """ return node ID with the minimum distance label from a set of nodes """ # empty nodes if not nodes: raise Exception('Empty Scan Eligible List!!') nodeID = nodes[0] min_ = dist[nodeID] for i in nodes: if dist[i] < min_: min_ = dist[i...
46a2153a5bb86db12715825462a8351156c3a5b9
56,235
import re def find_email(text): """ Extract email from text. Parameters ---------- text: str Text selected to apply transformation Examples: --------- ```python sentence="My gmail is abc99@gmail.com" find_email(sentence) >>> 'abc99@gmail.com' ``` ...
c1ebb0d851576aebc277fa48f7e3d2569a695d31
56,236
def import_module(callback): """ Handle "magic" Flask extension imports: ``flask.ext.foo`` is really ``flask_foo`` or ``flaskext.foo``. """ def wrapper(inference_state, import_names, module_context, *args, **kwargs): if len(import_names) == 3 and import_names[:2] == ('flask', 'ext'): ...
e2250476df234f6353385c4f37f743cf4e76edde
56,238
def about_view(request): """Display a page about the team.""" return {'message': 'Info about us.'}
2d6e5b98ac21aa2770a4aab7e4f9dce2b86e2cc1
56,239
def find_nth(str1, mystr, n): """ Finds a pattern in an input string and returns the starting index. """ start = str1.find(mystr) while start >= 0 and n > 1: start = str1.find(mystr, start+len(mystr)) n -=1 return start
79eb499dfa2e923624302acfb19dc9f4af46768a
56,240
def order(x, count=0): """Returns the base 10 order of magnitude of a number""" if x / 10 >= 1: count += order(x / 10, count) + 1 return count
c3eaf92d217ef86f9f2ccc55717cdbedf098613e
56,243
import torch def get_batch_r(node_arr, device="cpu"): """Returns batch of one user's ratings node_arr (2D float array): one line is [userID, vID1, vID2, rating] device (str): device used (cpu/gpu) Returns: (float tensor): batch of ratings """ return torch.FloatTensor(node_arr[:, 3], ...
84d0a3f1bb5d3893c87141aa0b9addd99bef245c
56,245
import re def to_camel_case(snake_case): """Turn `snake_case_name` or `slug-name` into `CamelCaseName`.""" name = "" for word in re.split(r"[-_]", snake_case): name += word.title() return name
b6ccb241052929eb0e5d7843d438bc467563c1da
56,249
def escape_shell(arg): """Escape a string to be a shell argument.""" result = [] for c in arg: if c in "$`\"\\": c = "\\" + c result.append(c) return "\"" + "".join(result) + "\""
4d74ba8e00ed6eea599852be9908f20cbbc036f5
56,252
from typing import Any import fractions def fractional(value: Any) -> Any: """Returns a human readable fractional number. The return can be in the form of fractions and mixed fractions. There will be some cases where one might not want to show ugly decimal places for floats and decimals. Pass in...
ad0e28ef519af41cfd06279e1e30efe5eba44b29
56,257
import gzip import json def read_json(filename): """ Read a JSON file. Parameters ---------- filename : str Filename. Must be of type .json or .json.gz. """ if filename.endswith('json.gz'): with gzip.open(filename) as f: tree = json.load(f) elif filename.endswith('.json'): with open...
d785a8191d961204a1e0e066e0a1e38c6b7c66de
56,263
def message(msg_content, title=None, content_type=None, extras=None): """Inner-conn push message payload creation. :param msg_content: Required, string :param title: Optional, string :keyword content_type: Optional, MIME type of the body :keyword extras: Optional, dictionary of string values. ...
74c092486f571bf7ede66fc091e333375ffc754f
56,264
import time def exec_remote_cmd(client, cmd, t_sleep=5, verbose=False): """A wrapper function around paramiko.client.exec_command that helps with error handling and returns only once the command has been completed. Parameters ---------- client : paramiko ssh client the client to use c...
e6a79b58925252284c5427895d41ce3eed77f58f
56,271
def get_nodes_by_lease(db, lease_id): """Get node ids of hosts in a lease.""" sql = '''\ SELECT ch.hypervisor_hostname AS node_id FROM blazar.leases AS l JOIN blazar.reservations AS r ON l.id = r.lease_id JOIN blazar.computehost_allocations AS ca ON ca.reservation_id = r.id JOIN blazar.compu...
ce074b4d8ffb32ae4c03b913e77319e5161df11d
56,272
def clamp(x, lower=0, upper=1): """Clamp a value to the given range (by default, 0 to 1).""" return max(lower, min(upper, x))
29ccb97e5fd65b1f859516cde9157affa307f7c1
56,273
def insert_leaf(csv_map, name, value, max_depth, current_depth): """ Insert a leaf to its proper csv column, creating it if it does not exist. Note that this function will not add a new column if the associated value is None, because there's a chance that it may be revealed to be a recursive column in t...
36a307c2d2dda20dc308860a5bceeb44fd154abd
56,274
def power_of_k(k, power=1): """ Compute an integer power of a user-specified number k. """ # initialize x = 1 # multiply x by k power times. for i in range(power): x *= k return x
79519dad002e36d25725f34bb087018fec2b6a64
56,275
def calc_assignment_average(assignment_list): """ Function that will take in a list of assignments and return a list of average grades for each assignment """ return [sum(grades)/len(grades) for grades in assignment_list]
3bd061e778d46e4d6cb06672f23e944cffec7725
56,276
def selection_sort(items): """ Sort items with a selection sort. """ for index, item in enumerate(items): current_smallest = index for search_index in range(index + 1, len(items)): if items[search_index] < items[current_smallest]: current_smallest = search_ind...
66325c5e577961dc4f40c9ade7eb4764bdcc7898
56,277
def any_none(els): """Return True if any of the elements is None.""" return any(el is None for el in els)
beea382b11f4f862b9982380504406f24f94b8ef
56,279
def load_fasta(path, seperator=None, verbose=False): """Loads a fasta file. Returns a dictionary with the scaffold names as the key and the sequence as the value.""" if verbose: print("Starting to load fasta!") try: with open(path, "r") as f: scaffolds = {} current_sc...
d644ddbb5dbdd02b5c39f45f35c1bb1a4e551449
56,283
def module_checkpoint(mod, prefix, period=1, save_optimizer_states=False): """Callback to checkpoint Module to prefix every epoch. Parameters ---------- mod : subclass of BaseModule The module to checkpoint. prefix : str The file prefix for this checkpoint. period : int ...
007ab00fe2b0ce3b6acca76596ff5b68cd7cb8d6
56,285
def get_project_id_from_req(request): """ Returns the project id from the request. """ id = request.args.get("id", "").strip().lower() return id
e9b571be55abd2b60d7d0fb20f09a02ab2203fac
56,288
def replace_tmt_labels(dfp, dfm): """Replace default tmt labels with sample names provided by metadata file Parameters: ----------- dfp : pandas dataframe protein/phosphoprotein dataset dfm : pandas dataframe metadata table that should contain atleast 2 columns named 'tmt_...
ce82648cde1a6fc1f3d3128463dd5d623f6c4c2a
56,293
def get_tag2idx(df): """ Returns tags maps from a given dataframe df Outputs: tag2idx: map from tag to idx idx2tag: map from idx to tag """ tag_values = list(df["tag"].unique()) + ['PAD'] tag2idx = {tag:idx for idx, tag in enumerate(tag_values)} idx2tag = {idx:tag for tag, idx in tag2idx.items()} return tag...
4c0d15bf567f47c82779798a0a69bb3966e65e65
56,294
def filterTests(module, testFilter, testNames): """ Filters out all test names that do not belong to the given module or where one name component equals the testFilter string. """ filteredNames = [] for testName in testNames: nameComponents = testName.split('.') testIsFromModule...
7d360bf49f3b96593a63c9977568305eccd58724
56,295
def get_batch_size(tensor, base_size): """Get the batch size of a tensor if it is a discrete or continuous tensor. Parameters ---------- tensor: torch.tensor. Tensor to identify batch size base_size: Tuple. Base size of tensor. Returns ------- batch_size: int or None ...
cef7cf5487260f26abc0dac343d2a38690006330
56,306
def copy_word_pairs(word_pairs): """ Return a copy of a list of WordPairs. The returned copy can be modified without affecting the original. """ new_list = [] for pair in word_pairs: pair_copy = pair.create_copy() new_list.append(pair_copy) return new_list
e05a3a616fef6ccd94f7e3b51e7e1f77dc7fc4b9
56,308
def filter_prediction(predictions, treshhold): """ Removes prediction where scores < threshold :param predictions: ``List[Dict[Tensor]]`` The fields of the ``Dict`` are as follows: - boxes (``FloatTensor[N, 4]``) - labels (``Int64Tensor[N]``) - scores (``Tensor[N]``) * op...
6cec413989b05a229a9caaa479e251adc133ebc9
56,311
def time_to_index(t, sampling_rate): """Convert a time to an index""" return int(round(t * sampling_rate))
62103761e178101d283c0f0b0021b6740e57e83c
56,315
def tag_from_topic(mqtt_topic): """Extract the RuuviTag's name from the MQTT topic.""" return mqtt_topic.split("/")[2]
6c70e6904703af0c88b58e0ed033a545ce48e2d1
56,317
def _verb_is_valid(verb_str): """Return True if verb_str is a valid French verb; else False.""" return (len(verb_str) >= 3) and (verb_str[-2:] in ["er", "ir", "re"])
44df5cb95279de8b3096211e51a1022b256f839e
56,318
def _provider_uuids_from_iterable(objs): """Return the set of resource_provider.uuid from an iterable. :param objs: Iterable of any object with a resource_provider attribute (e.g. an AllocationRequest.resource_requests or an AllocationCandidates.provider_summaries). """ ...
5f4fbac4be65ba982cd0e8e7176b098d7a7acd22
56,325
def _remove_duplicates(list_of_elements): """ Remove duplicates from a list but maintain the order :param list list_of_elements: list to be deduped :returns: list containing a distinct list of elements :rtype: list """ seen = set() return [x for x in list_of_elements if not (x in seen or...
871190be711883b53d46f2a8c6ea2f57c3ec695c
56,333
def remove_duplicate_field(event, field_to_keep, field_to_discard): """ Remove a field when both fields are present :param event: A dictionary :param field_to_keep: The field to keep if both keys are present and the value is not None :param field_to_discard: The field to discard if the field_to_keep i...
ab200bdaa76546e92f6a489021ae35e1f268b3ef
56,335
def pic_path(instance, filename): """Generates the path where user profile picture will be saved.""" return "images/users/%s.%s" % (instance.user, filename.split('.')[-1])
f018833551d34fd56d4860e0611c3d1f1837f07e
56,336
def rowvectorize(X): """Convert a 1D numpy array to a 2D row vector of size (1,N)""" return X.reshape((1, X. size)) if X.ndim == 1 else X
3183e8aa0590427b2e51921d464f7bc767330a5d
56,341
def normalize_date(date_string): """ Converts string to DD-MM-YYYY form :param date_string: string to be converted :return: normalized string """ if date_string in ["", "-"]: return "" normalized_date = date_string.split("/") return "-".join(normalized_date)
953c476ec5d7b964788455955b8660cd6e36ad23
56,342
def _makeUserRequestContext(user): """ Constructs a class to be used by settings.USERREQUESTCONTEXT_FINDER bound to a user, for testing purposes. """ class UserRequestContextTestFinder(object): def get_current_user_collections(self): return user.user_collection.all() de...
77821e41ad2264a107d123fea14bc4ed8165480b
56,347
def reduce_unique(items): """ Reduce given list to a list of unique values and respecting original order base on first value occurences. Arguments: items (list): List of element to reduce. Returns: list: List of unique values. """ used = set() return [x for x in items i...
21c01b8024d6bbaa3c44fd9a13507fbffa6ba122
56,349
import zipfile import json def get_pack_name(zip_fp: str) -> str: """returns the pack name from the zipped contribution file's metadata.json file""" with zipfile.ZipFile(zip_fp) as zipped_contrib: with zipped_contrib.open('metadata.json') as metadata_file: metadata = json.loads(metadata_fi...
fe7f2a4d24db425ff71c8aeb27c2c7b650e5a446
56,351
def train_test_split(df, test_ratio): """ Splitting the given dataset to train and test by preserving the order between the samples (it is time series data). Parameters ---------- df: pandas' DataFrame. The dataset test_ratio: float. Indicate the ratio of the test after the split """ ...
eeb7f3cfcabbe7ca7baf827728226a51abc813cd
56,353
def check_csv(csv_name): """ Checks if a CSV has three columns: response_date, user_id, nps_rating Args: csv_name (str): The name of the CSV file. Returns: Boolean: True if the CSV is valid, False otherwise """ # Open csv_name as f using with open with open(csv_name, 'r') as f...
553b8ab08e7183b4358ff80ed4351b8e2b98f026
56,359
def _flow_tuple_reversed(f_tuple): """Reversed tuple for flow (dst, src, dport, sport, proto)""" return (f_tuple[1], f_tuple[0], f_tuple[3], f_tuple[2], f_tuple[4])
643af8917c0c800d1710d7167fd6caaa248b4767
56,360
def add_whitespace(bounding_box: list, border: int = 5) -> list: """ Add white space to an existing bounding box. Parameters ---------- bounding_box : list Four corner coordinates of the cropped image without whitespace. border : int The amount of whitespace you want to add on a...
54d94b9b858e8ebf41275c7ab0a91c8520b06b68
56,362
def get_relevant_dates(year): """ Gets the relevant dates for the given year """ if year == 2003: return [ "20030102", "20030203", "20030303", "20030401", "20030502", "20030603", "20030701", "20030801", "20030902", "20031001", "20031103", "20031201", ] # you can add ...
023d7d0b01b01ce59bd6d04cb98df3e13187deed
56,366
def num_transfer(df): """Total number of track transfer.""" return df.extra.Type.isin(['TRANSFER']).sum()
b63861cf2b0299e7d01d946c0d5064ca02cf4792
56,367
import fnmatch def csv_matches(list_of_files): """Return matches for csv files""" matches = fnmatch.filter(list_of_files, "*.csv") return matches
ee81a533731b78f77c4b4472c2e19c643d04525f
56,370
import warnings def ignore_warnings(test_func): """Decorator to ignore specific warnings during unittesting""" """ Returns: do_test: The input function 'test_func' in decorated form to approrpriately handle resource warnings """ def do_test(self, *args, **kwargs): ...
9fbe878bcb8079eb7784d4eaaa2a8062508e6a66
56,375
import pickle def viw_pkl(path, start=0, end=10): """view dict in pickle file from start to end Args: path(str): absolute path start(int, optional): start index of dict. Defaults to 0. end(int, optional): end index of dict. Defaults to 10. Returns: result(dict): a small d...
f8f9c8eb58e76447f5c9fb093ca1b838b8e733b1
56,382
def calculate_temperature_equivalent(temperatures): """ Calculates the temperature equivalent from a series of average daily temperatures according to the formula: 0.6 * tempDay0 + 0.3 * tempDay-1 + 0.1 * tempDay-2 Parameters ---------- series : Pandas Series Returns ------- Pandas...
1f6f4e4062b7ce20d1579532250329d49cfc026a
56,384
def arrayFormat(arrays, format, indices, prependIndex=False): """ Makes a list of formated strings, where each string contains formated values of all vars for one of ids, that is: ['vars[0][ids[0]] vars[1][ids[0]] ... ', 'vars[0][ids[1]] ...', ... ] Arguments: - arrays: list of a...
a349f1e7cbdeb8865dc9ee62362b984f2f16fff5
56,386
def _create_combiners(table_to_config_dict, table_to_features_dict): """Create a per feature list of combiners, ordered by table.""" combiners = [] for table in table_to_config_dict: combiner = table_to_config_dict[table].combiner or 'sum' combiners.extend([combiner] * len(table_to_features_dict[table])) ...
c8b6f11cccb3450068ec1054cc5978d193439e10
56,393
import torch def metropolis_accept( current_energies, proposed_energies, proposal_delta_log_prob ): """Metropolis criterion. Parameters ---------- current_energies : torch.Tensor Dimensionless energy of the current state x. proposed_energies : torch.Tensor ...
ed968091752bbeb3624f3480237b3a37b95e0f66
56,394
import sqlite3 def robot_type_exists(cursor: sqlite3.Cursor, type: str) -> bool: """Determines whether or not the robot type exists in the db :param cursor: [description] :type cursor: sqlite3.Cursor :param type: [description] :type type: str :return: [description] :rtype: bool """ ...
4a7646c286ad92683e819263bed8410bff069736
56,395
import math def siteXYZ(sites): """ computes geocentric site coordinates from parallax constants. Parameters ---------- sites : dictionary Typically the value returned from read5c. Keys are obscodes and values must have attributes blank, rcos, rsin, and long. Returns ---...
3cea4e4ee44d0efb1b72d5a4a8f02fc05f845f1d
56,397
def isgrashof(l1,l2,l3,l4): """ Determine if a four-bar linkage is Grashof class. """ links = [l1,l2,l3,l4] S = min(links) # Shortest link L = max(links) # Largest link idxL = links.index(L) idxS = links.index(S) P, Q = [links[idx] for idx in range(len(links)) if not(idx in (idxL,idx...
abbc703c7e0fa8736c0dc371e7e2b53570b994ef
56,401
def build_cmd(seq, out_file, query_id, args): """ Builds a command to run blast.py on the command line. :param seq: A fasta sequence to BLAST :param out_file: The name of the file to store the results in :param query_id: The id of the query :param args: A dictionary of arguments need for th...
fb5f21174652428b435ae78fafe596be7fbd0d28
56,405
def is_not_extreme_outlier(x, _min, _max): """Returns true if x >=min and x<=max.""" return x >= _min and x <= _max
22514eedba0eeb44a3f25f2ba255ebce075c9ab6
56,412
def _constant_time_compare(first, second): """Return True if both string or binary inputs are equal, otherwise False. This function should take a constant amount of time regardless of how many characters in the strings match. This function uses an approach designed to prevent timing analysis by avoidin...
abbbed038c3040e6251a410f8de3177598a1ee10
56,415
import binascii def encode_hex(_bytes): """Encode binary string to hex string format.""" return binascii.b2a_hex(_bytes)
8b2f09bdc2f5a7fb9526836fa8a4e22293cb430b
56,416
import requests def edges(word: str, lang: str = "th"): """ Get edges from `ConceptNet <http://api.conceptnet.io/>`_ API. ConceptNet is a public semantic network, designed to help computers understand the meanings of words that people use. For example, the term "ConceptNet" is a "knowledge graph"...
1cc7041a1805aa05e8318097cf88bad93962a6b0
56,420
def is_const(op): """Is const op.""" return op.type in ["Const", "ConstV2"]
ea5fcfa38b8d077d4a50b3b7f01d4298e04e97cb
56,421
from pathlib import Path from typing import MutableMapping from typing import Any import toml def toml_loader(filepath: Path) -> MutableMapping[str, Any]: """Open and load a dict from a TOML file.""" with filepath.open("r") as f: return toml.load(f)
b5a3f58434fa9c38d57fa6dc362b0f031226b38f
56,422
import json def make_json_entry(data): """Return JSON entry to be added to indiacovid19.json.""" j = [ data.ref_date, data.active, data.cured, data.death, data.ref_date + ' ' + data.ref_time, 'https://indiacovid19.github.io/webarchive/mo...
07affb5ad2d0bb77676411f3d0c1321bfbaafaa7
56,427
def get_node_index(node): """Returns the index (position) of a given node.""" if node.parent is None: return 0 return node.parent.children.index(node)
3d453ecf22d3c6a0c7acac6735e8c0ec0dd8abcd
56,429
def vector_l2norm(v): """ Function that computes the L2 norm (magnitude) of a vector. Returns: float: magnitude value """ return (v['x']*v['x'] + v['y']*v['y']) ** 0.5
e3abe58d03c9cfa5b39d791fa9a1da248d354ea8
56,430
import unicodedata def normalize_unicode(string: str) -> str: """ Normalizes a string to replace all decomposed unicode characters with their single character equivalents. :param string: Original string. :returns: Normalized string. """ return unicodedata.normalize("NFC", string)
d7d8e77beeb524a3217b167f2e5fc71290164da8
56,433
def distinct(l): """ Given an iterable will return a list of all distinct values. """ return list(set(l))
02bc70f426af96dd99e7ae690754c8e61328efbe
56,434
def replace(params): """Replace in a string. This function works the same exact way a string replace operation would work with the ``.replace()`` method. **Syntax:** [replace]string[/replace] **Attributes** ``what`` Substring to replace. (**Required**.) ``with`` ...
5522b1c8ed00b58ed0657395427322287f52f68d
56,437
def as_sequence(iterable): """Helper function to convert iterable arguments into sequences.""" if isinstance(iterable, (list, tuple)): return iterable else: return list(iterable)
f04701a540efdee0bb262efdc65f91876fd3f441
56,448
def _contains_attribute_definition(line_str: str) -> bool: """Returns whether or not a line contains a an dataclass field definition. Arguments: line_str {str} -- the line content Returns: bool -- True if there is an attribute definition in the line. """ parts = line_str.split("#",...
a0f253c06931f1515f100bafee2f31912762e509
56,449
import re def clean_data(text): """ Accepts a single text document and performs several regex substitutions in order to clean the document. Currently not used. May potentially be used in the future to clean training data and tweets Parameters ---------- text: string or object Ret...
38a4a188f55db46283c1944162fa432f20a834e4
56,451
def uniq( lst ): """Build a list with uniques consecutive elements in the argument. >>> uniq([1,1,2,2,2,3]) [1,2,3] >>> uniq([0,1,1,2,3,3,3]) [0,1,2,3] """ assert( len(lst) > 0 ) uniq = [ lst[0] ] for i in range(1,len(lst)): if lst[i] != lst[i-1]: ...
cce38a2c93ef84b655c418b4b4d7a659d97ad32c
56,452