content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def to_camel_case(snake_case): """ convert a snake_case string to camelCase """ components = snake_case.split('_') return components[0] + "".join(x.title() for x in components[1:])
e7433ec546cc93700bd67bd4e559795a9add31ed
686,144
def elite_selection(population, elite_num): """ Uses elite selection to pick elite_num units from population :param population: population to be picked from :param elite_num: number of units to be selected :return: array of selected units """ return population[:elite_num]
e4fc4e42b49014e64d4f79547c99264b56e4bf02
202,356
def get_keys_from_val(dic, val): """Get all keys from a value in a dictionnary""" toreturn = list() for key in dic: if dic[key] == val: toreturn.append(key) return toreturn
3e6217af28b2192c63c4dfb220550535abc2eb5d
445,962
def is_tuple_starting_with(tuple_1, tuple_2): """ Returns whether `tuple_1` starts with `tuple_2`. Parameters ---------- tuple_1 : `tuple` The first tuple which should start with the second one. tuple_2 : `tuple` The second tuple. Returns ------- is_tuple_starting_with : `bool` """ tuple_1_length = len(tuple_1) tuple_2_length = len(tuple_2) if tuple_1_length > tuple_2_length: return tuple_1[:tuple_2_length] == tuple_2 if tuple_1_length == tuple_2_length: return tuple_1 == tuple_2 return False
1c69bd0033c2535212f22af74ae783af25959ec0
526,131
def is_in_file(file_path, text): """ Looks for text appearing in a file. :param str file_path: Path to the source file :param str text: Text to find in the file :raises OSError: If the file does not exist :returns bool: True is text is in file, False otherwise """ with open(file_path, 'r') as f: content = f.read() return text in content
3b5b482a9bec8d211dbe6631f888fed19376ecde
396,560
def IntToRGB(intValue): """ Convert an FL Studio Color Value (Int) to RGB """ blue = intValue & 255 green = (intValue >> 8) & 255 red = (intValue >> 16) & 255 return (red, green, blue)
5ba1735c73a2b0c51f67b8b4f0ae67dfcae8a5ea
64,726
import pkg_resources def get_package_version(pkg_name): """Get the version of the given package""" return pkg_resources.get_distribution(pkg_name).version
c72e1d09cf50cbcf2a9f1f4dd0f462c1e0cdac6c
224,462
def arr2str(arr): """Convert numpy 1D array into single string of spaced numbers.""" return " ".join(map(str, list(arr)))
44d9fb4ce0513945bf61da525bda8faed738d223
540,177
def clean_strains_with_bad_dates(ird_df): """ Removes strains that have bad dates (i.e. only MM-YYYY or YYYY). """ ird_df['date_length'] = ird_df['Collection Date'].str.split('/').str.len() ird_df = ird_df[ird_df['date_length'] == 3] return ird_df
9cda8c0d50cff313614170035f8fdf2c88cd7ce9
587,879
def mapped_ipv6_to_ipv4(hex): """ For converting ipv4 addresses mapped to ipv6 back to ipv4 :param hex: ipv6 address without the '00000000:00000000:0000FFFF:' prefix :return: String containing the ipv4 address """ grouped = [hex[i:i + 2] for i in range(0, len(hex), 2)] return '.'.join(list(map(lambda x: str(int(x, 16)), grouped)))
a79a5de9b7900dc5834b8e7eb27e9fd25aa9873d
378,861
def update_analyze_button(disabled): """ Updates the color of the analyze button depending on its disabled status :param disabled: if the button is disabled """ if not disabled: style = {"width": "100%", "text-transform": "uppercase", "font-weight": "700", "background": "green", "outline": "green"} else: style = {"width": "100%", "text-transform": "uppercase", "font-weight": "700"} return style
5a0056879fd5ecde05b7b4fbadbeb7e3aeb1d679
46,228
def is_simple_requires(requires): """ Return True if ``requires`` is a sequence of strings. """ return ( requires and isinstance(requires, list) and all(isinstance(i, str) for i in requires) )
d13c9fe631c32677fbf2be55fd7c048ed566f950
635,956
def publication_to_md(publication: dict) -> str: """ This function outputs a Markdown string for a publication ({"title": ..., "author": ..., "title": ...}) """ title = publication["title"] year = publication["year"] authors = publication["authors"] md = f"- **{title}** ({year})\n" md += f" - {authors}\n" return md
7af0b0fd718525abd7250e27d39dc9e2fc8495c8
214,936
def letters_swap(word1: str, word2: str) -> bool: """Returns True if two words have only two letters swapped. """ counter = 0 for i in range(len(word1)): if word1[i] != word2[i]: counter += 1 if counter != 2: return False else: return True
c191541ad4f542595aada52d789458b99ba4a083
481,786
def append_locations_work_orders(config): """ Append multiple work location points to each work order """ work_orders = config["work_orders_signs"]["records"] spec_actuals = config["work_orders_signs_asset_spec_actuals"]["records"] join_field = config["work_orders_signs_asset_spec_actuals"]["work_order_id_field"] for wo in work_orders: geometries = [] wo_id = wo.get(join_field) for sp in spec_actuals: if sp.get(join_field) == wo_id: x = sp.get("x") y = sp.get("y") if x and y: geometries.append((x, y)) # not that `points` key is required by arcgis geometry spec for multipoint features # https://developers.arcgis.com/documentation/common-data-types/geometry-objects.htm wo["points"] = geometries return work_orders
13d41972a9889a19889cf47d1c7889c952fd9512
447,909
import math def floor(value): """Rounds a number down to the nearest whole number.""" return math.floor(value)
ae79c659bbdb157c2d79e7bb7ba1747ef19ada1c
643,823
def _get_01_coords(x): """ Returns the coordinates normalised to (0,1). """ x1 = x[0][0] x2 = x[0][1] x3 = float(x[1]) / (194.0 - 103.0) x4 = x[2] - 10.0 return [x1, x2, x3, x4]
eb44417d3510638fda02d3612f2eca4eac37d25e
445,354
def series_sum(n): """Sum of first nth term in series and return float value.""" total_series = 0.00 for x in range(n): total_series += float(1) / (1 + (x * 3)) total_series_decimal = ('{0:.2f}'.format(total_series)) return total_series_decimal
d383b32638ef113d581cac6e30e619956e181961
651,297
def test_create_dataframe(data, columns, types, rows_allowed): """ Tests whether the data in a dataframe match the column name, data type, and row count constraints. Extended description of function. Parameters: data (pandas.dataframe): Data loaded from a publicdata source (911 CSV from data.seattle.gov, in this case). columns(list): The header columns expected from the given data. types(list): The data types (after loading from CSV) from the given data. row_allowed(int): A row count that the dataframe must equal or surpass. In this case, 10 is tested. Returns: Boolean: Whether data passes all tests. """ passed = sorted(data.columns.values.tolist()) == sorted(columns) if passed: passed = sorted(data.dtypes.tolist()) == sorted(types) if passed: passed = data.shape[0] >= rows_allowed return passed
1e27efc5e31fb933763e1ee3d64d35537e34c283
585,152
def exception_message(exc): """ Take an exception and return an error message. The message includes the type of the exception. """ return '{exc.__class__.__name__}: {exc}'.format(exc=exc)
f8ec26ba3fc82e436f32f6c527deb2d8da9b90dc
233,182
def column(matrix, i): """ Gets column of matrix. INPUTS: Matrix, Int of column to look at RETURNS: Array of the column """ return [row[i] for row in matrix]
ab7fba90b5f87486a7f52ba3f8aad5c0047ecad9
685,172
import json def dict_to_binary(json_dict: dict) -> bytes: """ Encode the json file to utf-8 :param json_dict: dict :return: json """ return json.dumps(json_dict).encode('utf-8')
dfb5c64342fa232379ebbbd9d7a69b1b7b93cf32
128,443
import socket import errno def mock_server_receive(sock, length): """Receive `length` bytes from a socket object.""" msg = b'' while length: chunk = sock.recv(length) if chunk == b'': raise socket.error(errno.ECONNRESET, 'closed') length -= len(chunk) msg += chunk return msg
1f9071e453ac617754b8b09cc36293a6d9e51dcb
611,807
def quaternion_multiply(r, q): """Multiplies two quaternions. Parameters ---------- r : list Quaternion as a list of four real values ``[rw, rx, ry, rz]``. q : list Quaternion as a list of four real values ``[qw, qx, qy, qz]``. Returns ------- list Quaternion :math:`p = rq` as a list of four real values ``[pw, px, py, pz]``. Notes ----- Multiplication of two quaternions :math:`p = rq` can be interpreted as applying rotation :math:`r` to an orientation :math:`q`, provided that both :math:`r` and :math:`q` are unit-length. The result is also unit-length. Multiplication of quaternions is not commutative! References ---------- .. _mathworld quaternion: http://mathworld.wolfram.com/Quaternion.html """ rw, rx, ry, rz = r qw, qx, qy, qz = q pw = rw*qw - rx*qx - ry*qy - rz*qz px = rw*qx + rx*qw + ry*qz - rz*qy py = rw*qy - rx*qz + ry*qw + rz*qx pz = rw*qz + rx*qy - ry*qx + rz*qw return [pw, px, py, pz]
da51aa780e90e46844086e06ff6b9e44c005a66c
220,621
def build_dataset_attributes_json_object(output_files, container_name, num_files, num_multi_page, percentage_multi_page): """ :param output_files: The files to output :param container_name: The storage container name :param num_files: The number of files processed :param num_multi_page: The number of multi-page forms :param percentage_multi_page: The % of forms that are multi-page :return: The output files object """ output_files[container_name].append({ 'numberInvoices': num_files, 'numMultipage': num_multi_page, 'percentageMultipage': percentage_multi_page }) return output_files
f49a1f4dbd15d49aea228c9689de4cd3a053b0a1
594,248
def get_float(fields, key): """Convert a string value to a float, handling blank values.""" value = fields[key] try: value = float(value) except ValueError: value = 0.0 return value
53629f5d8fa2c23ed19d97612e9adb3dc7299496
503,718
from typing import Any from typing import Optional import textwrap def add_prompt_alt(prompt: str, value: Any, max_width: Optional[int] = None, indent: str = ' ') -> str: """ Returns the ``str()`` of a value with a prompt prepended. This uses a different style from `add_prompt`: - If the value's string representation is single-line, and the whole result fits within the given max_width, then the prompt will just be prepended to the value. - Otherwise, the prompt will appear on the first line, and the value representation will follow on subsequent lines, indented so as to stand out. """ value_repr = str(value) if ('\n' not in value_repr) and ((max_width is None) or (len(prompt) + len(value_repr) <= max_width)): return prompt + value_repr else: return prompt.rstrip() + '\n' + textwrap.indent(value_repr, indent)
ad68efda5033e82b3da2873a06a68f7689712983
237,147
def find_project_dir(runpath): """ Scans up directories until it finds the project folder. :param runpath: pathlib.Path, where summit_core is called from. :return: pathlib.Path, the base project directory """ runpath = runpath.resolve() if runpath.name == "Summit" or runpath.name == 'summit_master': return runpath else: runpath = runpath / '..' return find_project_dir(runpath)
bb77ab81d5b3c08baa06fdabbae6afad5b120b59
110,025
def interpolate(a, b, v, doRound=False): """Answers the interpolated value of factor v between a and b. If doRound is True (default is False), then round the result before answering it.""" i = a + (b-a) * v if doRound: i = int(round(i)) return i
b385bece155f2b16dbb88b8c0f1a72e53e83ea9f
430,199
import socket def get_local_ip(target=None): """ Get the "public" IP address without sending any packets. :param target: Since the host might have different interfaces, we want to know the IP address that will be used to connect to "target", not just the "default gateway" IP address. :return: The IP address. """ connect_target = '4.4.4.2' if target is None else target try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP is connection-less, no packets are sent to 4.4.4.2 # I use port 80, but could use any port sock.connect((connect_target, 80)) local_address = sock.getsockname()[0] except Exception: return None else: return local_address
9fcac8ae9c8b6f93c4ec7878d9fd9d3016b0f174
326,738
import re def any_char_matches(substring: str, mainString: str): """Scans the string for any matches a certain pattern. Parameters ---------- substring : str The string that is used to find matches from `mainString`. mainString : str The `mainstring` which contains the original string. Returns ------- is_matching : bool Returns `True` if the `substring` matches with the `mainSting` else `False`. """ is_matching = bool(re.search(substring, mainString)) return is_matching
b0db76f9f7ed34cd45ba118c758944afbb7b0090
47,681
def text_color(message='{}', color_code='\033[0;37m'): """Set text to a color, default color is White""" no_color = '\033[0m' return f'{color_code}{message}{no_color}'
bede08b771b33ce26bbb0ee4fd42f3712d224cc1
10,301
def HamSN1D_Hamiltonian(t, u): """ Returns Hamiltonian for the 1DoF saddle-node model. Functional form: H = y**2/2 + x**3/3 + x**2/2, with u = (x, y). Parameters ---------- t : float Time. (This Hamiltonian is independent of time.) u : ndarray, shape(n,) Points in phase space. Returns ------- H : ndarray, shape(n,) Hamiltonian at points u, in phase space at time t. """ x, y = u.T return 0.5*y*y + x**3/3 + 0.5*x*x
ca29fb9b7d470b112a2337b084232a61ab190c8e
445,826
def str2bool(string): """ Convert string to corresponding boolean. - string : str """ if string in ["True","true","1"]: return True elif string in ["False","false","0"]: return False else : return False
87ef46e919aa40d656df16a5df6c2ce9932c9058
141,532
def unnest_lists(lists): """ [[0,1], [2]] -> [0,1,2] """ return [entrie for sublist in lists for entrie in sublist]
4f2554bec87bc885de8cc1bda8e710855c6a2105
491,301
def get_plural(val_list): """ Get Plural: Helper function to return 's' if a list has more than one (1) element, otherwise returns ''. Returns: str: String of 's' if the length of val_list is greater than 1, otherwise ''. """ return 's' if len(val_list) > 1 else ''
b86387cb2abd3c5176f5dcefbf7bc3e1a49a346c
17,535
from typing import List def str2ngrams(string: str) -> List[str]: """Converts a string to a list of ngrams (monogram, bigram, trigram).""" ngrams = string.split() # monograms token_list = string.split() if len(token_list) > 2: ngrams += [ w1 + " " + w2 + " " + w3 for w1, w2, w3 in zip(token_list[:-2], token_list[1:-1], token_list[2:]) ] # trigrams if len(token_list) > 1: ngrams += [ w1 + " " + w2 for w1, w2 in zip(token_list[:-1], token_list[1:]) ] # bigrams return ngrams
9f4e85766553fcef21222a849507dfea38b471dd
525,033
def validMoves(b): """Create a list of valid moves.""" return [i for i, v in enumerate(b) if v == ' ']
577899dc17af340d3000609f59954966e26da3d8
226,194
def lookUpGeometry(geom_type): """ converts ArcRest API geometry name to Python names Input: geom_type - string - name of geometry Output: name of python geometry type for create feature class function """ if geom_type == "esriGeometryPoint": return "POINT" elif geom_type == "esriGeometryPolygon": return "POLYGON" elif geom_type == "esriGeometryLine": return "POLYLINE" else: return "POINT"
eb4308894de3550602fcf4310d0e2ae701b0f86d
521,772
def find_nth(string, substring, n): """Finds the index of the nth instance of the given substring from the given string""" location = string.index(substring) while n > 1: location = string.index(substring, location+len(substring)) n -= 1 return location
8e590bc657172f7e526d225fe64adebf24be742a
516,604
def range_data_nomerge(main_data, added_data): """ Take main data and then update clusters with the added data only if they do not already exist. Return only the valid clusters (not full set) """ ret_data = {} for cluster in added_data: if main_data.get(cluster) is None: ret_data[cluster] = added_data[cluster] return ret_data
336b0a54524962bb00c8b82f4ebfae42da013698
121,859
def flip(axis): """Returns the opposite axis value to the one passed.""" return axis ^ 1
72dbe4fdc8f0d203b56bddc50c59ade23f37a7a0
64,819
def process_covid_json_data(local_json: dict, national_json: dict) -> dict: """Returns a dictionary of specified metrics based on the JSON files of local and national COVID data The specified metrics are: total cumulative deaths, current hospital cases, the 7-day infection rate for the national data set, and the 7-day infection rate for the local data set """ deaths_total = None hospitalCases = None national_7day_infections = 0 local_7day_infections = 0 counter = 0 skipped_first_day = False for date in national_json.keys(): current_data = national_json[date] # For cumDeaths and hospitalCases, find the first non-empty cells and use these values if current_data["cumDeaths"] is not None and deaths_total is None: deaths_total = current_data["cumDeaths"] if current_data["hospitalCases"] is not None and hospitalCases is None: hospitalCases = current_data["hospitalCases"] # Add up all the non-empty rows of 'newCases' until we have 7 (ie a week's worth of data) if current_data["newCases"] is not None and counter < 7: # Skip first day of COVID data as it is incomplete if skipped_first_day: national_7day_infections += current_data["newCases"] counter += 1 else: skipped_first_day = True counter = 0 skipped_first_day = False for date in local_json.keys(): current_data = local_json[date] if current_data["newCases"] is not None and counter < 7: if skipped_first_day: local_7day_infections += current_data["newCases"] counter += 1 else: skipped_first_day = True covid_data_dictionary = { "local_7day_infections": local_7day_infections, # local case total in the last 7 days "national_7day_infections": national_7day_infections, # national case total in the last 7 days "hospitalCases": hospitalCases, # current amount of hospitalised cases "deaths_total": deaths_total, # current amount of cumulative deaths } return covid_data_dictionary
0940f0ed82a9b0df39c7d32c0156ac3cd7a058f0
70,478
def rasterFromDataset(dataset): """ Reads all raster bands from a dataset and returns them as a NumPy ndarray of shape (h,w[,c]) """ raster = dataset.ReadAsArray() if len(raster.shape) > 2: raster = raster.transpose((1, 2, 0)) return raster
96163658b836c5da4cd97004bdf2564b1c0b44b5
280,875
def is_int(number): """Return if a number can be represented as an integer.""" return int(number) == number
7e32fa9e07d6b88aec386f598d47f90b7077d3a6
537,792
def unscale_coordinates(point, M): """ Unscale coordinates by M :param point: Point :param M: Scaling factor :return: Unscaled points """ return point * M
b528625c7a7d1f9ef135609d1d22fd7b2faeb756
622,859
def ConstantAddition(s, t, scheme): """ ConstantAddition function from LowMC spec. :params s: state :params bs: round constants :params t: round :param scheme: lowmc parametrization + constants """ return [s[i] ^ scheme['b'][t-1][i] for i in range(scheme['blocksize'])]
d9774db5e5c1ded9b5166e03b62154a806bd637d
325,477
def get_spatial_cell_id(dataset_uuid:str, tile_id:str, mask_index:int)->str: """Takes a dataset uuid, a tile_id within that dataset, and a mask_index number within that tile to prodduce a unique cell ID""" return "-".join([dataset_uuid, tile_id, str(mask_index)])
58e5bc01f973d38de831ec4f54c782c57e3ea825
469,779
def combine_prediction_metadata_batches(metadata_list): """Combines a list of dicts with the same keys and lists as values into a single dict with concatenated lists for each corresponding key Args: metadata_list (list): list of dicts with matching keys and lists for values Returns: dict: combined single dict """ combined_metadata = {} for metadata_batch in metadata_list: for meta_el in metadata_batch: if meta_el not in combined_metadata: combined_metadata[meta_el] = [] combined_metadata[meta_el] += metadata_batch[meta_el] return combined_metadata
28fd647b19e5affa3f04c7909a4ba7ff17993da1
615,866
import json def get_json_key(filepath: str, keyname: str): """ Gets a json file key from specified filepath and keyname """ with open(filepath, "r") as f: data: dict = json.load(f) return data.get(keyname)
c0bbca6bcdc039cdec26a9a8e655b56e5dab1637
178,494
def clean_word(word: str) -> str: """Return all alphanumeric characters from word, in the same order as they appear in word, converted to lowercase. >>> clean_word('') '' >>> clean_word('AlreadyClean?') 'alreadyclean' >>> clean_word('very123mes$_sy?') 'very123messy' """ cleaned_word = '' for char in word.lower(): if char.isalnum(): cleaned_word = cleaned_word + char return cleaned_word
552731e601ff7dca2f9d6f71cfb15cc252e1b616
167,658
def factorial_iter(num: int) -> int: """ Return the factorial of an integer non-negative number. Parameters ---------- num : int Raises ------ TypeError if num is not integer. ValueError if num is less than zero. Returns ------- int """ if not isinstance(num, int): raise TypeError("an integer number is required") if num < 0: raise ValueError("a non-negative integer number is required") product = 1 for factor in range(2, num + 1): product *= factor return product
36ec433bf02bdef0770f9f9b86feff9afa995eb3
702,663
def __partition2way__(arr, lo, hi): """ Function to achieve 2-way partitioning for quicksort 1. Start with 2 pointers lt and gt, choose first element (lo) as pivot 2. Invariant: everything to the left of lt is less than pivot, right of gt is larger than pivot 3. In each iteration, do the following in order: (a) Increment lt until arr[lt] >= arr[lo] (b) Decrement gt until arr[gt] <= arr[lo] (c) Check if pointers have crossed (gt<=lt), if yes then swap arr[lo] with arr[gt] and break out (d) If pointers didn't cross, then swap arr[lt] with arr[gt] 4. Return the index of the pivot (now gt) so that it can be used by __quicksortHelper__ """ if lo >= hi: return # Define lt and gt pointers lt = lo gt = hi + 1 while True: while lt < hi: lt += 1 if arr[lt] >= arr[lo]: # print("Break lt at ", lt) break while gt > lo: gt -= 1 if arr[gt] < arr[lo]: # print("Break gt at ", gt) break if gt <= lt: arr[lo], arr[gt] = arr[gt], arr[lo] break if arr[lt] > arr[gt]: # print(f"swap {arr[lt]} with {arr[gt]}") arr[lt], arr[gt] = arr[gt], arr[lt] # print(arr) return gt
2177bea6e30273ea5bb04d77e8df03516938217b
407,634
def page_type(content): """ Evaluate the request content and identify the type of the page. Args: content (str): page content to analyse. Returns: "album" if a track list was detected. "discography" if a set of albums and tracks was found. "track" if the above do not apply but a Bandcamp page was still identified. "none" if the supplied page is not a Bandcamp page. """ if "bandcamp.com" in content: if "Digital Album" and "track_list" in content: return "album" elif 'id="discography"' not in content: return "discography" else: return "track" else: return "none"
15cc73db157aaf3f86111a011e50704742f3a1b6
159,226
def cast_logo(instance, filename: str) -> str: """ Generate cast logo filename from cast slug """ return f"casts/{instance.slug}/logo.{filename.split('.')[-1]}"
99fb2860cc9ea8d7f4cd3d15afd1ba76d2abe56f
474,215
def count_params(model): """Count the number of parameters in the model""" param_count = sum([p.numel() for p in model.parameters()]) return param_count
bdaaed08a9d4f8bc265b3f0063ea7d1271c260b1
514,813
import hashlib def blake2b(filename: str) -> str: """Get blake2b digest for a file. Args: filename (str): The file to get a blake2b digest of. Returns: str: A blake2b hexdigest. """ with open(filename, "rb") as f: file_hash = hashlib.blake2b() while chunk := f.read(8192): file_hash.update(chunk) return file_hash.hexdigest()
a6dfca323324ce1f77bb086a7617e6a3eceb3d98
341,879
def camelCaseIt(snake_str): """ transform a snake string into camelCase Parameters: snake_str (str): snake_case style string Returns camelCaseStr (str): camelCase style of the input string. """ first, *others = snake_str.split('_') return ''.join([first.lower(), *map(str.title, others)])
691bbcaa12c8065e363e8b7c430f25bc44d370c5
549,481
def get_table_list(dbconn): """ Get a list of tables that exist in dbconn :param dbconn: database connection :return: List of table names """ cur = dbconn.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table';") try: return [item[0] for item in cur.fetchall()] except IndexError: return get_table_list(dbconn)
fb1f4cac07b7260852c3c8387f702bc7b3b4f423
331,789
def dict2conll(data, predict): """Writes conll string in file""" with open(predict, 'w') as CoNLL: CoNLL.write(data['conll_str']) CoNLL.close() return None
3fee99010656052597dc1f1ea34d04c20d053f53
398,898
from typing import Optional def _term_converter(term: Optional[int]) -> Optional[int]: """ Converter function for ``term`` in :class:`~.BaseProduct``. :param term: The number of months that a product lasts for if it is fixed length. """ if term is None: return None else: return int(term)
65277a31fe4666d410c9aa46a8b01fe59dbcb4fc
31,322
import re def tokenize(xs, pattern="([\s'\-\.\,\!])"): """Splits sentences into tokens by regex over punctuation: ( -.,!])[""" return [x for x in re.split(pattern, xs) if not re.match("\s", x) and x != ""]
10e9eae492f4ca6993e22fe7b567c934f33b6d8b
489,500
def ramp_function(t_list, start_value, end_value): """ Returns a function that implements a linear ramp from start_value to end_value over the time domain present in (an ordered) t_list """ rate = (end_value - start_value) / (t_list[-1] - t_list[0]) ftn = lambda t: start_value + (t - t_list[0]) * rate return ftn
64699a93a14609ebc00e6d1b215c3096ad636b3c
413,233
import csv def _load_params(file_path): """ Loading the hyperparameters from specific file. Parameters ---------- file_path : str File path of config files Returns ------- List of parameter dict """ config_list = [] exp_name = file_path.split("/")[-1].replace(".csv", "") with open(file_path, 'r+') as f: reader = csv.reader(f) for agent_config in reader: try: params_dict = {"name": agent_config[0], "model": agent_config[1], "batch_size": int(agent_config[2]), "gamma": float(agent_config[3]), "eps_start": int(agent_config[4]), "eps_end": float(agent_config[5]), "eps_decay": int(agent_config[6]), "target_update": int(agent_config[7]), "default_durability": int(agent_config[8]), "learning_rate": float(agent_config[9]), "initial_memory": int(agent_config[10]), "n_episode": int(agent_config[11]), "roulette_mode": str(agent_config[12]), "n_action": int(agent_config[13]), "default_durability_decreased_level": int(agent_config[14]), "default_durability_increased_level": int(agent_config[15]), "default_check_frequency": int(agent_config[16]), "default_healing_frequency": int(agent_config[17]), "env_name": agent_config[18], "exp_name": agent_config[19], "render": bool(agent_config[20]), "run_name": agent_config[21], "output_directory_path": agent_config[22], "hyper_dash": bool(agent_config[23]), "model_saving_frequency": int(agent_config[24]), "max_reward": float(agent_config[25]), "min_reward": float(agent_config[26])} config_list.append(params_dict) except ValueError: pass return config_list, exp_name
eb9a816c927b174ed3a0c35aa1ac2b367353f950
279,888
def table_with_9999_columns_10_rows(bigquery_client, project_id, dataset_id): """Generate a table of maximum width via CREATE TABLE AS SELECT. The first column is named 'rowval', and has a value from 1..rowcount Subsequent columns are named col_<N> and contain the value N*rowval, where N is between 1 and 9999 inclusive. """ table_id = "many_columns" row_count = 10 col_projections = ",".join(f"r * {n} as col_{n}" for n in range(1, 10000)) sql = f""" CREATE TABLE `{project_id}.{dataset_id}.{table_id}` AS SELECT r as rowval, {col_projections} FROM UNNEST(GENERATE_ARRAY(1,{row_count},1)) as r """ query_job = bigquery_client.query(sql) query_job.result() return f"{project_id}.{dataset_id}.{table_id}"
a37d5bf66cf5cf0e300c1d1209aabc0b0cf2e670
113,337
def dimension(x): """ Return the dimension of ``x``. EXAMPLES:: sage: V = VectorSpace(QQ,3) sage: S = V.subspace([[1,2,0],[2,2,-1]]) sage: dimension(S) 2 """ return x.dimension()
e2ebc115b88d83e6ea1ec81a6f27fece0df4f9be
204,558
import uuid def get_random_string(length: int = 32) -> str: """ This function returns an alphanumeric string of the requested length. :param int length: the length of the random string. Max of 32 characters :returns: a random string :rtype: str """ if length > 32: length = 32 elif length <= 0: length = 1 random_string = uuid.uuid4().hex return random_string[:length]
62e5682d01bef4bba86498a073c5942e5f0ee96c
424,791
import re def _parse_lambda(text): """Parse the definition of a lambda function in to a readable string.""" text = text.split('lambda')[1] param, rest = text.split(':') param = param.strip() # There are three things that could terminate a lambda: an (unparenthesized) # comma, a new line and an (unmatched) close paren. term_chars = [',', '\n', ')'] func_text = '' inside_paren = 0 # an int rather than a bool to keep track of nesting for c in rest: if c in term_chars and not inside_paren: break elif c == ')': # must be inside paren inside_paren -= 1 elif c == '(': inside_paren += 1 func_text += c # Rename the lambda parameter to 'value' so that the resulting # "description" makes more sense. func_text = re.sub(r'\b{}\b'.format(param), 'value', func_text) return func_text
7f026e685fdb1f5f72c4a5195acf46f22c42cb44
196,260
import re from typing import Tuple def parse_version_string(name: str) -> Tuple[str, str]: """Parse a version string (name ID 5) and return (major, minor) strings. Example of the expected format: 'Version 01.003; Comments'. Version strings like "Version 1.3" will be post-processed into ("1", "300"). The parsed version numbers will therefore match in spirit, but not necessarily in string form. """ # We assume ";" is the universal delimiter here. version_entry = name.split(";")[0] # Catch both "Version 1.234" and "1.234" but not "1x2.34". Note: search() # will return the first match. version_string = re.search(r"(?: |^)(\d+\.\d+)", version_entry) if version_string is None: raise ValueError("The version string didn't contain a number of the format" " major.minor.") major, minor = version_string.group(1).split('.') major = str(int(major)) # "01.123" -> "1.123" minor = minor.ljust(3, '0') # "3.0" -> "3.000", but "3.123" -> "3.123" return major, minor
0680cd64e28c7ddb5c0aeae5cb868387c8bd5a35
663,011
import time def task_symbols(storage): """ Task that prints first character of contents of storage["symbol"] forever. """ sym = storage.get("symbol", ".") print(sym[0], sep=" ", end="", flush=True) time.sleep(.25) return True
11982a69cd318d98b122350df3044fad7a6b87c5
330,412
def gcdr(a, b): """Recursive Greatest Common Divisor algorithm.""" if b == 0: return a if a<b: a,b = b,a print(a,b) return gcdr(b, a%b)
7edd0742f2f57dbed839b345067df734ec5e4544
645,120
from typing import List import random def _get_random_values(n_instants: int, items_per_instant: int) -> List[List[float]]: """Generates the list of items values randomly. """ return [[random.random() for _ in range(items_per_instant)] for _ in range(n_instants)]
7efcf657e8038de5f12c32d277a8da05b0264ad5
196,994
def yrotate(p, theta): """Return a new vector after performing a rotation on p around the y axis""" p = p.copy() return p.yrotate(theta)
2d32bb35aae8d69fc7767c60926d39ffa926553e
453,478
def toggles_block_quote(line): """Returns true if line toggles block quotes on or off (i.e. finds odd number of ```)""" n_block_quote = line.count("```") return n_block_quote > 0 and line.count("```") % 2 != 0
0223c487cfc0139aa6c96ecbd2559c45ad0b2fd5
495,877
import re def normalize(string): """Replace all invalid characters with "_" :param string string: A string to normalize. :return string: Normalized string """ string = str(string) if re.match("^[0-9]", string): string = "_" + string return re.sub("[^A-Za-z0-9_-]", "_", str(string))
a67ed717daad92f500582bcde7abc3344c281a32
428,893
def make_unique(qs, unique_var): """Make the queryset unique by unique_var, sort by unique_var""" if hasattr(qs, "distinct"): # Need to check so that this does not break in Preview mode in Wagtail distinct_pks = qs.distinct(unique_var).order_by(unique_var).values_list('pk', flat=True) return qs.filter(pk__in=distinct_pks) else: return qs
62b1bb9453d6eba885906ec3c67851a75a5f781d
127,736
def query_transform(request, **kwargs): """Alter parameters in a query string while keeping the rest.""" updated = request.GET.copy() for field, value in kwargs.items(): updated[field] = value return updated.urlencode()
c7745875944aecae6afbda81646f3cf5b1a21e1e
379,347
def is_ugly(num, factors=(2, 3, 5)): """ Check whether a given number is an ugly number :param num: given number :type num: int :param factors: prime factors for ugly number :type factors: list[int] or tuple[int] :return: whether a given number is an ugly number :rtype: bool """ if num == 1: return True elif num <= 0: return False for factor in factors: while num % factor == 0: num //= factor return num == 1
8f343ef6b9d382cbea778acc7d55c95ffcbdd4c1
108,304
import re import itertools import random def generate_spintax(text, single=True): """Return a list of unique spins of a Spintax text string. Args: text (string): Spintax text (i.e. I am the {President|King|Ambassador} of Nigeria.) single (bool, optional): Optional boolean to return a list or a single spin. Returns: spins (string, list): Single spin or list of spins depending on single. """ pattern = re.compile('({[^}]+}|[^{}]*)') chunks = pattern.split(text) def options(s): if len(s) > 0 and s[0] == '{': return [opt for opt in s[1:-1].split('|')] return [s] parts_list = [options(chunk) for chunk in chunks] spins = [] for spin in itertools.product(*parts_list): spins.append(''.join(spin)) if single: return spins[random.randint(0, len(spins) - 1)] else: return spins
a3635958fad90ace9592f3e32c4d0a2b3c29a152
77,912
def h(params, sample): """This evaluates a generic linear function h(x) with current parameters. h stands for hypothesis Args: params (lst) a list containing the corresponding parameter for each element x of the sample sample (lst) a list containing the values of a sample Returns: Evaluation of h(x) """ acum = 0 for i in range(len(params)): acum = acum + params[i]*sample[i] #evaluates h(x) = a+bx1+cx2+ ... nxn.. return acum
4267ba1499eb6863cdc32a9b3572afd196599105
621,196
def make_uniform(planes_dict, uniques, padding): """ Ensure each section has the same number of images This function makes the output collection uniform in the sense that it preserves same number of planes across sections. It also captures additional planes based on the value of the padding variable Args: planes_dict (dict): planes to keep in different sections uniques (list): unique values for the major grouping variable padding (int): additional images to capture outside cutoff Returns: dictionary: dictionary containing planes to keep """ # max no. of planes max_len = max([len(i) for i in planes_dict.values()]) # max planes that can be added on each side min_ind = min([min(planes_dict[k]) for k in planes_dict]) max_ind = max([max(planes_dict[k]) for k in planes_dict]) max_add_left = uniques.index(min_ind) max_add_right = len(uniques) - (uniques.index(max_ind)+1) # add planes in each section based on padding and max number of planes for section_id, planes in planes_dict.items(): len_to_add = max_len - len(planes) len_add_left = min(int(len_to_add)/2+padding, max_add_left) len_add_right = min(len_to_add - len_add_left+padding, max_add_right) left_ind = int(uniques.index(min(planes)) - len_add_left) right_ind = int(uniques.index(max(planes)) + len_add_right)+1 planes_dict[section_id] = uniques[left_ind:right_ind] return planes_dict
8f67f7226dcf8846707f9d190eb9b15ccb1b27e9
695,700
import re def hex_to_rgb(hx, hsl=False): """Converts a HEX code into RGB or HSL. Args: hx (str): Takes both short as well as long HEX codes. hsl (bool): Converts the given HEX code into HSL value if True. Return: Tuple of length 3 consisting of either int or float values. Raise: ValueError: If given value is not a valid HEX code.""" if re.compile(r'#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$').match(hx): div = 255.0 if hsl else 0 if len(hx) <= 4: return tuple(int(hx[i]*2, 16) / div if div else int(hx[i]*2, 16) for i in (1, 2, 3)) return tuple(int(hx[i:i+2], 16) / div if div else int(hx[i:i+2], 16) for i in (1, 3, 5)) raise ValueError(f'"{hx}" is not a valid HEX code.')
f0c197be38e93d8c0afe528ba40a5a6b74b7adb6
226,263
def get_reactions_producing(complexes, reactions): """ dict: maps complexes to lists of reactions where they appear as a product. """ return {c: [r for r in reactions if (c in r.products)] for c in complexes}
a695141f35190abd6248d112f0b7bc2f1a89770f
286,893
def get_default_simulation_kwargs(amp=None, model=None): """ Returns default keyword arguments to set up a basic stimulus in a simulations Doesn't include amp as this usually needs to calculated (e.g. to find rheobase) or set to a specific value. """ default_kwargs = { 'dur':500., 'delay':1000., 'interval':0., 'num_stims':1, 't_stop':1500., 'mechanisms':None, 'make_plot':False, 'plot_type':'default'} if amp: default_kwargs['amp'] = amp if model: default_kwargs['model'] = model return default_kwargs
066f676321fd5fecb9e84e3359dc2c976fb9ad67
434,232
def neighbors(lines, of): """Find the indices in a list of LineStrings that touch a given LineString. Args: lines: list of LineStrings in which to search for neighbors of: the LineString which must be touched Returns: list of indices, so that all lines[indices] touch the LineString of """ return [k for k, line in enumerate(lines) if line.touches(of)]
37aabaab8686911baf0ef6f93170a8b3422c6f09
443,425
def add_key(udict, key, value): """Add a new key:value combo to dict """ cdict = dict(udict) cdict[key] = value return cdict
6dfca9df39056d24ce51187ca89eb8e3f2bd5857
138,662
def take(arr: list, n: int) -> list: """ Accepts a list/array and a number n, and returns a list/array array of the first n elements from the list/array. :param arr: :param n: :return: """ return arr[:n]
b23d5c169934b52647c77a9fb7b8c9c0cfb48bd2
276,634
def nmiles_to_km(N): """convert nautical miles to km""" N = N * 1.852 return N
fc8fe240f179bd1166c6e2a6fe05679831a75a81
203,438
import re def extract_path(path_string): """Convert a path string to a list of names""" return re.findall(r"[^/\\]+", path_string)
85f6894688f458aaa4d8bf168f9a667c8ef2cc01
636,357
import inspect def _filter_class_attributes(path, parent, children): """Filter out class attirubtes that are part of the PTransform API.""" del path skip_class_attributes = { "expand", "label", "from_runner_api", "register_urn", "side_inputs" } if inspect.isclass(parent): children = [(name, child) for (name, child) in children if name not in skip_class_attributes] return children
b9911c076dc7aafcfbda0f7dcf197982ed8067a3
646,662
def compute_start_end(dataset_str, thread): """ calculate start and end points for multi_threading """ individuals_number = dataset_str.shape[0] number_each_thread = int(individuals_number/thread) start = [number_each_thread * i for i in range(thread)] end = start[1:] end.append(individuals_number) return start, end
cc1fcebc71b2e82876b98db33a80954306f4526b
74,172
def total_length(neurite): """Neurite length. For a morphology it will be a sum of all neurite lengths.""" return sum(s.length for s in neurite.iter_sections())
854429e073eaea49c168fb0f9e381c71d7a7038a
708,330
import json def load_default(key): """ Load default configuration. Args: key (str): Find credentials for this key Raises: None Returns: cred (dict): Default configuration """ path = 'securetea.conf' with open(path) as f: creds = json.load(f) return creds[key]
27ba2d56863a33f9f7f8946349d55002e0d9324b
295,968
def get_season(cube): """Return a climatological season time string.""" season = cube.coord('clim_season').points return season[0].upper()
f129cd01f17d8e6f55e1c621ca4a37e70b0ad410
191,863
from typing import Any def make_safe(value: Any) -> str: """ Transform an arbitrary value into a string Parameters ---------- value: Any Value to make safe Returns ------- str Safe value """ if isinstance(value, bool): return str(value).lower() return str(value)
4b342105d26458ddffd20712c777c5bc8e221c81
16,831
def getPositions(mask): """ Get a list of positions where the specified mask has the bit set """ # XXX I don't exactly love this implementation, # but it works. binaryString = bin(mask)[2:] result = [] for index, c in enumerate(binaryString[::-1]): if int(c): result.append(index) return result
f4976a7c900e82e62c7d067d337c6f5db7d269a9
591,997
def select_all(_): """ Returns True for all particles. """ return True
34e277c1ae59a9032e5d09e45cf27732185d9c49
692,810
def run(df, docs): """ drops all rows of the dataframe that contains at least one null :param df: :return: """ for doc in docs: doc.start("t05 - Drop null", df) df.dropna(inplace=True) for doc in docs: doc.end(df) return df
d544b7cbe1d7c0f216d189dd68690b581d3dde1a
413,691
def cell_width(cell_name): """ Set the width of the cells from the pdf report file.""" if cell_name == "No": table_cell_width = 6 elif cell_name == "Phrase": table_cell_width = 73 elif cell_name == "Question": table_cell_width = 57 else: table_cell_width = 25 return table_cell_width
fac9e9dc0f8ad3cac09ed3054a798e7d832cdcc6
36,396
def ff(items, targets): """First-Fit This is perhaps the simplest packing heuristic; it simply packs items in the next available bin. Complexity O(n^2) """ bins = [(target, []) for target in targets] skip = [] for item in items: for target, content in bins: if item <= (target - sum(content)): content.append(item) break else: skip.append(item) return bins, skip
3649d9b7704f36871f320a236cff0115b75689f3
48,071