content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import math def flux_ratio(meas_x, meas_y): """ Calculate the flux ratio between two `heuslertools.mbe.flux_ratio.FluxMeasurement`s. The ratio is calculate with $$\\frac{J_X}{J_Y}=\\frac{BEP_X}{BEP_Y}\\cdot\\frac{\\eta_Y}{\\eta_X}\\cdot\\sqrt{\\frac{T_X M_Y}{T_Y M_X}}$$ """ return (meas_x.bep/...
b008dc81ac4e427cbdab0523376484da66be02f5
637,249
def getFileLocations(years, filings): """ Returns a list with the folder names where the data will be found """ fileLocations = list() for year in years: if filings == ['10-K']: fileLocations.append(year + 'q1/') # only valid if the user wants solely 10-K's as they are filed in Q1 ...
a3fb7b87c524e9c8a75a5931de8ba593e9b5720a
637,250
def stripquotes(s): """ Enforce to be a string and strip matching quotes """ return str(s).lstrip('"').rstrip('"')
be8d1a844065bf5615e0f0a48596d8771b20fd86
637,256
def tuple_to_bool(value): """ Converts a value triplet to boolean2 values From a triplet: concentration, decay, threshold Truth value = conc > threshold/decay """ return value[0] > value[2] / value[1]
cf77add11c993078c8453b139ba05a758b2aff97
637,261
def normalize_module(module): """ Normalize a module name """ return module.lower()
8c27328afcf79c7564365d7e8c64c5b5ded21555
637,263
def split_list_into_chunks(list_to_split, max_entries_per_list): """ Takes a list and splits it up into smaller lists """ chunks = [] for i in range(0, len(list_to_split), max_entries_per_list): chunk = list_to_split[i:i + max_entries_per_list] chunks.append(chunk) return chunk...
826e3745bb703ab567d5ad707c095cfea299113d
637,273
def set_show_hit_test_borders(show: bool) -> dict: """Requests that backend shows hit-test borders on layers Parameters ---------- show: bool True for showing hit-test borders """ return {"method": "Overlay.setShowHitTestBorders", "params": {"show": show}}
32f27ca5e140a07bf76188780b2655d01f4b2f46
637,276
def groupify(data): """ Takes a dict with groups identified by ./ and turns it into a nested dict """ new = {} for key in data.keys(): if "./" in key: group, field = key.split("./") if group not in new: new[group] = {} new[group][field] = d...
59295a90203d8eb7a9af901ab3f62df3132fea27
637,278
def _BinaryElementwiseShape(op): """Returns same shape as both inputs to op. Args: op: Input operation. Returns: Shape of both inputs to `op`. """ return [op.inputs[0].get_shape().merge_with(op.inputs[1].get_shape())]
bf51d2d686772d34ca2dafa4cce7e4a4bdb4a278
637,279
def get_value(data, value): """Retrieve weather value.""" try: if value == "@mps": return round(float(data[value]) * 3.6, 1) return round(float(data[value]), 1) except (ValueError, IndexError, KeyError): return None
dddc1466b8be7c21a79f6bf15c23e6639a29dff5
637,280
def _intersect(rect1, rect2): """ Return True if the two rectangles rect1 and rect2 intersect. """ x1, y1, w1, h1 = rect1 x2, y2, w2, h2 = rect2 return (x1 + w1 > x2 and x2 + w2 > x1) and (y1 + h1 > y2 and y2 + h2 > y1)
ff06ae4d279716acae31823a7fa0021876f3db44
637,282
def load_fb15k_triples(path): """ Loads the raw data from file provided. Args: path: path to the file Returns: triples """ with open(path, 'r') as f: triples = [line.strip('\n').split('\t') for line in f.readlines()] return triples
79a82130c1a61765f259efb3613a5dff3b338fd4
637,284
def apply_update_rules(state, predecessor_node_lists, truth_tables): """ Update network state according to the update rule. :param state: current network state :param predecessor_node_lists: list of predecessor node lists :param truth_tables: list of dicts (key: tuple of predecessor node st...
2951f1f8df9c238af4e43965882384ed66d5584d
637,287
def parse_contour_file(filename): """Parse the given contour filename :param filename: filepath to the contourfile to parse :return: list of tuples holding x, y coordinates of the contour """ coords_lst = [] with open(filename, 'r') as infile: for line in infile: coords = ...
c8fc09dc91fa2b659be2ea0f63ee653670a4b513
637,288
def subset_by_iqr(df, column, iqr_mult=3): """Remove outliers from a dataframe by column, including optional whiskers, removing rows for which the column value are less than Q1-1.5IQR or greater than Q3+1.5IQR. Args: df (`:obj:pd.DataFrame`): A pandas dataframe to subset column (st...
ee34ca064c605fe1c1ff36131c8351dfe95321ef
637,290
import math def get_bounding_box(lat: float, lng: float, radius: float) -> str: """Get bounding box with length of radius * 2 and (lat, lng) as the centre""" offset = radius / 100.0 latMax = lat + offset latMin = lat - offset lngOffset = offset * math.cos(lat * math.pi / 180.0) lngMax = lng +...
85bbc550e75465633bdc441182da4b55c9a15291
637,291
from pathlib import Path def create_output_dir(dir_path: str) -> str: """Creates output directory if it doesn't exits Parameters ----------- dir_path: the output file directory Return ------- dir_path: the output file directory returned for later used """ if not Path(dir_path)...
750f50684b8f8b9fc08fd43a4c4068e9d6169ba2
637,292
def show_sticker_file_id(bot, update, session, chat, user): """Give the file id for a sticker.""" if update.message.reply_to_message is None: return "You need to reply to a sticker to use this command." message = update.message.reply_to_message if message.sticker is None: return "You ne...
4ce00f9b877259023337eeab3d4922b5cba86505
637,293
def factorial(number: int) -> int: """ Calculate the factorial of specified number (n!). >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral val...
af7d0707742bdf9ff39119f7d3b8823b5f3c0bb4
637,295
import csv def csv_to_list(csv_file): """ Function to read a csv file and convert the entries on each row to a list. """ csv_list = set() # Open CSV file for reading as provided to the function with open(csv_file, 'r', newline='') as input_file: input_reader = csv.reader(input_file) ...
a976bfc5da6f06dc43c0ce45ebfd7767f910c213
637,298
def create_function_from_source(function_source, imports=None): """Return a function object from a function source Parameters ---------- function_source : unicode string unicode string defining a function imports : list of strings list of import statements in string form that allow ...
2fa6c5ed6778270a4a2b1c2e02c0203a3d463e10
637,299
def simplify_http_accept_header(accept): """Parse an HTTP Accept header (RFC 2616) into a preferred value. The quality factors in the header determine the preference. Possible media-range parameters are allowed, but will be ignored. This function can also be used for the Accept-Charset, Accept-Enco...
9370a7dc9af20840a9e4f9a9826b65f8bae4f8db
637,300
def Int2Digits(i, base): """ The next function converts the number into a list of digits For example: if base=10, then Int2Digits(126, 10) = [1, 2, 6] if base=2, then Int2Digits(126, 2) = [1, 1, 1, 1, 1, 1, 0] (This function is called by the Number2String() function.) """ if (i < base...
9301f2023623b92db233ac1955b75154a2de9f33
637,306
import re def _is_auspex(path): """ Test if a given file path is an Auspex data file """ path = path.rstrip('/') filename = path.split('/')[-1] if re.findall(r".+.auspex", filename): return True else: return False
a644f14d9c8e7647546efa7f0f63694edd65e951
637,308
def clean_unit_errors(merged_df): """ This function will look in a DataFrame for rows where the height_cat and weight_cat are set to "Unit-Error-High" or "Unit-Error-Low". It will then multiply / divide the height and weight values to convert them. It will also create two new columns: postprocess_heigh...
88a99871cd2987d473d672c700e8972660c17f5b
637,314
def instanceof(obj, classinfo): """Wrap isinstance to only return True/False""" try: return isinstance(obj, classinfo) except TypeError: # pragma: no cover # No coverage since we never call this without a class, # type, or tuple of classes, types, or such typles. return Fals...
a9bb9fe54fe16d58ef8b944708fb837125f31147
637,325
def get_playseq(data, length): """return data read from file as a list of pattern numbers also return highest pattern number """ result = [] highpatt = 0 for bytechar in data[:length]: test = int(bytechar) result.append(test) if test > highpatt: highpatt = te...
6528eaa4bb0f31f1a495c6ff3a4e571b38ae26a4
637,327
import random def get_random_int(start=1, end=1000000): """Get an random integer between start and end inclusive.""" x = random.random() i = int(x*(end + 1 - start) + start) return i
13bf15ac00a2c717540644daa6b36b23cb367dc0
637,329
import torch def _pad_norm(x, implicit=False): """Add a channel that ensures that prob sum to one if the input has an implicit background class. Else, ensures that prob sum to one.""" if implicit: x = torch.cat((1 - x.sum(dim=1, keepdim=True), x), dim=1) return x
4439886e811d2a1e6d5241edc6cc39f0f645019b
637,330
import torch def all_edges(n): """Return a tensor of all (n choose 2) edges Constructs all possible edges among n items. For example, if ``n`` is 4, the return value will be equal to .. code:: python3 torch.Tensor([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]) """ return torch.tr...
b873868959273f87efb0ea31cc65a3f01afcaca7
637,332
def externalarray(file_manager): """ An array of external array references. """ return file_manager.external_array_references
cee20da69b485ef2260e7222135cd58466d8ad49
637,333
def matrix_add(list1, list2): """ Accepts two lists-of-lists of numbers and returns one list-of-lists with each of the corresponding numbers in the two given lists-of-lists added together. Example: >>> matrix1 = [[1, -2], [-3, 4]] >>> matrix2 = [[2, -1], [0, -1]] ...
f95de8387502ff2f244ba0c3e2b6d7fe0763e2bb
637,336
def eratosthenes(n): """ this fxn is the Sieve of Eratosthenes. this algorithm generates a list of positive integers up to a given input n, then removes all multiples of 2, then 3,then 4, and so on until only the numbers that are divisible by 1 and itself are left in the list. and therefore the lis...
a84ddbd257794ca49e65c1d04f9c62a37c47b191
637,338
def _compare(local, remote): """Compare versions.""" if local == remote: return True else: return False
4ad19adc79401deb9a93d3ff32dc58f32a58c4c5
637,342
from datetime import datetime def is_time_in_range(start: datetime, end: datetime, now: datetime): """Return true if now is in the range [start, end]""" if start <= end: return start <= now <= end return start <= now or now <= end
6f5cf0a25723ff65d259746d610f09d810e28330
637,346
def get_interface_connected_adjacent_router_interfaces( device, link_name, num=1 ): """ Get list of connected interfaces from adjacents routers Args: device ('obj'): Device object link_name ('str'): Interface alias in topology num ('int'): Number of interfaces to ret...
534baf2410df4e87a98581429b45347c31f58f7f
637,347
def ainv(x): """Additive inverse""" return -x
4a21c25695539070253277fdc6961e81a9ffb81e
637,348
def scale_pixels(X_np_a, max_pixel_intensity): """Scale pixel values to be in [0, 1] to help gradient-descent optimization. Args: X_np_a (:obj:`numpy.ndarray`): Matrix of pixel intensities max_pixel_intensity (int): normalization constant set by user Returns: matrix of scaled inten...
a0ad7ea7db749236f353bba091c2d2b3fc444d38
637,351
def get_num_classes(self): """ Retrieves the number of classes in dataset """ return len(self.id_to_class_info)
4b51c76d865a97e30d7531c8a05469e5fc8d66d7
637,352
import random def getAction(action_list,action_values,minimax_val): """ Returns a random action of the actions with minmax_val """ req_actions = list() min_val_indexs = [i for i in range(len(action_values)) if action_values[i]==minimax_val] for i in range(len(min_val_indexs)): req_act...
25f3b5c2954709c82f5ea0833400ca4b7ef0c898
637,355
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
import math def damping(temp, relhum, freq, pres=101325): """ Calculates the damping factor for sound in dB/m depending on temperature, humidity and sound frequency. Source: http://www.sengpielaudio.com/LuftdaempfungFormel.htm temp: Temperature in degrees celsius relhum: Relative humidity as ...
6780e2123a5845f238516273b713699cc75b4fe6
637,357
def _paths_to_tree(paths): """Build a tree from the given paths. The structure of the tree is described in the docstring for _prune_paths. """ tree = {} for path in paths: t = tree for c in path: if c not in t: t[c] = {} t = t[c] return t...
35b5a1a7b2b54f85252d1a45a4c59f8b8b9e0b3e
637,358
def is_main(args): """ returns True if process is being run on the main GPU """ return args.local_rank in [0, -1]
95a94a1216b1332d9bd7f5fae153dadf9b5c3d4e
637,363
import re def isHexEncodedString(subject): """ Checks if the provided string is hex encoded >>> isHexEncodedString('DEADBEEF') True >>> isHexEncodedString('test') False """ return re.match(r"\A[0-9a-fA-Fx]+\Z", subject) is not None
359143b15c88d94569e9a690f62d5f055c50cf11
637,373
def num_cat_feature_columns(df): """ Takes a pandas Dataframe (part of the black_friday_data_hack project) as input and separates numerical features from categorical features Arguments: data - DataFrame Returns: tuple of numerical features and categorical features ...
35467a6b4704b8495d8e13d96b26fc2cb75bcd0c
637,376
def trans_data_to_axis(ax): """Compute the transform from data to axis coordinate system in axis `ax`""" axis_to_data = ax.transAxes + ax.transData.inverted() data_to_axis = axis_to_data.inverted() return data_to_axis
2416a5472d51abe3a4389627820b392d737ad58d
637,381
def get_docs(d): """ Accepts a dictionary of the form {user: [cleaned word list]} and then returns the a list of lists, where each outer list is the word list for a particular user. This forms our document corpus on which we make LDA predictions. """ docs = [] for user in d: tex...
0e76ebc8b1a0f986cc00f4f0efaa7b7794676364
637,385
def get_Pin_ast(DLP, Pout): """ Calculate Pin_ast for given DLP (or DLP_ast) and Pout """ return DLP + Pout
61cd1c1841a391c48a9fbb8d784ecddf10545429
637,386
def filter_sb_transposon(fusions): """Filters fusions with genes related to transposon sequences.""" mask = fusions['fusion_name'].str.contains('En2|Foxf2') return fusions.loc[~mask]
7a1d1cf9904b52172e1b8a0a47ba286cd2000084
637,389
def _get_plural_forms(js_translations): """Extracts the parameters for what constitutes a plural. Args: js_translations: GNUTranslations object to be converted. Returns: A tuple of: A formula for what constitutes a plural How many plural forms there are """ ...
75a229b01e531d3bb0d9d95c0ce9b3868c37d299
637,391
def isWeekend(dt): """Finds if a date lies on a weekend or not. Returns a boolean""" if 0 < dt.weekday() < 6: return False else: return True
61c1f8df1f8791147c794b60c0f6452b4b540510
637,393
def get_file_content(filename): """Returns the contents of the specified file. :param filename: The full path/name of the file :return: The contents of the file """ file_contents = '' with open(filename) as f: file_contents = f.read() return file_contents
6fd24994de7b8cd086a41cb3e9ddb61226c50156
637,394
def factorial(n): """ Return the factorial of a number n. """ f = 1.0 for i in range(0, n): f *= (n - i) return f
3019ebb65b71f98720993f421ca2ce8cb175d2f0
637,399
def _http_forbidden(start_response): """Responds with HTTP 403.""" start_response('403 Forbidden', [('Content-Length', '0')]) return []
1bbff6e657c19520afd9176e0e787e31d532c2cc
637,401
def github_site_admin_action(rec): """ author: @mimeframe description: A Github site admin tool/action was used. Example: 'staff.fake_login' "A site admin signed into GitHub Enterprise as another user."" reference: https://help.github.com/enterprise/2.11/ad...
1766d85d1b7e96dfc080e3c209c48619b683fc98
637,405
def de_vec(a, rows, cols): """Column-major de-vectorization. First dimension is batch dim. """ batch = a.size(0) # dim = math.floor(math.sqrt(a.size(1))) a_mat = a.reshape(batch, cols, rows).permute(0, 2, 1) return a_mat
4a63a655b158de2e714e402b61f402d9876f2e85
637,407
import hashlib def get_file_md5(fpath, blocksize=2**20): """Get a file's MD5 checksum. Code from stackoverflow.com/a/1131255 Parameters ---------- fpath : string Path to file blocksize : int Read file in chunks of this many bytes Returns ------- md5sum : string ...
1df1e6c31ab30f025b27dc7d8a4b89146858bdf6
637,412
def xsd_datetime_str_from_dt(dt): """Format datetime to a xs:dateTime string. Args: dt : datetime - tz-aware: Used in the formatted string. - tz-naive: Assumed to be in UTC. Returns: str The returned format can be used as the date in xs:dateTime XML elements. It ...
c722a88a1eee276342066af2098d404f8302863a
637,413
from typing import Mapping def parse_kv_list(params): """Create a dict from a "key=value" list. Parameters ---------- params : sequence of str or mapping For a sequence, each item should have the form "<key>=<value". If `params` is a mapping, it will be returned as is. Returns ...
083f0941f23a61d9a99ad5bf08749a50a0038248
637,414
def parse_argstring(magic_func, argstring): """ Parse the string of arguments for the given magic function. """ return magic_func.parser.parse_argstring(argstring)
32a2d2e2014023eca67049eb1396013e2fa9eda2
637,418
def factorizeByBase(n, base, m = None): """ Find a factorization of n with factors from base, if one exists. If the modulus m is given, the base is allowed to contain -1. All other elements must be positive. """ assert n > 0 if m is not None and -1 in base: idx = base.index(-1) ...
c9846d9c8a9a8dd805f6158b952b56ec44cf6f6f
637,423
def read_file(path): """Returns document read in by line""" with open(path, 'r') as f_in: # read in text file doc = f_in.readlines() return doc
d2c5df99bb9e6589a3be59a358ab04b50857978c
637,425
import requests def post_as_json(url, payload): """post the payload as JSON data""" return requests.post(url, json=payload)
c8e250f5942fe2f3a5b979740af597260ddd2426
637,428
def get_other_causes(effect, cause, relations): """ For each effect-cause combination, return a list of the other prima facie causes. Parameters: effect: the variable representing the effect (key of the relations dict). cause: the cause to filter out. relations: the dict containing ...
68388c128e846ec736a26f4e9f970eaf598af610
637,434
def _IsReadableStream(obj): """Checks whether obj is a file-like readable stream. :rtype: boolean """ if (hasattr(obj, 'read') and callable(getattr(obj, 'read'))): return True return False
3f616a6e68686427c383af3aaca83478152737db
637,436
import yaml def read_yaml(file_path: str) -> dict: """ Safely reads a yaml-file. Parameters ---------- file_path : str File path to YAML-file. Returns ------- dict Loaded YAML-file. """ with open(file_path, 'r') as stream: try: retu...
21e59f65ffee8994999cce9d21b6697a20a1b759
637,440
def get_column_names(connection_or_cursor, table): """Return list of column names from given database table.""" cur = connection_or_cursor.execute(f'PRAGMA table_info({table})') return [row[1] for row in cur.fetchall()]
9e41c62180b46e2b9f2006b66563585761b1c50a
637,443
from typing import Optional import re def parse_timestamp(timestamp: str) -> Optional[int]: """Parse a playback timestamp into a number of seconds. Expects the timestamp to be in HH:MM:SS or MM:SS format. """ match = re.match( r"^(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)$", timest...
e408a9fb7a1373467359a6cf59d239b82f774b82
637,444
import ast def get_bool_input(input_parameter): """Returns a boolean corresponding to a string "True/False" input Args: input_parameter (str): String input for a boolean Returns: bool: True/False input """ if input_parameter.lower().capitalize() in ["True","False"]: return ast.literal_eval(input_...
48fefc90d88cc455e9859565fc16a4cdb290b165
637,445
from typing import List def xlnet_tokens_pre_processor(token_ids: List[int]) -> List[int]: """Add XLNET style special tokens. Args: token_ids: List of token ids without any special tokens. Returns: List of token ids augmented with special tokens. """ XLNET_CLS_ID = 3 XLNET_SE...
1f8703021d3c543ecda234f06430fbb1ec690c62
637,447
def rolling_variance(old,newValue): """Rolling variance computation according to Welford's algorithm. https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_Online_algorithm Parameters ---------- old : tuple containing the triplet count, mean, M2. Initialize with (0,0,...
caa36948d44cb64186de66e74dc3a226f0e1a65e
637,449
def convert_labels(Lorig, params, toLasStandard=True): """ Convert the labels from the original CLS file to consecutive integer values starting at 0 :param Lorig: numpy array containing original labels :param params: input parameters from params.py :param toLasStandard: determines if labels are conv...
b3f7a1165faba0b2aaabebcdd34a592367800a83
637,451
def max_len(seq_list): """Returns the maximum sequence length within the given list""" lmax=0 for seq in seq_list: lmax=max( lmax, len(seq) ) return lmax
dad4290683c5a386a16147ebe87df346148935d8
637,455
def account_from_role_arn(role_arn): """ Returns the AWS account ID portion of the given IAM role ARN. """ parts = role_arn.split(':') if len(parts) == 6: return parts[4] return '-'
4754089a654e52862b11b56d6991096621f2b292
637,457
def has_issue(item): """Return True if the testcase has an issue.""" return bool(item.issue_id)
1afd227555ed9a58e50a167eff5d344cd3ec56f5
637,462
def _i2col(i): """Given an index, return the column string: 0 = 'A' 27 = 'AB' 758 = 'ACE' """ b = (i//26) - 1 if b>=0: return _i2col(b) + chr(65+(i%26)) return chr(65+(i%26))
ae3ea60f149df46b501d6e61ba4b816a8236cb80
637,464
import math def rotate_coordinate(x, y, cx, cy, theta): """Return a new point (x', y') as rotating an existing point (x, y) theta radians around the point (cx, cy). """ x_p = ((x - cx) * math.cos(theta) + (y - cy) * math.sin(theta)) + cx y_p = (-(x - cx) * math.sin(theta) + (y - cy) * math.cos(the...
689220526937e5a139df49a627b393c1331f445a
637,466
from typing import List def _enumerate_cores(bounds: List[int], ring_bounds: List[int], ring_sizes: List[int], host_bounds: List[int], host_sizes: List[int]) -> List[List[int]]: """Enumerates cores within `bounds` from fatest to slowest varying axes. Args: bounds: Up...
50e4fbbdb9b57e0133a2d71916aa83c75c312a40
637,467
def convert_to_factors(die): """Converts a sympy factor_list tuple to a list of the factors and returns the list""" sub_list = die[1] # Create a list from the tuple factor_list = [] for i in sub_list: # Iterate through the `sub_list` which contains all the factors for j in range(i[1]): # Nesting...
568063246155befdf078da51887b9e513b961688
637,470
def clean_state(state): """ Upper cases the state and fixes a few weird issues. """ new_state = state.upper() if state else None # NF -> NL for Newfoundland and Labrador. if new_state == "NF": new_state = "NL" # PQ -> QC for Quebec. if new_state == "PQ": new_state = "QC" ...
5e4012d5edc2ffa581010f11ff5de02de8990d7c
637,472
def ensure_tz_UTC(df): """ Function to ensure that the tzinfo of a data frame is in UTC :param df: a pandas data frame with datetime_index :returns: the dataframe with df.index.tzinfo='UTC' """ # ensure tzinfo is in UTC if (str(df.index.tzinfo)=='None'): #print('The time...
4e8fb68dc648b32138dda66a415c9c5e660665f1
637,473
def get_service_start_name(start): """ Translate a Windows service start number to a friendly service start name. """ return { 0: 'Boot', 1: 'System', 2: 'Automatic', 3: 'Manual', 4: 'Disabled' }.get(start, 'Unknown')
f97e6476e187c22243ad1907314bc1443581e2aa
637,483
import re def fix_reserved_name(name): """Returns a tuple of (<name>, <replacement_name>) if name is a reserved word, otherwise returns (<name>, <name>). """ reserved_names = [ ('^key$', '_key_rr'), ('^interval$', '_interval_rr'), ('^load$', '_load_rr'), ('^primary$', '_pri...
713e8e3d5cc505241e488f4c70d68bd13e3b8c9a
637,488
def gray_code_sequence_string(bit_count: int) -> list: """ Will output the n-bit grey sequence as a string of bits >>> gray_code_sequence_string(2) ['00', '01', '11', '10'] >>> gray_code_sequence_string(1) ['0', '1'] """ # The approach is a recursive one # Base case achieved w...
d1f75e9ea4b607ef9720568dfa3f5504efa9ecfe
637,490
def pool_url(aws_region, aws_user_pool): """ Create an Amazon cognito issuer URL from a region and pool id Args: aws_region (string): The region the pool was created in. aws_user_pool (string): The Amazon region ID. Returns: string: a URL """ return ( "https://cogni...
e5d3653c10b4a5f5fe033625893ea7816224a4a2
637,491
def timedelta_to_integral_seconds(delta): """ Convert a pd.Timedelta to a number of seconds as an int. """ return int(delta.total_seconds())
8a049b167e2cc793785f24c16a2583634b1cb17c
637,494
def file_number(number, string_length): """Generate number strings with leading zeros so that numerical and string order coincide""" number_to_string = str(number+1) length = len(number_to_string) final_name = '0'*(string_length-length) + number_to_string return final_name
f224f3a7117c80a7d553c904a4f7a0176611e0be
637,495
def get_by_path(obj, path): """ Iteratively get on obj for each key in path. :param (list|dict) obj: The top-level object. :param (tuple[str]|tuple[int]) path: Keys to access parts of obj. :return: (*) Example: >>> figure = {'data': [{'x': [5]}]} >>> path = ('data', 0, 'x') ...
1cba19902076f732e61dc5647b084172c3f67ebc
637,498
def find_multiples(integer, limit): """ Finds all integers multiples. :param integer: integer value. :param limit: integer value. :return: a list of its multiples up to another value, limit. """ return [x for x in range(1, limit + 1) if x % integer == 0]
36b438541f6f067a92aad6317f3ce919b6e4bde2
637,504
import math def get_ticks(start, end, target_n_labels=10): """ Tries to put an appropriate number of ticks at nice round coordinates between the genomic positions `start` and `end`. Tries but doesn't guarantee to create `target_n_labels` number of ticks / labels. Returns: a list of tupl...
a91a090777e5b3697163bb6dcf88bdef501b9302
637,507
def ida_offset(string): """ Converts non-IDA conforming offset representation to a more IDAesk form. :param string: a non IDA conform string :return: IDA conform string """ segment, rest = string.split(':', 2) offset_start = rest.rfind('+') offset = rest[offset_start + 1:-1] operands...
71ec528603b172550e28c57c832317b6065fbd1e
637,508
def format_grid(grid): """ Formats each row to represent list value delimited by spaces :param list grid: input with nested lists to format """ formatted_grid = '' for row in grid: # list comprehension used to explicitly cast items to str # this allows for the grid param to cons...
7a2305f459740b991cfe57f510032eea6bcf15a0
637,509
import collections def invert_dict(d): """Invert a dictionary. Converts a dictionary (mapping strings to lists of strings) to a dictionary that maps into the other direction. Arguments: d: Dictionary to be inverted Returns: A dictionary n with the property that if "y in d[x]", then "x in n[y]". ...
b1ff7ebb163640b25132670a95e1826f2f5ed985
637,510
def _is_technical(computation: str) -> bool: """ Check if a computation is a technical computation. Parameters ---------- computation: str a computation name. Returns ------- True if it is a technical computation, false otherwise. """ if computation.startswith('_'): ...
f2cdd49d36d6558f95e736374c2c475bccda388c
637,512
def getPlaylists(sp, username, offset=0): """ Retrieves all the playlists a user has :param sp: A spotipy.Spotify object to be used for the request. :param username: The username of the user who's playlists you want the retrieve. :param offset: Do not worry about this ...
c4d3b8a651fc20bd9234c8949b3248cee68210d8
637,513
from typing import Optional def color_mid(value: float) -> Optional[str]: """Determine color for efficiency value where "mid" values are the target. Args: value: percent (0-100) of value to color Returns: The color string for click or None if color should be unchanged """ if valu...
b9418fcc41ae3453b39d8e4fed7a0e473d2bba1a
637,517
def _localize(dt, tzinfo): """ :return: A localized datetime :paramd dt: Naive datetime :param tzinfo: A pytz or python time zone object Attempts to localize the datetime using pytz if possible. Falls back to the builtin timezone handling otherwise. """ try: return tzinfo.locali...
f68588195197b250d88a710f01196d6dd701c2d1
637,518
import json def get_all_block_transactions(blocks_file_path): """ Return the number of transactions for blocks in the file in a dictionary """ transaction_counts = {} with open(blocks_file_path) as blocks_file: for line in blocks_file: block = json.loads(line) ...
1ded6ef1730e6124ff6d76da6fef1f53358802a9
637,519
def _is_file_valid(name): """Decide if a file is valid.""" return not name.startswith('.')
a7f00223686279f0e648e6bf828a3e51d5d5e988
637,521