content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import textwrap def public_doc(name: str, url: str) -> str: """Generate public module gallery docs from template.""" summary = f'This example was generated from `{name} source <{url}>`_' summary = '\n'.join(textwrap.wrap(summary, width=79)) return f""".. _gallery-{name}: {name} {'=' * len(name)} {sum...
84e77bad4f2050b4c3abfa8155ed20aed6964cea
664,751
def _format_list(param_name, list1, datadict, **kwargs): """Concatenate and format list items. This is used to prepare substitutions in user-supplied args to the various test invocations (ie: the location of flash). Args: @param param_name: The name of the item in `datadict`. @param lis...
756470f28817e33f94bf4aa798db691ac5e92ea0
664,752
import requests from bs4 import BeautifulSoup def make_request(url): """ Make the request and return a soup obj :param url: the subito.it url :return: a bs4 obj """ http_response = requests.get(url).text return BeautifulSoup(http_response, 'html.parser')
81fe071a35602c556113692872364790c6fa224b
664,754
def propagation_level_end(start_point: tuple, shape: tuple) -> int: """ Returns the maximum propagation level where our data points will change I.e. if start_point=(8, 8, 8) and shape=(16, 16, 16), then returns 8 If start_point=(1, 1, 3) and shape=(16, 16, 16) then returns 16-1=15 """ max_val = ...
4558f286851261016e6c8f268622a91eb5640b86
664,757
def sum(mat, axis, target = None): """ Sum the matrix along the given dimension, where 0 represents the leading dimension and 1 represents the non-leading dimension. If a target is not prvided, a new vector is created for storing the result. """ return mat.sum(axis, target)
105180c057bed95f2282ca168ec025fd06cf30e7
664,760
def truncate_xticklabels(plot, stop_index=30): """ Truncate xtick labels with an ellipsis after `stop_index` """ for label in plot.get_xticklabels(): t = label.get_text() if len(t) < stop_index: continue else: label.set_text(t[:stop_index] + '...') ...
960448266e8dcdd5dcca593d70c9d612e8cec160
664,762
import copy def with_base_config(base_config, extra_config): """Returns dict with updates applied, helpful for one-liners""" config = copy.deepcopy(base_config) config.update(extra_config) return config
9afbc45a84047bcb8f971e8b486c0cca7cfd5644
664,765
import pathlib def replace_marker(text: str, marker: str, src_filename: str, replace_marker_with_src_file: bool = True) -> str: """ replace a marker in the text with the content of a file, or with '' """ if replace_marker_with_src_file: path_base_dir = pathlib.Path(__file__).parent path_src_fi...
1c8302f40fadde7b85e6bd13e84c4a5cb6e6ceac
664,768
import bisect def find_le(a, x): """Find rightmost value less than or equal to x""" i = bisect.bisect_right(a, x) if i: return a[i-1] raise ValueError
a2bdd7d6a63bbabaf64b86469852647627ac7d35
664,770
def from_uint8_bytes(uint8: bytes) -> int: """Convert from uint8 to python int.""" return int.from_bytes(uint8, byteorder="little")
cdabcd0d9fa16681ab89e11bb16d4c6a4d556024
664,772
def Precipitation(prec, temp, tt, rfcf, sfcf): """ ======================================================== Precipitation (temp, tt, prec, rfcf, sfcf) ======================================================== Precipitaiton routine of the HBV96 model. If temperature is lower than TT [degree C], ...
5c6f92c73da5193e740a69ac26e5edbe52281fa3
664,773
import typing import math def triangle_ASA(alpha: float, c: float, beta: float) -> typing.Tuple[float, float, float]: """Given angle at A, included side A-B, angle at B of a plane triangle this returns side A-C, angle at C, side C-B. Angles in radians. See: https://en.wikipedia.org/wiki/Solution_of_triang...
9858caf5875c0842ecd6120a80abcb504e574af5
664,774
def is_runway_visibility(item: str) -> bool: """Returns True if the item is a runway visibility range string""" return ( len(item) > 4 and item[0] == "R" and (item[3] == "/" or item[4] == "/") and item[1:3].isdigit() )
e463aeb4e4faf07ab0daeb45eff072add448225f
664,775
def E(expr): """ The notion of the expectation of random variables and the worst-case expected values Notes ----- This function is used to denote 1. the expected value of an random variable when specifying the uncertainty set of expectations. 2. the worst-case expected value of an a...
70d23356c0e49e4decb9cd069f059af8a15104f2
664,779
def match_barcode_rule(trello_db, barcode): """Finds a barcode rule matching the given barcode. Returns the rule if it exists, otherwise returns None.""" for rule in trello_db.get_all('barcode_rules'): if rule['barcode'] == barcode: return rule return None
e6a240c265b61025f77175b7d4be4f7e868263b7
664,784
from typing import TextIO from typing import List def parse_floats(io: TextIO) -> List[float]: """Parse first line of io to list of floats. Parameters ---------- io :: TextIO Object supporting `readline()` Returns ------- floats :: List[float] A list of floats Exampl...
58c6cc69e28f06c5d831b7bdab47793619110b12
664,786
def hex2int(hex_str): """ Convert hex characters (e.g. "23" or "011a") to int (35 or 282) :param hex_str: hex character string :return: int integer """ return int(hex_str, 16)
b6ba55909550a9e4714f6209b08bda633a2c9a4b
664,788
def determine_ambiguous_references(columns: set, definitions: set) -> set: """ Return the set of reference names that exist as both a column and a definition. """ # get the diffs between the two sets unambiguous_columns = columns - definitions unambiguous_definitions = definitions - columns # then...
2adbd2133d73f1c7fed6cae9ab2bd4099dde5b17
664,792
def get_repo_name(pull_request, key): """ Extract repo name from a pull request dict. """ return pull_request[key]["repo"]["name"]
34d002d70d92005bb512c7ce624a2244cfad5519
664,798
import math def gon_to_rad(angle: float) -> float: """Converts from gon (grad) to radiant. Args: angle: Angle in gon. Returns: Converted angle in rad. """ return angle * math.pi / 200
e87714d6162ea8457118dfd4cbdfc67a7a21069d
664,802
def decode_int(v): """Decodes integer value from hex string. Helper function useful when decoding data from contracts. :param str v: Hexadecimal string :return: Decoded number :rtype: num """ if v[0:2] == '0x': return int(v.replace('0x', ''), 16) else: return int(v)
3bf1ae523a4d1597a019d9ec7d83d2667f89aba9
664,804
def closed_neighborhood(graph, v): """The closed neighborhood of a vertex in a graph Args: graph (networkx.classes.graph.Graph): graph v: vertex in a graph Returns: The neighbors of v in graph, as a set. Example: >>> import networkx as nx >>> from pycliques.dominated imp...
451b7c57d339bb9826bb417ee064dc3fb62c0df3
664,805
def NP(record): """ "No Process": the linked record is not processed. This is the default behavior of EPICS links. Example (Python source) ----------------------- `my_record.INP = NP(other_record)` Example (Generated DB) ---------------------- `field(INP, "other NPP")` """ retu...
68041ce93ffa3df2d12b989a1105f194b341126a
664,806
def camels_in_dest(camel_dict, destination): """Find the camels in the destination square Parameters ---------- camel_dict : nested dict Dictionary with current camel positions destination : int Square where camels are moving Returns ------- max_height_dest : int ...
1a619f06ba4d606357d7229f6a5a0d2e8d717476
664,813
def _capability(interface, version=3, supports_deactivation=None, cap_type='AlexaInterface'): """Return a Smart Home API capability object. https://developer.amazon.com/docs/device-apis/alexa-discovery.html#capability-object There are some additional fields ...
b12abc29c9fa1dd5bb7e8795be6dd6de8c865f40
664,814
import re def list_urls_from_string(text): """ From: https://stackoverflow.com/a/48769624/2907906 Modified to require the protocol (http:// or https://) to be present It'll return a list of urls present in the string """ return re.findall("(?:(?:https?):\/\/)[\w/\-?=%.]+\.[\w/\-?=%.]+", text)
88338c3c4e1eb75f5ee0819ab0f4cc15405cdb06
664,815
def coords_zero(coords): """ Return the origin for the coords """ return (0,) * len(coords)
345240a2b060ce5f7a295967de4bf432c436efc4
664,816
import json def loads(kv_data): """ Decoding Key Value Json String :param kv_data: [String] JSON String representing the Key Value information :return: [Dictionary] Returns the JSON in dictionary form """ dict_kv = {} if isinstance(kv_data, str): kvs = json.loads(kv_data) ...
8713262b8cac0cdbe0f3fd7cdfb1e9771a0727ca
664,817
import base64 def decode(encoded_message): """ Decodes the message in base64 Args: encoded_message (str): encoded message Returns: str: decoded message """ encoded_message_bytes = encoded_message.encode("ascii") decoded_base64_bytes = base64.b64decode(encoded_message_byt...
2d7a23bc4e0d36b4f72ae5b17d24f9957e187615
664,821
def is_unlimited(rate_limit): """ Check whether a rate limit is None or unlimited (indicated by '-1'). :param rate_limit: the rate limit to check :return: bool """ return rate_limit is None or rate_limit == -1
8e19a8aff46713c6e1886b40bf005217166eda01
664,822
def remove_arc(net, arc): """ Removes an arc from a Petri net Parameters --------------- net Petri net arc Arc of the Petri net Returns ------------- net Petri net """ net.arcs.remove(arc) arc.source.out_arcs.remove(arc) arc.target.in_arcs.re...
d8451203ab774ce936823a22022b0fdd2160162d
664,826
def get_overlap_between_intervals(a, b): """ Finds the overlap between two intervals end points inclusive. #Makes sure not to report overlap beyond either interval length. # a=[10,20]; b=[10,20] --> f(a,b)=10 !(not 11) # a=[10,20]; b=[20,30] --> f(a,b)=1 a=[10,20]; b=[15,30] --> f(a,b)=6 """ #lena=abs(float(a...
aac42510aa368cd793cc93cd3e9f840df9580005
664,827
def _async_get_hass_provider(hass): """Get the Home Assistant auth provider.""" for prv in hass.auth.auth_providers: if prv.type == 'homeassistant': return prv raise RuntimeError('No Home Assistant provider found')
2de333978a219f8a0aa2bc0942896477b8cbba9e
664,828
def split_train_test(X_all, y_all, frac_train): """ The first X% of X_all, y_all become the training set, the rest (1-X)% become the test set. Note that this assumes that the samples are already shuffled or if not (e.g. if we were to split MNIST) that this behavior is intended. """ num_total = X...
5939261def8afba47a2d0e88e23561f5d7e9acd3
664,829
def min_max_temp(cities_data): """Returns a list whose first and second elements are the min and the max temperatures of all the cities in cities_data. """ temps = [] for r in cities_data: temps.append(float(r['temperature'])) return [min(temps), max(temps)]
3b99aa8a1fd0c9d8539a3d7a7fe95bd80df47ab8
664,830
def trim(msa, threshold=0.0): """Trim a MSA to its first and last non-gap containing columns.""" def gap_pct(msa, index): return msa.column(index).count("-") / msa.count() length = len(msa) start, end = 0, length - 1 start_found, end_found = False, False for i in range(length): ...
c15a4e02af679ead90b90ef35d1d1d251971af84
664,832
def stray(arr): """ You are given an odd-length array of integers, in which all of them are the same, except for one single number. :param arr: an array of integers. :return: the single different number in the array. """ a, b = set(arr) return a if arr.count(a) == 1 else b
17e99c2d22baceb89c16c01a138896918ab3a9e6
664,833
def block_to_dict(block): """ Serialize a block as a dict. """ return { "type": block.type, "value": block.value }
c53b1d12eb1fd347b46afc2adb275cf41294b79e
664,834
def get_inside_outside_brackets(data, start_char, end_char, nested=True): """Split string into portions inside and outside delimiters Args: data: str The string to parse start_char: str Character indicating the beginning of a delimited string end_char: str ...
535c4d57ca8bfd7b9347e6251ecc95ffacdadf15
664,835
import hashlib def hash_string(string): """ return the md5 hash of a string""" return hashlib.md5(string).hexdigest()
356dd3c74b080fa8b305513c18ea5624f6e1435a
664,836
import torch def sample_from_latent_distribution(z_mean, z_logvar): """Samples from the Gaussian distribution defined by z_mean and z_logvar.""" e = torch.randn_like(z_mean) return torch.add( z_mean, torch.exp(z_logvar / 2) * e, )
d085282de657a7bb540aad1520ca984ac158aeb5
664,839
def valid_type(str_of_type): """Function for returning a pandas type given a string value representing that type Args: str_of_type (str): a python type in string form Outputs: the Pandas term for that type """ if str_of_type in ['int','integer']: return('Int6...
1e75e2a752f7ce44b6e6839ce570c2872d950c95
664,840
def file_id(file_query): """Returns an ID of the form `_file_$ID` to represent a [snoop.data.models.File][]. This ID is used to cross-link objects in the API. """ return f'_file_{file_query.pk}'
372c2290c372130f6e5ce9c5001952595aea81e9
664,843
def composeVideoMaskName(maskprefix, starttime, suffix): """ :param maskprefix: :param starttime: :param suffix: :return: A mask file name using the provided components """ if maskprefix.endswith('_mask_' + str(starttime)): return maskprefix + '.' + suffix return maskprefix + '_m...
0fe45da135f79086fa52ca2fdca55a6cc51b9a3d
664,845
def handler(context, inputs): """Set a name for a machine :param inputs :param inputs.resourceNames: Contains the original name of the machine. It is supplied from the event data during actual provisioning or from user input for testing purposes. :param inputs.newName: The new mac...
87251564bf262d3ef114d171767ce0afb8d03c77
664,847
def make_dict(tokens): """Converts a parsed list of tokens to a dictionary.""" tokdict={} for t in tokens: tokdict[t[0]]=t[1:] return tokdict
5048267d24d211aef26a72e74a4aa96792713304
664,848
def format_score(logpath, log, markup): """Turn a log file JSON into a pretty string.""" output = [] output.append('\nLog: ' + logpath) if log['unrecognized']: output.append('\nLog is unrecognized: {}'.format(log['unrecognized'])) else: if log['flagged']: output.append('\...
c3ac492375b72d05481a3a2dc2986149f79b405e
664,860
def reply(f): """ Mark f as a handler for mention notifications. """ f.reply = True return f
7da700ed2ab1b4b6e82b7c6d7bc6bab4e4c228a8
664,863
def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = {} index = 0 with open(vocab_file, "r", encoding="utf-8") as reader: while True: token = reader.readline() if not token: break token = token.strip() ...
2b5dd2acf12f6917154734beb7ab209270bef5f7
664,864
def win_check(board, mark): """ function that takes in a board and checks to see if someone has won. :param board: the board to check :param mark: the last mark in placed in the board :return: True if game is win or False otherwise """ return ((board[7] == mark and board[8] == mark and board...
38cad514d38aa42fdb88ebe4cb174f2999a9ae9b
664,866
import random def get_random_coordinate(image): """ Example: coordinates= get_random_coordinates() # gives random x-y coordinates inside image Output: return tupe (x,y). """ x,y,z=image.shape return (random.randint(0,y),random.randint(0,x))
54cbed37aba48363875602b60e2efa6c43dcff99
664,868
def contains(self, key): """ return True if key is in self, False otherwise """ try: # pylint: disable=pointless-statement self[key] return True except KeyError: return False
b8a0f34a5cfce124a474b881cfbdd822802e45c6
664,869
def convert_seconds(seconds): """Converts the provided seconds value into days, hours, minutes, seconds and returns a tuple containing each of these values""" # Converting seconds to a standard python float type to resolve the "negative 0 when using numpy.float64 type" issue . seconds = float(seconds) ...
664aead3b845243921fe259d7b858fe91f488a37
664,871
def _hashable(x): """ Ensure that an point is hashable by a python dict. """ return tuple(map(float, x))
a76a98475400df98978f5e4f12c5fcd842b56b29
664,873
def make_sepset_node_name(node_a_name, node_b_name): """ Make a standard sepset node name using the two neighboring nodes. :param str node_a_name: The one node's name. :param str node_b_name: The other node's name. :return: The sepset's name :rtype: str """ return "sepset__" + "__".join...
ef8f645dd514b792d278386edac250c02e0a22a6
664,874
def readHysteresisDelayfromGUI(delay, timeZero): """ Read and create Hysteresis Delays from GUI. The values are given relative to the timezero (so -20 means 20ps before the set t0). The returned value is the absolute ps Delay for the setting of the stage. :param delay, timeZero: :return: delayV...
f51e4a6348a63d6017a722457e661b6044a89317
664,876
def to_ascii(text): """Convert text to ascii.""" asciiText = ''.join([ch if ord(ch) < 128 else ' ' for ch in text]) return asciiText
e66f47599cf3ace70636f2ccec540c7d753301a8
664,881
def SpanValue(span, arena): """Given an line_span and a arena of lines, return the string value. """ line = arena.GetLine(span.line_id) c = span.col return line[c : c + span.length]
2511452c2ba055f267d405b2e959e898ccb66ca0
664,886
import re def parse_direct_mention(message_text): """ Finds a direct mention (a mention that is at the beginning) in message text and returns the user ID which was mentioned. If there is no direct mention, returns None """ matches = re.search("^<@(|[WU].+?)>(.*)", message_text) # the f...
f72b248f8e31d0bbfb620fb37f382ca4f7c66d28
664,889
def rpc_get_methods(client, current=None, include_aliases=None): """Get list of supported RPC methods. Args: current: Get list of RPC methods only callable in the current state. include_aliases: Include aliases in the list with RPC methods. """ params = {} if current: params...
7473720d7bfe354300176a107660ad4bdd4d4a88
664,891
import time def rt_format_comment_time(t): """ Given a time struct representing the RT ticket's comment timestamp, this returns a formatted, printable version of this timestamp. :param t: the time struct of the RT ticket's comment timestamp """ return time.strftime("%a %b %d %H:%M:%S %Y UTC"...
83e230471d2d0dbffed2e4bfac668c93a2f6dd92
664,893
from typing import Tuple def extended_euclidean(num_a: int, num_b: int) -> Tuple[int, int, int]: """ Perform the extended euclidean algorithm on the input numbers. The method returns gcd, x, y, such that a*x + b*y = gcd. :param num_a: First number a. :param num_b: Second number b. :return: Tu...
0ea9ef0c45ec70cf0c6642ad74ab312fc30fb8bc
664,895
def legacy_id_to_url_fn(id: str) -> str: """Generate an arxiv.org/archive URL given a paper ID.""" return 'https://arxiv.org/archive/' + id
05859591e6af147c2df5e958e1e2b3a4473e9376
664,898
def feature_engineering(df): """Add statistics to raw data to analyze changes across time""" # day-to-day change df['result_count_absolute_change'] = df.groupby('keyword').results_count.diff().reset_index(drop=True) # day-to-day absolute change df['result_count_relative_change'] = (df.result_count_ab...
10198d93c27f3d45ee046c751d89188768dfc108
664,901
def confirm_proceed(prompt='Shall I proceed? (y/n)'): """ Prompts user for confirmation. Expects 'y' or 'n'. """ confirm = '' while confirm not in ('y', 'Y', 'n', 'N'): confirm = input(prompt) if confirm in ('n', 'N'): return False return True
a71d78f5670eca9a13997b603e6c6805001e9167
664,906
def reversepath(path): """ This function reverses a path. """ return path[::-1]
16a9b33eaf6bb4f602952c094a2e1d272ae82857
664,908
import json def json_minimal(data): """Get JSON data in minimal form.""" return json.dumps(data, separators=(",", ":"))
e4b76f5decb0060f86071fed1a6fecf55012daff
664,910
import collections def get_table_data(cursor, table_name, single_row=False, replace_none=False): """ Extract all the data of the table Args: cursor: the DB cursor table_name: the name of the database single_row: if True, returns a single row replace_none: if True, replace ...
f8b15f82998bc4516346d54caeed40cc5f4fea1b
664,911
def galois_multiply(a, b): """Galois Field multiplicaiton for AES""" p = 0 while b: if b & 1: p ^= a a <<= 1 if a & 0x100: a ^= 0x1b b >>= 1 return p & 0xff
f9df9ff55f58747c0c2669e3813666841f0ce8ee
664,914
import math def calc_node_distance(graph, node_1, node_2): """ Calculates distance between two nodes of graph, Requires node attribute 'position' as shapely Point, e.g. Point(10, 15.2) Parameters ----------- graph : nx.graph Graph object of networkx node_1 : int Node id of...
a0a0def854fe2cef4e1fa59567b05a98874d8637
664,918
def compareThresh(value,threshold,mode,inclusive, *, default=False): """Returns a boolean only if value satisfies the threshold test. In case of failure of any sort, returns the default value (which defaults to 'False'). Accepted mode values are '<', '>', '<=' and '>='.""" #normalizing input i...
ea3b4fc683c7940996d42c27962217a1ebec7efe
664,919
def filter_rule(_): """ No rule is needed """ return True
59502d20357ba108f900605b30df012ea9e0462d
664,923
def calc_total_event(events_dict: dict) -> int: """各照射回数の合計を求める Args: events_dict (dict): Returns: int: cnt """ cnt = 0 for key in events_dict.keys(): n = int(events_dict[key]) cnt = cnt + n return cnt
62f7fb699238e208bdaf1b2dcf3527932e97a4ad
664,925
def _compute_bands_from_cuts(cuts, sequence_length, linear=True): """Compute the size of the obtained bands from the position of cuts. Returns a list of band sizes. Parameters ---------- cuts Location of the different cuts on the plasmid. sequence_length Length of the DNA molecule...
39fbf3b4d5bdfb188cb18aee69c454d59818da68
664,926
import glob def sorted_glob(pathname):#, cmp=None, key=None, reverse=None): """Returns a sorted list of file names matching glob pattern `pathname'. Added here to accomodate older python that do not have sorted() function.""" rslt = glob.glob(pathname) rslt.sort() #cmp=cmp, key=key, reverse=reverse) return ...
658cc141b54838cbffd07f6b34bd2bfcca50b704
664,927
def _get_valid_indices(shape, ix0, ix1, iy0, iy1): """Give array shape and desired indices, return indices that are correctly bounded by the shape.""" ymax, xmax = shape if ix0 < 0: ix0 = 0 if ix1 > xmax: ix1 = xmax if iy0 < 0: iy0 = 0 if iy1 > ymax: iy1 = ym...
576038f9b724688a654536e149d3731d90f4f33f
664,931
def get_var(environ, keys, default=None): """Try each of the keys in turn before falling back on the default.""" for key in keys: if environ.has_key(key): return environ.get(key) return default
6fff84d57c8713e09d134e1dea827c4bcff9b4b7
664,932
def sometrue(*args, **kwargs): """ Check whether some values are true. Refer to `any` for full documentation. See Also -------- any : equivalent function; see for details. """ return any(*args, **kwargs)
a457d7c0d67f4993703f3689022fcd07cdf930df
664,933
def _label_str(block): """Returns a string by which the given block may be named, even if `None`.""" if block is None: return 'exit' else: return block.label_str
17c4a3ede998dc1d62860777132f22763bb07b5d
664,935
def react_polymer(polymer_string): """ Iterate through polymer_string, replacing all instances where two adjacent characters are case-insensitive equal but not equal (i.e. A and a) with the empty string """ # convert to a list since strings are immutable polymer_list = [i for i in polymer_st...
6ed62ba4c70c3848764619b9cb3ef06057e512d0
664,936
def deepgetattr(obj, attr, default = None): """ Get a named attribute from an object; multi_getattr(x, 'a.b.c.d') is equivalent to x.a.b.c.d. When a default argument is given, it is returned when any attribute in the chain doesn't exist; without it, an exception is raised when a missing attribute is...
fb3363d362f198e1ad4037f18b8c514be5742c49
664,938
def graphql_mutation( field_name, field_type, arguments={}, context_args=[], description=None, is_deprecated=False, deprecation_reason=None): """Annotate a function as corresponding to a GraphQL mutation. Decorator that annotates a function as corresponding to a GraphQL mutation; i.e. a fie...
9606cc1360e896c43033d857294f7a78c5499471
664,941
import shutil def check_disk_space(available_disk_space_percent_threshold): """ Checks if disk space is above given threshold. Args: available_disk_space_percent_threshold(int): The disk space threshold you want the root drive to be above. Returns: (Bool): Returns true if disk sp...
1cddea39081ec4374025591ffccd3651d66bbd67
664,944
def humanize_timedelta(td): """Pretty-print a timedelta in a human readable format.""" secs = int(td.total_seconds()) hours, secs = divmod(secs, 60 * 60) mins, secs = divmod(secs, 60) if hours: return '%dh %dm' % (hours, mins) if mins: return '%dm' % mins return '%ds' % secs
fce51215776b39f0745dbc81b9bc1072e05cf443
664,946
def is_game_row_valid(game, lookup): """Returns whether all columns can be found in the game entry. Parameters: game: the entry for the game lookup: a lookup for fields to indexes in columns Returns: true if valid row otherwise False """ for index in lookup.values(): ...
a1a177788ddf827c236b4e71c7f8ee1a10fc9b65
664,948
def format_syntax_error(e: SyntaxError) -> str: """ Formats a SyntaxError. """ if e.text is None: return "```py\n{0.__class__.__name__}: {0}\n```".format(e) # display a nice arrow return "```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```".format( e, "^", type(e).__name__)
2ef5713ef65338c4f6b0a878a3632da85816bb20
664,949
from typing import List from typing import Dict def diff_to_new_interesting_lines(unified_diff_lines: List[str]) -> Dict[int, str]: """ Extracts a set of 'interesting' lines out of a GNU unified diff format. Format: gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html @@ from-li...
67e213b5b9f704287b25fa4cd226267b50869aa2
664,951
def find_xpath(xpath, tree, namespaces={}, **kwargs): """ Find elements within an XML tree whose attributes match certain values. :param xpath: an xpath query string. :param tree: `xml.etree.ElementTree` object. :param namespaces: a dictionary of namespace prefixes. :param kwargs: specifies...
2fe1bbc305a2dc651865b171efdcf5ea33d6089b
664,961
import inspect def getPublicTypeMembers(type_, onlyValues=False): """ Useful for getting members from types (e.g. in enums) >>> [_ for _ in getPublicTypeMembers(OS, True)] ['Linux', 'Windows'] """ retVal = [] for name, value in inspect.getmembers(type_): if not name.startswith("...
859dcce8245e6eac372fc8db5e4559366600b309
664,964
def rolling_average(current_avg: float, new_value: float, total_count: int) -> float: """Recalculate a running (or moving) average Needs the current average, a new value to include, and the total samples """ new_average = float(current_avg) new_average -= new_average / total_count new_average +...
212792c49d4ab83a3edb3547820028e1fbb8dad5
664,966
from typing import List from typing import Dict def _process(proc_data: List[Dict]) -> List[Dict]: """ Final processing to conform to the schema. Parameters: proc_data: (List of Dictionaries) raw structured data to process Returns: List of Dictionaries. Structured to conform to t...
ce8a7e10ab12ba58b41c4e8286b054ea4f81dad0
664,967
def remove_specific_key(dictionary, key): """ Remove a specific named key from a dictionary. Args: dictionary: The dictionary to have a key removed key: The key to be removed Returns: dictionary: The dictionary with the key removed """ if key in dictionary: del ...
fca4bc62e300ced8d472219374594235bc549f2b
664,969
def pulse_sink_port(sink, name_or_desc): """ Returns the PulseSinkInfo that matches the string, either against the name or the description. :param sink: the PulseSinkObject to get the port from :type sink: pulsectl.PulseSinkObject :param name_or_desc: the name or description string to look for, use...
819c97da9b5f27d65a59ad8d1b85335bc11de8d4
664,972
def _group_list(items, lens): """ Unflat the list of items by lens :param items: list of items :param lens: list of integers :return: list of list of items grouped by lengths """ res = [] cur_ofs = 0 for g_len in lens: res.append(items[cur_ofs:cur_ofs+g_len]) cur_ofs ...
1057ee2493fe6a439377f33b0c4f5401f3d7cefa
664,976
import json def dump_bytes(*args, **kwargs): """Converts an object to JSON and returns the bytes.""" return json.dumps(*args, **kwargs).encode("ascii")
95fbaf372723a3e462ab572e3311da79c596221c
664,977
import copy def _GenerateInferredAshFlags(device_config): """Generate runtime-packed ash flags into a single device config. Chrome flags are packed into /ui:serialized-ash-flags in the resultant runtime-only configuration, as a string of null-terminated strings. Args: device_config: transformed config...
0501a4a985910c8412584d9b64d620e6ae12febd
664,978
from typing import Sequence def _should_ignore_markdown_cell( source: Sequence[str], skip_celltags: Sequence[str], tags: Sequence[str], ) -> bool: """ Return True if the current cell should be ignored from processing. Parameters ---------- source Source from the notebook cell ...
a3de5307c3252df0388d2bc7d5f8060759b6f76f
664,979
def station_locations(df, id_index): """ Creates a dictionary with station IDs as keys and locations as values. Parameters ---------- df : pandas DataFrame Bikeshare trip data. id_index : dict Maps station ID (arbitrary integer) to the range from 0 to number of stations Ret...
482c1f1a1c4c42768b9a06e5ed608c6d95da4144
664,981
def camel_to_snake(s: str) -> str: """Converts "CamelCase" to "snake_case".""" return "".join(f"_{c}" if c.isupper() else c for c in s).strip("_").lower()
d6697877e5a00ce2bb1149dd6cf0da2b0230c9cd
664,982
import binascii def npbytearray2hexstring(npbytearray, prefix="0x"): """Convert a NumPy array of uint8 dtype into a hex string. Example: npbytearray2hexstring(array([15, 1], dtype=uint8)) = "0x0f01" """ return prefix + binascii.hexlify(bytearray(npbytearray)).decode("utf-8")
0d2dd571b25261774d7aad5156dbdb2bf9ec6357
664,985