content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def dump_feature(feature): """ Gets a single feature as a dictionary, and returns it rendered as a string """ s = "|f " for _key in sorted(feature.keys()): s += "{}:{} ".format(_key, feature[_key]) return s
b20dff368943aecbe485778b3cded552db56ffb0
686,435
def remove_padding(im, pad): """ Function for removing padding from an image. :param im: image to remove padding from :param pad: number of pixels of padding to remove :return: """ return im[pad:-pad, pad:-pad]
58d822dc9ab587f63d1a98eb19e17268d75b2ab4
686,436
def about_view(request): """Return about page.""" return {}
70a2324c5e7d578c83f6603f8fe81bbb6c258a97
686,437
import torch def split_with_shape(tensor_flatten, mask_flatten, tensor_shape): """ Params: :tensor_flatten: (B, L, C) :mask_flatten: (B, L) :tensor_shape: (N, 2) Return: :tensor_list: [(B, H1 * W1, C), ..., (B, HN * WN, C)] :mask_list: [(B, H1 * W1), ..., (B, HN * WN)] """ chunk_sizes = (tensor_shape[:, 0] * tensor_shape[:, 1]).tolist() if tensor_flatten is None and mask_flatten is None: raise ValueError("Both tensor and mask are None") if tensor_flatten is not None: tensor_list = torch.split(tensor_flatten, chunk_sizes, dim=1) else: tensor_list = None if mask_flatten is not None: mask_list = torch.split(mask_flatten, chunk_sizes, dim=1) else: mask_list = None return tensor_list, mask_list
9fd537ac1261ce13e7faef2078fa4c2960699169
686,438
def uniqueArrayName(dataset, name0): """ Generate a unique name for a DataArray in a dataset """ ii = 0 name = name0 while name in dataset.arrays: name = name0 + '_%d' % ii ii = ii + 1 if ii > 1000: raise Exception('too many arrays in DataSet') return name
d7da95a9e3a9d959012c101bbc40495a1e085dfd
686,439
import importlib def _import_module(mocker): """Fixture providing import_module mock.""" return mocker.Mock(spec_set=importlib.import_module)
67db797fdfe5602134b2ef0feaa6efded8865938
686,442
def bin2int(bin): """convert the binary (as string) to integer""" #print('bin conversion', bin, int(bin, 2)) return int(bin, 2)
def903c6015c13629b6c1778c69e747a82bb32be
686,443
def _ci_to_hgvs_coord(s, e): """ Convert continuous interbase (right-open) coordinates (..,-2,-1,0,1,..) to discontinuous HGVS coordinates (..,-2,-1,1,2,..) """ def _ci_to_hgvs(c): return c + 1 if c >= 0 else c return (None if s is None else _ci_to_hgvs(s), None if e is None else _ci_to_hgvs(e) - 1)
a25cee5f587b59fd52779f6eeba363f3ddda77b0
686,444
def num_sevens(n): """Returns the number of times 7 appears as a digit of n. >>> num_sevens(3) 0 >>> num_sevens(7) 1 >>> num_sevens(7777777) 7 >>> num_sevens(2637) 1 >>> num_sevens(76370) 2 >>> num_sevens(12345) 0 >>> from construct_check import check >>> # ban all assignment statements >>> check(HW_SOURCE_FILE, 'num_sevens', ... ['Assign', 'AugAssign']) True """ if n == 0: return 0 if n % 10 == 7: return num_sevens(n // 10) + 1 else: return num_sevens(n // 10)
67e3da342208fa130cd0d1400acfbe3d27585d0b
686,445
def _recurse_on_subclasses(klass): """Return as a set all subclasses in a classes' subclass hierarchy.""" return set(klass.__subclasses__()).union( [ sub for cls in klass.__subclasses__() for sub in _recurse_on_subclasses(cls) ] )
4fb399c5362ab0019e07c76e71cf16139c0be49a
686,447
def average_word_length(tweet): """ Return the average length of the tweet :param tweet: raw text tweet :return: the float number of character count divided by the word count """ character_count = 0 word_count = 0 for c in tweet: character_count += 1 word_count = len(tweet.split()) return float(character_count)/float(word_count)
4077e531c69b51f6df74546b0e84fc41720ffbe5
686,449
def flatten_dataframe_for_JSON(df): """Flatten a pandas dataframe to a plain list, suitable for JSON serialisation""" return df.values.flatten().tolist()
ef4ad28904f083f1d86daefab25ce13faf36a344
686,452
def _indent(text, amount): """Indent a multiline string by some number of spaces. Parameters ---------- text: str The text to be indented amount: int The number of spaces to indent the text Returns ------- indented_text """ indentation = amount * ' ' return indentation + ('\n' + indentation).join(text.split('\n'))
cf571a3d616e99547757c8ec7d69307985362280
686,455
def normalize(x, xmin, xmax): """Normalize `x` given explicit min/max values. """ return (x - xmin) / (xmax - xmin)
92d9e0d7e5aad9ee9ff83f3adb042161a3702aec
686,456
def _translate_snapshot_summary_view(context, vol): """Maps keys for snapshots summary view.""" d = {} d['id'] = vol['id'] d['volumeId'] = vol['volume_id'] d['status'] = vol['status'] # NOTE(gagupta): We map volume_size as the snapshot size d['size'] = vol['volume_size'] d['createdAt'] = vol['created_at'] d['displayName'] = vol['display_name'] d['displayDescription'] = vol['display_description'] return d
9e0fd90e7c6cd702b8309fae3f8122032e1ec854
686,457
from typing import List from typing import Dict import csv def read_csv(path: str) -> List[Dict[str, str]]: """Reads a csv file, and returns the content inside a list of dictionaries. Args: path: The path to the csv file. Returns: A list of dictionaries. Each row in the csv file will be a list entry. The dictionary is keyed by the column names. """ with open(path, 'r') as f: return list(csv.DictReader(f))
4051c851fc8919e5c6cb2c6bfd52793e6ab7f639
686,458
def correct_date(date): """ Converts the date format to one accepted by SWA SWA form cannot accept slashes for dates and is in the format YYYY-MM-DD :param date: Date string to correct :return: Corrected date string """ if date is None: return "" else: a, b, c = date.split("/") if len(a) == 4: # Assumed format is year, month, day return "%s-%s-%s"%(a, b, c) else: # Assumed format is month, day, year return "%s-%s-%s" % (c, a, b)
6b17124b4b5e4a3740b56210fc88ea79ca816434
686,459
def dns_name_encode(name): """ DNS domain name encoder (string to bytes) name -- example: "www.example.com" return -- example: b'\x03www\x07example\x03com\x00' """ name_encoded = [b""] # "www" -> b"www" labels = [part.encode() for part in name.split(".") if len(part) != 0] for label in labels: # b"www" -> "\x03www" name_encoded.append(chr(len(label)).encode() + label) return b"".join(name_encoded) + b"\x00"
48b298ade17d232caf533d462ea5ef125ce78622
686,461
def TestingResources(network_ref, subnet_ref, region, zones): """Get the resources necessary to test an internal load balancer. This creates a test service, and a standalone client. Args: network_ref: A reference to a GCE network for resources to act in. subnet_ref: A reference to a GCE subnetwork for resources to act in. region: The region to deploy the load balancer. zones: A list of zones to deploy the service. Returns: A list of resource definitions. """ return [{ 'name': 'test-service', 'type': 'test_service.py', 'properties': { 'network': network_ref, 'subnet': subnet_ref, 'region': region, 'zones': zones } }, { 'name': 'standalone-client', 'type': 'standalone_test_instance.py', 'properties': { 'network': network_ref, 'subnet': subnet_ref, 'zone': zones[0] } }]
80545f5c4b842bee788a9b03aa9f975ba073d251
686,464
def compute_bigram(input, unigram_count, bigram_count): """ compute_bigram - function to compute bigram probability Inputs: input : tuple bigram unigram_count : defaultdict(int) Occurence hashmap of single words/tokens bigram_count : defaultdict(int) Occurence hasmap of bi-words/tokens Outputs: output : float Bigram probability """ return bigram_count[input] / unigram_count[input[0]]
0e8efd792171ae48b3627779e7cf51a6d60d774f
686,469
def addQuotes(s): """wrap a strings with quotes""" return "\"" + s + "\""
b7895bb9ef872585bfcf9bab2103803dab5b676a
686,476
def remove_matching_braces(latex): """ If `latex` is surrounded by matching braces, remove them. They are not necessary. Parameters ---------- latex : string Returns ------- string Examples -------- >>> remove_matching_braces('{2+2}') '2+2' >>> remove_matching_braces('{2+2') '{2+2' """ if latex.startswith("{") and latex.endswith("}"): opened = 1 matches = True for char in latex[1:-1]: if char == "{": opened += 1 elif char == "}": opened -= 1 if opened == 0: matches = False if matches: latex = latex[1:-1] return latex
67adfaa0962c94515cea43b6f393a910443e32f8
686,479
def point_avg(points): """ Accepts a list of points, each with the same number of dimensions. NB. points can have more dimensions than 2 Returns a new point which is the center of all the points. """ dimensions = len(points[0]) new_center = [] for dimension in range(dimensions): dim_sum = 0 # dimension sum for p in points: dim_sum += p[dimension] # average of each dimension new_center.append(dim_sum / float(len(points))) return new_center
ac82a036ce5b6fdea0e8c842fba065acd16160a4
686,480
def _check_errors(results): """ <SEMI-PRIVATE> Checks whether the results from the Azure API contain errors or not. _check_errors(results) results: [str] The results from the Azure translation API call Returns: bool; True if the API results contain errors. """ errors = False for result in results: if 'translations' not in result: errors = True break return errors
4e35ede6f5146b91022e9a799ed1954897200eab
686,482
from typing import List def join_sublist_element(input_list: List[List[str]]) -> List[str]: """Join each sublist of chars into string. This function joins all the element(chars) in each sub-lists together, and turns every sub-lists to one element in the overall list. The sublist will turned into a string with all the same elements as before. :param input_list: the returned list after cut :return: the list that contains all the segments as strings. """ return ["".join(chars) for chars in input_list]
0594b85d264db84faf39b4b4de3e438dd90d4c11
686,483
import json def make_split_change_event(change_number): """Make a split change event.""" return { 'event': 'message', 'data': json.dumps({ 'id':'TVUsxaabHs:0:0', 'clientId':'pri:MzM0ODI1MTkxMw==', 'timestamp': change_number-1, 'encoding':'json', 'channel':'MTYyMTcxOTQ4Mw==_MjA4MzczNDU1Mg==_splits', 'data': json.dumps({ 'type': 'SPLIT_UPDATE', 'changeNumber': change_number }) }) }
38c79f7b53fd63b83255deea987ebe1c9f4359ed
686,486
import logging def _get_logger(fp, enabled=True, log_level="INFO"): """Create a logger that outputs to supplied filepath Args: enabled (bool): Whether logging is enabled. This function is called in scripts that call it with suppied arguments, and allows the scripts this utility blindly. fp (str): filename of the log log_level (str): Python logging level to set Returns: (logging.logger) logging handle """ # no matter what a fangless logger is created (for cleaner code) logger = logging.getLogger(fp.split("/")[-1].split(".")[0]) logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s \n', datefmt="%Y-%m-%d %H:%M:%S") if enabled: # set filehandler fh = logging.FileHandler(fp, mode='w') fh.setFormatter(formatter) fh.setLevel(getattr(logging, log_level.upper())) logger.addHandler(fh) return logger
1fbbca246b9b235e74ee3d0ee5e1d591c165d322
686,490
def assemble(current_lst): """ :param current_lst: list of index for the string list :return: str, assemble list as string """ string = '' for alphabet in current_lst: string += alphabet return string
86f7b4fc9a72f2cd2ea17600d1bc0e31fcd03c97
686,492
import random def dataset_creation(labeled_data): """Split labeled data into train and test""" one_class = [] zero_class = [] for data_point in labeled_data: if data_point[2] == 0: zero_class.append(data_point) else: one_class.append(data_point) random.shuffle(zero_class) random.shuffle(one_class) training_data = one_class[:len(one_class) // 2] + zero_class[:len(one_class) // 2] test_data = one_class[len(one_class) // 2:] + zero_class[len(one_class) // 2:] return training_data, test_data
e94a6b289d133866b2a4f2a48ded626aeb6228e5
686,495
def is_power_of_two(value: int) -> bool: """ Determine if the given value is a power of 2. Negative numbers and 0 cannot be a power of 2 and will thus return `False`. :param value: The value to check. :return: `True` if the value is a power of two, 0 otherwise. """ if value <= 0: return False # If value is a power of two, its highest bit that is set to 1 will toggle to 0 when subtracting 1 because all # other bits are 0; all other bits will thus be flipped to 1. Therefore, value and (value - 1) don't have any bits # in common and the bitwise AND will return 0. # On the other hand, if value is not a power of two, the highest bit set to 1 will not be flipped when subtracting 1 # and thus, value and (value - 1) will have bits in common and the bitwise AND will not return 0. # Therefore, if the result is 0, value is a power of two. return (value & (value - 1)) == 0
306702ee4291fdcc2a7d4871e7ec4f2e24c8ffd6
686,499
def get_ctx_result(result): """ This function get's called for every result object. The result object represents every ActionResult object that you've added in the action handler. Usually this is one per action. This function converts the result object into a context dictionary. :param result: ActionResult object :param provides: action name :return: context dictionary """ ctx_result = {} # param = result.get_param() summary = result.get_summary() ctx_result['vault_id'] = summary.get('vault_id') ctx_result['vault_file_name'] = summary.get('name') ctx_result['vault_file_path'] = summary.get('vault_file_path') try: ctx_result[' '] = result.get_message() except: pass return ctx_result
ac6f0a4d4e4632a69703f036fbb6e5ffc3444df9
686,505
def pintensity(policies, weights): """Get the total intensity of a given bin of policies""" total = 0 for p in policies: if p == "nan": continue if p not in weights.keys(): raise ValueError(f"Missing intensity group: {p}") else: total += weights[p] return total
86b305f75a8027aedacc52709e83b316c3233e88
686,509
def get(seq, ind, defVal=None): """Return seq[ind] if available, else defVal""" try: return seq[ind] except LookupError: return defVal
9e9f64145fb1780b8c956737e080dcddb7e4e0d5
686,524
def get_bot_in_location(location, game): """Returns the bot in the given location.""" bots = game.get('robots') if location in bots.keys(): return bots[location] else: return None
bcc4f909dc2fd936fe83a641d2966c475e58ffa6
686,526
def is_mutable_s(text: str) -> bool: """ Checks if the word starts with a mutable 's'. ('s' is mutable when followed by a vowel, n, r, or l) :param text: the string to check :return: true if the input starts with a mutable s """ lc = text.lower() return len(lc) >= 2 and lc[0] == 's' and lc[1] in "rnlaeiouáéíóú"
e45ddd8b7cc060d39944fc6590f6aa2eb86bb379
686,528
def NBR(ds): """ Computes the Normalized Burn Ratio for an `xarray.Dataset`. The formula is (NIR - SWIR2) / (NIR + SWIR2). Values should be in the range [-1,1] for valid LANDSAT data (nir and swir2 are positive). Parameters ---------- ds: xarray.Dataset An `xarray.Dataset` that must contain 'nir' and 'swir2' `DataArrays`. Returns ------- nbr: xarray.DataArray An `xarray.DataArray` with the same shape as `ds` - the same coordinates in the same order. """ return (ds.nir - ds.swir2) / (ds.nir + ds.swir2)
2030cde88eaf8e4e2999d4db09ba4d3ea7e93260
686,533
def epsIndicator(frontOld, frontNew): """ This function computes the epsilon indicator :param frontOld: Old Pareto front :type frontOld: list :param frontNew: New Pareto front :type frontNew: list :return: epsilon indicator between the old and new Pareto fronts :rtype: float """ epsInd = 0 firstValueAll = True for indNew in frontNew: tempEpsInd = 0 firstValue = True for indOld in frontOld: (aOld, bOld, cOld) = indOld.fitness.values (aNew, bNew, cNew) = indNew.fitness.values compare = max(aOld-aNew, bOld-bNew, cOld-cNew) if firstValue: tempEpsInd = compare firstValue = False if compare < tempEpsInd: tempEpsInd = compare if firstValueAll: epsInd = tempEpsInd firstValueAll = False if tempEpsInd > epsInd: epsInd = tempEpsInd return epsInd
8ec7b18b36a32b963c148aa7592557c2724bde0d
686,534
from typing import Optional from typing import Tuple import cgi def _parse_content_type(content_type: Optional[str]) -> Tuple[Optional[str], str]: """Tease out the content-type and character encoding. A default character encoding of UTF-8 is used, so the content-type must be used to determine if any decoding is necessary to begin with. """ if not content_type: return None, "utf-8" else: type_, parameters = cgi.parse_header(content_type) encoding = parameters.get("charset", "utf-8") return type_, encoding
e6ae570ff6bf65fce4000d8d5216f8977f6a19a0
686,541
def ranked_vaccine_peptides(variant_to_vaccine_peptides_dict): """ This function returns a sorted list whose first element is a Variant and whose second element is a list of VaccinePeptide objects. Parameters ---------- variant_to_vaccine_peptides_dict : dict Dictionary from varcode.Variant to list of VaccinePeptide Returns list of (varcode.Variant, VaccinePeptide list) tuples """ result_list = list(variant_to_vaccine_peptides_dict.items()) def sort_key(variant_and_vaccine_peptides_pair): vaccine_peptides = variant_and_vaccine_peptides_pair[1] if len(vaccine_peptides) == 0: return 0.0 else: top_vaccine_peptide = vaccine_peptides[0] return top_vaccine_peptide.combined_score # sort in descending order of combined (expression * mhc binding) scores result_list.sort(key=sort_key, reverse=True) return result_list
e775eff9c84a0404dfd5165b3116c5a661c475e3
686,544
def get_coord_by_index(da, indx): """ Take an Xarray DataArray, return a coordinate by its index in the order of the data structure. E.g. if var is defined on: ('time', 'lat'), indx=0 will return the coordinate labelled as 'time'. """ coord_name = da.dims[indx] return da.coords[coord_name]
c6b2710351e71f6d17f5b50a8759a30811e4a41c
686,546
def variance(hist:dict): """Compute the variance of an histogram. :param hist: the histogram :type hist: dict :return: the variance of the histogram :rtype: float """ vl = list(hist.values()) m = sum(vl) / float(len(vl)) return sum([(m - v)**2 for v in vl]) / float(len(vl))
87124db6bc41757fd899177fb935c0023d007140
686,548
import base64 import io def mpl_png(fig) -> str: """Return the base64 encoded png string of a matplotlib figure. Parameters ---------- fig : Figure Matplotlib figure Returns ------- str Figure base64 encoding """ f = io.BytesIO() fig.savefig(f, format="png", bbox_inches="tight") f.seek(0) b = base64.b64encode(f.getvalue()).decode("utf-8").replace("\n", "") return '<img class="mpl-figure-png" align="center" src="data:image/png;base64,%s">' % b
7e11fdeeceef128141ff63cfd4cbbacfa40cca8f
686,553
import collections def compute_f1(hypothesis_list, reference_list, eps=1e-8): """ Computes token F1 given a hypothesis and reference. This is defined as F1 = 2 * ((P * R) / (P + R + eps)) where P = precision, R = recall, and eps = epsilon for smoothing zero denominators. By default, eps = 1e-8. """ hypothesis_set = collections.Counter(hypothesis_list) reference_set = collections.Counter(reference_list) overlapping_set = hypothesis_set & reference_set hypothesis_count = len(hypothesis_list) reference_count = len(reference_list) overlapping_count = sum(overlapping_set.values()) precision = overlapping_count / hypothesis_count if hypothesis_count > 0 else 0 recall = overlapping_count / reference_count if reference_count > 0 else 0 f1 = (2.0 * precision * recall) / (precision + recall + eps) return f1
0d4c4cec2dcd91791b2e00c8792ed2ea5d9e814b
686,556
def get_p_key(episode_info): """ create the primary key field by concatenating episode information :param episode_info: Dictionary of a single episode """ return f'{episode_info["show_stub"]}S{episode_info["season"]}E{episode_info["episode"]}'
f1f7b497aae69a715c312c2de4384f53ee1755d8
686,560
from typing import List def maxCrossingSum(arr: List[int], start: int, mid: int, stop: int): """Helper Function - Find the max crossing sum w.r.t. middle index""" leftSum = arr[mid] # start point leftMaxSum = arr[mid] # Keep track of maximum sum # Traverse in reverse direction from (mid-1) to start for i in range(mid - 1, start - 1, -1): leftSum = leftSum + arr[i] if leftSum > leftMaxSum: leftMaxSum = leftSum rightSum = arr[mid + 1] # start point rightMaxSum = arr[mid + 1] # keep track of maximum sum # Traverse in forward direction from (mid+2) to stop for j in range(mid + 2, stop + 1): rightSum = rightSum + arr[j] if rightSum > rightMaxSum: rightMaxSum = rightSum return rightMaxSum + leftMaxSum
61c334b5a9d1857fb54a0518a992ef9c756f57a2
686,567
def get_attack_name(node): """Returns the first of the three '|'-delimited fields in the 'text' field of the child 'attack' node.""" for child in node.iterchildren(): if child.tag == 'attack': return child.text.split('|')[0]
5ecdb060814fd94ff749718d50d9b8601351e5b4
686,572
def clean_html(html_text): """ Converts <1 to 1 in html text""" return html_text.replace("><1<", ">less than 1<")
d07db5cf23445aa9a6e6782a8de089299ec30dc4
686,573
def occupancy_accuracy(gt, pred): """Compute occupancy accuracy of numpy tensors.""" return (gt == pred).sum() / float(gt.size)
e3eb56650978d33f1e1c61d0128695ec2fc399d8
686,574
def _get_winsdk_full_version(repository_ctx): """Return the value of BAZEL_WINSDK_FULL_VERSION if defined, otherwise an empty string.""" return repository_ctx.os.environ.get("BAZEL_WINSDK_FULL_VERSION", default = "")
bc14431495312ee910bb9e9e69eb05b571f63deb
686,579
def asses_quality(spec, negative_threshold_percent=20): """ // default - 0 = default // good - 1: to be defined - 2: to be defined // bad - 3: Pointing Problem - 4: more than `negative_threshold_percent` of the flux is negative - 5: A science target with no WCS """ if "STD" not in spec.header.get("OBJECT") and spec.header.get("SRCPOS",None) =="auto": return 5 if not spec.header.get("POSOK",True): return 3 flagnegative = spec.data<0 if len(spec.data[flagnegative]) / len(spec.data) > negative_threshold_percent/100: return 4 return 0
752c97be8f0752ae7aad02b93afde77f8a36fd39
686,582
def extendImages(center, left, right, steering, correction): """ Extend the image paths from `center`, `left` and `right` using the correction factor `correction` Returns ([imagePaths], [steerings]) """ imagePaths = [] imagePaths.extend(center) imagePaths.extend(left) imagePaths.extend(right) steerings = [] steerings.extend(steering) steerings.extend([x + correction for x in steering]) steerings.extend([x - correction for x in steering]) return (imagePaths, steerings)
235883b4b04ed33cf36e8c0fbdb6f47c4645d95a
686,590
from typing import Callable def linear_schedule( initial_value: float, final_value: float, end: float = 0 ) -> Callable[[float], float]: """ Linear learning rate schedule. :param initial_value: Initial learning rate. :param final_value: Final learning rate :param end: Progress remaining where final value will be reached. :return: schedule that computes current learning rate depending on remaining progress """ assert 0 < end < 1 def func(progress_remaining: float) -> float: """ Progress will decrease from 1 (beginning) to 0. :param progress_remaining: :return: current learning rate """ if progress_remaining < end: lr = final_value else: x0 = end x1 = 1 y0 = final_value y1 = initial_value a = (y1 - y0) / (x1 - x0) b = y1 - a * x1 lr = a * progress_remaining + b return lr return func
0363718b080ee9c111e25e1d32b96245d18ec0fc
686,591
def is_target_platform(ctx, platform): """ Determine if the platform is a target platform or a configure/platform generator platform :param ctx: Context :param platform: Platform to check :return: True if it is a target platform, False if not """ return platform and platform not in ('project_generator', [])
7c48e886f15beba0f2350aee4a6b1a8aef408537
686,595
def convert_station_group_to_dictionary(group): """ Takes station group in format: [[station, component, network, location, start, end], [..], ...] and returns its dictionary representation: { station: <station>, components: [component1, .., componentN], network: <network>, location: <location>, start: <start>, end: <end> } """ components = [x[1] for x in group] station = group[0] return { 'station': station[0], 'components': components, 'network': station[2], 'location': station[3], 'start': station[4], 'end': station[5] }
f06e83188fe81f59fe6a18dc02704b47f17fbe6d
686,596
def get_max_lat(shape): """ It returns the maximum latitude given a shape :param shape: country shape :return: the max latitude """ return shape.bounds[3]
f165ac6158a874afb454bdca5fc2be59b64730d1
686,599
def get_card_group(card, idolized): """ Returns an identifier for a card's group, to help separate them by rarities :param card: card data from schoolido.lu api :param idolized: True if idolized version :return: card group name """ return "%s-%s%d" % (card['rarity'], card['attribute'], 1 if idolized else 0)
d675a1c575b5e212172116eb23d97fab95ab9d32
686,600
def parse(address): """Parses the given MAC address and transforms it into "xx:xx:xx:xx:xx:xx" form. This form of expressing MAC addresses is the most standard one. In general, the "address" parameter accepts three forms of MAC address i input: - '1234567890af', - '12-34-56-78-90-af' (windows-like) and - '12:34:56:78:90:af' (the most used form). The 'address' parameter must be string, of course. """ assert address is not None temp = address if "-" in temp: temp = temp.replace("-", ":") if ":" not in temp: lst = list(temp) for cnt in range(10, 0, -2): lst.insert(cnt, ":") temp = "" for c in lst: temp = temp + c return temp.lower()
5bf3e63e35872b01c01f3462354bb33f27c8f7b9
686,601
def parse_mode(cipher_nme): """ Parse the cipher mode from cipher name e.g. aes-128-gcm, the mode is gcm :param cipher_nme: str cipher name, aes-128-cfb, aes-128-gcm ... :return: str/None The mode, cfb, gcm ... """ hyphen = cipher_nme.rfind('-') if hyphen > 0: return cipher_nme[hyphen:] return None
0c5f82465f3ab3ec4e4735ef86c825880c1db203
686,606
def get_coordinates(read): """ return external coordinates of aligned read bases """ fivep = read.aend if read.is_reverse else read.pos threep = read.pos if read.is_reverse else read.aend return fivep, threep
fa77cc9498598ab9e64c9f008a671e56636a932a
686,607
def add_drip_columns(cave_results_df): """ Calculates Drips per min Calculates Drip Rate Error Adds all as columns ad returns input df. Parameters ---------- cave_results_df : pandas dataframe Returns ------- cave_results_df : pandas dataframe """ # Data Conversions cave_results_df['DripsPerMin'] = 60.0/cave_results_df['DripInterval'] # Error Propagation cave_results_df['DripRate_Err'] = (60*cave_results_df['DripInterval_err'] / cave_results_df['DripInterval'].pow(2)) return cave_results_df
c418af1c806eee9fd09a28ffb2e6cf92bc139f0b
686,608
import calendar def datetime_to_ms(dt): """ Converts a datetime to a millisecond accuracy timestamp """ seconds = calendar.timegm(dt.utctimetuple()) return seconds * 1000 + dt.microsecond / 1000
cd2ad394c478905988b145c5b8a2c242f7165674
686,609
def temp_gradient(x, y): """Calculate the temperature gradient for a point defined by its cartesian coordinates: x, y. """ # Could also use SymPy to calculate derivative tbh fx = -x / (x**2 + y**2) fy = -y / (x**2 + y**2) return fx, fy
e21e95133cfd803bb63b14aabe6cd27ab0a08d87
686,610
import math def get_tile_size(num_pixels, tile_size=400): """ num_pixels is the number of pixels in a dimension of the image. tile_size is the desired tile-size. """ # How many times can we repeat a tile of the desired size. num_tiles = int(round(num_pixels / tile_size)) # Ensure that there is at least 1 tile. num_tiles = max(1, num_tiles) # The actual tile-size. actual_tile_size = math.ceil(num_pixels / num_tiles) return actual_tile_size
a139fdb8f4548dd2f8576f116943473475294bae
686,613
def b(b1, b2): """ Return the difference between b1 and b2. """ return b1 - b2
7073bd8bceea55e130709db6f8f5ec722d3670c6
686,614
import csv def load_examples(input_file): """Load data that we'll learn from""" with open(input_file) as f: reader = csv.reader(f) header = next(reader) assert header == ["From", "To"] examples_to_learn_from = [l for l in reader] return examples_to_learn_from
e49f9f81f6993aa100378a0777166ef2efbcecdc
686,615
def sublist(full_list, index): """ returns a sub-list of contiguous non-emtpy lines starting at index """ sub_list = [] while index < len(full_list): line = full_list[index].strip() if line != "": sub_list.append(line) index += 1 else: break return sub_list
ee4ed5e730829a22cb825e39aa95b19e037dda00
686,617
import imp def load_model(model_name, X_train, y_train, optimization_parameters, sklearn_model=None): """ Loads the base model model with the specific parameters :param model_name: the name of the model :param X_train: training data (# of samples x # of features) :param y_train: labels for the training data (# of samples * 1) :return: model object """ model_source = imp.load_source(model_name, 'models/%s.py' % (model_name)) model = model_source.Model(X_train, y_train, optimization_parameters, sklearn_model) return model
201c0b66e5cce4236f9757e781e7a9428c53840e
686,621
def is_int(n): """Determines if a value is a valid integer""" try: int(n) return True except ValueError: return False
1e99dcc056971e030853fef23b10340b2d4bf3fb
686,622
def _token_to_dict(name, prefix=None): """ Generates function that converts a token to a dict containing the token name as key. The length of prefix is stripped from the key. """ if prefix is not None: return lambda x: {name[len(prefix) :]: x[0]} return lambda x: {name: x[0]}
2c141bb780c45c3d1bd387ed1423f900cc8a3bdb
686,625
def keypoint_outside_bbox(kp, bb): """ Check if keypoint is outside box :param kp: co ordinates of keypoint(x, y) :param bb: bounding box details (x_top_left, y_top_left, x_bottom_right, y_bottom_right) :return: True if keypoint is outside of bounding box, else False """ x = kp.pt[0] y = kp.pt[1] x_top_left, y_top_left, x_bottom_right, y_bottom_right = bb return not ((x > x_top_left) and (x < x_bottom_right) and (y > y_top_left) and (y < y_bottom_right))
a95c02dae09468bfadd5d88f16fdf40848ef343e
686,626
def isInt(string): """ Determine whether a string is an int @param string: the string to check @return True if the string is an int, False otherwise """ try: int(string) except: return False return True
400eebfd4c0eeac78e56fe026e5e7b5846f9df31
686,628
def is_unlinked_account(user): """ Returns whether the provided user has authenticated via an InstitutionAccount not yet linked to a Uniauth profile. """ return user.username and user.username.startswith('cas-')
6090c8fc6e1eacb3063bc39178f3f8dc4757274c
686,631
def add_prefix_safely(token, prefix): """Attaches the passed in prefix argument to the front of the token, unless the token is an empty string in which case nothing happens and the token is returned unchaged. This can be important for avoiding accidentally making a meaningless token meaningful by modifying it with an additional text component. Args: token (str): Any arbitrary string. prefix (str): Any arbitrary string. Returns: str: The token with the prefix added to the beginning of the string. """ if len(token) > 0: return("{}{}".format(prefix, token)) else: return("")
bccf22b4ecbac2de40796e0b46c2707142ab3a70
686,632
def in_bounds(lat, lon, corners): """ Return true if the lat lon is within the corners. """ return \ lat >= corners[0] and lat <= corners[2] and \ lon >= corners[1] and lon <= corners[3]
680512f122f7110ff20fdf85891d0f0b87df1b29
686,634
def hours2days(input_hours): """ Receive the hours and will return ow many days and hours there is in the input """ # Floor division to get the days but not the extra hours days = input_hours // 24 # Modulus to get the left hours after calculating the days hours = input_hours % 24 # Returns tuples return days, hours
fcd04352aa990154d55bd8c3352c717d06ad50f0
686,636
def class_name(obj): """Fetch the class name of an object (class or instance). Another cosmetic shortcut. The builtin way of getting an instance's class name is pretty disgusting (and long), accessing two hidden attributes in a row just feels wrong. :param any obj: The object you want the class name of :returns str: The class name """ if isinstance(obj, type): # It's a class. return obj.__name__ else: # It's an instance of a class. return obj.__class__.__name__
6e6e41df7d8eb4fe83f4bea7e763446805a55477
686,640
import typing import re def extract_ints(raw: str) -> typing.List[int]: """Utility function to extract all integers from some string. Many inputs can be directly parsed with this function. """ return list(map(int, re.findall(r"((?:-|\+)?\d+)", raw)))
6385360142bfa9ba39467a2f534404e48b48c528
686,641
def tokenize_description(description, has_name): """ Splits comma-separated resource descriptions into tokens. :param description: String describing a resource, as described in the ion-hash-test-driver CLI help. :param has_name: If True, there may be three tokens, the first of which must be the resource's name. Otherwise, there may be a maximum of two tokens, which represent the location and optional revision. :return: If `has_name` is True, three components (name, location, revision). Otherwise, two components (name, location) """ components = description.split(',') max_components = 3 if not has_name: max_components = 2 if len(components) < max_components: revision = 'master' else: revision = components[max_components - 1] if len(components) < max_components - 1: raise ValueError("Invalid implementation description.") if has_name: return components[0], components[max_components - 2], revision else: return components[max_components - 2], revision
34c27f892a1c3e08782c33a28f0ce76a13934044
686,642
from typing import Counter def _get_object_count_by_type(objects): """Counts Python objects by type.""" return Counter(map(type, objects))
49b29527e08b404dd5a56090c70c82d84768ad6a
686,645
def Sqr_Chord_Len_C3V(vec1, vec2): """Computes the square length of the difference between the two arguments. The arguments are assumed to be 3d vectors (indexable items of length 3).""" diff0 = vec1[0] - vec2[0]; diff1 = vec1[1] - vec2[1]; diff2 = vec1[2] - vec2[2]; result = diff0 * diff0 + diff1 * diff1 + diff2 * diff2; return result
2d89ddaa35aba5cc7ee9d30d07086288c3b6194f
686,646
def set_binary_labels(input_examples, positive_label): """ Replaces the class labels with 1.0 or -1.0, depending on whether the class label matches 'positive_label'. Returns an array of tuples, where the first element is the label number and the second is a path to the image file. """ examples = [] for example in input_examples: if example[0] == positive_label: examples.append(("1.0", example[1])) else: examples.append(("-1.0", example[1])) return examples
e610ffb8abf6ec5e672b0a5615e219e1489ff59a
686,647
def _ExtractCommentText(comment, users_by_id): """Return a string with all the searchable text of the given Comment PB.""" commenter_email = users_by_id[comment.user_id].email return '%s %s %s' % ( commenter_email, comment.content, ' '.join(attach.filename for attach in comment.attachments if not attach.deleted))
7c372eb15805ca3f47b54c32ba9afb64208815dc
686,649
import torch def inv_quad_chol_lower(x,L,y): """ Computes x (L L^T) y x : (m x n) L : (n x n) y : (n x k) """ m = x.shape[0] if m == 1: xy = torch.cat([x.reshape(-1,1),y],dim=1) return torch.triangular_solve(xy,L,upper=False)[0].prod(dim=1).sum(dim=0).reshape(1,1) else: z1 = torch.triangular_solve(x.transpose(1,0),L,upper=False)[0].transpose(1,0) #m x n z2 = torch.triangular_solve(y,L,upper=False)[0] #n x k return torch.matmul(z1,z2)
5f89775b2c735c71e904562a110a1d550e9d7665
686,655
import re def get_original_image_link(url): """ Parse the image URL to cut off the 150x150 from the RSS feed Args: url (str): The image URL Returns: str: The updated URL if it matches the regex, else the original URL """ match = re.match(r"^(?P<prefix>.+)-150x150\.(?P<suffix>.+)$", url) if match: return f"{match.group('prefix')}.{match.group('suffix')}" return url
31b9a0e42b1a1852e2afe974aa0b799e266cd4cd
686,656
def rgb_to_hex(rgb_color: tuple) -> str: """ Convert rgb color to hex example: (255, 255, 255) to #FFFFFF :param rgb_color: :return: """ r, g, b = rgb_color return '#%02x%02x%02x' % (r, g, b)
a382d69fb4d12c6ae977fa30b4e097d4da675840
686,657
def _slugify(value: str) -> str: """ Converts the value to a slugified version reducing the str down to just alpha-numeric values and removing white-space :param value: value as a str :return: slugified version of the value """ return ''.join(s for s in value if s.isalnum()).lower()
dd0e28381f1033c4fea9bb4b368a715f2ba132fe
686,664
def sort_nodes_by_priority(g): """ Sort node ids in ascending order of priority. :param g: a game graph. :return: the node ids sorted in ascending order of priority. """ # x is a key of the dictionary a value (1, 4) means player 1, priority 4 # we return the node id, sorted by priority incrementally return sorted(g.nodes.iterkeys(), key=lambda x: g.nodes[x][1])
3018606b8bb49c217b106f957b47c41f4680b22c
686,665
def notcontains(value, arg): """ Test whether a value does not contain any of a given set of strings. `arg` should be a comma-separated list of strings. """ for s in arg.split(','): if s in value: return False return True
d7d2b5bf4b3b28b771083677b0817537cdeea455
686,666
def power_time_series(series, scalar): """ Multiply a series by itself X times where X is a scalar """ s = str(series) return f"multiply([{','.join([s for _ in range(scalar)])}])"
1d76ccf684d5ed2380be6cf3f7dad846b36f1733
686,669
def TraceAgent(agent): """Wrap the agent's program to print its input and output. This will let you see what the agent is doing in the environment.""" old_program = agent.program def new_program(percept): action = old_program(percept) print('{} perceives {} and does {}'.format(agent, percept, action)) return action agent.program = new_program return agent
ef6c2bdf48e16645f8374e85a19b2060ca450537
686,670
def is_valid_id(id): """Check if id is valid. """ parts = id.split(':') if len(parts) == 3: group, artifact, version = parts if group and artifact and version: return True return False
c81ff28cbca39e601ddc7ea0786db0e62779096a
686,681
def STD_DEV_SAMP(*expression): """ Calculates the sample standard deviation of the input values. Use if the values encompass a sample of a population of data from which to generalize about the population. See https://docs.mongodb.com/manual/reference/operator/aggregation/stdDevSamp/ for more details :param expression: expression/expressions :return: Aggregation operator """ return {'$stdDevSamp': list(expression)} if len(expression) > 1 else {'$stdDevSamp': expression[0]} if expression else {}
cfd4b27cf75e014f8c7debda0dfd97dfa118d7b9
686,685
def misclassification_percentage(y_true, y_pred): """ Returns misclassification percentage ( misclassified_examples / total_examples * 100.0) """ misclassified_examples = list(y_true == y_pred).count(False) * 1. total_examples = y_true.shape[0] return (misclassified_examples / total_examples) * 100.0
262057b506ea3e3edbefc9bc019f36b67b485ee1
686,687
import socket def int_to_ip(ip): """Convert 32-bit integer to an IP""" return socket.inet_ntoa(ip.to_bytes(4, 'big'))
4263848279ba9dd5b45c04ede7ac20e38ab9dd60
686,688
from typing import Iterable def _unique(*args: Iterable) -> list: """Return a list of all unique values, in order of first appearance. Args: args: Iterables of values. Examples: >>> _unique([0, 2], (2, 1)) [0, 2, 1] >>> _unique([{'x': 0, 'y': 1}, {'y': 1, 'x': 0}], [{'z': 2}]) [{'x': 0, 'y': 1}, {'z': 2}] """ values = [] for parent in args: for child in parent: if child not in values: values.append(child) return values
5d43dfa3d13b04b40c2ae37fac25df44d4d37295
686,691
def linear_function(m, x, b): """ A linear function of one variable x with slope m and and intercept b. """ return m * x + b
f61b62d36314483029a3f668a8aaa2b98b1a765c
686,692
import functools def dgetattr(obj, name, is_dict=False): """ get deep attribute operates the same as getattr(obj, name) but can use '.' for nested attributes e.g. dgetattr(my_object, 'a.b') would return value of my_object.a.b """ atr = dict.__getitem__ if is_dict else getattr names = name.split('.') names = [obj] + names return functools.reduce(atr, names)
0bde83bf68c031d7ea27bb42ffde6c9f751b94fa
686,693
import json from pathlib import Path def get_total_epochs(save_path, run, last_gen): """ Compute the total number of performed epochs. Parameters ---------- save_path: str path where the ojects needed to resume evolution are stored. run : int current evolutionary run last_gen : int count the number of performed epochs until the last_gen generation Returns ------- total_epochs : int sum of the number of epochs performed by all trainings """ total_epochs = 0 for gen in range(0, last_gen+1): j = json.load(open(Path('%s/run_%d/gen_%d.csv' % (save_path, run, gen)))) num_epochs = [elm['num_epochs'] for elm in j] total_epochs += sum(num_epochs) return total_epochs
a9f046640b2502ae5057ab9cfc88ea37d895863e
686,701
def filter_same_tokens(tokens): """ Function for filtering repetitions in tokens. :param tokens: list with str List of tokens for filtering. :return: Filtered list of tokens without repetitions. """ if not isinstance(tokens, list): raise TypeError for token in tokens: if not isinstance(token, str): raise TypeError tmp_set = set(tokens) return [token for token in tmp_set]
bb489aea2dd7c05b2c359555fcc8e7f619859d0c
686,702
import json def loads(json_str): """Load an object from a JSON string""" return json.loads(json_str)
2a6d810349e99db6f5169b9e50df7f070f3de70a
686,704