content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def build_evaluation_from_config_item(configuration_item, compliance_type, annotation=None): """Form an evaluation as a dictionary. Usually suited to report on configuration change rules. Keyword arguments: configuration_item -- the configurationItem dictionary in the invokingEvent compliance_type -- ei...
05769fc549acdcec7ed611abeff5f0b4f695e57e
699,335
def splitbycharset(txt, charset): """Splits a string at the first occurrence of a character in a set. Args: txt: Text to split. chars: Chars to look for (specified as string). Returns: (char, before, after) where char is the character from the character set whic...
c23577eb96c9621909acaa816e8791e95dbf493d
699,340
def process_meta_review(meta_review): """ Do something with the meta-review JSON! This is where you would: 1. Translate meta_review["ty_id"] to your own hotel ID, dropping any unmapped hotels 2. Traverse the JSON structure to find the data you are interested in, documented at http://api.trustyo...
681ace9b9685f4bfd284ac6e41efde12bafbb1b9
699,341
def find_natural_number(position: int) -> tuple: """Return natural number at specified position and number its a part of.""" num_range = "" counter = 0 while len(str(num_range)) < position: counter += 1 num_range += str(counter) return int(num_range[-1]), counter
62aff0c400ac007fc67dafd25eb4cacf63262105
699,342
def camel_case(snake_case: str) -> str: """Converts snake case strings to camel case Args: snake_case (str): raw snake case string, eg `sample_text` Returns: str: camel cased string """ cpnts = snake_case.split("_") return cpnts[0] + "".join(x.title() for x in cpnts[1:])
b3080a3e3520209581cbd381ffaff24045343115
699,343
def identify_contentType(url): """ Given a URL for a content, it identifies the type of the content :param url(str): URL :returns: Type of the content """ extensions = ['mp3', 'wav', 'jpeg', 'zip', 'jpg', 'mp4', 'webm', 'ecar', 'wav', 'png'] if ('youtu.be' in url) or ('youtube' in url): ...
720a9ea9adaab547309f61b6858b0eb19ddebafe
699,349
def stack(x, filters, num_blocks, block_fn, use_bias, stride1=2, name=None): """A set of stacked residual blocks. Arguments: x: input tensor. filters: integer, filters of the bottleneck layer in a block. use_bias: boolean, enables or disables all biases in conv layers. num_blocks: integ...
1ed366778a5abba4e05c070da05e3c87cbd92560
699,351
def pid_info(output_line): """ Take a line of 'ps -o pid,comm' output and return the PID number and name. The line looks something like: 9108 orterun or 10183 daos_server Need both items. Return a tuple (name, pid) Note: there could be leading spaces on the pid. """ info =...
479c51e562b7bbeb7e812fad4b2cb1f771e2e830
699,354
from typing import List from typing import Tuple def two_columns(pairs: List[Tuple]) -> str: """ Join pairs (or more) of strings to a string. :param pairs: List of tuples of strings :return: String separated by newlines """ return '\n'.join([' '.join(map(str, t)) for t in pairs])
810fdab52b4641c32f54c6adc772f8352b8f2ae6
699,357
def get_record_as_json(cur, tablename, row_id): """ Get a single record from the database, by id, as json. """ # IMPORTANT NOTE: Only use this function in trusted input. Never on data # being created by users. The table name is not escaped. q = """ SELECT row_to_json(new_with_table) F...
00521ae582a013f97b77494944e0f6e04069ed05
699,358
def segno(x): """ Input: x, a number Return: 1.0 if x>0, -1.0 if x<0, 0.0 if x==0 """ if x > 0.0: return 1.0 elif x < 0.0: return -1.0 elif x == 0.0: return 0.0
5caccfa037b2972755958f647f009660aefae59d
699,361
def speed_2_pace(speed): """Convert speed in km/hr to pace in s/km""" return 60*60/speed
25379049e98622ec5888461a9f6455be399d5f5a
699,364
from pathlib import Path def get_dictionaries(base: Path) -> list[tuple[str, list[Path]]]: """Make a list of available dictionaries and the interesting files. :param base: The Apple Dictionaries root directory. :return: A list of tuples of name, files for each dictionary. """ all_dicts = sorted( ...
98068ecb847aa6975cc8dc7eed59b8948316f191
699,366
def generate_recipient_from(nhais_cypher): """ Generates the recipient cypher. This value can be deduced from the nhais_cypher provided. The nhais cypher can be 2 to 3 characters is length. If it is 2 characters in length it will append "01" to generate the recipient cypher If it is 3 characters in ...
ac29a09f246fc38b43301cc1b00a4056fc49e203
699,367
def _convert_color(color): """Convert a 24-bit color to 16-bit. The input `color` is assumed to be a 3-component list [R,G,B], each with 8 bits for color level. This method will translate that list of colors into a 16-bit number, with first 5 bits indicating R component, last 5 bits indicating...
6635e30d574288146c5ff07bf3d0d1661cd33b97
699,368
def list_get(lst, index, default=None): """ A safety mechanism for accessing uncharted indexes of a list. Always remember: safety first! :param lst: list :param index: int :param default: A default value :return: Value of list at index -or- default value """ assert type(lst) == list, "Re...
41ca83d6a9b0ba66858617b48dcb6c43ca5a6a54
699,371
def iterate_items(collection, *args, **kwargs): """ iterates over the items of given object. :param type collection: collection type to be used to iterate over given object's items. :rtype: iterator[tuple[object, object]] """ return iter(collection.items(*args, **k...
49fde9f9c027ff1fc64a57ee67b06c91033f8755
699,372
from typing import Tuple def is_multi_class(output_shape: Tuple[int, ...]) -> bool: """Checks if output is multi-class.""" # If single value output if len(output_shape) == 1: return False return True
66726be66cce6f837b40287b75c547d28d709a74
699,374
def cradmin_instance_url(context, appname, viewname, *args, **kwargs): """ Template tag implementation of :meth:`cradmin_legacy.crinstance.BaseCrAdminInstance.reverse_url`. Examples: Reverse the view named ``"edit"`` within the app named ``"pages"``: .. code-block:: htmldjango ...
9cea000ff75b68d536796cbcc323fef1b0a7059b
699,375
import torch def get_discretized_transformation_matrix(matrix, discrete_ratio, downsample_rate): """ Get disretized transformation matrix. Parameters ---------- matrix : torch.Tensor Shape -- (B, L, 4, 4) where B is the batch size, L is the max cav...
fd6ab95dcbb6fca9cab6b35fd5e20998fc12472b
699,378
import yaml def represent_ordered_dict(dumper, data): """ Serializes ``OrderedDict`` to YAML by its proper order. Registering this function to ``yaml.SafeDumper`` enables using ``yaml.safe_dump`` with ``OrderedDict``s. """ return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_...
f8c83dd3b3ecf94077b7b465334ffa84df7e16a8
699,385
def get_dot_size(val, verbose=False): """ Get the size of the marker based on val :param val: the value to test :param verbose: more output :return: the size of the marker in pixels """ markersizes = [6, 9, 12, 15, 18] # there should be one less maxmakervals than markersizes and then we...
aa84c98a3cb78822dd02a9062f9f9a325907b310
699,387
import six def _tuplify_version(version): """ Coerces the version string (if not None), to a version tuple. Ex. "1.7.0" becomes (1, 7, 0). """ if version is None: return version if isinstance(version, six.string_types): version = tuple(int(x) for x in version.split(".")) as...
97575c813ce585e7e928b129e67196dcece5db0a
699,388
from typing import Type from typing import Callable from typing import Any def is_type(tipe: Type) -> Callable[[Any], bool]: """ :param tipe: A Type :return: A predicate that checks if an object is an instance of that Type """ def predicate(value: Any) -> bool: """ :param value: An...
2b4be636675216c810f9e14f70fe8a5647552e3f
699,394
def strip_constants(df, indices): """Remove columns from DF that are constant input factors. Parameters ---------- * df : DataFrame, of input parameters used in model run(s). * indices : list, of constant input factor index positions. Returns ---------- * copy of `df` modified to exclu...
5a68d9beaa39cb2651ccd995af20d25165ccb03e
699,397
def input_details(interpreter, key): """Returns input details by specified key.""" return interpreter.get_input_details()[0][key]
b06bd5278fcc5d95da387cb506ac9b9f443d9f27
699,401
def format_date( date_obj ): # date_obj is a datetime.date object """Returns a formatted date string given a date object. If the day is the first of the month, then the day is dropped, eg: format_date ( datetime.date(2013, 04, 12)) returns 2013-04-12 format_date ( datetime.date(2013, 4, 1)) r...
bfcddc9cbd4228084a0a4c5e6736be28a90d520e
699,404
from typing import Dict from typing import Any def _make_pod_podannotations() -> Dict[str, Any]: """Generate pod annotation. Returns: Dict[str, Any]: pod annotations. """ annot = { "annotations": { "k8s.v1.cni.cncf.io/networks": '[\n{\n"name" : "internet-network",' ...
94ab8b66c5cf63546f15cb8fef6e1fbc4aa3cb49
699,406
def merge_result(docker_list: dict, result_dict: dict = {}, max_entries_per_docker: int = 5) -> dict: """Returns a python dict of the merge result Args: :type docker_list: ``dict`` :param docker_list: dictionary representation for the docker image used by integration or script :type re...
7cfd2708e15eb65c09e32cf0c08a360f780aacb8
699,408
def _major_minor(version): """Given a string of the form ``X.Y.Z``, returns ``X.Y``.""" return ".".join(version.split(".")[:2])
8ca52bd0324bb0445ab3c5b9b44124c0f627f635
699,412
def is_lock_valid(transfer, block_number): """ True if the lock has not expired. """ return block_number <= transfer.expiration
186c48c8a81458a9ff25891f5afa380f07dcbede
699,413
def set_overlay(background, overlay, pos=(0,0)): """ Function to overlay a transparent image on background. :param background: input color background image :param overlay: input transparent image (BGRA) :param pos: position where the image to be set. :return: result image """ h...
ae9b8be9193e04ede7649ff9cab2ad4a94c4876a
699,415
def format_line(entries, sep=' | ', pads=None, center=False): """ Format data for use in a simple table output to text. args: entries: List of data to put in table, left to right. sep: String to separate data with. pad: List of numbers, pad each entry as you go with this number. ...
c5dfd312f8f13a54943fe18e254a6d8836d4460a
699,417
def int_or_none(x): """ A helper to allow filtering by an integer value or None. """ if x.lower() in ("null", "none", ""): return None return int(x)
f7a99fd637b5f5e2f4519034b36d03128279726c
699,423
import platform def supports_posix() -> bool: """Check if the current machine supports basic posix. Returns: bool: True if the current machine is MacOSX or Linux. """ return platform.system().lower() in ( "darwin", "linux", )
527bb8570e0493deec01aadafdf929e7315b27c0
699,426
import torch def compute_reconstruction_error(vae, data_loader, **kwargs): """ Computes log p(x/z), which is the reconstruction error. Differs from the marginal log likelihood, but still gives good insights on the modeling of the data, and is fast to compute. """ # Iterate once over the data ...
ee4fa35002e0f43d6482ae7f9ccfc7b7b1282db7
699,427
def _whbtms(anchor): """Return width, height, x bottom, and y bottom for an anchor (window).""" w = anchor[2] - anchor[0] + 1 h = anchor[3] - anchor[1] + 1 x_btm = anchor[0] + 0.5 * (w - 1) y_btm = anchor[1] + 1.0 * (h - 1) return w, h, x_btm, y_btm
0b4d65ad8a9dca2753ee703ad47764a1cb88f50e
699,428
def _compute_land_only_mask(ds, lsm_min=0.8): """Computes a mask for cells that are considered to be over the land. The lsm fraction is above lsm_min. Here, lsm is the land-sea mask as a fraction (0 is all water, 1 is all land).""" da_mask = ds.lsm > lsm_min da_mask.attrs[ "long_name" ] ...
23b682a216031abac3e90989d130f7b3de9abf7c
699,432
def check_datasets(datasets): """Check that datasets is a list of (X,y) pairs or a dictionary of dataset-name:(X,y) pairs.""" try: datasets_names = [dataset_name for dataset_name, _ in datasets] are_all_strings = all([isinstance(dataset_name, str) for dataset_name in datasets_names]) are...
e02771dd7d2df3d9e716141ba2ada92408a2b14e
699,433
import requests import json def get_card_updated_data(scryfall_id) -> str: """Gets updated data from scryfall Args: scryfall_id ([type]): [description] Returns: json: result from scryfalls card api ref: https://scryfall.com/docs/api/cards/id ex scryfall_id="e9d5aee0-5963-41db-a2...
2a0f1a9c65cbe7e173543e8a3d4b03fd364e2ae6
699,435
def get_candidate_file_name( monotonous: bool, agg_point: bool, both: bool = False, ) -> str: """Get canonical filename for candidate set sizes.""" if both: return f"candidate_sizes{'_mono' if monotonous else ''}_k_point" else: return f"candidate_sizes{'_mono' if monotonous else ...
85b27f7767fd495a46459553b96160691a3dbeda
699,438
def square_of_sum(limit): """ Returns the square of the sum of all integers in the range 1 up to and including limit. """ return sum([i for i in range(limit + 1)]) ** 2
503048c7b175d10dce20ff9d2f9435be4fbe1c35
699,439
import re def is_valid_regex(regex): """Helper function to determine whether the provided regex is valid. Args: regex (str): The user provided regex. Returns: bool: Indicates whether the provided regex was valid or not. """ try: re.compile(regex) return True ...
4c544168f2b1894e7cc7c7804342f923287022b5
699,441
def normalize_medical_kind(shape, properties, fid, zoom): """ Many medical practices, such as doctors and dentists, have a speciality, which is indicated through the `healthcare:speciality` tag. This is a semi-colon delimited list, so we expand it to an actual list. """ kind = properties.get('k...
dbf75799624cbe119c4c3a74c8814d0a979d828e
699,443
def _get_tws(sel_cim_data): """Return terrestrial water storage.""" return sel_cim_data.TWS_tavg
2b8405a245d39466ef2b47463d88518cc3b5bedf
699,444
def merge_arrays(*lsts: list): """Merges all arrays into one flat list. Examples: >>> lst_abc = ['a','b','c']\n >>> lst_123 = [1,2,3]\n >>> lst_names = ['John','Alice','Bob']\n >>> merge_arrays(lst_abc,lst_123,lst_names)\n ['a', 'b', 'c', 1, 2, 3, 'John', 'Alice', 'Bob']...
f2dd78a9e2d31347d72e1e904c0f2c6e30b37431
699,449
def is_within_range(num, lower_bound: int, upper_bound: int) -> bool: """ check if a number is within a range bounded by upper and lower bound :param num: target number needs to be checked against :param lower_bound: exclusive lower bound :param upper_bound: exclusive upper bound :return: True ...
325f4084a88254ec2f29dd28749b8709de394078
699,452
from typing import Optional from typing import Tuple def _shape_param_to_id_str(shape_param: Optional[Tuple[Optional[int], ...]]) -> str: """Convert kernel input shape parameter used in `test_call.py` and `conftest.py` into a human readable representation which is used in the pytest parameter id.""" if s...
ba73efa0693217a32ba42754af36204631c4200d
699,453
def getbox(xcenter, ycenter, size=500): """ A function to compute coordinates of a bounding box. Arguments: - xcenter: int, x position of the center of the box. - ycenter: int, y position of the center of the box. - size: int, size of the side of the box. Returns: - box...
6e8030f113a13775365fcd715be46690849154f3
699,460
from typing import List def get_entity_attributes(entity: dict) -> List[str]: """Get a list with the attributes of the entity. Args: entity(:obj:`dict`): entity. Returns: list: containing the attributes. """ keys = entity.keys() not_attributes = ["id", "type"] attributes ...
a5482a679ff5060d2deb26d7af6f4dc7fe394bf5
699,461
def fahrenheitToRankie(fahrenheit:float, ndigits = 2)->float: """ Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale """ return round(flo...
feea06edfbc800fbb4da6a3a128b2a89f07966ed
699,462
def connect(H, G, Gout=None, Hin=None): """ Connect outputs Gout of G to inputs Hin of H. The outputs and inputs of the connected system are arranged as follows: - remaining outputs of G get lower, the outputs of H the higher indices - inputs of G get the lower, remaining inputs of H the hi...
c5a6bbf86ec9da5daf006a5e1dc3de1f8140e45f
699,463
def factorial(x): """Return the factorial of a given number.""" if x == 1: return 1 else: return factorial(x-1) * x
a1c3adacf122c1bec57bbbfd246f07bf627febcd
699,465
from pathlib import Path def is_file_suffix(filename, suffixes, check_exist=True): """ is_file + check for suffix :param filename: pathlike object :param suffixes: tuple of possible suffixes :param check_exist: whether to check the file's existence :return: bool """ if check_exist and ...
e1e81eb0c39c991586097882c728535829acf415
699,467
import shutil def cmd_exists(cmd): """Returns True if a binary exists on the system path""" return shutil.which(cmd) is not None
0d43181532b9b71cb06b6a5d1f207bbb19899129
699,468
import requests def get_swapi_resource(url, params=None): """This function initiates an HTTP GET request to the SWAPI service in order to return a representation of a resource. The function defines two parameters, the resource url (str) and an optional params (dict) query string of key:value pairs may be ...
3a5de57fc498da1e25de4f2b3e61cae8508ad7c7
699,469
def assertify(text): """Wraps text in the (assert ).""" return '(assert ' + text + ')'
da7af0fe5d27759d8cef4589843796bee8e74383
699,470
def bubble_sort(items): """Sort given items by swapping adjacent items that are out of order, and repeating until all items are in sorted order. Running time: O(n**2) because it passes through n/2 (on average) elements n-1 times, which simplifies to n elements n times, n**2 Memory usage: O(1), a...
88748e0d552f0d08e228049f12268e34aed4907b
699,473
def human_list(_list) -> str: """Convert a list of items into 'a, b or c'""" last_item = _list.pop() result = ", ".join(_list) return "%s or %s" % (result, last_item)
04ee703d1878ac7602ba33aaf1831ccc188ee9e2
699,474
def ccall_except_check(x): """ >>> ccall_except_check(41) 42 >>> ccall_except_check(-2) -1 >>> ccall_except_check(0) Traceback (most recent call last): ValueError """ if x == 0: raise ValueError return x+1
f4a877f63a189b39fea477af218438de2e6c2a78
699,479
def input_prompt(prompt): """ Get user input :param prompt: the prompt to display to the user """ return input(prompt)
b780278c37f048d1ea61f36af0947b683c5f9b9c
699,481
def safeintorbignumber(value): """safely converts value to integer or 10M""" try: return int(value) except ValueError: return 10000000
de665dc11ba27c6846412b706cf833e46dc26758
699,482
def isNumber(s): """ Tests whether an input is a number Parameters ---------- s : string or a number Any string or number which needs to be type-checked as a number Returns ------- isNum : Bool Returns True if 's' can be converted to a float Returns False if con...
bd1bae27814ddca22c39d6411df3581e8116c324
699,484
def read_epi_params(item_basename): """Read all the necessary EPI parameters from text files with the given basename. Args: item_basename (str): The basename for all the files we need to read. In particular the following files should exist: - basename + '.read_out_time.txt' ...
3af788073607df214c447f2b87606b2d3e1638fd
699,487
def filled_int(val, length): """ Takes a value and returns a zero padded representation of the integer component. :param val: The original value. :param length: Minimum length of the returned string :return: Zero-padded integer representation (if possible) of string. Original string used if integer...
55da47570ab03c5964f3af167bb8a4f27656a660
699,488
import pickle def _load_batch(fpath, label_key='labels'): """Internal utility for parsing CIFAR data. Arguments: fpath: path the file to parse. label_key: key for label data in the retrieve dictionary. Returns: A tuple `(data, labels)`. """ with open(fpath, 'rb') as f: d = ...
4311566594ac6f0f6c9573bdb3ccf162205991ae
699,491
def velocity(estimate, actual, times=60): """Calculate velocity. >>> velocity(2, 160, times=60) 0.75 >>> velocity(3, 160, times=60) 1.125 >>> velocity(3, 160, times=80) 1.5 """ return (estimate*times)/(actual*1.)
ffdb12c7aea05f9fc8aa9e354e8db2320cbf431a
699,496
from pathlib import Path def _node_does_not_exist(node_path): """ Determine whether module already exists for node :param node_path: full path to node module :return: bool; True if node does not exist; False if it does exist """ try: # noinspection PyArgumentList Path(node_pa...
242f9895cb6e7ef4441b6d76b013cbdc88f8de45
699,499
def indent(s, depth): # type: (str, int) -> str """ Indent a string of text with *depth* additional spaces on each line. """ spaces = " "*depth interline_separator = "\n" + spaces return spaces + interline_separator.join(s.split("\n"))
69d509761cc6ab2f861f8b8c7fe7097ce8deff13
699,502
def prior_transform(u): """Flat prior between -10. and 10.""" return 10. * (2. * u - 1.)
4dd488a76a08361f1c7d833eaef96a7dfdf51ca6
699,503
def ensure_components(model_tracer_list): """If a CO2 flavor is detected for a model, ensure all flavors are present.""" co2_components = {'CO2', 'CO2_OCN', 'CO2_LND', 'CO2_FFF'} models = set(m for m, t in model_tracer_list) new_list = [] for model in models: m_tracers = set(t for m, t in mo...
8cb7f4e14f51718c8db75779ea02f6a73917323d
699,506
def subtraction(a, b): """subtraction: subtracts b from a, return result c""" a = float(a) b = float(b) c = b - a return c
0115222efc08588a12a6fbc1965441b83a7eaff0
699,510
import time def sec_to_datetime(timestamp): """ Convert secondes since epoch to a date and time """ return time.strftime("%d/%m/%Y %H:%M:%S %Z", time.localtime(timestamp))
e1e72e2e9e34259fcf2e2d3fcd6a6598dc77e3ae
699,511
def contains_failure(lines): """Check if any line starts with 'FAILED'.""" for line in lines: if line.startswith('FAILED'): return True return False
c3a74373f351a946e7d8f9d9497c8ee9af32282e
699,512
def Jaccard3d(a, b): """ This will compute the Jaccard Similarity coefficient for two 3-dimensional volumes Volumes are expected to be of the same size. We are expecting binary masks - 0's are treated as background and anything else is counted as data Arguments: a {Numpy array} -- 3D array...
0c5e7be04f596736ab0184b2799708350691c240
699,516
def imputation(matrix, nan_filling): """ takes in matrix dataframe and value for filling in NaNs for imputation Parameters: matrix dataframe, NaN filling value Returns: imputed matrix dataframe """ matrix.fillna(nan_filling, inplace=True) return matrix
a6981e54f6228e9ebfcbb6ea65e5305f50a327ca
699,521
import pkg_resources def is_version_greater_equal(version1, version2): """Returns True if version1 is greater or equal than version2 else False""" return (pkg_resources.parse_version(version1) >= pkg_resources.parse_version(version2))
0618f18c22121d954ae156af7bb6eff80236ae29
699,524
def get_config(config, group): """Return the tuple of song_data, log_data and output_data paths. Arguments: config -- ConfigParser object used to extract data values group -- Top-level grouping of config values (AWS or LOCAL)""" group = group.upper() return config[group]['SONG_DATA'], c...
62af332b29e0a901c14143bd8b77834229ce0013
699,525
import asyncio def run_coro(coro): """Runs a co-routing in the default event loop and retuns it result.""" return asyncio.get_event_loop().run_until_complete(coro)
62f109ef4440ecb2807640ff91b27f07e91d8f9f
699,530
def buildaff(ulx: float, uly: float, pixelres: float) -> tuple: """ Build a gdal GeoTransform tuple Args: ulx: projected geo-spatial upper-left x reference coord uly: projected geo-spatial upper-left y reference coord pixelres: pixel resolution Returns: affine tuple ...
43e593050a6b3ebef876f4347d3df787e2a49795
699,534
def parse_search_result_data(api_response): """ Parse the search result data from the given raw json by following the response style of tokopedia Arg: - api_response (list): list of products Returns: - product_list (list): list of compiled product properties """ product_list =...
ee1314589e1599f2d4a58523077abc8a7f270f88
699,535
import re def parse_show_spanning_tree_mst_config(raw_result): """ Parse the 'show spanning-tree mst-config' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show spanning-tree \ mst-config command in a dictionary of the for...
2f07e13ff7f79e4c15e0fe5111cbc18fb638dae8
699,538
def read_sql_file(filename, encoding='utf-8') -> str: """Read SQL file, remove comments, and return a list of sql statements as a string""" with open(filename, encoding=encoding) as f: file = f.read() statements = file.split('\n') return '\n'.join(filter(lambda line: not line.startswith('--'), s...
bd29c1080b2fd95d690b4696bf63c92932616964
699,540
def scenegraphLocationString(dataPacket): """ Given a datapacket, return a string representing its location in the scenegraph. (::UUID:OUTPUT) """ return "::"+str(dataPacket.sourceNode.uuid)+":"+dataPacket.sourceOutputName
027a69984acac4454e27a149ad822864751a0983
699,541
def get_directive_type(directive): """Given a dict containing a directive, return the directive type Directives have the form {'<directive type>' : <dict of stuff>} Example: {'#requirement': {...}} --> '#requirement' """ keys = list(directive.keys()) if len(keys) != 1: raise ValueError(...
584c1f22fc120815e79c781fc7ace69940c0f651
699,544
def u8(x: int) -> bytes: """ Encode an 8-bit unsigned integer. """ assert 0 <= x < 256 return x.to_bytes(1, byteorder='little')
c23bb4b6ea6bb610da5c3ecd281129e0bcc40bb7
699,547
def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. Example: >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 >>> x = -13 >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2 180339.9 po...
2705dbdaa937c564454078dc2cbc8dd4a9bd56e8
699,551
def split(string_to_split, separator): """Returns the list of strings divided by the separator.""" return string_to_split.split(separator)
c96d4ed6e3128617925c7d52c19d607cbfe1ece1
699,554
def _find_biggest_value(list): """ Get the intex of the largest value in list of values :return: -1 if list empty, otherwise index of biggest value """ if len(list) < 1: return -1 max = 0 for idx, val in enumerate(list): if val > list[max]: max = idx return ...
e4c4267ac2bfe73ad3bdb11433935805f4859e95
699,555
def inline(s, fmt): """Wrap string with inline escape""" return "`\u200B{}\u200B`".format(fmt.format(s))
3f07a4f55e60c763a10956c9ac52314b6958eca8
699,557
def _compute_cultural_score_building(building_geometry, historical_elements_gdf, historical_elements_gdf_sindex, score = None): """ Compute pragmatic for a single building. It supports the function "pragmatic_meaning" Parameters ---------- buildings_geometry: Polygon building_land_use: s...
743be39a3c100f53787df8195298c43affac8b4d
699,561
import requests def get_json_from_url(url): """Retrieve JSON from a URL, raising on failure.""" response = requests.get(url) response.raise_for_status() return response.json()
c88b36ff6d4911aaa6d4115b5c054fbab2f3051f
699,568
def is_param(arg): """Returns whether the passed argument is a list or dictionary of params.""" return isinstance(arg, tuple) and arg[0] == "params"
bedb4745f8fc7095e235be588ad53c28db9fb4d8
699,569
def evaluate_numeric_condition(target, reveal_response): """ Tests whether the reveal_response contains a numeric condition. If so, it will evaluate the numeric condition and return the results of that comparison. :param target: the questions value being tested against :param reveal_response: the ...
1eeb170635e5fb0ac5fd379af885a7a0222fb722
699,570
import hashlib def checksum(filepath, hcnstrctr=hashlib.md5, enc="utf-8"): """Compute the checksum of given file, `filepath` :raises: OSError, IOError """ return hcnstrctr(open(filepath).read().encode(enc)).hexdigest()
a0a6c576ef9f22de106834088f69cbbc2b3c4bd0
699,573
def increment(x): """increments input by one""" return x+1
416451d93765ee148de9b69bd3e1af0e846d6fb5
699,575
def flatten(list_like, recursive=True): """ Flattens a list-like datastructure (returning a new list). """ retval = [] for element in list_like: if isinstance(element, list): if recursive: retval += flatten(element, recursive=True) else: retval...
ad343decfa9e8ae949af303fc3f1a52179464009
699,579
def intents_to_string(intents, queryset=False): """ Args: intents: [{"action": "/application/json/view"}, ...] OR [models.Intent] (if queryset=True) Returns: ['<intent.action', ...] """ if queryset: new_intents = [i.action for i in intents] else: ...
55e9350d2db63de474f46836e02ae32297e2c170
699,581
import re def greek_to_english(string): """ Converts all greek letters to the corresponding english letters. Useful for creating song slugs from greek song titles. """ GREEK_MAP = { 'α':'a', 'β':'b', 'γ':'g', 'δ':'d', 'ε':'e', 'ζ':'z', 'η':'h', 'θ':'th', 'ι':'i', 'κ':'k', 'λ':'l',...
5c4752b1a1d08b0b37acc3f0e0c884d775eae637
699,582
def anum(self, num="", type_="", xhot="", yhot="", **kwargs): """Specifies the annotation number, type, and hot spot (GUI). APDL Command: /ANUM Parameters ---------- num Annotation number. ANSYS automatically assigns the lowest available number. You cannot assign a higher number ...
be3acd32deffcd31a3a83758b64d0d6950bbd791
699,583