content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def get_dependency(container, dependency_cls, **match_attrs): """ Inspect ``container.dependencies`` and return the first item that is an instance of ``dependency_cls``. Optionally also require that the instance has an attribute with a particular value as given in the ``match_attrs`` kwargs. """ for dep in container.dependencies: if isinstance(dep, dependency_cls): if not match_attrs: return dep has_attribute = lambda name, value: getattr(dep, name) == value if all([has_attribute(name, value) for name, value in match_attrs.items()]): return dep
e0b98143e096b7d183a56b69938afc628481329f
602,878
def parseRawData(response_data) : """ Given the raw response data, we extract only the required data factors from this. Parameters ---------- response_data - the raw json data from the api Return ------ candidate_centers - the list of filtered out centers """ # Initialize a list to store all the filtered out centers candidate_centers = [] # Parse through this json data and save the ones which have availability for center in response_data['sessions'] : if ( (center['vaccine'] in ['COVISHIELD']) and (center['min_age_limit'] >= 18 ) and (center['available_capacity'] > 0 ) ) : cur_candidate = { 'name' : center['name'], 'num_dose_1' : center['available_capacity_dose1'], 'num_dose_2' : center['available_capacity_dose2'], 'fee' : center['fee'], 'vaccine' : center['vaccine'], 'date' : center['date'], 'min_age' : center['min_age_limit'], 'slots' : center['slots'] } candidate_centers.append(cur_candidate) # Return this list of candidates return candidate_centers
36e78a69b2ab90828a8f1c4cea74ac0e8f3a739e
502,495
def is_valid_deck(deck_of_cards): """ (list of int) -> bool A valid deck contains every integer from 1 up to the number of cards in the deck. Return True if and only if the deck_of_cards is a valid deck of cards. >>> is_valid_deck([1, 4, 3, 2]) True >>> is_valid_deck([]) False """ # If the length of deck_of_cards is less than 3, it's not a valid deck. if len(deck_of_cards) < 3: return False # Otherwise, check whether every number from 1 up to the biggest integer # is in the deck_of_cards. else: for i in range(1, len(deck_of_cards) + 1): if not (i in deck_of_cards): return False return True
3a1dd74be6fe349a80b3522760b518ac668eea6d
270,162
def get_reference_key(entity, prop_name): """Returns a encoded key from a ``db.ReferenceProperty`` without fetching the referenced entity. Example:: from google.appengine.ext import db from tipfy.appengine.db import get_reference_key # Set a book entity with an author reference. class Author(db.Model): name = db.StringProperty() class Book(db.Model): title = db.StringProperty() author = db.ReferenceProperty(Author) author = Author(name='Stephen King') author.put() book = Book(key_name='the-shining', title='The Shining', author=author) book.put() # Now let's fetch the book and get the author key without fetching it. fetched_book = Book.get_by_key_name('the-shining') assert str(author.key()) == str(get_reference_key(fetched_book, 'author')) :param entity: A ``db.Model`` instance. :param prop_name: The name of the ``db.ReferenceProperty`` property. :returns: An entity Key, as a string. """ return getattr(entity.__class__, prop_name).get_value_for_datastore(entity)
07371df1f7c72abec384c578bdb6baa844967c22
249,377
from typing import List from typing import Type def get_class_from_name(class_name: str, classes: List, err_msg: str) -> Type: """ Return class from class name. :param class_name: String with class name. :param classes: List of classes to match the given class_name. :param err_msg: Helper string for error message. :return: Class. """ for s in classes: if class_name == s.__name__: return s raise Exception(f"{err_msg} class name is not valid: {class_name}.")
f7a670b021fa96e9720457982367fe8ae054ba8e
487,036
def get_pred_class(lls): """ Get MAP - class with max likelihood assigned Gets max key of dict passed in :param lls: Map from class name to log likelihood """ return max(lls, key=lls.get)
0c9af2e55b1d4837aaa322a25d1bb719987793a6
344,702
from typing import List def full(board: List[List[int]]) -> bool: """ Checks if board is full (there is a tie) :param board: tic tac toe board """ for i in range(len(board)): for j in range(len(board)): if board[i][j] == 0: return False return True
ee4bcd7bf7bc726aa83447baa8261f68a44fa3f6
497,514
def show_instruction(ticker): """ Displays initial instruction based on ticker insertion :param ticker: the inserted ticker :return: dict setting visibility of instruction """ if not ticker: return { 'margin-top':'25%', 'textAlign':'center', 'color':'#9C9C9C', 'display':'block' } return { 'display':'none' }
6cb9fd8b382e93c56077d76d3f77bcfecc5bf94d
261,270
def static_div(divisor): """ >>> class A: ... m = static_div(10) ... >>> a = A() >>> a.m(12345) 1234 """ def func(divident): return divident // divisor return staticmethod(func)
af73500608ef82aa1ff05e338fcf7338de201cc7
596,170
def clean_brackets( string, brackets=(("(", ")"),), ): """Removes matching brackets from the outside of a string Only supports single-character brackets """ while len(string) > 1 and (string[0], string[-1]) in brackets: string = string[1:-1] return string
d6cb7575ec0a8f4cad4c3fa859d998bc6d483d99
660,445
import re def remove_extra_whitespace(text): """ Method used to remove extra whitespaces from the text Parameters: ----------------- text (string): Text to clean Returns: ----------------- text (string): Text after removing extra whitespaces. """ pattern = re.compile(r"\s+") without_whitespace = re.sub(pattern, " ", text) # Adding space for some instance where there is space before and after. if " ? " not in text: text = without_whitespace.replace("?", " ? ") if ") " not in text: text = without_whitespace.replace(")", ") ") return text
ad942aa425e36344323d90e3665df3bf36b34e98
254,095
def uniq(lst): """ this is like list(set(lst)) except that it gets around unhashability by stringifying everything. If str(a) == str(b) then this will get rid of one of them. """ seen = {} result = [] for item in lst: if str(item) not in seen: result.append(item) seen[str(item)]=True return result
706ec44f340fbfca36cb1a605391e9fc32d38ca0
587,579
def merit3(EValw, Sw): """ Merit function calculation. Computes the merit function by selecting the first scalar, ``Sw`` minus a weight. The weight is given by the average of the second until last scalar. The first scalar is constructed in `pypcaf.find_period` and `pypcaf.pca` functions. First the eigenvalues are sorted (maximum in the zero position) and then the eigenvector are ordered according to the same relocation done in the sorting of the eigenvalues. Later the hyper-diagonal is multiplied by the new sort of the eigenvectors. Finally the first scalar is multiplied by the first eigenvalues. Parameters ---------- EValw : `~numpy.ndarray` Set of eigenvalues of math:`N` length, i.e. the number of iterations, ``iteration``. EValw[:, 0] represents all iteration for the first eigenvalue. Sw : `~numpy.ndarray` Set of scalars of math:`N` length, i.e. the number of iterations, ``iteration``. The scalar value is the projection of each for the eigenvectors into the hyper-diagonal unitary vector. In other words, the dot product of the (absolute value) eigenvector times the same dimension unitary vector. Sw[:, 0] represents all iteration for the first eigenvector. Returns ------- merit : `~numpy.ndarray` The merit function is calculated by selecting only the first position or first scalar minus weight (average of second until last scalar) and then multiplied it by its correspondent eigenvalue which coincides with the first eigenvalue as well. """ weight = Sw[:, 0] - Sw[:, 1:].mean(axis=1) # Negative values don't make any sense so for now they'll be set to zero weight[weight < 0] = 0 return EValw[:, 0] * weight
a56379e9aa13fbdbf232b3a3ea4078bb83489001
606,052
import numbers def isdigit(s): """ check if the number is a digit, including if it has a decimal place in it Or is numeric :param s: :return: """ if isinstance(s, numbers.Number): return True else: return s.replace('.','',1).replace('-', '').isdigit()
adbc844ad6d0b4b3c8fa603c21d871077026995b
421,024
import json def load_profiling_details(json_path: str) -> dict: """Load profiling details from json.""" with open(json_path, "r") as json_file: data = json.load(json_file) return data
acc19c2a2387458c203a92a7bf4f1a9bf1e76fa0
142,813
def summarize(logger): """ Creates a short summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status of every performed task. """ summary = [] for log in logger.get_logs(): thestatus = log.has_error() and log.get_error(False) or 'ok' name = log.get_name() summary.append(name + ': ' + thestatus) return '\n'.join(summary)
be2fdee12085de7913c5a3ba63d2fdad2e5caf70
521,796
def get_answer(current_row): """Returns the answer text value og HTML element""" return current_row.find_all("td", class_="risp")[0].text.strip()
14e91c250d6f28b98534fe7839e47b3650750152
20,106
from typing import Dict from typing import Any def unflatten_dict( flat_dict: Dict[str, Any], separator: str = ' ' ) -> Dict[str, Any]: """ The inverse operator to flatten_dict. Takes a flattened dictionary and returns a nested one. :param flat_dict: The dictionary to be nested. :param separator: The separator used when flattening the dictionary to separate keys of different levels. :return: A nested dictionary with structure corresponding to the keys of the flattened dictionary passed in. """ # Code adapted from link below. # https://www.geeksforgeeks.org/python-convert-flattened-dictionary-into-nested-dictionary def split_record(key, value, out): """Helper function to split up key.""" # splitting keys in dict through recursive calls. key, *rest = key.split(separator, 1) if rest: split_record(rest[0], value, out.setdefault(key, {})) else: out[key] = value nested_dict: Dict[str, Any] = {} for k, v in flat_dict.items(): # for each key call split_record which splits keys to form a recursively nested dictionary. split_record(k, v, nested_dict) return nested_dict
0f4f41f82fddc0681eaab74f378b10901f4407ab
252,934
def _find_branch(pt, targets, branches): """Determines which branch a pathway belongs to and returns that branch. A ShortestPath belongs to a branch if the first surface exposed residue it reaches during the pathway is the target of that particular branch. Parameters ---------- pt: ShortestPath ShortestPath object targets: list of str List of surface exposed residues branches: list of pyemapBranch objects List of branches already found Returns ------- cur_branch: Branch Branch object that pt belongs to """ res = pt.path[0] count = 0 while res not in targets: count += 1 res = pt.path[count] count = 0 cur_branch = branches[0] while not res == cur_branch.target: count += 1 cur_branch = branches[count] return cur_branch
6a79186fecd22c2253b67c82d83e06a0aaa6a0d2
596,581
def beautify_url(url): """ Remove the URL protocol and if it is only a hostname also the final '/' """ try: ix = url.index('://') except ValueError: pass else: url = url[ix+3:] if url.endswith('/') and url.index('/') == len(url)-1: url = url[:-1] return url
5c0ba43534758eb5d90ade1531881006ef58e8a8
645,915
def calc_NPSH(P_suction, P_vapor, rho_liq): """Return NPSH in ft given suction and vapor pressure in Pa and density in kg/m^3.""" # Note: NPSH = (P_suction - P_vapor)/(rho_liq*gravity) # Taking into account units, NPSH will be equal to return value return 0.334438*(P_suction - P_vapor)/rho_liq
da7f09873023de717743fe635f4e0042009b0fa8
510,626
def split_and_clean_text(source_text: str, split: str) -> list[str]: """Split the text into sections and strip each individually.""" source_text = source_text.strip() if split: sections = source_text.split(split) else: sections = [source_text] sections = [section.strip() for section in sections if section.strip()] return sections
ec25893c4af04b0a7462127218882c0b712ac941
455,338
import json def load_json_file(filename): """Read a JSON file and return the data as a dict. Return None on failure. """ try: with open(filename, "r") as file: data = json.load(file) return data except Exception as e: print(e) return None
5de64a66967ace3a932d7c308d6d5ea00347b082
427,566
def getPervValues(dataframe, period, on): """ Gets previous values of sma and requested column. Args: dataframe: pandas dataframe. period: the value on this many indecies in the past. on: requested column (e.g: Adj close, close, etc) Returns: dataframe containing the shifted values of sma and the requested column """ dataframe["shifted_value"] = dataframe[on].shift(period) dataframe["shifted_sma"] = dataframe["sma"].shift(period) return dataframe
2fa5a05e102373031e332327144c4c2e50866a87
519,595
def num_bytes(byte_tmpl): """Given a list of raw bytes and template strings, calculate the total number of bytes that the final output will have. Assumes all template strings are replaced by 8 bytes. >>> num_bytes([0x127, "prog_bytes"]) 9 """ total = 0 for b in byte_tmpl: if isinstance(b, int): total += 1 elif isinstance(b, list) and b: tmpl_key = b[0] if tmpl_key == "string_lit": total += 8 elif tmpl_key == "fun_offset": total += 4 else: assert False, "tmpl key: {!r}".format(tmpl_key) elif b in ("prog_entry", "prog_length"): total += 8 else: assert False, "tmpl: {!r}".format(b) return total
390e74b214bb29925d5273c1685c03d9cbca9714
631,788
def runOutOfMemory(sc): """ Run out of memory on the workers. In standalone modes results in a memory error, but in YARN may trigger YARN container overhead errors. >>> runOutOfMemory(sc) Traceback (most recent call last): ... Py4JJavaError:... """ # tag::worker_oom[] data = sc.parallelize(range(10)) def generate_too_much(itr): return range(10000000000000) itr = data.flatMap(generate_too_much) itr.count() # end::worker_oom[]
dda5239af26a4c9c32e308262dae612b65aa4de5
240,764
import csv def GetLinesFromDrivingLogs(dataPath, skipHeader=False): """ Returns the lines from a driving log with base directory `dataPath`. If the file include headers, pass `skipHeader=True`. """ lines = [] with open(dataPath + '/driving_log.csv') as csvFile: reader = csv.reader(csvFile) if skipHeader: next(reader, None) for line in reader: lines.append(line) return lines
5423e52f5e658bb3f3d590780484ada286fbd77b
588,898
def display_duration(value): """ Maps a session requested duration from select index to label.""" map = {'0':'None', '1800':'30 Minutes', '3000':'50 Minutes', '3600':'1 Hour', '5400':'1.5 Hours', '6000':'100 Minutes', '7200':'2 Hours', '9000':'2.5 Hours'} return map[value]
686576178b0cd695ad0c2de1cdd12890277e06da
600,799
def my_map(fun1, obj, iterlist): """ Map() function with a non-iterable and iterable set of parameters. Args: fun1: Function to use with 2 arguments (obj, element) obj: Non iterable or constant object. iterlist: List of elements to iterate. Returns: Return list from map(func1, obj_cte, iterlist) """ def fun2(x): """ Apply function 1. Args: x: Element of a list Returns: The return from function 1 """ return fun1(obj, x) return map(fun2, iterlist)
fe22645aa9c1151049bf6b24f75f242cbd70291b
195,225
def indexesof(l, fn, opposite=0): """indexesof(l, fn) -> list of indexes Return a list of indexes i where fn(l[i]) is true. """ indexes = [] for i in range(len(l)): f = fn(l[i]) if (not opposite and f) or (opposite and not f): indexes.append(i) return indexes
c7f961701b347e0a29a16fcade3377e16f94b61f
318,351
def df_diff(df1, df2, which='both'): """ Find rows which are different between two dataframes. """ _df = df1.merge(df2, indicator=True, how='outer') diff_df = _df[_df['_merge'] != which] return diff_df.reset_index(drop=True)
8905aed63aca458c7beb176bbabda63ab05f4cbd
215,071
def models_dict_to_list(models): """ Given a models dict containing subapp names as keys and models as a list of values return an aggregated list of all models """ all_models = [] if isinstance(models, dict): for _, app_models in list(models.items()): all_models.extend(app_models) else: all_models = models return all_models
1753ae5b921de87b57e5dd9571a39c4dbdecc16c
374,555
def Query(cursor, sql, params=None): """Query against the Cursor. Params will be formatted into the sql query string if present. Returns: list of dicts """ # No parameters if not params: cursor.execute(sql) # Else, parameters need to be passed in too else: cursor.execute(sql, params) # Get the SQLite object rows object_rows = cursor.fetchall() # Convert the object rows into dicts for my preferred usage (requires setting connection: conn.row_factory = sqlite3.Row) rows = [] for row in object_rows: rows.append(dict(row)) return rows
9f9bbd6a526d867a960eb5a45c442a3e62f08854
252,092
def minmax(x): """ Returns a tuple containing the min and max value of the iterable `x`. .. note:: this also works if `x` is a generator. >>> minmax([1, -2, 3, 4, 1, 0, -2, 5, 1, 0]) (-2, 5) """ (minItem, maxItem) = (None, None) for item in x: if (minItem is None) or (item < minItem): minItem = item if (maxItem is None) or (item > maxItem): maxItem = item return (minItem, maxItem)
f2127bf8cb6d444d97f23b147590d94265b5480c
634,826
def list_workers(input_data, workerlimit): """ Count number of threads, either length of iterable or provided limit. :param input_data: Input data, some iterable. :type input_data: list :param workerlimit: Maximum number of workers. :type workerlimit: int """ runners = len(input_data) if len(input_data) < workerlimit else workerlimit return runners
9ea30a3a3fc3ebd67ffee7117d502caa9110de08
29,713
import math def morse_energy(dist, params): """The Morse interaction energy :param dist: The distance between the two interacting atoms. :param params: The Morse parameters. :returns: The interaction energy. """ de, a, r0 = params return de * (( math.exp(a * (r0 - dist)) - 1 ) ** 2 - 1.0)
6f29c090eab8d5fb07b4470457007f38943403a7
575,598
def untuple_dict(the_dict): """ convert dict with keys that are tuples to a dict with keys that are strings :param the_dict: ({tuple: obj}) :return: ({str: obj}) """ def to_key(obj): return ( f'({",".join(str(o) for o in obj)})' if isinstance(obj, tuple) else obj ) return {to_key(k): v for k, v in the_dict.items()}
5d7f91eab99bd604a93ffe3b0176812728e56116
485,112
def get_normalized_language(language_code): """ Returns the actual language extracted from the given language code (ie. locale stripped off). For example, 'en-us' becomes 'en'. """ return language_code.split('-')[0]
e5de7b22eb3bce36099d5cd195efe8b85b42fc11
315,976
def get_critical_process_from_monit(duthost, container_name): """Gets command lines of critical processes by parsing the Monit configration file of each container. Args: duthost: Hostname of DuT. container_name: Name of container. Returns: A list contains command lines of critical processes. Bool varaible indicates whether the operation in this funciton was done successfully or not. """ critical_process_list = [] succeeded = True monit_config_file_name = "monit_" + container_name file_content = duthost.shell("bash -c '[ -f /etc/monit/conf.d/{0} ] && cat /etc/monit/conf.d/{0}'" .format(monit_config_file_name)) if file_content["rc"] != 0: succeeded = False return critical_process_list, succeeded for line in file_content["stdout_lines"]: if "process_checker" in line: command_line = line.split(" {} ".format(container_name))[1].strip(" \n\"") critical_process_list.append(command_line) return critical_process_list, succeeded
c26b4b788252b4e6273fb77fd14c22619fe2d125
578,322
import torch def asymmetric_linear_quantization_params(num_bits, saturation_min, saturation_max, integral_zero_point=True): """ Compute the scaling factor and zeropoint with the given quantization range for asymmetric quantization. Parameters: ---------- saturation_min: lower bound for quantization range saturation_max: upper bound for quantization range integral_zero_point: if True, adjust zero_point accordingly to make sure 0.0 in floating point tensor be exactly mapped to an integer value. """ # these computation do not require any gradients, to enforce this, we use torch.no_grad() with torch.no_grad(): n = 2 ** num_bits - 1 scale = torch.clamp((saturation_max - saturation_min), min=1e-8) / float(n) # For asymmetric quantization, the current hardware support scaled unsigned integers without zero_point. # So saturation_min = 0 (we only do asymmetric quantization for activations after ReLU.) zero_point = -saturation_min / scale if integral_zero_point: if isinstance(zero_point, torch.Tensor): zero_point = zero_point.round() else: zero_point = float(round(zero_point)) return scale, zero_point
4faf7496323a3e174309c01fde01d5ae90db1248
230,158
import re def fix_enye(text): """Reconstructs 'ñ' character if it's broken. Args: text (string): markdown text that is going to be processed. Returns: string: text once it is processed. """ enye_regex = re.compile(r'˜ *n', re.UNICODE) processed_text = enye_regex.sub(r'ñ', text) return processed_text
ff4e7dbb1093d17921169410d7d49f4d02ee74a7
441,930
import itertools def disjoint_subsets(list_a: list, groups): """Problem 27: Group elements of set into disjoint subsets. Parameters ---------- list_a : list The input list groups Returns ------- Raises ------ TypeError If the given argument is not of `list` type """ if not isinstance(list_a, list): raise TypeError('The argument given is not of `list` type.') set_a = set(list_a) # Find all combinations with the given plurality of the first subset first_set = itertools.combinations(set_a, groups[0]) disjoint_list = [] for x in first_set: # For every subset of the possible combinations of the first # group, remove its members and find all combinations with # given plurality of the second subset temp_subset = set_a - set(x) second_set = itertools.combinations(temp_subset, groups[1]) list_x = list(x) for y in second_set: subset = [list_x, list(y), list(temp_subset - set(y))] disjoint_list.append(subset) return disjoint_list
a894009dccd198113db13212af1d6d03ecbe3e44
428,707
from datetime import datetime def get_timestamp(timestamp_format="%Y%m%d_%H%M%S"): """Return timestamp with the given format.""" return datetime.now().strftime(timestamp_format)
b5a53d49df7c52598e9a171936e351869ef5cf6b
101,066
def find(predicate, collection): """ Attempts to find a match for the given predicate function in a given collection. We return the first match only, or None if no match exists. """ for item in collection: if predicate(item): return item return None
b09fb15fc11990a3ea7e82762bf6a53640b57787
153,289
from datetime import datetime def unixtime_to_datestring(unix_time): """Convert unix timestamp into a string.""" return datetime.fromtimestamp(unix_time).strftime("%Y-%m-%d %H:%M:%S")
2c26927af8c066eb4e0e9b3ae05fcffa35d8fa3f
260,921
def jaccard(A,B): """[Jaccard similarity between 2 sets] Args: A ([set]): [description] B ([set]): [description] Returns: [int]: [Jaccard Similarity] """ union = A.union(B) inter = A.intersection(B) return len(inter)/len(union)
f4ae370b150bd230e002475eac199f1b1f2f1f80
428,016
def last_name_first(n): """ Returns: copy of n but in the form 'last-name, first-name' We assume that n is just two names (first and last). Middle names are not supported. Examples: last_name_first('Walker White') returns 'White, Walker' last_name_first('Walker White') returns 'White, Walker' Parameter n: the person's name Precondition: n is a string in the form 'first-name last-name' with one or more spaces between the two names. There are no spaces in either <first-name> or <last-name> """ end_first = n.find(' ') first = n[:end_first] # Get the last name # Put them together with a comma return ', '+first # Last variable assigned
27207471131aa6c0271f97a50355cfee52dfc62e
192,565
def is_power_of_two(x): """ Checks whether the input is the power of 2. """ return x & (x-1) == 0
64e199b8b7a53ec7cd458ffddc7f7a9d8f4992cb
482,019
def balanced_sums(arr): """Hackerrank Problem: https://www.hackerrank.com/challenges/sherlock-and-array/problem Watson gives Sherlock an array of integers. His challenge is to find an element of the array such that the sum of all elements to the left is equal to the sum of all elements to the right. For instance, given the array , arr = [5, 6, 8, 11], 8 is between two subarrays that sum to 11. If your starting array is [1], that element satisfies the rule as left and right sum to 0. You will be given arrays of integers and must determine whether there is an element that meets the criterion. Args: arr (list): An array of integers Returns: str: YES or NO depending on whether there is a balanced sum in the list """ left = 0 right = sum(arr) for i in range(len(arr)): right -= arr[i] if left == right: return "YES" left += arr[i] return "NO"
8d10a30c64b434b98b709718a729d32590b00ae8
371,753
def mayan_tzolkin_date(number, name): """Return a Tzolkin Mayan date data structure.""" return [number, name]
8cfd4120ea76de36e824311f1afab752beed84a3
649,435
def add_month_year_columns(data, datetime_field): """Adds month and year columns to a DataFrame using a timestamp column. :param data: The DataFrame :type data: DataFrame :param datetime_field: The datetime fields name :type datetime_field: str :returns: Altered DataFrame""" data['year'] = data[datetime_field].dt.year data['month'] = data[datetime_field].dt.month return data
cdf157ae3634372803900e9e131db1d70e76d0c7
406,634
import csv def readCSV(filename): """ Reads the .data file and creates a list of the rows Input filename - string - filename of the input data file Output data - list containing all rows of the csv as elements """ data = [] with open(filename, 'rt', encoding='utf8') as csvfile: lines = csv.reader(csvfile) for row in lines: data.append(row) return data
65eb44a9900babeae09af340880a96f35eb9e25c
681,389
import requests def post_input_form(input_text): """Posts a string as a form field (application/x-www-form-urlencoded) named 'input' to the REST API and returns the response. """ url = 'http://localhost:5000/parse' return requests.post(url, data={'input': input_text})
d2e7c9aa97ca7ef0d5f7100a74e83f2cdc6d882b
650,842
import six def let(__context__, *args, **kwargs): """:yaql:let Returns context object where args are stored with 1-based indexes and kwargs values are stored with appropriate keys. :signature: let([args], {kwargs}) :arg [args]: values to be stored under appropriate numbers $1, $2, ... :argType [args]: chain of any values :arg {kwargs}: values to be stored under appropriate keys :argType {kwargs}: chain of mappings :returnType: context object .. code:: yaql> let(1, 2, a => 3, b => 4) -> $1 + $a + $2 + $b 10 """ for i, value in enumerate(args, 1): __context__[str(i)] = value for key, value in six.iteritems(kwargs): __context__[key] = value return __context__
c1c1e55b6b514ea88594f8126c7ced7aa8b1d2e5
692,469
def gferror(reply): """Determines if a GF reply is an error""" return (reply.startswith('The parser failed') or reply.startswith('The sentence is not complete') or reply.startswith('Warning:') or reply.startswith('Function') and reply.endswith('is not in scope'))
c286b2c5ce399774ef0638c204f5d303bd181269
602,588
def check_solution(task, solution_string, ops_namespace=None): """Checks whether solution_string passes all examples in the task.""" for example_index in range(task.num_examples): namespace = ops_namespace.copy() if ops_namespace else {} for input_name, input_values in task.inputs_dict.items(): namespace[input_name] = input_values[example_index] try: result = eval(solution_string, {'__builtins__': {}}, namespace) # pylint: disable=eval-used if result != task.outputs[example_index]: return False except: # pylint: disable=bare-except return False return True
76a75e449fe39e37edb45ace1a6a29d20e695d3a
159,297
from pathlib import Path def home_directory() -> str: """ Return home directory path Returns: str: home path """ return str(Path.home())
8c9c1ccccfc547a26794e5494975e27cde4e73ef
65,110
def convert_to_csv(records): """Convert records in list type to csv string. Args: records: A list of power data records each of which contains timestamp, power value, and channel. e.g. [[12345678, 80, "SYSTEM"],[23456789, 60, "SENSOR"]]. Returns: A string that contains all CSV records, None if the given list if empty. """ if not records: return '' csv_lines = list() for record in records: string_record = [str(element) for element in record] csv_line = ','.join(string_record) csv_lines.append(csv_line) return '\n'.join(csv_lines)
8a788f6a1325735e7747ffe3a03b44e21286aa66
344,563
def schmdt_nmbr(diffusivity, kinematic_viscosity = 10**-6): """ Return the Schmidt number [] Parameters ---------- kinematic_viscosity : kinematic viscosity of water (defautl 10^-6)[m²/s] diffusivity : mass diffusivity of the chemical in water [m²/s] """ return kinematic_viscosity / diffusivity
4242e5e2775770ab13a82ce2b81902077660ff24
522,179
import struct def get_uint32(s: bytes) -> int: """ Get unsigned int32 value from bytes :param s: bytes array contains unsigned int32 value :return: unsigned int32 value from bytes array """ return struct.unpack('I', s)[0]
69f499ad9001f3313681b48a951cac4fd3c0b406
436,310
import keyword def validate_module_name(value, convert_lowercase=False, allow_keywords=False): """ Validate a string to be used as python package or module name """ if not isinstance(value, str): raise NameError(f'Module must be string: {value}') if not value.isidentifier(): raise NameError(f'Name is not valid python identifier: {value}') if not allow_keywords and keyword.iskeyword(value): raise NameError(f'Name is a python keyword: {value}') lowercase = value.lower() if not convert_lowercase and lowercase != value: raise NameError(f'Name is not a lowercase string: {value}') if convert_lowercase: value = lowercase return value
0049f9b15a677cf9c508b95c8c7e8d30864f4183
358,687
def _deindent(line, indent): """Deindent 'line' by 'indent' spaces.""" line = line.expandtabs() if len(line) <= indent: return line return line[indent:]
6fba2ed9a8387901bd8d100d0cb98d808db44310
121,888
def csv_to_list(s): """Split commas separated string into a list (remove whitespace too)""" return [x for x in s.replace(" ", "").split(",")]
fe47ecabaee49fad30d4d693e7109744e13adeeb
398,395
def quartile(arr, val): """ Return the quartile (0-3) of val in arr. """ sorted_array = sorted(arr) interval_length = len(sorted_array) / 4.0 return int(sorted_array.index(val) / interval_length)
ae1ddeddcd03c4525764ab4d4ce2d6b10c52b3d0
238,480
def write_uleb128(num: int) -> bytearray: """ Write `num` into an unsigned LEB128. """ if num == 0: return bytearray(b'\x00') ret = bytearray() length = 0 while num > 0: ret.append(num & 0b01111111) num >>= 7 if num != 0: ret[length] |= 0b10000000 length += 1 return ret
fb13878a0c5e984cb1447dfad4536c6f9dcb9ed3
605,401
from functools import reduce from typing import cast def cast_schema(df, schema): """Enforce the schema on the data frame. Args: df (DataFrame): The dataframe. schema (list): The simple schema to be applied. Returns: A data frame converted to the schema. """ spark_schema = schema.to_spark() # return spark_session.createDataFrame(df.rdd, schema=spark_schema) return reduce(cast, spark_schema.fields, df.select(*spark_schema.fieldNames()))
1a8412a2a3a363589c18f09e672145e94a020aab
674,708
def remove_dash(item): """ Remove the first character in a string. :param item: String :return: input string, with first character removed """ return item[1:]
2fbabb1b2359f6e89b69fd1d65a411e4b1012e6d
634,273
from pathlib import Path from typing import Tuple def _is_file_with_supported_extensions(path: Path, extensions: Tuple[str, ...]) -> bool: """ Check if the file is supported for the media type :param path: File path to check :param extensions: Supported extensions for the media type :example: >>> from pathlib import Path >>> path = Path("./demo.mp4") >>> extensions = _get_extensions(media_type=MediaType.video) >>> _is_file_with_supported_extensions(path, extensions) True >>> path = Path("demo.jpg") >>> extensions = _get_extensions(media_type=MediaType.image) >>> _is_file_with_supported_extensions(path, extensions) True >>> path = Path("demo.mp3") >>> extensions = _get_extensions(media_type=MediaType.image) >>> _is_file_with_supported_extensions(path, extensions) False """ return path.suffix.lower() in extensions
0bab2e1eead6dca863d062bd9d187e6a5f54c788
615,808
def get_ip(driver, ip_site="https://api.ipify.org"): """ gets ip from specified page :param driver: selenium webdriver object :param ip_site: ip site, which only returns ip as string :return: str of current ip address """ driver.get(ip_site) return driver.find_element_by_tag_name("body").text
9cd943aa3288d50beb90755d85ed5708a14bec5f
161,124
def scale_series(series): """ Scales a series. Scaling involves dividing the series standard deviation from each entry in series, resulting in a new standard deviation of 1 Parameters ------------ series : pd.Series Returns ---------- tuple A tuple containing (1) the std deviation used, and (2) the resultant transformed series """ sigma = series.std() if sigma > 0: series = series.apply(lambda x: x / sigma) return (sigma, series)
689d9600227f324dc6161802573223e9f8c7649a
322,498
def parse_grammar(file_path): """ Generate a grammar from a file describing the production rules. Note that the symbols are inferred from the production rules. For more information on the format of the file, please reffer to the README.md or the the sample grammars provided in this repository. :param file_path: Path to the file containing the description of the grammar. :returns: the grammar object and the starting symbol. """ with open(file_path) as f: content = f.read().splitlines() if len(content) <= 1: raise Exception('Grammar should have at least one production rule and a starting symbol') # First line should be the starting symbol start_symbol = content[0] grammar = {} for line in content[1:]: # Each line should be in the format: # X -> A B ... C symbols = line.split() if len(symbols) <= 2 or symbols[1] != '->': raise Exception('Each production line should be in the format: X -> A B ... C') if symbols[0] not in grammar: grammar[symbols[0]] = [] grammar[symbols[0]].append(symbols[2:]) if start_symbol not in grammar: raise Exception('Grammar should have at leats one production rule with the start_symbol.') return grammar, start_symbol
1dda39f139b5e032ba6610dbeb0b861de98bb928
173,714
def all_unique(x): """Return True if the collection has no duplications.""" return len(set(x)) == len(x)
db0ec5eaff3a9144646a470a5df335b1cf27f421
209,808
from pathlib import Path def get_file_content(file_path: Path) -> str: """ Get the content of the file. :param file_path: Path to the file you want to read. :return: File content. """ with open(file_path, encoding='utf-8', errors='ignore') as file: return file.read()
000989f82454e6a84478f7d51677e16a3ff45a6f
338,694
from typing import Dict from typing import Any def has_key(dictionary: Dict[str, Any], key: str) -> bool: """ Check whether dictionary has given key is present or not :param dictionary: Dictionary that need to check if key present or not :param key: Key value that need to check :return: Boolean value based on given key is present in the dictionary """ if key in dictionary.keys(): return True return False
e1bb6eae8b9758b777003a9fd937d21dcd7166a7
622,463
def neutral_mass_from_mz_charge(mz: float, charge: int) -> float: """ Calculate the neutral mass of an ion given its m/z and charge. Parameters ---------- mz : float The ion's m/z. charge : int The ion's charge. Returns ------- float The ion's neutral mass. """ hydrogen_mass = 1.00794 return (mz - hydrogen_mass) * charge
1212fffcf7b924768cc9c50079197ed294d937b3
63,430
from typing import Type def _type_to_key(t: Type) -> str: """ Common function for transforming a class type to its associated string key for use in configuration semantics. :param t: Type to get the key for. :return: String key for the input type. """ return f"{t.__module__}.{t.__name__}"
c88bd2ebb6b537682328d3bcc9350daa2fe54e6c
583,652
def runge_kutta_ode_solver(ode, time_step, y, params): """4th order Runge-Kutta ODE solver. Carnahan, B., Luther, H. A., and Wilkes, J. O. (1969). Applied Numerical Methods. Wiley, New York. Parameters ---------- ode : function Ordinary differential equation function. In the Lorenz model it is SDE. time_step : float y : np.ndarray of dimension (batch_size, n_obs) Current state of the time-series. params : list of parameters The parameters needed to evaluate the ode. In this case it is list of four elements - eta, theta1, theta2 and f. Returns ------- np.ndarray Resulting state initiated at y and satisfying ode solved by this solver. """ k1 = time_step * ode(y, params) k2 = time_step * ode(y + k1 / 2, params) k3 = time_step * ode(y + k2 / 2, params) k4 = time_step * ode(y + k3, params) y = y + (k1 + 2 * k2 + 2 * k3 + k4) / 6 return y
2db376cc7a97bd808c0ea7e4b439213b8132ac09
595,386
def is_same_module_or_submodule(orig, incoming): """ Returns true if the incoming module is the same module as the original, or is a submodule of the original module """ if incoming is None: return False if orig == incoming: return True if incoming.__name__.startswith(orig.__name__): return True return False
a3ecf3f1d9d1546a9f8a30f9ef6609ae9e94cc6e
627,884
def resample_history_df(df, freq, field): """ Resample the OHCLV DataFrame using the specified frequency. Parameters ---------- df: DataFrame freq: str field: str Returns ------- DataFrame """ if field == 'open': agg = 'first' elif field == 'high': agg = 'max' elif field == 'low': agg = 'min' elif field == 'close': agg = 'last' elif field == 'volume': agg = 'sum' else: raise ValueError('Invalid field.') resampled_df = df.resample(freq).agg(agg) return resampled_df
36a089470fbe56971da4763129e0c337cb149e2a
350,821
import glob def _GetCasedFilename(filename): """Returns the full case-sensitive filename for the given |filename|. If the path does not exist, returns the original |filename| as is. """ pattern = '%s[%s]' % (filename[:-1], filename[-1]) filenames = glob.glob(pattern) if not filenames: return filename return filenames[0]
df033b24b76ed90aa49bc4d88b4e289774bacf7a
139,183
from typing import Tuple def get_pos(target: Tuple[float, ...], area: Tuple[int, ...]) -> Tuple[int, ...]: """Get absolute position, given relative position and target area Parameters ---------- target : Tuple[float, float] Relative position area : Tuple[int, int] Absolute area Returns ------- Tuple[int, int] Absolute position """ return tuple(int(a * b) for a, b in zip(target, area))
44c469a807ca9e256f87a32bb2c03e4e0a1b9cf3
63,756
def get_pr_required_statuses(pr): """Gets a list off all of the required statuses for a PR to be merged.""" statuses = pr.session.get( 'https://api.github.com/repos/{}/{}/branches/{}/protection/' 'required_status_checks/contexts'.format( pr.repository[0], pr.repository[1], pr.base.ref)).json() return statuses
c8870d5c1eb204c836ada30664232b02ca08b445
225,637
def uuid_encode(uuid): """ Turns a UUID instance into a uuid string. """ if not uuid: return '' if isinstance(uuid, str): return uuid return uuid.hex
8ec81fe6d4a0484dc02f4ef4f27379bcf8435897
361,194
def entitydata_delete_confirm_form_data(entity_id=None, search=None): """ Form data from entity deletion confirmation """ form_data = ( { 'entity_id': entity_id, 'entity_delete': 'Delete' }) if search: form_data['search'] = search return form_data
df473118ea31df991d65395f2e55dfdc350a24ed
76,267
import hashlib def calcChecksum(filepath): """ Calculate MD5 of relevant information Returns tuple of filename and calculated hash """ with open(filepath, "r") as fil: cnt = fil.readlines() relinfo = [] for line in cnt: atm = line[12:16].rstrip().lstrip() altloc = line[16] if (atm == "CA"): if (altloc == ' '): AA = line[17:20].rstrip().lstrip() relinfo.append(AA) else: return None return (filepath, hashlib.md5("".join(relinfo).encode("utf-8")).hexdigest())
36a84ca868dd12f1ae42a037f057f507d395455a
103,790
import csv def get_tsv_header(input): """Get a header of a tsv file. Column counts of the first (header) and second (content) line are compared. If the header has one column less than the content, then a new column is added to the beginning of the returned list (convention in Chipster to handle R files). """ with open(input) as file: reader = csv.reader(file, delimiter='\t') header = next(reader) row = next(reader); if len(header) + 1 == len(row): header = [' '] + header; return header
dc66e14da5158e691d02a8085ff1ae6ef8a9d3eb
86,300
import gzip def naive_count_lines(infile): """ Count lines in a gzip JSON LD file """ n = 0 with gzip.open(infile, 'r') as source: for _, n in enumerate(source, 1): pass return n
b1d67b214c9e1e9840a7840454c90f8edbc10a41
213,374
def dump_dict(dump): """Returns dict of common profiles (radial quantities) """ return {'y': dump.y, 'tn': dump.tn, 'xkn': dump.xkn, 'abar': dump.abar, 'zbar': dump.zbar, }
38877c9daa27115ac67ec9f5176f9bcccd5b8ebd
637,356
def basic_listifier(item): """Takes strings, tuples, and lists of letters and/or numbers separated by spaces, with and without commas, and returns them in a neat and tidy list (without commas attached at the end.""" if type(item) == tuple or type(item) == list: final = [x.replace(',','') for x in item] return final elif type(item) == str: final = [x.replace(',','') for x in item.split(' ')] return final
bc78df79e896e773d3465258e9d4fa89fe8e4f15
360,631
def _cast_types(args): """ This method performs casting to all types of inputs passed via cmd. :param args: argparse.ArgumentParser object. :return: argparse.ArgumentParser object. """ args.x_val = None if args.x_val == 'None' else int(args.x_val) args.test_size = float(args.test_size) args.dual = (args.dual in ['True', "True", 'true', "true"]) args.tol = float(args.tol) args.C = float(args.C) args.fit_intercept = (args.fit_intercept in ['True', "True", 'true', "true"]) args.intercept_scaling = float(args.intercept_scaling) args.class_weight = None if args.class_weight == 'None' else {} args.random_state = None if args.random_state == 'None' else int(args.random_state) args.max_iter = int(args.max_iter) args.verbose = int(args.verbose) args.warm_start = (args.warm_start in ['True', "True", 'true', "true"]) args.n_jobs = None if args.n_jobs == 'None' else int(args.n_jobs) args.l1_ratio = None if args.l1_ratio == 'None' else float(args.l1_ratio) # --------------- # return args
40285a3b93606b6503f5ad1486fb61cc61d32a8e
99,081
from typing import Any import math def make_divisible(x: Any, divisor: int): """Returns x evenly divisible by divisor.""" return math.ceil(x / divisor) * divisor
bfbcfb334777a6c7214f16aa0fadd56906e2b7bc
5,731
import re def pattern_match(item : str, pattern : str, strict : bool = True) -> bool: """ Check if item matches with the pattern that contains "*" wildcards and "?" question marks. Args: item: The string that pattern will be applied to. pattern: A wildcard (glob) pattern. strict: If `True`, then it will check if matched string equals with the `item` parameter. So applying "foo?" pattern on "foobar" will result in `False`. Default is `True`. Returns: A boolean value. """ _ptn = pattern.replace(".", "\.").replace("+", "\+").replace("*", ".+").replace("?", ".") _match = re.match(_ptn, item) if strict and bool(_match): return _match.group(0) == item return bool(_match)
fb92c1782f684e6a6fbad4890a299e5670a9487e
692,947
def prepare_velo_points(pts3d_raw): """ Replaces the reflectance value by 1, and tranposes the array, so points can be directly multiplied by the camera projection matrix """ pts3d = pts3d_raw # Reflectance > 0 pts3d = pts3d[pts3d[:, 3] > 0 ,:] pts3d[:,3] = 1 return pts3d.transpose()
a9a5efd5e305f1a9b160f82fe3f005f3fb2b67ac
328,902
import math def compute_idfs(documents): """ Given a dictionary of `documents` that maps names of documents to a list of words, return a dictionary that maps words to their IDF values. Any word that appears in at least one of the documents should be in the resulting dictionary. """ idf = {} seen = set() docsets = {k: set(v) for k,v in documents.items()} for file, doc in documents.items(): for word in doc: if word in seen: continue df = [1 if word in otherdoc else 0 for otherdoc in docsets.values()] df = sum(df) idf[word] = math.log(len(documents) / df) seen.add(word) return idf
3ce13136b1b8d573976e3d9dca09929b50c5db0e
362,582
import re def clean_utterance_text(text: str) -> str: """Removes line breaking and extra spaces in the user utterance.""" # sometimes the user utterance contains line breaking and extra spaces text = re.sub(r"\s+", " ", text) # sometimes the user utterance has leading/ending spaces text = text.strip() return text
8ca6f5c8b6109b5a17327ce109452a4d3bf092c7
313,562
import logging def build_logger(name, **kwargs): """ Builds a logging instance with the specified name Arguments --------- name: name of the logger Keyword arguments ----------------- format: event description message format level: lowest-severity log message logger will handle propagate: events logged will be passed to higher level handlers stream: specified stream to initialize StreamHandler """ # set default arguments kwargs.setdefault('format', '%(levelname)s:%(name)s:%(message)s') kwargs.setdefault('level', logging.CRITICAL) kwargs.setdefault('propagate',False) kwargs.setdefault('stream',None) # build logger logger = logging.getLogger(name) logger.setLevel(kwargs['level']) logger.propagate = kwargs['propagate'] # create and add handlers to logger if not logger.handlers: # create handler for logger handler = logging.StreamHandler(stream=kwargs['stream']) formatter = logging.Formatter(kwargs['format']) handler.setFormatter(formatter) # add handler to logger logger.addHandler(handler) return logger
577fb63ce5a40171b2b44d03e60931afe1ab5a51
389,147
def _isCpuOnly(log): """check for CPU-Only mode""" for l in log: if "cpu" in l.lower(): return True return False
0840b5ae6bf5840740be4ad24e3b430013c1b09f
223,393
import re def rule_to_regex(rule: str, prefix: str = "", suffix: str = "") -> "re.Pattern": """Convert a rule from the mast to regular expressions. Args: rule (str): The line from the mast prefix (str, optional): Regex to be prepended suffix (str, optional): Regex to be appended Returns: re.Pattern: A regular expression """ rule = rule.replace(".", "\\.") rule = rule.replace("*", "[^/]*") rule = rule.replace("#", "(|/|/?.*/?)") rule = prefix + rule + suffix return re.compile(rule)
64f24abd3c831d939a6a1d17375ef1c430acac2f
177,285
def readFile(filepath): """Gets string representing the path of the file to be processed and returns it as a list. It will omit blank lines. Parameters ---------- filepath : str The path of the filename to be processed Returns ------- lines a list that contains the lines of the file """ try: with open(filepath) as f_in: lines = list(line for line in (l.strip() for l in f_in) if line) except IOError as err: print(err) return None if not lines: print("Empty file") exit(1) return lines
d1dc54b48f7012cbf0f253154af96d673cd00259
44,755
def band_info(band_names, band_uris=None): """ :param list band_names: names of the bands :param dict band_uris: mapping from names to dicts with 'path' and 'layer' specs """ if band_uris is None: band_uris = {name: {'path': '', 'layer': name} for name in band_names} return { 'image': { 'bands': {name: band_uris[name] for name in band_names} } }
34b84713a9f77cfd4570c63440719d48ca235145
482,060