content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_aggregated_metrics_from_dict(input_metric_dict): """Get a dictionary of the mean metric values (to log) from a dictionary of metric values""" metric_dict = {} for metric_name, metric_value in input_metric_dict.items(): metric_dim = len(metric_value.shape) if metric_dim == 0: metric_dict[metric_name] =...
7570ed93878ac899a9d89f22a070ea70eab12f98
660,073
def to_float(v): """Convert a string into a better type. >>> to_float('foo') 'foo' >>> to_float('1.23') 1.23 >>> to_float('45') 45 """ try: if '.' in v: return float(v) else: return int(v) except: return v
56ada02c7d0e31a186f9ac6b3afc4f6c04a993f8
660,074
def get_public_instances(game): """ Return the instance ids of public instances for the specified game. Args: game: The parent Game database model to query for instances. Returns: An empty list if game is None. Else, returns a list of the instance ids of all joinable public instances with game as ...
035a25a1b41c5889191da600b7791c9c89637e11
660,076
def lift_calc(PPV, PRE): """ Calculate lift score. :param PPV: precision or positive predictive value :type PPV : float :param PRE: Prevalence :type PRE : float :return: lift score as float """ try: return PPV / PRE except Exception: return "None"
8e43458ad9bdceacf5613597c3b1bb00f8dd69ec
660,079
def change_exclusion_header_format(header): """ Method to modify the exclusion header format. ex: content-type to Content-Type""" if type(header) is list: tmp_list = list() for head in header: tmp = head.split("-") val = str() for t in tmp: ...
498a66b68f7bbef26f6cb07c3292ffc7a20ad8d5
660,080
def update_mean(new_data, old_mean, num_data): """Compute a new mean recursively using the old mean and new measurement From the arithmetic mean computed using the n-1 measurements (M_n-1), we compute the new mean (M_n) adding a new measurement (X_n) with the formula: M_n = M_n-1 + (X_n - M_n-1)/n ...
8daf0d5acf369fa059e81caa4a2f95a1102780c2
660,091
def quantize(source, steps=32767): """ Quantize signal so that there are N steps in the unit interval. """ i_steps = 1.0 / steps return [round(sample * steps) * i_steps for sample in source]
3d879a4b35a384ef9fcaabdadb07f9b7b4e721f8
660,093
def fibonacci(n: int) -> int: """Compute the N-th fibonacci number.""" if n in (0, 1): return 1 return fibonacci(n - 1) + fibonacci(n - 2)
cbefe9914fa5aa2a1eb445eb00a5c932ee04d0e6
660,098
def test_pp_model(text, pp_tokenizer, pp_model): """Get some paraphrases for a bit of text""" print("ORIGINAL\n",text) num_beams = 10 num_return_sequences = 10 batch = pp_tokenizer([text], return_tensors='pt', max_length=60, truncation=True) translated = pp_model.generate(**batch, num_beams=num_...
10394e7fe39e568f67c0347e09024ae21ca30d96
660,101
def none_formatter(error): """ Formatter that does nothing, no escaping HTML, nothin' """ return error
a08468a71060cf6f629c6f8b9b9e0c1dabc5f60d
660,102
def point_inside_polygon(polygon, p, thresh_val=0): """ Returns true if the point p lies inside the polygon (ndarray) Checks if point lies in a thresholded area :param polygon: ndarray that represents the thresholded image contour that we want to circle pack :param p: ndarray 1x2 representing a poi...
3faa905a7ddf3ce5e6a176f301222e0c993a0f1e
660,103
def np_get_index(ndim,axis,slice_number): """ Construct an index for used in slicing numpy array by specifying the axis and the slice in the axis. Parameters: ----------- 1. axis: the axis of the array. 2. slice_number: the 0-based slice number in the axis. 3. ndim: the ndim of the ...
211cf4d29b730a72e481296ddb244f99d14df224
660,107
def leftjust_lines(lines): # 2007 May 25 """Left justify lines of text. Lines is a Python list of strings *without* new-line terminators. The result is a Python list of strings *without* new-Line terminators. """ result = [line.strip() for line in lines] return result
b7e5de88bd3f5e8234ca9a7363302fa608ab967e
660,108
def final_metric(low_corr: float, high_corr: float) -> float: """Metric as defined on the page https://signate.jp/competitions/423#evaluation Args: low_corr (float): low model spearman high_corr (float): high model spearman Returns: float: final evaluation metric as defi...
ff1f1283f5e12917cc72a1c3a72bd2292690ea2a
660,110
import json def _parse_json_file(data): """Parse the data from a json file. Args: data (filepointer): File-like object containing a Json document, to be parsed into json. Returns: dict: The file successfully parsed into a dict. Raises: ValueError: If there was an...
b7cfafd6c8985e36bc8b8399c69ed27e6c613129
660,112
from typing import Tuple def parse_description(description: str) -> Tuple[int, str]: """Parse task description into amount and currency.""" raw_amount, currency = description.split(' ') raw_amount = raw_amount.replace('k', '000') return int(raw_amount), currency
181f0f0fb57acae68b6bcbc7315387fdb63e8056
660,119
from typing import Mapping def update(to_update, update_with): """ Recursively update a dictionary with another. :param dict to_update: Dictionary to update. :param dict update_with: Dictionary to update with. :return: The first dictionary recursively updated by the second. :rtype: dict ...
95082bcc6884bf4728801f058be576b5121e4bcb
660,120
def _splitter(value, separator): """ Return a list of values from a `value` string using `separator` as list delimiters. Empty values are NOT returned. """ if not value: return [] return [v.strip() for v in value.split(separator) if v.strip()]
8a2cd3faec1e56b02c6cd4c4ed508193957d9013
660,121
def rprpet_point(pet, snowmelt, avh2o_3, precip): """Calculate the ratio of precipitation to ref evapotranspiration. The ratio of precipitation or snowmelt to reference evapotranspiration influences agdefac and bgdefac, the above- and belowground decomposition factors. Parameters: pet (flo...
94473f9dc1dab4dffaf8a7556ed4109a3a7497a1
660,122
def form2audio(cldf, mimetype='audio/mpeg'): """ Read a media table augmented with a formReference column. :return: `dict` mapping form ID to audio file. """ res = {} for r in cldf.iter_rows('media.csv', 'id', 'formReference'): if r['mimetype'] == mimetype: res[r['formRefere...
460f3b73f407a4c0c8bf0157c4b141f418aa6bcf
660,132
def get_value_of_bills(denomination, number_of_bills): """ The total value of bills you now have. :param denomination: int - the value of a bill. :param number_of_bills: int - amount of bills you received. :return: int - total value of bills you now have """ return denomination * number_of...
39c243588fafc32c5e5c962cacf11c0154411a22
660,133
def strip_script(environ): """ Strips the script portion of a url path so the middleware works even when mounted under a path other than root. """ path = environ['PATH_INFO'] if path.startswith('/') and 'SCRIPT_NAME' in environ: prefix = environ.get('SCRIPT_NAME') if prefix.endsw...
3ec4a8da3289ea8fd281328bbc74b8fab525a366
660,136
def truncateWord32(value): """ Truncate an unsigned integer to 32 bits. """ return value & 0xFFFFFFFF
67ea12cf212590c2a7cb2f09879ca499364b5ce6
660,137
def _strip_comments_from_pex_json_lockfile(lockfile_bytes: bytes) -> bytes: """Pex does not like the header Pants adds to lockfiles, as it violates JSON. Note that we only strip lines starting with `//`, which is all that Pants will ever add. If users add their own comments, things will fail. """ r...
2ccba30bd4ecdbb41432496e9d34c1975934f621
660,139
def subcloud_db_model_to_dict(subcloud): """Convert subcloud db model to dictionary.""" result = {"id": subcloud.id, "name": subcloud.name, "description": subcloud.description, "location": subcloud.location, "software-version": subcloud.software_version, ...
f1a4d1ec6f838522b5dcf8d5109aa52a95c7d5d8
660,142
def remove_non_printable_chars(s): """ removes 'ZERO WIDTH SPACE' (U+200B) 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF) """ return s.replace(u'\ufeff', '').replace(u'\u200f', '')
670dce3bf9d77816d64d1311270e898d2801b6dd
660,146
def diffmean(xl, yl): """Return the difference between the means of 2 lists.""" return abs(sum(xl) / len(xl) - sum(yl) / len(yl))
36a449f68311f6ec8b23698c9c9797501eb73240
660,150
def _multihex (blob): """Prepare a hex dump of binary data, given in any common form including [[str]], [[list]], [[bytes]], or [[bytearray]].""" return ' '.join(['%02X' % b for b in bytearray(blob)])
b5f7698275e9e71b6e1c70bf728277a27c78c30e
660,152
def is_disabled(field): """ Returns True if fields is disabled, readonly or not marked as editable, False otherwise """ if not getattr(field.field, 'editable', True): return True if getattr(field.field.widget.attrs, 'readonly', False): return True if getattr(field.field.widget.at...
e1b7064d0a1cb54fa7539f84460893b886202d53
660,154
def escape_chars(s): """ Performs character escaping of comma, pipe and equals characters """ return "".join(['\\' + ch if ch in '=|,' else ch for ch in s])
a28d3a991e34e480291c7c51ee7b4a5d367c5588
660,156
def unordered_types_overall(x_name_type_unord): """Create dummies capturing if particular types of unordered vars exit. Parameters ---------- x_name_type_unord : list of 0,1,2 Returns ------- type_0, type_1, type_2 : Boolean. Type exist """ type_2 = bool(2 in x_name_type_unord) ...
6cabf76a62875960e920179db79f0d7eb4a210e5
660,160
def slugify(str_): """Remove single quotes, brackets, and newline characters from a string.""" bad_chars = ["'", '[', ']', '\n', '<', '>' , '\\'] for ch in bad_chars: str_ = str_.replace(ch, '') return str_
e170ee44bea9d96eefbad2c7f2f4fa81efc18a42
660,167
def _extract_image(img, x_off, y_off, max_x, max_y): """Returns a subsection of the image Args: img(numpy array): the source image (with 2 or 3 size dimensions) x_off(int): the starting X clip position (0th index of image) y_off(int): the starting Y clip position (1st index of image) ...
520a72a8b5778e385f93bdfc9d40bec4210b0683
660,179
def _dict_mixed_empty_parser(v, v_delimiter): """ Parse a value into the appropriate form, for a mixed value based column. Args: v: The raw string value parsed from a column. v_delimiter: The delimiter between components of the value. Returns: The parsed value, which can either...
b0529b5248fe371f4e6371aa5c7ea9962ac1c928
660,180
def calc_ifg_delay(master_delay, slave_delay): """Calculate the interferometric delay. Arguments --------- master_delay : (n,m) ndarray Matrix containing the atmospheric delay on the master date. slave_delay : (n,m) ndarray Matrix containing the atmospheric delay on the slave date. ...
3fdf12807037c9371f2228c56282b90bab9ac9c3
660,185
import pathlib def make_subdirectory(directory, append_name=""): """Makes subdirectories. Parameters ---------- directory : str or pathlib object A string with the path of directory where subdirectories should be created. append_name : str A string to be appended to the directory ...
abf42b0d7f85af9bf6728001eac652de513ffba4
660,186
def Kt_real_deph(alpha_liq_deph, alpha_cond_deph, sigma_thermpollution_deph): """ Calculates the coefficient of heat transfer (Kt). Parameters ---------- alpha_liq_deph : float The coefficent of heat transfer(alpha), [W / (m**2 * degrees celcium)] alpha_cond_deph : float The coef...
c630f740fb4d295975c4c5b844b0410e0134ec04
660,187
def strip_2tuple(dict): """ Strips the second value of the tuple out of a dictionary {key: (first, second)} => {key: first} """ new_dict = {} for key, (first, second) in dict.items(): new_dict[key] = first return new_dict
20f721da141f75bceb8bfd90d7ab02dbb82a01ce
660,188
def create_dict(list1, list2, key1, key2): """Create list of dictionaries from two lists """ list_dict = [] for i in range(len(list1)): dictionary = {key1 : list1[i], key2 : list2[i]} list_dict.append(dictionary) return list_dict
ee83e989ef22925f6db04f0de1078db3c553c965
660,193
def _num_starting_hashes(line: str) -> int: """Return the number of hashes (#) at the beginning of the line.""" if not line: return 0 for n, char in enumerate(line, start=0): if char != "#": return n return len(line)
915ed7fbb971f14bcc6795f95d674afe43d41f32
660,194
def greedy_coloring(adj): """Determines a vertex coloring. Args: adj (dict): The edge structure of the graph to be colored. `adj` should be of the form {node: neighbors, ...} where neighbors is a set. Returns: dict: the coloring {node: color, ...} dict: the ...
23fd23fafabb0bbb5b7facde33ebc7b3c7be6734
660,196
def position_side_formatter(side_name): """ Create a formatter that extracts and formats the long or short side from a Position Args: side_name: "long" or "short" indicating which side of the position to format """ def f(p): """The formatting function for the ...
b286d2fee11788934b62522f1fa4492ecd2586e5
660,197
def get_mean_score(rating_scores): """Compute the mean rating score given a list. Args: rating_scores: a list of rating scores. Returns: The mean rating. """ return sum(rating_scores) / len(rating_scores)
c6c5cc165ed078961c779ccff23db8d948e1c455
660,205
def tstv(ts, tv): """ Calculate ts/tv, and avoid division by zero error """ try: return round(float(ts) / float(tv), 4) except ZeroDivisionError: return 0
a9a876ef2d8cddae3a8844ac52a611abcbaf4ddd
660,208
def is_convolution_or_linear(layer): """ Return True if `layer` is a convolution or a linear layer """ classname = layer.__class__.__name__ if classname.find('Conv') != -1: return True if classname.find('Linear') != -1: return True return False
c7bbaedf40aa6b34079eac068bf50ed90734e819
660,209
import requests from bs4 import BeautifulSoup def get_chapters_raw(page_url): """Return BeautifulSoup object of chapter page""" r = requests.get(page_url) return BeautifulSoup(r.text, "lxml")
02c0653f8369ad74aa6f308c065a9e26ec2c47e5
660,212
def zero_if_less_than(x, eps): """Return 0 if x<eps, otherwise return x""" if x < eps: return 0 else: return x
67ee0c584eef4432c683b3b568f92605ff55b297
660,216
import math def date_to_jd(year,month,day): """ Convert a date to Julian Day. Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet', 4th ed., Duffet-Smith and Zwart, 2011. Parameters ---------- year : int Year as integer. Years preceding 1 A.D. should be 0 ...
2b50233e64361398dd856e237ce791a4aac6b870
660,225
def create_masked_lm_predictions_force_last(tokens): """Creates the predictions for the masked LM objective.""" last_index = -1 for (i, token) in enumerate(tokens): if token == "[CLS]" or token == "[PAD]" or token == '[NO_USE]': continue last_index = i assert last_index > 0...
e6e2a5e774bfd419bc01f71d5113d0d0adf9e60b
660,226
from typing import Tuple def deserialize_ecdsa_recoverable(signature: bytes) -> Tuple[int, int, int]: """ deserialize recoverable ECDSA signature from bytes to (r, s, recovery_id) """ assert len(signature) == 65, 'invalid length of recoverable ECDSA signature' recovery_id = signature[-1] asser...
b47bd8e2f117048057a1a03395f78d61a1509346
660,227
def semi_loss_func(ac, full_ob, semi_dataset, is_relative_actions=False): """ get the L2 loss between generated actions and semi supervised actions :param ac: the semi supervised actions :param full_ob: the full observations of the semi supervised dataset :param semi_dataset: the semi supervised dat...
6718b42cbe86ea75d1593694704ac6a7ffd881f8
660,228
def index_generation(crt_i, max_n, N, padding='reflection'): """Generate an index list for reading N frames from a sequence of images Args: crt_i (int): current center index max_n (int): max number of the sequence of images (calculated from 1) N (int): reading N frames padding (s...
559f6bb3278de6e920396489b4018dbc80e5f065
660,230
def NoTestRunnerFiles(path, dent, is_dir): """Filter function that can be passed to FindCFiles or FindHeaderFiles in order to exclude test runner files.""" # NOTE(martinkr): This prevents .h/.cc files in src/ssl/test/runner, which # are in their own subpackage, from being included in boringssl/BUILD files. re...
3401046d340c8746b2fd1ee5b49ac47bfa97566c
660,231
from typing import List def chunk(s: str, n: int = 80) -> List[str]: """Chunk string into segments of specified length. >>> chunk(('wordsX' * 5), 11) ['wordsXwords', 'XwordsXword', 'sXwordsX'] >>> chunk('x', 80) ['x'] """ return [s[i:i + n] for i in range(0, len(s), n)]
dcc20fa7323a650c8da72de67946a71406354e14
660,240
import math def dist(p1, p2): """ Compute euclidean distance :param p1: first coordinate tuple :param p2: second coordinate tuple :return: distance Float """ return math.sqrt((p2[0] - p1[0]) ** 2 + (p1[1] - p2[1]) ** 2)
bf82a24ae52bf528bc54c92fbb0afc46d6cd0117
660,241
def get_answer(s): """Given a choice (A, B, C, D) this function returns the integer index representation of that choice (0, 1, 2, 3)""" return 'ABCD'.index(s)
c8f785642f6ae276fab70705108b589e88e92098
660,243
import click def ensure_valid_type(node_type_choices: click.Choice, node_type: str) -> str: """Uses click's convert_type function to check the validity of the specified node_type. Re-raises with a custom error message to ensure consistency across click versions. """ try: click.types.conver...
27d0b57931690066c64fb2343d419dfe8a104d8e
660,248
import torch def _mean_plus_r_var(data: torch.Tensor, ratio: float = 0, **kwargs): """ Function caclulates mean + ratio * stdv. and returns the largest of this value and the smallest element in the list (can happen when ratio is negative). """ return max( data.min().item(), dat...
4a9ea4b23f144d2834b8b972b0a1f70c2a289788
660,251
import base64 def b64_to_utf8_decode(b64_str): """Decode base64 string to UTF-8.""" return base64.urlsafe_b64decode(b64_str).decode('utf-8')
21c80f077f52ea1df523a2d0aac8c547f8a7875e
660,256
def roll(l): """rolls a list to the right e.g.: roll([0,1,1]) => [1,0,1] """ tmp1, tmp2 = l[:-1], l[-1] l[1:] = tmp1 l[0] = tmp2 return l
9a3b1566cac74d78037842455eccda63278a65bc
660,257
def std_pres(elev): """Calculate standard pressure. Args: elev (float): Elevation above sea-level in meters Returns: float: Standard Pressure (kPa) """ return 101.325 * (((293.0 - 0.0065 * elev) / 293.0) ** 5.26)
c269f872f038efff6eb26c83cfb931033301a045
660,258
def add_obs_prob_to_dict(dictionary, obs, prob): """ Updates a dictionary that tracks a probability distribution over observations. """ obs_str = obs.tostring() if obs_str not in dictionary: dictionary[obs_str] = 0 dictionary[obs_str] += prob return dictionary
24ef9386cc9da12cd0c4a0df145e4fa78b44686d
660,270
def sphere_to_plane_car(az0, el0, az, el): """Project sphere to plane using plate carree (CAR) projection. The target point can be anywhere on the sphere. The output (x, y) coordinates are likewise unrestricted. Please read the module documentation for the interpretation of the input parameters an...
0af644382f75f7278271ad048d66e8e20492ed8c
660,272
import math def sqrt(value): """Returns the square root of a value""" return math.sqrt(value)
52d0b34be5dec7f46392a2ba732438be007fe010
660,274
def cov_files_by_platform(reads, assembly, platform): """ Return a list of coverage files for a given sequencing platform. """ accessions = [] if reads is not None: accessions += [accession for accession in reads if reads[accession]['platform'] == platform] return list(map(lambda sra: "%...
ae2e5b71e03141e9fb38247a463380ceba80cf3d
660,275
from datetime import datetime def get_time_delta(start_time: str, end_time: str): """Returns the difference between two times in minutes""" t1 = datetime.strptime(start_time, "%Y-%m-%d_%H-%M-%S") t2 = datetime.strptime(end_time, "%Y-%m-%d_%H-%M-%S") delta = t2 - t1 return int(delta.seconds / 60)
59f8f9742b746ea67d5ef5d954b77f651a3ada0c
660,276
def symmetric_closure_function(rel): """ Function to determine the symmetric closure of a relation :param rel: A list that represents a relation :return: The symmetric closure of relation rel """ return rel + [(y, x) for (x, y) in rel if (y, x) not in rel]
c43b123de13931d1caa4088f23b896c1f56f2c1f
660,277
import torch def get_pyg_edge_index(graph, both_dir=True): """ Get edge_index for an instance of torch_geometric.data.Data. Args: graph: networkx Graph both_dir: boolean; whether to include reverse edge from graph Return: torch.LongTensor of edge_index with size [2, num_e...
d0300a93a6e4a68302d04dfa8b646b92c7ac256b
660,279
def ctypes_shape(x): """Infer shape of a ctypes array.""" try: dim = x._length_ return (dim,) + ctypes_shape(x[0]) except AttributeError: return ()
13c81a6028a49c41a74f2623cb7936323602795e
660,280
def get_magicc6_to_magicc7_variable_mapping(inverse=False): """Get the mappings from MAGICC6 to MAGICC7 variables. Note that this mapping is not one to one. For example, "HFC4310", "HFC43-10" and "HFC-43-10" in MAGICC6 both map to "HFC4310" in MAGICC7 but "HFC4310" in MAGICC7 maps back to "HFC4310". ...
822cff3dac5b8aa18ce5f0e6c4bd13b9762a41e6
660,282
def assert_train_test_temporal_consistency(t_train, t_test): """Helper function to assert train-test temporal constraint (C1). All objects in the training set need to be temporally anterior to all objects in the testing set. Violating this constraint will positively bias the results by integrating "fut...
92842014832ddb2d8e9b3a97172f92f5d9f82bed
660,286
def _layout_column_width(col): """ Returns the logical column width of a column """ column_equivs = [pi.column_equiv for pi in col.presinfo if pi.column_equiv is not None] if len(column_equivs) > 0: # assume user has not done something silly like put # *2* column_equiv classes on a c...
f3df6c0863e2f04c4808b4817ccabb4a304bb951
660,289
def get_one_col_str(i_col, line): """ extract the column index in line i_col: index of column line: string """ col_split = '\t' return line.split(col_split)[i_col]
ce8a63e0522f2038452ef33d751c2a3feb69b974
660,294
import spwd def unix_crypted_shadow_password(username): """ Requests the crypted shadow password on unix systems for a specific user and returns it. """ crypted_password = spwd.getspnam(username)[1] return crypted_password
2fd5f59176ebc1256c5dff70e0f4e6d773af2aa2
660,298
from typing import Tuple import re def _lex_whitespace(header: str) -> Tuple[str, str]: """ >>> _lex_whitespace(" \\n a") ('', 'a') >>> _lex_whitespace(" abc") ('', 'abc') >>> _lex_whitespace("a ") ('', 'a ') """ whitespace_match = re.match(r"\s+", header) if not whitespace_ma...
7e8a0d856d9c3726850f93bbbfb6bebd73271d7f
660,299
def compute_cchalf(mean, var): """ Compute the CC 1/2 using the formular from Assmann, Brehm and Diederichs 2016 :param mean: The list of mean intensities :param var: The list of variances on the half set of mean intensities :returns: The CC 1/2 """ assert len(mean) == len(var) n = len(...
f8cb9de5a4b4367be4be3b4125316ae56210a78b
660,303
def attrFinder(attrib, attribString): """Easy function to pull attributes from column 8 of gtf files""" for entry in attribString.split(";"): if entry.lstrip().startswith(attrib): return entry.lstrip().split(" ")[1][1:-1] return None
2838ebea0caada50d527b57c8c5008989e6c88a3
660,304
import warnings def _method_cache_key_generator(*args, **kwargs) -> int: """A cache key generator implementation for methods. This generator does not implement any hashing for keyword arguments. Additionally, it skips the first argument provided to the function, which is assumed to be a class instanc...
00e8b26beb63a1c44fad35fce0cea2d132e79f38
660,305
def _mst_path(csgraph, predecessors, start, end): """Construct a path along the minimum spanning tree""" preds = predecessors[start] path = [end] while end != start: end = preds[start, end] path.append(end) return path[::-1]
7ce30eb6c155dab1fe8dad886b1adf2a4f71b408
660,308
def kewley_sf_nii(log_nii_ha): """Star forming classification line for log([NII]/Ha).""" return 0.61 / (log_nii_ha - 0.05) + 1.3
e44dade36ffc5879c3206dbf9aaaa30b9dfbcf3f
660,310
import math def calc_distance(ij_start, ij_end, R): """" Calculate distance from start to end point Args: ij_start: The coordinate of origin point with (0,0) in the upper-left corner ij_end: The coordinate of destination point with (0,0) in the upper-left corner R: Map resolution ...
4242d8fe01f3d286f69aac2a9432726280271530
660,314
from datetime import datetime, timedelta def ldap_to_datetime(timestamp: float): """ Takes an LDAP timestamp and converts it to a datetime object """ return datetime(1601, 1, 1) + timedelta(timestamp/10000000)
c4d42c606a220ba67b6ac2860cb3df87775b38bd
660,316
def parse_dss_bus_name(dss_bus_name: str, sep='.') -> str: """ Given a bus name string that may include phase from opendss, returns just the busname. Assumes that dss appends bus names with phases, separated by '.' Ex: 'sourcebus.1.2.3' -> 'sourcebus' """ return dss_bus_name.split(sep)[0]
7bec2a59724381f99a95df45e60b1bcbffbb05e9
660,318
import re def get_version(filename='canaveral/__init__.py'): """ Extract version information stored as a tuple in source code """ version = '' with open(filename, 'r') as fp: for line in fp: m = re.search("__version__ = '(.*)'", line) if m is not None: versi...
80c2e54b2b9b435162ac9f2879d6122055140f04
660,319
def rk4(x,t,tau,derivsRK,**kwargs): """ Runge-Kutta integrator (4th order). Calling format derivsRK(x,t,**kwargs). Inputs: x current value of dependent variable t independent variable (usually time) tau step size (usually timestep) derivsRK ri...
5010992dcecb39943750e5043fc6b489c3fa0a37
660,325
import math def cos(X, max_order=30): """ A taylor series expansion for cos The parameter `max_order` is the maximum order of the taylor series to use """ op = 1 + 0*X X2 = X * X X2n = 1 + 0*X for n in range(1, max_order): X2n = X2n*X2 op = op + ((-1) ** (n) / math.gamm...
151987cac39f3cf71276cc34fbdf4c5af5be673a
660,327
def fib(n): """ Assumes n an int >= 0 Returns Fibonacci of n""" if n == 0 or n == 1: return 1 else: return fib(n-1) + fib(n-2)
477816f8aa60c444528f99124f85b7e87ad6272d
660,328
def _unsplit_name(name): """ Convert "this_name" into "This Name". """ return " ".join(s.capitalize() for s in name.split('_'))
9dd79695af74bb1755a09169870b7c2de472353c
660,331
def listminus(L1, L2): """In : L1 : list or set L2 : list or set Out: List of items in L1 that are not in L2. Helper for min_dfa and bash_1. Implements subtraction (L1 - L2). """ return [x for x in L1 if x not in L2]
d5b39b530fd41493b53975c7ed34eab9bf55425d
660,333
from typing import List from typing import Optional def str_replace(s: str, old: List[str], new: Optional[List[str]] = None) -> str: """Replaces occurences of all strings in *old* by the corresponding ones in *new*. If None is passed in new, *old* are simply removed fromm *s*""" if new is None: new = ['']...
9c070a2f6d3d3e63a32498fc5e5cdb3b3c55292b
660,336
def precision(cm): """ Return precision. :param cm: Confusion matrix. :return: Value of precision. """ return float(cm[1, 1]) / (cm[1, 1] + cm[0, 1])
5f919854b4b329daea17e1d798c2e848c5bc847f
660,339
def get_window_g_value(window): """For windows based on SimpleGlazingSystems, returns the g-value. Otherwise, an exception is thrown. """ assert hasattr(window.Type.Layers[0].Material, 'GValue'), \ "SimpleGlazingSystem required" assert len(window.Type.Layers) == 1, "SimpleGlazingSystem requi...
2d6c0b2c0d11ac693ce8a0c99ed57583f52dc8d0
660,341
def crop(image, startX, startY, endX, endY): """ Crop an image :param image: Image to be cropped :param startX: Starting X coord :param startY: Starting Y coord :param endX: Ending X coord :param endY: Ending Y coord :return: Cropped image """ cropped = image[startY:endY, startX...
361d9f799aef03f3ce9d621550801c4d2a293b3b
660,342
from typing import List from typing import Dict def csv_to_list(data: List[List], fields: List[str]) -> List[Dict[str, str]]: """ Converts the raw csv column to a list of dicts with the specified field names """ return list(dict(zip(fields, f)) for f in data if f)
137fd6c051e7e7af7b9430ce082871c6097a30ca
660,343
def tokenise_text_col(df, text_col="text", suffix="_tokens", return_col_name = False): """ wrapper function for a list comprehenshion that tokenises a text column in df, returning df with a new column containing tokenised text Args: df: dataframe with text data text_col: column with tex...
4d9ce6c6b30e399dce6fd191bc337bfae4e5fc4a
660,346
import requests def download_file(url: str, prefix=""): """Download file by streaming and writing to file. Args: url: download url. prefix: prefix for output file. """ local_filename = url.split("/")[-1] with requests.get(url, stream=True) as r: r.raise_for_status() ...
7485b6d94415f986c63635bf8de0d71eb4577567
660,348
import fnmatch def getLabels(source, path): """Get all labels for given path :param source: Labels definition :type path: dict :param path: File full path :type path: string :return: Labels :rtype: list[string] """ result = [] for label, patterns in source.items(): ...
0310e38b185016f781ff2a958f4e6bbd82d86d39
660,352
def stream_element_handler(element_name, usage_restriction = None): """Method decorator generator for decorating stream element handler methods in `StreamFeatureHandler` subclasses. :Parameters: - `element_name`: stream element QName - `usage_restriction`: optional usage restriction: "initi...
3e424c67c0839a1b3d4beccbf546b8b6d4b6ba33
660,355
def normalize_host(host): """Normalize a host string.""" return host.lower()
f533fae1c740c9ce54e53d10a82f24ddd2f2da2f
660,359
import json from pathlib import Path def load_test_data(filename: str) -> list: """Utility function to load JSON files from 'test_data'""" json_file_path = ( Path(__file__).parent.joinpath("test_data").joinpath(filename).resolve() ) if not json_file_path.exists(): raise RuntimeError(f...
2e2cf2c43212136007132311087f9e5bfdbc0679
660,360