content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def remove_if(rng, pred): """ Remove each element from `rng` for which `pred` evaluates to true by swapping them to the end of the sequence. The function returns the number of elements retained. """ j = 0 for i, x in enumerate(rng): if pred(x): continue if i != j...
9a449133f3eff0ef047b03b499b4a5b7b532a871
631,287
def c_linker_options(ctx, blacklist=[]): """Extracts flags to pass to $(CC) on link from the current context Args: ctx: the current context blacklist: Any flags starts with any of these prefixes are filtered out from the return value. Returns: A list of command line flags """ cpp = ctx.fra...
6a5aa9f820098523ad4243da174c3d96477eaa00
631,288
def stack_projection_args(cli_args): """ Converts the flat processing options into nested JSON Args: cli_args (dict): arguments parsed from the CLI Returns: dict: nested dictionary grouped by types/usage Example: >>> stack_projection_args({'target_projection': 'utm', 'zone': 1...
67101b35ac2d4210e7af15b4d8356b0095fcb60e
631,291
def validate_reviews(df): """ Enrich no review records with default review scores. """ df['first_review'].fillna(value='1991-01-01', inplace=True) df['last_review'].fillna(value='0', inplace=True) df['review_scores_rating'].fillna(value=0, inplace=True) df['review_scores_accuracy'].fillna(value...
752718cc50073c6fb66161e90003e06b74a21353
631,293
from datetime import datetime def _create_stack_id(name: str) -> str: """ Creates a stack name that should be unique within the region. Args: name (str): Name of the project for which to create the stack ID. Returns: (str): The generated stack name. """ dt_string = datetime.n...
c3de9b923df0ae3132f90a908c7cbe8ed92ee777
631,299
def parse_version(vers_string): """Parse a version string into its component parts. Returns a list of ints representing the version, or None on parse error.""" vers_string = vers_string.strip() vers_parts = vers_string.split('.') if len(vers_parts) != 4: return None try: major =...
46d96c48e03ab9e68362cfb850ba49ecf54ba49d
631,301
def matrix_block(M, rows, cols): """ Select a block of a matrix given by the row and column indices """ return M[rows,:][:,cols]
e797dc92cfa77eda7e1228e7bba01116ab87e901
631,304
import random def bootstrap_sample(data): """randomly sample len(data) elements with replacement""" return [random.choice(data) for _ in data]
787033910ee48618b36e7ad39cae13a58f4a3f0b
631,305
def nested_get(dictionary, keys): """Get nested fields in a dictionary""" to_return = dictionary.get(keys[0], None) for key in keys[1:]: if to_return: to_return = to_return.get(key, None) else: break return to_return
a01f04aae670f118c97808ab27933799b0613c56
631,306
def format_long_time(timespan): """ Formats a long timespan in a human-readable form with a precision of a 100th of a second. """ formatted_time = [] units = (('d', 24 * 60 * 60), ('h', 60 * 60), ('m', 60), ('s', 1)) for unit, length in units: value = int(timespan / length) ...
ddfd2d0351b48d3c2e221b54688bff96905f65eb
631,307
def overrides(interface_class): """ To be used as a decorator, it allows the explicit declaration you are overriding the method of class from the one it has inherited. It checks that the name you have used matches that in the parent class and returns an assertion error if not """ def over...
e5264baf1c5a5d97b354a4db3b3a49ccb580c082
631,308
def _build_param_docstring(param): """Builds param docstring from the param dict :param param: data to create docstring from :type param: dict :returns: string giving meta info Example: :: status (string) : Statuses to be considered for filter from_date (string) : Start date filter...
14b51d6966d0a5a5b8a185830f3d62585ae2d1d1
631,312
import uuid def create_api_release(client, resource_group_name, service_name, api_id, api_revision, release_id=None, if_match=None, notes=None): """Creates a new Release for the API.""" if release_id is None: release_id = uuid.uuid4().hex api_revision_to_release_and_make_current = "/apis/" + api_...
eaf1f76bf2fea685847ff732d5603f78ff307b2a
631,315
def predict(model, X, threshold = 0.3): """ desc: given an x dataframe, make a prediction using our model args: model (Sklearn.pipeline Pipeline) : Trained model we are going to evaluate X (pd.DataFrame): X values passed to model. returns: y (int) : 1 or 0, 1 for ...
1e2f21f9b602f5f82294e5af283b84a40e64afed
631,316
def evaluate(labels, predictions): """ Given a list of actual labels and a list of predicted labels, return a tuple (sensitivity, specificity). Assume each label is either a 1 (positive) or 0 (negative). `sensitivity` should be a floating-point value from 0 to 1 representing the "true positive...
9f754488dc0c10da43b985a8c33d8ef681d3b873
631,323
def fact(n): """ Return 1, if n is 1 or below, otherwise, return n * fact(n-1). """ return 1 if n <= 1 else n * fact(n - 1)
d4365b2c3d4aaaf9039011eabb9b04f508048be6
631,324
import tempfile def create_dir(basedir=''): """ Create a unique, temporary directory in /tmp where processing will occur Parameters ---------- basedir : str The PATH to create the temporary directory in. """ return tempfile.mkdtemp(dir=basedir)
02edbd021215d25a835e86e3566763733165e9b0
631,326
def convert_dict(dicts: dict) -> dict: """ Convert all the values in a dictionary to str and replace char. For example: <class 'torch.Tensor'>(unknow type) to torch.Tensor(str type). Args: dicts (`dict`): The dictionary to convert. Returns: (`dict`) The...
d73cf26d6dc0f5bab31277710c7188baafbce21f
631,328
def dimensions_match(matrix1, matrix2): """ This function checks if the orders of the given matrices match. Arguments: matrix1 {Matrix} - The first Matrix object matrix2 {Matrix} - The second Matrix object Returns: boolean-- True or False depending on if their orders match or not. """ ...
a7ce6a7894b4ec8ff6827e8b802c2227909d9c60
631,331
from pathlib import Path from typing import Optional from typing import Union from typing import Pattern from typing import List import re def get_all_files_in_directory( path: Path, pattern: Optional[Union[Pattern, str]] = None ) -> List[Path]: """ Returns all the files in a directory structure. For...
c1bc4f752125f287bf2fee3e8ab3f921f2e0a6a0
631,333
def run_on_nested_arrays2(a, b, func, **param): """run func on each pair of element in a and b: a and b can be singlets, an array, an array of arrays, an array of arrays of arrays ... The return value is a flattened array """ if isinstance(a, list): if not isinstance(b, list): ra...
2f2c4b5309df5fbfe2b97e39e1c58b43e1b699f4
631,335
def format_output(result): """Format output to preserve consistence in output""" formatted = "WPM: %-3s " % result["wpm"] formatted += "KPS: %-3s " % result["kps"] formatted += "Error: %%-3s " % result["error"] formatted += "Strokes: %d " % result["strokes"] return formatted
7488939497045ed86b586072b3fa6f9636417a76
631,338
import torch def face_area(vertices, faces): """ Computes area of each faces using cross product Args: vertices (torch.tensor): Vx3, xyz coordinates of vertices faces (torch.tensor): Fx3, index of vertices for each face Returns: (torch.tensor): F, area of each face """ ...
92c067949ee3c7c486ccf3a27b8ea2a3e2e60de3
631,339
def triangular_number(x: int) -> int: """ Get the xth triangular number """ return (x * (x + 1)) // 2
db640d26cfa4ba524c18bc443fc657758260f585
631,341
def mnet_kwargs(config, task_id, mnet): """Keyword arguments that should be passed to the main network. In particular, if batch normalization is used in the main network, then this function makes sure that the main network chooses the correct set if batch statistics in case they are checkpointed (i.e.,...
e922f70dfec3d247843c39ee6763443f65a2d4f7
631,342
from numbers import Number def dict_splicer(plot_dict,Ld,Lx): """Dictionary constructor for plotting Base-level function used by most other plotting functions to construct a list of dictionaries, each containing the passed arguments to the underlying plotting calls for each different dataset. Parameters ----...
14e5a1009ba14dcb861507c8f3f6a563a7889a25
631,343
def calc_bpe_exchange_current(K_standard_rate_constant, c_bulk_oxidized, c_bulk_reduced, alpha_transfer_coefficient=0.5): """ The exchange current density at a specific BPE location units: Coulombs/s*m2 Notes: K_standard_rate_constant: usually between 2 and 6 c_bulk (oxidized and reduced...
f09c19bab7f23762b9f20816eff57a6e20dbaf63
631,347
def safe_join(separator, values): """Safely join a list of values. :param separator: The separator to use for the string. :type separator: str :param values: A list or iterable of values. :rtype: str """ _values = [str(i) for i in values] return separator.join(_values)
e6ef01fe4bcdd5fa8ed34a922b896dc10ec7eda0
631,350
from typing import List def keys_exists(multi_dict: dict, keys: List[str]) -> bool: """Check if multi-level dict has specific keys""" _multi_dict = multi_dict for key in keys: try: _multi_dict = _multi_dict[key] except KeyError: return False return True
1de1ef0060a6f0953335e7968de824e6880bcda6
631,355
def fix_url(url): """Add http:// prefix to url if it doesn't have one.""" if "://" not in url: if url.startswith("//"): url = "http:" + url else: url = "http://" + url return(url)
332925f66415fb42c02d6677742859d0dd2955c3
631,363
def get_timecode(td): """Convert a timedelta to an ffmpeg compatible string timecode. A timecode has the format HH:MM:SS, with decimals if needed. """ seconds = td.total_seconds() hours = int(seconds // 3600) seconds %= 3600 minutes = int(seconds // 60) seconds %= 60 str_seconds,...
a5f8d14a1e42ffb1ea5403023c16268265b554c3
631,366
def _end_of_set_index(string, start_index): """ Returns the position of the appropriate closing bracket for a glob set in string. :param string: Glob string with wildcards :param start_index: Index at which the set starts, meaning the position right behind the opening b...
ef9b68b4065992900c6d3dd7b2f8c5591b36c596
631,368
def fix_brace_c(a, b): """Move any `}`s between the contents of line `a` and line `b` to the end of line `a`. :param a: A line of Lean code, ending with `\n' :param b: A line of Lean code, ending with `\n' :returns: A tuple `(anew, bnew, merge)`, where `anew` and `bnew` are `a` and `b` with co...
972354cc1a6ec684a24503c4e31b3d0b02855645
631,371
def f_sq(num: int) -> int: """Return [num] squared.""" return num**2
0c7e2403afb58235fb398bb8c8dd473aa8f8e5bd
631,375
def container(**criteria): """ Turns keyword arguments into a formatted container criteria. """ criteria = ['%s="%s"' % (key, val) for key, val in criteria.items()] return '[%s]' % ' '.join(criteria)
1c581691840d3a33f0d203e53901824bd566d61c
631,379
import re def camelback2snake(camel_dict: dict): """Convert the passed dictionary's keys from camelBack case to snake_case.""" converted_obj = {} for key in camel_dict.keys(): converted_key = re.sub(r'[A-Z]', lambda x: '_' + x.group(0).lower(), key) converted_obj[converted_key] = camel_dic...
a6f08f5bdec441662a8feca0898e1bde9f25a456
631,386
def find_on_grid(grid, wanted): """Find location of wanted on grid.""" for row_no, row in enumerate(grid): for col_no, col in enumerate(row): if col == wanted: return (row_no, col_no) return None
370785637254c18764da3a404e51033020631c34
631,390
import re def get_r_filename(r_file): """Remove the file extension from an r_file using regex. Probably unnecessary but improves readability Parameters ---------- r_file : string name of R file including file extension Returns ------- string name of R file without f...
bde15f79afcc585d0f86b45debf932c22d22f271
631,392
def set_show_scroll_bottleneck_rects(show: bool) -> dict: """Requests that backend shows scroll bottleneck rects Parameters ---------- show: bool True for showing scroll bottleneck rects """ return {"method": "Overlay.setShowScrollBottleneckRects", "params": {"show": show}}
9e2a16540015084154d612d2a3dedbd8523b5058
631,394
import re def count_vocals(file_name, start=0, end=100): """ Count vocals in specified file Args: file_name (str): path to file start (int): first line in file end (int): last line in file Returns: int : number of vocals in file """ vocals_number = 0...
bd3de89d95a7c0c3fa1f73a0627c5be2fa9ecab3
631,398
def _requirements_with_three_elements(requirements): """Return true if requirement list looks like ['<', '$ram', '1024'].""" return (isinstance(requirements, list) and len(requirements) == 3 and isinstance(requirements[0], str) and isinstance(requirements[1], str) and ...
ccb05ca4dd46bf4202a2a4b16c10666e43a3af35
631,403
def _check_mutual_preference(resident, hospital): """ Determine whether two players each have a preference of the other. """ return resident in hospital.prefs and hospital in resident.prefs
29856e3ef65e60f06c6b12e8b598579b89156295
631,404
def posting(client, route, title_field='test title', content_field='test body', is_page=False, categories_field_0='', categories_field_1='', categories_field_2='', publish='yes', preview=None): """Helper function to create/edit posts and drafts by posting to our routes. This helper ...
fb20f18284d6066c8ff07946c3b55751dec94abc
631,406
import re def create_paired_list(value): """ Create a list of paired items from a string. :param value: the format must be 003,003,004,004 (commas with no space) :type value: String :returns: List :example: create_paired_list('003,003,004,004') [['003','003'...
7733ab7ef576a226522bfacadf4e5eeb306f1053
631,412
import typing def get_ctffind_4_1_0_header_names() -> typing.List[str]: """ Returns the header names for the ctffind4 input file. Arguments: None Returns: List of names """ return [ 'DefocusU', 'DefocusV', 'DefocusAngle', 'PhaseShift', 'CtfFigu...
8e8ea28cc1a66690b67c5fe1d5f4f11aed79a49d
631,413
from pathlib import Path def _get_dataset_path_from_args(args_dataset): """Remove 'benchmark:' from the dataset name and add .csv suffix. Parameters ---------- args_dataset : str Name of the dataset. Returns ------- str Dataset name without 'benchmark:' if it started with...
f34d5185f439751cb54765c32634727726ca426b
631,414
import re def normalize_name(str): """Converts names into JavaScript-safe ascii string keys that adhere to the expected conventions.""" if not str: return str # The Tam\u2013Tara Deepcroft str = re.sub(r"\u2013", "-", str) # The <Emphasis>Whorleater</Emphasis> Extreme str = re.sub(r"...
9575a96454a0a874c8a2d94b04a89eb57646ab49
631,415
def _cast_value_to_type(value, cast_type_string): """Return the value casted to the type specified by the cast_type_string, as defined in the type maps in the ReferenceGenome object's variant_key_map field """ if cast_type_string == 'Integer': return int(value) elif cast_type_string == 'Floa...
d01a83c465703c66134ece06df7f67deb366525a
631,416
def merge(numbers_list): """ Mergesort algorithm :param numbers_list: list of number to order :return: new list with numbers ordered """ if len(numbers_list) <= 1: return numbers_list result = [] # identify the middle item mid = len(numbers_list) // 2 numbers_list_a = m...
c5e713a7fb22de36fa20ee4d982e89b5f7585b2e
631,420
def fizz_buzz_elif(n): """ Return the correct FizzBuzz value for n by testing divisibility in an if-elif. """ divisible_by_3 = n % 3 == 0 divisible_by_5 = n % 5 == 0 if divisible_by_3 and divisible_by_5: return "Fizz Buzz!" elif divisible_by_3: return "Fizz!" elif div...
d98b01d2dc73328884a875de753338dea58f4799
631,422
def factorial(n): """ Input: a number. Output: find the factorial of the input number via iteration. """ product = 1 if n == 0: return 0 for thing in range(1, n+1): product *= thing return product
8006c96ec916156840fd20914430c7ff9e24af80
631,424
def npix_above_threshold(pix, thr): """ Calculate number of pixels above a given threshold Parameters ---------- pix: array-like array with pixel content, usually pe thr: float threshold for the pixels to be counted Returns ------ npix_above_threshold: float ...
a464605f724db3a40be24a62e6eb532e7249114a
631,425
def SplitRange(regression): """Splits a range as retrieved from clusterfuzz. Args: regression: A string in format 'r1234:r5678'. Returns: A list containing two numbers represented in string, for example ['1234','5678']. """ if not regression: return None revisions = regression.split(':') ...
3f81178c1eee611e73acdf03b3f006c03b0f1ca8
631,428
def is_import(line): """Returns if the line is an import.""" return "import " in line or "__import__" in line
7a145fff7177bb222a14a439cee554dc2a93b6de
631,429
import pickle def pickle_from_file(path): """Load the pickle file from the provided path and returns the object.""" return pickle.load(open(path, 'rb'))
71cacc34457314853897f2835d52a893d6a56547
631,434
def truncate(text, max_length=1024): """Limit huge texts in number of characters""" text = str(text) if text and len(text) >= max_length: return text[:max_length//2-3] + " ... " + text[-max_length//2+3:] return text
fa69b875a1921bd6b0f2754a061ef6f8f4f77d2c
631,435
def get_outliers(df, forecast, today_index, predict_days=21): """ Combine the actual values and forecast in a data frame and identify the outliers Args ---- df : pandas DataFrame The daily time-series data set contains ds column for dates (datetime types such as datetime64[ns]) and ...
93184cbebd46dab654d4224d9a4d0f4cea190bc3
631,436
from io import BytesIO from io import StringIO from zipfile import ZipFile import requests def get_zip_file(url, filepath): """Gets zip file from url. Args: url: A string, the url of zip file. filepath: A string, the file path inside the zip file. Returns: A String, the content of ...
6630fadd083523a3575acebf9a3db49bb5aa8537
631,437
def check_vocab_file(file, special_tokens): """Check a vocab file, adding special tokens to it. Args: file: A constant string, path of the vocab file special_tokens: A list of special tokens Returns: The size of the processed vocab. """ vocabs = set() with open(file, mo...
7e21578d1fa96789d7f8d646d3111fab13ee2e84
631,442
def extract_vertices_from_name(name: str) -> str: """Takes the number of vertices from a string of the form: '{type}_{num_vertices}_{k}_{rank}_{m1}_{m2}' """ suffix = name[name.find('_')+1:] return suffix[:suffix.find('_')]
e66a72142fea08446473049fa26799b04ce6ce18
631,444
def EncodeFileRecordSegmentReference(FileRecordSegmentNumber, SequenceNumber): """Encode a file record segment reference and return it.""" return (SequenceNumber << 48) | FileRecordSegmentNumber
ecde23e47c929b84c309504c1798cd160979c864
631,453
def to_setting( checked: bool, text: str, active_style='class:toolbar-setting-active', inactive_style='', mouse_handler=None, ): """Apply a style to text if checked is True.""" style = active_style if checked else inactive_style if mouse_handler: return (style, text, mouse_handle...
61ecece14d1260e922cf2a9871a26184882ab92b
631,456
def parse_compute_version(compute_version): """Parse compute capability string to divide major and minor version Parameters ---------- compute_version : str compute capability of a GPU (e.g. "6.0") Returns ------- major : int major version number minor : int min...
ab48bbd69ebbb99d3671d3c39fb77fbb12a76ad4
631,457
def remove_dup_loop(input_list): """ Remove all duplicates in list. Using loop method. Arguments: input_list -- a list input Returns: new_list -- a list remove all the duplicates. """ new_list = [] new_list.extend(i for i in input_list if i not in new_list) return new_l...
08c20c3fb40a0294811bc78305aab9dbd0f5bc71
631,460
from typing import Union from pathlib import Path import json def load_json(ffp: Union[Path, str]): """Loads a data from a json file""" with open(ffp, "r") as f: return json.load(f)
0bb8240f858f69f8c0ede131403c59ad5703ec42
631,461
def assignment_history(task): """ Return all assignments for `task` ordered by `assignment_counter`. Args: task (orchestra.models.Task): The specified task object. Returns: assignment_history ([orchestra.models.TaskAssignment]): All assignments for `task` ordere...
7dc71357093a3a83c897c80ae378a7e53b6bfe72
631,463
def coords_in_image(rr_cc, shape): """ Taken almost directly from skimage.draw(). Decided best not to do any formatting implicitly in the shape models. Attributes ---------- rr_cc : len(2) iter rr, cc returns from skimage.draw(); or shape_models.rr_cc shape : ...
4243374d5eee3e6a51f8dee1ece4a77d5e319df1
631,464
from pathlib import Path def create_filename(name_segments, part=None, num=None, extension='.jpg'): """Returns a Path object comprising a filename built up from a list of name segments. Parameters: name_segments (list): file name segments part (str): optional LOC image designator (e.g., i...
5ce9f2c58cb512acb8e1144c99badfbbb893fcb0
631,471
import logging def get_logger(name: str) -> logging.Logger: """ Create new logger. :param name: The logger domain. :return: New logger. """ return logging.getLogger(name)
d19f287e2ed62cb094de297de09f32d26d02d5ef
631,474
def lag_to_suffix(lag: int) -> str: """ Return the suffix for a column, given its lag. """ if lag < 0: str_lag = "f" + str(abs(lag)) else: str_lag = "l" + str(abs(lag)) return str_lag
c2208d55aa53f343817ffbe9163410feddc050ac
631,475
import math def nPVI(items): """Calculate the Normalized Pairwise Variability Index. :param items: (list) list of data values :returns: (float) """ if len(items) < 2: return 0. n = len(items) - 1 sumd = 0. for i in range(n): d1 = items[i] d2 = items[i+1] ...
b6b3e5efea9d97755a92763d0994415d30c7a4cd
631,476
def bdev_virtio_scsi_get_devices(client): """Get list of virtio scsi devices.""" return client.call('bdev_virtio_scsi_get_devices')
26e9926ae4920000e524e38363258b2cb495ea58
631,478
import functools def flat_map(l): """Transform a list of list in a list with all the elements of the nested lists >>> flat_map([[1, 2, 3], [4, 5]]) [1, 2, 3, 4, 5] """ l = list(l) return functools.reduce(list.__add__, l) if l else []
737ab9e620aea120e24458f45256bf663a0bc3ec
631,483
def _must_contain_scenarios(must_contain_conf, scenario_model): """ Return a set of scenarios and process names that are entries of must contain configuration. :param must_contain_conf: dict. :param scenario_model: ScenarioModel. :return: set of process names, set of Scenario objects. """ n...
bd02bee56c0670065e0fe46e82f95893db488aa1
631,484
def using_split2(text, _len=len): """ LEGACY Takes a text in input and returns a list of tuples with surface, start and end offsets for each token. From: http://stackoverflow.com/questions/9518806/how-to-split-a-string-on-whitespace-and-retain-offsets-and-lengths-of-words :param text: a string of t...
dd70fadca81248d2277e9e86d12f7cfd8f25c08b
631,490
from pathlib import Path import importlib import inspect def create_init_line_library(module_path: str, lib_name: str) -> str: """Creates an __init__ entry of the library dir for the corresponding metadatablocks file""" # Get the module name from file module_name = Path(module_path).stem # Import pa...
fb1d1cd713cc1bd39aed4de7441d9c801a255ece
631,491
def decode_bin(bin_array): """Takes in an array of bits and returns the number associated""" bitstring = ''.join(bin_array) number = int(bitstring, 2) return number
04b3944db60d29214141afd4e458ad7dad66ccf6
631,500
def max_degree(g): """ Returns the maximum number of edges of any node in the graph """ return max([g.degree[n] for n in g])
0184e4c795e326bb09c5ecb4830cfb489fc7b419
631,509
import re def natural_sort(item): """ Sort strings that contain numbers correctly. >>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1'] >>> l.sort(key=natural_sort) >>> print l "['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']" """ if item is None: ...
f121cf37b0dfc24f01fcb4d798d491b664048a00
631,510
def build_alignment_param_metrics(align): """ Transform alignment param dict -> alignment metrics for output to json""" aln_param_metrics = {} for key, value in align.iteritems(): aln_param_metrics['alignment_' + key] = value return aln_param_metrics
6adf44805776ae5b3e93a08888050e34d5e9a92a
631,514
def _reduce_sampled_fluxes(sampled_fluxes, reactions): """ Reduces the input dataframe of sampled fluxes to a subset of selected reactions. Parameters ---------- sampled_fluxes : pandas.Dataframe The calculated fluxes, output of sampling. For each reaction, n fluxes will be calc...
b6d6a618a0435b9e4f28fe4b10c611e9d269b698
631,515
import pwd def uidFromString(uidString): """ Convert a user identifier, as a string, into an integer UID. @type uid: C{str} @param uid: A string giving the base-ten representation of a UID or the name of a user which can be converted to a UID via L{pwd.getpwnam}. @rtype: C{int} @retu...
d83a6c9dff5bc193335f1719b7f0e7395aacc2fd
631,517
def istrue(value): """ Accepts a string as input. If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns ``True``. If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns ``False``. ``istrue`` is not case sensitive. Any other input ...
b1b14852cb814c9ed64a4074b32dffe6e4c0de49
631,518
import re def decode_bytes(data: bytearray) -> str: """ Decodes a bytes array from a file upload :param data: a UTF-8 encoded byte array :return: a cleaned string """ pattern = re.compile('\r', re.UNICODE) res = data.decode('utf-8', 'ignore') res = pattern.sub('', res) return res
0ec48f84da9acfdb68363fffbdf81546523588fb
631,528
def slice_for_range(data, fromVal, toVal): """ Returns a slice indicating the region [fromVal, toVal] in a 1D ndarray data Example: >>> data = linspace(1, 50, 50) >>> s = slice_for_range(data, 4, 10) >>> data[s] array([ 4., 5., 6., 7., 8., 9., 10.]) """ if (data[-1] - da...
44cb009d01cb1bf4415aa867cd4cc9e2685e8d4c
631,529
import dill def load(filename): """ This function opens a serialized file and returns the object. Parameters: ---------- filename: str, the name of the serialized file to be opened. Returns: ------- obj: The object contained in the serialized file. """ input_file = open(filename, 'rb') obj = dill.load(...
47b4dd55ac3cc37ea466407e5581e6826f24b29e
631,531
def timesTwo(input_array): """ Multiples the input array times two. """ return 2*input_array
4aa7c9408d1ea6f608dcdde6e297e571579f735d
631,532
def get_login_tokens(login_response_body_dict): """Creates dictionary of login keys to use to make additional request calls to USPS Args: login_response_body_dict: response body (type dictionary) returned by the USPS logon endpoint. Returns: Dictionary containing logon key and...
7e4fc7f7564fbc85ffa62fb31709f29154ae4f61
631,533
import torch def from_tanh_space(x, box=(-1., 1.)): """ Convert a batch of tensors from tanh-space to oridinary image space. This method complements the implementation of the change-of-variable trick in terms of tanh. :param x: the batch of tensors, of dimension [B x C x H x W] :param box: a ...
4331e6d353e26c17ebc9721cbf8ebf49807a6ff7
631,535
def read_file_str(filename): """Read the file and return as a string.""" with open(filename, "r") as f: file_str = f.read() return file_str
973939c2173ae374c12ca4dd8e325ef0adb03b95
631,536
import requests from pathlib import Path import tempfile import shutil def download_file(url: str) -> str: """ Download ngrok binary file to local Args: url (:code:`str`): URL to download Returns: :code:`download_path`: str """ local_filename = url.split("/")[-1] ...
93f4f6acbd6e08272d8dc9fd9b0f079be0c8ab94
631,537
from typing import Dict from typing import List def compute_recall_at_k( question_id_to_docs: Dict[str, List[dict]], k: int, relevance_threshold: float ) -> float: """ Given a dictionary mapping a question id to a list of docs, find the recall@k. We define recall@k = 1.0 if any document in the top-k ...
d912809c1aa96b0a7da05e5ab23a4e823e804923
631,538
def _(s, truncateAt=None): """Nicely print a string to sys.stdout, optionally truncating it a the given char.""" if truncateAt is not None: s = s[:truncateAt] return s
3d4cf40e19c3412d6c7fd6fb68077291c067ff6c
631,540
from typing import List import warnings def find_warning(caught: List[warnings.WarningMessage], msg: str) -> bool: """Return whether exactly one matching warning was caught. This only works for UserWarning subclasses. Arguments: caught: The messages to check. msg: The warning message str...
b9bda98135bd97028880b015c5f3a9af625efdaa
631,542
def get_files() -> list: """Gets a list of paths of files the user wants to compare""" files = [] while True: file = input("Enter the path of a file to compare (or enter to quit): ") if file == "": break files.append(file) return files
d47a95448f6b69acbc517e48f2862371e3f09208
631,543
def _atomic_hotspot_ins(jobname, probename, settings): """ template for atomic hotspot input file (SuperStar ins) :param str jobname: general format (<probe_type>.ins) :param str probename: probe identifier :param `hotspots.atomic_hotspot_calculation.AtomicHotspot.Settings`settings: :return: str...
242f6a0b47221000f77862ef76dcabbcc0d8a08a
631,544
def all_anagrams(chars: str) -> list[str]: """ Returns: A list of all permutations of a given string of characters, without character repetition. Example: >>> print(all_anagrams('abc')) >>> ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] """ result: list[str] = [] if len(cha...
77bfcfce65cb21998de8c5f9fc0fe4e5dd8bb8bf
631,546
def _inject_encrypted_credentials(dataproc, project, region, cluster_name, cluster_uuid, credentials_ciphertext): """Inject credentials into the given cluster. The credentials must have already been encrypted before calling this method. Args: dataproc: The API client for ca...
951e3cec056be3a119449b809132ba5bc21c7c5b
631,547
def from_file(filename): """Open a file and read its first line. :param filename: the name of the file to be read :returns: string -- the first line of filename, stripped of the final '\n' :raises: IOError """ with open(filename) as f: value = f.readline().rstrip('\n') return value
35c0e5cd7461e990ba0c5e33b9ace4b18dfb649b
631,550
def psf_sample_to_pupil_sample(psf_sample, samples, wavelength, efl): """Convert PSF sample spacing to pupil sample spacing. Parameters ---------- psf_sample : float sample spacing in the PSF plane samples : int number of samples present in both planes (must be equal) wavelength...
420196a40438b4aaf1fb2dfe6075418a99d1a614
631,552