content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def reshape(a): """Combine the last two dimensions of a numpy array""" all_head_size = a.shape[-2] * a.shape[-1] new_shape = a.shape[:-2] + (all_head_size,) return a.reshape(new_shape)
7381657c14b8b9245af2d85c1d1b7a0f5d40fff8
701,105
import jinja2 def _render(value, params): """Renders text, interpolating params.""" return str(jinja2.Template(value).render(params))
b8d9698dfaf1c2500abfa272c8da98a0cf3dd482
701,108
import math def inWhichGrid(coord, grid_info): """ Specify which grid it is in for a given coordinate :param coord: (latitude, longitude) :param grid_info: grid_info dictionary :return: row, column, grid ID """ lat, lng = coord row = math.floor((grid_info['maxLat'] - lat) / grid_info['gridLat']) col = math.floor((lng - grid_info['minLng']) / grid_info['gridLng']) gridID = row * grid_info['lngGridNum'] + col return row, col, gridID
260d31b57413902febf503ac3f7a11232940d245
701,109
def transpose(matrix): """Matrix transpose Args: matrix: list of list Returns: list: list of list """ return list(map(list, zip(*matrix)))
22c45de26bc19ca69ac0d04af8e2e02697290035
701,111
def new_line(string: str): """ Append a new line at the end of the string Args: string: String to make a new line on Returns: Same string with a new line character """ return string + "\n"
f4deeaa94a6980f95a3020fa54570fbe1f0a6e9e
701,112
import itertools def decaying(start, decay): """Return an iterator of exponentially decaying values. The first value is ``start``. Every further value is obtained by multiplying the last one by a factor of ``decay``. Examples -------- >>> from climin.schedule import decaying >>> s = decaying(10, .9) >>> [s.next() for i in range(5)] [10.0, 9.0, 8.100000000000001, 7.290000000000001, 6.561] """ return (start * decay ** i for i in itertools.count(0))
ee88365b3a8e768952fc66d02047b60e3e1a34c1
701,114
import inspect def _is_bound_method(the_function: object) -> bool: """ Returns True if fn is a bound method, regardless of whether fn was implemented in Python or in C. """ if inspect.ismethod(the_function): return True if inspect.isbuiltin(the_function): self = getattr(the_function, "__self__", None) return not (inspect.ismodule(self) or (self is None)) return False
a0d3121c6c4e1c26b2000af73e25a3d772ef2ad3
701,115
def macro_calc(item): """ Calculate PPV_Macro and TPR_Macro. :param item: PPV or TPR :type item:dict :return: PPV_Macro or TPR_Macro as float """ try: item_sum = sum(item.values()) item_len = len(item.values()) return item_sum / item_len except Exception: return "None"
ec74fe80a4f52d7676beeca1f9abd701043c77af
701,116
def height_implied_by_aspect_ratio(W, X, Y): """ Utility function for calculating height (in pixels) which is implied by a width, x-range, and y-range. Simple ratios are used to maintain aspect ratio. Parameters ---------- W: int width in pixel X: tuple(xmin, xmax) x-range in data units Y: tuple(xmin, xmax) x-range in data units Returns ------- H: int height in pixels Example ------- plot_width = 1000 x_range = (0,35 y_range = (0, 70) plot_height = height_implied_by_aspect_ratio(plot_width, x_range, y_range) """ return int((W * (Y[1] - Y[0])) / (X[1] - X[0]))
8c3225a27f0284acb708434238d4861bb49b0899
701,118
import re def get_namespace(element): """Extract the namespace using a regular expression.""" match = re.match(r"\{.*\}", element.tag) return match.group(0) if match else ""
9380e104d05ae6b56463b96bf87d9c0fcd8202cf
701,119
def get_bag_of_communities(network, partition): """ :param network: dictionary containing for each key (each node/page) a dictionary containing the page categories. :param partition: list of the community assignment :return: list of dictionaries, one dictionary per community. Each dictionary contains the categories of all the nodes of a given community as keys and the number of pages in the community that have this category as values. """ k = len(set(partition)) # number of communities bags_of_categories = [{} for _ in range(k)] for i, title in enumerate(network.keys()): cats = network[title]['categories'] if type(partition) == list: label = partition[i] else: label = partition[title] for c in cats: if c in bags_of_categories[label].keys(): bags_of_categories[label][c] += 1 else: bags_of_categories[label][c] = 1 return bags_of_categories
615e88393b30b1989d98eeea1ac7123588a51ea9
701,122
def _to_pascal_case(value: str) -> str: """Converts a snake_case string into a PascalCase one.""" value = value.replace("-", "_") if value.find("_") == -1: return value[0].upper() + value[1:] return "".join([v.capitalize() for v in value.split("_")])
d41985f1d182b723c9861473e4f9eca8c7a7977e
701,123
def remove_list_duplicates(my_list: list) -> list: """ Removes any duplicated values from a list. """ return list(dict.fromkeys(my_list))
e3dd86733117fce7bad2860d860b98b349efcfb5
701,125
from typing import Callable import click def target_id_option(command: Callable[..., None]) -> Callable[..., None]: """ An option decorator for choosing a target ID. """ click_option_function: Callable[ [Callable[..., None]], Callable[..., None], ] = click.option( '--target-id', type=str, help='The ID of a target in the Vuforia database.', required=True, ) function: Callable[..., None] = click_option_function(command) return function
1fe67f22e00b4d4930af347c482d28e30032508d
701,126
def _get_keys(response): """ return lists of strings that are the keys from a client.list_objects() response """ keys = [] if 'Contents' in response: objects_list = response['Contents'] keys = [obj['Key'] for obj in objects_list] return keys
dfa1f066ac19138920509935b1dbbdde52591f18
701,127
def round_updown_to_x(num_in, x, direction="up"): """ Rounds a given value (num_in) to the nearest multiple of x, in a given direction (up or down) :param num_in: Input value :param x: Value to round to a multiple of :param direction: Round up or down. Default: 'up' :return: Rounded number """ if direction == "down": num_out = int(num_in) - int(num_in) % int(x) else: num_out = num_in + (x - num_in) % int(x) return num_out
206b582843eea234b5b655dddd54eea6e32eec42
701,128
def coverage(tiles): """Sum of length of all tiles. """ accu = 0 for tile in tiles: accu = accu + tile[2] return accu
b2cbb6b926e070d9fc457523bb60169ef9b70821
701,130
def get_int() -> int: """ Gets a lone integer from the console (the integer is on its own line) :return: The int value that was read in from the console """ line = input().strip() return int(line)
1bffcb1c5c1e7910a11358d4616a747b38ba3d73
701,131
def regex_search_matches_output(get_output, search): """ Applies a regex search func to the current output """ return search(get_output())
6f054990d3454a447656567b3ceb12a38c2809a5
701,132
def crop(img, start_y, start_x, h, w): """ Crop an image given the top left corner. :param img: The image :param start_y: The top left corner y coord :param start_x: The top left corner x coord :param h: The result height :param w: The result width :return: The cropped image. """ return img[start_y:start_y + h, start_x:start_x + w, :].copy()
cb3a05989f1538bcec34102c33291d500a21c59d
701,133
import xml.etree.cElementTree as ET def getDataSetUuid(xmlfile): """ Quickly retrieve the uuid from the root element of a dataset XML file, using a streaming parser to avoid loading the entire dataset into memory. Returns None if the parsing fails. """ try: for event, element in ET.iterparse(xmlfile, events=("start",)): return element.get("UniqueId") except Exception: return None
7386efea461056f8f4b472923b8f4a30d6d80d3b
701,136
from typing import Optional def validate_charge_efficiency(charge_efficiency: Optional[float]) -> Optional[float]: """ Validates the charge efficiency of an object. Charge efficiency is always optional. :param charge_efficiency: The charge efficiency of the object. :return: The validated charge efficiency. """ if charge_efficiency is None: return None if charge_efficiency < 0 or charge_efficiency > 1: raise ValueError("Charge efficiency must be between 0 and 1.") return charge_efficiency
46e40fcdc65ffec453f1bac9bd03f6a9297647fd
701,138
def stream_name_to_dict(stream_name, separator='-'): """Transform stream name string to dictionary""" catalog_name = None schema_name = None table_name = stream_name # Schema and table name can be derived from stream if it's in <schema_nama>-<table_name> format s_parts = stream_name.split(separator) if len(s_parts) == 2: schema_name = s_parts[0] table_name = s_parts[1] if len(s_parts) > 2: catalog_name = s_parts[0] schema_name = s_parts[1] table_name = '_'.join(s_parts[2:]) return { 'catalog_name': catalog_name, 'schema_name': schema_name, 'table_name': table_name }
389826fe03f1f5e1c704e2ce54f90da443e1d23c
701,140
def snake_split(s): """ Split a string into words list using snake_case rules. """ s = s.strip().replace(" ", "") return s.split("_")
af70dfa1190ec783b8431630be2ae92434af146a
701,142
import decimal from typing import Iterable def try_parse(text, valid_types=None): """try to parse a text string as a number. Returns (valid, value) where valid represents whether the conversion was successful, and value is the result of the conversion, or None if failed. Accepts a string, and one optional parameter "valid_types" which is a list of valid number types to try conversion to By default, only attempts Decimal """ if valid_types is None: valid_types = [decimal.Decimal] if isinstance(valid_types, Iterable): for t in valid_types: if isinstance(t, type): try: result = t(text) return True, result except: pass else: raise RuntimeError("Non-type given in type list") else: raise RuntimeError("Invalid type list provided") return False, None
c210a88c86b55404cf620f504da7e229a033eeed
701,143
def read_file(filepath): """Reads text file and returns each line as a list element. Parameters: filepath (str): path to file Returns list: list of strings """ data = [] with open(filepath, 'r', encoding='utf-8') as file_obj: for line in file_obj.readlines(): line = line.strip() data.append(line) return data
da1db5ffb99b746271b0fd0f9779da4e6f520246
701,148
def clear(num: int, start: int, end: int) -> int: """ Sets zeros on bits of num from start to end non inclusive """ if start == end: raise ValueError('Start value same as end') # Builds group of 1s the size of the start - end mask: int = (1 << (end - start)) - 1 return num & ~(mask << start)
68dd669bd9df5ce260daf09375c6ed872580e475
701,149
def imag(x): """Returns the imaginary part of a complex tensor. :param x: The complex tensor :type x: torch.Tensor :returns: The imaginary part of `x`; will have one less dimension than `x`. :rtype: torch.Tensor """ return x[1, ...]
e2a9a3ba22a4ec896a60b3991618f32014d088fd
701,153
import math def roundoff(a, digit=2): """ roundoff the number with specified digits. :param a: float :param digit: :return: :Examples: >>> roundoff(3.44e10, digit=2) 3.4e10 >>> roundoff(3.49e-10, digit=2) 3.5e-10 """ if a > 1: return round(a, -int(math.log10(a)) + digit - 1) else: return round(a, -int(math.log10(a)) + digit)
c2bded960f9fa6431a03f6562b49f73477379a32
701,155
def _unsur(s: str) -> str: """Merge surrogates.""" return s.encode("utf-16", "surrogatepass").decode("utf-16", "surrogatepass")
d6bc230a77c735c9922ec66aa6a3537beea5b42f
701,159
def _split_comma_separated(string): """Return a set of strings.""" return set(filter(None, string.split(',')))
855c23c7a6602c9306b73016cc66573773d1d502
701,161
import hashlib def str_to_sha256(s: str): """Generate a 256 bit integer hash of an arbitrary string.""" return int.from_bytes(hashlib.sha256(s.encode("utf-8")).digest(), "big")
90fcae50485e1469cdb0f363e4110011d5e6b642
701,163
def cityscapes_palette(num_cls=None): """ Generates the Cityscapes data-set color palette. Data-Set URL: https://www.cityscapes-dataset.com/ Color palette definition: https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/helpers/labels.py Original source taken from: https://gluon-cv.mxnet.io/_modules/gluoncv/utils/viz/segmentation.html . `num_cls`: the number of colors to generate return: the generated color palette """ palette = [ 128, 64, 128, 244, 35, 232, 70, 70, 70, 102, 102, 156, 190, 153, 153, 153, 153, 153, 250, 170, 30, 220, 220, 0, 107, 142, 35, 152, 251, 152, 0, 130, 180, 220, 20, 60, 255, 0, 0, 0, 0, 142, 0, 0, 70, 0, 60, 100, 0, 80, 100, 0, 0, 230, 119, 11, 32, ] if num_cls is not None: if num_cls >= len(palette): raise Exception("Palette Color Definition exceeded.") palette = palette[:num_cls*3] return palette
b1a69a4e511e541f13aeb584003b7f4ec0dde956
701,164
def try_with_lazy_context(error_context, f, *args, **kwargs): """ Call an arbitrary function with arbitrary args / kwargs, wrapping in an exception handler that attaches a prefix to the exception message and then raises (the original stack trace is preserved). The `error_context` argument should be a lambda taking no arguments and returning a message which gets prepended to any errors. """ try: return f(*args, **kwargs) except Exception as e: msg = error_context() e.args = tuple( ["%s:\n%s" % (msg, e.args[0])] + [a for a in e.args[1:]] ) raise
7e2a4cfee7b4acf5a449b4b07f8c56baca5a63d3
701,165
def make_tweet_fn(text, time, lat, lon): """An alternate implementation of make_tweet: a tweet is a function. >>> t = make_tweet_fn("just ate lunch", datetime(2012, 9, 24, 13), 38, 74) >>> tweet_text_fn(t) 'just ate lunch' >>> tweet_time_fn(t) datetime.datetime(2012, 9, 24, 13, 0) >>> latitude(tweet_location_fn(t)) 38 """ def tweet(string): if string == 'text': return text elif string == 'time': return time elif string == 'lat': return lat elif string == 'lon': return lon return tweet # Please don't call make_tweet in your solution
3f465f91dce37641e1ce391f6025c742d9e6ef36
701,166
def calc_d(D_o, t, inner=False): """Return the outer or inner diameter [m]. :param float D_o: Outer diameter [m] :param float t: Layer thickness [m] :param boolean inner: Select diameter """ if inner: return D_o - 2 * t else: return D_o + 2 * t
eaadfed210c0b06b7fd0bbc500fe093461d9766c
701,170
def is_neq_prefix(text_1, text_2): """Return True if text_1 is a non-equal prefix of text_2""" return text_1 != text_2 and text_2.startswith(text_1)
f9e7f835ec577dc539cd586da5e6f9e2e0903a74
701,174
import json def read_config(fn, perm="r"): """ Read config file which consists parameters used in program. :param str fn: Name of config file (config.json) :param str perm: Mode in which the file is opened :return: Config file paramteres """ with open(fn, perm) as file: config = json.load(file) return config
f77a1dbb9b1e0f9f43dbef745f550485f1003cf7
701,176
import uuid def uuid_uri(prefix): """Construct a URI using a UUID""" return prefix + str(uuid.uuid1())
2361583122396296d40ff5b1c284662a918fc871
701,181
from typing import Any def is_raw_json_null(py_obj: Any) -> bool: """ Checks if the given Python object is a raw JSON null. :param py_obj: The Python object to check. :return: True if the Python object is a raw JSON null, False if not. """ # Must be None return py_obj is None
1d206ed8242caeb806a646aa617a3bf6707fd5d8
701,182
import re def underscore_2_space(string: str): """ Return string with underscores replaced by spaces. """ return re.sub('[_]', ' ', string)
a4ef9b19cda662ec4714cab58e1f502f668b6aaa
701,183
import torch from typing import Optional from typing import Union from typing import Tuple def wmean( x: torch.Tensor, weight: Optional[torch.Tensor] = None, dim: Union[int, Tuple[int]] = -2, keepdim: bool = True, eps: float = 1e-9, ) -> torch.Tensor: """ Finds the mean of the input tensor across the specified dimension. If the `weight` argument is provided, computes weighted mean. Args: x: tensor of shape `(*, D)`, where D is assumed to be spatial; weights: if given, non-negative tensor of shape `(*,)`. It must be broadcastable to `x.shape[:-1]`. Note that the weights for the last (spatial) dimension are assumed same; dim: dimension(s) in `x` to average over; keepdim: tells whether to keep the resulting singleton dimension. eps: minimum clamping value in the denominator. Returns: the mean tensor: * if `weights` is None => `mean(x, dim)`, * otherwise => `sum(x*w, dim) / max{sum(w, dim), eps}`. """ args = {"dim": dim, "keepdim": keepdim} if weight is None: return x.mean(**args) if any( xd != wd and xd != 1 and wd != 1 for xd, wd in zip(x.shape[-2::-1], weight.shape[::-1]) ): raise ValueError("wmean: weights are not compatible with the tensor") return (x * weight[..., None]).sum(**args) / weight[..., None].sum(**args).clamp( eps )
db742eb5d899b190609a8e40cd9e4a65f52a45cd
701,186
def ts(nodes, topo_order): # topo must be a list of names """ Orders nodes by their topological order :param nodes: Nodes to be ordered :param topo_order: Order to arrange nodes :return: Ordered nodes (indices) """ node_set = set(nodes) return [n for n in topo_order if n in node_set]
741c7b3ac34c9f5beb6dc57ebf1539a27cc2b91b
701,188
def return_slice(axis, index): """Prepares a slice tuple to use for extracting a slice for rendering Args: axis (str): One of "x", "y" or "z" index (int): The index of the slice to fetch Returns: tuple: can be used to extract a slice """ if axis == "x": return (slice(None), slice(None), index) if axis == "y": return (slice(None), index, slice(None)) if axis == "z": return (index, slice(None), slice(None)) return None
ac6db30fc12509062efa4481d1f7b2fdaff8149b
701,191
def get(*args, **kwargs): """Decorates a test to issue a GET request to the application. This is sugar for ``@open(method='GET')``. Arguments are the same as to :class:`~werkzeug.test.EnvironBuilder`. Typical usage:: @frontend.test @get('/') def index(response): assert 'Welcome!' in response.data """ kwargs['method'] = 'GET' return open(*args, **kwargs)
c6322bd1340f5fe919ba25d70823be52ec368363
701,193
def _count_dot_semicolumn(value): """Count the number of `.` and `:` in the given string.""" return sum([1 for c in value if c in [".", ":"]])
57ee0c88d31ed62168e562191bb1dd4ebb3de859
701,197
def calc_montage_horizontal(border_size, *frames): """Return total[], pos1[], pos2[], ... for a horizontal montage. Usage example: >>> calc_montage_horizontal(1, [2,1], [3,2]) ([8, 4], [1, 1], [4, 1]) """ num_frames = len(frames) total_width = sum(f[0] for f in frames) + (border_size * num_frames + 1) max_height = max(f[1] for f in frames) total_height = max_height + (2 * border_size) x = border_size pos_list = [] for f in frames: y = border_size + (max_height - f[1]) // 2 pos_list.append([x, y]) x += f[0] + border_size result = [[total_width, total_height]] result.extend(pos_list) return tuple(result)
8fe5de84d9b1bff9950690ec99f63e174f2f0d22
701,204
def confused(total, max_part, threshold): """Determine whether it is too complex to become a cluster. If a data set have several(<threshold) sub parts, this method use the total count of the data set, the count of the max sub set and min cluster threshold to determine whether it is too complex to become a cluster. Args: total (int): Total count of a data set. max_part (int): The max part of the data set. threshold (int): The min threashold of a cluster. Returns: bool: Too complex return True, otherwise False. """ if total < threshold: return False o_part = total - max_part if max_part >= threshold and o_part >= threshold: return True return abs(max_part - o_part) < threshold - 1
eb674774a8792b4e06d810738fb46f50589b7815
701,206
def predicted_retention(alpha, beta, t): """ Generate the retention probability r at period t, the probability of customer to be active at the end of period t−1 who are still active at the end of period t. Implementing the formula in equation (8). """ assert t > 0, "period t should be positive" return (beta + t) / (alpha + beta + t)
0bc94878e93b65711fc0f520e2de898cd113b91f
701,207
def is_palindrome(s): """ Determine whether or not given string is valid palindrome :param s: given string :type s: str :return: whether or not given string is valid palindrome :rtype: bool """ # basic case if s == '': return True # two pointers # one from left, one from right i = 0 j = len(s) - 1 while i < j: # find left alphanumeric character if not s[i].isalnum(): i += 1 continue # find right alphanumeric character elif not s[j].isalnum(): j -= 1 continue # case insensitive compare if s[i].lower() != s[j].lower(): return False i += 1 j -= 1 return True
a9d700a2e7907e551cb5060f61de5c829ab77291
701,208
def range_to_level_window(min_value, max_value): """Convert min/max value range to level/window parameters.""" window = max_value - min_value level = min_value + .5 * window return (level, window)
0a388ff48a29f0daff20a7cdfd200f8330a32a15
701,209
def type_(printer, ast): """Prints "[const|meta|...] type".""" prefixes_str = ''.join(map(lambda prefix: f'{prefix} ', ast["prefixes"])) type_id_str = printer.ast_to_string(ast["typeId"]) return f'{prefixes_str}{type_id_str}'
cdf03cfb3ff0a00fa973aa4eaf7a32cb9b822191
701,210
def rid(num): """Translate from id to rid""" return num-1
9080d1d2fa9329ee5678800c2d55f3228d0ffb79
701,215
from typing import Tuple def stack_fixture(stack_function_fixture) -> Tuple[str, str]: """ Fixture that creates a dummy stack with dummy resources. :return: Tuple, where first element is stack name, and second element is stack id. """ return stack_function_fixture()
379d4f4202bcf197d855efe72ca84c7c1a319acd
701,216
def IsEnabled(test, possible_browser): """Returns True iff |test| is enabled given the |possible_browser|. Use to respect the @Enabled / @Disabled decorators. Args: test: A function or class that may contain _disabled_strings and/or _enabled_strings attributes. possible_browser: A PossibleBrowser to check whether |test| may run against. """ platform_attributes = [a.lower() for a in [ possible_browser.browser_type, possible_browser.platform.GetOSName(), possible_browser.platform.GetOSVersionName(), ]] if possible_browser.supports_tab_control: platform_attributes.append('has tabs') if hasattr(test, '__name__'): name = test.__name__ elif hasattr(test, '__class__'): name = test.__class__.__name__ else: name = str(test) if hasattr(test, '_disabled_strings'): disabled_strings = test._disabled_strings if not disabled_strings: return False # No arguments to @Disabled means always disable. for disabled_string in disabled_strings: if disabled_string in platform_attributes: print ( 'Skipping %s because it is disabled for %s. ' 'You are running %s.' % (name, ' and '.join(disabled_strings), ' '.join(platform_attributes))) return False if hasattr(test, '_enabled_strings'): enabled_strings = test._enabled_strings if not enabled_strings: return True # No arguments to @Enabled means always enable. for enabled_string in enabled_strings: if enabled_string in platform_attributes: return True print ( 'Skipping %s because it is only enabled for %s. ' 'You are running %s.' % (name, ' or '.join(enabled_strings), ' '.join(platform_attributes))) return False return True
a51835a29cdc0b6909986af7a698cc9d40213f39
701,222
def flatten_list(a_list): """Given a list of sequences, return a flattened list >>> flatten_list([['a', 'b', 'c'], ['e', 'f', 'j']]) ['a', 'b', 'c', 'e', 'f', 'j'] >>> flatten_list([['aaaa', 'bbbb'], 'b', 'cc']) ['aaaa', 'bbbb', 'b', 'cc'] """ # isinstance check to ensure we're not iterating over characters # in a string return sum([isinstance(item, (list, tuple)) and list(item) or [item] \ for item in a_list], [])
49baca675cfa59a4cf7b813bc10c12f16d0960bd
701,223
def up(user_version: int) -> str: """Return minimal up script SQL for testing.""" return f""" BEGIN TRANSACTION; PRAGMA user_version = {user_version}; CREATE TABLE Test (key PRIMARY KEY); COMMIT; """
2cd7f9204bddeea94d392f40dc91fcfcb9464632
701,224
def get_doc_id_filter(doc_id_set): """ This function returns a filter which removes any documents not in doc_id_set. This filter does not alter record_dict, but instead returns either true or false indicating whether to document should be kept or not. Parameters ---------- doc_id_set : set Returns ------- doc_id_filter : function Note ---- It is recommended that this filter be used before any others in order to minimize unnecessary computations. """ def doc_id_filter(record_dict): doc_id = record_dict['doc_id'] keep_doc = doc_id in doc_id_set return keep_doc return doc_id_filter
7a62a6cf8a290947174183c97fdfc398781d5b19
701,229
def ldrpc_source_address(line): """Calculate the absolute source address of a PC-relative load. 'line' is a line returned by disassembly_lines(). If it doesn't look like the right kind of instruction, returns None. """ # Example: ldr r2, [pc, #900] ; (0x000034b4) if line.op == 'ldr' and line.args.find('[pc') > 0: return int(line.comment.strip(';( )'), 0)
de9ffb9a3e7f1b6a66c6f6727c6d4e37fc42a4b7
701,230
def get_swap_targets(node): """ All pairs of columns that do not have the same types in every cell """ pairs = [] n_col = node.table.n_col for i in range(n_col): col_i = node.table.get_col(i) for j in range(i + 1, n_col): col_j = node.table.get_col(j) same = True for ci, cj in zip(col_i, col_j): if not ci.t == cj.t: same = False break if not same: pairs.append((i, j)) return pairs
372d2fed3c2e1544f20f69a3166b5773f954736e
701,233
import functools import operator def product (nums): """ get the product of numbers in an array. """ return functools.reduce(operator.mul, nums, 1)
801b3e9c3fe9229eaf8ad58fe73a9a1e63506b41
701,234
def get_mapindex(res, index): """Get the index of the atom in the original molecule Parameters ---------- res : prolif.residue.Residue The residue in the protein or ligand index : int The index of the atom in the :class:`~prolif.residue.Residue` Returns ------- mapindex : int The index of the atom in the :class:`~prolif.molecule.Molecule` """ return res.GetAtomWithIdx(index).GetUnsignedProp("mapindex")
21c1724a5da26cc98857ef3dbaba6806ca653ef8
701,238
def get_combos(itr1, itr2): """Returns all the combinations of elements between two iterables.""" return [[x, y] for x in itr1 for y in itr2]
5a57a1237cc73692abd077360f19916c9f366900
701,239
from typing import Any import numbers def is_num(a: Any) -> bool: """Checks if the specified Python object is a number (int, float, long, etc).""" return isinstance(a, numbers.Number)
437aed69142ea7a3e15eac27aa4c7d9026c8de8e
701,241
import time def strftime(dt, *args, **kwargs): """Version of datetime.strftime that always uses the C locale. This is because date strings are used internally in the database, and should not be localized. """ if hasattr(dt, 'strftime'): return dt.strftime(*args, **kwargs) else: return time.strftime(dt, *args, **kwargs)
c4fd0f707915e0e26a1a59ab8c5c72f2d22ce8f0
701,242
import hashlib def HashFileContents(filename): """Return the hash (sha1) of tthe contents of a file. Args: filename: Filename to read. Returns: The sha1 of a file. """ hasher = hashlib.sha1() fh = open(filename, 'rb') try: while True: data = fh.read(4096) if not data: break hasher.update(data) finally: fh.close() return hasher.hexdigest()
930ecd76dac76c09a17cddeeb52229189098553a
701,248
def impute_features(feature_df): """Imputes data using the following methods: - `smoothed_ssn`: forward fill - `solar_wind`: interpolation """ # forward fill sunspot data for the rest of the month feature_df.smoothed_ssn = feature_df.smoothed_ssn.fillna(method="ffill") # interpolate between missing solar wind values feature_df = feature_df.interpolate() return feature_df
3b61e29b30a011f86a8f18f649b77e72f3f87878
701,252
import random def rand_5() -> int: """ Generates a single, randomly generated 5-digit number. Returns: The generated 5-digit number. """ return random.randrange(100000)
b6abb4ecbd4397548e35c386a4e653df205282ea
701,254
def interval2string_m(i: float) -> str: """Convert a time interval to a string or to NA if it is does not have a value Arguments: i: is a number of seconds Returns: a string of the number of minutes represented or NA if i is not a float """ if type(i) == float: i_m = str(round(i / 60.0, 2)) else: i_m = 'NA' return i_m
e7d710d10fb8a3393ca2fad4d99e7acc5f4b45eb
701,261
def tab(column) -> str: """Emulates the TAB command in BASIC. Returns a string with ASCII codes for setting the cursor to the specified column.""" return f"\r\33[{column}C"
d57e0d6840c9f446b2832bbe725bc986aaabf13e
701,262
import binascii def x(h): """Convert a hex string to bytes""" return binascii.unhexlify(h.encode('utf8'))
0cbba146b22419f9e67f0a2ea46851a47826d4f8
701,264
import typing def cumprod(mod: int, a: typing.List[int]) -> typing.List[int]: """Compute cummulative product over Modular.""" a = a.copy() for i in range(len(a) - 1): a[i + 1] = a[i + 1] * a[i] % mod return a
62a99a916c5e09187f05b9a31096037b3c53eb85
701,268
import ipaddress def is_valid_ipv4(address): """Check an IPv4 address for validity""" try: ip = ipaddress.ip_address(address) except ValueError: return False if not isinstance(ip, ipaddress.IPv4Address): return False warning = None if ip.is_loopback: warning = "loopback address" elif ip.is_multicast: warning = "multicast address" elif ip.is_reserved: warning = "reserved address" elif ip.is_link_local: warning = "link-local address" elif ip.is_unspecified: warning = "unspecified address" elif ip.is_private: warning = "private address" elif address.endswith(".0") or address.endswith(".255"): warning = "potential broadcast address" if warning: print("*** Warning: {} is a {}".format(address, warning)) return True
fd095d8903cd0a44bfd6a7eb02fa95217a60077a
701,270
def two_pts_to_line(pt1, pt2): """ Create a line from two points in form of a1(x) + a2(y) = b """ pt1 = [float(p) for p in pt1] pt2 = [float(p) for p in pt2] try: slp = (pt2[1] - pt1[1]) / (pt2[0] - pt1[0]) except ZeroDivisionError: slp = 1e5 * (pt2[1] - pt1[1]) a1 = -slp a2 = 1. b = -slp * pt1[0] + pt1[1] return a1, a2, b
d607008c41eaa052c0988a7ac66588b464aab8e0
701,271
def semi_split(s): """ Split 's' on semicolons. """ return map(lambda x: x.strip(), s.split(';'))
f81eff42e170c7b760a75d86d5d0d9326365ca8e
701,275
def reconstruct_path(goal, branch, waypoint_fn): """ Reconstruct a path from the goal state and branch information """ current_node = goal path = [current_node] while current_node is not None: previous_node = branch[waypoint_fn(current_node)] path.append(previous_node) current_node = previous_node path.pop() path.reverse() return path
cdc99ebaa5b987785e86a8b277c25638af1a3e71
701,278
import typing def _de_bruijn(k: int, n: int) -> typing.List[int]: """Generate a De Bruijn sequence. This is a piece of mathematical heavy machinery needed for O(1) ctz on integers of bounded size. The algorithm is adapted from chapter 7 of Frank Ruskey's "Combinatorial Generation". Args: k: The number of symbols in the alphabet. Must be > 1. n: The length of subsequences. Should be >= 0. Returns: The De Bruijn sequence, as a list of integer indices. >>> _de_bruijn(2, 3) [0, 0, 0, 1, 0, 1, 1, 1] >>> _de_bruijn(4, 2) [0, 0, 1, 0, 2, 0, 3, 1, 1, 2, 1, 3, 2, 2, 3, 3] >>> _de_bruijn(2, 5) [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1] """ a: typing.List[int] = [0] * k * n sequence: typing.List[int] = [] def gen(t: int, p: int): if t > n: if n % p == 0: sequence.extend(a[1:p + 1]) else: a[t] = a[t - p] gen(t + 1, p) for j in range(a[t - p] + 1, k): a[t] = j gen(t + 1, t) gen(1, 1) return sequence
bbb86a4f0a7ef03bbce29126cc56e4fb3e41e288
701,289
def template_used(response, template_name): """Asserts a given template was used (with caveats) First off, this is a gross simplification of what the Django assertTemplateUsed() TestCase method does. This does not work as a context manager and it doesn't handle a lot of the pseudo-response cases. However, it does work with Jinja2 templates provided that monkeypatch_render() has patched ``django.shortcuts.render`` to add the information required. Also, it's not tied to TestCase. Also, it uses fewer characters to invoke. For example:: self.assertTemplateUsed(resp, 'new_user.html') assert template_used(resp, 'new_user.html') :arg response: HttpResponse object :arg template_name: the template in question :returns: whether the template was used """ templates = [] # templates is an array of TemplateObjects templates += [t.name for t in getattr(response, "templates", [])] # jinja_templates is a list of strings templates += getattr(response, "jinja_templates", []) return template_name in templates
f8a878d27c5379b0b2f2fac2a08fbeee91607858
701,291
def sanitizer(name): """ Sanitizes a string supposed to be an entity name. That is, invalid characters like slashes are substituted with underscores. :param name: A string representing the name. :returns: The sanitized name. :rtype: str """ return name.replace("/", "_")
f59aa75a40067068c711a4ca01b643c69d43cd0c
701,296
import ctypes def make_array_ctype(ndim): """Create a ctypes representation of an array_type. Parameters ----------- ndim: int number of dimensions of array Returns ----------- a ctypes array structure for an array with the given number of dimensions """ c_intp = ctypes.c_ssize_t class c_array(ctypes.Structure): _fields_ = [('parent', ctypes.c_void_p), ('nitems', c_intp), ('itemsize', c_intp), ('data', ctypes.c_void_p), ('shape', c_intp * ndim), ('strides', c_intp * ndim)] return c_array
c83ab386d40043d49d1b86c21c2789c461999fc5
701,305
def eq_xtl( Cl, D, F, ): """ eq_xtl calculates the composition of a trace element in the remaining liquid after a certain amount of crystallization has occured from a source melt when the crystal remeains in equilibrium with the melt as described by White (2013) Chapter 7 eq. 7.81. It then calculates the concentration of that trace element in a specific solid phase based on partition coefficient input. Inputs: Cl = concentration of trace element in original liquid D = bulk distribution coefficient for trace element of crystallizing assemblage F = fraction of melt remaining Returns: Cl_new = concentration of trace element in the remaining liquid """ Cl_new = Cl / (D + F * (1 - D)) return Cl_new
298a5557775a953a645aade70f41818e42e761ac
701,310
def quantity_label(quantity): """Returns formatted string of parameter label """ labels = { 'accrate': r'$\dot{m}$', 'alpha': r'$\alpha$', 'd_b': r'$d \sqrt{\xi_\mathrm{b}}$', 'dt': r'$\Delta t$', 'fluence': r'$E_\mathrm{b}$', 'length': 'Burst length', 'lum': r'$\mathit{L}$', 'm_gr': '$M$', 'm_nw': r'$M_\mathrm{NW}$', 'mdot': r'$\dot{m}$', 'peak': r'$L_\mathrm{peak}$', 'qb': r'$Q_\mathrm{b}$', 'rate': r'Burst rate', 'redshift': '$z$', 'x': r'$X_0$', 'xedd': r'$X_\mathrm{Edd}$', 'xedd_ratio': r'$X_\mathrm{Edd} / X_0$', 'xi_ratio': r'$\xi_\mathrm{p} / \xi_\mathrm{b}$', 'xi_b': r'$\xi_\mathrm{b}$', 'xi_p': r'$\xi_\mathrm{p}$', 'z': r'$Z_\mathrm{CNO}$', } return labels.get(quantity, f'${quantity}$')
467baf8f3d2ae72474e6f65e6990779e7cb10034
701,311
def local_overrides_git(install_req, existing_req): """Check whether we have a local directory and a Git URL :param install_req: The requirement to install :type install_req: pip.req.req_install.InstallRequirement :param existing_req: An existing requirement or constraint :type existing_req: pip.req.req_install.InstallRequirement :return: True if the requirement to install is a local directory and the existing requirement is a Git URL :rtype: bool """ return (install_req.link and existing_req.link and install_req.link.url.startswith('file:///') and existing_req.link.url.startswith('git+'))
5c031506ddee4d05332421f8470026fbceb0978d
701,320
from typing import Any import torch def infer_device(x: Any): """Infer the device of any object (CPU for any non-torch object)""" if isinstance(x, torch.Tensor): return x.device return torch.device("cpu")
a566c267897ca602e13710a30d928fdc49f856a5
701,322
def __increaseCombinationCounter(root): """ increase the combination-counter, which is located in the provided root-node """ if root['type']=='graphroot': root['combination'] += 1 return root
c2f7c88ef2eca4f8c4bf6532cc76ed5a1833dfe6
701,329
import re def remove_numbers(s): """Removes numbers, including times.""" return re.sub('\d+(:\d*)*(\.\d*)?', ' ', s)
b234b914cc84b04cd183ba086674df0775f3b098
701,335
def _escapeWildCard(klassContent): """ >>> _escapeWildCard('') '' >>> _escapeWildCard(':*') '' >>> _escapeWildCard(':Object') ':Object' """ return klassContent.replace(':*', '')
537b3969dabb46c3a093dacc3ba49a58833f8c18
701,336
from typing import Any def tsv_escape(x: Any) -> str: """ Escape data for tab-separated value (TSV) format. """ if x is None: return "" x = str(x) return x.replace("\t", "\\t").replace("\n", "\\n")
febefd579773aa4deea90e589114d39c5b8a4784
701,338
def cardinal(converted_data, path): """ Translates first move on path to cardinal direction. Args: converted_data (dict): python readable json path (list): path from a* Return: direction (str): cardinal direction as string """ # if x values are same check y values for direction if converted_data["you"]["body"][0]['x'] == path[1][0]: if (converted_data["you"]["body"][0]['y']) < (path[1][1]): direction = 'down' else: direction = 'up' # x values are different check them for direction else: if (converted_data["you"]["body"][0]['x']) < (path[1][0]): direction = 'right' else: direction = 'left' return direction
6802276a8e06a127383cfbe0dcbe511bd0ef2260
701,340
def decrypt(sk, c): """Decrypt a cyphertext based on the provided key.""" return (c % sk) % 2
d3a96f66e1b449ffbd5b6ca1ba0827455b83f9e2
701,346
def _fix_filename(filename): """Return a filename which we can use to identify the file. The file paths printed by llvm-cov take the form: /path/to/repo/out/dir/../../src/filename.cpp And then they're truncated to 22 characters with leading ellipses: ...../../src/filename.cpp This makes it really tough to determine whether the file actually belongs in the Skia repo. This function strips out the leading junk so that, if the file exists in the repo, the returned string matches the end of some relative path in the repo. This doesn't guarantee correctness, but it's about as close as we can get. """ return filename.split('..')[-1].lstrip('./')
d4b005f591879aab44275d100e725f61b5d6a764
701,357
def testFloat(val): """ Test value for float. Used to detect use of variables, strings and none types, which cannot be checked. """ try: return type(float(val)) == float except Exception: return False
19f3eac980b4489b7d14b1f994002a887f063ac7
701,358
def to_xhr_response(request, non_xhr_result, form): """ Return an XHR response for the given ``form``, or ``non_xhr_result``. If the given ``request`` is an XMLHttpRequest then return an XHR form submission response for the given form (contains only the ``<form>`` element as an HTML snippet, not the entire HTML page). If ``request`` is not an XHR request then return ``non_xhr_result``, which should be the result that the view callable would normally return if this were not an XHR request. :param request: the Pyramid request :param non_xhr_result: the view callable result that should be returned if ``request`` is *not* an XHR request :param form: the form that was submitted :type form: deform.form.Form """ if not request.is_xhr: return non_xhr_result request.override_renderer = 'string' return form.render()
e32c94ecb3a5ce12c81ea312647b8bf527007bfc
701,365
def optional(converter): """ A converter that allows an attribute to be optional. An optional attribute is one which can be set to ``None``. :param callable converter: the converter that is used for non-``None`` values. .. versionadded:: 17.1.0 """ def optional_converter(val): if val is None: return None return converter(val) return optional_converter
128042c7a95bb91c665ab6ac0f6771e4a72632ed
701,366
import pickle def get_challenge_by_channel_id(database, challenge_channel_id): """ Fetch a Challenge object in the database with a given channel ID Return the matching Challenge object if found, or None otherwise. """ ctfs = pickle.load(open(database, "rb")) for ctf in ctfs: for challenge in ctf.challenges: if challenge.channel_id == challenge_channel_id: return challenge return None
9ae3fc3519b61c6e9a1abceb20b8882e2e29ca48
701,367
def qstr(s, validate=True): """Return a quoted string after escaping '\' and '"' characters. When validate is set to True (default), the string must consist only of 7-bit ASCII characters excluding NULL, CR, and LF. """ if validate: s.encode('ascii') if '\0' in s or '\r' in s or '\n' in s: raise ValueError('string contains NULL, CR, or LF characters') return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"'
2805c2aff61294cafe6719e9a8bd93082d9603df
701,372
import random def random_permutation(iterable, r = None): """random_product(iterable, r = None) -> tuple Arguments: iterable: An iterable. r(int): Size of the permutation. If :const:`None` select all elements in `iterable`. Returns: A random element from ``itertools.permutations(iterable, r = r)``. Examples: >>> random_permutation(range(2)) in {(0, 1), (1, 0)} True >>> random_permutation(range(10), r = 2) in permutations(range(10), r = 2) True """ pool = tuple(iterable) r = len(pool) if r is None else r return tuple(random.sample(pool, r))
7e84d33b62786d08443dc5ea2c66ff65ced3070c
701,373
def language_to_flag(code): """Generates css flag class for the language code""" if code.lower() == 'en': return 'flag-icon flag-icon-us' return 'flag-icon flag-icon-' + code.lower()
8d81d1e1cdac675a6bdf94bb22ac6f45993338db
701,375
def truncate_patch_version(version): """Return just the major and minor versions from `version`.""" split_version = version.split(".") return "{}.{}".format(split_version[0], split_version[1])
d4eb7f23aeab17f862b13109315a417039eb6897
701,378
def get_key_value_list(lines): """ Split lines at the first space. :param lines: lines from trackhub file :return: [(name, value)] where name is before first space and value is after first space """ result = [] for line in lines: line = line.strip() if line: parts = line.split(" ", 1) name = parts[0] value = parts[1] result.append((name, value)) return result
aa2d1c3b100c963a50c05cfaf684df5bbed612bd
701,380